Prime triangle: Difference between revisions
Content added Content deleted
(Added Rust solution) |
|||
Line 502: | Line 502: | ||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
=== Filter method === |
|||
<lang julia>using Combinatorics |
<lang julia>using Combinatorics, Primes |
||
function primetriangle(nrows::Integer) |
function primetriangle(nrows::Integer) |
||
Line 554: | Line 555: | ||
[1, 1, 1, 1, 1, 2, 4, 7, 24, 80, 216, 648, 1304, 3392, 13808, 59448] |
[1, 1, 1, 1, 1, 2, 4, 7, 24, 80, 216, 648, 1304, 3392, 13808, 59448] |
||
36.933227 seconds (699.10 M allocations: 55.557 GiB, 46.71% gc time, 0.37% compilation time) |
36.933227 seconds (699.10 M allocations: 55.557 GiB, 46.71% gc time, 0.37% compilation time) |
||
</pre> |
|||
=== Generator method === |
|||
Similar to the Phix entry. |
|||
<lang julia>using Primes |
|||
function solverow(row, pos, avail) |
|||
results, nresults = Int[], 0 |
|||
for (i, tf) in enumerate(avail) |
|||
if tf && isprime(row[pos - 1] + i + 1) |
|||
if pos >= length(row) - 1 && isprime(row[end] + i + 1) |
|||
row[pos] = i + 1 |
|||
return (copy(row), 1) |
|||
else |
|||
row[pos] = i + 1 |
|||
newav = copy(avail) |
|||
newav[i] = false |
|||
newresults, n = solverow(copy(row), pos + 1, newav) |
|||
nresults += n |
|||
results = isempty(results) && !isempty(newresults) ? newresults : results |
|||
end |
|||
end |
|||
end |
|||
return results, nresults |
|||
end |
|||
function primetriangle(nrows::Integer) |
|||
nrows < 2 && error("number of rows requested must be > 1") |
|||
counts, rowstrings = [1; zeros(Int, nrows - 1)], ["" for _ in 1:nrows] |
|||
for r in 2:nrows |
|||
p, n = solverow(collect(1:r+1), 2, trues(r - 1)) |
|||
rowstrings[r] = prod([lpad(n, 3) for n in p]) * "\n" |
|||
counts[r] = n |
|||
end |
|||
println(" 1 2\n" * prod(rowstrings), "\n", counts) |
|||
end |
|||
</lang> {{out}} |
|||
<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] |
|||
25.818809 seconds (249.58 M allocations: 22.295 GiB, 15.56% gc time) |
|||
</pre> |
</pre> |
||