Anonymous user
Sum to 100: Difference between revisions
Added a recursive solution. Corrected a bug in previous version. Had not the courage to translate it into English and to improve it.
(→{{header|Haskell}}: Replaced an arrow with an applicative, tidied.) |
(Added a recursive solution. Corrected a bug in previous version. Had not the courage to translate it into English and to improve it.) |
||
Line 4,544:
=={{header|Nim}}==
Recursive solution.
import strutils▼
<lang Nim>import algorithm, parseutils, sequtils, strutils, tables
type Expression = string
proc buildExprs(start: Natural = 0): seq[Expression] =
let item = if start == 0: "" else: $start
if start == 9: return @[item]
for expr in buildExprs(start + 1):
result.add item & expr
result.add item & '-' & expr
if start != 0: result.add item & '+' & expr
proc evaluate(expr: Expression): int =
var idx = 0
var val: int
while idx < expr.len:
let n = expr.parseInt(val, idx)
inc idx, n
result += val
let exprs = buildExprs()
var counts: CountTable[int]
echo "The solutions for 100 are:"
for expr in exprs:
let sum = evaluate(expr)
if sum == 100: echo expr
if sum > 0: counts.inc(sum)
let (n, count) = counts.largest()
echo "\nThe maximum count of positive solutions is $1 for number $2.".format(count, n)
var s = 1
while true:
if s notin counts:
echo "\nThe smallest number than cannot be expressed is: $1.".format(s)
break
inc s
echo "\nThe ten highest numbers than can be expressed are:"
let numbers = sorted(toSeq(counts.keys), Descending)
echo numbers[0..9].join(", ")</lang>
{{out}}
<pre>The solutions for 100 are:
123+4-5+67-89
123-45-67+89
12+3+4+5-6-7+89
12-3-4+5-6+7+89
1+23-4+5+6+78-9
123+45-67+8-9
123-4-5-6-7+8-9
1+2+3-4+5+6+78+9
-1+2-3+4+5+6+78+9
1+2+34-5+67-8+9
12+3-4+5+67+8+9
1+23-4+56+7+8+9
The maximum count of positive solutions is 46 for number 9.
The smallest number than cannot be expressed is: 211.
The ten highest numbers than can be expressed are:
123456789, 23456790, 23456788, 12345687, 12345669, 3456801, 3456792, 3456790, 3456788, 3456786</pre>
Iterative previous solution written in French (updated).
▲<lang Nim>import strutils
var
Line 4,565 ⟶ 4,633:
liS = split(li," ")
for i in liS:
if i.len > 0: result += parseInt(i)
echo "Valeur à atteindre : ",aAtteindre
|