I have the following code:
public class solutionsTest {
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException {
int allsolutions[][][][][] = new int[16][16][16][16][16];
for (int i = 0; i <= 15; i++) {
for (int j = 0; j <= 15; j++) {
for (int k = 0; k <= 15; k++) {
for (int l = 0; l <= 15; l++) {
allsolutions[i][j][k][l][j] = i;
System.out.println("Set index " + i + " " + j + " " + k + " " + l + " " + j + " equal to " + i);
}
}
}
}
System.out.println(allsolutions[4][2][1][4][5]);
System.out.println(allsolutions[5][2][1][4][5]);
System.out.println(allsolutions[6][2][1][4][5]);
System.out.println(allsolutions[7][2][1][4][5]);
System.out.println(allsolutions[8][2][1][4][5]);
}
}
The println check inside the loop correctly reports the stored data correctly, as you can see if you run the program. However, after the loops, if I try to retrieve any of the values that were set inside the loops, all of the values = 0. What am I missing?
As set in the loop, all values should correspond to the index of the first dimension of the array as such:
allsolutions[0][x][x][x][x] = 0;
allsolutions[1][x][x][x][x] = 1;
allsolutions[2][x][x][x][x] = 2;
And so on...
You never assign anything to allsolutions[4][2][1][4][5], or any of the other 4 array positions you are printing, so they remains 0. You only have 4 nested loops and 5 dimensions in your array.
You only assign values to positions where the 2nd index is equal the 5th index. If you try to print, for example, System.out.println(allsolutions[4][2][1][4][2]);, you'll see a non-zero value.
You should probably use 5 nested loop instead of re-using the j index :
for(int i=0;i<=15;i++){
for(int j=0;j<=15;j++){
for(int k=0;k<=15;k++){
for(int l=0;l<=15;l++){
for(int m=0;m<=15;m++){
allsolutions[i][j][k][l][m] = i;
System.out.println("Set index "+ i + " " + j + " " + k + " " + l + " " + m + " equal to " + i);
}
}
}
}
}
You're missing an inner loop. Try the following:
final int DIM = 16;
int[][][][][] allsolutions = new int[DIM][DIM][DIM][DIM][DIM];
for (int i = 0; i < DIM; i++){
for (int j = 0; j < DIM; j++) {
for (int k = 0; k < DIM; k++) {
for (int l = 0; l < DIM; l++){
for (int m = 0; m < DIM; m++) {
allsolutions[i][j][k][l][m] = i;
System.out.println("Set index " + i + " " + j + " " + k + " " + l + " " + m + " equal to " + i);
}
}
}
}
}
The issue stems from your last index using j instead of a new variable, such as m.
You're repeating j so you're not populating [?][x1][?][?][x2] when x1 != x2.
If the values are dependant on the indices, why are you not using a function?
public int getValue(int i, int dc1, int dc2, int dc3, int dc4){
if (i < 16 && 0 <= i){
return i;
}
// ... throw error or return sentinel value
}
And use it:
System.out.println(getValue(4,2,1,4,5)); // 4
You can extend it to something more sophisticated without storing all the data statically.
It worked for me :
import java.util.Arrays;
public class SolutionsTest {
private static int [][][][] allsolutions;
//make the arrays static and as a field not local
public static void main (String args[]) {
allsolutions = new int [16][16][16][16];
//Initialize the arrays
for (int i = 0; i < 16;i++) { // The i or index loop
for (int x = 0; x < 16;x++) {
for (int y = 0; y < 16;y++) {
for (int z = 0; z < 16; z++) {
allsolutions[i][x][y][z] = i; //set all as index
}
}
}
}
System.out.println(allsolutions[0][0][0][0]); //prints 0
System.out.println(allsolutions[1][0][0][0]); //prints 1
System.out.println(allsolutions[2][0][0][0]); //prints 2
System.out.println(allsolutions[3][0][0][0]); //prints 3
System.out.println(allsolutions[0][4][5][5]); //prints 0
System.out.println(allsolutions[1][8][9][10]); //prints 1
System.out.println(allsolutions[2][9][10][1]); //prints 2
System.out.println(Arrays.deepToString(allsolutions));
//prints all arrays
}
}
The following code output the right results
Related
As the title says, I want to know a way (in Java) to find which row (in a matrix/2D Array) and column has the highest sum of its numbers.
There might be an easy solution but I'm struggling to find it.
I currently have the first part of the program but I can't seem to find a solution to the second part, which is finding the row and column with the highest sum.
Desired output
I'm a beginner at this so any kind of advice would be appreciated.
This is the first part of my code:
import javax.swing.JOptionPane;
public class summat{
public static void main(String[] args){
int mat[][] = new int [3][3];
int num, sumop, sumw, i, j, mayop = 0, mayw = 0;
for(i=0;i<3;i++){
for(j=0;j<3;j++){
String input = JOptionPane.showInputDialog(null, "Products sold by the operator " + (i+1) + " in week " + (j+1) + ".");
mat[i][j] = Integer.parseInt(input);
}
}
/*Sum of individual rows*/
for(i=0;i<3;i++){
sumop = 0;
for(j=0;j<3;j++){
sumop = sumop + mat[i][j];
}
JOptionPane.showMessageDialog(null, "The operator " + (i+1) + " sold " + sumop + " units.");
}
/*Sum of individual columns*/
for(j=0;j<3;j++){
sumw = 0;
for(i=0;i<3;i++){
sumw = sumw + mat[i][j];
}
JOptionPane.showMessageDialog(null, "In week " + (j+1) + " the company sold " + sumw + " units.");
}
}
}
public static void method(int[] arr, int row, int col) {
// converting array to matrix
int index = 0;
int mat[][] = new int[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
mat[i][j] = arr[index];
index++;
}
}
// calculating sum of each row and adding to arraylist
ArrayList<Integer> rsum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int r = 0;
for (int j = 0; j < col; j++) {
r = r + mat[i][j];
}
rsum.add(r);
}
// calculating sum of each col and adding to arraylist
ArrayList<Integer> csum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int sum = 0;
for (int j = 0; j < col; j++) {
sum = sum + mat[j][i];
}
csum.add(sum);
}
System.out.println(
"Maximum row sum is " + Collections.max(rsum) + " at row " + rsum.indexOf(Collections.max(rsum)));
System.out.println(
"Maximum col sum is " + Collections.max(csum) + " at col " + csum.indexOf(Collections.max(csum)));
}
public static void method(int[][] mat, int row, int col) {
// calculating sum of each row and adding to arraylist
ArrayList<Integer> rsum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int r = 0;
for (int j = 0; j < col; j++) {
r = r + mat[i][j];
}
rsum.add(r);
}
// calculating sum of each col and adding to arraylist
ArrayList<Integer> csum = new ArrayList<Integer>();
for (int i = 0; i < row; i++) {
int sum = 0;
for (int j = 0; j < col; j++) {
sum = sum + mat[j][i];
}
csum.add(sum);
}
System.out.println(
"Maximum row sum is " + Collections.max(rsum) + " at row " + rsum.indexOf(Collections.max(rsum)));
System.out.println(
"Maximum col sum is " + Collections.max(csum) + " at col " + csum.indexOf(Collections.max(csum)));
}
You can use the following logic and implement it as desired.
// Row calculation
int rowSum = 0, maxRowSum = Integer.MIN_VALUE, maxRowIndex = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
rowSum = rowSum + mat[i][j];
}
if (maxRowSum < rowSum) {
maxRowSum = rowSum;
maxRowIndex = i;
}
rowSum = 0; // resetting before next iteration
}
// Column calculation
int colSum = 0, maxColSum = Integer.MIN_VALUE, maxColIndex = Integer.MIN_VALUE;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
colSum = colSum + mat[j][i];
}
if (maxColSum < colSum) {
maxColSum = colSum;
maxColIndex = i;
}
colSum = 0; // resetting before next iteration
}
System.out.println("Row " + maxRowIndex + " has highest sum = " +maxRowSum);
System.out.println("Col " + maxColIndex + " has highest sum = " +maxColSum);
Here we use two additional variables maxRowSum to store the highest sum of the row and maxRowIndex to store the index of the highest row. The same applies for column as well.
You can have to integers one for row(maxRow) and one for col(maxCol) to maintain max values:
int maxRow = Integer.MIN_VALUE;
/*Sum of individual rows*/
for(i=0;i<3;i++){
sumop = 0;
for(j=0;j<3;j++){
sumop = sumop + mat[i][j];
}
if(maxRow > sumop)
maxRow = sumop;
JOptionPane.showMessageDialog(null, "The operator " + (i+1) + " sold " + sumop + " units.");
}
int maxCol = Integer.MIN_VALUE;
/*Sum of individual columns*/
for(j=0;j<3;j++){
sumw = 0;
for(i=0;i<3;i++){
sumw = sumw + mat[i][j];
}
if(maxCol > sumw)
maxCol = sumw;
JOptionPane.showMessageDialog(null, "In week " + (j+1) + " the company sold " + sumw + " units.");
}
Here's a method that first computes both row-wise and column-wise sums in one loop (the same one it uses to find max row sum), and a second one to find the max column sum:
//This returns an array with {maxRowIndex, maxColumnIndex}
public static int[] findMax(int[][] mat) {
int[] rowSums = new int[mat.length];
int[] colSums = new int[mat[0].length];
int maxRowValue = Integer.MIN_VALUE;
int maxRowIndex = -1;
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat[i].length; j++) {
rowSums[i] += mat[i][j];
colSums[j] += mat[i][j];
}
if (rowSums[i] > maxRowValue) {
maxRowIndex = i;
maxRowValue = rowSums[i];
}
// display current row message
JOptionPane.showMessageDialog(null, "The operator " +
(i + 1) + " sold " + rowSums[i] + " units.");
}
int maxColumnValue = Integer.MIN_VALUE;
int maxColumnIndex = -1;
// look for max column:
for (int j = 0; j < mat[0].length; j++) {
if (colSums[j] > maxColumnValue) {
maxColumnValue = colSums[j];
maxColumnIndex = j;
}
// display column message
JOptionPane.showMessageDialog(null, "In week " +
(j + 1) + " the company sold " + colSums[j] + " units.");
}
return new int[] { maxRowIndex, maxColumnIndex };
}
The following test (I had to hard-code matrix values) produces [2, 2]:
public static void main(String[] args) {
int mat[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
int[] maxValues = findMax(mat);
System.out.println("Max row index: " +
maxValues[0] + ". Max Column index: " + maxValues[1]);
}
I want to print the following pattern in java:
a+1357+1
b+246+2
a+13+3
b+2+4
following is my code, but with this i can only print odd no. or only even no.s
public static void main(String[] args) {
int rows = 7;
for(int i = rows; i >= 1; i=i-2) {
for(int j = 1; j <= i; j=j+2) {
System.out.print(j + " ");
}
System.out.println();
}
}
DEMO
var rows = 4;
for (var i = 4; i > 0; i--) {
for (var j = 1; j <= i; j++) {
document.write((i % 2) + (2 * j) - 1 + " ");
}
document.write('<br>');
}
public static void main(String[] args) {
int rows = 4;
for(int i = rows; i > 0; i--) {
for(int j = 1; j <= i; j++) {
System.out.print((i%2)+(2*j)-1 + " ");
}
System.out.println();
}
}
You need to make a pattern for it. here you can use (i%2)+(2*j)-1
With only a few updates of your code (but not very readable):
int rows = 7;
for (int i = rows; i >= 1; i = i - 2) {
System.out.print((((i + 1) % 4) == 0 ? "a" : "b") + " + ");
for (int j = 1; j <= i; j = j + 2) {
System.out.print((j + ((i + 2) % 4) / 2));
}
System.out.println(" + " + (10 - i) / 2);
}
But instead of using my code, I suggest you write down exactly how the "pattern" is defined and write new code based on your specification. These loops are not optimal.
Am confused about getting the "sub diagonal" for 2D array, I can get the columns , rows and major diagonal, but i don't know how to get sub diagonal, here is what i'v done so far:
int size = input.nextInt();
int[][] list = initiateArr(size);
for (int i = 0; i < list.length; i++) {
for (int j = i ; j < i + 1; j++) {
System.out.print(list[i][j] + " ");
}
}
My attempt for "sub diagonal":
for (int i = 0; i < list.length; i++) {
for (int j = (list.length / 2) + 1; j > list.length - (i + 1) ; j--) {
System.out.print(list[i][j] + " ");
System.out.println("j = " + j);
}
}
How to get sub diagonal?
I can get the major diagonal right as described in the output 1111, the sub diagonal should be 1010.
Here is the answer. Let me know if you have any questions.
public static void main(String args[]) {
int[][] list = {{1,2,3}, {4,5,6},{7,8,9}};
int matrixSize = 3;
System.out.println("Subdiagonal");
for( int i = 0; i < matrixSize ; i ++){
System.out.print( list[i][matrixSize - i -1] + " ");
}
System.out.println("");
System.out.println("Major ");
for( int i = 0; i < matrixSize ; i ++){
System.out.print( list[i][i] + " ");
}
}
Hello I am trying to create a java program that output multiplication grid and I want to know if there is way to do it without having a lot of if statement if I had n values. Here is the code
public class MultiplicationGrid {
public static void main(String[] args) {
int num[][] = new int[4][4];
//String size[][] = new String[1][13];
for(int i = 0; i < num.length; ++i) {
for(int j = 0; j < num[i].length;++j) {
num[i][j] = (j+1)*(i+1);
}
}
int count = 0;
int count1 = 0;
int count2 = 0;
int count3 = 0;
for (int i = 0; i < num.length; ++i) {
for(int j = 0; j < num[i].length; ++j) {
if(count == 0) {
count = num [i][j];
continue;
}
if(count1 == 0) {
count1 = num [i][j];
continue;
}
if(count2 == 0) {
count2 = num [i][j];
continue;
}
if(count3 == 0) {
count3 = num [i][j];
}
System.out.println(count + " " + (count1) + " " + (count2) + " " + (count3));
count = 0;
count1 = 0;
count2 = 0;
count3 = 0;
}
}
}
}
Thanks in advance.
You can define the table size and print the multiplication grid as follows:
public static void main(String[]args) {
final int TABLE_SIZE = 12;
// Declare the rectangular array to store the multiplication table:
int[][] table = new int[TABLE_SIZE][TABLE_SIZE];
// Fill in the array with the multiplication table:
for(int i = 0 ; i < table.length ; ++i) {
for(int j = 0 ; j < table[i].length ; ++j) {
table[i][j] = (i+1)*(j+1);
}
}
// Output the table heading
System.out.print(" :"); // Row name column heading
for(int j = 1 ; j <= table[0].length ; ++j) {
System.out.print((j<10 ? " ": " ") + j);
}
System.out.println("\n-------------------------------------------------------");
// Output the table contents
for(int i = 0 ; i < table.length ; ++i) {
System.out.print("Row" + (i<9 ? " ":" ") + (i+1) + ":");
for(int j = 0; j < table[i].length; ++j) {
System.out.print((table[i][j] < 10 ? " " : table[i][j] < 100 ? " " : " ") + table[i][j]);
}
System.out.println();
}
}
I'm trying to write code that checks for repeat numbers in an array. If numbers repeat within the same row, it should generate another random number to replace the number. This is my class/method that is meant to accomplish this goal:
import java.util.*;
public class NoRepeats
{
public static void clean(int ticks[][])
{
for(int i = 0; i < ticks.length; i++)
{
for(int j = 0; j < ticks[0].length; j++)
{
nums[j] = ticks[i][j];
}
for(int k = 0; k < nums.length; k++)
{
for(int count = k + 1; count < nums.length; count++)
{
int othNums = nums[count];
while(true)
{
if(nums[k] == othNums)
{
System.out.print("\n\n Repeat:" + nums[k] + k + " " + othNums + "\tTicket Number: " + (i+1) +"\n\n\n");
nums[k] = 1 + rndm.nextInt(48);
for(int counter = count; counter < nums.length; counter++)
{
int othNums2 = nums[count];
if(nums[k] == othNums2)
{
System.out.print("\n\n Repeat NUM2:" + nums[k] + " " + othNums2 + "\tTicket Number: " + (i+1) +"\n\n\n");
nums[k] = 1 + rndm.nextInt(48);
}
}
for(int l = 0; l < k; l++)
{
int othNums3 = nums[l];
if(nums[k] == othNums3)
{
System.out.print("\n\n RepeatNUM2: " + nums[k] + " " + othNums3 + "\tTicket Number: " + (i+1) +"\n\n\n");
nums[k] = 1 + rndm.nextInt(48);
}
}
}
else
{
break;
}
}
count++;
}
}
for(int q = 0; q < nums.length; q++)
{
ticks[i][q] = nums[q];
}
count = 0;
}
}
public static int nums[] = new int[6];
public static int count = 1;
public static Random rndm = new Random();
public static int numsMatched[] = new int[100];
}
For some reason, there are still matches and I don't know why. Can anyone find what I've done wrong?
You're incrementing count twice and thus skip entries:
for(int count = k + 1; count < nums.length; count++) //<- increment 1
{
int othNums = nums[count];
while(true)
{
//snip
}
count++; //<- increment 2
}
The problem probably originates from the fact that you have a static variable which is also called count and which will be shadowed by the count defined in the loop:
public static int count = 1;
So either remove the second increment or rename one of the variables.