Magic Square Code (java) - java

I've been having an issue with my Magic Square code. It continually prints "This is a magic square" even when I'm positive it isn't.
You enter 16 integers, and then the code is supposed to run and determine whether the entered integers create a magic square (i.e. the sum of all rows, columns, and diagonals are all equal).
I can't figure out how to make it print false.
import java.util.*;
public class MagicSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner keyboard = new Scanner (System.in);
int [] [] square = new int [4][4];
for (int row = 0; row < 4; row++)
{
for (int col = 0; col < 4; col++)
{
System.out.println("Input value for row " + (row+1) + " column " + (col+1));
square[row][col] = keyboard.nextInt();
}
}
int [] sumRow = new int [4];
int [] sumCol = new int [4];
int sum = 0;
for (int row = 0; row < 4; row ++)
{
for (int col = 0; col < 4; col ++)
{
sum = sum + square[row][col];
sumRow[row] = sum;
}
System.out.println("sum row " + row + "\n" + sumRow[row]);
sum = 0;
}
sum = 0;
for (int col = 0; col < 4; col ++)
{
for (int row = 0; row < 4; row ++)
{
sum = sum + square[row][col];
sumCol[col] = sum;
}
System.out.println("sum columns " + col + "\n" + sumCol[col]);
sum = 0;
}
int [] sumDiag = new int [4];
sum = 0;
for (int row = 0; row < 4; row++)
{
for (int col = 3; col > -1; col--)
{
sum = sum + square [row][col];
sumDiag[row] = sum;
}
System.out.println("sum diagonal " + row + "\n" + sumDiag[row]);
sum = 0;
}
int [] sumDiag2 = new int [4];
sum = 0;
for (int col = 0; col < 4; col ++)
{
for (int row = 3; row > -1; row --)
{
sum = sum + square[row][col];
sumDiag2[col] = sum;
}
System.out.println("sum diagonal 2 " + col + "\n" + sumDiag2[col]);
}
boolean bool = false;
int k = 0; int j = 1;
do
{
if (sumRow[k] == sumRow[j])
{
k = j;
j += 1;
bool = true;
}
else
{
bool = false;
System.out.println("Not a magic square");
break;
}
} while ((k < 4) && (j >- 1));
k = 0; j = 1;
do
{
if (sumCol[k] == sumRow[j])
{
k = j;
j += 1;
bool = true;
}
else
{
bool = false;
System.out.println("Not a magic square");
break;
}
} while ((k < 4) && (j >= -1));
String TorF = "";
if (bool = true)
{
TorF = "is";
}
else if (bool = false)
{
TorF = "is not";
}
System.out.println("This " + TorF + " a magic square.");
}
}

There is a number of issues in your code, as said in the comments.
First, you only need to verify the main and secondary diagonals.
Second, your code to compare the sums doesn't work for all cases and doesn't compare the diagonals.
Also, the if in the end is just wrong. Do this instead:
if (bool) {
} else {
}
And here is a solution:
int order = square.length;
int[] sumRow = new int[order];
int[] sumCol = new int[order];
int[] sumDiag = new int[2];
Arrays.fill(sumRow, 0);
Arrays.fill(sumCol, 0);
Arrays.fill(sumDiag, 0);
for (int row = 0; row < order; row++) {
for (int col = 0; col < order; col ++) {
sumRow[row] += square[row][col];
}
System.out.println("sum row " + row + "\n" + sumRow[row]);
}
for (int col = 0; col < order; col++) {
for (int row = 0; row < order; row ++) {
sumCol[col] += square[row][col];
}
System.out.println("sum columns " + col + "\n" + sumCol[col]);
}
for (int row = 0; row < order; row++) {
sumDiag[0] += square[row][row];
}
System.out.println("sum diagonal 0 " + "\n" + sumDiag[0]);
for(int row = 0; row < order; row++) {
sumDiag[1] += square[row][order - 1 - row];
}
System.out.println("sum diagonal 1 " + "\n" + sumDiag[1]);
boolean bool = true;
int sum = sumRow[0];
for (int i = 1; i < order; i++) {
bool = bool && (sum == sumRow[i]);
}
for (int i = 0; i < order; i++) {
bool = bool && (sum == sumCol[i]);
}
for (int i = 0; i < 2; i++) {
bool = bool && (sum == sumDiag[i]);
}
String tOrF = "";
if (bool) {
tOrF = "is";
} else {
tOrF = "is not";
}
System.out.println("This " + tOrF + " a magic square.");
Furthermore, there are some things you could do to optimize this code.

Related

How to escape infinite loop in this recursive code?

I am implementing N-Queen problem solver with backjumping algorithm and I have caught infinite loop error in recursive call.
I have mainly caused trouble in returning function.I think I have error in designing recursive calls.
package Backjumping;
import org.python.google.common.primitives.Ints;
import java.util.*;
public class Backjumping {
int size;
List<Integer> columns;
int numberofplaces;
int numberofbacktracks;
HashMap<Integer, List<Integer>> conflict;
boolean noBreak = true;
Backjumping(int size) {
this.size = size;
columns = new ArrayList();
conflict = new HashMap<>(size);
for (int i = 0; i < size; i++) {
conflict.put(i, new ArrayList<>());
}
}
List place(int startRow) {
if (columns.size() == size) {
System.out.println("Solution Found! The board size was :" + size);
System.out.println(numberofplaces + " total nodes assigned were made.");
System.out.println(numberofbacktracks + " total backtracks were executed.");
return this.columns;
} else {
for (int row = 0; row < size; row++) {
if (isSafe(columns.size(), row)) {
if (indexExists(columns, columns.size()))
columns.set(columns.size(), row);
else
columns.add(columns.size(), row);
numberofplaces += 1;
return place(startRow);
}
}
if (noBreak) {
List<Integer> max_check = conflict.get(columns.size());
int lastRow = Collections.min(max_check);
numberofbacktracks += 1;
conflict.replace(columns.size(), new ArrayList<>());
int previous_variable = columns.remove(lastRow);
return place(previous_variable);
}
}
return this.columns;
}
private boolean isSafe(int cols, int rows) {
for (int threatrow : columns) {
int threatcol = columns.indexOf(threatrow);
if (rows == threatrow || cols == columns.indexOf(threatrow)) {
(conflict.get(cols)).add(threatcol);
return false;
} else if ((threatrow + threatcol) == (rows + cols) || (threatrow - threatcol) == (rows - cols)) {
(conflict.get(cols)).add(threatcol);
return false;
}
}
return true;
}
public boolean indexExists(final List list, final int index) {
return index >= 0 && index < list.size();
}
public static void main(String[] args) {
System.out.println("Enter the size of board");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
Backjumping bj = new Backjumping(n);
double start = System.currentTimeMillis();
List cols = bj.place(0);
double end = System.currentTimeMillis();
System.out.println("Time to solve in second = " + (end - start) * 0.001 + " s");
System.out.print("Ths solution is : ");
cols.forEach(i -> System.out.print(((int) i + 1) + ", "));
System.out.println("\n\nPlotting CSP result on N_Queens board");
System.out.println("......................................\n");
bj.getBoardPic(n, cols);
}
public void getBoardPic(int size, List columns) {
int[] cols = Ints.toArray(columns);
int[][] matrix = new int[size][size];
for (int a = 0; a < size; a++) {
int j = cols[a];
matrix[a][j] = 1;
}
for (int a = 0; a < size; a++) {
for (int b = 0; b < size; b++) {
if (matrix[b][a] == 1)
System.out.print(" Q ");
else
System.out.print(" - ");
}
System.out.println();
}
}
}
The main errors are that when I assign row=0 in for (int row = 0; row < size; row++) the input size of n=6 goes wrong and other values are right.
When I assign row=startrow in for (int row = startrow; row < size; row++) the input size of n=6 goes right and other values are wrong.

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

Sorting multidimensional array without sort method?

I was tasked with creating a 2D array (10-by-10), filling it with random numbers (from 10 to 99), and other tasks. I am, however, having difficulty sorting each row of this array in ascending order without using the array sort() method.
My sorting method does not sort. Instead, it prints out values diagonally, from the top leftmost corner to the bottom right corner. What should I do to sort the numbers?
Here is my code:
public class Program3
{
public static void main(String args[])
{
int[][] arrayOne = new int[10][10];
int[][] arrayTwo = new int[10][10];
arrayTwo = fillArray(arrayOne);
System.out.println("");
looper(arrayTwo);
System.out.println("");
sorter(arrayTwo);
}
public static int randomRange(int min, int max)
{
// Where (int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);
return (int)(Math.random()* ((max - min) + 1) + min);
}
public static int[][] fillArray(int x[][])
{
for (int row = 0; row < x.length; row++)
{
for (int column = 0; column < x[row].length; column++)
{
x[row][column] = randomRange(10,99);
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
return x;
}
public static void looper(int y[][])
{
for (int row = 0; row < y.length; row++)
{
for (int column = 0; column < y[row].length; column++)
{
if (y[row][column]%2 == 0)
{
y[row][column] = 2 * y[row][column];
if (y[row][column]%10 == 0)
{
y[row][column] = y[row][column]/10;
}
}
else if (y[row][column] == 59)
{
y[row][column] = 99;
}
System.out.print(y[row][column] + "\t");
}
System.out.println();
}
//return y;
}
public static void sorter(int[][] z)
{
int temp = 0;
int tempTwo = 0;
int lowest;
int bravo = 0;
int bravoBefore = -1;
for (int alpha = 0; alpha < z.length; alpha++)
{
//System.out.println(alpha + "a");
lowest = z[alpha][bravoBefore + 1];
bravoBefore++;
for (bravo = alpha + 1; bravo < z[alpha].length; bravo++)
{
//System.out.println(alpha + "b");
temp = bravo;
if((z[alpha][bravo]) < lowest)
{
temp = bravo;
lowest = z[alpha][bravo];
//System.out.println(lowest + " " + temp);
//System.out.println(alpha + "c" + temp);
tempTwo = z[alpha][bravo];
z[alpha][bravo] = z[alpha][temp];
z[alpha][temp] = tempTwo;
//System.out.println(alpha + "d" + temp);
}
}
System.out.print(z[alpha][bravoBefore] + "\t");
}
/*
for (int alpha = 0; alpha < z.length; alpha++)
{
for (int bravo = 0; bravo < z.length - 1; bravo++)
{
if(Integer.valueOf(z[alpha][bravo]) < Integer.valueOf(z[alpha - 1][bravo]))
{
int[][] temp = z[alpha - 1][bravo];
z[alpha-1][bravo] = z[alpha][bravo];
z[alpha][bravo] = temp;
}
}
}
*/
}
}
for(int k = 0; k < arr.length; k++)
{
for(int p = 0; p < arr[k].length; p++)
{
least = arr[k][p];
for(int i = k; i < arr.length; i++)
{
if(i == k)
z = p + 1;
else
z = 0;
for(;z < arr[i].length; z++)
{
if(arr[i][z] <= small)
{
least = array[i][z];
row = i;
col = z;
}
}
}
arr[row][col] = arr[k][p];
arr[k][p] = least;
System.out.print(arr[k][p] + " ");
}
System.out.println();
}
Hope this code helps . Happy coding
let x is our unsorted array;
int t1=0;
int i1=0;
int j1=0;
int n=0;
boolean f1=false;
for(int i=0;i<x.length;i++){
for(int j=0;j<x[i].length;j++){
t1=x[i][j];
for(int m=i;m<x.length;m++){
if(m==i)n=j+1;
else n=0;
for(;n<x[m].length;n++){
if(x[m][n]<=t1){
t1=x[m][n];
i1=m;
j1=n;
f1=true;
}
}
}
if(f1){
x[i1][j1]=x[i][j];
x[i][j]=t1;
f1=false;
}
}
}
//now x is sorted; "-";

Trouble printing chars thru a 2 dim java array

I tried to run this code as a score table where I have chars and ints as below for heading;
A B c
1
2 65 //this is where I'm stuck again!
3
In order to print the score like (65) above in a particular place (matrix) but as soon as I try to add the print statements the table falls apart. Any help would be appreciated;
public class Table3 {
static int[][] list = new int[4][4];
//private char column = 'A';
//private int row = 1;
private static int row = 1;
public Table3(){
//column = 'A';
for (int i = 0; i < 4; i++) {
for (int j = 1; j < 4; j++)
list[i][j] = 0;
}
}
public static void table(char col, int row, int value) {
//System.out.printf("\n\n%s\n", "Table");
for (int i = 1; i < 4; i++) {
System.out.print(row + " ");
row++;
for (int j = 1; j < 4; j++)System.out.print(col + " ");
System.out.println("\n");
col++;
if (row >= 0 && row <= 4 && col >=0 && col <= 4)
System.out.print(list[col][row]=value);
System.out.println("\n");
}
}
}
Client
public class TableTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Table3 t = new Table3();
t.table('A', 5, 5);
}
}
Learn how to use System.out.printf. The docs are here.
public class Table3
{
static int numRows = 4;
static int numCols = 4;
static int[][] list = new int[numRows][numCols];
public Table3()
{
//column = 'A';
for (int i = 0; i < 4; i++)
{
//this is the row number so you don't have to print it manually
//just print the array
list[i][0] = i;
//initialize the list to 0
for (int j = 1; j < 4; j++)
{
list[i][j] = 0;
}
}
}
public static void table(char col, int row, int value)
{
list[row][col] = value;
int columnWidth = 5; //in characters
//empty space before first column header
for (int i = 0; i < columnWidth; i++)
{
System.out.print(" ");
}
//print the column headers (A through C)
for (int i = 1; i < numCols; i++)
{
System.out.printf("%-" + columnWidth" + "c", (char)(64 + i));
}
System.out.println(); //get off of the column header row
//print the rest of the table
for (int i = 1; i < numRows; i++)
{
for (int j = 0; j < numCols; j++)
{
if (list[i][j] == 0)
{
System.out.printf("%" + columnWidth + "s", " ");
}
else
{
System.out.printf("%-" + columnWidth + "d", list[i][j]);
}
}
System.out.println("\n");
}
}
}

Categories