How to check number of rows with only 0 on 3D matrix? - java

I need to count how many rows does the user inputs that are only 0, something like:
Test 1
0 0 0
1 2 3
2 2 1
Test 2
1 2 3
0 0 0
0 0 0
Rows with only 0 values: 3
This is the code that reads the matrices:
final int rows = 3, cols = 3;
Scanner input = new Scanner(System.in);
System.out.println("Number of tests");
int n = input.nextInt();
int test[][][] = new int[n][rows][cols];
for (int i = 0; i < n; i++) {
System.out.println("Test " + (i + 1));
for (int j = 0; j < rows; j++) {
for (int k = 0; k < cols; k++) {
test[i][j][k] = input.nextInt();
}
}
}

You can get the number of zero rows in a 3D matrix using Streams as follows:
public static void main(String[] args) {
int[][][] test = {
{{0, 0, 0}, {1, 2, 3}, {2, 2, 1}},
{{1, 2, 3}, {0, 0, 0}, {0, 0, 0}}};
System.out.println(zeroRowsCount(test)); // 3
}
public static long zeroRowsCount(int[][][] arr3d) {
return Arrays.stream(arr3d)
// the number of zero rows in each 2D array
.mapToLong(arr2d -> zeroRowsCount(arr2d))
// total number of zero rows
.sum();
}
public static long zeroRowsCount(int[][] arr2d) {
return Arrays.stream(arr2d)
// filter those rows that consist of zeros
.filter(row -> Arrays.stream(row)
// all elements are zeros
.allMatch(i -> i == 0))
// the number of zero rows
.count();
}

Related

How do we do sum of indexes in a 2D array

I have a 2D array where rows = 3 and columns = 2. I want to get a sum of all the indices. Here is my array.
arr[][] = [1, 2], [3, 4], [5, 6]
Row 1
At index (0, 0) the sum of indexes becomes (0 + 0 = 0)
At index (0, 1) the sum of indexes becomes (0 + 1 = 1)
Row 2
At index (1, 0) the sum of indexes becomes (1 + 0 = 1)
At index (1,1) the sum of indexes becomes (1 + 1 = 2)
Row 3
At index (2, 0) the sum of indexes becomes (2 + 0 = 2)
At index (2, 1) the sum of indexes becomes (2 + 1 = 3)
My expected output becomes
0 1 1 2 2 3
I am unable to find any resource, how to do this
Another quick example:
import java.util.*;
class Main {
public static void main(String[] args) {
int[][] arr = new int[3][2];
for(int row=0; row<arr.length; row++) {
for(int col=0; col<arr[row].length; col++) {
arr[row][col] = row + col;
}
}
for(int[] row : arr) {
System.out.println(Arrays.toString(row));
}
}
}
Output:
[0, 1]
[1, 2]
[2, 3]
You have to do sum of column and row using for loop or any other loop.
import java.util.*;
public class Main
{
public static void main(String[] args) {
int rows, cols, sumIndex = 0;
int a[][] = {
{1, 2},
{3, 4},
{5, 6}
};
rows = a.length;
cols = a[0].length;
for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
sumIndex = i + j;
System.out.print(sumIndex + " ");
}
}
}
}

How to get all possible combinations of elements of one (int) array?

I've been writing code to get all combinations of elements from array, but I couldn't figure out how to do it. Can you guys give me some advice?
This is what I'm trying to do...
int[] num = {1, 2, 3, 4, 5};
int n = num.length;
int length = (n * (n - 1)) / 2;
int[] list = new int[length];
for (int j = 0; j < n - 1; j++) {
for (int p = 4;p < n; p--) {
for (int i = 0; (I < length); i++) {
list[i] = Math.abs(num[j] - num[j + p]);
}
p++;
}
}
My result list would look like this..
list = {1, 2, 3, 4, 1, 2, 3, 1, 2, 1};
Thank you in advance.
edit: I'm really sorry that I didn't post my question clearly. What I was trying to do is get the absolute value of subtracting each values from array.
ex) 1-2 , 1-3, 1-4, 1-5, 2-3, 2-4, 2-5, 3-4, 3-5, 4,5
for (int v : list) {
System.out.println(v);
}
output:
1
2
3
4
1
2
...
Do it as follows:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] num = { 1, 2, 3, 4, 5 };
int n = num.length;
int length = (n * (n - 1)) / 2;
int[] list = new int[length];
// Index counter for list[]
int c = 0;
for (int i = n - 1; i >= 0; i--) {
for (int j = 0; j < i; j++) {
list[c++] = num[j];
}
}
// Display
System.out.println(Arrays.toString(list));
}
}
Output:
[1, 2, 3, 4, 1, 2, 3, 1, 2, 1]
For any value n the following should work. The key is to base the termination point of the inner loop on the outer loop's termination point.
System.out.println(string);
int n = 5;
int[] num = {1, 2, 3, 4, 5};
int length = (n * (n - 1)) / 2;
int m = 0;
int[] list = new int[length];
for (int i = 1; i<n ; i++) {
for (int k = 1; k <= n-i; k++) {
list[m++] = num[k-1];
}
}
System.out.println(Arrays.toString(list));
Prints
1 2 3 4 1 2 3 1 2 1

Make new int array double the size of an array copy the first numbers and put others in reverse without using methods

Lets say I input array {1,2,3,4} and I want to make a new one {1,2,3,4,4,3,2,1}.
import java.util.Scanner;
public class Task2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] arr = new int[4];
for(int i = 0; i < arr.length; i++){
System.out.println("Please enter number!");
arr[i]=sc.nextInt();
}
int[] actualArr = new int[arr.length*2];
for(int j = 0; j < arr.length; j++){
actualArr[j]=arr[j];
}
for (int k = arr.length - 1; k >= 0; k--) { //problem loop
actualArr[arr.length] = arr[k];
}
for (int g = 0; g < actualArr.length; g++) {
System.out.print(actualArr[g] + " ");
}
}
}
Why do I get 1 2 3 4 1 0 0 0 ? My int k starts from 3 but I get the [0] index from int[]arr which is 1 and not the last which is 4, also how can i copy the rest of the first array in reverse order?
Your problem is on this line insithe the for loop:
actualArr[arr.length] = arr[k];
arr.length will always be 4, so you will always update the 5th element (element at index 4 because arrays are zero-based in Java) in your actualArr array leaving the remaining slots of the array with the default int value 0. Look how actualArr changes on each iteration of that loop:
actualArr = {1, 2, 3, 4, 4, 0, 0, 0} // 1st iteration
actualArr = {1, 2, 3, 4, 3, 0, 0, 0} // 2nd iteration
actualArr = {1, 2, 3, 4, 2, 0, 0, 0} // 3rd iteration
actualArr = {1, 2, 3, 4, 1, 0, 0, 0} // 4th iteration and final output
You can do this to fill the array correctly:
for (int k = arr.length - 1; k >= 0; k--) {
actualArr[actualArr.length - k - 1] = arr[k];
}
The expression actualArr.length - k - 1 will result in a sequence from 4-7 filling the array as you want.
You may can define a new integer like z and z is initial for your new array (actualArr):
int[] actualArr = new int[arr.length*2];
int z=0;
for(int j = 0; j < arr.length; j++){
actualArr[z]=arr[j];
z++;
}
for (int k = arr.length-1 ; k >= 0; k--) { //problem loop
actualArr[z] = arr[k];
z++;
}

how to check all reachable cells from one cell

I need to check all possible paths that is reachable from one certain cell in a 2d array. For example;
int [][] grid = {{2, 0, 0, 1, 1, 2},
{1, 0, 2, 0, 0, 1},
{1, 0, 2, 0, 4, 2},
{8, 3, 4, 0, 1, 2},
{1, 2, 5, 0, 3, 3},
{5, 1, 1, 2, 1, 0}};`
and I want to check all cells that is reachable from cell(2)(1) (it is just an example location). First some number will be placed here if this location is zero. For example, 1 is placed at that location.
Then I need to start merging all 1’s which are reachable from cell (2,1).Then cell(2)(1) location must be replaced with the 2 if the cells that create this path includes at least two 1 since 1+1 = 2.
After that, the cells which are used during merging process must be assigned to zero.
But if there is still possible merging for cell(2)(1) they should be merged too.
I try to use recursive function but it did not work as I want.
I could not figure out how to prevent merging if there are less than 3 neighbor cells which includes same value and how to merge until no possible merging left. Method should continue merging until there are no possible merge left, but my code merge for once. I have just started to learn java sorry for mistakes already now.
So...
I am not sure if I got everything right because some things are misleading.
cell(2)(2) has the initial content: 2
I think your chosen cell is (1)(2). //note: indices in java start with 0
So your idea is a little bit more complex and should not be solved with only one method.
I've written some code:
private static int[][] directions = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
public static void step(int[][] array, int x, int y) {
if(array[x][y] == 0){
array[x][y] = 1;
}else{
return;
}
int number = 1;
while(true){
printGrid(array);
int amount = process(array, x, y);
if(amount == 1)break;
number ++;
array[x][y] = number;
}
}
public static int process(int[][] array,int x, int y){
int number = array[x][y];
if(number == 0) return 0;
int total = 1;
array[x][y] = 0;
for(int[] dire:directions){
if(x + dire[0] >= 0 && x + dire[0] < array.length && y + dire[1] >= 0 && y + dire[1] < array[0].length){
if(array[x + dire[0]][y+dire[1]] == number){
total += process(array, x + dire[0], y+dire[1]);
}
}
}
return total;
}
public static void printGrid(int[][] grid) {
for(int i = 0; i < grid.length; i++){
String s = "";
for(int n = 0; n< grid[0].length; n++){
s += grid[i][n]+", ";
}
System.out.println(s);
}
System.out.println("");
}
public static void main(String[] args){
int [][] grid =
{{2, 0, 0, 1, 1, 2},
{1, 0, 2, 0, 0, 1},
{1, 0, 2, 0, 4, 2},
{8, 3, 4, 0, 1, 2},
{1, 2, 5, 0, 3, 3},
{5, 1, 1, 2, 1, 0}};
Main.step(grid, 2,1);
printGrid(grid);
}
I modified it like this;
public static void main(String []args){
System.out.println("Welcome to the game Merge Numbers. Your grid as follows:");
int[][] newGrid = {{2, 0, 1, 1, 0, 8},
{2, 1, 0, 2, 4, 0},
{1, 2, 1, 2, 1, 3},
{2, 3, 2,0, 1, 0},
{0, 0, 5, 8, 7, 2},
{2, 0, 1, 1, 0, 0}};
for(int i = 0 ; i < newGrid.length ; i++){
for (int j = 0; j < newGrid[i].length; j++) {
System.out.print(newGrid[i][j] + " ");
}
System.out.println();
}
try (Scanner keyboard = new Scanner(System.in)){
System.out.print("Please enter your target's row index:");
int newRow = keyboard.nextInt();
System.out.print("Please enter your target's column index:");
int newColumn = keyboard.nextInt();
System.out.print("Please enter the number that you want to add to location " + newRow + " " + newColumn);
int newNextNumber = keyboard.nextInt();
step(newGrid, newRow, newColumn, newNextNumber);
for(int i = 0 ; i < newGrid.length ; i++){
for (int j = 0; j < newGrid[i].length; j++) {
System.out.print(newGrid[i][j] + " ");
}
System.out.println();
}}
}
public static void step(int[][] grid, int row, int column, int nextNumber ) {
if(grid[row][column] == 0){
grid[row][column] = nextNumber;
}else{
return;
}
int number = nextNumber;
while(true){
int amount = process(grid, row, column);
if(amount == 1)break;
number ++;
grid[row][column] = number;
}
}
public static int process(int[][] grid,int row, int column){
int number = grid[row][column];
if(number == 0) return 0;
int total = 1;
grid[row][column] = 0;
for(int[] dire:directions){
if(row + dire[0] >= 0 && row + dire[0] < grid.length && column + dire[1] >= 0 && column + dire[1] < grid[0].length){
if(grid[row + dire[0]][column+dire[1]] == number){
total += process(grid, row + dire[0], column+dire[1]);
}
}
}
return total;
}
}
But when I run it all the points include the target location becomes zero. Output is like;
Welcome to the game Merge Numbers. Your grid as follows:
2 0 1 1 0 8
2 1 0 2 4 0
1 2 1 2 1 3
2 3 2 0 1 0
0 0 5 8 7 2
2 0 1 1 0 0
Please enter your target's row index:3
Please enter your target's column index:3
Please enter the number that you want to add to location 3 3: 1
2 0 1 1 0 8
2 1 0 0 4 0
1 2 1 0 0 3
2 3 0 0 0 0
0 0 5 8 7 2
2 0 1 1 0 0
I mean if you look at the first grid in the output, cell(3)(3) is zero. When 1 is placed here, the 1's that are reachable from this cell(3)(3) merged. Then cell(3)(3) includes 2. After that same procedure follows. But when all possible merges done, all cells that has been used during the process include center became 0. Center should be increase by one after each merging. I think, I use the fourth parameter which is nextNumber incorrectly. Should function process also include that parameter or not? Sorry to disturb you so much :)
here is how you can find neighbors of a cell...
int x[] = {-1, -1, -1, 0, 0, +1, +1, +1};
int y[] = {-1, 0, +1, -1, +1, -1, 0, +1};
// looping through the neghibours...
for(int i=0; i<8; i++) {
if( p+x[i] < n && q+y[i] < m && a[p + x[i]][q + y[i]] == a[p][q]) {
// neighbour
}
}
Here is the recursive implementation of your problem, n & m is the size of grid a and p & q is the index of the cell you want to perform merge...
public static void merge(int a[][], int n, int m, int p, int q) {
int x[] = {-1, -1, -1, 0, 0, +1, +1, +1};
int y[] = {-1, 0, +1, -1, +1, -1, 0, +1};
int c = 0;
// looping through the neghibours...
for(int i=0; i<8; i++) {
if( p+x[i] < n && q+y[i] < m && a[p + x[i]][q + y[i]] == a[p][q]) {
c++;
}
}
if(c > 3) { // merging only if neghibours > 3
for(int i=0; i<8; i++) {
if( p+x[i] < n && q+y[i] < m && a[p + x[i]][q + y[i]] == a[p][q]) {
a[p + x[i]][q + y[i]] = 0;
}
}
a[p][q] += 1;
merge(a, n, m, p, q); // recurcively merging if possible...
}
}

How to find the common set of numbers in a 2D array?

I have a 2D array which if filled like this .
1 2 0 0 0
1 2 0 0 0
0 0 3 4 5
0 0 3 4 5
0 0 3 4 5
another example
1 2 3 0
1 2 0 4
1 0 3 4
0 2 3 4
the code which I want to write is
searching about the maximum set of number repeated in the array .
in example 1 : the answer is 3 because the maximum is ( 3 4 5 ) repeted 3 times unlike ( 1 2 ) repeated just once .
Also in example 2, the maximum is 2 because you will not have the same set of numbers repeated more than two times .
I want to write a code for that .
any help ?!
Although this does not solve your issue directly, you can gather and count all sequences by assigning them as keys in a Map. After you do this, you can get the longest sequences and see which one has the highest frequency.
Output from Code Below
Sequence Frequency
-------- ---------
2 2
5 3
1,2 2
3,4,5 3 // <- Longest sequence, Highest frequency.
4,5 3
Sequence Frequency
-------- ---------
1 1
2 1
3 1
4 3 // <- Highest frequency, but not a sequence.
2,3,4 1
1,2 1
1,2,3 1
2,3 1
3,4 2 // <- Second highest frequency, is a sequence.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
public class MatrixSequenceFrequency {
public static void main(String[] args) {
int[][] arr1 = new int[][] {
{ 1, 2, 0, 0, 0 },
{ 1, 2, 0, 0, 0 },
{ 0, 0, 3, 4, 5 },
{ 0, 0, 3, 4, 5 },
{ 0, 0, 3, 4, 5 }
};
printSequences(findSequences(arr1));
int[][] arr2 = new int[][] {
{ 1, 2, 3, 0 },
{ 1, 2, 0, 4 },
{ 1, 0, 3, 4 },
{ 0, 2, 3, 4 }
};
printSequences(findSequences(arr2));
}
private static Map<String, Integer> findSequences(int[][] arr) {
Map<String, Integer> sequences = new HashMap<String, Integer>();
for (int i = 0; i < arr.length; i++) {
indexSequences(arr[i], sequences);
}
return sequences;
}
private static void indexSequences(int[] arr, Map<String, Integer> sequences) {
StringBuffer buff = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
for (int j = i; j < arr.length; j++) {
if (arr[j] != 0) {
buff.append(arr[j]).append(',');
} else {
break; // `0` breaks the sequence.
}
}
if (buff.length() > 0) {
if (buff.charAt(buff.length() - 1) == ',') {
buff.deleteCharAt(buff.length() - 1); // Remove extra comma.
}
Integer value = sequences.get(buff.toString());
sequences.put(buff.toString(), value == null ? 1 : value + 1);
buff.delete(0, buff.length()); // Clear Buffer
}
}
}
private static void printSequences(Map<String, Integer> sequences) {
String format = "%-10s %s%n";
System.out.printf(format, "Sequence", "Frequency");
System.out.printf(format, "--------", "---------");
for (Iterator<Entry<String, Integer>> it = sequences.entrySet().iterator(); it.hasNext();) {
Entry<String, Integer> entry = it.next();
System.out.printf(format, entry.getKey(), entry.getValue().toString());
}
System.out.println();
}
}
I would filter through the array and add each number that is the same to a variable and then display the variable with the most hits
int three = 0;
for (int i = 0; i < array.size(); i++){
if(array.get(i) == 3){
three++;
}else if(array.get(i) == "Some other number"){
number++;
}
then you would need to filter through the numbers you just added up so
Collections.sort(arrayList); // Sort the arraylist
arrayList.get(arrayList.size() - 1); //gets the last item, largest for an ascending sort
then i would sort through the Array as to see how many are the same
if(arrayList.size() - 1 == arrayList.size() - 2){
System.out.println(arrayList.size() - 1 " & " arrayList.size() - 2);
}
There would be a lot more tedious coding but this would be the foundation of your code you first add the values to the variable and sort through the array list to see what value appeared the most and you would need a 2D Array for adding the actual variables we made at the start then sort them highest to lowest.
Here use this program
public class Matrix {
public static void main(String[] args) {
int[][] a = new int[][] {
{ 1, 2, 3 },
{ 3, 3, 3 },
{ 1, 2, 3 }
};
int result = 0;
int largestNum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (result <= count(a[i][j], a)) {
result = count(a[i][j], a);
largestNum = a[i][j];
}
}
}
// Display the result
System.out.println("Largest Number: " + largestNum);
}
public static int count(int arrVal, int[][] a) {
int count = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (arrVal == a[i][j]) {
count++;
}
}
}
return count;
}
}
For simplicity I have declared a 2d array of length 3 for both rows and columns. You can use array of any length

Categories

Resources