Jump to content

Some array utilities for your convenience


Botre

Recommended Posts

LAST UPDATE: MARCH 6, 2015

 

Some of these might be found in other library classes such as Arrays (if you find a more efficient implementation feel free to share it)

 

Feel free to leave constructive feedback (on the code/comments) / suggest methods.

package org.bjornkrols.utilities.array;

import java.util.Comparator;
import java.util.Random;

import org.bjornkrols.algorithms.sequence_search.BinarySearch;

/**
 * A set of utility methods for arrays.
 * 
 * @author 		Bjorn Krols (Botre)
 * @version		0.0
 * @since		March 6, 2015
 */

public final class ArrayUtilities {

	private ArrayUtilities() {
		// This class should never be instantiated.
		// Do not delete or make accessible.
	}
	
	private static final Random RANDOM = new Random();
		
	/**
	 * @return A string representation of the array with the following format: [0, 1, 2, ..., length - 1].
	 */
	public static String toString(Object[] array) {
		if (array == null) {
			return "null";
		}
		int max = array.length - 1;
		if (max == -1) {
			return "[]";
		}
		StringBuilder sb = new StringBuilder();
		sb.append('[');
		for (int i = 0; ; i++) {
			sb.append(array[i]);
			if (i == max) {
				return sb.append(']').toString();
			}
			sb.append(", ");
		}
	}
	
	/**
	 * Calls java.io.PrintStream.println on every entry of the array.
	 */
	public static void printlnContents(Object[] array) {
        if (array == null) {
        	System.out.println("null");
        	return;
        }
		for (int i = 0; i < array.length; i++) {
        	System.out.println(array[i]);
        }
    }
	
	/**
	 * Prints a String representation of the array and terminates the line.
	 */
	public static void printlnString(Object[] array) {
		System.out.println(toString(array));
	}

	/**
	 * @return A new array resulting from the concatenation of a set of arrays.
	 */
	public static int[] concatenate (int[]... arrays) {
		int size = 0;
		for (int[] array : arrays) size += array.length;
		int[] result = new int[size];
		int index = 0;
		for (int[] array : arrays) for (int element : array) result[index++] = element;	        
		return result;
	}

	/**
	 * @see ArrayUtilities#concatenate(int[]...)
	 */
	public static Object[] concatenate (Object[]... arrays) {
		int size = 0;
		for (Object[] array : arrays) size += array.length;
		Object[] result = new Object[size];
		int index = 0;
		for (Object[] array : arrays) for (Object element : array) result[index++] = element;	        
		return result;
	}
	
	/**
	 * Swaps the entries at indexes a & b.
	 */
	public static void swapEntriesByIndex(boolean[] array, int a, int b) {
		boolean temp = array[a];
		array[a] = array[b];
		array[b] = temp;
	}
	
	/**
	 * @see ArrayUtilities#swapEntriesByIndex(boolean[], int, int)
	 */
	public static void swapEntriesByIndex(byte[] array, int a, int b) {
		byte temp = array[a];
		array[a] = array[b];
		array[b] = temp;
	}
	
	/**
	 * @see ArrayUtilities#swapEntriesByIndex(boolean[], int, int)
	 */
	public static void swapEntriesByIndex(short[] array, int a, int b) {
		short temp = array[a];
		array[a] = array[b];
		array[b] = temp;
	}
	
	/**
	 * @see ArrayUtilities#swapEntriesByIndex(boolean[], int, int)
	 */
	public static void swapEntriesByIndex(char[] array, int a, int b) {
		char temp = array[a];
		array[a] = array[b];
		array[b] = temp;
	}
	
	/**
	 * @see ArrayUtilities#swapEntriesByIndex(boolean[], int, int)
	 */
	public static void swapEntriesByIndex(int[] array, int a, int b) {
		int temp = array[a];
		array[a] = array[b];
		array[b] = temp;
	}
	
	/**
	 * @see ArrayUtilities#swapEntriesByIndex(boolean[], int, int)
	 */
	public static void swapEntriesByIndex(long[] array, int a, int b) {
		long temp = array[a];
		array[a] = array[b];
		array[b] = temp;
	}
	
	/**
	 * @see ArrayUtilities#swapEntriesByIndex(boolean[], int, int)
	 */
	public static void swapEntriesByIndex(float[] array, int a, int b) {
		float temp = array[a];
		array[a] = array[b];
		array[b] = temp;
	}
	
	/**
	 * @see ArrayUtilities#swapEntriesByIndex(boolean[], int, int)
	 */
	public static void swapEntriesByIndex(double[] array, int a, int b) {
		double temp = array[a];
		array[a] = array[b];
		array[b] = temp;
	}
	
	/**
	 * @see ArrayUtilities#swapEntriesByIndex(boolean[], int, int)
	 */
	public static void swapEntriesByIndex(Object[] array, int a, int b) {
		Object temp = array[a];
		array[a] = array[b];
		array[b] = temp;
	}
	
	/**
	 * @return Whether the array is sorted.
	 */
	@SuppressWarnings("rawtypes")
	public static boolean isSorted(Comparable[] array) {
		return isSorted(array, 0, array.length - 1);
	}

	/**
	 * @return Whether the array is sorted between indexes low and high.
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static boolean isSorted(Comparable[] array, int low, int high) {
		for (int i = low + 1; i <= high; i++) if (array[i].compareTo(array[i - 1]) < 0) return false;
		return true;
	}
		
	/**
	 * @see ArrayUtilities#isSorted(Comparable[])
	 */
	@SuppressWarnings("rawtypes")
	public static boolean isSorted(Object[] array, Comparator comparator) {
		return isSorted(array, comparator, 0, array.length - 1);
	}
	
	/**
	 * @see ArrayUtilities#isSorted(Comparable[], int, int)
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static boolean isSorted(Object[] array, Comparator comparator, int low, int high) {
		for (int i = low + 1; i <= high; i++) if (comparator.compare(array[i], array[i - 1]) < 0) return false;
		return true;
	}
	
	/**
	 * @return Whether the sorted array contains a specific key value.
	 */
	public static boolean sortedContains(int[] array, int key) {
		return BinarySearch.getIndex(array, key) != -1;
	}
	
	/**
	 * Reverses the array.
	 */
	public static void reverse(int[] array) {
		int length = array.length;
	    for (int i = 0; i < length / 2; i++) {
	        array[i] = array[i] ^ array[length - i  - 1];
	        array[length - i  - 1] = array[i] ^ array[length - i  - 1];
	        array[i] = array[i] ^ array[length - i  - 1];
	    }
	}
	
	/**
	 * @return A random entry from the array.
	 */
	public static int getRandomEntry(int[] array) {
		return array[RANDOM.nextInt(array.length)];
	}
	
}
Edited by Botre
  • Like 2
Link to comment
Share on other sites

  • 3 weeks later...

your reverse method

http://stackoverflow.com/questions/2137755/how-do-i-reverse-an-int-array-in-java

 

your concatenate method

http://stackoverflow.com/questions/80476/how-to-concatenate-two-arrays-in-java

 

at least give credit or post ref when you copy code m8

 

The concatenate method is mine.

The reverse method not, who seriously credits stackoverflow code though ? Oo

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...