• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 16:59
CEST 22:59
KST 05:59
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
[ASL22] Ro16 Preview: Rough Waters9[ASL22] Ro24 Preview: Siren's Call8[ASL22] Ro24 Preview: Summer's End9Serral wins HomeStory Cup 2915Serral wins Maestros of the Game 244
Community News
Weekly Cups (Aug 30-Sep 7): herO thrives amid growing schism6Official StarCraft website teases new content ahead of BlizzCon?119Stellar Fest TWO the Moon (Dec 16-20)9Weekly Cups (August 24-30): Patches' balance mod takes over3New 3v3 BGH Ladder (and more) on ShieldBattery!46
StarCraft 2
General
Weekly Cups (Aug 30-Sep 7): herO thrives amid growing schism SC4ALL: II Winner Will Earn a Spot at HSC 30! SC4ALL II: StarCraft 2 Player Announcement 7/8 Nexon wins bid to develop StarCraft IP content, distribute Overwatch mobile game Balance hotfix patch 5.0.16b (July 16)
Tourneys
Sparkling Tuna Cup - Weekly Open Tournament Sea Duckling Open (Global, Bronze-Diamond) 2026 GSTL Announcement Stellar Fest TWO the Moon (Dec 16-20) IntoTheTV X SOOP SC2 League : Weekly & Monthly
Strategy
[G] Having the right mentality to improve
Custom Maps
Nexus Wars 2021 GUIDE [M] (2) Industrial Park
External Content
Mutation # 542 The Ascended Mutation # 541 Binary Choice The PondCast: SC2 News & Results Mutation # 540 Dodge This
Brood War
General
Official StarCraft website teases new content ahead of BlizzCon? [ASL22] Ro16 Preview: Rough Waters ASL22 General Discussion Pros React To: Calm's Big Brain Play Vs Mini New 3v3 BGH Ladder (and more) on ShieldBattery!
Tourneys
[Megathread] Daily Proleagues [ASL22] Ro16 Group A BWCL Season 65 Announcement [ASL22] Ro16 Group B
Strategy
Replay Review Process - What do you do? Simple Questions, Simple Answers Odyssey Mineral Stack Saturation Game Theory for Starcraft
Other Games
General Games
Nintendo Switch Thread EVE Corporation Diablo IV [Maplestory Hardcore] Let's Play~!! General RTS Discussion Thread
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
[TL LoL EUW IHs] Teemo shall perish TSM pausing esports and CLG Dead
Heroes of the Storm
Heroes of the Storm 2.0
Hearthstone
Deck construction bug
TL Mafia
TL Mafia Power Rank TL Mafia Community Thread NeO.D_StephenKing vs This Guy From 1 Million Dance
Community
General
US Politics Mega-thread Russo-Ukrainian War Thread European Politico-economics QA Mega-thread Trading/Investing Thread Things Aren’t Peaceful in Palestine
Fan Clubs
MarineLorD Fan Club The Creator Fan Club The ShoWTimE Fan Club
Media & Entertainment
Movie Discussion! Anime Discussion Thread
Sports
Football (Soccer) Thread TeamLiquid Health and Fitness Initiative For 2023 MLB/Baseball 2023
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List Northern Ireland Global Starcraft
Blogs
F* the Children and Get Off …
TrAiDoS
Dreaming of BW patches (mod…
c3rberUs
Regacy Esports: The Bh…
regacyesports
LOCKPICKING NOOB
LUCKY_NOOB
Customize Sidebar...

Website Feedback

Closed Threads



Active: 5614 users

The Big Programming Thread - Page 814

Forum Index > General Forum
Post a Reply
Prev 1 812 813 814 815 816 1032 Next
Thread Rules
1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution.
2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20)
3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible.
4. Use [code] tags to format code blocks.
mantequilla
Profile Blog Joined June 2012
Turkey781 Posts
December 11 2016 21:51 GMT
#16261
maybe the class submit test itself is buggy
Age of Mythology forever!
Nesserev
Profile Blog Joined January 2011
Belgium2760 Posts
Last Edited: 2016-12-11 21:56:03
December 11 2016 21:55 GMT
#16262
--- Nuked ---
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
Last Edited: 2016-12-11 22:41:30
December 11 2016 21:58 GMT
#16263
On December 12 2016 06:55 Nesserev wrote:
Show nested quote +
On December 12 2016 06:28 travis wrote:
edit:

figured it out

rubber ducky debugging is the truth

I was lucky enough to read your original post (no reason to remove it :/).
Are you dynamically resizing your array based on the amount of contained elements?


I do that during adds to increase the table size if necessary

but not during the removes, we have no specification to decrease the table size

the actual issue was much stupider

instead of finding the bucket that I will be removing a node from with it's hashcode, I was iterating through my entire hashset, so it must have been timing out during test


I am actually still failing and I am not sure why now but I expect I will get to the bottom of it. probably some legit bug in my code


edit:

well now I am actually more confused because it passes all my tests again but I still failed


On December 12 2016 06:51 mantequilla wrote:
maybe the class submit test itself is buggy


probably not the case or other students would have complained

though I do feel like our last project's tests were really poorly made


edit: maybe the test is passing (null) as an element?
if that's the case, I am not even sure what I would be supposed to do within the context of the project (empty indexes are null, and the end of our linked lists point to null)
im just having it not remove anything if it asks for me to remove null
Yurie
Profile Blog Joined August 2010
12160 Posts
Last Edited: 2016-12-12 01:47:42
December 12 2016 01:41 GMT
#16264
Got stuck with another java question. I am making a graphical sudoku solver as homework and have managed to make a logic based on a 9x9 array that solves it if valid. I then start making the grid and UI for it in javafx and manage two different solutions to this, then I get utterly stuck since I don't know how get the input from the user in both cases to then send it to the right row, col combination in the array.

Solution 1 for the UI using a gridpane with textfields:
GridPane board = new GridPane();
for (int column = 0; column < 9; column++) {
for (int row = 0; row < 9; row++) {
TextField textField = new TextField("0");
textField.setStyle("-fx-pref-width: 2em;");

GridPane.setConstraints(textField, column, row);
board.getChildren().add(textField);
}
}

[image loading]

Solution 2 using buttons where I imagine a pop up using oneInputDialog for feeding in the value or some way adding clickable buttons for 1-9 so I don't have to deal with inputs that are not valid.
    for (int r = 0; r < 9; r++) {
for (int c = 0; c < 9; c++) {
Button button = new Button(String.valueOf(0));
grid.add(button, c, r);
}
}

[image loading]

I know how to get it from a single named field as I did that in the phone catalogue but can't transition it into these grids. Worst case I guess I can create 81 named fields/buttons in the code and then somehow read them one by one (hundreds of lines of codes when I imagine it should be 3 or so).

Could any kind soul suggest a way of getting the user input here so I can check if it is valid and then put it into my solver?
Nesserev
Profile Blog Joined January 2011
Belgium2760 Posts
Last Edited: 2016-12-12 02:26:23
December 12 2016 02:25 GMT
#16265
--- Nuked ---
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
December 12 2016 02:28 GMT
#16266
I am not sure I understand your question.

I think you need to use a data structure

Make a 2 dimensional array that matches your grind

then do 2 for loops to go through the columns and rows of your grid
and put each button into the array

then went you want to read them loop through your 2d array in whatever ways you need to read the values


am i understanding your question correctly?
Yurie
Profile Blog Joined August 2010
12160 Posts
Last Edited: 2016-12-12 03:41:29
December 12 2016 03:40 GMT
#16267
From reading your two answers I seem to know too little to ask the right questions. I've answered as well as I can below but to reiterate the problem. I have a class that solves sudoku problems where I can put(row, column, value) to fill in the starting positions and then start it. I need a GUI to get those values from the user and input them into that solver. After that I need to output the solution back to the GUI. I can create the GUI using the two forms I showed but I don't know how to store them to get the values or input from the solution back to the GUI.

On December 12 2016 11:25 Nesserev wrote:
Show nested quote +
On December 12 2016 10:41 Yurie wrote:
Could any kind soul suggest a way of getting the user input here so I can check if it is valid and then put it into my solver?

I don't think there's a way to retrieve the buttons from the GridPane, so you'll have to also keep references to the added buttons in a separate data structure (probably map coordinates to button at said coordinates), so that you can retrieve their contents.

I would also extend the Button class you're using, and overwrite some methods so that:
- validate content value when user has changed it
- set default value to 0 automatically


How to create those references seems to be my problem then. I don't understand how to do it. I only know how to create the cells. Should I do something like creating a flatter int with size [81] and adding them to it and then getting their values? Is it possible to get some short example?

Once I get the basic functionality working I'll look at making it prettier with a proper class. Unless it is needed then I'll fix it.

On December 12 2016 11:28 travis wrote:
I am not sure I understand your question.

I think you need to use a data structure

Make a 2 dimensional array that matches your grind

then do 2 for loops to go through the columns and rows of your grid
and put each button into the array

then went you want to read them loop through your 2d array in whatever ways you need to read the values


am i understanding your question correctly?


First I should make an array, something in the form of int[][]?

Then I should do as I have done in the attached code to create the grids with the loops?

Not sure how that is connected to the button in the next step you mention. This or the step before is where I seem to be lacking understanding and thus not making progress.

Then to get the values I just do the normal int x = board[row][col] and loop through all row, col combinations putting them into the proper solving array?
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
Last Edited: 2016-12-12 03:54:47
December 12 2016 03:51 GMT
#16268
I am not familiar with javax but what I would do is create an array of type: whatever the button objects are. Let's call them button

so do button[][] myGrid = new button[columns][rows];

then loop through your columns and rows

for(i from 0 to columns-1) {
for(j from 0 to rows-1) {
myGrid[i][j] = new Button(); //however you instantiate a new button you want
}}


the key is that you can have a data structure of objects, not just say ints or strings or whatever. you can literally make an array of buttons or an array of cats or an array of arrays
so you can fill that data structure with your objects, and then instead of having to refer to a thousand different names for your objects, you refer to that position in your data structure to call up the appropriate object



You aren't limited to using an array, either. You can use any data structure, like say a map which nesserev suggested.

I just thought a 2dimensional array would make conceptual sense here, since the array positions can correspond to a grid nicely



so anyways. whatever the object it is that is in your grid that stores your data, that's what you want to store in your data structure. That way you don't have to have 81 uniquely named objects, you have 81 positions in a data structure instead.
Yurie
Profile Blog Joined August 2010
12160 Posts
Last Edited: 2016-12-12 07:49:53
December 12 2016 07:44 GMT
#16269
Thanks for the help. With that guidance I messed around a bit with iterating through all nodes and the solvers array. It worked out fine combined with an addListener that updated values when the user did something. In the end I didn't need to create an array to keep track of the nodes since the one in the grid was enough, if cumbersome to use. Might have been a bit shorter in code but I never got how to use that to refer to the nodes.

Only thing remaining on it are cosmetics such as making different backgrounds for the 3x3 areas using tilepanes. I'll see if I have time for it before the deadline on Wednesday or not. Well that and the required comments on everything.
Shield
Profile Blog Joined August 2009
Bulgaria4824 Posts
Last Edited: 2016-12-12 19:07:43
December 12 2016 19:00 GMT
#16270
User input can be via buttons like in this game: http://www.sudokukingdom.com/
This is similar to how I did it for my university project anyway. There is almost no input check in this case. Well, other than if integer could be placed there based on sudoku's rules.

As far as program goes, you'd ideally want something like MVC (or similar) architecture, but I don't know if it's too much for your homework. Your model could have a 2D array as suggested earlier. E.g. int[][] grid = new int[9][9]. Then, you model and view match nicely as travis said.\

Edit: I think what I also ended up doing back then was extending a UI component that represents cells. I gave it row and column fields. After that, as travis said, row and column match your 2D array exactly.
Yurie
Profile Blog Joined August 2010
12160 Posts
Last Edited: 2016-12-12 19:57:45
December 12 2016 19:53 GMT
#16271
On December 13 2016 04:00 Shield wrote:
User input can be via buttons like in this game: http://www.sudokukingdom.com/
This is similar to how I did it for my university project anyway. There is almost no input check in this case. Well, other than if integer could be placed there based on sudoku's rules.

As far as program goes, you'd ideally want something like MVC (or similar) architecture, but I don't know if it's too much for your homework. Your model could have a 2D array as suggested earlier. E.g. int[][] grid = new int[9][9]. Then, you model and view match nicely as travis said.\

Edit: I think what I also ended up doing back then was extending a UI component that represents cells. I gave it row and column fields. After that, as travis said, row and column match your 2D array exactly.


If I ever need to solve it again or want to learn a bit more this is how it would be better to solve. It sounds much better than the solution I did, included in the spoiler below (with non English comments removed and the class for the not possible sudoku alert not included since it was in a different file not relevant here). I am skipping doing 3x3 coloured grid backgrounds since it isn't required as I understand it and I didn't get it after 30 min or so of googling how to use tilepanes and gridpanes together in layers.

+ Show Spoiler +


package GUI;

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;
import org.apache.commons.lang3.math.NumberUtils;
import Sudoku.Solver;

public class Sudoku extends Application {
public static void main(String[] args) {
launch(args);
}

private Solver solver;
private GridPane board;

/*
* start creates a windows with a title, label in top area,
* Sudoku grid with 0 values in center and buttons to the right.
* It also creates a listener to catch when the user updates a value.
*/
@Override
public void start(Stage primaryStage) throws Exception {
solver = new Solver();
board = new GridPane();

for (int column = 0; column < 9; column++) {
for (int row = 0; row < 9; row++) {

int col = column;
int r = row;

TextField textField = new TextField("0");

textField.setStyle("-fx-pref-width: 2em;");

GridPane.setConstraints(textField, column, row);
board.getChildren().add(textField);

textField.textProperty().addListener((observable, oldValue, newValue) -> {
// returns defaultValue if the string cannot be parsed.
int newValueInt = NumberUtils.toInt(newValue, 0);
if (!(newValueInt > 0 && newValueInt < 10)) {
textField.setText("0");
}
solver.put(r, col, newValueInt);
});
}
}

BorderPane root = new BorderPane();

HBox introText = new HBox();
// create top box for intro text
root.setTop(introText);
root.setCenter(board);
// create right area for box Vbox = vertical boxes
VBox buttonBox = new VBox();
root.setRight(buttonBox);


Label topText = new Label("Welcome to a Sudoko solving program. \n"
+ "Enter numbers between 1 and 9 in the text fields. \n"
+ "If you enter an incorrect input such as 'a' it will be changed to 0.\n");

introText.getChildren().addAll(topText);

// Buttons
Button solveButton = new Button("Solve");
solveButton.setOnAction(e -> solve());

Button clearButton = new Button("Clear");
clearButton.setOnAction(e -> clear());

Button testCase5 = new Button("Test Case 5");
testCase5.setOnAction(e -> testcase5());

Button testCase3 = new Button("Test Case 3");
testCase3.setOnAction(e -> testcase3());

solveButton.setMaxWidth(Double.MAX_VALUE);
clearButton.setMaxWidth(Double.MAX_VALUE);
testCase5.setMaxWidth(Double.MAX_VALUE);
testCase3.setMaxWidth(Double.MAX_VALUE);
buttonBox.getChildren().addAll(solveButton, clearButton, testCase3, testCase5);

//Stylesheets
introText.setStyle("-fx-font-size: 20;");
introText.setPadding(new Insets(10, 10, 10, 10));

buttonBox.setSpacing(5);
buttonBox.setPadding(new Insets(10, 10, 10, 10));
buttonBox.setStyle("-fx-font-size: 20;");

board.setPadding(new Insets(10, 10, 10, 10));
board.setStyle("-fx-font-size: 20;");

primaryStage.setTitle("Sudoku Solver");
primaryStage.setScene(new Scene(root));
primaryStage.show();
}

/*
* solve sends a request to Solver to solve the board.
* It then updates the GUI board with the content.
*/
private void solve() {
// Reset counter for if solver is done or not
Solver.resetSquaresFilled();

// Does solver return true, then solved
Boolean solved = Solver.solve();

if(!solved){
Dialogs.alert("Sudoko Solver Failure", "Sudoko not solved",
"Your sudoko was not possible to solve, please verify that you don't have duplicate numbers or other common errors.");
}
updateFromSolver();

}

/*
* updateFromSolver gets the content from the Solver board and updates the GUI.
*/
private void updateFromSolver() {
for (int column = 0; column < 9; column++) {
for (int row = 0; row < 9; row++) {
String value = Integer.toString(solver.get(row, column));
Node node = getNodeByRowColumnIndex(row, column, board);
((TextField) node).setText(value);
}
}
}

/*
* getNodeByRowColumnIndex gets the node from the GUI board.
* This is used to get or update the content of a textfield in the grid.
*
* @param int row, int column and GridPane name to check.
* @return node that matches the parameters.
*/
public Node getNodeByRowColumnIndex(final int row, final int column, GridPane gridPane) {
Node result = null;
ObservableList<Node> childrens = gridPane.getChildren();

for (Node node : childrens) {
if (GridPane.getRowIndex(node) == row && GridPane.getColumnIndex(node) == column) {
result = node;
break;
}
}

return result;
}

/*
* clear sets the GUI board and the solver board to all 0 values.
*/
private void clear() {
// Clear Solver board
for (int column = 0; column < 9; column++) {
for (int row = 0; row < 9; row++) {
solver.put(row, column, 0);
}
}
// Clear visual board
for (Node node : board.getChildren()) {
if (node instanceof TextField) {
((TextField) node).setText("0");
}
}
}

/*
* testcase3 inputs a few values to solver board and then updates it to the GUI board.
* Used to test a case that isn't possible to solve.
*/
public void testcase3() {
clear();
solver.put(0, 0, 1);
solver.put(0, 1, 2);
solver.put(0, 2, 3);
solver.put(1, 0, 4);
solver.put(1, 1, 5);
solver.put(1, 2, 6);
solver.put(2, 3, 7);
updateFromSolver();
}

/*
* testcase5 inputs a few values to solver board and then updates it to the GUI board.
* Used to test a case that is possible to solve.
*/
public void testcase5() {
clear();
solver.put(0, 2, 8);
solver.put(0, 5, 9);
solver.put(0, 7, 6);
solver.put(0, 8, 2);
solver.put(1, 8, 5);
solver.put(2, 0, 1);
solver.put(2, 2, 2);
solver.put(2, 3, 5);
solver.put(3, 3, 2);
solver.put(3, 4, 1);
solver.put(3, 7, 9);
solver.put(4, 1, 5);
solver.put(4, 6, 6);
solver.put(5, 0, 6);
solver.put(5, 7, 2);
solver.put(5, 8, 8);
solver.put(6, 0, 4);
solver.put(6, 1, 1);
solver.put(6, 3, 6);
solver.put(6, 5, 8);
solver.put(7, 0, 8);
solver.put(7, 1, 6);
solver.put(7, 4, 3);
solver.put(7, 6, 1);
solver.put(8, 6, 4);
updateFromSolver();
}
}



package Sudoku;

public class Solver {
// Board with cell content
private static int[][] board;
// Number of squaresfilled, counts to know when done
static int numSquaresFilled;

/*
* Solver creates a board.
*
* @return creates a Sudoku board
*/
public Solver() {
board = new int[9][9];
}

/*
* solve solves the board that has been put in previously.
*
* @return true if the board is solved
*/
public static boolean solve() {
// If all squares filled return true
if (81 == numSquaresFilled) {
return true;
}

boolean findCell = true;
// booleanCondition ? executeThisPartIfBooleanConditionIsTrue :
// executeThisPartIfBooleanConditionIsFalse
RowColoumn rc = findCell ? getConstrained() : findFirstOpenCell();
// get row and cell from rc
int r = rc.row;
int c = rc.col;
for (int i = 1; i <= 9; i++) {
numSquaresFilled++;
// fill cell with i value
board[r][c] = i;
// if board is legal start the search for next cell
if (isBoardLegal(r, c)) {
if (solve()) {
return true;
}
}
// else set cell to 0 and remove the squares filled to previous
// value.
board[r][c] = 0;
numSquaresFilled--;
}
// return false if not possible
return false;
}

/*
* RowColoumn creates a simple row and column state that can be used
*/
static class RowColoumn {
int row;
int col;

RowColoumn(int r, int c) {
row = r;
col = c;
}
}

/*
* put adds a value to a cell.
*
* @param int row, int column, int value
*
* @return true if the cell value is added to board
*/
public boolean put(int row, int col, int value) {
board[row][col] = value;
if (board[row][col] == value) {
return true;
}
return false;
}

/*
* get Returns a value of a cell.
*
* @param int row, int column
* @return value of cell
*/
public int get(int row, int col) {
int returnValue = board[row][col];
return returnValue;
}

/*
* isLegal tests if the entire board is valid. It does this by testing if
* there is a duplicate number in the row, column or 3x3 square. It is not a
* test to see if it is possible to solve.
*
* @return true if the board follows sudoku rules
*/
public static boolean isLegal() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (!isBoardLegal(i, j)) {
return false;
}
}
}
return true;
}

/*
* isBoardLegal tests if the cell on the board is valid. It does this by
* testing if there is a duplicate number in the row, column or 3x3 square.
*
* @param int row and int column to check.
* @return true if the cell follows sudoku rules
*/
static boolean isBoardLegal(int row, int col) {
return (isRowLegal(row) && isColLegal(col) && isSquareLegal(row, col));
}

/*
* isRowLegal tests if the cell in the row is valid. It does this by testing
* if there is a duplicate number in the row.
*
* @param int row to check.
* @return true if the row follows sudoku rules
*/
static boolean isRowLegal(int row) {
int[] count = new int[9];
for (int col = 0; col < 9; col++) {
int n = board[row][col] - 1;
if (n == -1)
continue;
count[n]++;
if (count[n] > 1)
return false;
}
return true;
}

/*
* isRowLegal tests if the cell in the column is valid. It does this by
* testing if there is a duplicate number in the row.
*
* @param int col to check.
* @return true if the column follows sudoku rules
*/
static boolean isColLegal(int col) {
int[] count = new int[9];
for (int row = 0; row < 9; row++) {
int n = board[row][col] - 1;
if (n == -1)
continue;
count[n]++;
if (count[n] > 1)
return false;
}
return true;
}

/*
* isRowLegal tests if the cell in the square is valid. It does this by
* testing if there is a duplicate number in the square.
*
* @param int row and int column to check.
* @return true if the square follows sudoku rules
*/
static boolean isSquareLegal(int row, int col) {
int r = (row / 3) * 3;
int c = (col / 3) * 3;
int[] count = new int[9];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int n = board[r + i][c + j] - 1;
if (n == -1)
continue;
count[n]++;
if (count[n] > 1)
return false;
}
}
return true;
}

/*
* findFirstOpenCell looks for the first empty cell and returns it.
*
* @return RowColoumn that can be called internally.
*/
static RowColoumn findFirstOpenCell() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == 0) {
return new RowColoumn(i, j);
}
}
}
return new RowColoumn(0, 0);
}
/*
* findFirstOpenCell looks for the cell with most variables to fill in with.
* So a cell with more data is used before one with no conditions.
*
* @return RowColoumn that can be called internally.
*/
static RowColoumn getConstrained() {

int r = 0, c = 0, max = 0;

int[] rowCounts = new int[9];
int[] colCounts = new int[9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != 0)
rowCounts[i]++;
if (board[j][i] != 0)
colCounts[i]++;
}
}

int[][] squareCounts = new int[3][3];

for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int count = 0;
for (int m = 0; m < 3; m++) {
for (int n = 0; n < 3; n++) {

if (board[(i * 3) + m][(j * 3) + n] != 0)
count++;
}
}
squareCounts[i][j] = count;
}
}

for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == 0) {
if (rowCounts[i] > max) {
max = rowCounts[i];
r = i;
c = j;
}
if (colCounts[j] > max) {
max = rowCounts[j];
r = i;
c = j;
}
}
}
}
return new RowColoumn(r, c);
}

/*
* printBoard prints the current board state to console.
* Used for testing to see if the situation matches the expected.
*/
public static void printBoard() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(" " + (board[i][j] == 0 ? " " : board[i][j]) + " ");
if (j % 3 == 2 && j < 8)
System.out.print("|");
}
System.out.println();
if (i % 3 == 2 && i < 8)
System.out.println("---------|---------|---------");
}
System.out.println();
}

/*
* resetSquaresFilled resets the numSquaresFilled to 0 for repeated usage of board.
*/
public static void resetSquaresFilled() {
numSquaresFilled = 0;
}

}




...
public class Dialogs {
public static void alert(String title, String headerText, String infoText) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle(title);
alert.setHeaderText(headerText);
alert.setContentText(infoText);
alert.showAndWait();
}
...
}

Manit0u
Profile Blog Joined August 2004
Poland17843 Posts
Last Edited: 2016-12-12 23:42:53
December 12 2016 23:32 GMT
#16272
Geez. You should really break this code into smaller parts...


// We can throw that away since it's not being utilized...
//for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// squareCounts[i][j] = getCount(i, j);
// }
//}

for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != 0) {
rowCounts[i]++;
}

if (board[j][i] != 0) {
colCounts[i]++;
}
}
}

for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == 0) {
if (rowCounts[i] > max) {
max = rowCounts[i];
r = i;
c = j;
}

if (colCounts[j] > max) {
max = rowCounts[j];
r = i;
c = j;
}
}
}
}

// no more need for that
public static int getCount(int i, int j) {
int count = 0;

for (int m = 0; m < 3; m++) {
for (int n = 0; n < 3; n++) {
if (board[(i * 3) + m][(j * 3) + n] != 0) {
count++;
}
}
}

return count;
}


Plenty less loops and a bit more readability (still, doing the same loop twice seems highly inefficient).
I believe it could be optimized further but it's late and I hate Java
Time is precious. Waste it wisely.
Yurie
Profile Blog Joined August 2010
12160 Posts
Last Edited: 2016-12-13 05:07:40
December 13 2016 05:06 GMT
#16273
On December 13 2016 08:32 Manit0u wrote:
Geez. You should really break this code into smaller parts...
+ Show Spoiler +


// We can throw that away since it's not being utilized...
//for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// squareCounts[i][j] = getCount(i, j);
// }
//}

for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != 0) {
rowCounts[i]++;
}

if (board[j][i] != 0) {
colCounts[i]++;
}
}
}

for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == 0) {
if (rowCounts[i] > max) {
max = rowCounts[i];
r = i;
c = j;
}

if (colCounts[j] > max) {
max = rowCounts[j];
r = i;
c = j;
}
}
}
}

// no more need for that
public static int getCount(int i, int j) {
int count = 0;

for (int m = 0; m < 3; m++) {
for (int n = 0; n < 3; n++) {
if (board[(i * 3) + m][(j * 3) + n] != 0) {
count++;
}
}
}

return count;
}


Plenty less loops and a bit more readability (still, doing the same loop twice seems highly inefficient).
I believe it could be optimized further but it's late and I hate Java


You are right that squarecount isn't being used. Would probably speed it up if I managed to figure out a good way to use it but commented it out now instead. Improved speed of my testcase5 by 2-3 miliseconds in most cases. So good catch.

I guess there are plenty of faster solutions using logic in how you normally solve it but we weren't allowed to use those.
3FFA
Profile Blog Joined February 2010
United States3931 Posts
December 13 2016 07:48 GMT
#16274
What are some good Discord chat groups for helping learn? Asking for both myself and others, since a chat community is helpful for both answering questions as well as morale, preventing burnout.
"As long as it comes from a pure place and from a honest place, you know, you can write whatever you want."
Manit0u
Profile Blog Joined August 2004
Poland17843 Posts
Last Edited: 2016-12-13 11:07:09
December 13 2016 11:06 GMT
#16275
On December 13 2016 14:06 Yurie wrote:
Show nested quote +
On December 13 2016 08:32 Manit0u wrote:
Geez. You should really break this code into smaller parts...
+ Show Spoiler +


// We can throw that away since it's not being utilized...
//for (int i = 0; i < 3; i++) {
// for (int j = 0; j < 3; j++) {
// squareCounts[i][j] = getCount(i, j);
// }
//}

for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != 0) {
rowCounts[i]++;
}

if (board[j][i] != 0) {
colCounts[i]++;
}
}
}

for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == 0) {
if (rowCounts[i] > max) {
max = rowCounts[i];
r = i;
c = j;
}

if (colCounts[j] > max) {
max = rowCounts[j];
r = i;
c = j;
}
}
}
}

// no more need for that
public static int getCount(int i, int j) {
int count = 0;

for (int m = 0; m < 3; m++) {
for (int n = 0; n < 3; n++) {
if (board[(i * 3) + m][(j * 3) + n] != 0) {
count++;
}
}
}

return count;
}


Plenty less loops and a bit more readability (still, doing the same loop twice seems highly inefficient).
I believe it could be optimized further but it's late and I hate Java


You are right that squarecount isn't being used. Would probably speed it up if I managed to figure out a good way to use it but commented it out now instead. Improved speed of my testcase5 by 2-3 miliseconds in most cases. So good catch.

I guess there are plenty of faster solutions using logic in how you normally solve it but we weren't allowed to use those.


It's not really that much a matter of efficiency (some small loops won't impact that much) but rather readability and maintainability of your code.

You could also work on encapsulation a bit more (try not to use public and/or static functions and properties when not necessary).
Time is precious. Waste it wisely.
mantequilla
Profile Blog Joined June 2012
Turkey781 Posts
December 13 2016 12:40 GMT
#16276
can't imagine the horror of the assistant who is going to grade those sudoku homeworks, entering 81 numbers by hand for each student :/
Age of Mythology forever!
Acrofales
Profile Joined August 2010
Spain18434 Posts
December 13 2016 12:56 GMT
#16277
On December 13 2016 21:40 mantequilla wrote:
can't imagine the horror of the assistant who is going to grade those sudoku homeworks, entering 81 numbers by hand for each student :/

Huh? When I corrected homework for uni classes all I really did was:
1) compile it (about 1/3 of homework assignments failed here).
2) fire it up and see if it loaded (another 1/3 failed).
3) run it through a battery of automated tests.
4) open up the code and check whether the specific assignment goals had been met (things like encapsulation, using at least 2 different classes, some given design pattern, etc. etc.)

Most of the work wasn't in testing those cases that seemed to work, but had some small bug (automated tests would weed those out). It was in figuring out whether one of the ones that completely failed step 1 or 2 deserved a pass because the massive fail was a small last-minute too-rushed addition, or because the code was a complete utter failure.

It was also only after grading such works that I realized I had spent entirely too much time on my own homework when following those courses
mantequilla
Profile Blog Joined June 2012
Turkey781 Posts
Last Edited: 2016-12-13 13:15:59
December 13 2016 13:15 GMT
#16278
how can you automate tests for an app that interacts through a ui, which of course would be different for each student

it is easy to test just code, especially if you given an interface to implement to students, but I dunno if theres a way to test a bunch of different gui's :D

most of them should fail before reaching that step though, so you can get away with only couple manual tests
Age of Mythology forever!
Manit0u
Profile Blog Joined August 2004
Poland17843 Posts
Last Edited: 2016-12-13 15:06:39
December 13 2016 13:36 GMT
#16279
On December 13 2016 22:15 mantequilla wrote:
how can you automate tests for an app that interacts through a ui, which of course would be different for each student


https://en.wikipedia.org/wiki/List_of_GUI_testing_tools

On a side note:


def perform
DIRECTORIES.each do |directory|
remove_outdated(directory)
end
end

protected

def expiration_time
ChronicDuration.parse(EXPIRATION_TIME, keep_zero: true)
end

def is_outdated?(path)
File.ctime(path) < (Time.zone.now - expiration_time)
end

def list_directory(path)
Dir.glob(File.join(path, '**', "*#{File::Separator}"))
end

def outdated_folders(path)
list_directory(path).each_with_object([]) do |entry, result|
result << entry if is_outdated?(entry)
end
end

def remove_outdated(path)
FileUtils.rm_rf(outdated_folders(path))
end


I love my new job
Time is precious. Waste it wisely.
mantequilla
Profile Blog Joined June 2012
Turkey781 Posts
Last Edited: 2016-12-13 13:59:23
December 13 2016 13:51 GMT
#16280
On December 13 2016 22:36 Manit0u wrote:
Show nested quote +
On December 13 2016 22:15 mantequilla wrote:
how can you automate tests for an app that interacts through a ui, which of course would be different for each student


https://en.wikipedia.org/wiki/List_of_GUI_testing_tools




seriously the attitute in this thread... I know how to google for "gui testing tools". I know about their existence before I google. I used them in the past.

They work for testing your own app which you know the workflow, the layout etc. They can't test an arbitrary gui automatically without setting them up appropriately. How could they test a bunch off different "sudoku" apps written by different people with a bunch of different ui?

anyways I just wanted to say a simple funny thing and got people giving me smart answers... won't do it anymore.
Age of Mythology forever!
Prev 1 812 813 814 815 816 1032 Next
Please log in or register to reply.
Live Events Refresh
Next event in 3h 1m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
mouzHeroMarine 513
ViBE28
CosmosSc2 21
StarCraft: Brood War
Yoon 31
NaDa 16
Dota 2
monkeys_forever211
League of Legends
Doublelift3282
Counter-Strike
shoxiejesuss1268
Heroes of the Storm
Liquid`Hasu452
Other Games
Grubby2827
FrodaN2262
fl0m868
Beastyqt724
C9.Mang0238
XaKoH 154
IndyStarCraft 106
UpATreeSC63
Trikslyr54
ZombieGrub50
gofns15
ToD13
Nathanias4
Organizations
StarCraft 2
WardiTV358
[ Show 15 non-featured ]
StarCraft 2
• intothetv
• AfreecaTV YouTube
• Kozan
• IndyKCrew
• Migwel
StarCraft: Brood War
• blackmanpl 51
• HerbMon 25
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• masondota22058
• WagamamaTV533
League of Legends
• TFBlade1055
Other Games
• imaqtpie1493
• Shiphtur150
Upcoming Events
Replay Cast
3h 1m
The PondCast
13h 1m
KCM Race Survival
13h 1m
OSC
1d 1h
Escore
1d 13h
IntoTheTV X SOOP
1d 14h
CranKy Ducklings
2 days
Sparkling Tuna Cup
3 days
Shopify Rebellion Sundays
3 days
Spirit vs Mixu
Clem vs TBD
RSL Revival
3 days
Serral vs Rogue
[ Show More ]
BlizzCon
3 days
Replay Cast
4 days
Afreeca Starleague
4 days
WardiTV Weekly
4 days
Afreeca Starleague
5 days
GSL
5 days
PiGosaur Cup
6 days
The PondCast
6 days
Kung Fu Cup
6 days
Liquipedia Results

Completed

Proleague 2026-09-08
PiG Sty Festival 8.0
Big Dog Cup 2026 Div 1

Ongoing

KCM Race Survival 2026 Season 3
K-JUNGMAN
ASL Season 22
Super Anchor Qualifying S3
CSL 2026 AUTUMN (S22)
Acropolis #5
Acropolis #5 - TRS
RSL Revival: Season 6
Calamity Invitational
FISSURE Playground #3
BLAST Open Fall 2026
Esports World Cup 2026
BLAST Bounty Summer 2026
BLAST Bounty Summer Qual
Stake Ranked Episode 3
XSE Pro League 2026

Upcoming

Escore Tournament S3: King of Kings
Acropolis #5 - GSA
Blizzard Classic Cup 2026
Acropolis #5 - GSB
Acropolis #5 - GSC
SC4ALL II: Brood War
HSC XXX
Stellar Fest 2: Lunar Cup
SC4ALL II: StarCraft II
Kung Fu Cup 2026 Grand Finals
RSL Offline Finals
Blizzard Classic Cup 2026
Stake Ranked Episode 6
BLAST Rivals Fall 2026
IEM Beijing 2026
Stake Ranked Episode 5
PGL Masters Bucharest 2026
1win Private Club #2
Thunderpick World Champ. '26
ESL Pro League Season 24
Stake Ranked Episode 4
1win Private Club #1
Logitech G Play Connect 2026
SL StarSeries Fall 2026
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2026 TLnet. All Rights Reserved.