Checking For Repeats - java

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.

Related

Index out of bounds, error in IF line of code

So, this code is supposed to do the following:
Check if the neighboring members in a row of the square matrix and write them if their sum is an even number and also write the members which sum is a odd number. But it sends an error in the first if statement. But it only does the first row and outputs the Index out of bounds. Here is the code:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Ucitati broj clanova kvadratne matrice: ");
int n = scan.nextInt();
int niz[][] = new int[n][n];
System.out.println("Ucitati clanove matrice: ");
for (int i = 0; i < niz.length; i++) {
for (int j = 0; j < niz.length; j++) {
System.out.print("n[" + i + ", " + j + "]" + "=");
niz[i][j] = scan.nextInt();
}
}
System.out.println();
for (int i = 0; i < niz.length; i++) {
for (int j = 0; j < niz.length; j++) {
System.out.print(niz[i][j] + " ");
}
System.out.println();
}
System.out.println("Susedni clanovi cija je suma parna su: ");
for (int i = 0; i < niz.length; i++) {
for (int j = 0; j < niz.length; j++) {
if ((niz[i][j] + niz[i][j + 1]) % 2 == 0) {
System.out.print(niz[i][j] + " " + niz[i][j + 1] + "; ");
}
}
}
System.out.println("Susedni clanovi cija je suma neparna su: ");
for (int i = 0; i < niz.length; i++) {
for (int j = 0; j < niz.length; j++) {
if ((niz[i][j] + niz[i][j + 1]) % 2 != 0) {
System.out.print(niz[i][j] + " " + niz[i][j + 1] + "; ");
}
}
}
}
System.out.println are in Serbian so if u need a translate let me know, but that shouldn't be needed.

(Java ) Finding the largest number in an array and it's location

I'm currently learning Java and while I'm able to find the largest number I'm stuck on how to find it's location. Any help would be greatly appreciated!
import java.util.Random;
public class FindingLargestValueInAnArray {
public static void main(String[] args) {
Random number = new Random();
int[] array_1 = new int[10];
int i = 0;
for (i = 0; i < array_1.length; i++) {
int randNum = 1 + number.nextInt(99);
array_1[i] = randNum;
}
System.out.print("Array:");
for (i = 0; i < array_1.length; i++) {
System.out.print(" " + array_1[i]);
}
int largeNumb = 0;
for (i = 0; i < array_1.length; i++) {
if (array_1[i] > largeNumb) {
largeNumb = array_1[i];
}
}
System.out.println("\n\nThe largest value is
"+largeNumb);
}
}
public class FindingLargestValueInAnArray {
public static void main(String[] args) {
Random number = new Random();
int[] array_1 = new int[10];
int i = 0;
for (i = 0; i < array_1.length; i++) {
int randNum = 1 + number.nextInt(99);
array_1[i] = randNum;
}
System.out.print("Array:");
for (i = 0; i < array_1.length; i++) {
System.out.print(" " + array_1[i]);
}
int largeNumb = 0;
int index = 0;
for (i = 0; i < array_1.length; i++) {
if (array_1[i] > largeNumb) {
largeNumb = array_1[i];
index = i;
}
}
System.out.println("The largest value is " + largeNumb + " and it's location is" + index);
}
}
You should get an another variable for the index = 0 and then put it inside the if statement and make it equal to index = i;. After the loop ends the largest value index would be stored here.
you can make an int index=0
in the loop where you check if the number is bigger in the body of the if make infex=i. This way you will always have both the value and the index of the largest numnber.
import java.util.Random;
public class FindingLargestValueInAnArray {
public static void main(String[] args) {
Random number = new Random();
int[] array_1 = new int[10];
int i = 0;
for (i = 0; i < array_1.length; i++) {
int randNum = 1 + number.nextInt(99);
array_1[i] = randNum;
}
System.out.print("Array:");
for (i = 0; i < array_1.length; i++) {
System.out.print(" " + array_1[i]);
}
int largeNumb = array_1[0];
int index = 0;
for (i = 1; i < array_1.length; i++) {
if (array_1[i] > largeNumb) {
largeNumb = array_1[i];
index = i;
}
}
System.out.println("\n\nThe largest value is :" + largeNumb + " and it's index is: " + index);
}
}

Java - Find the row and column with the max sum

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]);
}

Optimal way to creating a multiplication table -java

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();
}
}

Java for loops not populating array correctly

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

Categories