Prime triangle: Difference between revisions

m (Add link to OEIS)
Line 744:
Elapsed time: 833 milliseconds
</pre>
 
=={{header|jq}}==
{{works with|jq}}
'''Adapted from [[#Wren|Wren]]'''
 
(gojq requires too much memory to complete the task.)
<syntaxhighlight lang=jq>
# $i and $j should be relevant integers (possibly negataive)
# Usage with an array-valued key: .key |= array_swap($i; $j)
def array_swap($i; $j):
if $i == $j then .
else .[$i] as $t
| .[$i] = .[$j]
| .[$j] = $t
end;
 
# For syntactic convenience
def swap($array; $i; $j):
$array | array_swap($i; $j);
 
def pmap:
reduce (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37) as $i ([];
.[$i] = true) ;
 
# input: {bFirst, arrang, canFollow, emit}
# output: same + {res, emit, i, count}
def ptrs($res; $n; $done):
. + {$res, count: $done}
| .arrang[$done-1] as $ad
| if ($n - $done <= 1)
then if .canFollow[$ad-1][$n-1]
then if .bFirst
then .emit += [.arrang]
| .bFirst = false
else .
end
| .res += 1
else .
end
else .count += 1
| .i = .count - 1
| until (.i > $n - 2; # $n-2
.arrang[.i] as $ai
| if .canFollow[$ad-1][$ai-1]
then .count as $count
| .i as $i
| .arrang = swap(.arrang; $i; $count-1)
| ptrs(.res; $n; $count) # updates .res but also .count and .i
| .count = $count # restore .count
| .i = $i # restore .i
| .arrang = swap(.arrang; $i; $count-1) # restore .arrang
else .
end
| .i += 2
)
end;
 
# Emit {emit, res} from the call to ptrs
def primeTriangle($n):
pmap as $pmap
| {}
| .canFollow = (reduce range(0;$n) as $i ([];
.[$i] = [range(0;$n) | false]
| reduce range(0;$n) as $j (.;
.[$i][$j] = $pmap[$i+$j+2] )))
| .bFirst = true
| .arrang = [range(1; 1+$n)]
| ptrs(0; $n; 1)
| {emit, res} ;
 
def task($n):
range(2;$n+1) as $i
| primeTriangle($i) ;
 
def task($n):
foreach (range(2;$n+1), null) as $i ({counts: [], emit: null};
if $i == null then .emit = "\n\(.counts)"
else primeTriangle($i) as $pt
| .counts += [$pt|.res]
| .emit = $pt.emit
end;
.emit);
 
task(20)[]
</syntaxhighlight>
{{output}}
<pre>
[1,2]
[1,2,3]
[1,2,3,4]
[1,4,3,2,5]
[1,4,3,2,5,6]
[1,4,3,2,5,6,7]
[1,2,3,4,7,6,5,8]
[1,2,3,4,7,6,5,8,9]
[1,2,3,4,7,6,5,8,9,10]
[1,2,3,4,7,10,9,8,5,6,11]
[1,2,3,4,7,10,9,8,5,6,11,12]
[1,2,3,4,7,6,5,12,11,8,9,10,13]
[1,2,3,4,7,6,13,10,9,8,11,12,5,14]
[1,2,3,4,7,6,13,10,9,8,11,12,5,14,15]
[1,2,3,4,7,6,5,12,11,8,15,14,9,10,13,16]
[1,2,3,4,7,6,5,12,11,8,9,10,13,16,15,14,17]
[1,2,3,4,7,6,5,8,9,10,13,16,15,14,17,12,11,18]
[[1,2,3,4,7,6,5,8,9,10,13,16,15,14,17,12,11,18,19]]
[[1,2,3,4,7,6,5,8,9,10,13,16,15,14,17,12,19,18,11,20]]
 
[1,1,1,1,1,2,4,7,24,80,216,648,1304,3392,13808,59448,155464,480728,1588162]
</pre>
 
 
=={{header|Julia}}==
2,461

edits