Skip to content

Instantly share code, notes, and snippets.

@qwert2603
Created February 28, 2018 10:26
Show Gist options
  • Save qwert2603/6112bdf82f3ecf7244d7547b0f035b65 to your computer and use it in GitHub Desktop.
Save qwert2603/6112bdf82f3ecf7244d7547b0f035b65 to your computer and use it in GitHub Desktop.
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
import kotlin.concurrent.thread
private val numbers = (0..9999)
.map { listOf(it / 1000, it % 1000 / 100, it % 100 / 10, it % 10) }
.filter { it.distinct().size == 4 }
private fun newNumber(): List<Int> = numbers[Random().nextInt(numbers.size)]
@Volatile
private var result = 0
private val nextPlayer = AtomicInteger(1)
private class Player(val index: Int, n: List<Int>? = null) {
private val n = n ?: newNumber()
fun ask(q: List<Int>): Pair<Int, Int> {
val b = n.zip(q).count { it.first == it.second }
var k = 0
for (i in 0..3) {
for (j in 0..3) {
if (i != j) {
if (n[i] == q[j]) ++k
}
}
}
return Pair(b, k)
}
fun playWith(anth: Player) {
thread(name = "player #$index") {
numbers.forEach {
while (nextPlayer.get() != index);
if (result != 0) return@forEach
println("ask $index $it ${Thread.currentThread()}")
if (anth.ask(it).first == 4) {
result = index
return@forEach
}
nextPlayer.set(if (index == 1) 2 else 1)
Thread.sleep(10)
}
}
}
}
fun main(args: Array<String>) {
val player1 = Player(1/*, listOf(1, 2, 5, 7)*/)
// val player2 = Player(2, listOf(1, 6, 7, 8))
// player1.playWith(player2)
// player2.playWith(player1)
//
// while (result == 0);
// println("over.\nplayer #$result WIN!")
var q: List<Int>
var ask: Pair<Int, Int>
do {
try {
q = readLine()!!.map { it.toString().toInt() }
ask = player1.ask(q)
println("быки=${ask.first}\tкоровы=${ask.second}")
} catch (e: Exception) {
ask = Pair(-1, -1)
println("error!")
}
} while (ask.first != 4)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment