• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 13:36
CET 19:36
KST 03:36
  • 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
TL.net Map Contest #21: Winners10Intel X Team Liquid Seoul event: Showmatches and Meet the Pros10[ASL20] Finals Preview: Arrival13TL.net Map Contest #21: Voting12[ASL20] Ro4 Preview: Descent11
Community News
StarCraft, SC2, HotS, WC3, Returning to Blizzcon!44$5,000+ WardiTV 2025 Championship7[BSL21] RO32 Group Stage4Weekly Cups (Oct 26-Nov 2): Liquid, Clem, Solar win; LAN in Philly2Weekly Cups (Oct 20-26): MaxPax, Clem, Creator win10
StarCraft 2
General
Mech is the composition that needs teleportation t StarCraft, SC2, HotS, WC3, Returning to Blizzcon! RotterdaM "Serral is the GOAT, and it's not close" TL.net Map Contest #21: Winners Weekly Cups (Oct 20-26): MaxPax, Clem, Creator win
Tourneys
Sparkling Tuna Cup - Weekly Open Tournament Constellation Cup - Main Event - Stellar Fest $5,000+ WardiTV 2025 Championship Merivale 8 Open - LAN - Stellar Fest Sea Duckling Open (Global, Bronze-Diamond)
Strategy
Custom Maps
Map Editor closed ?
External Content
Mutation # 498 Wheel of Misfortune|Cradle of Death Mutation # 497 Battle Haredened Mutation # 496 Endless Infection Mutation # 495 Rest In Peace
Brood War
General
FlaSh on: Biggest Problem With SnOw's Playstyle BW General Discussion BGH Auto Balance -> http://bghmmr.eu/ Where's CardinalAllin/Jukado the mapmaker? [ASL20] Ask the mapmakers — Drop your questions
Tourneys
[ASL20] Grand Finals [BSL21] RO32 Group A - Saturday 21:00 CET [Megathread] Daily Proleagues [BSL21] RO32 Group B - Sunday 21:00 CET
Strategy
Current Meta PvZ map balance How to stay on top of macro? Soma's 9 hatch build from ASL Game 2
Other Games
General Games
Stormgate/Frost Giant Megathread Nintendo Switch Thread Path of Exile Should offensive tower rushing be viable in RTS games? Dawn of War IV
Dota 2
Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread SPIRED by.ASL Mafia {211640}
Community
General
US Politics Mega-thread The Games Industry And ATVI Russo-Ukrainian War Thread Things Aren’t Peaceful in Palestine YouTube Thread
Fan Clubs
White-Ra Fan Club The herO Fan Club!
Media & Entertainment
[Manga] One Piece Anime Discussion Thread Movie Discussion! Korean Music Discussion Series you have seen recently...
Sports
2024 - 2026 Football Thread Formula 1 Discussion NBA General Discussion MLB/Baseball 2023 TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
SC2 Client Relocalization [Change SC2 Language] Linksys AE2500 USB WIFI keeps disconnecting Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List Recent Gifted Posts
Blogs
Learning my new SC2 hotkey…
Hildegard
Coffee x Performance in Espo…
TrAiDoS
Saturation point
Uldridge
DnB/metal remix FFO Mick Go…
ImbaTosS
Reality "theory" prov…
perfectspheres
Our Last Hope in th…
KrillinFromwales
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1670 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
Turkey779 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
11927 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
11927 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
11927 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
11927 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
Poland17421 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
11927 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
Poland17421 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
Turkey779 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
Spain18112 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
Turkey779 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
Poland17421 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
Turkey779 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
IPSL
18:00
Ro24 Group F
JDConan vs WIZARD
WolFix vs Cross
Liquipedia
LAN Event
15:00
Stellar Fest: Day 3
Clem vs Zoun
ComeBackTV 1149
UrsaTVCanada616
IndyStarCraft 313
EnkiAlexander 63
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
IndyStarCraft 320
BRAT_OK 120
Railgan 57
ProTech31
StarCraft: Brood War
Backho 43
zelot 32
scan(afreeca) 9
Dota 2
qojqva2942
Dendi1158
syndereN288
Heroes of the Storm
Khaldor536
Other Games
gofns7773
FrodaN1132
B2W.Neo780
ceh9316
Liquid`VortiX307
Hui .158
Sick156
ArmadaUGS110
Mew2King85
ToD36
mouzStarbuck5
Organizations
Other Games
gamesdonequick648
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 18 non-featured ]
StarCraft 2
• Adnapsc2 19
• davetesta7
• Kozan
• AfreecaTV YouTube
• sooper7s
• intothetv
• IndyKCrew
• LaughNgamezSOOP
• Migwel
StarCraft: Brood War
• Michael_bg 7
• Pr0nogo 7
• STPLYoutube
• ZZZeroYoutube
• BSLYoutube
Dota 2
• WagamamaTV649
• Ler64
League of Legends
• Nemesis3301
• Shiphtur837
Upcoming Events
BSL 21
1h 24m
spx vs rasowy
HBO vs KameZerg
Cross vs Razz
dxtr13 vs ZZZero
OSC
4h 24m
OSC
14h 24m
Wardi Open
17h 24m
Wardi Open
21h 24m
Replay Cast
1d 4h
WardiTV Korean Royale
1d 17h
Replay Cast
2 days
Kung Fu Cup
2 days
Classic vs Solar
herO vs Cure
Reynor vs GuMiho
ByuN vs ShoWTimE
Tenacious Turtle Tussle
3 days
[ Show More ]
The PondCast
3 days
RSL Revival
3 days
Solar vs Zoun
MaxPax vs Bunny
Kung Fu Cup
3 days
WardiTV Korean Royale
3 days
Replay Cast
4 days
RSL Revival
4 days
Classic vs Creator
Cure vs TriGGeR
Kung Fu Cup
4 days
CranKy Ducklings
5 days
RSL Revival
5 days
herO vs Gerald
ByuN vs SHIN
Kung Fu Cup
5 days
BSL 21
6 days
Tarson vs Julia
Doodle vs OldBoy
eOnzErG vs WolFix
StRyKeR vs Aeternum
Sparkling Tuna Cup
6 days
RSL Revival
6 days
Reynor vs sOs
Maru vs Ryung
Kung Fu Cup
6 days
WardiTV Korean Royale
6 days
Liquipedia Results

Completed

Proleague 2025-11-07
SC4ALL: StarCraft II
Eternal Conflict S1

Ongoing

C-Race Season 1
IPSL Winter 2025-26
KCM Race Survival 2025 Season 4
SOOP Univ League 2025
YSL S2
BSL Season 21
Stellar Fest: Constellation Cup
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
CS Asia Championships 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual

Upcoming

SLON Tour Season 2
BSL 21 Non-Korean Championship
Acropolis #4
IPSL Spring 2026
HSC XXVIII
RSL Offline Finals
WardiTV 2025
RSL Revival: Season 3
META Madness #9
BLAST Bounty Winter 2026: Closed Qualifier
eXTREMESLAND 2025
ESL Impact League Season 8
SL Budapest Major 2025
BLAST Rivals Fall 2025
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 © 2025 TLnet. All Rights Reserved.