Advertisement
Guest User

Untitled

a guest
Jan 15th, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.92 KB | None | 0 0
  1. package ru
  2.  
  3. import java.util.concurrent.atomic.LongAdder
  4. import kotlin.math.absoluteValue
  5.  
  6. private const val BOARD_SIZE = 15
  7. private val counter = LongAdder()
  8.  
  9. fun main(args: Array<String>) {
  10.     val board = IntArray(BOARD_SIZE)
  11.     val start = System.nanoTime()
  12.     try {
  13.         successfulComb(intArrayOf(), board)
  14.     } catch (e: Exception) {
  15.     }
  16.     println(System.nanoTime() - start)
  17.     println(counter.sum())
  18.  
  19. }
  20.  
  21. tailrec fun successfulComb(head: IntArray, tail: IntArray): IntArray {
  22.     if (tail.isEmpty()) {
  23.         if (head[0] > 7) throw IllegalArgumentException()
  24.         counter.increment()
  25.     } else {
  26.         for (i in 0 until BOARD_SIZE) {
  27.             if (!fights(head, i)) return successfulComb(head + i, tail.sliceArray(1 until tail.size))
  28.         }
  29.     }
  30.     val newHead = prepareNextIteraion(head, tail)
  31.     return successfulComb(newHead, IntArray(BOARD_SIZE - newHead.size))
  32. }
  33.  
  34. private fun prepareNextIteraion(head: IntArray, tail: IntArray): IntArray {
  35.     resetHead(head)
  36.     tail.fill(0)
  37.     val count = findLastZeroesCount(head)
  38.     return head.sliceArray(0 until head.size - count)
  39. }
  40.  
  41. fun findLastZeroesCount(head: IntArray): Int {
  42.     var count = 0
  43.     for (i in head.size - 1 downTo 0) {
  44.         if (head[i] == 0) count++
  45.         else break
  46.     }
  47.     return count
  48. }
  49.  
  50. fun resetHead(head: IntArray) {
  51.     for (i in head.size - 1 downTo 0) {
  52.         do {
  53.             head[i]++
  54.         } while (head[i] < BOARD_SIZE && fights(head.sliceArray(0 until i), head[i]))
  55.         if (head[i] >= BOARD_SIZE) continue
  56.         for (j in i + 1 until head.size) {
  57.             head[j] = 0
  58.         }
  59.         return
  60.     }
  61. }
  62.  
  63. fun fights(head: IntArray, position: Int): Boolean {
  64.     for (index in head.indices) {
  65.         if (head[index] == position) return true
  66.         if ((head[index] - position).absoluteValue == (index - head.size).absoluteValue) return true
  67.     }
  68.     return false
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement