Java Magic square program
Here is my improved version of my Magic square program from this topic:
Speed up Magic square program.
I also added a few comments.
Any help for improvments would be really appreciated.
import java.util.HashSet;
import java.util.Scanner;
public class MagicSquare {
private int square;
private int row_sum;
private int col_sum;
private int magicNumber;
private int size;
private boolean usedNumbers;
private int solutions=0;
private int squareSize;
public MagicSquare(int size) {
this.size = size;
this.usedNumbers = new boolean[size * size + 1];
this.square = new int[size * size];
this.row_sum = new int[size];
this.col_sum = new int[size];
this.magicNumber = ((size * size * size + size) / 2);
this.squareSize = size * size;
}
private boolean solve(int x) {
if (x == squareSize && checkDiagonals()) {
for (int i = 0; i < size; i++) {
if (row_sum[i] != magicNumber || col_sum[i] != magicNumber) {
return false; // no solution, backtrack
}
}
solutions++;
System.out.println("Solution: "+solutions);
printSquare();
return false; // serach for next solution
}
// the 1d square is mapped to 2d square
HashSet<Integer> validNumbers = new HashSet<Integer>(); // all valid Numbers from one position
if(x%size == size-1 && magicNumber-row_sum[(x/size)] <= squareSize &&
usedNumbers[magicNumber-row_sum[x/size]] == false) {
validNumbers.add(magicNumber-row_sum[(x/size)]); // All values in a row, except for the last one were set
}
if(x/size == size-1 && magicNumber-col_sum[(x%size)] <= squareSize && //
usedNumbers[magicNumber-col_sum[x%size]] == false) {
validNumbers.add(magicNumber-col_sum[x%size]); // // All values in a col, except for the last one were set
}
if(x%size != size-1 && x/size != size-1) { // for all other positions
for(int i=1; i<usedNumbers.length; i++) {
if (usedNumbers[i]== false) validNumbers.add(i);
}
}
if(validNumbers.size()==0) {
return false; // no valid numbers, backtrack
}
for (int v : validNumbers) {
row_sum[x/size] += v;
col_sum[x%size] += v;
if (row_sum[x/size] <= magicNumber && col_sum[x%size] <= magicNumber) {
square[x] = v;
usedNumbers[v] = true;
if (solve(x + 1) == true) {
return true;
}
usedNumbers[v] = false;
square[x] = 0;
}
row_sum[x/size] -= v;
col_sum[x%size] -= v;
}
return false;
}
private boolean checkDiagonals() {
int diagonal1 = 0;
int diagonal2 = 0;
for(int i=0; i<squareSize; i=i+size+1) {
diagonal1 = diagonal1 + square[i];
}
for(int i=size-1; i<squareSize-size+1; i = i+size-1) {
diagonal2 = diagonal2 + square[i];
}
return diagonal1==magicNumber && diagonal2==magicNumber;
}
private void printSquare() {
for (int i = 0; i < squareSize; i++) {
if(i%size ==0) {
System.out.println();
}
System.out.print(square[i] + " ");
}
System.out.println();
}
public static void main(String args) {
try {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
MagicSquare m = new MagicSquare(size);
sc.close();
long start = System.currentTimeMillis();
m.solve(0);
long duration = System.currentTimeMillis() - start;
System.out.println("Runtime in ms : " + duration+" = "+duration/1000 + "sec");
System.out.println("There are "+m.solutions+" solutions with mirroring");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
java performance recursion backtracking
add a comment |
Here is my improved version of my Magic square program from this topic:
Speed up Magic square program.
I also added a few comments.
Any help for improvments would be really appreciated.
import java.util.HashSet;
import java.util.Scanner;
public class MagicSquare {
private int square;
private int row_sum;
private int col_sum;
private int magicNumber;
private int size;
private boolean usedNumbers;
private int solutions=0;
private int squareSize;
public MagicSquare(int size) {
this.size = size;
this.usedNumbers = new boolean[size * size + 1];
this.square = new int[size * size];
this.row_sum = new int[size];
this.col_sum = new int[size];
this.magicNumber = ((size * size * size + size) / 2);
this.squareSize = size * size;
}
private boolean solve(int x) {
if (x == squareSize && checkDiagonals()) {
for (int i = 0; i < size; i++) {
if (row_sum[i] != magicNumber || col_sum[i] != magicNumber) {
return false; // no solution, backtrack
}
}
solutions++;
System.out.println("Solution: "+solutions);
printSquare();
return false; // serach for next solution
}
// the 1d square is mapped to 2d square
HashSet<Integer> validNumbers = new HashSet<Integer>(); // all valid Numbers from one position
if(x%size == size-1 && magicNumber-row_sum[(x/size)] <= squareSize &&
usedNumbers[magicNumber-row_sum[x/size]] == false) {
validNumbers.add(magicNumber-row_sum[(x/size)]); // All values in a row, except for the last one were set
}
if(x/size == size-1 && magicNumber-col_sum[(x%size)] <= squareSize && //
usedNumbers[magicNumber-col_sum[x%size]] == false) {
validNumbers.add(magicNumber-col_sum[x%size]); // // All values in a col, except for the last one were set
}
if(x%size != size-1 && x/size != size-1) { // for all other positions
for(int i=1; i<usedNumbers.length; i++) {
if (usedNumbers[i]== false) validNumbers.add(i);
}
}
if(validNumbers.size()==0) {
return false; // no valid numbers, backtrack
}
for (int v : validNumbers) {
row_sum[x/size] += v;
col_sum[x%size] += v;
if (row_sum[x/size] <= magicNumber && col_sum[x%size] <= magicNumber) {
square[x] = v;
usedNumbers[v] = true;
if (solve(x + 1) == true) {
return true;
}
usedNumbers[v] = false;
square[x] = 0;
}
row_sum[x/size] -= v;
col_sum[x%size] -= v;
}
return false;
}
private boolean checkDiagonals() {
int diagonal1 = 0;
int diagonal2 = 0;
for(int i=0; i<squareSize; i=i+size+1) {
diagonal1 = diagonal1 + square[i];
}
for(int i=size-1; i<squareSize-size+1; i = i+size-1) {
diagonal2 = diagonal2 + square[i];
}
return diagonal1==magicNumber && diagonal2==magicNumber;
}
private void printSquare() {
for (int i = 0; i < squareSize; i++) {
if(i%size ==0) {
System.out.println();
}
System.out.print(square[i] + " ");
}
System.out.println();
}
public static void main(String args) {
try {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
MagicSquare m = new MagicSquare(size);
sc.close();
long start = System.currentTimeMillis();
m.solve(0);
long duration = System.currentTimeMillis() - start;
System.out.println("Runtime in ms : " + duration+" = "+duration/1000 + "sec");
System.out.println("There are "+m.solutions+" solutions with mirroring");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
java performance recursion backtracking
add a comment |
Here is my improved version of my Magic square program from this topic:
Speed up Magic square program.
I also added a few comments.
Any help for improvments would be really appreciated.
import java.util.HashSet;
import java.util.Scanner;
public class MagicSquare {
private int square;
private int row_sum;
private int col_sum;
private int magicNumber;
private int size;
private boolean usedNumbers;
private int solutions=0;
private int squareSize;
public MagicSquare(int size) {
this.size = size;
this.usedNumbers = new boolean[size * size + 1];
this.square = new int[size * size];
this.row_sum = new int[size];
this.col_sum = new int[size];
this.magicNumber = ((size * size * size + size) / 2);
this.squareSize = size * size;
}
private boolean solve(int x) {
if (x == squareSize && checkDiagonals()) {
for (int i = 0; i < size; i++) {
if (row_sum[i] != magicNumber || col_sum[i] != magicNumber) {
return false; // no solution, backtrack
}
}
solutions++;
System.out.println("Solution: "+solutions);
printSquare();
return false; // serach for next solution
}
// the 1d square is mapped to 2d square
HashSet<Integer> validNumbers = new HashSet<Integer>(); // all valid Numbers from one position
if(x%size == size-1 && magicNumber-row_sum[(x/size)] <= squareSize &&
usedNumbers[magicNumber-row_sum[x/size]] == false) {
validNumbers.add(magicNumber-row_sum[(x/size)]); // All values in a row, except for the last one were set
}
if(x/size == size-1 && magicNumber-col_sum[(x%size)] <= squareSize && //
usedNumbers[magicNumber-col_sum[x%size]] == false) {
validNumbers.add(magicNumber-col_sum[x%size]); // // All values in a col, except for the last one were set
}
if(x%size != size-1 && x/size != size-1) { // for all other positions
for(int i=1; i<usedNumbers.length; i++) {
if (usedNumbers[i]== false) validNumbers.add(i);
}
}
if(validNumbers.size()==0) {
return false; // no valid numbers, backtrack
}
for (int v : validNumbers) {
row_sum[x/size] += v;
col_sum[x%size] += v;
if (row_sum[x/size] <= magicNumber && col_sum[x%size] <= magicNumber) {
square[x] = v;
usedNumbers[v] = true;
if (solve(x + 1) == true) {
return true;
}
usedNumbers[v] = false;
square[x] = 0;
}
row_sum[x/size] -= v;
col_sum[x%size] -= v;
}
return false;
}
private boolean checkDiagonals() {
int diagonal1 = 0;
int diagonal2 = 0;
for(int i=0; i<squareSize; i=i+size+1) {
diagonal1 = diagonal1 + square[i];
}
for(int i=size-1; i<squareSize-size+1; i = i+size-1) {
diagonal2 = diagonal2 + square[i];
}
return diagonal1==magicNumber && diagonal2==magicNumber;
}
private void printSquare() {
for (int i = 0; i < squareSize; i++) {
if(i%size ==0) {
System.out.println();
}
System.out.print(square[i] + " ");
}
System.out.println();
}
public static void main(String args) {
try {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
MagicSquare m = new MagicSquare(size);
sc.close();
long start = System.currentTimeMillis();
m.solve(0);
long duration = System.currentTimeMillis() - start;
System.out.println("Runtime in ms : " + duration+" = "+duration/1000 + "sec");
System.out.println("There are "+m.solutions+" solutions with mirroring");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
java performance recursion backtracking
Here is my improved version of my Magic square program from this topic:
Speed up Magic square program.
I also added a few comments.
Any help for improvments would be really appreciated.
import java.util.HashSet;
import java.util.Scanner;
public class MagicSquare {
private int square;
private int row_sum;
private int col_sum;
private int magicNumber;
private int size;
private boolean usedNumbers;
private int solutions=0;
private int squareSize;
public MagicSquare(int size) {
this.size = size;
this.usedNumbers = new boolean[size * size + 1];
this.square = new int[size * size];
this.row_sum = new int[size];
this.col_sum = new int[size];
this.magicNumber = ((size * size * size + size) / 2);
this.squareSize = size * size;
}
private boolean solve(int x) {
if (x == squareSize && checkDiagonals()) {
for (int i = 0; i < size; i++) {
if (row_sum[i] != magicNumber || col_sum[i] != magicNumber) {
return false; // no solution, backtrack
}
}
solutions++;
System.out.println("Solution: "+solutions);
printSquare();
return false; // serach for next solution
}
// the 1d square is mapped to 2d square
HashSet<Integer> validNumbers = new HashSet<Integer>(); // all valid Numbers from one position
if(x%size == size-1 && magicNumber-row_sum[(x/size)] <= squareSize &&
usedNumbers[magicNumber-row_sum[x/size]] == false) {
validNumbers.add(magicNumber-row_sum[(x/size)]); // All values in a row, except for the last one were set
}
if(x/size == size-1 && magicNumber-col_sum[(x%size)] <= squareSize && //
usedNumbers[magicNumber-col_sum[x%size]] == false) {
validNumbers.add(magicNumber-col_sum[x%size]); // // All values in a col, except for the last one were set
}
if(x%size != size-1 && x/size != size-1) { // for all other positions
for(int i=1; i<usedNumbers.length; i++) {
if (usedNumbers[i]== false) validNumbers.add(i);
}
}
if(validNumbers.size()==0) {
return false; // no valid numbers, backtrack
}
for (int v : validNumbers) {
row_sum[x/size] += v;
col_sum[x%size] += v;
if (row_sum[x/size] <= magicNumber && col_sum[x%size] <= magicNumber) {
square[x] = v;
usedNumbers[v] = true;
if (solve(x + 1) == true) {
return true;
}
usedNumbers[v] = false;
square[x] = 0;
}
row_sum[x/size] -= v;
col_sum[x%size] -= v;
}
return false;
}
private boolean checkDiagonals() {
int diagonal1 = 0;
int diagonal2 = 0;
for(int i=0; i<squareSize; i=i+size+1) {
diagonal1 = diagonal1 + square[i];
}
for(int i=size-1; i<squareSize-size+1; i = i+size-1) {
diagonal2 = diagonal2 + square[i];
}
return diagonal1==magicNumber && diagonal2==magicNumber;
}
private void printSquare() {
for (int i = 0; i < squareSize; i++) {
if(i%size ==0) {
System.out.println();
}
System.out.print(square[i] + " ");
}
System.out.println();
}
public static void main(String args) {
try {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
MagicSquare m = new MagicSquare(size);
sc.close();
long start = System.currentTimeMillis();
m.solve(0);
long duration = System.currentTimeMillis() - start;
System.out.println("Runtime in ms : " + duration+" = "+duration/1000 + "sec");
System.out.println("There are "+m.solutions+" solutions with mirroring");
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
java performance recursion backtracking
java performance recursion backtracking
edited 1 hour ago
Sᴀᴍ Onᴇᴌᴀ
8,34261853
8,34261853
asked 1 hour ago
Marten
1386
1386
add a comment |
add a comment |
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210648%2fjava-magic-square-program%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
active
oldest
votes
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f210648%2fjava-magic-square-program%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown