Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Test
- fun generate() {
- val random = Random(123)
- for (i in 1..100000) {
- val xs = listOf(S.Plus(random.nextInt(10))) + (1..5).map { S.rands(random) }
- val c = calc(xs)
- if (c != null) {
- val ss = xs.joinToString { wraps(it) }
- println("$ss = $c")
- }
- }
- }
- fun calc(xs: List<S>): Int? {
- var sum: Int? = 0
- for (x in xs) {
- sum = when (x) {
- is S.Plus -> sum?.plus(x.n)
- is S.Minus -> sum?.minus(x.n)
- is S.Mul -> {
- if (sum == null) null
- else {
- val y = sum * x.n
- if (y < -20 || y > 20) null else y
- }
- }
- is S.Div -> {
- if (sum == null) null
- else {
- if (x.n <= 0 || (sum / x.n) * x.n != sum) null else sum / x.n
- }
- }
- }
- if (sum == null)
- break
- }
- return sum
- }
- }
- sealed class S {
- data class Plus(val n: Int) : S()
- data class Minus(val n: Int) : S()
- data class Mul(val n: Int) : S()
- data class Div(val n: Int) : S()
- companion object {
- fun rands(r: Random): S {
- val x = r.nextInt(10)
- return when (r.nextInt(4)) {
- 0 -> Plus(x)
- 1 -> Minus(x)
- 2 -> Mul(x)
- else -> Div(x)
- }
- }
- fun wraps(s: S): String {
- return when (s) {
- is Plus -> "+" + s.n
- is Minus -> "-" + s.n
- is Mul -> "*" + s.n
- is Div -> "/" + s.n
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement