fork download
  1. package countdownsolver
  2.  
  3. fun main(args: Array<String>) {
  4. solve(listOf(1, 3, 7, 6, 8, 3), 250)
  5. solve(listOf(25, 100, 9, 7, 3, 7), 881)
  6. solve(listOf(6, 75, 3, 25, 50, 100), 952)
  7. }
  8.  
  9. fun solve(lst: List<Int>, sol: Int) {
  10. val perms = permuteList(lst)
  11. val ops = operators()
  12. var eq = ""
  13. var res = 0
  14.  
  15. for(op in ops) {
  16. for(perm in perms.distinct().toTypedArray()) {
  17. eq = perm[0].toString()
  18. res = perm[0]
  19. for(i in 1 until perm.size) {
  20. eq = eq + " " + opToString(op[i-1]) + " " + perm[i].toString()
  21. res = applyOp(op[i-1], res, perm[i])
  22. }
  23.  
  24. if(res == sol) {
  25. println(eq+" = "+res.toString())
  26. }
  27. }
  28. }
  29. }
  30.  
  31. fun permuteList(lst: List<Int>): List<List<Int>> {
  32. if (lst.size == 1) return listOf(lst)
  33. val perms = mutableListOf<List<Int>>()
  34. val toInsert = lst[0]
  35. for(perm in permuteList(lst.drop(1))) {
  36. for(i in 0..perm.size) {
  37. val newPerm = perm.toMutableList()
  38. newPerm.add(i, toInsert)
  39. perms.add(newPerm)
  40. }
  41. }
  42. return perms
  43. }
  44.  
  45. fun operators(): Array<IntArray> {
  46. var res = mutableListOf(intArrayOf(0, 0, 0, 0, 0))
  47. for(i in 0 until 4) {
  48. for(j in 0 until 4) {
  49. for(k in 0 until 4) {
  50. for(l in 0 until 4) {
  51. for(m in 0 until 4) {
  52. res.add(intArrayOf(i, j, k, l, m))
  53. }
  54. }
  55. }
  56. }
  57. }
  58. res.removeAt(0)
  59. return res.toTypedArray()
  60. }
  61.  
  62. fun opToString(x: Int): String = when(x) {
  63. 0 -> "+"
  64. 1 -> "-"
  65. 2 -> "*"
  66. 3 -> "/"
  67. else -> ""
  68. }
  69.  
  70. fun applyOp(op: Int, x: Int, y: Int): Int = when(op) {
  71. 0 -> x + y
  72. 1 -> x - y
  73. 2 -> x * y
  74. 3 -> x / y
  75. else -> x
  76. }
Success #stdin #stdout 2.01s 4382720KB
stdin
Standard input is empty
stdout
3 + 8 * 7 + 6 * 3 + 1 = 250
8 + 3 * 7 + 6 * 3 + 1 = 250
3 + 3 * 7 + 1 * 6 - 8 = 250
100 + 7 * 25 - 9 / 3 - 7 = 881
7 + 100 * 25 - 9 / 3 - 7 = 881
25 - 9 * 7 * 7 + 100 - 3 = 881
25 - 9 * 7 * 7 - 3 + 100 = 881
7 * 3 + 100 * 7 + 25 + 9 = 881
7 * 3 + 100 * 7 + 9 + 25 = 881
3 * 7 + 100 * 7 + 25 + 9 = 881
3 * 7 + 100 * 7 + 9 + 25 = 881
7 / 7 + 100 * 9 - 25 - 3 = 881
7 / 7 + 100 * 9 - 3 - 25 = 881
6 + 100 * 75 * 3 - 50 / 25 = 952
100 + 6 * 75 * 3 - 50 / 25 = 952
6 + 100 * 3 * 75 - 50 / 25 = 952
100 + 6 * 3 * 75 - 50 / 25 = 952
3 + 100 * 6 * 75 / 50 + 25 = 952
3 + 100 * 75 * 6 / 50 + 25 = 952
100 + 3 * 6 * 75 / 50 + 25 = 952
100 + 3 * 75 * 6 / 50 + 25 = 952
25 * 100 / 3 + 75 + 50 - 6 = 952
25 * 100 / 3 + 50 + 75 - 6 = 952
100 * 25 / 3 + 75 + 50 - 6 = 952
100 * 25 / 3 + 50 + 75 - 6 = 952
25 * 100 / 3 + 75 - 6 + 50 = 952
25 * 100 / 3 + 50 - 6 + 75 = 952
100 * 25 / 3 + 75 - 6 + 50 = 952
100 * 25 / 3 + 50 - 6 + 75 = 952
25 * 100 / 3 - 6 + 75 + 50 = 952
25 * 100 / 3 - 6 + 50 + 75 = 952
100 * 25 / 3 - 6 + 75 + 50 = 952
100 * 25 / 3 - 6 + 50 + 75 = 952