Reputation: 21
I have this one boolean array [true,false,false,true,true] and want to split a 2d array using it. what I tried doing is
public static void sorting(boolean[] test, String[][] arr)
{
int counter = 0;
//finds how many people passed
for(int z = 0; z < arr.length; z++)
{
if (test[z] != false)
counter++;
}
String[][] passed = new String[counter][2];
//tests for which people had Passed and copies it over
for(int x = 0; x < passed.length; x++)
{
for(int y = 0; y < passed[x].length; y++)
if(arr[x] != false)
passed[x][y] = arr[x][y];
}
example2dArrayPrint(passed);
}
an input I would have is
Bob A
Fred F
Larry F
John C
Tom B
and the output would be
Bob A
John C
Tom B
I don't see why this will not properly sort. EDIT
the relation between the 2 arrays is, if test[0] == true, that part of arr[0][0] and arr[0][1] would be put into the new passed array, false would be skipped over.
EDIT2
Changed passed from 3 to 2, was a mistype while making this.
Upvotes: 0
Views: 60
Reputation: 40034
Here is a different approach using streams. I renamed the method to filtering as that is what you are doing, not sorting.
String[][] data = { { "Bob", "A" }, { "Fred", "F" },
{ "Larry", "F" }, { "John", "C" }, { "Tom", "B" } };
boolean[] test = { true, false, false, true, true };
String[][] result = filtering(test, data);
for (String[] a : result) {
System.out.println(Arrays.toString(a));
}
Prints
[Bob, A]
[John, C]
[Tom, B]
test
array.public static String[][] filtering(boolean[] test,
String[][] arr) {
return IntStream.range(0, test.length).filter(i -> test[i])
.mapToObj(i -> arr[i]).toArray(String[][]::new);
}
Upvotes: 1
Reputation:
public static void sorting(boolean[] test, String[][] arr){
int counter = 0;
//finds how many people passed
for(int z = 0; z < arr.length; z++){
if (test[z])
counter++;
}
//cols represents number of columns you have in your 2d matrix.
int cols=2;
String[][] passed = new String[counter][2];
counter=0;
//out loop for iterating over arr
for(int i=0;i<arr.length;i++)
if(test[i]){
//for all cols
for(int j=0;j<cols;j++){
passed[counter][j]=arr[i][j];
}
counter++;
}
example2dArrayPrint(passed);
}
Upvotes: 0
Reputation: 39477
You have to keep two different pointers - one for current position in passed
array and another in the input arr
.
Try this:
public static void sorting(boolean[] test, String[][] arr) {
int counter = 0;
//finds how many people passed
for (int z = 0; z < arr.length; z++) {
if (test[z])
counter++;
}
String[][] passed = new String[counter][2];
int i = 0;
//tests for which people had Passed and copies it over
for (int x = 0; x < arr.length; x++) {
if (test[x]) {
for (int y = 0; y < 2; y++) {
passed[i][y] = arr[x][y];
}
i++;
}
}
example2dArrayPrint(passed);
}
Outputs:
[[Bob, A], [John, C], [Tom, B]]
Upvotes: 1