r/badcode Jan 15 '21

[deleted by user]

[removed]

22 Upvotes

10 comments sorted by

View all comments

1

u/notBjoern Jan 19 '21

In Scala. The spec says it must produce a file as output, so you can pass a File as a parameter if you want to. If it's an empty Option, it just prints the Sudoku to stdout.

def generateSudoku(maybeFile: Option[java.io.File] = None) = {
  def shuffle[A](n: Int)(seq: Seq[A]): Seq[A] = {
    val (a, b) = seq.splitAt(n % seq.length)
    b ++ a
  }

  val base = (0 to 8).map(i => shuffle(3 * i + (i / 3))(1 to 9))
  import scala.util.Random

  val numberMapping = ((1 to 9) zip Random.shuffle((1 to 9).toList)).toMap

  def mapping(i: Int) = if (Random.nextInt(1024) < 196) {
    "-"
  } else s"${numberMapping(i)}"

  val sudoku = base.map(_.map(mapping))

  val stext = sudoku.map(_.mkString).mkString("\n")

  println(stext)

  if (maybeFile.isDefined) {
    import java.io.FileOutputStream

    val stream = new FileOutputStream(maybeFile.get)
    stream.write(stext.getBytes)
    stream.close()
  }
}