Advertisement
Guest User

Untitled

a guest
Jan 16th, 2019
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.72 KB | None | 0 0
  1. package ru
  2.  
  3. import kotlin.math.absoluteValue
  4.  
  5. private var BOARD_SIZE = 15
  6. private var counter = 0L
  7.  
  8. fun main(args: Array<String>) {
  9.     if (!args.isEmpty()) BOARD_SIZE = args[0].toInt()
  10.     val board = IntArray(BOARD_SIZE)
  11.     val start = System.nanoTime()
  12.     try {
  13.         successfulComb(board, 0)
  14.     } catch (e: Exception) {
  15.     }
  16.     val timeSpent = System.nanoTime() - start
  17.     println("for board of size $BOARD_SIZE found $counter correct solutions in $timeSpent nanos, which is ${timeSpent / 1000000} millis, which is approx ${timeSpent / 1000000000} seconds")
  18.  
  19. }
  20.  
  21. tailrec fun successfulComb(body: IntArray, position: Int): IntArray {
  22.     if (position >= BOARD_SIZE) {
  23.         counter++
  24.     } else {
  25.         for (i in 0 until BOARD_SIZE) {
  26.             if (!conflicts(body, i, position)) {
  27.                 body[position] = i
  28.                 return successfulComb(body, position + 1)
  29.             }
  30.         }
  31.     }
  32.     val newHead = prepareNextIteraion(body, position)
  33.     return successfulComb(body, newHead)
  34. }
  35.  
  36. private fun prepareNextIteraion(body: IntArray, position: Int): Int {
  37.     var result = -1
  38.     for (i in position - 1 downTo 0) {
  39.         do {
  40.             body[i]++
  41.         } while (body[i] < BOARD_SIZE && conflicts(body, body[i], i))
  42.         if (body[i] >= BOARD_SIZE) continue
  43.         body.fill(0, i + 1, body.size)
  44.         result = i + 1
  45.         break
  46.     }
  47.     return if (result == -1) throw IllegalArgumentException() else result
  48. }
  49.  
  50. fun conflicts(head: IntArray, position: Int, until: Int): Boolean {
  51.     for (index in 0 until until) {
  52.         if (head[index] == position || (head[index] - position).absoluteValue == (index - until).absoluteValue) return true
  53.     }
  54.     return false
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement