Jump to content

Sum to 100: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 36:
{{trans|Kotlin}}
 
<langsyntaxhighlight lang="11l">-V
NUMBER_OF_DIGITS = 9
THREE_POW_4 = 3 * 3 * 3 * 3
Line 112:
print("\nThe ten highest numbers that do have solutions are:\n")
L(i) sorted(stat.countSum.keys(), reverse' 1B)[0.<10]
printe(i)</langsyntaxhighlight>
 
{{out}}
Line 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 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 209:
end Print;
end Sum_To;</langsyntaxhighlight>
 
===The First Subtask===
Line 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 224:
begin
Eval_100;
end Sum_To_100;</langsyntaxhighlight>
 
{{out}}
Line 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 310:
end loop;
New_Line;
end Three_others;</langsyntaxhighlight>
 
{{out}}
Line 322:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">integer b, i, j, k, l, p, s, z;
index r, w;
 
Line 383:
break;
}
}</langsyntaxhighlight>
{{Out}}
<pre>123-45-67+89
Line 411:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN
# find the numbers the string 123456789 ( with "+/-" optionally inserted #
# before each digit ) can generate #
Line 541:
print( ( newline ) )
 
END</langsyntaxhighlight>
{{out}}
<pre>
Line 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 879:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<pre>Sums to 100:
Line 897:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">output:=""
for k, v in (sum2num(100))
output .= k "`n"
Line 952:
DllCall("msvcrt.dll\" v, "Int64", value, "Str", s, "UInt", OutputBase, "CDECL")
return s
}</langsyntaxhighlight>
{{out}}
<pre>
Line 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 1,084:
limit = best
}
}</langsyntaxhighlight>
{{Out}}
<pre>Show all solutions that sum to 100
Line 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,262:
return 0;
}</langsyntaxhighlight>
{{Out}}
<pre>
Line 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,394:
return 0;
}</langsyntaxhighlight>
{{Out}}
<pre>Show all solutions that sum to 100
Line 1,434:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 1,560:
return left;
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 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,707:
 
return 0;
}</langsyntaxhighlight>
{{Out}}
<pre>
Line 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,769:
(parse-integer (format nil "~{~d~}" lst)) ))
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,792:
=={{header|D}}==
{{Trans|Java}}
<langsyntaxhighlight Dlang="d">import std.stdio;
 
void main() {
Line 1,944:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,987:
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">defmodule Sum do
def to(val) do
generate
Line 2,032:
Sum.max_solve
Sum.min_solve
Sum.highest_sums</langsyntaxhighlight>
 
{{out}}
Line 2,058:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">
(*
Generate the data set
Line 2,077:
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 2,096:
-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,130:
{{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,181:
: .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,340:
=== 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,470:
ivalue = ievaluate(icode)
print *, ivalue, ' = ', s
end</langsyntaxhighlight>
{{Out}}
<pre>
Line 2,511:
 
===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,617:
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,643:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">
#define PERM 13122
 
Line 2,734:
print eqn
sum(champ) = -9999 'overwrite to stop this being found a second time
next i</langsyntaxhighlight>
{{out}}<pre>
-1 + 2 - 3 + 4 + 5 + 6 + 78 + 9 = 100
Line 2,764:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
digits = array[1 to 9]
opList = makeArray[[8], ["", " + ", " - "]]
Line 2,813:
for i = size-10 to size-1
println[freq@i@0]
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,847:
=={{header|Go}}==
{{trans|C}}
<langsyntaxhighlight Golang="go">package main
 
import (
Line 2,996:
fmt.Println(e)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,033:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Control.Monad (replicateM)
import Data.Char (intToDigit)
import Data.List
Line 3,150:
String
maybeReport (Just (x, _)) = show x
maybeReport _ = "No gaps found"</langsyntaxhighlight>
{{Out}}
(Run in Atom editor, through Script package)
Line 3,181:
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 3,192:
'Ten largest:';,.(->:i.10){ss
'First not expressible:';>:pos{~ 1 i.~ 1<|2-/\pos
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,234:
{{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,401:
}
}
}</langsyntaxhighlight>
{{Out}}
<pre>Show all solutions that sum to 100
Line 3,442:
===ES5===
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 3,668:
show(take(10, uniqueNonNegativeSums.sort(flip(compare))))
].join('\n') + '\n';
})();</langsyntaxhighlight>
 
{{Out}}
Line 3,705:
===ES6===
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 3,888:
show(take(10, uniqueNonNegativeSums.sort(flip(compare))))
].join('\n') + '\n';
})();</langsyntaxhighlight>
 
{{Out}}
Line 3,926:
{{Works with|Microsoft Windows Script Host}}
{{Trans|AWK}}
<langsyntaxhighlight lang="javascript">SumTo100();
 
function SumTo100()
Line 4,048:
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>Show all solutions that sum to 100
Line 4,090:
 
'''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 4,110:
# 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 4,132:
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 4,140:
| 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 4,226:
println("\nHighest sums representable:")
foreach(println, hsums)
</langsyntaxhighlight>{{out}}
<pre>100 =
1+23-4+56+7+8+9
Line 4,261:
=={{header|Kotlin}}==
{{trans|C++}}
<langsyntaxhighlight lang="scala">// version 1.1.51
 
class Expression {
Line 4,361:
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,400:
=={{header|Lua}}==
{{trans|C}}
<langsyntaxhighlight lang="lua">local expressionsLength = 0
function compareExpressionBySum(a, b)
return a.sum - b.sum
Line 4,522:
end
limit = best
end</langsyntaxhighlight>
{{out}}
<pre>Show all solutions that sum to 100
Line 4,558:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Defining all possible sums:
<langsyntaxhighlight Mathematicalang="mathematica">operations = DeleteCases[Tuples[{"+", "-", ""}, 9], {x_, y__} /; x == "+"];
sums = Map[StringJoin[Riffle[#, CharacterRange["1", "9"]]] &, operations];</langsyntaxhighlight>
Sums to 100:
<langsyntaxhighlight Mathematicalang="mathematica"> TableForm@Select[sums, ToExpression@# == 100 &] </langsyntaxhighlight>
{{out}}
<pre>-1+2-3+4+5+6+78+9
Line 4,577:
 
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,603:
=={{header|Modula-2}}==
{{trans|C}}
<langsyntaxhighlight lang="modula2">MODULE SumTo100;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 4,740:
 
ReadChar
END SumTo100.</langsyntaxhighlight>
{{out}}
<pre>Show all solutions that sum to 100
Line 4,777:
Recursive solution.
 
<langsyntaxhighlight Nimlang="nim">import algorithm, parseutils, sequtils, strutils, tables
 
type Expression = string
Line 4,818:
echo "\nThe ten highest numbers than can be expressed are:"
let numbers = sorted(toSeq(counts.keys), Descending)
echo numbers[0..9].join(", ")</langsyntaxhighlight>
 
{{out}}
Line 4,844:
Iterative previous solution written in French (updated).
 
<langsyntaxhighlight Nimlang="nim">import strutils
 
var
Line 4,919:
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,955:
{{works with|Lazarus}}
{{trans|C}}
<langsyntaxhighlight Pascallang="pascal">{ RossetaCode: Sum to 100, Pascal.
 
Find solutions to the "sum to one hundred" puzzle.
Line 5,080:
limit := best;
end
end.</langsyntaxhighlight>
{{Out}}
<pre>Show all solutions that sum to 100
Line 5,121:
=={{header|Perl}}==
{{works with|Perl|5.10}}
<langsyntaxhighlight lang="perl">#!/usr/bin/perl
use warnings;
use strict;
Line 5,182:
 
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 5,216:
===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 5,257:
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>
Line 5,342:
<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,366:
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">main =>
L = "23456789",
gen(L,Str),
Line 5,377:
gen([D|Ds],Str) ?=> Str = ['+',D|StrR], gen(Ds,StrR). % insert +
gen([D|Ds],Str) => Str = ['-',D|StrR], gen(Ds,StrR). % insert -
</syntaxhighlight>
</lang>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">#START=6561
#STOPP=19682
#SUMME=100
Line 5,452:
EndIf
Input()
EndIf</langsyntaxhighlight>
{{out}}
<pre>Show all solutions that sum to 100:
Line 5,486:
=={{header|Python}}==
 
<langsyntaxhighlight lang="python">from itertools import product, islice
 
 
Line 5,536:
max_solve()
min_solve()
highest_sums()</langsyntaxhighlight>
 
{{out}}
Line 5,558:
Mostly the same algorithm, but both shorter and faster.
 
<langsyntaxhighlight lang="python">import itertools
from collections import defaultdict, Counter
 
Line 5,586:
print("Ten highest sums")
for k in reversed(v[-10:]):
print(k)</langsyntaxhighlight>
 
{{out}}
Line 5,619:
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">#lang racket
 
(define list-partitions
Line 5,685:
(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,713:
{{works with|Rakudo|2017.03}}
 
<syntaxhighlight lang="raku" perl6line>my $sum = 100;
my $N = 10;
my @ops = ['-', ''], |( [' + ', ' - ', ''] xx 8 );
Line 5,731:
}
 
.say for :$max-solutions, :$first-unsolvable, "$N largest sums:", n-largest-sums($N);</langsyntaxhighlight>
{{out}}
<pre>12 solutions for sum 100:
Line 5,761:
 
=={{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,811:
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,835:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">digits = ("1".."9").to_a
 
ar = ["+", "-", ""].repeated_permutation(digits.size).filter_map do |op_perm|
Line 5,852:
 
puts res.max(10).map{|pair| pair.join(": ")}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 5,885:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object SumTo100 {
def main(args: Array[String]): Unit = {
val exps = expressions(9).map(str => (str, eval(str)))
Line 5,918:
case _ => ""
}
}</langsyntaxhighlight>
{{out}}
<pre>All 12 solutions that sum to 100:
Line 5,940:
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">func gen_expr() is cached {
var x = ['-', '']
var y = ['+', '-', '']
Line 5,979:
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 6,000:
 
=={{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 6,036:
return $res
}
sum_to_100</langsyntaxhighlight>
<pre>
~ $ ./sum_to_100.tcl
Line 6,062:
 
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 6,164:
Sub Main()
Solve100() ' if interested, try this: Solve100("987654321")
End Sub</langsyntaxhighlight>
{{out}}
<pre>List of solutions that evaluate to 100:
Line 6,192:
{{libheader|Wren-math}}
{{libheader|Wren-sort}}
<langsyntaxhighlight lang="ecmascript">import "/dynamic" for Enum
import "/fmt" for Fmt
import "/set" for Set
Line 6,297:
var res = stat.countSum.keys.toList
Sort.quick(res)
res[-1..0].take(10).each { |e| Expression.print(e) }</langsyntaxhighlight>
 
{{out}}
Line 6,336:
=={{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 6,350:
}
// "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 6,370:
'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>
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.