Skip to content

Instantly share code, notes, and snippets.

@retheviper
Last active April 1, 2022 12:27
Show Gist options
  • Save retheviper/0aad3bf7620ea36e3c32d1a387aa5c10 to your computer and use it in GitHub Desktop.
Save retheviper/0aad3bf7620ea36e3c32d1a387aa5c10 to your computer and use it in GitHub Desktop.
1, 3, 3, 7 to 10
import kotlin.random.Random
fun main() {
while (true) {
val (result, expression) = calculate()
if (result == 10.0) {
println("${expression.removeSurrounding("(", ")")} = ${result.toInt()}")
break
}
}
}
fun calculate(): Pair<Double, String> {
val values = listOf(1, 3, 3, 7).shuffled()
var result = 0.0
var expression = ""
for ((index, value) in values.withIndex()) {
if (index == 0) {
result = value.toDouble()
expression += value
continue
}
val arithmetic = Random.nextInt(0, 4)
when (arithmetic) {
0 -> {
result += value
expression = "($expression + $value)"
}
1 -> {
result -= value
expression = "($expression - $value)"
}
2 -> {
result /= value
expression = "($expression ÷ $value)"
}
3 -> {
result *= value
expression = "($expression × $value)"
}
}
}
return result to expression
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment