Sum and product puzzle: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 55:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F counter(arr)
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)</langsyntaxhighlight>
 
{{out}}
Line 89:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SUM_AND_PRODUCT_PUZZLE.AWK
BEGIN {
Line 153:
return(1)
}
</syntaxhighlight>
</lang>
<p>Output:</p>
<pre>
Line 161:
=={{header|C}}==
{{trans|C#}}
<langsyntaxhighlight lang="c">#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
Line 443:
free_list(&candidates);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>2352 candidates
Line 453:
=={{header|C++}}==
{{trans|C}}
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iostream>
#include <map>
Line 609:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>2352 candidates
Line 618:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Linq;
using System.Collections.Generic;
Line 657:
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> source) => new HashSet<T>(source);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 669:
=={{header|Common Lisp}}==
===Version 1===
<langsyntaxhighlight lang="lisp">
;;; 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>
</lang>
 
===Version 2===
<langsyntaxhighlight lang="lisp">
;;; Algorithm of Rosetta code:
 
Line 813:
 
(find-xy *all-possible-pairs*) ;; => ((4 13))
</syntaxhighlight>
</lang>
 
=={{header|D}}==
{{trans|Scala}}
<langsyntaxhighlight lang="d">void main() {
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;
}</langsyntaxhighlight>
{{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">
<lang d>
const s1 = iota(1, 101).map!(x => iota(1, 101).map!(y => tuple(x, y))).joiner
</syntaxhighlight>
</lang>
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}}
<langsyntaxhighlight lang="elixir">defmodule Puzzle do
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</langsyntaxhighlight>
 
{{out}}
Line 879:
=={{header|Factor}}==
A loose translation of D.
<langsyntaxhighlight lang="factor">USING: combinators.short-circuit fry kernel literals math
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</langsyntaxhighlight>
{{out}}
<pre>
Line 911:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,005:
}
return pairs
}</langsyntaxhighlight>
{{out}}
For x + y < 100 (<code>max = 100</code>):
Line 1,028:
=={{header|Haskell}}==
{{trans|D}}
<langsyntaxhighlight lang="haskell">import Data.List (intersect)
 
s1, s2, s3, s4 :: [(Int, Int)]
Line 1,045:
s4 = filter (\p -> length (sumEq p `intersect` s3) == 1) s3
 
main = print s4</langsyntaxhighlight>
{{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.
<langsyntaxhighlight Haskelllang="haskell">import Data.List (intersect)
 
------------------ SUM AND PRODUCT PUZZLE ----------------
Line 1,087:
--------------------------- TEST -------------------------
main :: IO ()
main = print $ take 1 s4</langsyntaxhighlight>
{{Out}}
<pre>[(4,13)]</pre>
Line 1,093:
=={{header|Java}}==
 
<langsyntaxhighlight Javalang="java">package org.rosettacode;
 
import java.util.ArrayList;
Line 1,240:
return list;
}
}</langsyntaxhighlight>
 
{{Out}}
Line 1,259:
 
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 1,354:
return s4;
})();
</syntaxhighlight>
</lang>
 
{{Out}}
<syntaxhighlight lang JavaScript="javascript">[[4, 13]]</langsyntaxhighlight>
(Finished in 0.69s)
 
Line 1,363:
===ES6===
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
"use strict";
 
Line 1,445:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<syntaxhighlight lang JavaScript="javascript">[[4, 13]]</langsyntaxhighlight>
 
=={{header|jq}}==
Line 1,455:
 
A transcription from the problem statement, with these helper functions:
<syntaxhighlight lang="jq">
<lang jq>
# For readability:
def collect(c): map(select(c));
Line 1,498:
 
solve
</syntaxhighlight>
</lang>
{{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.
 
<langsyntaxhighlight lang="julia">
using Primes
 
Line 1,549:
println("Solution: ($j, $(i - j))")
end
end</langsyntaxhighlight>
 
{{out}}
Line 1,555:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.4-3
 
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")
}</langsyntaxhighlight>
 
{{out}}
Line 1,584:
=={{header|Lua}}==
{{trans|C++}}
<langsyntaxhighlight lang="lua">function print_count(t)
local cnt = 0
for k,v in pairs(t) do
Line 1,726:
end
 
main()</langsyntaxhighlight>
{{out}}
<pre>2352 candidates
Line 1,735:
 
=={{header|Nim}}==
<langsyntaxhighlight Nimlang="nim">import sequtils, sets, sugar, tables
 
var
Line 1,782:
for s in sums:
for (x, y) in s.terms:
if x * y in factors: echo (x, y)</langsyntaxhighlight>
 
{{out}}
Line 1,791:
{{trans|REXX}}
for comments see REXX version 4.
<langsyntaxhighlight lang="oorexx">all =.set~new
Call time 'R'
cnt.=0
Line 1,880:
take=0
End
return epairs</langsyntaxhighlight>
{{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)
<langsyntaxhighlight lang="oorexx">all =.set~new
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"]"</langsyntaxhighlight>
{{out}}
<pre>There are 2352 pairs where X+Y <= MAX (and X<Y)
Line 2,018:
=={{header|Perl}}==
{{trans|Raku}}
<langsyntaxhighlight lang="perl">use List::Util qw(none);
 
sub grep_unique {
Line 2,056:
@final_pair = grep_unique(\&sum, @p_pairs);
 
printf "X = %d, Y = %d\n", split ' ', $final_pair[0];</langsyntaxhighlight>
{{out}}
<pre>X = 4, Y = 13</pre>
Line 2,063:
{{trans|AWK}}
Runs in 0.03s
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,121:
</pre>
=={{header|Picat}}==
<syntaxhighlight lang="picat">
<lang Picat>
main =>
N = 98,
Line 2,141:
 
println(Solutions3).
</syntaxhighlight>
</lang>
Output:
<pre>[[4,13]]</pre>
Line 2,148:
 
Based on the Python solution from [[wp:Sum_and_Product_Puzzle#Python_code|Wikipedia]]:
<langsyntaxhighlight lang="python">#!/usr/bin/env python
 
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)</langsyntaxhighlight>
 
{{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.
<langsyntaxhighlight Racketlang="racket">#lang racket
(define-syntax-rule (define/mem (name args ...) body ...)
(begin
Line 2,219:
(displayln s4))
 
(puzzle 100)</langsyntaxhighlight>
{{out}}
<pre>Max Sum: 100
Line 2,232:
{{trans|Python}}
{{works with|Rakudo|2016.07}}
<syntaxhighlight lang="raku" perl6line>sub grep-unique (&by, @list) { @list.classify(&by).values.grep(* == 1).map(*[0]) }
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;</langsyntaxhighlight>
 
{{out}}
Line 2,262:
http://www.win.tue.nl/~gwoegi/papers/freudenthal1.pdf
which had a very clear description.
<langsyntaxhighlight lang="rexx">debug=0
If debug Then Do
oid='sppn.txt'; 'erase' oid
Line 2,488:
End
/* Say swl */
Return strip(swl)</langsyntaxhighlight>
{{out}}
<pre>2352 possible pairs
Line 2,501:
===version 2===
{{trans|AWK}}
<langsyntaxhighlight lang="rexx">Call time 'R'
Do s=2 To 100
a=satisfies_statement3(s)
Line 2,560:
If datatype(x/i,'W') Then Return 0
End
Return 1</langsyntaxhighlight>
{{out}}
<pre>4/13 s=17 p=52
Line 2,567:
===version 3===
{{trans|GO}}
<langsyntaxhighlight lang="rexx">/*---------------------------------------------------------------------
* 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</langsyntaxhighlight>
{{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.
<langsyntaxhighlight lang="rexx">/*---------------------------------------------------------------------
* 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</langsyntaxhighlight>
{{out}}
<pre>There are 2352 pairs where X+Y <= 100 (and X<Y)
Line 2,806:
===version 5, fast ===
This REXX version is over &nbsp; '''ten''' &nbsp; times faster than the previous REXX version.
<langsyntaxhighlight lang="rexx">/*REXX program solves the Sum and Product Puzzle (also known as the Impossible Puzzle).*/
@.= 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 $</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default internal input:}}
<pre>
Line 2,840:
=={{header|Ruby}}==
{{trans|D}}
<langsyntaxhighlight lang="ruby">def add(x,y) x + y end
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}</langsyntaxhighlight>
 
{{out}}
Line 2,857:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">object ImpossiblePuzzle extends App {
type XY = (Int, Int)
val step0 = for {
Line 2,874:
val step4 = step3 filter { sumEq(_).intersect(step3).size == 1 }
println(step4)
}</langsyntaxhighlight>
{{out}}
<pre>Vector((4,13))</pre>
Line 2,881:
=={{header|Scheme}}==
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme cxr)
Line 2,932:
(number->string (cadar *fact-3*))
"\n"))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,945:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func grep_uniq(a, by) { a.group_by{ .(by) }.values.grep{.len == 1}.map{_[0]} }
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...) }</langsyntaxhighlight>
{{out}}
<pre>
Line 2,967:
{{libheader|Wren-dynamic}}
{{libheader|Wren-seq}}
<langsyntaxhighlight lang="ecmascript">import "/dynamic" for Tuple
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)")</langsyntaxhighlight>
 
{{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.
<langsyntaxhighlight lang="zkl">mul:=Utils.Helpers.summer.fp1('*,1); //-->list.reduce('*,1), multiply list items
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();</langsyntaxhighlight>
[[ ]] 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>
10,327

edits