Sum and product puzzle: Difference between revisions
m
syntax highlighting fixup automation
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
|||
Line 55:
{{trans|Python}}
<
DefaultDict[Int, Int] d
L(a) arr
Line 81:
V final_pairs = p_pairs.filter((a, b) -> :sum_counts[a + b] == 1)
print(final_pairs)</
{{out}}
Line 89:
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f SUM_AND_PRODUCT_PUZZLE.AWK
BEGIN {
Line 153:
return(1)
}
</syntaxhighlight>
<p>Output:</p>
<pre>
Line 161:
=={{header|C}}==
{{trans|C#}}
<
#include <stdio.h>
#include <stdlib.h>
Line 443:
free_list(&candidates);
return 0;
}</
{{out}}
<pre>2352 candidates
Line 453:
=={{header|C++}}==
{{trans|C}}
<
#include <iostream>
#include <map>
Line 609:
return 0;
}</
{{out}}
<pre>2352 candidates
Line 618:
=={{header|C sharp}}==
<
using System.Linq;
using System.Collections.Generic;
Line 657:
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);
}</
{{out}}
<pre>
Line 669:
=={{header|Common Lisp}}==
===Version 1===
<
;;; Calculate all x's and their possible y's.
(defparameter *x-possibleys*
Line 758:
(statement-2
(statement-1b *x-possibleys*)))) ;; => ((PRODUCT . 52) (SUM . 17) (Y . 13) (X . 4))
</syntaxhighlight>
===Version 2===
<
;;; Algorithm of Rosetta code:
Line 813:
(find-xy *all-possible-pairs*) ;; => ((4 13))
</syntaxhighlight>
=={{header|D}}==
{{trans|Scala}}
<
import std.stdio, std.algorithm, std.range, std.typecons;
Line 833:
const s3 = s2.filter!(p => mulEq(p).setIntersection(s2).walkLength == 1).array;
s3.filter!(p => sumEq(p).setIntersection(s3).walkLength == 1).writeln;
}</
{{out}}
<pre>[const(Tuple!(int, int))(4, 13)]</pre>
With an older version of the LDC2 compiler replace the <code>cartesianProduct</code> line with:
<syntaxhighlight lang="d">
const s1 = iota(1, 101).map!(x => iota(1, 101).map!(y => tuple(x, y))).joiner
</syntaxhighlight>
The <code>.array</code> turn the lazy ranges into arrays. This is a necessary optimization because D lazy Ranges aren't memoized as Haskell lazy lists.
Line 847:
=={{header|Elixir}}==
{{trans|Ruby}}
<
def sum_and_product do
s1 = for x <- 2..49, y <- x+1..99, x+y<100, do: {x,y}
Line 870:
end
Puzzle.sum_and_product</
{{out}}
Line 879:
=={{header|Factor}}==
A loose translation of D.
<
math.ranges memoize prettyprint sequences sets tools.time ;
IN: rosetta-code.sum-and-product
Line 903:
[ s2 [ mul-eq ] [ sum-eq ] [ only-1 ] bi@ . ] time ;
MAIN: sum-and-product</
{{out}}
<pre>
Line 911:
=={{header|Go}}==
<
import "fmt"
Line 1,005:
}
return pairs
}</
{{out}}
For x + y < 100 (<code>max = 100</code>):
Line 1,028:
=={{header|Haskell}}==
{{trans|D}}
<
s1, s2, s3, s4 :: [(Int, Int)]
Line 1,045:
s4 = filter (\p -> length (sumEq p `intersect` s3) == 1) s3
main = print s4</
{{out}}
<pre>[(4,13)]</pre>
Line 1,057:
Finally, as we expect and need only one solution, Haskell's lazy evaluation strategy will avoid wasted tests if we request only the first item from the possible solution stream.
<
------------------ SUM AND PRODUCT PUZZLE ----------------
Line 1,087:
--------------------------- TEST -------------------------
main :: IO ()
main = print $ take 1 s4</
{{Out}}
<pre>[(4,13)]</pre>
Line 1,093:
=={{header|Java}}==
<
import java.util.ArrayList;
Line 1,240:
return list;
}
}</
{{Out}}
Line 1,259:
{{Trans|Haskell}}
<
'use strict';
Line 1,354:
return s4;
})();
</syntaxhighlight>
{{Out}}
<syntaxhighlight lang
(Finished in 0.69s)
Line 1,363:
===ES6===
{{Trans|Haskell}}
<
"use strict";
Line 1,445:
// MAIN ---
return main();
})();</
{{Out}}
<syntaxhighlight lang
=={{header|jq}}==
Line 1,455:
A transcription from the problem statement, with these helper functions:
<syntaxhighlight lang="jq">
# For readability:
def collect(c): map(select(c));
Line 1,498:
solve
</syntaxhighlight>
{{out}}
<pre>[4,13]</pre>
Line 1,506:
using filters would be much slower in Julia, which often favors fast for loops over lists for speed.
<
using Primes
Line 1,549:
println("Solution: ($j, $(i - j))")
end
end</
{{out}}
Line 1,555:
=={{header|Kotlin}}==
<
data class P(val x: Int, val y: Int, val sum: Int, val prod: Int)
Line 1,575:
print("The only solution is : ")
for ((x, y, _, _) in fact3) println("x = $x, y = $y")
}</
{{out}}
Line 1,584:
=={{header|Lua}}==
{{trans|C++}}
<
local cnt = 0
for k,v in pairs(t) do
Line 1,726:
end
main()</
{{out}}
<pre>2352 candidates
Line 1,735:
=={{header|Nim}}==
<
var
Line 1,782:
for s in sums:
for (x, y) in s.terms:
if x * y in factors: echo (x, y)</
{{out}}
Line 1,791:
{{trans|REXX}}
for comments see REXX version 4.
<
Call time 'R'
cnt.=0
Line 1,880:
take=0
End
return epairs</
{{out}}
<pre>There are 2352 pairs where X+Y <= MAX (and X<Y)
Line 1,890:
Uses objects for storing the number pairs. Note the computed hash value and the == method
(required to make the set difference work)
<
Call time 'R'
cnt.=0
Line 2,008:
::method string -- this creates the string to be shown
expose a b
return "[x="||a",y="||b"]"</
{{out}}
<pre>There are 2352 pairs where X+Y <= MAX (and X<Y)
Line 2,018:
=={{header|Perl}}==
{{trans|Raku}}
<
sub grep_unique {
Line 2,056:
@final_pair = grep_unique(\&sum, @p_pairs);
printf "X = %d, Y = %d\n", split ' ', $final_pair[0];</
{{out}}
<pre>X = 4, Y = 13</pre>
Line 2,063:
{{trans|AWK}}
Runs in 0.03s
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">satisfies_statement1</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
Line 2,115:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 2,121:
</pre>
=={{header|Picat}}==
<syntaxhighlight lang="picat">
main =>
N = 98,
Line 2,141:
println(Solutions3).
</syntaxhighlight>
Output:
<pre>[[4,13]]</pre>
Line 2,148:
Based on the Python solution from [[wp:Sum_and_Product_Puzzle#Python_code|Wikipedia]]:
<
from collections import Counter
Line 2,172:
final_pairs = [(a,b) for a,b in p_pairs if sum_counts[a+b]==1]
print(final_pairs)</
{{out}}
Line 2,179:
=={{header|Racket}}==
{{trans|D}}To calculate the results faster this program use memorization. So it has a modified version of <code>sum=</code> and <code>mul=</code> to increase the chances of reusing the results.
<
(define-syntax-rule (define/mem (name args ...) body ...)
(begin
Line 2,219:
(displayln s4))
(puzzle 100)</
{{out}}
<pre>Max Sum: 100
Line 2,232:
{{trans|Python}}
{{works with|Rakudo|2016.07}}
<syntaxhighlight lang="raku"
sub sums ($n) { ($_, $n - $_ for 2 .. $n div 2) }
sub sum ([$x, $y]) { $x + $y }
Line 2,249:
my @final-pairs = grep-unique &sum, @p-pairs;
printf "X = %d, Y = %d\n", |$_ for @final-pairs;</
{{out}}
Line 2,262:
http://www.win.tue.nl/~gwoegi/papers/freudenthal1.pdf
which had a very clear description.
<
If debug Then Do
oid='sppn.txt'; 'erase' oid
Line 2,488:
End
/* Say swl */
Return strip(swl)</
{{out}}
<pre>2352 possible pairs
Line 2,501:
===version 2===
{{trans|AWK}}
<
Do s=2 To 100
a=satisfies_statement3(s)
Line 2,560:
If datatype(x/i,'W') Then Return 0
End
Return 1</
{{out}}
<pre>4/13 s=17 p=52
Line 2,567:
===version 3===
{{trans|GO}}
<
* X and Y are two different whole numbers greater than 1.
* Their sum is no greater than 100, and Y is greater than X.
Line 2,675:
End
Say "Elapsed time:" time('E') "seconds"
Exit</
{{out}}
<pre>There are 2352 pairs where X+Y <= 100 (and X<Y)
Line 2,685:
===version 4===
Now that I have understood the logic (I am neither S nor P) I have created an alternative to version 3.
<
* X and Y are two different whole numbers greater than 1.
* Their sum is no greater than 100, and Y is greater than X.
Line 2,796:
End
Say "Elapsed time:" time('E') "seconds"
Exit</
{{out}}
<pre>There are 2352 pairs where X+Y <= 100 (and X<Y)
Line 2,806:
===version 5, fast ===
This REXX version is over '''ten''' times faster than the previous REXX version.
<
@.= 0; h= 100; @.3= 1 /*assign array default; assign high P.*/
do j=5 by 2 to h /*find all odd primes ≤ 1st argument.*/
Line 2,832:
else $= 1
end
end /*j*/; return $</
{{out|output|text= when using the default internal input:}}
<pre>
Line 2,840:
=={{header|Ruby}}==
{{trans|D}}
<
def mul(x,y) x * y end
Line 2,849:
s2 = s1.select{|p| sumEq(s1,p).all?{|q| mulEq(s1,q).size != 1} }
s3 = s2.select{|p| (mulEq(s1,p) & s2).size == 1}
p s3.select{|p| (sumEq(s1,p) & s3).size == 1}</
{{out}}
Line 2,857:
=={{header|Scala}}==
<
type XY = (Int, Int)
val step0 = for {
Line 2,874:
val step4 = step3 filter { sumEq(_).intersect(step3).size == 1 }
println(step4)
}</
{{out}}
<pre>Vector((4,13))</pre>
Line 2,881:
=={{header|Scheme}}==
<
(import (scheme base)
(scheme cxr)
Line 2,932:
(number->string (cadar *fact-3*))
"\n"))
</syntaxhighlight>
{{out}}
Line 2,945:
=={{header|Sidef}}==
{{trans|Raku}}
<
func sums (n) { 2 .. n//2 -> map {|i| [i, n-i] } }
Line 2,957:
var f_pairs = grep_uniq(p_pairs, :sum)
f_pairs.each { |p| printf("X = %d, Y = %d\n", p...) }</
{{out}}
<pre>
Line 2,967:
{{libheader|Wren-dynamic}}
{{libheader|Wren-seq}}
<
import "/seq" for Lst
Line 3,001:
var fact3 = fact2.where { |c| intersect.call(sumMap[c.sum], fact2).count == 1 }.toList
System.write("The only solution is : ")
for (p in fact3) System.print("x = %(p.x), y = %(p.y)")</
{{out}}
Line 3,010:
=={{header|zkl}}==
Damn it Jim, I'm a programmer, not a logician. So I translated the python code found in https://qmaurmann.wordpress.com/2013/08/10/sam-and-polly-and-python/ but I don't understand it. It does seem quite a bit more efficient than the Scala code, on par with the Python code.
<
var allPairs=[[(a,b); [2..100]; { [a+1..100] },{ a+b<100 }; ROList]]; // 2,304 pairs
Line 3,020:
sOK2:='wrap(s){ 1==sxys[s].filter('wrap(xy){ pOK(xy:mul(_)) }).len() };
allPairs.filter('wrap([(x,y)]){ sOK(x+y) and pOK(x*y) and sOK2(x+y) })
.println();</
[[ ]] denotes list comprehension, filter1 returns (and stops at) the first thing that is "true", 'wrap creates a closure so the "wrapped" code/function can see local variables (read only). In a [function] prototype, the "[(x,y)]xy]" notation says xy is a list like thing, assign the parts to x & y (xy is optional), used here to just to do it both ways. The ":" says take the LHS and stuff it into the "_".
{{out}}<pre>L(L(4,13))</pre>
|