Magic numbers: Difference between revisions

Content added Content deleted
(→‎{{header|jq}}: def extend:)
Line 175: Line 175:


The solution presented here depends on the unbounded-precision integer
The solution presented here depends on the unbounded-precision integer
arithmetic of the Go implementations of jq:
arithmetic of the Go implementations of jq, and the results shown
can be generated by an invocation of the form:

<pre>
'''Invocation''': gojq -nr -f magic-numbers.jq
gojq -nr -f magic-numbers.jq
</pre>
<syntaxhighlight lang=jq>
<syntaxhighlight lang=jq>
def sum(s): reduce s as $x (0; .+$x);
def sum(s): reduce s as $x (0; .+$x);


# Emit all the polydivisibles in the form of an array of arrays
# such that the numbers in .[i] are the polydivisibles of length i+1
def polydivisible:
def polydivisible:
def extend($n):
{ numbers: [],
previous: [range(1;10)],
((. * 10) + range(0;10)) | select(. % $n == 0);
# input: an array of arrays, such that the numbers in .[i] are the polydivisibles of length i+1
new: [],
digits: 2 }
def extend:
| until (.previous|length == 0;
. as $in
.numbers += [.previous]
| length as $n
| reduce .previous[] as $n (.;
| [$in[-1][] | extend($n+1)] as $x
reduce range(0;10) as $j (.;
| if $x|length == 0 then $in
.number = 10 * $n + $j
else $in + [$x] | extend
end;
| if (.number % .digits) == 0 then .new += [.number] else . end) )
[[range(1;10)]] | extend;
| .previous = .new
| .new = []
| .digits += 1 )
| .numbers;


def pandigital:
def pandigital:
tostring | gsub("0";"") | explode | unique | length == 9;
tostring | gsub("0";"") | explode | unique | length == 9;


# Select the pandigitals from .numbers[$k]
# Select the pandigitals from .[$k]
# Input: {numbers} as produced by polydivisible
# Input: an array as produced by polydivisible
# Output: an array
# Output: an array
def pd($k):
def pd($k):
.numbers[$k] | map(select(pandigital));
.[$k] | map(select(pandigital));
def tasks:
def tasks:
{numbers: polydivisible}
polydivisible
| .numbers[0] += [0]
| .[0] += [0]
| "There are \(sum(.numbers[] | length)) magic numbers in total.",
| "There are \(sum(.[] | length)) magic numbers in total.",
"\nThe largest is \(.numbers[-1][-1])",
"\nThe largest is \(.[-1][-1])",
"\nThere are:",
"\nThere are:",
(range(0; .numbers|length) as $i
(range(0; length) as $i
| "\(.numbers[$i]|length) with \($i + 1) digit\(if ($i == 0) then "" else "s" end)"),
| "\(.[$i]|length) with \($i + 1) digit\(if ($i == 0) then "" else "s" end)"),
( "\nAll magic numbers that are pan-digital in 1 through 9 with no repeats: ", pd(8)[] ),
( "\nAll magic numbers that are pan-digital in 1 through 9 with no repeats: ", pd(8)[] ),
( "\nAll magic numbers that are pan-digital in 0 through 9 with no repeats: ", pd(9)[] ) ;
( "\nAll magic numbers that are pan-digital in 0 through 9 with no repeats: ", pd(9)[] ) ;
Line 258: Line 259:
3816547290
3816547290
</pre>
</pre>



=={{header|Phix}}==
=={{header|Phix}}==