cipheron

Sudoku Creator - 7s Checker

Sep 22nd, 2024
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.90 KB | None | 0 0
  1. import random
  2.  
  3. def print_grid(grid):
  4. for row in grid:
  5. print(" ".join(str(num) for num in row))
  6.  
  7. def is_valid(grid, row, col, num):
  8. for i in range(9):
  9. if grid[row][i] == num or grid[i][col] == num:
  10. return False
  11. start_row, start_col = 3 * (row // 3), 3 * (col // 3)
  12. for i in range(start_row, start_row + 3):
  13. for j in range(start_col, start_col + 3):
  14. if grid[i][j] == num:
  15. return False
  16. return True
  17.  
  18. def fill_grid(grid):
  19. for row in range(9):
  20. for col in range(9):
  21. if grid[row][col] == 0:
  22. random_nums = list(range(1, 10))
  23. random.shuffle(random_nums)
  24. for num in random_nums:
  25. if is_valid(grid, row, col, num):
  26. grid[row][col] = num
  27. if fill_grid(grid):
  28. return True
  29. grid[row][col] = 0
  30. return False
  31. return True
  32.  
  33. def generate_sudoku():
  34. grid = [[0] * 9 for _ in range(9)]
  35. fill_grid(grid)
  36. return grid
  37.  
  38. def check_for_sevens(grid, num_samples=30):
  39. flat_grid = [num for row in grid for num in row]
  40. selected_tiles = random.sample(flat_grid, num_samples)
  41. has_seven = 7 in selected_tiles
  42. return has_seven
  43.  
  44. # Generate a completed Sudoku grid
  45. sudoku_grid = generate_sudoku()
  46.  
  47. # Print the Sudoku grid
  48. print("Generated Sudoku Grid:")
  49. print_grid(sudoku_grid)
  50.  
  51. # Run 1,000,000 trials to check for 7s
  52. num_trials = 1000000
  53. count_no_sevens = 0
  54.  
  55. for _ in range(num_trials):
  56. if not check_for_sevens(sudoku_grid):
  57. count_no_sevens += 1
  58.  
  59. # Calculate percentage of no-7s
  60. percentage_no_sevens = (count_no_sevens / num_trials) * 100
  61.  
  62. # Output results
  63. print(f"Total occurrences of no 7s: {count_no_sevens}")
  64. print(f"Percentage of trials with no 7s: {percentage_no_sevens:.4f}%")
  65. input()
  66.  
Advertisement
Add Comment
Please, Sign In to add comment