Sum to 100: Difference between revisions

22,357 bytes added ,  1 month ago
m
Minor edit to Rust code
m (added whitespace, showed a solution in a bigger font.)
m (Minor edit to Rust code)
 
(22 intermediate revisions by 16 users not shown)
Line 21:
 
:* &nbsp; Show all solutions that sum to &nbsp; <big> '''100''' </big>
:* &nbsp; Show the sum that has the maximum &nbsp; ''number'' &nbsp; of solutions &nbsp; (from zero to infinity<sup>*<big>&Dagger;</big></sup>)
:* &nbsp; Show the lowest positive sum that &nbsp; ''can't'' &nbsp; be expressed &nbsp; (has no solutions), &nbsp; using the rules for this task
:* &nbsp; Show the ten highest numbers that can be expressed using the rules for this task &nbsp; (extra credit)
<br>
 
<sup><big>&Dagger;</big></sup> &nbsp; (where &nbsp; ''infinity'' &nbsp; would be a relatively small &nbsp; 123,456,789)
 
 
An example of a sum that can't be expressed &nbsp; (within the rules of this task) &nbsp; is: &nbsp; '''5074'''
<br>(which, &nbsp; of course, &nbsp; isn't the lowest positive sum that can't be expressed).
<br><br>
 
=={{header|11l}}==
{{trans|Kotlin}}
 
<syntaxhighlight lang="11l">-V
<sup>*</sup> &nbsp; (where &nbsp; ''infinity'' &nbsp; would be a relatively small &nbsp; 123,456,789)
NUMBER_OF_DIGITS = 9
<br><br>
THREE_POW_4 = 3 * 3 * 3 * 3
NUMBER_OF_EXPRESSIONS = 2 * THREE_POW_4 * THREE_POW_4
 
T.enum Op
ADD
SUB
JOIN
 
T Expression
code = [Op.ADD] * :NUMBER_OF_DIGITS
 
F inc()
L(i) 0 .< .code.len
.code[i] = Op((Int(.code[i]) + 1) % 3)
I .code[i] != ADD
L.break
 
F toInt()
V value = 0
V number = 0
V sign = 1
L(digit) 1..9
V c = .code[:NUMBER_OF_DIGITS - digit]
I c == ADD {value += sign * number; number = digit; sign = 1}
E I c == SUB {value += sign * number; number = digit; sign = -1}
E {number = 10 * number + digit}
R value + sign * number
 
F String()
V s = ‘’
L(digit) 1 .. :NUMBER_OF_DIGITS
V c = .code[:NUMBER_OF_DIGITS - digit]
I c == ADD
I digit > 1
s ‘’= ‘ + ’
E I c == SUB
s ‘’= ‘ - ’
s ‘’= String(digit)
R s.ltrim(‘ ’)
 
F printe(givenSum)
V expression = Expression()
L 0 .< :NUMBER_OF_EXPRESSIONS
I expression.toInt() == givenSum
print(‘#9’.format(givenSum)‘ = ’expression)
expression.inc()
 
T Stat
DefaultDict[Int, Int] countSum
DefaultDict[Int, Set[Int]] sumCount
F ()
V expression = Expression()
L 0 .< :NUMBER_OF_EXPRESSIONS
V sum = expression.toInt()
.countSum[sum]++
expression.inc()
L(k, v) .countSum
.sumCount[v].add(k)
 
print("100 has the following solutions:\n")
printe(100)
 
V stat = Stat()
V maxCount = max(stat.sumCount.keys())
V maxSum = max(stat.sumCount[maxCount])
print("\n#. has the maximum number of solutions, namely #.".format(maxSum, maxCount))
 
V value = 0
L value C stat.countSum
value++
print("\n#. is the lowest positive number with no solutions".format(value))
 
print("\nThe ten highest numbers that do have solutions are:\n")
L(i) sorted(stat.countSum.keys(), reverse' 1B)[0.<10]
printe(i)</syntaxhighlight>
 
{{out}}
<pre>
100 has the following solutions:
 
100 = 1 + 2 + 3 - 4 + 5 + 6 + 78 + 9
100 = 1 + 2 + 34 - 5 + 67 - 8 + 9
100 = 1 + 23 - 4 + 5 + 6 + 78 - 9
100 = 1 + 23 - 4 + 56 + 7 + 8 + 9
100 = 12 + 3 + 4 + 5 - 6 - 7 + 89
100 = 12 + 3 - 4 + 5 + 67 + 8 + 9
100 = 12 - 3 - 4 + 5 - 6 + 7 + 89
100 = 123 + 4 - 5 + 67 - 89
100 = 123 + 45 - 67 + 8 - 9
100 = 123 - 4 - 5 - 6 - 7 + 8 - 9
100 = 123 - 45 - 67 + 89
100 = - 1 + 2 - 3 + 4 + 5 + 6 + 78 + 9
 
9 has the maximum number of solutions, namely 46
 
211 is the lowest positive number with no solutions
 
The ten highest numbers that do have solutions are:
 
123456789 = 123456789
23456790 = 1 + 23456789
23456788 = - 1 + 23456789
12345687 = 12345678 + 9
12345669 = 12345678 - 9
3456801 = 12 + 3456789
3456792 = 1 + 2 + 3456789
3456790 = - 1 + 2 + 3456789
3456788 = 1 - 2 + 3456789
3456786 = - 1 - 2 + 3456789
</pre>
 
=={{header|Ada}}==
Line 39 ⟶ 155:
Between any two consecutive digits, there can be a "+", a "-", or no operator. E.g., the digits "4" and "5" occur in the string as either of the following three substrings: "4+5", "4-5", or "45". For the first digit, we only have two choices: "+1" (written as "1"), and "-1". This makes 2*3^8 (two times (three to the power of eight)) different strings. Essential is the generic function Eval in the package Sum_To calls the procedure Callback for each such string Str, with the number Int holding the sum corresponding to the evaluation of Str. The second generic procedure Print is for convenience. If the Sum fits the condition, i.e., if Print_If(Sum, Number), then Print writes Sum = Str to the output.
 
<langsyntaxhighlight Adalang="ada">package Sum_To is
generic
Line 50 ⟶ 166:
procedure Print(S: String; Sum: Integer);
 
end Sum_To;</langsyntaxhighlight>
 
The implementation of Eval follows the observation above: Eval calls Rec_Eval with the initial string "1" and "-1". For each call, Rec_Eval recursively evaluates a ternary tree with 3^8 leafs. At each leaf, Rec_Eval calls Callback. The implementation of Print is straightforward.
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Containers.Ordered_Maps;
 
package body Sum_To is
Line 93 ⟶ 209:
end Print;
end Sum_To;</langsyntaxhighlight>
 
===The First Subtask===
Line 99 ⟶ 215:
Given the package Sum_To, the solution to the first subtask (print all solution for the sum 100) is trivial: Eval_100 calls Print_100 for all 2*3^8 strings, and Print_100 writes the output if the sum is equal to 100.
 
<langsyntaxhighlight Adalang="ada">with Sum_To;
 
procedure Sum_To_100 is
Line 108 ⟶ 224:
begin
Eval_100;
end Sum_To_100;</langsyntaxhighlight>
 
{{out}}
Line 128 ⟶ 244:
For the three other subtasks, we maintain an ordered map of sums (as the keys) and counters for the number of solutions (as the elements). The procedure Generate_Map generates the Map by calling the procedure Insert_Solution for all 2*3^8 solutions. Finding (1) the sum with the maximal number of solutions, (2) the first sum>=0 without a solution and (3) the ten largest sums with a solution (extra credit) are done by iterating this map.
 
<langsyntaxhighlight Adalang="ada">with Sum_To, Ada.Containers.Ordered_Maps, Ada.Text_IO;
use Ada.Text_IO;
 
Line 194 ⟶ 310:
end loop;
New_Line;
end Three_others;</langsyntaxhighlight>
 
{{out}}
Line 206 ⟶ 322:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer b, i, j, k, l, p, s, z;
index r, w;
 
Line 267 ⟶ 383:
break;
}
}</langsyntaxhighlight>
{{Out}}
<pre>123-45-67+89
Line 295 ⟶ 411:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN
# find the numbers the string 123456789 ( with "+/-" optionally inserted #
# before each digit ) can generate #
Line 322 ⟶ 438:
# we don't distinguish between strings starting "+1" and starting " 1" #
FOR s1 FROM -1 TO 0 DO
sum string[ 1 ] := sign char[ s1 ];
FOR s2 FROM -1 TO 1 DO
sum string[ 3 ] := sign char[ s2 ];
FOR s3 FROM -1 TO 1 DO
sum string[ 5 ] := sign char[ s3 ];
FOR s4 FROM -1 TO 1 DO
sum string[ 7 ] := sign char[ s4 ];
FOR s5 FROM -1 TO 1 DO
sum string[ 9 ] := sign char[ s5 ];
FOR s6 FROM -1 TO 1 DO
sum string[ 11 ] := sign char[ s6 ];
FOR s7 FROM -1 TO 1 DO
sum string[ 13 ] := sign char[ s7 ];
FOR s8 FROM -1 TO 1 DO
sum string[ 15 ] := sign char[ s8 ];
FOR s9 FROM -1 TO 1 DO
sum string[ 17 ] := sign char[ s9 ];
INT number := 0;
INT part := IF s1 < 0 THEN -1 ELSE 1 FI;
IF s2 = 0 THEN part *:= 10 +:= 2 * SIGN part ELSE number +:= part; part := 2 * s2 FI;
IF s3 = 0 THEN part *:= 10 +:= 3 * SIGN part ELSE number +:= part; part := 3 * s3 FI;
IF s4 = 0 THEN part *:= 10 +:= 4 * SIGN part ELSE number +:= part; part := 4 * s4 FI;
IF s5 = 0 THEN part *:= 10 +:= 5 * SIGN part ELSE number +:= part; part := 5 * s5 FI;
IF s6 = 0 THEN part *:= 10 +:= 6 * SIGN part ELSE number +:= part; part := 6 * s6 FI;
IF s7 = 0 THEN part *:= 10 +:= 7 * SIGN part ELSE number +:= part; part := 7 * s7 FI;
IF s8 = 0 THEN part *:= 10 +:= 8 * SIGN part ELSE number +:= part; part := 8 * s8 FI;
IF s9 = 0 THEN part *:= 10 +:= 9 * SIGN part ELSE number +:= part; part := 9 * s9 FI;
number +:= part;
IF number >= LWB solutions IF AND number ><= LWBUPB solutions THEN
solutions[ number ] +:= ";" AND+ numbersum <= UPB solutionsstring;
count [ THENnumber ] +:= 1
solutions[ number ] +:= ";" + sum stringFI;
BOOL inserted count [ number ] +:= 1FALSE;
FOR l pos FROM LWB largest TO UPB largest FI;WHILE NOT inserted DO
IF number > largest[ l pos BOOL] inserted := FALSE;THEN
# found a FORnew llarger posnumber FROM LWB largest TO UPB largest WHILE NOT inserted DO#
FOR m pos FROM UPB largest BY IF-1 number > largest[TO l pos ]+ 1 THENDO
largest [ m #pos found] a:= newlargest larger number # [ m pos - 1 ];
largest FORcount[ m pos FROM] UPB:= largest BYcount[ -1 TO lm pos +- 1 DO]
largest [ m pos ] := largest [ m pos - 1 ]OD;
largest largest count[ ml pos ] := largest count[ m pos - 1 ]number;
largest count[ l pos ] := OD1;
largest [ l pos ]inserted := number;TRUE
ELIF number = largest count[ l pos ] := 1;THEN
# have another way of generating this number inserted := TRUE#
largest ELIF number = largestcount[ l pos ] THEN+:= 1;
inserted := # have another way of generating this number #TRUE
largest count[ l pos ] +:= 1;FI
inserted := TRUEOD
FI
OD
OD
OD
OD
OD
OD
OD
OD
OD
OD
OD
OD;
 
Line 407 ⟶ 521:
FI
OD;
print( ( whole( number with max, 0 ), " has the maximum number of solutions: ", whole( max solutions, 0 ), newline ) );
print( ( whole( max solutions, 0 ), newline ) );
# find the smallest positive number that has no solutions #
BOOL have solutions := TRUE;
Line 425 ⟶ 540:
print( ( newline ) )
 
END</lang>
</syntaxhighlight>
{{out}}
<pre>
Line 450 ⟶ 566:
{{Trans|JavaScript}}
AppleScript is essentially out of its depth at this scale. The first task (number of distinct paths to 100) is accessible within a few seconds. Subsequent tasks, however, terminate only (if at all) after impractical amounts of time. Note the contrast with the lighter and more optimised JavaScript interpreter, which takes less than half a second to return full results for all the listed tasks.
<langsyntaxhighlight AppleScriptlang="applescript">use framework "Foundation" -- for basic NSArray sort
 
property pSigns : {1, 0, -1} --> ( + | unsigned | - )
Line 763 ⟶ 879:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<pre>Sums to 100:
Line 781 ⟶ 897:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">output:=""
for k, v in (sum2num(100))
output .= k "`n"
Line 836 ⟶ 952:
DllCall("msvcrt.dll\" v, "Int64", value, "Str", s, "UInt", OutputBase, "CDECL")
return s
}</langsyntaxhighlight>
{{out}}
<pre>
Line 862 ⟶ 978:
{{trans|Fortran IV}}
Awk is a weird language: there are no integers, no switch-case (in the standard language version), programs are controlled by data flow, the interpreter speed is moderate. The advantage of Awk are associative arrays, used here for counting how many times we get the same sum as the result of calculations.
<syntaxhighlight lang="awk">#
<lang AWK>#
# RossetaCode: Sum to 100, AWK.
#
Line 968 ⟶ 1,084:
limit = best
}
}</langsyntaxhighlight>
{{Out}}
<pre>Show all solutions that sum to 100
Line 1,011 ⟶ 1,127:
{{Works with|Microsoft Visual Studio|2015}}
Warning: '''this version requires at least four byte integers.'''
<langsyntaxhighlight Clang="c">/*
* RossetaCode: Sum to 100, C99, an algorithm using ternary numbers.
*
Line 1,146 ⟶ 1,262:
return 0;
}</langsyntaxhighlight>
{{Out}}
<pre>
Line 1,193 ⟶ 1,309:
{{Works with|GCC|5.1}}
Warning: '''this program needs at least four byte integers'''.
<langsyntaxhighlight Clang="c">/*
* RossetaCode: Sum to 100, C11, MCU friendly.
*
Line 1,278 ⟶ 1,394:
return 0;
}</langsyntaxhighlight>
{{Out}}
<pre>Show all solutions that sum to 100
Line 1,318 ⟶ 1,434:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,444 ⟶ 1,560:
return left;
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,481 ⟶ 1,597:
{{Works with|Microsoft Visual Studio|2010}}
For each expression of sum s, there is at least one expression whose sum is -s. If the sum s can be represented by n expressions, the sum -s can also be represented by n expressions. The change of all signs in an expression change the sign of the sum of this expression. For example, -1+23-456+789 has the opposite sign than +1-23+456-789. Therefore only the positive sum with the maximum number of solutions is shown. The program does not check uniqueness of this sum. We can easily check (modifying the program) that: sum 9 has 46 solutions; sum -9 has 46 solutions; any other sum has less than 46 solutions.
<syntaxhighlight lang="cpp">/*
<lang Cpp>/*
* RossetaCode: Sum to 100, C++, STL, OOP.
* Works with: MSC 16.0 (MSVS2010); GCC 5.1 (use -std=c++11 or -std=c++14 etc.).
Line 1,591 ⟶ 1,707:
 
return 0;
}</langsyntaxhighlight>
{{Out}}
<pre>
Line 1,632 ⟶ 1,748:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun f (lst &optional (sum 100) (so-far nil))
"Takes a list of digits as argument"
(if (null lst)
Line 1,653 ⟶ 1,769:
(parse-integer (format nil "~{~d~}" lst)) ))
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,676 ⟶ 1,792:
=={{header|D}}==
{{Trans|Java}}
<langsyntaxhighlight Dlang="d">import std.stdio;
 
void main() {
Line 1,828 ⟶ 1,944:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,869 ⟶ 1,985:
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Sum_to_100#Pascal Pascal].
 
=={{header|EasyLang}}==
{{trans|C}}
<syntaxhighlight>
ADD = 0
SUB = 1
nexpr = 13122 - 1
len f[] nexpr + 1
arrbase f[] 0
#
func evaluate code .
power = 1
for k = 9 downto 1
numb += power * k
m = code mod 3
if m = ADD
value += numb
numb = 0
power = 1
elif m = SUB
value -= numb
numb = 0
power = 1
else
power *= 10
.
code = code div 3
.
return value
.
proc init . .
for i = 0 to nexpr
f[i] = evaluate i
.
.
call init
proc out code . .
a = 19683
b = 6561
for k = 1 to 9
h = code mod a div b
if h = ADD
if k > 1
s$ &= "+"
.
elif h = SUB
s$ &= "-"
.
a = b
b = b div 3
s$ &= strchar (48 + k)
.
print evaluate code & " = " & s$
.
print "Show all solutions that sum to 100\n"
for i = 0 to nexpr
if f[i] = 100
out i
.
.
print "\nShow the sum that has the maximum number of solutions\n"
for i = 0 to nexpr
test = f[i]
if test > 0
ntest = 0
for j = 0 to nexpr
if f[j] = test
ntest += 1
.
.
if ntest > nbest
best = test
nbest = ntest
.
.
.
print best & " has " & nbest & " solutions"
print "\nShow the lowest positive number that can't be expressed\n"
for i = 0 to 123456789
for j = 0 to nexpr
if i = f[j]
break 1
.
.
if j > nexpr
break 1
.
.
print i
print "\nShow the ten highest numbers that can be expressed\n"
limit = 123456789 + 1
for i = 1 to 10
best = 0
for j = 0 to nexpr
test = f[j]
if test < limit and test > best
best = test
.
.
for j = 0 to nexpr
if f[j] = best
out j
.
.
limit = best
.
</syntaxhighlight>
{{out}}
<pre>
Show all solutions that sum to 100
 
100 = 1+2+3-4+5+6+78+9
100 = 1+2+34-5+67-8+9
100 = 1+23-4+5+6+78-9
100 = 1+23-4+56+7+8+9
100 = 12+3+4+5-6-7+89
100 = 12+3-4+5+67+8+9
100 = 12-3-4+5-6+7+89
100 = 123+4-5+67-89
100 = 123+45-67+8-9
100 = 123-4-5-6-7+8-9
100 = 123-45-67+89
100 = -1+2-3+4+5+6+78+9
 
Show the sum that has the maximum number of solutions
 
9 has 46 solutions
 
Show the lowest positive number that can't be expressed
 
211
 
Show the ten highest numbers that can be expressed
 
123456789 = 123456789
23456790 = 1+23456789
23456788 = -1+23456789
12345687 = 12345678+9
12345669 = 12345678-9
3456801 = 12+3456789
3456792 = 1+2+3456789
3456790 = -1+2+3456789
3456788 = 1-2+3456789
3456786 = -1-2+3456789
</pre>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Sum do
def to(val) do
generate
Line 1,916 ⟶ 2,177:
Sum.max_solve
Sum.min_solve
Sum.highest_sums</langsyntaxhighlight>
 
{{out}}
Line 1,938 ⟶ 2,199:
3456788, 3456786]
</pre>
 
 
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
(*
Generate the data set
Line 1,961 ⟶ 2,220:
yield! fn -1 2 0 -1 "-1"
}
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="fsharp">
N |> Seq.filter(fun n->n.g=100) |> Seq.iter(fun n->printfn "%s" n.n)
</syntaxhighlight>
</lang>
<pre>
1+2+3-4+5+6+78+9
Line 1,980 ⟶ 2,239:
-1+2-3+4+5+6+78+9
</pre>
<langsyntaxhighlight lang="fsharp">
let n,g = N |> Seq.filter(fun n->n.g>=0) |> Seq.countBy(fun n->n.g) |> Seq.maxBy(snd)
printfn "%d has %d solutions" n g
</syntaxhighlight>
</lang>
<pre>
9 has 46 solutions
</pre>
<langsyntaxhighlight lang="fsharp">
match N |> Seq.filter(fun n->n.g>=0) |> Seq.distinctBy(fun n->n.g) |> Seq.sortBy(fun n->n.g) |> Seq.pairwise |> Seq.tryFind(fun n->(snd n).g-(fst n).g > 1) with
|Some(n) -> printfn "least non-value is %d" ((fst n).g+1)
|None -> printfn "No non-values found"
</syntaxhighlight>
</lang>
<pre>
least non-value is 211
</pre>
<langsyntaxhighlight lang="fsharp">
N |> Seq.filter(fun n->n.g>=0) |> Seq.distinctBy(fun n->n.g) |> Seq.sortBy(fun n->(-n.g)) |> Seq.take 10 |> Seq.iter(fun n->printfn "%d" n.g )
</syntaxhighlight>
</lang>
<pre>
123456789
Line 2,014 ⟶ 2,273:
{{works with|Gforth|0.7.3}}
This solution uses <code>EVALUATE</code> on a string buffer to compute the sum. Given the copious string manipulations, <code>EVALUATE</code>, and the large byte-array used to keep sum counts, this implementation is optimized neither for speed nor for memory. On my machine it runs in about 3.8 seconds, compared to the speed-optimized C solution which runs in about 0.005 seconds.
<langsyntaxhighlight Forthlang="forth">CREATE *OPS CHAR + C, CHAR - C, CHAR # C,
CREATE 0OPS CHAR - C, CHAR # C,
CREATE BUFF 43 C, 43 CHARS ALLOT
Line 2,065 ⟶ 2,324:
: .SOLUTIONS cr ." Solutions that sum to 100:"
BEGIN SYNTH EVALUATE REPORT INDX+ UNTIL ;
: SUM100 .SOLUTIONS .MOST .CANT .BEST cr ;</langsyntaxhighlight>
{{Out}}
Note: must start Gforth with a larger-than-default dictionary size:
Line 2,224 ⟶ 2,483:
=== Fortran 95 ===
{{works with|gfortran|5.1}}
<langsyntaxhighlight Fortranlang="fortran">! RossetaCode: Sum to 100, Fortran 95, an algorithm using ternary numbers.
!
! Find solutions to the 'sum to one hundred' puzzle.
Line 2,354 ⟶ 2,613:
ivalue = ievaluate(icode)
print *, ivalue, ' = ', s
end</langsyntaxhighlight>
{{Out}}
<pre>
Line 2,395 ⟶ 2,654:
 
===Batch processing===
By the simple expedient of storing all evaluations in an array (which is not so large) and then sorting the array, the required results appear in a blink. The source is essentially F77 except for the usage of an array assignment of OP = -1, writing out the highest ten results via an array expression instead of a DO-loop, array OPNAME extending from -1 to +1, a CYCLE statement rather than a GO TO, and the use of the I0 format code. Subroutine DEBLANK is straightforward, and omitted. It was only to remove spaces from the text of the expression. Reading the expression from right to left is about as picky as left-to-right. <langsyntaxhighlight Fortranlang="fortran"> INTEGER NDIGITS,TARGET !Document the shape.
PARAMETER (NDIGITS = 9, TARGET = 100)
INTEGER*1 OP(NDIGITS) !A set of operation codes, associated with each digit.
Line 2,501 ⟶ 2,760:
WRITE (MSG,322) VALUE(LOOP - 9:LOOP) !Surely LOOP > 9.
322 FORMAT ("The ten highest sums: ",10(I0:","))
END !That was fun!</langsyntaxhighlight>
 
Results:
Line 2,524 ⟶ 2,783:
The lowest positive sum that can't be expressed is 211
The ten highest sums: 3456786,3456788,3456790,3456792,3456801,12345669,12345687,23456788,23456790,123456789
</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">
#define PERM 13122
 
'Between any two adjacent digits there can be nothing, a plus, or a minus.
'And the first term can only be + or -
'This is equivalent to an eight-digit base 3 number. We therefore only need
'to consider 2*3^8=13122 possibilities
 
function ndig(n as uinteger) as uinteger
return 1+int(log(n+0.5)/log(10))
end function
 
function calculate( byval n as uinteger, outstr as string ) as integer
'calculates the sum given by one of the 13122 possibilities, as well as
'storing the equation itself as a string
outstr = "9"
dim as integer ret = 0, curr = 9
dim as boolean firstplus = n>=PERM/2
for i as integer = 8 to 1 step -1
select case n mod 3
case 0 'no symbol means we just prepend the next number
curr += i*10^(ndig(curr))
case 1 'addition: add the current term to the running sum, and clear the current term
ret += curr
curr = i
outstr = " + " + outstr
case 2 'subtraction: minus the current term from the running sum, and clear the current term
ret -= curr
curr = i
outstr = " - " + outstr
end select
outstr = str(i) + outstr 'prepend the previous digit to the string
n \= 3 'get next symbol
next i
if firstplus = 0 then
outstr = "-"+outstr
ret -= curr
else
ret += curr
end if
outstr = outstr + " = " + str(ret)
return ret
end function
 
'calculate and store all 13122 solutions
dim as string eqn
dim as integer n, sum(0 to PERM-1), curr
for n = 0 to PERM-1
curr = calculate(n, eqn)
sum(n) = curr
if curr = 100 then print eqn
next n
 
'what is the sum that has the most solutions?
dim as integer champ = 0, cnum = 0, i, j, acc
for i = 0 to PERM-1
acc = 0
for j = i to PERM-1
if sum(j) = sum(i) then acc+=1
next j
if acc>cnum then
champ = sum(i)
cnum=acc
end if
next i
print "The sum with the most occurrences is ";champ;", which shows up ";cnum;" times."
 
'what is the first nonnegative number that has no solution
for i = 0 to 123456788
for j = 0 to PERM-1
if sum(j)=i then goto nexti
next j
print "The first number that has no solution is ";i
exit for
nexti:
next i
 
'What are the ten highest numbers?
'this partially destroys the information in the array, but who cares?
'We're almost done and these excessive questionnaires are the worst
'and most boring part of Rosetta Code tasks
print "The ten highest numbers attainable are:"
champ = 0
for i = 1 to 10
for j = 0 to PERM-1
if sum(j)>sum(champ) then champ = j
next j
calculate(champ, eqn)
print eqn
sum(champ) = -9999 'overwrite to stop this being found a second time
next i</syntaxhighlight>
{{out}}<pre>
-1 + 2 - 3 + 4 + 5 + 6 + 78 + 9 = 100
123 + 45 - 67 + 8 - 9 = 100
123 + 4 - 5 + 67 - 89 = 100
123 - 45 - 67 + 89 = 100
123 - 4 - 5 - 6 - 7 + 8 - 9 = 100
12 + 3 + 4 + 5 - 6 - 7 + 89 = 100
12 + 3 - 4 + 5 + 67 + 8 + 9 = 100
12 - 3 - 4 + 5 - 6 + 7 + 89 = 100
1 + 23 - 4 + 56 + 7 + 8 + 9 = 100
1 + 23 - 4 + 5 + 6 + 78 - 9 = 100
1 + 2 + 34 - 5 + 67 - 8 + 9 = 100
1 + 2 + 3 - 4 + 5 + 6 + 78 + 9 = 100
The sum with the most occurrences is 9, which shows up 46 times.
The first number that has no solution is 211
The ten highest numbers attainable are:
123456789 = 123456789
1 + 23456789 = 23456790
-1 + 23456789 = 23456788
12345678 + 9 = 12345687
12345678 - 9 = 12345669
12 + 3456789 = 3456801
1 + 2 + 3456789 = 3456792
-1 + 2 + 3456789 = 3456790
1 - 2 + 3456789 = 3456788
-1 - 2 + 3456789 = 3456786
</pre>
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
digits = array[1 to 9]
opList = makeArray[[8], ["", " + ", " - "]]
Line 2,576 ⟶ 2,956:
for i = size-10 to size-1
println[freq@i@0]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,610 ⟶ 2,990:
=={{header|Go}}==
{{trans|C}}
<langsyntaxhighlight Golang="go">package main
 
import (
Line 2,759 ⟶ 3,139:
fmt.Println(e)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,796 ⟶ 3,176:
 
=={{header|Haskell}}==
<syntaxhighlight lang Haskell="haskell">import DataControl.MonoidMonad ((<>)replicateM)
import Data.Ord (comparing)
import Control.Arrow ((&&&))
import Data.Char (intToDigit)
import ControlData.Monad (replicateM)List
( find,
import Data.List (nub, group, sort, sortBy, find, intercalate)
group,
intercalate,
nub,
sort,
sortBy,
)
import Data.Monoid ((<>))
import Data.Ord (comparing)
 
data Sign
Line 2,808 ⟶ 3,194:
| Minus
deriving (Eq, Show)
 
------------------------ SUM TO 100 ----------------------
 
universe :: [[(Int, Sign)]]
universe =
zip [1 .. 9] <$>
<$> filter
filter ((/= Plus) . head) (replicateM 9 [Unsigned, Plus, Minus])
((/= Plus) . head)
(replicateM 9 [Unsigned, Plus, Minus])
 
allNonNegativeSums :: [Int]
allNonNegativeSums = sort $ filter (>= 0) (asSum <$> universe)
sort $
filter
(>= 0)
(asSum <$> universe)
 
uniqueNonNegativeSums :: [Int]
Line 2,822 ⟶ 3,216:
asSum :: [(Int, Sign)] -> Int
asSum xs =
n +
+ ( case s of
[] -> 0
_ -> read s :: Int)
)
where
(n, s) = foldr readSign (0, []) xs
readSign :: (Int, Sign) -> (Int, String) -> (Int, String)
(Int, Sign) ->
(Int, String) ->
(Int, String)
readSign (i, x) (n, s)
| x == Unsigned = (n, intToDigit i : s)
| otherwise =
( ( case x of
Plus -> (+)
_ -> (-))
)
n
(read (show i <> s) :: Int),
, [])
)
 
asString :: [(Int, Sign)] -> String
Line 2,845 ⟶ 3,245:
| x == Unsigned = intToDigit i : s
| otherwise =
( case x of
Plus -> " +"
_ -> " -") <>
[intToDigit i] <>)
s <> [intToDigit i]
<> s
 
--------------------------- TEST -------------------------
main :: IO ()
main =
putStrLn $
unlines
[ "Sums to 100:",
unlines
, unlines (asString <$> filter ((100 ==) . asSum) universe)
(asString <$> filter ((100 ==) . asSum) universe),
, "\n10 commonest sums (sum, number of routes to it):"
"\n10 commonest sums (sum, number of routes to it):",
, show
((head &&& length) <$>show
take 10 (sortBy (flip (comparing length),) (group<$> allNonNegativeSums))head <*> length)
, "\nFirst positive integer not expressible as a sum of this<$> kind:"take
10
, maybeReport (find (uncurry (/=)) (zip [0 ..] uniqueNonNegativeSums))
( sortBy
, "\n10 largest sums:"
, show (take 10 (sortBy (flip compare)(comparing uniqueNonNegativeSumslength))
(group allNonNegativeSums)
]
)
),
"\nFirst positive integer not expressible "
<> "as a sum of this kind:",
maybeReport
( find
(uncurry (/=))
(zip [0 ..] uniqueNonNegativeSums)
),
"\n10 largest sums:",
show
( take
10
( sortBy
(flip compare)
uniqueNonNegativeSums
)
)
]
where
maybeReport ::
:: Show a =>
=> Maybe (a, b) -> String
String
maybeReport (Just (x, _)) = show x
maybeReport _ = "No gaps found"</langsyntaxhighlight>
{{Out}}
(Run in Atom editor, through Script package)
Line 2,902 ⟶ 3,324:
Since J has no verb precedence, -1-2 would evaluate to 1 and not to -3. That's why I decided to multiply each of the partitions of '123456789' (like '123','45', '6', '78', '9') with each possible +1/-1 vectors of length 9 (like 1 1 -1 1 -1 -1 1 1 -1) and to add up the results. This leads to 512*256 results, that of course include a lot of duplicates. To use directly ~. (nub) on the 512x256x9 vector is very slow and that's why I computed a sort of a hash to use it to get only the unique expressions. The rest is trivial - I check which expressions add up to 100; sort the sum vector and find the longest sequence ot repeating sums; get the 10 largest sums and finnaly check which sum differs with more then 1 from the previous one.
 
<syntaxhighlight lang="j">
<lang J>
p =: ,"2".>(#: (+ i.)2^8) <;.1 '123456789'
m =. (9$_1x)^"1#:i.2^9
Line 2,913 ⟶ 3,335:
'Ten largest:';,.(->:i.10){ss
'First not expressible:';>:pos{~ 1 i.~ 1<|2-/\pos
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,955 ⟶ 3,377:
{{trans|C++}}
For each expression of sum s, there is at least one expression whose sum is -s. If the sum s can be represented by n expressions, the sum -s can also be represented by n expressions. The change of all signs in an expression change the sign of the sum of this expression. For example, -1+23-456+789 has the opposite sign than +1-23+456-789. Therefore only the positive sum with the maximum number of solutions is shown. The program does not check uniqueness of this sum. We can easily check (modifying the program) that: sum 9 has 46 solutions; sum -9 has 46 solutions; any other sum has less than 46 solutions.
<syntaxhighlight lang="java">/*
<lang Java>/*
* RossetaCode: Sum to 100, Java 8.
*
Line 3,122 ⟶ 3,544:
}
}
}</langsyntaxhighlight>
{{Out}}
<pre>Show all solutions that sum to 100
Line 3,163 ⟶ 3,585:
===ES5===
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 3,389 ⟶ 3,811:
show(take(10, uniqueNonNegativeSums.sort(flip(compare))))
].join('\n') + '\n';
})();</langsyntaxhighlight>
 
{{Out}}
Line 3,426 ⟶ 3,848:
===ES6===
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 3,609 ⟶ 4,031:
show(take(10, uniqueNonNegativeSums.sort(flip(compare))))
].join('\n') + '\n';
})();</langsyntaxhighlight>
 
{{Out}}
Line 3,647 ⟶ 4,069:
{{Works with|Microsoft Windows Script Host}}
{{Trans|AWK}}
<langsyntaxhighlight lang="javascript">SumTo100();
 
function SumTo100()
Line 3,769 ⟶ 4,191:
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>Show all solutions that sum to 100
Line 3,811 ⟶ 4,233:
 
'''All possible sums'''
<langsyntaxhighlight lang="jq"># Generate a "sum" in the form: [I, 1, X, 2, X, 3, ..., X, n] where I is "-" or "", and X is "+", "-", or ""
def generate(n):
def pm: ["+"], ["-"], [""];
Line 3,831 ⟶ 4,253:
# Pretty-print a "sum", e.g. ["",1,"+", 2] => 1 + 2
def pp: map(if . == "+" or . == "-" then " " + . else tostring end) | join("");
</syntaxhighlight>
</lang>
'''Solutions to "Sum to 100" problem'''
<langsyntaxhighlight lang="jq">generate(9) | select(addup == 100) | pp</langsyntaxhighlight>
{{out}}
<pre>
Line 3,853 ⟶ 4,275:
For brevity, we define an efficient function for computing a histogram in the form of a JSON object, and
a helper function for identifying the values with the n highest frequencies.
<langsyntaxhighlight lang="jq">def histogram(s): reduce s as $x ({}; ($x|tostring) as $k | .[$k] += 1);
 
# Emit an array of [ value, frequency ] pairs
Line 3,861 ⟶ 4,283:
| sort_by(.[1])
| .[(length-n):]
| reverse ; </langsyntaxhighlight>
 
'''Maximum number of solutions'''
<langsyntaxhighlight lang="jq">histogram(generate(9) | addup | select(.>0)) | greatest(1)</langsyntaxhighlight>
{{out}}
<pre>[["9",46]]</pre>
 
'''Ten most frequent sums'''
<langsyntaxhighlight lang="jq">histogram(generate(9) | addup | select(.>0)) | greatest(1)</langsyntaxhighlight>
{{out}}
<pre>[["9",46],["27",44],["1",43],["21",43],["15",43],["45",42],["3",41],["5",40],["7",39],["17",39]]</pre>
 
'''First unsolvable'''
<langsyntaxhighlight lang="jq">def first_missing(s):
first( foreach s as $i (null;
if . == null or $i == . or $i == .+1 then $i else [.+1] end;
select(type == "array") | .[0]));
 
first_missing( [generate(9) | addup | select(.>0) ] | unique[])</langsyntaxhighlight>
{{out}}
211
 
'''Ten largest sums'''
<langsyntaxhighlight lang="jq">[generate(9) | addup | select(.>0)] | unique | .[(length-10):]</langsyntaxhighlight>
{{out}}
[3456786,3456788,3456790,3456792,3456801,12345669,12345687,23456788,23456790,123456789]
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Printf, IterTools, DataStructures
expr(p::String...)::String = @sprintf("%s1%s2%s3%s4%s5%s6%s7%s8%s9", p...)
Line 3,947 ⟶ 4,369:
println("\nHighest sums representable:")
foreach(println, hsums)
</langsyntaxhighlight>{{out}}
<pre>100 =
1+23-4+56+7+8+9
Line 3,982 ⟶ 4,404:
=={{header|Kotlin}}==
{{trans|C++}}
<langsyntaxhighlight lang="scala">// version 1.1.51
 
class Expression {
Line 4,082 ⟶ 4,504:
println("\nThe ten highest numbers that do have solutions are:\n")
stat.countSum.keys.toIntArray().sorted().reversed().take(10).forEach { Expression.print(it) }
}</langsyntaxhighlight>
 
{{out}}
Line 4,121 ⟶ 4,543:
=={{header|Lua}}==
{{trans|C}}
<langsyntaxhighlight lang="lua">local expressionsLength = 0
function compareExpressionBySum(a, b)
return a.sum - b.sum
Line 4,243 ⟶ 4,665:
end
limit = best
end</langsyntaxhighlight>
{{out}}
<pre>Show all solutions that sum to 100
Line 4,277 ⟶ 4,699:
3456786 = -1-2+3456789</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Defining all possible sums:
<syntaxhighlight lang="mathematica">operations = DeleteCases[Tuples[{"+", "-", ""}, 9], {x_, y__} /; x == "+"];
 
sums = Map[StringJoin[Riffle[#, CharacterRange["1", "9"]]] &, operations];</syntaxhighlight>
<lang Mathematica>operations =
DeleteCases[Tuples[{"+", "-", ""}, 9], {x_, y__} /; x == "+"];
 
sums =
Map[StringJoin[Riffle[#, CharacterRange["1", "9"]]] &, operations];</lang>
 
Sums to 100:
<syntaxhighlight lang="mathematica"> TableForm@Select[sums, ToExpression@# == 100 &] </syntaxhighlight>
 
<lang Mathematica> TableForm@Select[sums, ToExpression@# == 100 &] </lang>
{{out}}
<pre>-1+2-3+4+5+6+78+9
Line 4,304 ⟶ 4,720:
 
Maximum number of solutions:
<langsyntaxhighlight Mathematicalang="mathematica"> MaximalBy[Counts@ToExpression@sums, Identity] </langsyntaxhighlight>
{{out}}
<pre> <|9 -> 46, -9 -> 46|> </pre>
 
First unsolvable:
<langsyntaxhighlight Mathematicalang="mathematica"> pos = Cases[ToExpression@sums, _?Positive];
n = 1; While[MemberQ[pos, n], ++n]; </langsyntaxhighlight>
{{out}}
<pre>211</pre>
 
Ten largest sums:
<langsyntaxhighlight Mathematicalang="mathematica"> {#, ToExpression@#}&/@TakeLargestBy[sums, ToExpression, 10]//TableForm </langsyntaxhighlight>
{{out}}
<pre> 123456789 123456789
Line 4,330 ⟶ 4,746:
=={{header|Modula-2}}==
{{trans|C}}
<langsyntaxhighlight lang="modula2">MODULE SumTo100;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 4,467 ⟶ 4,883:
 
ReadChar
END SumTo100.</langsyntaxhighlight>
{{out}}
<pre>Show all solutions that sum to 100
Line 4,502 ⟶ 4,918:
 
=={{header|Nim}}==
Recursive solution.
<lang Nim>
 
import strutils
<syntaxhighlight 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(", ")</syntaxhighlight>
 
{{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).
 
<syntaxhighlight lang="nim">import strutils
 
var
Line 4,523 ⟶ 5,007:
liS = split(li," ")
for i in liS:
if i.len > 0: result += parseInt(i)
echo "Valeur à atteindre : ",aAtteindre
Line 4,578 ⟶ 5,062:
echo "Plus grandes valeurs pouvant être atteintes :"
for i in 1..10:
echo calcul(plusGrandes[i])," = ",plusGrandes[i]</langsyntaxhighlight>
{{out}}
<pre>Valeur à atteindre : 100
Line 4,614 ⟶ 5,098:
{{works with|Lazarus}}
{{trans|C}}
<langsyntaxhighlight Pascallang="pascal">{ RossetaCode: Sum to 100, Pascal.
 
Find solutions to the "sum to one hundred" puzzle.
Line 4,739 ⟶ 5,223:
limit := best;
end
end.</langsyntaxhighlight>
{{Out}}
<pre>Show all solutions that sum to 100
Line 4,780 ⟶ 5,264:
=={{header|Perl}}==
{{works with|Perl|5.10}}
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
use warnings;
use strict;
Line 4,841 ⟶ 5,325:
 
say 'Show the ten highest numbers that can be expressed';
say for (sort { $b <=> $a } keys %count)[0 .. 9];</langsyntaxhighlight>
{{Out}}
<pre>Show all solutions that sum to 100
Line 4,875 ⟶ 5,359:
===oneliner version===
The first task posed can be solved simply with (pay attention to doublequotes around the program: adjust for you OS):
<langsyntaxhighlight lang="perl">
perl -E "say for grep{eval $_ == 100} glob '{-,}'.join '{+,-,}',1..9"
</syntaxhighlight>
</lang>
 
While the whole task can be solved by:
<langsyntaxhighlight lang="perl">
perl -MList::Util="first" -E "@c[0..10**6]=(0..10**6);say for grep{$e=eval;$c[$e]=undef if $e>=0;$h{$e}++;eval $_==100}glob'{-,}'.join'{+,-,}',1..9;END{say for(sort{$h{$b}<=>$h{$a}}grep{$_>=0}keys %h)[0],first{defined $_}@c;say for(sort{$b<=>$a}grep{$_>0}keys %h)[0..9]}"
</syntaxhighlight>
</lang>
which outputs
<pre>
Line 4,916 ⟶ 5,400:
Admittedly, categorising them into 3429 bins is slightly more effort, but otherwise I am somewhat bemused by all the applescript/javascript/Haskell shenanegins.<br>
 
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #000000;">javascript_semantics</span>
<span style="color: #008080;">enum</span> <span style="color: #000000;">SUB</span><span style="color: #0000FF;">=-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">NOP</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">ADD</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">evalevaluate</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">tmp</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">op</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">ADD</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
Line 4,941 ⟶ 5,426:
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #008000;">'0'</span><span style="color: #0000FF;">+</span><span style="color: #000000;">i</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s = %d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">res</span><span style="color: #0000FF;">,</span><span style="color: #000000;">evalevaluate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
Line 4,952 ⟶ 5,437:
<span style="color: #008080;">while</span> <span style="color: #008080;">not</span> <span style="color: #000000;">done</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">evalevaluate</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">),</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">getd_index</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">solns</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">k</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">}:</span><span style="color: #7060A8;">appenddeep_copy</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">getd_by_index</span><span style="color: #0000FF;">(</span><span style="color: #000000;">k</span><span style="color: #0000FF;">),</span><span style="color: #000000;">s</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">solns</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">append</span><span style="color: #0000FF;">(</span><span style="color: #000000;">solns</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">deep_copy</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">))</span>
<span style="color: #7060A8;">setd</span><span style="color: #0000FF;">(</span><span style="color: #000000;">r</span><span style="color: #0000FF;">,</span><span style="color: #000000;">solns</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">r</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">and</span> <span style="color: #000000;">maxl</span><span style="color: #0000FF;"><</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">solns</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
Line 4,995 ⟶ 5,481:
<span style="color: #008080;">return</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">highest</span><span style="color: #0000FF;">)<</span><span style="color: #000000;">10</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #000080;font-style:italic;">--DEV named params on builtins need pre-loading...:
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #000000;">top10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">rev</span><span style="color: #0000FF;">:=</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)</span>
--traverse_dict(top10,rev:=1)</span>
<span style="color: #7060A8;">traverse_dict</span><span style="color: #0000FF;">(</span><span style="color: #000000;">top10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #004600;">true</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The 10 highest sums: %v\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">highest</span><span style="color: #0000FF;">})</span>
<!--</langsyntaxhighlight>-->
 
{{Out}}
Line 5,018 ⟶ 5,506:
The lowest positive sum that cannot be expressed: 211
The 10 highest sums: {123456789,23456790,23456788,12345687,12345669,3456801,3456792,3456790,3456788,3456786}
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
L = "23456789",
gen(L,Str),
Exp = parse_term(['1'|Str]),
Exp =:= 100,
println(['1'|Str]).
 
gen(L@[_],Str) => Str = L.
gen([D|Ds],Str) ?=> Str = [D|StrR], gen(Ds,StrR). % no operator
gen([D|Ds],Str) ?=> Str = ['+',D|StrR], gen(Ds,StrR). % insert +
gen([D|Ds],Str) => Str = ['-',D|StrR], gen(Ds,StrR). % insert -
</syntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">#START=6561
#STOPP=19682
#SUMME=100
#BASIS="123456789"
 
Structure TSumTerm
sum.i
ter.s
EndStructure
 
NewList Solutions.TSumTerm()
NewMap SolCount.i()
Dim op.s{1}(8)
Dim b.s{1}(8)
PokeS(@b(),#BASIS)
 
Procedure StripTerm(*p_Term)
If PeekS(*p_Term,1)="+" : PokeC(*p_Term,' ') : EndIf
EndProcedure
 
Procedure.s Triadisch(v)
While v : r$=Str(v%3)+r$ : v/3 : Wend
ProcedureReturn r$
EndProcedure
 
Procedure.i Calc(t$)
While Len(t$)
x=Val(t$) : r+x
If x<0 : s$=Str(x) : Else : s$="+"+Str(x) : EndIf
t$=RemoveString(t$,s$,#PB_String_NoCase,1,1)
Wend
ProcedureReturn r
EndProcedure
 
For n=#START To #STOPP
PokeS(@op(),Triadisch(n))
Term$=""
For i=0 To 8
Select op(i)
Case "0" : Term$+ b(i)
Case "1" : Term$+"+"+b(i)
Case "2" : Term$+"-"+b(i)
EndSelect
Next
AddElement(Solutions()) : Solutions()\sum=Calc(Term$) : StripTerm(@Term$) : Solutions()\ter=Term$
Next
SortStructuredList(Solutions(),#PB_Sort_Ascending,OffsetOf(TSumTerm\sum),TypeOf(TSumTerm\sum))
 
If OpenConsole()
PrintN("Show all solutions that sum to 100:")
ForEach Solutions()
If Solutions()\sum=#SUMME : PrintN(#TAB$+Solutions()\ter) : EndIf
SolCount(Str(Solutions()\sum))+1
Next
ForEach SolCount()
If SolCount()>MaxCount : MaxCount=SolCount() : MaxVal$=MapKey(SolCount()) : EndIf
Next
PrintN("Show the positve sum that has the maximum number of solutions:")
PrintN(#TAB$+MaxVal$+" has "+Str(MaxCount)+" solutions")
If LastElement(Solutions())
MaxVal=Solutions()\sum
PrintN("Show the lowest positive number that can't be expressed:")
For i=1 To MaxVal
If SolCount(Str(i))=0 : PrintN(#TAB$+Str(i)) : Break : EndIf
Next
PrintN("Show the 10 highest numbers that can be expressed:")
For i=1 To 10
PrintN(#TAB$+LSet(Str(Solutions()\sum),9)+" = "+Solutions()\ter)
If Not PreviousElement(Solutions()) : Break : EndIf
Next
EndIf
Input()
EndIf</syntaxhighlight>
{{out}}
<pre>Show all solutions that sum to 100:
123+45-67+8-9
123+4-5+67-89
123-45-67+89
123-4-5-6-7+8-9
12+3+4+5-6-7+89
12+3-4+5+67+8+9
12-3-4+5-6+7+89
1+23-4+56+7+8+9
1+23-4+5+6+78-9
1+2+34-5+67-8+9
1+2+3-4+5+6+78+9
-1+2-3+4+5+6+78+9
Show the positve sum that has the maximum number of solutions:
9 has 46 solutions
Show the lowest positive number that can't be expressed:
211
Show the 10 highest numbers that can be expressed:
123456789 = 123456789
23456790 = 1+23456789
23456788 = -1+23456789
12345687 = 12345678+9
12345669 = 12345678-9
3456801 = 12+3456789
3456792 = 1+2+3456789
3456790 = -1+2+3456789
3456788 = 1-2+3456789
3456786 = -1-2+3456789
</pre>
 
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">from itertools import product, islice
 
 
Line 5,072 ⟶ 5,679:
max_solve()
min_solve()
highest_sums()</langsyntaxhighlight>
 
{{out}}
Line 5,094 ⟶ 5,701:
Mostly the same algorithm, but both shorter and faster.
 
<langsyntaxhighlight lang="python">import itertools
from collections import defaultdict, Counter
 
Line 5,122 ⟶ 5,729:
print("Ten highest sums")
for k in reversed(v[-10:]):
print(k)</langsyntaxhighlight>
 
{{out}}
Line 5,155 ⟶ 5,762:
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket
 
(define list-partitions
Line 5,221 ⟶ 5,828:
(check-equal? (partition-digits-to-numbers '()) '(()))
(check-equal? (partition-digits-to-numbers '(1)) '((1)))
(check-equal? (partition-digits-to-numbers '(1 2)) '((1 2) (12))))</langsyntaxhighlight>
 
{{out}}
Line 5,249 ⟶ 5,856:
{{works with|Rakudo|2017.03}}
 
<syntaxhighlight lang="raku" perl6line>my $sum = 100;
my $N = 10;
my @ops = ['-', ''], |( [' + ', ' - ', ''] xx 8 );
Line 5,267 ⟶ 5,874:
}
 
.say for :$max-solutions, :$first-unsolvable, "$N largest sums:", n-largest-sums($N);</langsyntaxhighlight>
{{out}}
<pre>12 solutions for sum 100:
Line 5,297 ⟶ 5,904:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/*REXX pgm solves a puzzle: using the string 123456789, insert - or + to sum to 100*/
parse arg LO HI . /*obtain optional arguments from the CL*/
if LO=='' | LO=="," then LO= 100 /*Not specified? Then use the default.*/
Line 5,347 ⟶ 5,954:
if LO\==00 then say right(y, 9) 'solution's(#, , " ") 'found for' ,
right(j, length(HI) ) left('', #, "─")
return # /*return the number of solutions found.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 5,371 ⟶ 5,978:
 
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">digits = ("1".."9").to_a
{{trans|Elixir}}
<lang ruby>def gen_expr
x = ['-', '']
y = ['+', '-', '']
x.product(y,y,y,y,y,y,y,y)
.map do |a,b,c,d,e,f,g,h,i|
"#{a}1#{b}2#{c}3#{d}4#{e}5#{f}6#{g}7#{h}8#{i}9"
end
end
 
ar = ["+", "-", ""].repeated_permutation(digits.size).filter_map do |op_perm|
def sum_to(val)
str = op_perm.zip(digits).join
gen_expr.map{|expr| [eval(expr), expr]}.select{|v,expr| v==val}.each{|x| p x}
str unless str.start_with?("+")
end
res = ar.group_by{|str| eval(str)}
 
puts res[100] , ""
def max_solve
n,size = gen_expr.group_by{|expr| eval(expr)}
.select{|val,_| val>=0}
.map{|val,exprs| [val, exprs.size]}
.max_by{|_,size| size}
puts "sum of #{n} has the maximum number of solutions : #{size}"
end
 
sum, solutions = res.max_by{|k,v| v.size}
def min_solve
puts "#{sum} has #{solutions.size} solutions.", ""
solves = gen_expr.group_by{|expr| eval(expr)}
n = 0.step{|i| break i unless solves[i]}
puts "lowest positive sum that can't be expressed : #{n}"
end
 
no_solution = (1..).find{|n| res[n] == nil}
def highest_sums(n=10)
puts "#{no_solution} is the lowest positive number without a solution.", ""
n = gen_expr.map{|expr| eval(expr)}.uniq.sort.reverse.take(n)
puts "highest sums : #{n}"
end
 
puts res.max(10).map{|pair| pair.join(": ")}
sum_to(100)
</syntaxhighlight>
max_solve
{{out}}
min_solve
<pre>
highest_sums</lang>
-1+2-3+4+5+6+78+9
1+2+3-4+5+6+78+9
1+2+34-5+67-8+9
1+23-4+5+6+78-9
1+23-4+56+7+8+9
12+3+4+5-6-7+89
12+3-4+5+67+8+9
12-3-4+5-6+7+89
123+4-5+67-89
123+45-67+8-9
123-4-5-6-7+8-9
123-45-67+89
 
9 has 46 solutions.
 
211 is the lowest positive number without a solution.
 
123456789: 123456789
23456790: 1+23456789
23456788: -1+23456789
12345687: 12345678+9
12345669: 12345678-9
3456801: 12+3456789
3456792: 1+2+3456789
3456790: -1+2+3456789
3456788: 1-2+3456789
3456786: -1-2+3456789
</pre>
 
=={{header|Rust}}==
<syntaxhighlight lang="rust">use std::collections::BTreeMap;
use std::fmt;
 
#[derive(Copy, Clone)]
enum Operator {
None,
Plus,
Minus,
}
 
#[derive(Clone)]
struct Expression {
ops: [Operator; 9],
}
 
impl Expression {
fn new() -> Expression {
Expression {
ops: [Operator::None; 9],
}
}
fn sum(&self) -> i32 {
let mut result: i32 = 0;
let mut n: i32 = 0;
let mut p: i32 = 1;
let mut i: usize = 9;
while i > 0 {
n += p * (i as i32);
i -= 1;
match self.ops[i] {
Operator::None => p *= 10,
Operator::Plus => {
p = 1;
result += n;
n = 0;
}
Operator::Minus => {
p = 1;
result -= n;
n = 0;
}
}
}
result += n;
result
}
fn next(&mut self) -> bool {
let mut i: usize = 9;
while i > 0 {
i -= 1;
match self.ops[i] {
Operator::None => {
self.ops[i] = if i == 0 {
Operator::Minus
} else {
Operator::Plus
};
return true;
}
Operator::Plus => {
self.ops[i] = Operator::Minus;
return true;
}
Operator::Minus => self.ops[i] = Operator::None,
}
}
false
}
}
 
impl fmt::Display for Expression {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for i in 0..9 {
match self.ops[i] {
Operator::None => {}
Operator::Plus => write!(f, "+")?,
Operator::Minus => write!(f, "-")?,
}
write!(f, "{}", i + 1)?;
}
Ok(())
}
}
 
fn main() {
let mut exp = Expression::new();
let mut sums: BTreeMap<i32, Vec<Expression>> = BTreeMap::new();
loop {
sums.entry(exp.sum()).or_insert(Vec::new()).push(exp.clone());
if !exp.next() {
break;
}
}
 
println!("Solutions that sum to 100:");
if let Some(expressions) = sums.get(&100) {
for e in expressions {
println!("100 = {}", e);
}
}
 
let mut max_sum = 0;
let mut max_count = 0;
for (sum, expressions) in &sums {
let count = expressions.len();
if count > max_count {
max_count = count;
max_sum = *sum;
}
}
println!(
"\nThe sum with the greatest number of solutions is {} ({}).",
max_sum, max_count
);
 
let mut n = 1;
while sums.contains_key(&n) {
n += 1;
}
println!(
"\nThe smallest positive number that cannot be expressed is {}.",
n
);
 
println!("\nThe ten highest numbers that can be expressed are:");
for (sum, expressions) in sums.iter().rev().take(10) {
println!("{} = {}", sum, expressions[0]);
}
}</syntaxhighlight>
 
{{out}}
<pre>
Solutions that sum to 100:
[100, "-1+2-3+4+5+6+78+9"]
[100, "1= 123+245-67+38-4+5+6+78+9"]
[100, "1= 123+2+344-5+67-8+9"]89
[100, "1+23= 123-445-67+5+6+78-9"]89
[100, "1+23= 123-4+56+-5-6-7+8+-9"]
[100, "= 12+3+4+5-6-7+89"]
[100, "= 12+3-4+5+67+8+9"]
[100, "= 12-3-4+5-6+7+89"]
[100, "123= 1+423-54+67-89"]56+7+8+9
[100, "123= 1+4523-674+5+6+878-9"]
[100, "123-4= 1+2+34-5-6-7+867-8+9"]
[100, "123= 1+2+3-45-674+5+6+78+89"]9
100 = -1+2-3+4+5+6+78+9
sum of 9 has the maximum number of solutions : 46
 
lowest positive sum that can't be expressed : 211
The sum with the greatest number of solutions is 9 (46).
highest sums : [123456789, 23456790, 23456788, 12345687, 12345669, 3456801, 3456792, 3456790, 3456788, 3456786]
 
The smallest positive number that cannot be expressed is 211.
 
The ten highest numbers that can be expressed are:
123456789 = 123456789
23456790 = 1+23456789
23456788 = -1+23456789
12345687 = 12345678+9
12345669 = 12345678-9
3456801 = 12+3456789
3456792 = 1+2+3456789
3456790 = -1+2+3456789
3456788 = 1-2+3456789
3456786 = -1-2+3456789
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object SumTo100 {
def main(args: Array[String]): Unit = {
val exps = expressions(9).map(str => (str, eval(str)))
Line 5,462 ⟶ 6,225:
case _ => ""
}
}</langsyntaxhighlight>
{{out}}
<pre>All 12 solutions that sum to 100:
Line 5,484 ⟶ 6,247:
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">func gen_expr() is cached {
var x = ['-', '']
var y = ['+', '-', '']
Line 5,523 ⟶ 6,286:
say "Sum of #{n} has the maximum number of solutions: #{solutions.len}"
say "Lowest positive sum that can't be expressed : #{min_solve()}"
say "Highest sums: #{highest_sums()}"</langsyntaxhighlight>
{{out}}
<pre>
Line 5,544 ⟶ 6,307:
 
=={{header|Tcl}}==
<langsyntaxhighlight Tcllang="tcl">proc sum_to_100 {} {
for {set i 0} {$i <= 13121} {incr i} {
set i3 [format %09d [dec2base 3 $i]]
Line 5,580 ⟶ 6,343:
return $res
}
sum_to_100</langsyntaxhighlight>
<pre>
~ $ ./sum_to_100.tcl
Line 5,600 ⟶ 6,363:
highest 10:
123456789 23456790 23456788 12345687 12345669 3456801 3456792 3456790 3456788 3456786
</pre>
 
=={{header|UNIX Shell}}==
{{works with|Korn Shell|93+}}
{{works with|Bourne Again SHell|4.0+}}
{{works with|Z Shell|4.0+}}
 
<syntaxhighlight lang=bash>sumto100() {
typeset expr sum max_count=0 max_values i
typeset -A histogram
printf 'Strings that evaluate to 100:\n'
for expr in {,-}1{,+,-}2{,+,-}3{,+,-}4{,+,-}5{,+,-}6{,+,-}7{,+,-}8{,+,-}9
do
(( sum = expr ))
if (( sum == 100 )); then
printf '\t%s\n' "$expr"
fi
histogram[$sum]=$(( ${histogram[$sum]:-0}+1 ))
if (( histogram[$sum] > max_count )); then
(( max_count = histogram[$sum] ))
max_values=( $sum )
elif (( histogram[$sum] == max_count )); then
max_values+=( $sum )
fi
done
printf '\nMost solutions for any number is %d: ' "$max_count"
if [[ -n $ZSH_VERSION ]]; then
printf '%s\n\n' "${(j:, :)max_values}"
else
printf '%s' "${max_values[0]}"
printf ', %s' "${max_values[@]:1}"
printf '\n\n'
fi
 
for (( i=1; i<123456789; ++i )); do
if (( !histogram[$i] )); then
printf "Lowest positive sum that can't be expressed: %d\n\n" "$i"
break
fi
done
printf 'Ten highest reachable numbers:\n';
if [[ -n $ZSH_VERSION ]]; then
printf '\t%9d\n' "${(k@)histogram}"
else
printf '\t%9d\n' "${!histogram[@]}"
fi | sort -nr | head -n 10
}
 
sumto100
</syntaxhighlight>
{{Out}}
<pre>Strings that evaluate to 100:
123+45-67+8-9
123+4-5+67-89
123-45-67+89
123-4-5-6-7+8-9
12+3+4+5-6-7+89
12+3-4+5+67+8+9
12-3-4+5-6+7+89
1+23-4+56+7+8+9
1+23-4+5+6+78-9
1+2+34-5+67-8+9
1+2+3-4+5+6+78+9
-1+2-3+4+5+6+78+9
 
Most solutions for any number is 46: 9, -9
 
Lowest positive sum that can't be expressed: 211
 
Ten highest reachable numbers:
123456789
23456790
23456788
12345687
12345669
3456801
3456792
3456790
3456788
3456786
 
</pre>
 
Line 5,606 ⟶ 6,450:
 
Another interesting thing this program can do is solve for other sets of numbers easily, as neither the number of digits, nor the digit sequence itself, is hard-coded. You could solve for the digits 1 through 8, for example, or the digits starting at 9 and going down to 1. One can even override the target sum (of 100) parameter, if you happen to be interested in another number.
<langsyntaxhighlight lang="vbnet">' Recursively iterates (increments) iteration array, returns -1 when out of "digits".
Function plusOne(iAry() As Integer, spot As Integer) As Integer
Dim spotLim As Integer = If(spot = 0, 1, 2) ' The first "digit" has a lower limit.
Line 5,708 ⟶ 6,552:
Sub Main()
Solve100() ' if interested, try this: Solve100("987654321")
End Sub</langsyntaxhighlight>
{{out}}
<pre>List of solutions that evaluate to 100:
Line 5,736 ⟶ 6,580:
{{libheader|Wren-math}}
{{libheader|Wren-sort}}
<langsyntaxhighlight ecmascriptlang="wren">import "./dynamic" for Enum
import "./fmt" for Fmt
import "./set" for Set
import "./math" for Nums
import "./sort" for Sort
 
var Op = Enum.create("Op", ["ADD", "SUB", "JOIN"])
Line 5,841 ⟶ 6,685:
var res = stat.countSum.keys.toList
Sort.quick(res)
res[-1..0].take(10).each { |e| Expression.print(e) }</langsyntaxhighlight>
 
{{out}}
Line 5,880 ⟶ 6,724:
=={{header|zkl}}==
Taking a big clue from Haskell and just calculate the world.
<langsyntaxhighlight lang="zkl">var all = // ( (1,12,123...-1,-12,...), (2,23,...) ...)
(9).pump(List,fcn(n){ split("123456789"[n,*]) }) // 45
.apply(fcn(ns){ ns.extend(ns.copy().apply('*(-1))) }); // 90
Line 5,894 ⟶ 6,738:
}
// "123" --> (1,12,123)
fcn split(nstr){ (1).pump(nstr.len(),List,nstr.get.fp(0),"toInt") }</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">fcn showSums(allSums,N=100,printSolutions=2){
slns:=allSums.find(N,T);
if(printSolutions) println("%d solutions for N=%d".fmt(slns.len(),N));
Line 5,914 ⟶ 6,758:
'wrap([(k,v)]){ v=v.len(); ms.holds(v) and T(k.toInt(),v) or Void.Skip })
.sort(fcn(kv1,kv2){ kv1[1]>kv2[1] }) // and sort
.println();</langsyntaxhighlight>
{{out}}
<pre>
1,777

edits