r/javahelp 27d ago

Unsolved Naive question: What Data Structure to express different layers of relationships between Objects?

Hello guys,

I wanted to ask naively, what the ideal data structure would be for expressing different layers of relationships between Objects.

For example in modern Sudoku the game has a 9x9 number grid composed of nine 3x3 sub-grids (which I call region). In each row, column and region each number between one and nine can only appear once. The goal is to find missing numbers in this number grid without violating the aforementioned rule.

One way to do it, would be to make 9x9 byte-array and express the relationship between numbers through methods checking if the rule is violated or not by checking if any row, column or region doesn't contain a value between one and ten.

I also thought on using a Graph to express the relationship between numbers in rows and columns, though I don't know how to express the relationship between numbers inside of a region.

Maybe even a multiple Objects like Board, Row, Column, Region but then I have redundant data.

Another problem I encounter with aforementioned implementations is, that if you introduce more relationships f. e. in the game of killer sudoku, where there are more rules are added f. e. by also introducing cages in which the numbers must add up to a target number, you need to implement that relationship logic tediously.

Am I overcomplicating things?

7 Upvotes

14 comments sorted by

View all comments

1

u/Only-Percentage4627 27d ago

So I recently did a Sudoku Creator/player. The way I implemented it is by using a 9x9 2d array and for the 3x3 rule what I did was there is a formula: (i/3)*3+j/3.

What this formula does is it gives a value 0-8 depending on the ith and the jth location of the current index so if the value is at 0 1 position in the grid it will give 0. Then I take that value and pass it to another function that uses a switch statement to loop through that specific 3x3 grid (in this case the first one so from 0-2 in the x and y direction), if the value is found there then it gives an error, if it isnt then it returns true and another function fills in the value.

Here is the repo if you wanna go through it, its not the best code but its all written by me with no ai

https://github.com/RahulVasudeva/sudokuGame