DEV Community

Cover image for Day 46: Sudoku Generator
Matt Ryan
Matt Ryan

Posted on

2 1

Day 46: Sudoku Generator

public class SudokuGenerator {
    public SudokuGenerator(int dim) {
        int[] topSeed = new int[dim];
        int[] sideSeed = new int[dim - 1];

        for (int i = 0; i < topSeed.length; i++) {
            topSeed[i] = i + 1;
        }

        shuffle(topSeed);

        for (int i = 0; i < sideSeed.length; i++) {
            int seedVal = i + 1;
            if (seedVal == topSeed[0]) sideSeed[i] = dim;
            else sideSeed[i] = i + 1;
        }

        shuffle(sideSeed);

        int[][] puzzleBuilder = new int[dim][dim];

        for (int i = 0; i < topSeed.length; i++) {
            puzzleBuilder[0][i] = topSeed[i];
        }

        for (int i = 0; i < sideSeed.length; i++) {
            puzzleBuilder[i + 1][0] = sideSeed[i];
        }

        SudokuPuzzle newPuzzle = new SudokuPuzzle(puzzleBuilder);

        System.out.println("Seed Puzzle:");
        System.out.println(newPuzzle + "\n");

        SudokuSolver ss = new SudokuSolver(newPuzzle);

        System.out.println("Generated Puzzle:");
        System.out.println(ss.results());

    }



    private int[] shuffle(int[] input) {

        int N = input.length;

        for (int i = 0; i < (N - 2); i++) {
            int swapIndex = (int) (Math.random() * (N - i)) + i;
            int temp = input[i];
            input[i] = input[swapIndex];
            input[swapIndex] = temp;
        }
        return input;
    }

    public static void main(String[] args) {
        int N = 9;        
        SudokuGenerator sg = new SudokuGenerator(N);

    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.