Advertisement
vkazar

Untitled

Feb 28th, 2024
257
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.42 KB | None | 0 0
  1. private val charRange = ('a'..'z')
  2.  
  3. private const val limit = 1000
  4. private const val a = 1000
  5. private const val m = 123_987_123
  6.  
  7. fun main() {
  8.     try {
  9.         val firstString = "ckfiar".also { println(it) }
  10.  
  11.         val firstHash = firstString.polynomialHash(a, m)
  12.         val sb = StringBuilder()
  13.         generateSequence {
  14.             val cur = sb.nextSequence().toString()//.also(::println)
  15.             if (cur.length > limit)
  16.                 throw Error("последовательность не найдена")
  17.             else
  18.                 cur
  19.         }
  20.             .first {
  21.                 it.polynomialHash(a, m) == firstHash && it != firstString
  22.             }
  23.             .let(::println)
  24.     } catch (e: Throwable) {
  25.         e.printStackTrace()
  26.     }
  27. }
  28.  
  29. private fun StringBuilder.nextSequence(): StringBuilder {
  30.     if (isEmpty() || all { it == 'z' }) {
  31.         // самое начало или все элементы -- z
  32.         for (i in indices) this[i] = 'a'
  33.         return append('a')
  34.     }
  35.     for (i in lastIndex downTo 0) {
  36.         if (this[i] == 'z') this[i] = 'a'
  37.         else {
  38.             this[i] = this[i].next()
  39.             break
  40.         }
  41.     }
  42.  
  43.     return this
  44. }
  45.  
  46. private fun Char.next() = ((this.code - 96) % 26 + 97).toChar()
  47.  
  48. private fun randomString(size: Int = 20) =
  49.     buildString {
  50.         repeat(size) {
  51.             append(charRange.random())
  52.         }
  53.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement