Population count: Difference between revisions
Content added Content deleted
(Added missing final end of line.) |
(Added a functional version.) |
||
Line 2,498: | Line 2,498: | ||
write(stdout, "\nodious:") |
write(stdout, "\nodious:") |
||
for i in 0..<30: |
for i in 0..<30: |
||
write(stdout, fmt"{od[i]:2} ") |
write(stdout, fmt"{od[i]:2} ") |
||
write(stdout, '\n') |
write(stdout, '\n')</lang> |
||
{{out}} |
|||
<pre> |
<pre> |
||
3^x : 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25 |
3^x : 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25 |
||
Line 2,505: | Line 2,507: | ||
odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59 |
odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59 |
||
</pre> |
</pre> |
||
Another version, in functional style, with most computations done at compile time: |
|||
<lang Nim>import bitops, math, sequtils, strutils |
|||
const |
|||
N = 30 |
|||
popcounts = toSeq(0..<N).mapIt(popcount(3^it)) |
|||
mapping = toSeq(0..<(2 * N)).mapIt((it, it.popcount)) |
|||
evil = mapping.filterIt((it[1] and 1) == 0).mapIt(it[0]) |
|||
odious = mapping.filterIt((it[1] and 1) != 0).mapIt(it[0]) |
|||
echo "3^n: ", popcounts.mapIt(($it).align(2)).join(" ") |
|||
echo "evil: ", evil.mapIt(($it).align(2)).join(" ") |
|||
echo "odious:", odious.mapIt(($it).align(2)).join(" ")</lang> |
|||
{{out}} |
|||
<pre>3^n: 1 2 2 4 3 6 6 5 6 8 9 13 10 11 14 15 11 14 14 17 17 20 19 22 16 18 24 30 25 25 |
|||
evil: 0 3 5 6 9 10 12 15 17 18 20 23 24 27 29 30 33 34 36 39 40 43 45 46 48 51 53 54 57 58 |
|||
odious: 1 2 4 7 8 11 13 14 16 19 21 22 25 26 28 31 32 35 37 38 41 42 44 47 49 50 52 55 56 59</pre> |
|||
=={{header|Oforth}}== |
=={{header|Oforth}}== |