Another update from ingydotnet^djgoku

This commit is contained in:
Ingy döt Net 2015-11-18 06:14:39 +00:00
parent 91df62d461
commit 948b86eafa
7604 changed files with 108452 additions and 22726 deletions

View file

@ -0,0 +1,19 @@
// Monadic bind (chain) for lists
function chain(xs, f) {
return [].concat.apply([], xs.map(f));
}
// [m..n]
function range(m, n) {
return Array.apply(null, Array(n - m + 1)).map(function (x, i) {
return m + i;
});
}
function factors_naive(n) {
return chain( range(1, n), function (x) { // monadic chain/bind
return n % x ? [] : [x]; // monadic fail or inject/return
});
}
factors_naive(6)

View file

@ -0,0 +1 @@
[1, 2, 3, 6]

View file

@ -0,0 +1,59 @@
console.log(
(function (lstTest) {
// INTEGER FACTORS
function integerFactors(n) {
var rRoot = Math.sqrt(n),
intRoot = Math.floor(rRoot),
lows = range(1, intRoot).filter(function (x) {
return (n % x) === 0;
});
// for perfect squares, we can drop the head of the 'highs' list
return lows.concat(lows.map(function (x) {
return n / x;
}).reverse().slice((rRoot === intRoot) | 0));
}
// [m .. n]
function range(m, n) {
return Array.apply(null, Array(n - m + 1)).map(function (x, i) {
return m + i;
});
}
/*************************** TESTING *****************************/
// TABULATION OF RESULTS IN SPACED AND ALIGNED COLUMNS
function alignedTable(lstRows, lngPad, fnAligned) {
var lstColWidths = range(0, lstRows.reduce(function (a, x) {
return x.length > a ? x.length : a;
}, 0) - 1).map(function (iCol) {
return lstRows.reduce(function (a, lst) {
var w = lst[iCol] ? lst[iCol].toString().length : 0;
return (w > a) ? w : a;
}, 0);
});
return lstRows.map(function (lstRow) {
return lstRow.map(function (v, i) {
return fnAligned(v, lstColWidths[i] + lngPad);
}).join('')
}).join('\n');
}
function alignRight(n, lngWidth) {
var s = n.toString();
return Array(lngWidth - s.length + 1).join(' ') + s;
}
// TEST
return '\nintegerFactors(n)\n\n' + alignedTable(
lstTest.map(integerFactors).map(function (x, i) {
return [lstTest[i], '-->'].concat(x);
}), 2, alignRight
) + '\n';
})([25, 45, 53, 64, 100, 102, 120, 12345, 32766, 32767])
);

View file

@ -0,0 +1,12 @@
integerFactors(n)
25 --> 1 5 25
45 --> 1 3 5 9 15 45
53 --> 1 53
64 --> 1 2 4 8 16 32 64
100 --> 1 2 4 5 10 20 25 50 100
102 --> 1 2 3 6 17 34 51 102
120 --> 1 2 3 4 5 6 8 10 12 15 20 24 30 40 60 120
12345 --> 1 3 5 15 823 2469 4115 12345
32766 --> 1 2 3 6 43 86 127 129 254 258 381 762 5461 10922 16383 32766
32767 --> 1 7 31 151 217 1057 4681 32767