Sorting a Dynamic 2D Array according to a column in JAVA - java

I have created an ArrayList of arrays which may contain n rows but two fixed columns. For e.g.
ArrayList<int[]> rows = new ArrayList<>();
rows.add(new int[] {3, 100});
rows.add(new int[] {4, 150});
rows.add(new int[] {4, 80});
rows.add(new int[] {2, 90});
rows.add(new int[] {2, 300});
Note that there may be more rows. I want to sort these list of rows based on the second column. How do I go about doing that? If there is any other better method to do this not based on ArrayList, please let me know that as well.

Comparator::comparingInt
Use it as shown below:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
ArrayList<int[]> rows = new ArrayList<>();
rows.add(new int[] { 3, 100 });
rows.add(new int[] { 4, 150 });
rows.add(new int[] { 4, 80 });
rows.add(new int[] { 2, 90 });
rows.add(new int[] { 2, 300 });
// Sort arrays (i.e. rows) on the value at index, 1 (i.e. second column)
rows.sort(Comparator.comparingInt(e -> e[1]));
// Display
rows.forEach(e -> System.out.println(Arrays.toString(e)));
}
}
Output:
[4, 80]
[2, 90]
[3, 100]
[4, 150]
[2, 300]

You can use comparator of collections class also..
public static void main(String[] args) {
ArrayList<int[]> rows = new ArrayList<>();
rows.add(new int[] {3, 100});
rows.add(new int[] {4, 150});
rows.add(new int[] {4, 80});
rows.add(new int[] {2, 90});
rows.add(new int[] {2, 300});
Collections.sort(rows, new Comparator<int[]>() {
#Override
public int compare(int[] o1, int[] o2) {
// TODO Auto-generated method stub
if (o1[1] > o2[1])
return 1;
else
return -1;
}
});
rows.forEach(e -> System.out.println(Arrays.toString(e)));
}

Related

I try to compare two Collections of int arrays and I've got results which origin I don't understand

I am solving this kata on Codewars: https://www.codewars.com/kata/635fc0497dadea0030cb7936
this is my code:
public static void main(String[] args) {
int[][] ms;
ms = new int[][] {{1, 2, 3, 4},
{3, 1, 4, 2},
{4, 3, 2, 1},
{2, 4, 1, 3}};
System.out.println(count_different_matrices(ms));
}
private static final Set<int[]> registeredM = new HashSet<>();
static public int count_different_matrices(int[][] matrices) {
Arrays.stream(matrices).forEach(m -> {
if(unwrapPossibleMatrices(m).stream().noneMatch(registeredM::contains)) {
registeredM.add(m);
}});
registeredM.forEach(e -> System.out.println(Arrays.toString(e)));
return registeredM.size();
}
static private List<int[]> unwrapPossibleMatrices(int[] m) {
return Arrays.asList(new int[][]{
m,
{m[2], m[0], m[3], m[1]},
{m[3], m[2], m[1], m[0]},
{m[1], m[3], m[0], m[2]}
});
}
Output received in the console:
[1, 2, 3, 4]
[2, 4, 1, 3]
[4, 3, 2, 1]
[3, 1, 4, 2]
4
I expected output of only [1, 2, 3, 4], My train of thought was that contains() should invoke a.equals(b) where a and b in this example is of type int[] and when they will be compared by equals - it will check if length and elements in the arrays match. Instead what happened (I think) was that address of the object was checked - thus, giving different results for arrays with the same elements. My question is the following: how to modify this code to check actual elements passed in arrays?
Ok, I've changed my solution as #Pshemo pointed out (thank you :)
public static void main(String[] args) {
int[][] ms;
ms = new int[][] {{1, 2, 3, 4},
{3, 1, 4, 2},
{4, 3, 2, 1},
{2, 4, 1, 3}};
System.out.println(count_different_matrices(ms));
}
private static final Set<Row> registeredM = new HashSet<>();
static public int count_different_matrices(int[][] matrices) {
registeredM.clear();
Arrays.stream(matrices).forEach(m -> {
if(unwrapPossibleMatrices(m).stream().noneMatch(registeredM::contains)) {
registeredM.add(new Row(m));
}});
registeredM.forEach(e -> System.out.println(Arrays.toString(e.row())));
return registeredM.size();
}
private static List<Row> unwrapPossibleMatrices(int[] m) {
return Arrays.asList(
new Row(m),
new Row(new int[]{m[2], m[0], m[3], m[1]}),
new Row(new int[]{m[3], m[2], m[1], m[0]}),
new Row(new int[]{m[1], m[3], m[0], m[2]})
);
}
record Row(int[] row) {
#Override
public int hashCode() {
return Arrays.hashCode(row);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Row row1 = (Row) o;
return Arrays.equals(row, row1.row);
}
}

Java: Sort an Array Based on the Index Order of Another Array

In Java, how can I sort an array based on the index order of another sorted array? For instance, if I have:
arr1 = {26, 8, 3}
arr2 = {3, 1, 2}
arr3 = {57, 23, 11}
arr4 = {78, 2, 61}
and I sort arr2 in ascending order to be
arr2 = {1, 2, 3}
and I want the other to then be:
arr1 = {8, 3, 26}
arr3 = {23, 11, 57}
arr4 = {2, 61, 78}
How can I accomplish this is Java? I know I would save the new sorted arrays into new instances. Anything helps, thanks!
Found answer elsewhere
public class SortTogether{
// sort the array a, and also update the elements in array b, c, and d
// based on the index of a
public static void bubbleSort(int[] a, int[] b, int[] c, int[] d) {
for(int i=0; i<a.length; i++){
for(int j=0; j<a.length-i-1;j++){
if(a[j]>a[j+1]){
// when you are swapping the elements
int t = a[j]; a[j]=a[j+1];a[j+1]=t;
// swap the elements in the other arrays as well
// so the elements in other array will also stay together
t = b[j]; b[j]=b[j+1];b[j+1]=t;
t = c[j]; c[j]=c[j+1];c[j+1]=t;
t = d[j]; d[j]=d[j+1];d[j+1]=t;
}
}
}
}
public static void main(String a[]) {
int[] arr1 = {26, 8, 3};
int[] arr2 = {3, 1, 2};
int[] arr3 = {57, 23, 11};
int[] arr4 = {78, 2, 61};
System.out.println("Before sort");
display(arr1);
display(arr2);
display(arr3);
display(arr4);
bubbleSort(arr2,arr1,arr3,arr4);
System.out.println("\nAfter sort");
display(arr1);
display(arr2);
display(arr3);
display(arr4);
}
public static void display(int[] arr) {
for (int num : arr) System.out.printf("%4d", num);
System.out.println();
}
}
Here is one way to do it.
sort the indices of the target array based on the arrays contents.
then use that index array to map all the arrays based on the indexed one.
Integer[] indices = IntStream.range(0, arr2.length)
.boxed()
.sorted(Comparator.comparing(i -> arr2[i]))
.toArray(Integer[]::new);
List<int[]> list = Stream
.of(arr1, arr2, arr3, arr4).map(arr -> Stream
.of(indices)
.mapToInt(i -> arr[i])
.toArray())
.collect(Collectors.toList());
list.forEach(arr -> System.out.println(Arrays.toString(arr)));
Prints
[8, 3, 26]
[1, 2, 3]
[23, 11, 57]
[2, 61, 78]
You could also place the arrays in another "2D" array and do as follow with the same result.
int[][] arrays = { arr1, arr2, arr3, arr4 };
List<int[]> list = Arrays
.stream(arrays)
.map(arr -> Stream
.of(indices)
.mapToInt(i -> arr[i])
.toArray())
.collect(Collectors.toList());

Java. How can I check if element was successfully added in set and tracking indexes with forEach?

I need to find non similar rows in matrix and return set of such rows.
A rows is said to be similar if the sets of numbers occurring in these rows coincide.
Example:
origin:
1 2 2 4 4
4 2 1 4
3 2 4 1 5 8
expected result:
1 2 2 4 4
3 2 4 1 5 8
My ideas:
Clean duplicates from each row via convert two dimensional array to List>
Create new set of int[] and add row then if row was added its means that row is non similar.then record number of row. return created new set of rows of origin matrix.
I know that I can check if element was added via Boolean return value of Add method of Set.
But there is problem by forEach, that don't provide index. And I can't use expressions inside forEach. What should I do?
My code:
class NonSimilar {
private int[][] matrix;
private List<Set<Integer>> rows = new ArrayList<>();
public NonSimilar (int[][] matrix) {
this.matrix = matrix;
for (int i = 0; i < matrix.length; i++) {
rows.add(Arrays.stream(matrix[i]).boxed().collect(Collectors.toSet()));
}
}
public Set<int[]> getNonSimilarRows() {
Set<Set<Integer>> nonSimularRows = new HashSet<>();
rows.forEach(item -> nonSimularRows.add(item));
// Now I have to check successfully added rows numbers and construct new Set from Origin matrix
return new HashSet<int[]>();
}
}
Ok. I replaced forEach with for iteration and now all works correctly.
public Set<int[]> getNonSimilarRows() {
Set<Set<Integer>> nonSimularRows = new HashSet<>();
//rows.forEach(item -> nonSimularRows.add(item));
int index = -1;
ArrayList<Integer> indexes = new ArrayList<>();
for (Set<Integer> item : rows) {
index++;
if (nonSimularRows.add(item)) {
indexes.add(index);
}
}
HashSet<int[]> newSet = new HashSet<int[]>();
for (Integer item : indexes) {
newSet.add(matrix[item]);
}
return newSet;
}
Anyway code looks very ugly and I want to get advice how I can refactor code with modern approaches like forEach and Stream API.
You only need 2 lines of code to remove all "similar" rows:
Set<Set<Integer>> sets = new HashSet<>();
List<int[]> nonSimilar = Arrays.stream(matrix)
.filter(row -> sets.add(Arrays.stream(row).boxed().collect(Collectors.toSet())))
.collect(Collectors.toList());
The add() method of Set returns true if the set was changed - ie if the element being added is not already in the set, so we can use that as a filter.
List is chosen as the output of the stream to preserve order (a requirement that seems to be implied by the example data).
I leave it to the reader to convert List<int[]> to whatever output is required, because that's unimportant to the question/answer.
Some test code:
int[][] matrix = {{1, 2, 2, 4, 4},{4, 2, 1, 4}, {3, 2, 4, 1, 5, 8}};
Set<Set<Integer>> sets = new HashSet<>();
List<int[]> nonSimilar = Arrays.stream(matrix)
.filter(row -> sets.add(Arrays.stream(row).boxed().collect(Collectors.toSet())))
.collect(Collectors.toList());
nonSimilar.stream().map(Arrays::toString).forEach(System.out::println);
Output:
[1, 2, 2, 4, 4]
[3, 2, 4, 1, 5, 8]
See live demo.
Let's just say that it you need to give the first non-duplicate rows of the existing matrix. Then instead of keeping the indexes in a separate list, you could use a Map for which the unique key is the set of numbers in a row and the value is the row itself. Here is the complete class with the main method to test it :
public class NonSimilar {
private final int[][] matrix;
public NonSimilar(int[][] matrix) {
this.matrix = matrix;
}
public Set<int[]> getNonSimilarRows() {
Map<Set<Integer>, int[]> map = new HashMap<>();
for (int[] row : matrix) {
map.putIfAbsent(convertRowToSet(row), row);
}
return new HashSet<>(map.values());
}
public Set<Integer> convertRowToSet(int[] row){
return Arrays.stream(row).boxed().collect(Collectors.toSet());
}
public static void main(String[] args) {
int[][] matrix = {{1, 2, 2, 4, 4}, {4, 2, 1, 4}, {3, 2, 4, 1, 5, 8}};
Set<int[]> result = new NonSimilar(matrix).getNonSimilarRows();
result.forEach(row -> System.out.println(Arrays.toString(row)));
}
}
Now you might say that it prints
3 2 4 1 5 8
1 2 2 4 4
instead of
1 2 2 4 4
3 2 4 1 5 8
That's because the result is a Set and a set doesn't have the concept of order. If you really want it to be printed in the correct order, you can use a LinkedHashMap and return a LinkedHashSet.
NOTE : you can even make it shorter by using Collectors.toMap:
public Set<int[]> getNonSimilarRows() {
Map<Set<Integer>, int[]> map = Arrays.stream(matrix)
.collect(Collectors.toMap(this::convertRowToSet, Function.identity(), (r1, r2) -> null));
return new HashSet<>(map.values());
}
(r1, r2) -> r1 is to state that you accept duplicate keys and that you should keep the first value encountered. In the case of you want to keep the last value encountered, you can replace it by (r1, r2) -> r2.
With this
How to convert an Array to a Set in Java
How to compare two sets for equality
you could write it like this:
public class NonSimilarRowsTest {
#Test
public void test() {
int[][] matrix = {{1, 2, 2, 4, 4}, {4, 2, 1, 4}, {3, 2, 4, 1, 5, 8}};
int[][] expected = {{1, 2, 2, 4, 4}, {3, 2, 4, 1, 5, 8}};
assertEquals(expected, nonSimilarRows(matrix));
}
int[][] nonSimilarRows(int[][] matrix) {
Set<Set<Integer>> rows = new HashSet<>();
int[][] result = new int[matrix.length][];
int length = 0;
for (int[] row : matrix) {
if (rows.add(toSet(row))) {
result[length++] = row;
}
}
return Arrays.copyOf(result, length);
}
Set<Integer> toSet(int[] array) {
return Arrays.stream(array).boxed().collect(Collectors.toSet());
}
}
Here's another solution that maintains an unordered set that keeps tracks of duplicate rows and also maintains order by storing the results in list:
import java.util.Set;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Test {
private static final int[][] rows = new int[][] {
{ 1, 2, 2, 4, 4 },
{ 4, 2, 1, 4 },
{ 3, 2, 4, 1, 5, 8 }
};
private static Set<Set<Integer>> seenRows = new HashSet<>();
private static List<int[]> uniqueRows = new ArrayList<>();
public static void main(String[] args) {
for (int[] row : rows) {
Set<Integer> uniqueNumbers = Arrays.stream(row).boxed().collect(Collectors.toSet());
if (!seenRows.contains(uniqueNumbers)) {
uniqueRows.add(row);
seenRows.add(uniqueNumbers);
}
}
for (int[] row : uniqueRows) {
System.out.println(Arrays.toString(row));
}
}
}
Output:
[1, 2, 2, 4, 4]
[3, 2, 4, 1, 5, 8]

Initializing an array inside of adding it to an Array List

Hi so pretty much what I have been trying to do is create a method that is passed an Array List of Integers and returns an ArrayList of int arrays. I want each array inside of the returned Array List to contain on of the values of passed Array List. here is what I have so far
public static ArrayList<int[]> createPossible(ArrayList<Integer> al)
{
ArrayList<int[]> returned = new ArrayList<int[]>();
for(int i = 0; i < al.size(); i++)
{
returned.add(new int [1]{al.get(i)});
}
return returned;
}
I think that you can see the basic point of what I'm getting at here. Just cant figure out how to properly initialize each new array inside of where I'm adding it to the returned ArrayList
Just use
new int[] {al.get(i)}
The length of the array is useless, since you pass a given number of values inside the curly braces.
This will work similar to what you have described but it uses List<Integer[]> rather than a List<int[]>. If you must have List<int[]> then it could be augmented to suit your needs.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StackOverflow {
public static List<Integer[]> createPossible(List<Integer> al) {
List<Integer[]> returned = new ArrayList<Integer[]>();
for (int i = 0; i < al.size(); i++) {
returned.add(al.toArray(new Integer[0]));
}
return returned;
}
public static void main(String[] args) {
List<Integer> al = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
List<Integer[]> result = createPossible(al);
System.out.println(Arrays.deepToString(result.toArray()));
}
}
The output of the code above:
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]]

Sorting 2D Array but keeping column elements together

I have a 2D array with 2 rows and n columns.
I am trying to sort the array using the built in Arrays.sort method, but I am struggling with the comparator. I want to sort the 2D array by the first row, so that the 2nd row elements will remain with the original elements they were aligned with ie. keep the columns together.
For example original array:
int[] unsortedArray = new int[][]{
{ 6, 3, 1, 2, 3, 0},
{ 2, 1, 6, 6, 2, 4},
sorted array:
int[] unsortedArray = new int[][]{
{ 0, 1, 2, 3, 3, 6},
{ 4, 6, 6, 1, 2, 2},
What is the best way to go about doing this?
Cheers.
Here is an alternative way of keeping your columns aligned. This uses a simple class to hold both column elements.
class TwoInts {
public final int aElement;
public final int bElement;
public TwoInts(int a_element, int b_element) {
aElement = a_element;
bElement = b_element;
}
}
One by one, each column (from sub-array one and two) are placed in this object, and immediately put into a Map<Integer,List<TwoInts>>. The key is the element from intArrayArray[0], and the value is a list of TwoInts, because there may be (and in your example code, are) duplicate values in intArrayArray[0].
You then iterate through the map's key-set, and replace them into the array.
Full code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
<P>{#code java SortOneArrayKeepSecondArrayElementsAligned}</P>
**/
public class SortOneArrayKeepSecondArrayElementsAligned {
public static final void main(String[] ignored) {
int[][] intArrayArray = new int[][]{
{ 6, 3, 1, 2, 3, 0},
{ 2, 1, 6, 6, 2, 4}};
output2DArray("Unsorted", intArrayArray);
Map<Integer,List<TwoInts>> twoIntMap = new TreeMap<Integer,List<TwoInts>>();
for(int i = 0; i < intArrayArray[0].length; i++) {
int intIn0 = intArrayArray[0][i];
if(!twoIntMap.containsKey(intIn0)) {
List<TwoInts> twoIntList = new ArrayList<TwoInts>(intArrayArray.length);
twoIntList.add(new TwoInts(intArrayArray[0][i], intArrayArray[1][i]));
twoIntMap.put(intIn0, twoIntList);
} else {
twoIntMap.get(intIn0).add(new TwoInts(intArrayArray[0][i], intArrayArray[1][i]));
}
}
int idx = 0;
Iterator<Integer> itr2i = twoIntMap.keySet().iterator();
while(itr2i.hasNext()) {
List<TwoInts> twoIntList = twoIntMap.get(itr2i.next());
for(TwoInts twoi : twoIntList) {
intArrayArray[0][idx] = twoi.aElement;
intArrayArray[1][idx++] = twoi.bElement;
}
}
output2DArray("Sorted", intArrayArray);
}
private static final void output2DArray(String description, int[][] twoD_array) {
System.out.println(description + ":");
System.out.println("0: " + Arrays.toString(twoD_array[0]));
System.out.println("1: " + Arrays.toString(twoD_array[1]));
System.out.println();
}
}
class TwoInts {
public final int aElement;
public final int bElement;
public TwoInts(int a_element, int b_element) {
aElement = a_element;
bElement = b_element;
}
}
Output:
[C:\java_code\]java SortOneArrayKeepSecondArrayElementsAligned
Unsorted:
0: [6, 3, 1, 2, 3, 0]
1: [2, 1, 6, 6, 2, 4]
Sorted:
0: [0, 1, 2, 3, 3, 6]
1: [4, 6, 6, 1, 2, 2]
Try the following:
Disclaimer: Not tested :)
myarray = new int[10][2];
// populate the array here
Arrays.sort(myarray, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if (a[0] > b[0])
return 1;
else if (a[0] < b[0])
return -1;
else {
return 0;
}
}
};
You will have to write a custom sort. Look into Comparable and Comparator.
Something along the lines of:
public class MyComparator implements Comparator<T[]> {
int columnToSortOn;
public MyComparator(int columnToSortOn) {
this.columnToSortOn = columnToSortOn;
}
#Override
public int compare(T[] array1, T[] array2) {
return array1[columnToSortOn].compareTo(array2[columnToSortOn]);
}
}

Categories