Sum to 100: Difference between revisions

2,218 bytes added ,  4 years ago
Line 5,313:
highest sums : [123456789, 23456790, 23456788, 12345687, 12345669, 3456801, 3456792, 3456790, 3456788, 3456786]
</pre>
 
=={{header|Scala}}==
<lang scala>package solutions
 
object SumTo100 {
def main(args: Array[String]): Unit = {
val configs = configurations(9).map(c => (c, eval(c)))
val sums = configs.map(_._2).sortWith(_>_)
val s1 = configs.filter(_._2 == 100)
val s2 = sums.distinct.map(s => (s, sums.count(_ == s))).maxBy(_._2)
val s3 = sums.distinct.reverse.filter(_>0).zipWithIndex.dropWhile{case (n, i) => n == i + 1}.head._2 + 1
val s4 = sums.distinct.take(10)
println(s"""All ${s1.size} solutions that sum to 100:
|${s1.map(p => s"${p._2} = ${mkStr(p._1).tail}").mkString("\n")}
|
|Most common sum: ${s2._1} (${s2._2})
|Lowest unreachable sum: $s3
|Highest 10 sums: ${s4.mkString(", ")}""".stripMargin)
}
def configurations(l: Int): LazyList[Vector[Int]] = LazyList.range(0, math.pow(3, l).toInt).map(config(l)).filter(_.last != 0)
def config(l: Int)(num: Int): Vector[Int] = Iterator.iterate((num%3, num/3)){case (_, n) => (n%3, n/3)}.map(_._1 - 1).take(l).toVector
val nums: Vector[Int] = Vector(1, 2, 3, 4, 5, 6, 7, 8, 9)
def opChar(sel: Int): Char = if(sel >= 0) '+' else '-'
def mkStr(ops: Vector[Int], src: Vector[String] = nums.map(_.toString)): String = (src, ops) match{
case (ns :+ n2 :+ n1, os :+ o2 :+ o1) if o2 == 0 => mkStr(os :+ o1, ns :+ s"$n2$n1")
case (ns :+ n, os :+ o) if o != 0 => s"${mkStr(os, ns)}${opChar(o)}$n"
case _ => ""
}
def eval(ops: Vector[Int], src: Vector[Int] = nums): Int = (src, ops) match{
case (n1 +: n2 +: ns, o +: os) if o == 0 => eval(os, s"$n1$n2".toInt +: ns)
case (n +: ns, o +: os) if o != 0 => o*n + eval(os, ns)
case _ => 0
}
}</lang>
{{out}}
<pre>All 12 solutiongs that sum to 100:
100 = 123+4-5+67-89
100 = 123-4-5-6-7+8-9
100 = 123+45-67+8-9
100 = 1+23-4+5+6+78-9
100 = 1+2+34-5+67-8+9
100 = 12+3+4+5-6-7+89
100 = 123-45-67+89
100 = 12-3-4+5-6+7+89
100 = 1+2+3-4+5+6+78+9
100 = 1+2-3+4+5+6+78+9
100 = 12+3-4+5+67+8+9
100 = 1+23-4+56+7+8+9
 
Most common sum: 9 (46)
Lowest unreachable sum: 211
Highest 10 sums: 123456789, 23456790, 23456788, 12345687, 12345669, 3456801, 3456792, 3456790, 3456788, 3456786</pre>
 
=={{header|Sidef}}==
Anonymous user