Class ArrayUtils
java.lang.Object
org.flag4j.util.ArrayUtils
The ArrayUtils
class provides a set of utility methods for performing operations on arrays.
This includes transformations, comparisons, cumulative operations, validations, and copying.
For other array operations see: ArrayBuilder
, ArrayConversions
, and ArrayJoiner
.
Key Features:
- Deep comparison and copying of multidimensional arrays.
- Element-wise operations, including transformations, swaps, and permutations.
- Efficient searching and validation, including methods for finding unique values, indices, and membership checks.
- Flattening and reshaping of multidimensional arrays.
Usage Examples
// Compute the cumulative sum of an integer array
int[] array = {1, 2, 3, 4};
int[] cumSumArray = ArrayUtils.cumSum(array, null);
// Check if two 2D arrays are element-wise equal
int[][] array1 = {{1, 2}, {3, 4}};
int[][] array2 = {{1, 2}, {3, 4}};
boolean isEqual = ArrayUtils.deepEquals2D(array1, array2);
// Swap elements in an array
int[] numbers = {1, 2, 3};
ArrayUtils.swap(numbers, 0, 2); // Result: {3, 2, 1}
// Find unique values in an array
int[] values = {1, 2, 2, 3};
int[] uniqueValues = ArrayUtils.uniqueSorted(values); // Result: {1, 2, 3}
// Apply a transformation to a numeric array
double[] data = {1.0, 2.0, 3.0};
ArrayUtils.applyTransform(data, x -> x * x); // Squares each value in the array
Restrictions
- Multidimensional arrays are expected to be rectangular for all methods in this class. However, this is not explicitly enforced and jagged arrays may cause unexpected behavior.
- Many methods assume that input arrays are non-null unless explicitly stated otherwise.
- Sorting is required, but not enforced, for some methods to function correctly, such as
contains(int[], int)
andfindFirstLast(int[], int)
. Passing non-sorted arrays to such method results in undefined behavior.
Note: This class is a utility class and cannot be instantiated.
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionstatic Complex128[]
applyTransform
(double[] src, Function<Double, Complex128> opp) Applies a transform to an array.static double[]
applyTransform
(double[] src, UnaryOperator<Double> opp) Applies a transform to an array.static double[]
applyTransform
(Complex128[] src, Function<Complex128, Double> opp) Applies a transform to an array.static <T> T[]
applyTransform
(T[] src, UnaryOperator<T> opp) Applies a transform to an array.static void
arraycopy
(double[] src, int srcPos, Complex128[] dest, int destPos, int length) Performs an array copy similar toSystem.arraycopy(Object, int, Object, int, int)
but wraps doubles as complex numbers.static void
Performs an array copy similar toSystem.arraycopy(Object, int, Object, int, int)
but wraps floats as complex numbers.static boolean
contains
(double[] arr, double key) Checks if an array contains a specified value.static boolean[]
contains
(double[] src, double... keys) Checks if a set of keys are in an array.static boolean
contains
(int[] arr, int key) Checks if an array contains a specified value.static boolean[]
contains
(int[] src, int... keys) Checks if a set of keys is in an array.createUniqueMapping
(int[] arr) Creates a mapping of unique values in {code arr} to integers such that each unique value is mapped to a unique integer and those integers range from0
tonumUnique(arr) - 1
.static int[]
cumSum
(int[] src, int[] dest) Computes the cumulative sum of the elements of an array.static int[][]
deepCopy2D
(int[][] src, int[][] dest) Creates a deep copy of a 2D array.static boolean
deepEquals2D
(int[][] src1, int[][] src2) Checks if two primitive 2D integer arrays are element-wise equal.static <T extends Field<T>>
booleanequals
(double[] src1, T[] src2) Checks if a double array is numerically equal to acomplex number
array.static int[]
findFirstLast
(int[] src, int key) Finds the first and last index of a specified key within a sorted array.static double[]
flatten
(double[][] src) Flattens a two-dimensional array.static int[]
flatten
(int[][] src) Flattens a two-dimensional array.static Complex128[]
flatten
(Complex128[][] src) Flattens a two-dimensional array.static <T extends Field<T>>
T[]flatten
(T[][] src) Flattens a two-dimensional array.static <T extends Semiring<T>>
T[]flatten
(T[][] src) Flattens a two-dimensional array.static int
indexOf
(int[] arr, int key) Finds the fist index of the specifiedkey
within an array.static Shape
nDArrayShape
(Object nDArray) Infers the shape of a rectangular nD Java array.static int
Recursively validates the shape of the nD array and flattens it into the provided 1D array.static <T> int
Recursively validates the shape of the nD array and flattens it into the provided 1D array.static boolean
notContains
(int[] src, int key) Checks if a key is in an array.static int[]
notInAxes
(int[] srcAxes, int dim) Given a list of integers,srcAxes
, which is a subset of{0, 1, 2, ...., dim-1}
in no particular order, compute the integers which are in{0, 1, 2, ...., dim-1}
but not insrcAxes
.static int
numUnique
(double[] arr) Counts the number of unique elements in an array.static int
numUnique
(int[] arr) Counts the number of unique elements in an array.static void
permute
(int[] src, int[] indices) Swaps elements in an array according to a specified permutation.static void
permuteUnsafe
(int[] src, int[] indices) Swaps elements in an array according to a specified permutation.static int[]
shift
(int shift, int[] indices) Shifts all indices in an array by a specified amount.static int[]
shiftRange
(int shift, int[] indices, int start, int stop) Shifts a range of indices in an array by a specified amount.static void
swap
(double[] arr, int i, int j) Swaps to elements in an array.static void
swap
(int[] arr, int i, int j) Swaps to elements in an array.static void
Swaps to elements in an array.static double[]
unboxFlatten
(Double[][] src) Flattens a two-dimensional array and unboxes.static int[]
uniqueSorted
(int[] src) Gets the unique values from an array and sorts them.
-
Method Details
-
cumSum
public static int[] cumSum(int[] src, int[] dest) Computes the cumulative sum of the elements of an array.- Parameters:
src
- Source array to compute cumulative sum within.dest
- Array to store the result of the cumulative sum. May be the same array assrc
ornull
.- Returns:
- If
dest != null
then a reference todest
is returned. Ifdest == null
then a new array of appropriate size will be constructed and returned. - Throws:
IllegalArgumentException
- Ifdest != null && dest.length != src.length
.
-
deepEquals2D
public static boolean deepEquals2D(int[][] src1, int[][] src2) Checks if two primitive 2D integer arrays are element-wise equal.- Parameters:
src1
- First array in comparison.src2
- Second array in comparison.- Returns:
- The
-
equals
Checks if a double array is numerically equal to acomplex number
array.- Parameters:
src1
- Double array.src2
- Complex number array.- Returns:
true
if all data insrc2
have zero imaginary component and real component equal to the corresponding entry insrc1
;false
otherwise.
-
deepCopy2D
public static int[][] deepCopy2D(int[][] src, int[][] dest) Creates a deep copy of a 2D array. Assumes arrays are not jagged.- Parameters:
src
- Source array to copy.dest
- Destination array of copy. Ifnull
, a new array will be initialized.- Returns:
- A reference to
dest
if it was notnull
. In the case wheredest
isnull
, then a new array will be initialized and returned. - Throws:
IllegalArgumentException
- If the two arrays are not the same shape.
-
arraycopy
Performs an array copy similar toSystem.arraycopy(Object, int, Object, int, int)
but wraps doubles as complex numbers.- Parameters:
src
- The source array.srcPos
- The starting position from which to copy elements of the source array.dest
- The destination array for the copy.destPos
- Starting index to place copied elements in the destination array.length
- The number of array elements to be copied.- Throws:
ArrayIndexOutOfBoundsException
- If the destPos parameter plus the length parameter exceeds the length of the source array length or the destination array length.
-
arraycopy
Performs an array copy similar toSystem.arraycopy(Object, int, Object, int, int)
but wraps floats as complex numbers.- Parameters:
src
- The source array.srcPos
- The starting position from which to copy elements of the source array.dest
- The destination array for the copy.destPos
- Starting index to place copied elements in the destination array.length
- The number of array elements to be copied.- Throws:
ArrayIndexOutOfBoundsException
- If the destPos parameter plus the length parameter exceeds the length of the source array length or the destination array length.
-
swap
public static void swap(int[] arr, int i, int j) Swaps to elements in an array. This is done in place.- Parameters:
arr
- Array to swap elements in. This array is modified.i
- Index of first value to swap.j
- Index of second value to swap.- Throws:
IndexOutOfBoundsException
- Ifi
orj
are out of the bounds ofarr
.
-
permute
public static void permute(int[] src, int[] indices) Swaps elements in an array according to a specified permutation.- Parameters:
src
- Array to swap elements within.indices
- Array containing indices of the permutation. If thesrc
array has lengthN
, then the array must be a permutation of{0, 1, 2, ..., N-1}
.- Throws:
IllegalArgumentException
- Ifindices
is not a permutation of{0, 1, 2, ..., N-1}
.
-
permuteUnsafe
public static void permuteUnsafe(int[] src, int[] indices) Swaps elements in an array according to a specified permutation. This method should be used with extreme caution as unlikepermute(int[], int[])
, this method does not verify thatindices
is a permutation.- Parameters:
src
- Array to swap elements within.indices
- Array containing indices of the permutation. If thesrc
array has lengthN
, then the array must be a permutation of{0, 1, 2, ..., N-1}
.
-
swap
public static void swap(double[] arr, int i, int j) Swaps to elements in an array. This is done in place.- Parameters:
arr
- Array to swap elements in. This array is modified.i
- Index of first value to swap.j
- Index of second value to swap.- Throws:
IndexOutOfBoundsException
- Ifi
orj
are out of the bounds ofarr
.
-
swap
Swaps to elements in an array. This is done in place.- Parameters:
arr
- Array to swap elements in. This array is modified.i
- Index of first value to swap.j
- Index of second value to swap.- Throws:
IndexOutOfBoundsException
- Ifi
orj
are out of the bounds ofarr
.
-
notContains
public static boolean notContains(int[] src, int key) Checks if a key is in an array.- Parameters:
src
- Source array. Must be sorted, if not, callArrays.sort(double[])
first. Otherwise, the behavior of this method is undefined.key
- Values to check if they are in the source array.- Returns:
- A boolean describing if the specified key is in the array or not.
-
contains
public static boolean[] contains(double[] src, double... keys) Checks if a set of keys are in an array.- Parameters:
src
- Source array. Must be sorted, if not, callArrays.sort(double[])
first. Otherwise, the behavior of this method is undefined.keys
- Values to check if they are in the source array.- Returns:
- A boolean array with the same length as
keys
describing if the associated keys are in the array.
-
contains
public static boolean[] contains(int[] src, int... keys) Checks if a set of keys is in an array.- Parameters:
src
- Source array. Must be sorted, if not, callArrays.sort(int[])
first. Otherwise, the behavior of this method is undefined.keys
- Values to check if they are in the source array.- Returns:
- A boolean array with the same length as
keys
describing if the associated keys are in the array.
-
contains
public static boolean contains(int[] arr, int key) Checks if an array contains a specified value. This method assumes that the array is sorted as it uses the binary search algorithm. If the array is not sorted, useArrays.sort(int[])
first.- Parameters:
arr
- Array of interest.key
- Value to check for in thearr
array.- Returns:
- True if the
key
value is found in the array. False otherwise. - See Also:
-
contains
public static boolean contains(double[] arr, double key) Checks if an array contains a specified value. This method assumes that the array is sorted as it uses the binary search algorithm. If the array is not sorted, useArrays.sort(int[])
first.- Parameters:
arr
- Array of interest.key
- Value to check for in thearr
array.- Returns:
- True if the
key
value is found in the array. False otherwise. - See Also:
-
nDArrayShape
Infers the shape of a rectangular nD Java array.- Parameters:
nDArray
- The nD Java array to infer the shape from.- Returns:
- The shape of the nD array as a
Shape
object. - Throws:
IllegalArgumentException
- IfnDArray
is not an array or has inconsistent (i.e. non-rectangular) dimensions.
-
nDFlatten
Recursively validates the shape of the nD array and flattens it into the provided 1D array.- Parameters:
nDArray
- The nD array to flatten.shape
- The expected shape of the nD array.flatArray
- The 1D array to populate with flattened data.offset
- The starting index for the current level of recursion.- Returns:
- The next available index in the flatArray after processing the current nDArray.
- Throws:
IllegalArgumentException
- If the shape of the nD array is inconsistent with the inferred shape.
-
nDFlatten
Recursively validates the shape of the nD array and flattens it into the provided 1D array.- Parameters:
nDArray
- The nD array to flatten.shape
- The expected shape of the nD array.flatArray
- The 1D array to populate with flattened data.offset
- The starting index for the current level of recursion.- Returns:
- The next available index in the flatArray after processing the current nDArray.
- Throws:
IllegalArgumentException
- If the shape of the nD array is inconsistent with the inferred shape.
-
flatten
public static int[] flatten(int[][] src) Flattens a two-dimensional array.- Parameters:
src
- Array to flatten.- Returns:
- The flattened array.
-
flatten
public static double[] flatten(double[][] src) Flattens a two-dimensional array.- Parameters:
src
- Array to flatten.- Returns:
- The flattened array.
-
unboxFlatten
Flattens a two-dimensional array and unboxes.- Parameters:
src
- Array to flatten and unbox.- Returns:
- The flattened array.
-
flatten
Flattens a two-dimensional array.- Parameters:
src
- Array to flatten.- Returns:
- The flattened array.
-
flatten
Flattens a two-dimensional array.- Parameters:
src
- Array to flatten.- Returns:
- The flattened array.
-
flatten
Flattens a two-dimensional array.- Parameters:
src
- Array to flatten.- Returns:
- The flattened array.
-
notInAxes
public static int[] notInAxes(int[] srcAxes, int dim) Given a list of integers,srcAxes
, which is a subset of{0, 1, 2, ...., dim-1}
in no particular order, compute the integers which are in{0, 1, 2, ...., dim-1}
but not insrcAxes
.- Parameters:
srcAxes
- Source axes which contains a subset of{0, 1, 2, ...., dim-1}
in no particular order.dim
- Dimension of space which contains the axes of interest.- Returns:
- An array containing the set subtraction
{0, 1, 2, ...., dim-1}
- srcAxes.
-
shift
public static int[] shift(int shift, int[] indices) Shifts all indices in an array by a specified amount.- Parameters:
shift
- Amount to shift indices by.indices
- Array of indices to shift.- Returns:
- A reference to
indices
. - See Also:
-
shiftRange
public static int[] shiftRange(int shift, int[] indices, int start, int stop) Shifts a range of indices in an array by a specified amount.- Parameters:
shift
- Amount to shift indices by.indices
- Array of indices to shift.start
- Starting index of range to shift (inclusive).stop
- Stopping index of range to shift (exclusive).- Returns:
- A reference to
indices
. - Throws:
ArrayIndexOutOfBoundsException
- If start or stop is not within the bounds of theindices
array.- See Also:
-
uniqueSorted
public static int[] uniqueSorted(int[] src) Gets the unique values from an array and sorts them.- Parameters:
src
- The array to get unique values from.- Returns:
- A sorted array containing all unique values in the
src
array.
-
indexOf
public static int indexOf(int[] arr, int key) Finds the fist index of the specifiedkey
within an array. If the element does not exist, then-1
is returned.- Parameters:
arr
- Array of interest.key
- Key value to search for.- Returns:
- Returns the first index of the value
key
within thearr
array. If thekey
does not occur in the array,-1
will be returned.
-
numUnique
public static int numUnique(double[] arr) Counts the number of unique elements in an array.- Parameters:
arr
- Array to count unique elements in.- Returns:
- The number of unique elements in
arr
.
-
numUnique
public static int numUnique(int[] arr) Counts the number of unique elements in an array.- Parameters:
arr
- Array to count unique elements in.- Returns:
- The number of unique elements in
arr
.
-
createUniqueMapping
Creates a mapping of unique values in {code arr} to integers such that each unique value is mapped to a unique integer and those integers range from0
tonumUnique(arr) - 1
.- Parameters:
arr
- Array to create a mapping for.- Returns:
- A mapping of unique values in {code arr} to integers such that each unique value is
mapped to a unique integer and those integers range from
0
tonumUnique(arr) - 1
.
-
findFirstLast
public static int[] findFirstLast(int[] src, int key) Finds the first and last index of a specified key within a sorted array.- Parameters:
src
- The source array to search within. This array is assumed ot be sorted. If the array is not sorted, callArrays.sort(src)
before this method. If this is not done, and an unsorted array is passed to this method, the results are undefined.key
- The key value to find the first and last index of within thesrc
array.- Returns:
- An array of length 2 containing the first (inclusive) and last (exclusive) index of the
key
within thesrc
array. If thekey
value does not exist in the array, then both first and last index will be(-insertion_point - 1)
whereinsertion_point
is defined as the index thekey
would be inserted into the sorted array.
-
applyTransform
Applies a transform to an array. This is done in place.- Parameters:
src
- Array to apply transform to. Modified.opp
- Operation to use to transform the array.- Returns:
- A reference to the
src
array.
-
applyTransform
Applies a transform to an array. This is done in place.- Parameters:
src
- Array to apply transform to. Modified.opp
- Operation to use to transform the array.- Returns:
- A reference to the
src
array.
-
applyTransform
Applies a transform to an array. Note, unlikeapplyTransform(double[], UnaryOperator)
andapplyTransform(Object[], UnaryOperator)
, this method does not work in place.- Parameters:
src
- Array to apply transform to.opp
- Operation to use to transform the array.- Returns:
- A new array containing the result of the transformation.
- See Also:
-
applyTransform
Applies a transform to an array. Note, unlikeapplyTransform(double[], UnaryOperator)
andapplyTransform(Object[], UnaryOperator)
, this method does not work in place.- Parameters:
src
- Array to apply transform to.opp
- Operation to use to transform the array.- Returns:
- A new array containing the result of the transformation.
- See Also:
-