Population count: Difference between revisions

→‎JS ES6: Updated primitives and top-level function, wrapping object methods in directly composable functions
(Add Forth solution)
(→‎JS ES6: Updated primitives and top-level function, wrapping object methods in directly composable functions)
Line 927:
 
===ES6===
 
<lang JavaScript>(() => {
'use strict';
 
// popCount :: Int -> Int
const popCount = n =>
n.toStringfoldl(2)
.split (a, x) => a + (x === '1' ? 1 : 0),
.reduce((a, x) => a + (x === '1' ? 1 : 0), 0);
splitOn('', showIntAsBinary(n))
);
 
// GENERIC FUNCTIONS ------------------------------------------------------
// range :: Int -> Int -> [Int]
 
const range = (m, n) =>
// (++) :: [a] -> [a] -> [a]
const append = (xs, ys) => xs.concat(ys);
 
// rangeenumFromTo :: Int -> Int -> [Int]
const rangeenumFromTo = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
 
// foldl :: (b -> a -> b) -> b -> [a] -> b
const foldl = (f, a, xs) => xs.reduce(f, a);
 
// length :: [a] -> Int
const length = xs => xs.length;
 
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
 
// raise :: Num -> Int -> Num
const raise = Math.pow;
 
// showIntAsBinary :: Int -> String
const showIntAsBinary = n => n.toString(2);
 
// splitOn :: String -> String -> [String]
const splitOn = (cs, xs) => xs.split(cs);
 
// until :: (a -> Bool) -> (a -> a) -> a -> a
Line 951 ⟶ 973:
}
 
// TEST -------------------------------------------------------------------
 
// { popCounts : [Int], evenThenOdd : ([Int], [Int]) }
return {
popCounts: rangemap(x => popCount(raise(3, x)), enumFromTo(0, 30)),
.map(x => popCount(Math.pow(3, x))),
evenThenOdd: until(
m => length(m.evodevenOdd[0].length) >= 30 && length(m.evodevenOdd[1].length) >= 30,
m => ({
x: m.x + 1,
evod evenOdd: popCount(m.x) % 2 === 0 ? (
[append(m.evodevenOdd[0].concat(, m.x), m.evodevenOdd[1]]
) : [m.evodevenOdd[0], append(m.evodevenOdd[1].concat(, m.x)]
}), {
x: 0,
evod evenOdd: [
[],
[]
]
}
).evod
.evenOdd
};
})();</lang>
 
{{Out}}
<lang JavaScript>{"popCounts":[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, 25],
9,655

edits