-1

I am working with the R programming language.

Here is a Sudoku Puzzle that I have (represented in matrix form) :

#https://en.wikipedia.org/wiki/Sudoku_solving_algorithms#/media/File:Sudoku_Puzzle_by_L2G-20050714_standardized_layout.svg

problem <- matrix(c(
    5, 3, NA, NA, 7, NA, NA, NA, NA,
    6, NA, NA, 1, 9, 5, NA, NA, NA,
    NA, 9, 8, NA, NA, NA, NA, 6, NA,
    8, NA, NA, NA, 6, NA, NA, NA, 3,
    4, NA, NA, 8, NA, 3, NA, NA, 1,
    7, NA, NA, NA, 2, NA, NA, NA ,6,
    NA ,6 ,NA ,NA ,NA ,NA ,2 ,8 ,NA,
    NA ,NA ,NA ,4 ,1 ,9 ,NA ,NA ,5,
    NA ,NA ,NA ,NA ,8 ,NA ,NA ,7 ,9
), nrow = 9)

Here is a Function and a WHILE LOOP that I am using to randomly fill numbers into this Sudoku until a solution is found:

# check if answer is valid
is_valid <- function(mat) {
    all(apply(mat, 1, function(row) length(unique(row)) == length(row))) &&
        all(apply(mat, 2, function(col) length(unique(col)) == length(col))) &&
        length(unique(as.vector(mat))) == length(as.vector(mat))
}

# counter
attempt <- 0

# Loop 
while(TRUE) {
    attempt <- attempt + 1
    
  
    solution <- problem
    
    # fill NA values with random numbers from 1 to 9
    solution[is.na(solution)] <- sample(1:9, sum(is.na(solution)), replace = TRUE)
    
    # Print 
    cat(paste("Attempt", attempt, ":\n"))
    print(solution)
    
    # Break
    if(is_valid(solution)) {
        break
    }
}

My Question: Is it possible to use the Genetic Algorithm (e.g. https://en.wikipedia.org/wiki/Genetic_algorithm, https://cran.r-project.org/web/packages/GA/vignettes/GA.html) on this problem?

I tried to find some references (e.g. Solving Sudoku using a genetic algorithm), but I could not find anything which shows how I can set up the Fitness Function in this problem.

Can someone please show me how to do this?

Thanks!

Phil
  • 7,287
  • 3
  • 36
  • 66
stats_noob
  • 5,401
  • 4
  • 27
  • 83

0 Answers0