HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Sudoku game logic

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
gamesudokulogic

Problem

I am trying to create a Sudoku game in F# and I'm having a bit of trouble with the file reading and writing. But since I've also just started programming in f# I would like to check if my thinking is truly functional or if it have any obvious flaws.

The Sudoku game is made up of 5 parts, Logic.fs with the game board:

let sudokuGame = Array2D.init 9 9 (fun i j -> createSquare i j)


and the Square data structure:

type Square = { x : int; y : int; number : int; optionList : int list }


(x, y being the position x,y in the 2D array, number the accepted value of the Square and optionList the candidates for being the number of the Square), and getter/creation functions for it.

Solver.fs which contains functions to get rows, columns and islands (as lists) that can be matched against the lists in the Squares with a member function. It also has a solver:

```
let getRow S =
let rec getR pos =
match pos with
| 10 -> []
| x -> (sudokuGame.[(x-1), ((S.y) - 1)]).number :: getR (x+1)
in getR 1

let getCol S =
let rec getC pos =
match pos with
| 10 -> []
| y -> (sudokuGame.[(S.x - 1), (y - 1)]).number :: getC (y+1)
in getC 1

let getIsland S =

let getX =
match S.x with
| x when x 0
| x when x 3
| x -> 6

let getY =
match S.y with
| y when y 0
| y when y 3
| y -> 6
List.ofArray [| for x in 0 .. 2 do for y in 0 .. 2 -> sudokuGame.[getX+x,getY+y].number; |]

//placeInX is a function which leaves the items in x not found in y
let updateOptionList L S = { x= S.x; y=S.y; number = S.number; optionList = (placeInX (S.optionList) L )}

let getUpdatedSquare S =
if List.length (getSquareList S) <> 0
then
updateOptionList (getRow S) S |> updateOptionList (getCol S) |> updateOptionList (getIsland S) |> createCompleteSquare
else
S

let sodukoSolver (gameBoard : Squ

Solution

Array2D is a bit deficient in terms of basic operations, especially compared to Array, List, Set, and so on. For writing to a file, I would suggest using Array2D.iter and writing each record out in turn; the format that you choose to do this in is up to you. Then reading in each record is as simple as doing an Array2D.init, and taking each record from the file in-turn.

I can't see any obvious flaws here. Perhaps you might want to store the possible values using the built-in Set data-type.

Your code is functional enough, but you will gain more flexibility if you pass around values instead of using a global.

Context

StackExchange Code Review Q#91912, answer score: 3

Revisions (0)

No revisions yet.