title
stringlengths
3
86
language
stringlengths
1
35
task
stringlengths
41
8.77k
solution
stringlengths
60
47.6k
Department numbers
Javascript from Haskell
There is a highly organized city that has decided to assign a number to each of their departments: ::* police department ::* sanitation department ::* fire department Each department can have a number between '''1''' and '''7''' (inclusive). The three department numbers are to be unique (different from each other) and must add up to '''12'''. The Chief of the Police doesn't like odd numbers and wants to have an even number for his department. ;Task: Write a computer program which outputs all valid combinations. Possible output (for the 1st and 14th solutions): --police-- --sanitation-- --fire-- 2 3 7 6 5 1
(() => { "use strict"; // -------------- NUMBERING CONSTRAINTS -------------- // options :: Int -> Int -> Int -> [(Int, Int, Int)] const options = lo => hi => total => { const bind = xs => f => xs.flatMap(f), ds = enumFromTo(lo)(hi); return bind(ds.filter(even))( x => bind(ds.filter(d => d !== x))( y => bind([total - (x + y)])( z => (z !== y && lo <= z && z <= hi) ? [ [x, y, z] ] : [] ) ) ); }; // ---------------------- TEST ----------------------- const main = () => { const label = "(Police, Sanitation, Fire)", solutions = options(1)(7)(12), n = solutions.length, list = solutions .map(JSON.stringify) .join("\n"); return ( `${label}\n\n${list}\n\nNumber of options: ${n}` ); }; // ---------------- GENERIC FUNCTIONS ---------------- // enumFromTo :: Int -> Int -> [Int] const enumFromTo = m => n => Array.from({ length: 1 + n - m }, (_, i) => m + i); // even :: Integral a => a -> Bool const even = n => n % 2 === 0; // MAIN --- return main(); })();
Detect division by zero
JavaScript
Write a function to detect a ''divide by zero error'' without checking if the denominator is zero.
function divByZero(dividend,divisor) { var quotient=dividend/divisor; if(isNaN(quotient)) return 0; //Can be changed to whatever is desired by the programmer to be 0, false, or Infinity return quotient; //Will return Infinity or -Infinity in cases of, for example, 5/0 or -7/0 respectively } alert(divByZero(0,0));
Determinant and permanent
JavaScript
permanent of the matrix. The determinant is given by :: \det(A) = \sum_\sigma\sgn(\sigma)\prod_{i=1}^n M_{i,\sigma_i} while the permanent is given by :: \operatorname{perm}(A)=\sum_\sigma\prod_{i=1}^n M_{i,\sigma_i} In both cases the sum is over the permutations \sigma of the permutations of 1, 2, ..., ''n''. (A permutation's sign is 1 if there are an even number of inversions and -1 otherwise; see parity of a permutation.) More efficient algorithms for the determinant are known: [[LU decomposition]], see for example [[wp:LU decomposition#Computing the determinant]]. Efficient methods for calculating the permanent are not known. ;Related task: * [[Permutations by swapping]]
const determinant = arr => arr.length === 1 ? ( arr[0][0] ) : arr[0].reduce( (sum, v, i) => sum + v * (-1) ** i * determinant( arr.slice(1) .map(x => x.filter((_, j) => i !== j)) ), 0 ); const permanent = arr => arr.length === 1 ? ( arr[0][0] ) : arr[0].reduce( (sum, v, i) => sum + v * permanent( arr.slice(1) .map(x => x.filter((_, j) => i !== j)) ), 0 ); const M = [ [0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24] ]; console.log(determinant(M)); console.log(permanent(M));
Determine if a string has all the same characters
JavaScript
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are the same ::::* indicate if or which character is different from the previous character ::* display each string and its length (as the strings are being examined) ::* a zero-length (empty) string shall be considered as all the same character(s) ::* process the strings from left-to-right ::* if all the same character, display a message saying such ::* if not all the same character, then: ::::* display a message saying such ::::* display what character is different ::::* only the 1st different character need be displayed ::::* display where the different character is in the string ::::* the above messages can be part of a single message ::::* display the hexadecimal value of the different character Use (at least) these seven test values (strings): :::* a string of length 0 (an empty string) :::* a string of length 3 which contains three blanks :::* a string of length 1 which contains: '''2''' :::* a string of length 3 which contains: '''333''' :::* a string of length 3 which contains: '''.55''' :::* a string of length 6 which contains: '''tttTTT''' :::* a string of length 9 with a blank in the middle: '''4444 444k''' Show all output here on this page.
const check = s => { const arr = [...s]; const at = arr.findIndex( (v, i) => i === 0 ? false : v !== arr[i - 1] ) const l = arr.length; const ok = at === -1; const p = ok ? "" : at + 1; const v = ok ? "" : arr[at]; const vs = v === "" ? v : `"${v}"` const h = ok ? "" : `0x${v.codePointAt(0).toString(16)}`; console.log(`"${s}" => Length:${l}\tSame:${ok}\tPos:${p}\tChar:${vs}\tHex:${h}`) } ['', ' ', '2', '333', '.55', 'tttTTT', '4444 444k', '🐶🐶🐺🐶', '🎄🎄🎄🎄'].forEach(check)
Determine if a string has all unique characters
JavaScript
Given a character string (which may be empty, or have a length of zero characters): ::* create a function/procedure/routine to: ::::* determine if all the characters in the string are unique ::::* indicate if or which character is duplicated and where ::* display each string and its length (as the strings are being examined) ::* a zero-length (empty) string shall be considered as unique ::* process the strings from left-to-right ::* if unique, display a message saying such ::* if not unique, then: ::::* display a message saying such ::::* display what character is duplicated ::::* only the 1st non-unique character need be displayed ::::* display where "both" duplicated characters are in the string ::::* the above messages can be part of a single message ::::* display the hexadecimal value of the duplicated character Use (at least) these five test values (strings): :::* a string of length 0 (an empty string) :::* a string of length 1 which is a single period ('''.''') :::* a string of length 6 which contains: '''abcABC''' :::* a string of length 7 which contains a blank in the middle: '''XYZ ZYX''' :::* a string of length 36 which ''doesn't'' contain the letter "oh": :::::::: '''1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ''' Show all output here on this page.
(() => { 'use strict'; // duplicatedCharIndices :: String -> Maybe (Char, [Int]) const duplicatedCharIndices = s => { const duplicates = filter(g => 1 < g.length)( groupBy(on(eq)(snd))( sortOn(snd)( zip(enumFrom(0))(chars(s)) ) ) ); return 0 < duplicates.length ? Just( fanArrow(compose(snd, fst))(map(fst))( sortOn(compose(fst, fst))( duplicates )[0] ) ) : Nothing(); }; // ------------------------TEST------------------------ const main = () => console.log( fTable('First duplicated character, if any:')( s => `'${s}' (${s.length})` )(maybe('None')(tpl => { const [c, ixs] = Array.from(tpl); return `'${c}' (0x${showHex(ord(c))}) at ${ixs.join(', ')}` }))(duplicatedCharIndices)([ "", ".", "abcABC", "XYZ ZYX", "1234567890ABCDEFGHIJKLMN0PQRSTUVWXYZ" ]) ); // -----------------GENERIC FUNCTIONS------------------ // Just :: a -> Maybe a const Just = x => ({ type: 'Maybe', Nothing: false, Just: x }); // Nothing :: Maybe a const Nothing = () => ({ type: 'Maybe', Nothing: true, }); // Tuple (,) :: a -> b -> (a, b) const Tuple = a => b => ({ type: 'Tuple', '0': a, '1': b, length: 2 }); // chars :: String -> [Char] const chars = s => s.split(''); // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (...fs) => x => fs.reduceRight((a, f) => f(a), x); // enumFrom :: Enum a => a -> [a] function* enumFrom(x) { let v = x; while (true) { yield v; v = 1 + v; } } // eq (==) :: Eq a => a -> a -> Bool const eq = a => b => a === b; // fanArrow (&&&) :: (a -> b) -> (a -> c) -> (a -> (b, c)) const fanArrow = f => // Compose a function from a simple value to a tuple of // the separate outputs of two different functions. g => x => Tuple(f(x))(g(x)); // filter :: (a -> Bool) -> [a] -> [a] const filter = f => xs => xs.filter(f); // fst :: (a, b) -> a const fst = tpl => tpl[0]; // fTable :: String -> (a -> String) -> (b -> String) // -> (a -> b) -> [a] -> String const fTable = s => xShow => fxShow => f => xs => { // Heading -> x display function -> // fx display function -> // f -> values -> tabular string const ys = xs.map(xShow), w = Math.max(...ys.map(length)); return s + '\n' + zipWith( a => b => a.padStart(w, ' ') + ' -> ' + b )(ys)( xs.map(x => fxShow(f(x))) ).join('\n'); }; // groupBy :: (a -> a -> Bool) -> [a] -> [[a]] const groupBy = fEq => // Typical usage: groupBy(on(eq)(f), xs) xs => 0 < xs.length ? (() => { const tpl = xs.slice(1).reduce( (gw, x) => { const gps = gw[0], wkg = gw[1]; return fEq(wkg[0])(x) ? ( Tuple(gps)(wkg.concat([x])) ) : Tuple(gps.concat([wkg]))([x]); }, Tuple([])([xs[0]]) ); return tpl[0].concat([tpl[1]]) })() : []; // length :: [a] -> Int const length = xs => // Returns Infinity over objects without finite length. // This enables zip and zipWith to choose the shorter // argument when one is non-finite, like cycle, repeat etc (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity; // map :: (a -> b) -> [a] -> [b] const map = f => xs => (Array.isArray(xs) ? ( xs ) : xs.split('')).map(f); // maybe :: b -> (a -> b) -> Maybe a -> b const maybe = v => // Default value (v) if m is Nothing, or f(m.Just) f => m => m.Nothing ? v : f(m.Just); // on :: (b -> b -> c) -> (a -> b) -> a -> a -> c const on = f => g => a => b => f(g(a))(g(b)); // ord :: Char -> Int const ord = c => c.codePointAt(0); // showHex :: Int -> String const showHex = n => n.toString(16); // snd :: (a, b) -> b const snd = tpl => tpl[1]; // sortOn :: Ord b => (a -> b) -> [a] -> [a] const sortOn = f => // Equivalent to sortBy(comparing(f)), but with f(x) // evaluated only once for each x in xs. // ('Schwartzian' decorate-sort-undecorate). xs => xs.map( x => [f(x), x] ).sort( (a, b) => a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0) ).map(x => x[1]); // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = n => xs => 'GeneratorFunction' !== xs.constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; })); // uncurry :: (a -> b -> c) -> ((a, b) -> c) const uncurry = f => (x, y) => f(x)(y) // zip :: [a] -> [b] -> [(a, b)] const zip = xs => ys => { const lng = Math.min(length(xs), length(ys)), vs = take(lng)(ys); return take(lng)(xs) .map((x, i) => Tuple(x)(vs[i])); }; // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => xs => ys => { const lng = Math.min(length(xs), length(ys)), vs = take(lng)(ys); return take(lng)(xs) .map((x, i) => f(x)(vs[i])); }; // MAIN --- return main(); })();
Determine if a string is collapsible
JavaScript
Determine if a character string is ''collapsible''. And if so, collapse the string (by removing ''immediately repeated'' characters). If a character string has ''immediately repeated'' character(s), the repeated characters are to be deleted (removed), but not the primary (1st) character(s). An ''immediately repeated'' character is any character that is immediately followed by an identical character (or characters). Another word choice could've been ''duplicated character'', but that might have ruled out (to some readers) triplicated characters *** or more. {This Rosetta Code task was inspired by a newly introduced (as of around November 2019) '''PL/I''' BIF: '''collapse'''.} ;Examples: In the following character string: The better the 4-wheel drive, the further you'll be from help when ya get stuck! Only the 2nd '''t''', '''e''', and '''l''' are repeated characters, indicated by underscores (above), even though they (those characters) appear elsewhere in the character string. So, after ''collapsing'' the string, the result would be: The beter the 4-whel drive, the further you'l be from help when ya get stuck! Another example: In the following character string: headmistressship The "collapsed" string would be: headmistreship ;Task: Write a subroutine/function/procedure/routine*** to locate ''repeated'' characters and ''collapse'' (delete) them from the character string. The character string can be processed from either direction. Show all output here, on this page: :* the original string and its length :* the resultant string and its length :* the above strings should be "bracketed" with '''<<<''' and '''>>>''' (to delineate blanks) ;* <<<<<<Guillemets may be used instead for "bracketing" for the more artistic programmers, shown used here>>>>>> Use (at least) the following five strings, all strings are length seventy-two (characters, including blanks), except the 1st string: string number ++ 1 |+-----------------------------------------------------------------------+ <###### a null string (length zero) 2 |"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln | 3 |..1111111111111111111111111111111111111111111111111111111111111117777888| 4 |I never give 'em hell, I just tell the truth, and they think it's hell. | 5 | --- Harry S Truman | <###### has many repeated blanks +------------------------------------------------------------------------+
String.prototype.collapse = function() { let str = this; for (let i = 0; i < str.length; i++) { while (str[i] == str[i+1]) str = str.substr(0,i) + str.substr(i+1); } return str; } // testing let strings = [ '', '"If I were two-faced, would I be wearing this one?" --- Abraham Lincoln ', '..1111111111111111111111111111111111111111111111111111111111111117777888', `I never give 'em hell, I just tell the truth, and they think it's hell. `, ' --- Harry S Truman ' ]; for (let i = 0; i < strings.length; i++) { let str = strings[i], col = str.collapse(); console.log(`«««${str}»»» (${str.length})`); console.log(`«««${col}»»» (${col.length})`); }
Dice game probabilities
JavaScript
Two players have a set of dice each. The first player has nine dice with four faces each, with numbers one to four. The second player has six normal dice with six faces each, each face has the usual numbers from one to six. They roll their dice and sum the totals of the faces. The player with the highest total wins (it's a draw if the totals are the same). What's the probability of the first player beating the second player? Later the two players use a different set of dice each. Now the first player has five dice with ten faces each, and the second player has six dice with seven faces each. Now what's the probability of the first player beating the second player? This task was adapted from the Project Euler Problem n.205: https://projecteuler.net/problem=205
let Player = function(dice, faces) { this.dice = dice; this.faces = faces; this.roll = function() { let results = []; for (let x = 0; x < dice; x++) results.push(Math.floor(Math.random() * faces +1)); return eval(results.join('+')); } } function contest(player1, player2, rounds) { let res = [0, 0, 0]; for (let x = 1; x <= rounds; x++) { let a = player1.roll(), b = player2.roll(); switch (true) { case (a > b): res[0]++; break; case (a < b): res[1]++; break; case (a == b): res[2]++; break; } } document.write(` <p> <b>Player 1</b> (${player1.dice} × d${player1.faces}): ${res[0]} wins<br> <b>Player 2</b> (${player2.dice} × d${player2.faces}): ${res[1]} wins<br> <b>Draws:</b> ${res[2]}<br> Chances for Player 1 to win: ~${Math.round(res[0] / eval(res.join('+')) * 100)} % </p> `); } let p1, p2; p1 = new Player(9, 4), p2 = new Player(6, 6); contest(p1, p2, 1e6); p1 = new Player(5, 10); p2 = new Player(6, 7); contest(p1, p2, 1e6);
Digital root
JavaScript
The digital root, X, of a number, n, is calculated: : find X as the sum of the digits of n : find a new X by summing the digits of X, repeating until X has only one digit. The additive persistence is the number of summations required to obtain the single digit. The task is to calculate the additive persistence and the digital root of a number, e.g.: :627615 has additive persistence 2 and digital root of 9; :39390 has additive persistence 2 and digital root of 6; :588225 has additive persistence 2 and digital root of 3; :393900588225 has additive persistence 2 and digital root of 9; The digital root may be calculated in bases other than 10. ;See: * [[Casting out nines]] for this wiki's use of this procedure. * [[Digital root/Multiplicative digital root]] * [[Sum digits of an integer]] * Digital root sequence on OEIS * Additive persistence sequence on OEIS * [[Iterated digits squaring]]
/// Digital root of 'x' in base 'b'. /// @return {addpers, digrt} function digitalRootBase(x,b) { if (x < b) return {addpers:0, digrt:x}; var fauxroot = 0; while (b <= x) { x = (x / b) | 0; fauxroot += x % b; } var rootobj = digitalRootBase(fauxroot,b); rootobj.addpers += 1; return rootobj; }
Disarium numbers
JavaScript
A '''Disarium number''' is an integer where the sum of each digit raised to the power of its position in the number, is equal to the number. ;E.G. '''135''' is a '''Disarium number''': 11 + 32 + 53 == 1 + 9 + 125 == 135 There are a finite number of '''Disarium numbers'''. ;Task * Find and display the first 18 '''Disarium numbers'''. ;Stretch * Find and display all 20 '''Disarium numbers'''. ;See also ;* Geeks for Geeks - Disarium numbers ;* OEIS:A032799 - Numbers n such that n equals the sum of its digits raised to the consecutive powers (1,2,3,...) ;* Related task: Narcissistic decimal number ;* Related task: Own digits power sum ''Which seems to be the same task as Narcissistic decimal number...''
function is_disarium (num) { let n = num let len = n.toString().length let sum = 0 while (n > 0) { sum += (n % 10) ** len n = parseInt(n / 10, 10) len-- } return num == sum } let count = 0 let i = 1 while (count < 18) { if (is_disarium(i)) { process.stdout.write(i + " ") count++ } i++ }
Display an outline as a nested table
JavaScript
{| class="wikitable" style="text-align: center;" |- | style="background: #ffffe6; " colspan=7 | Display an outline as a nested table. |- | style="background: #ffebd2; " colspan=3 | Parse the outline to a tree, | style="background: #f0fff0; " colspan=2 | count the leaves descending from each node, | style="background: #e6ffff; " colspan=2 | and write out a table with 'colspan' values |- | style="background: #ffebd2; " | measuring the indent of each line, | style="background: #ffebd2; " | translating the indentation to a nested structure, | style="background: #ffebd2; " | and padding the tree to even depth. | style="background: #f0fff0; " | defining the width of a leaf as 1, | style="background: #f0fff0; " | and the width of a parent node as a sum. | style="background: #e6ffff; " | either as a wiki table, | style="background: #e6ffff; " | or as HTML. |- | | | | | | | | | style="background: #f0fff0; " | (The sum of the widths of its children) | | | | |} The graphic representation of outlines is a staple of mind-mapping and the planning of papers, reports, and speeches. ;Task: Given a outline with at least 3 levels of indentation, for example: Display an outline as a nested table. Parse the outline to a tree, measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even depth. count the leaves descending from each node, defining the width of a leaf as 1, and the width of a parent node as a sum. (The sum of the widths of its children) and write out a table with 'colspan' values either as a wiki table, or as HTML. write a program in your language which translates your outline into a nested table, with WikiTable or HTML colspan values attached (where needed) to parent nodes in the nested table. The WikiTable at the top of this page was generated from the indented outline shown above, producing the following markup string: {| class="wikitable" style="text-align: center;" |- | style="background: #ffffe6; " colspan=7 | Display an outline as a nested table. |- | style="background: #ffebd2; " colspan=3 | Parse the outline to a tree, | style="background: #f0fff0; " colspan=2 | count the leaves descending from each node, | style="background: #e6ffff; " colspan=2 | and write out a table with 'colspan' values |- | style="background: #ffebd2; " | measuring the indent of each line, | style="background: #ffebd2; " | translating the indentation to a nested structure, | style="background: #ffebd2; " | and padding the tree to even depth. | style="background: #f0fff0; " | defining the width of a leaf as 1, | style="background: #f0fff0; " | and the width of a parent node as a sum. | style="background: #e6ffff; " | either as a wiki table, | style="background: #e6ffff; " | or as HTML. |- | | | | | | | | | style="background: #f0fff0; " | (The sum of the widths of its children) | | | | |} ;Extra credit: Use background color to distinguish the main stages of your outline, so that the subtree of each node at level two is consistently colored, and the edges between adjacent subtrees are immediately revealed. ;Output: Display your nested table on this page.
(() => { "use strict"; // ----------- NESTED TABLES FROM OUTLINE ------------ // wikiTablesFromOutline :: [String] -> String -> String const wikiTablesFromOutline = colorSwatch => outline => forestFromIndentedLines( indentLevelsFromLines(lines(outline)) ) .map(wikiTableFromTree(colorSwatch)) .join("\n\n"); // wikiTableFromTree :: [String] -> Tree String -> String const wikiTableFromTree = colorSwatch => compose( wikiTableFromRows, levels, paintedTree(colorSwatch), widthLabelledTree, ap(paddedTree(""))(treeDepth) ); // ---------------------- TEST ----------------------- // main :: IO () const main = () => { const outline = `Display an outline as a nested table. Parse the outline to a tree, measuring the indent of each line, translating the indentation to a nested structure, and padding the tree to even depth. count the leaves descending from each node, defining the width of a leaf as 1, and the width of a parent node as a sum. (The sum of the widths of its children) and write out a table with 'colspan' values either as a wiki table, or as HTML.`; return wikiTablesFromOutline([ "#ffffe6", "#ffebd2", "#f0fff0", "#e6ffff", "#ffeeff" ])(outline); }; // --------- TREE STRUCTURE FROM NESTED TEXT --------- // forestFromIndentedLines :: [(Int, String)] -> // [Tree String] const forestFromIndentedLines = tuples => { const go = xs => 0 < xs.length ? (() => { // First line and its sub-tree, const [indented, body] = Array.from( xs[0] ), [tree, rest] = Array.from( span(compose(lt(indented), fst))( tail(xs) ) ); // followed by the rest. return [ Node(body)(go(tree)) ].concat(go(rest)); })() : []; return go(tuples); }; // indentLevelsFromLines :: [String] -> [(Int, String)] const indentLevelsFromLines = xs => { const pairs = xs.map( x => bimap(length)(cs => cs.join(""))( span(isSpace)(list(x)) ) ), indentUnit = pairs.reduce( (a, tpl) => { const i = tpl[0]; return 0 < i ? ( i < a ? i : a ) : a; }, Infinity ); return [Infinity, 0].includes(indentUnit) ? ( pairs ) : pairs.map(first(n => n / indentUnit)); }; // ------------ TREE PADDED TO EVEN DEPTH ------------ // paddedTree :: a -> Tree a -> Int -> Tree a const paddedTree = padValue => // All descendants expanded to same depth // with empty nodes where needed. node => depth => { const go = n => tree => 1 < n ? (() => { const children = nest(tree); return Node(root(tree))( ( 0 < children.length ? ( children ) : [Node(padValue)([])] ).map(go(n - 1)) ); })() : tree; return go(depth)(node); }; // treeDepth :: Tree a -> Int const treeDepth = tree => foldTree( () => xs => 0 < xs.length ? ( 1 + maximum(xs) ) : 1 )(tree); // ------------- SUBTREE WIDTHS MEASURED ------------- // widthLabelledTree :: Tree a -> Tree (a, Int) const widthLabelledTree = tree => // A tree in which each node is labelled with // the width of its own subtree. foldTree(x => xs => 0 < xs.length ? ( Node(Tuple(x)( xs.reduce( (a, node) => a + snd(root(node)), 0 ) ))(xs) ) : Node(Tuple(x)(1))([]) )(tree); // -------------- COLOR SWATCH APPLIED --------------- // paintedTree :: [String] -> Tree a -> Tree (String, a) const paintedTree = colorSwatch => tree => 0 < colorSwatch.length ? ( Node( Tuple(colorSwatch[0])(root(tree)) )( zipWith(compose(fmapTree, Tuple))( cycle(colorSwatch.slice(1)) )( nest(tree) ) ) ) : fmapTree(Tuple(""))(tree); // --------------- WIKITABLE RENDERED ---------------- // wikiTableFromRows :: // [[(String, (String, Int))]] -> String const wikiTableFromRows = rows => { const cw = color => width => { const go = w => 1 < w ? ( `colspan=${w} ` ) : ""; return `style="background:${color}; "` + ( ` ${go(width)}` ); }, cellText = ctw => { const [color, tw] = Array.from(ctw); const [txt, width] = Array.from(tw); return 0 < txt.length ? ( `| ${cw(color)(width)}| ${txt}` ) : "| |"; }, classText = "class=\"wikitable\"", styleText = "style=\"text-align:center;\"", header = `{| ${classText} ${styleText}\n|-`, tableBody = rows.map( cells => cells.map(cellText).join("\n") ).join("\n|-\n"); return `${header}\n${tableBody}\n|}`; }; // ------------------ GENERIC TREES ------------------ // Node :: a -> [Tree a] -> Tree a const Node = v => // Constructor for a Tree node which connects a // value of some kind to a list of zero or // more child trees. xs => ({ type: "Node", root: v, nest: xs || [] }); // fmapTree :: (a -> b) -> Tree a -> Tree b const fmapTree = f => { // A new tree. The result of a // structure-preserving application of f // to each root in the existing tree. const go = t => Node( f(t.root) )( t.nest.map(go) ); return go; }; // foldTree :: (a -> [b] -> b) -> Tree a -> b const foldTree = f => { // The catamorphism on trees. A summary // value obtained by a depth-first fold. const go = tree => f( root(tree) )( nest(tree).map(go) ); return go; }; // levels :: Tree a -> [[a]] const levels = tree => { // A list of lists, grouping the root // values of each level of the tree. const go = (a, node) => { const [h, ...t] = 0 < a.length ? ( a ) : [ [], [] ]; return [ [node.root, ...h], ...node.nest.slice(0) .reverse() .reduce(go, t) ]; }; return go([], tree); }; // nest :: Tree a -> [a] const nest = tree => { // Allowing for lazy (on-demand) evaluation. // If the nest turns out to be a function – // rather than a list – that function is applied // here to the root, and returns a list. const xs = tree.nest; return "function" !== typeof xs ? ( xs ) : xs(root(tree)); }; // root :: Tree a -> a const root = tree => // The value attached to a tree node. tree.root; // --------------------- GENERIC --------------------- // Just :: a -> Maybe a const Just = x => ({ type: "Maybe", Nothing: false, Just: x }); // Nothing :: Maybe a const Nothing = () => ({ type: "Maybe", Nothing: true }); // Tuple (,) :: a -> b -> (a, b) const Tuple = a => b => ({ type: "Tuple", "0": a, "1": b, length: 2 }); // apFn :: (a -> b -> c) -> (a -> b) -> (a -> c) const ap = f => // Applicative instance for functions. // f(x) applied to g(x). g => x => f(x)( g(x) ); // bimap :: (a -> b) -> (c -> d) -> (a, c) -> (b, d) const bimap = f => // Tuple instance of bimap. // A tuple of the application of f and g to the // first and second values respectively. g => tpl => Tuple(f(tpl[0]))( g(tpl[1]) ); // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (...fs) => // A function defined by the right-to-left // composition of all the functions in fs. fs.reduce( (f, g) => x => f(g(x)), x => x ); // cycle :: [a] -> Generator [a] const cycle = function* (xs) { // An infinite repetition of xs, // from which an arbitrary prefix // may be taken. const lng = xs.length; let i = 0; while (true) { yield xs[i]; i = (1 + i) % lng; } }; // first :: (a -> b) -> ((a, c) -> (b, c)) const first = f => // A simple function lifted to one which applies // to a tuple, transforming only its first item. xy => { const tpl = Tuple(f(xy[0]))(xy[1]); return Array.isArray(xy) ? ( Array.from(tpl) ) : tpl; }; // fst :: (a, b) -> a const fst = tpl => // First member of a pair. tpl[0]; // isSpace :: Char -> Bool const isSpace = c => // True if c is a white space character. (/\s/u).test(c); // length :: [a] -> Int const length = xs => // Returns Infinity over objects without finite // length. This enables zip and zipWith to choose // the shorter argument when one is non-finite, // like cycle, repeat etc "GeneratorFunction" !== xs.constructor .constructor.name ? ( xs.length ) : Infinity; // lines :: String -> [String] const lines = s => // A list of strings derived from a single // string delimited by newline and or CR. 0 < s.length ? ( s.split(/[\r\n]+/u) ) : []; // list :: StringOrArrayLike b => b -> [a] const list = xs => // xs itself, if it is an Array, // or an Array derived from xs. Array.isArray(xs) ? ( xs ) : Array.from(xs || []); // lt (<) :: Ord a => a -> a -> Bool const lt = a => b => a < b; // maximum :: Ord a => [a] -> a const maximum = xs => ( // The largest value in a non-empty list. ys => 0 < ys.length ? ( ys.slice(1).reduce( (a, y) => y > a ? ( y ) : a, ys[0] ) ) : undefined )(list(xs)); // snd :: (a, b) -> b const snd = tpl => // Second member of a pair. tpl[1]; // span :: (a -> Bool) -> [a] -> ([a], [a]) const span = p => // Longest prefix of xs consisting of elements which // all satisfy p, tupled with the remainder of xs. xs => { const i = xs.findIndex(x => !p(x)); return -1 !== i ? ( Tuple(xs.slice(0, i))( xs.slice(i) ) ) : Tuple(xs)([]); }; // tail :: [a] -> [a] const tail = xs => // A new list consisting of all // items of xs except the first. "GeneratorFunction" !== xs.constructor .constructor.name ? ( (ys => 0 < ys.length ? ys.slice(1) : [])( xs ) ) : (take(1)(xs), xs); // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = n => // The first n elements of a list, // string of characters, or stream. xs => "GeneratorFunction" !== xs .constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat(...Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; })); // uncons :: [a] -> Maybe (a, [a]) const uncons = xs => { // Just a tuple of the head of xs and its tail, // Or Nothing if xs is an empty list. const lng = length(xs); return (0 < lng) ? ( Infinity > lng ? ( // Finite list Just(Tuple(xs[0])(xs.slice(1))) ) : (() => { // Lazy generator const nxt = take(1)(xs); return 0 < nxt.length ? ( Just(Tuple(nxt[0])(xs)) ) : Nothing(); })() ) : Nothing(); }; // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => // A list with the length of the shorter of // xs and ys, defined by zipping with a // custom function, rather than with the // default tuple constructor. xs => ys => { const n = Math.min(length(xs), length(ys)); return Infinity > n ? ( (([as, bs]) => Array.from({ length: n }, (_, i) => f(as[i])( bs[i] )))([xs, ys].map( take(n) )) ) : zipWithGen(f)(xs)(ys); }; // zipWithGen :: (a -> b -> c) -> // Gen [a] -> Gen [b] -> Gen [c] const zipWithGen = f => ga => gb => { const go = function* (ma, mb) { let a = ma, b = mb; while (!a.Nothing && !b.Nothing) { const ta = a.Just, tb = b.Just; yield f(fst(ta))(fst(tb)); a = uncons(snd(ta)); b = uncons(snd(tb)); } }; return go(uncons(ga), uncons(gb)); }; // MAIN --- return main(); })();
Diversity prediction theorem
JavaScript
The ''wisdom of the crowd'' is the collective opinion of a group of individuals rather than that of a single expert. Wisdom-of-the-crowds research routinely attributes the superiority of crowd averages over individual judgments to the elimination of individual noise, an explanation that assumes independence of the individual judgments from each other. Thus the crowd tends to make its best decisions if it is made up of diverse opinions and ideologies. Scott E. Page introduced the diversity prediction theorem: : ''The squared error of the collective prediction equals the average squared error minus the predictive diversity''. Therefore, when the diversity in a group is large, the error of the crowd is small. ;Definitions: ::* Average Individual Error: Average of the individual squared errors ::* Collective Error: Squared error of the collective prediction ::* Prediction Diversity: Average squared distance from the individual predictions to the collective prediction ::* Diversity Prediction Theorem: ''Given a crowd of predictive models'', then :::::: Collective Error = Average Individual Error - Prediction Diversity ;Task: For a given true value and a number of number of estimates (from a crowd), show (here on this page): :::* the true value and the crowd estimates :::* the average error :::* the crowd error :::* the prediction diversity Use (at least) these two examples: :::* a true value of '''49''' with crowd estimates of: ''' 48 47 51''' :::* a true value of '''49''' with crowd estimates of: ''' 48 47 51 42''' ;Also see: :* Wikipedia entry: Wisdom of the crowd :* University of Michigan: PDF paper (exists on a web archive, the ''Wayback Machine'').
'use strict'; function sum(array) { return array.reduce(function (a, b) { return a + b; }); } function square(x) { return x * x; } function mean(array) { return sum(array) / array.length; } function averageSquareDiff(a, predictions) { return mean(predictions.map(function (x) { return square(x - a); })); } function diversityTheorem(truth, predictions) { var average = mean(predictions); return { 'average-error': averageSquareDiff(truth, predictions), 'crowd-error': square(truth - average), 'diversity': averageSquareDiff(average, predictions) }; } console.log(diversityTheorem(49, [48,47,51])) console.log(diversityTheorem(49, [48,47,51,42]))
Dot product
JavaScript
Create a function/use an in-built function, to compute the '''dot product''', also known as the '''scalar product''' of two vectors. If possible, make the vectors of arbitrary length. As an example, compute the dot product of the vectors: :::: [1, 3, -5] and :::: [4, -2, -1] If implementing the dot product of two vectors directly: :::* each vector must be the same length :::* multiply corresponding terms from each vector :::* sum the products (to produce the answer) ;Related task: * [[Vector products]]
(() => { "use strict"; // ------------------- DOT PRODUCT ------------------- // dotProduct :: [Num] -> [Num] -> Either Null Num const dotProduct = xs => ys => xs.length === ys.length ? sum(zipWith(mul)(xs)(ys)) : null; // ---------------------- TEST ----------------------- // main :: IO () const main = () => dotProduct([1, 3, -5])([4, -2, -1]); // --------------------- GENERIC --------------------- // mul :: Num -> Num -> Num const mul = x => y => x * y; // sum :: [Num] -> Num const sum = xs => // The numeric sum of all values in xs. xs.reduce((a, x) => a + x, 0); // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => // A list constructed by zipping with a // custom function, rather than with the // default tuple constructor. xs => ys => xs.map( (x, i) => f(x)(ys[i]) ).slice( 0, Math.min(xs.length, ys.length) ); // MAIN --- return main(); })();
Draw a clock
JavaScript
Draw a clock. More specific: # Draw a time keeping device. It can be a stopwatch, hourglass, sundial, a mouth counting "one thousand and one", anything. Only showing the seconds is required, e.g.: a watch with just a second hand will suffice. However, it must clearly change every second, and the change must cycle every so often (one minute, 30 seconds, etc.) It must be ''drawn''; printing a string of numbers to your terminal doesn't qualify. Both text-based and graphical drawing are OK. # The clock is unlikely to be used to control space flights, so it needs not be hyper-accurate, but it should be usable, meaning if one can read the seconds off the clock, it must agree with the system clock. # A clock is rarely (never?) a major application: don't be a CPU hog and poll the system timer every microsecond, use a proper timer/signal/event from your system or language instead. For a bad example, many OpenGL programs update the frame-buffer in a busy loop even if no redraw is needed, which is very undesirable for this task. # A clock is rarely (never?) a major application: try to keep your code simple and to the point. Don't write something too elaborate or convoluted, instead do whatever is natural, concise and clear in your language. ;Key points * animate simple object * timed event * polling system resources * code clarity
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> canvas { background-color: black; } </style> </head> <body> <canvas></canvas> <script> var canvas = document.querySelector("canvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var g = canvas.getContext("2d"); // which leds are on or off for each digit var masks = ["1110111", "0010010", "1011101", "1011011", "0111010", "1101011", "1101111", "1010010", "1111111", "1111011"]; // horizontal and vertical layouts in scalable units var vertices = [ [ [0, 0], [1, 1], [7, 1], [8, 0], [7, -1], [1, -1] ], [ [0, 0], [-1, 1], [-1, 7], [0, 8], [1, 7], [1, 1] ] ]; function Led(x, y, idx, ox, oy) { // starting points in scalable units this.x = x; this.y = y; // horizontal or vertical layout this.idx = idx; // pixel values to create small gaps between the leds this.offset_x = ox; this.offset_y = oy; } var leds = []; leds.push(new Led(0, 0, 0, 0, -1)); leds.push(new Led(0, 0, 1, -1, 0)); leds.push(new Led(8, 0, 1, 1, 0)); leds.push(new Led(0, 8, 0, 0, 1)); leds.push(new Led(0, 8, 1, -1, 2)); leds.push(new Led(8, 8, 1, 1, 2)); leds.push(new Led(0, 16, 0, 0, 3)); var onColor, offColor; function drawDigitalClock(color1, color2, size) { var clockWidth = (6 * 15 + 2 * 10) * size; var clockHeight = 20 * size; var x = (canvas.width - clockWidth) / 2; var y = (canvas.height - clockHeight) / 2; onColor = color1; offColor = color2; g.clearRect(0, 0, canvas.width, canvas.height); var date = new Date(); var segments = [date.getHours(), date.getMinutes(), date.getSeconds()]; segments.forEach(function (value, index) { x = drawDigits(x, y, size, value); if (index < 2) { x = drawSeparator(x, y, size); } }); } function drawDigits(x, y, size, timeUnit) { var digit1 = Math.floor(timeUnit / 10); var digit2 = timeUnit % 10; x = drawLeds(x, y, size, masks[digit1]); x = drawLeds(x, y, size, masks[digit2]); return x; } function drawSeparator(x, y, size) { g.fillStyle = onColor; g.fillRect(x + 0.5 * size, y + 3 * size, 2 * size, 2 * size); g.fillRect(x + 0.5 * size, y + 10 * size, 2 * size, 2 * size); return x + size * 10; } function drawLeds(x, y, size, mask) { leds.forEach(function (led, i) { g.fillStyle = mask[i] == '1' ? onColor : offColor; var xx = x + led.x * size + led.offset_x; var yy = y + led.y * size + led.offset_y; drawLed(xx, yy, size, vertices[led.idx]); }); return x + size * 15; } function drawLed(x, y, size, vertices) { g.beginPath(); g.moveTo(x, y); vertices.forEach(function (vertex) { g.lineTo(x + vertex[0] * size, y + vertex[1] * size); }); g.closePath(); g.fill(); } setInterval(drawDigitalClock, 1000, "#00FF00", "#002200", 12); </script> </body> </html>
Draw a rotating cube
JavaScript from Java
Task Draw a rotating cube. It should be oriented with one vertex pointing straight up, and its opposite vertex on the main diagonal (the one farthest away) straight down. It can be solid or wire-frame, and you can use ASCII art if your language doesn't have graphical capabilities. Perspective is optional. ;Related tasks * Draw a cuboid * write language name in 3D ASCII
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <style> canvas { background-color: black; } </style> </head> <body> <canvas></canvas> <script> var canvas = document.querySelector("canvas"); canvas.width = window.innerWidth; canvas.height = window.innerHeight; var g = canvas.getContext("2d"); var nodes = [[-1, -1, -1], [-1, -1, 1], [-1, 1, -1], [-1, 1, 1], [1, -1, -1], [1, -1, 1], [1, 1, -1], [1, 1, 1]]; var edges = [[0, 1], [1, 3], [3, 2], [2, 0], [4, 5], [5, 7], [7, 6], [6, 4], [0, 4], [1, 5], [2, 6], [3, 7]]; function scale(factor0, factor1, factor2) { nodes.forEach(function (node) { node[0] *= factor0; node[1] *= factor1; node[2] *= factor2; }); } function rotateCuboid(angleX, angleY) { var sinX = Math.sin(angleX); var cosX = Math.cos(angleX); var sinY = Math.sin(angleY); var cosY = Math.cos(angleY); nodes.forEach(function (node) { var x = node[0]; var y = node[1]; var z = node[2]; node[0] = x * cosX - z * sinX; node[2] = z * cosX + x * sinX; z = node[2]; node[1] = y * cosY - z * sinY; node[2] = z * cosY + y * sinY; }); } function drawCuboid() { g.save(); g.clearRect(0, 0, canvas.width, canvas.height); g.translate(canvas.width / 2, canvas.height / 2); g.strokeStyle = "#FFFFFF"; g.beginPath(); edges.forEach(function (edge) { var p1 = nodes[edge[0]]; var p2 = nodes[edge[1]]; g.moveTo(p1[0], p1[1]); g.lineTo(p2[0], p2[1]); }); g.closePath(); g.stroke(); g.restore(); } scale(200, 200, 200); rotateCuboid(Math.PI / 4, Math.atan(Math.sqrt(2))); setInterval(function() { rotateCuboid(Math.PI / 180, 0); drawCuboid(); }, 17); </script> </body> </html>
Draw a sphere
JavaScript from C
{{requires|Graphics}} ;Task: Draw a sphere. The sphere can be represented graphically, or in ASCII art, depending on the language capabilities. Either static or rotational projection is acceptable for this task. ;Related tasks: * draw a cuboid * draw a rotating cube * write language name in 3D ASCII * draw a Deathstar
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Draw a sphere</title> <script> var light=[30,30,-50],gR,gk,gambient; function normalize(v){ var len=Math.sqrt(v[0]*v[0]+v[1]*v[1]+v[2]*v[2]); v[0]/=len; v[1]/=len; v[2]/=len; return v; } function dot(x,y){ var d=x[0]*y[0]+x[1]*y[1]+x[2]*y[2]; return d<0?-d:0; } function draw_sphere(R,k,ambient){ var i,j,intensity,b,vec,x,y,cvs,ctx,imgdata,idx; cvs=document.getElementById("c"); ctx=cvs.getContext("2d"); cvs.width=cvs.height=2*Math.ceil(R)+1; imgdata=ctx.createImageData(2*Math.ceil(R)+1,2*Math.ceil(R)+1); idx=0; for(i=Math.floor(-R);i<=Math.ceil(R);i++){ x=i+.5; for(j=Math.floor(-R);j<=Math.ceil(R);j++){ y=j+.5; if(x*x+y*y<=R*R){ vec=[x,y,Math.sqrt(R*R-x*x-y*y)]; vec=normalize(vec); b=Math.pow(dot(light,vec),k)+ambient; intensity=(1-b)*256; if(intensity<0)intensity=0; if(intensity>=256)intensity=255; imgdata.data[idx++]=imgdata.data[idx++]=255-~~(intensity); //RG imgdata.data[idx++]=imgdata.data[idx++]=255; //BA } else { imgdata.data[idx++]=imgdata.data[idx++]=imgdata.data[idx++]=imgdata.data[idx++]=255; //RGBA } } } ctx.putImageData(imgdata,0,0); } light=normalize(light); </script> </head> <body onload="gR=200;gk=4;gambient=.2;draw_sphere(gR,gk,gambient)"> R=<input type="range" id="R" name="R" min="5" max="500" value="200" step="5" onchange="document.getElementById('lR').innerHTML=gR=parseFloat(this.value);draw_sphere(gR,gk,gambient)"> <label for="R" id="lR">200</label><br> k=<input type="range" id="k" name="k" min="0" max="10" value="4" step=".25" onchange="document.getElementById('lk').innerHTML=gk=parseFloat(this.value);draw_sphere(gR,gk,gambient)"> <label for="k" id="lk">4</label><br> ambient=<input type="range" id="ambient" name="ambient" min="0" max="1" value=".2" step=".05" onchange="document.getElementById('lambient').innerHTML=gambient=parseFloat(this.value);draw_sphere(gR,gk,gambient)"> <label for="ambient" id="lambient">0.2</label><br> <canvas id="c">Unsupportive browser...</canvas><br> </body> </html>
Dutch national flag problem
Javascript
The Dutch national flag is composed of three coloured bands in the order: ::* red (top) ::* then white, and ::* lastly blue (at the bottom). The problem posed by Edsger Dijkstra is: :Given a number of red, blue and white balls in random order, arrange them in the order of the colours in the Dutch national flag. When the problem was first posed, Dijkstra then went on to successively refine a solution, minimising the number of swaps and the number of times the colour of a ball needed to determined and restricting the balls to end in an array, ... ;Task # Generate a randomized order of balls ''ensuring that they are not in the order of the Dutch national flag''. # Sort the balls in a way idiomatic to your language. # Check the sorted balls ''are'' in the order of the Dutch national flag. ;C.f.: * Dutch national flag problem * Probabilistic analysis of algorithms for the Dutch national flag problem by Wei-Mei Chen. (pdf)
const dutchNationalFlag = () => { /** * Return the name of the given number in this way: * 0 = Red * 1 = White * 2 = Blue * @param {!number} e */ const name = e => e > 1 ? 'Blue' : e > 0 ? 'White' : 'Red'; /** * Given an array of numbers return true if each number is bigger than * or the same as the previous * @param {!Array<!number>} arr */ const isSorted = arr => arr.every((e,i) => e >= arr[Math.max(i-1, 0)]); /** * Generator that keeps yielding a random int between 0(inclusive) and * max(exclusive), up till n times, and then is done. * @param max * @param n */ function* randomGen (max, n) { let i = 0; while (i < n) { i += 1; yield Math.floor(Math.random() * max); } } /** * An array of random integers between 0 and 3 * @type {[!number]} */ const mixedBalls = [...(randomGen(3, 22))]; /** * Sort the given array into 3 sub-arrays and then concatenate those. */ const sortedBalls = mixedBalls .reduce((p,c) => p[c].push(c) && p, [[],[],[]]) .reduce((p,c) => p.concat(c), []); /** * A verbatim implementation of the Wikipedia pseudo-code * @param {!Array<!number>} A * @param {!number} mid The value of the 'mid' number. In our case 1 as * low is 0 and high is 2 */ const dutchSort = (A, mid) => { let i = 0; let j = 0; let n = A.length - 1; while(j <= n) { if (A[j] < mid) { [A[i], A[j]] = [A[j], A[i]]; i += 1; j += 1; } else if (A[j] > mid) { [A[j], A[n]] = [A[n], A[j]]; n -= 1 } else { j += 1; } } }; console.log(`Mixed balls : ${mixedBalls.map(name).join()}`); console.log(`Is sorted: ${isSorted(mixedBalls)}`); console.log(`Sorted balls : ${sortedBalls.map(name).join()}`); console.log(`Is sorted: ${isSorted(sortedBalls)}`); // Only do the dutch sort now as it mutates the mixedBalls array in place. dutchSort(mixedBalls, 1); console.log(`Dutch Sorted balls: ${mixedBalls.map(name).join()}`); console.log(`Is sorted: ${isSorted(mixedBalls)}`); }; dutchNationalFlag();
Egyptian division
JavaScript
Egyptian division is a method of dividing integers using addition and doubling that is similar to the algorithm of [[Ethiopian multiplication]] '''Algorithm:''' Given two numbers where the '''dividend''' is to be divided by the '''divisor''': # Start the construction of a table of two columns: '''powers_of_2''', and '''doublings'''; by a first row of a 1 (i.e. 2^0) in the first column and 1 times the divisor in the first row second column. # Create the second row with columns of 2 (i.e 2^1), and 2 * divisor in order. # Continue with successive i'th rows of 2^i and 2^i * divisor. # Stop adding rows, and keep only those rows, where 2^i * divisor is less than or equal to the dividend. # We now assemble two separate sums that both start as zero, called here '''answer''' and '''accumulator''' # Consider each row of the table, in the ''reverse'' order of its construction. # If the current value of the accumulator added to the doublings cell would be less than or equal to the dividend then add it to the accumulator, as well as adding the powers_of_2 cell value to the answer. # When the first row has been considered as above, then the integer division of dividend by divisor is given by answer. (And the remainder is given by the absolute value of accumulator - dividend). '''Example: 580 / 34''' ''' Table creation: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings |- | 1 | 34 |- | 2 | 68 |- | 4 | 136 |- | 8 | 272 |- | 16 | 544 |} ''' Initialization of sums: ''' ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | 16 | 544 | | |- | | | 0 | 0 |} ''' Considering table rows, bottom-up: ''' When a row is considered it is shown crossed out if it is not accumulated, or '''bold''' if the row causes summations. ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | 16 | 544 |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | 16 | 544 |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | | |- | 4 | 136 | 16 | 544 |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | 1 | 34 | | |- | 2 | 68 | 16 | 544 |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ::: {| class="wikitable" ! powers_of_2 ! doublings ! answer ! accumulator |- | '''1''' | '''34''' | 17 | 578 |- | 2 | 68 | | |- | 4 | 136 | | |- | 8 | 272 | | |- | '''16''' | '''544''' | | |} ;Answer: So 580 divided by 34 using the Egyptian method is '''17''' remainder (578 - 580) or '''2'''. ;Task: The task is to create a function that does Egyptian division. The function should closely follow the description above in using a list/array of powers of two, and another of doublings. * Functions should be clear interpretations of the algorithm. * Use the function to divide 580 by 34 and show the answer '''here, on this page'''. ;Related tasks: :* Egyptian fractions ;References: :* Egyptian Number System
(() => { 'use strict'; // EGYPTIAN DIVISION -------------------------------- // eqyptianQuotRem :: Int -> Int -> (Int, Int) const eqyptianQuotRem = (m, n) => { const expansion = ([i, x]) => x > m ? ( Nothing() ) : Just([ [i, x], [i + i, x + x] ]); const collapse = ([i, x], [q, r]) => x < r ? ( [q + i, r - x] ) : [q, r]; return foldr( collapse, [0, m], unfoldr(expansion, [1, n]) ); }; // TEST --------------------------------------------- // main :: IO () const main = () => showLog( eqyptianQuotRem(580, 34) ); // -> [17, 2] // GENERIC FUNCTIONS -------------------------------- // Just :: a -> Maybe a const Just = x => ({ type: 'Maybe', Nothing: false, Just: x }); // Nothing :: Maybe a const Nothing = () => ({ type: 'Maybe', Nothing: true, }); // flip :: (a -> b -> c) -> b -> a -> c const flip = f => 1 < f.length ? ( (a, b) => f(b, a) ) : (x => y => f(y)(x)); // foldr :: (a -> b -> b) -> b -> [a] -> b const foldr = (f, a, xs) => xs.reduceRight(flip(f), a); // unfoldr :: (b -> Maybe (a, b)) -> b -> [a] const unfoldr = (f, v) => { let xr = [v, v], xs = []; while (true) { const mb = f(xr[1]); if (mb.Nothing) { return xs } else { xr = mb.Just; xs.push(xr[0]) } } }; // showLog :: a -> IO () const showLog = (...args) => console.log( args .map(JSON.stringify) .join(' -> ') ); // MAIN --- return main(); })();
Elementary cellular automaton
JavaScript
An '''cellular automaton where there are two possible states (labeled 0 and 1) and the rule to determine the state of a cell in the next generation depends only on the current state of the cell and its two immediate neighbors. Those three values can be encoded with three bits. The rules of evolution are then encoded with eight bits indicating the outcome of each of the eight possibilities 111, 110, 101, 100, 011, 010, 001 and 000 in this order. Thus for instance the rule 13 means that a state is updated to 1 only in the cases 011, 010 and 000, since 13 in binary is 0b00001101. ;Task: Create a subroutine, program or function that allows to create and visualize the evolution of any of the 256 possible elementary cellular automaton of arbitrary space length and for any given initial state. You can demonstrate your solution with any automaton of your choice. The space state should ''wrap'': this means that the left-most cell should be considered as the right neighbor of the right-most cell, and reciprocally. This task is basically a generalization of [[one-dimensional cellular automata]]. ;See also * Cellular automata (natureofcode.com)
const alive = '#'; const dead = '.'; // ------------------------------------------------------------[ Bit banging ]-- const setBitAt = (val, idx) => BigInt(val) | (1n << BigInt(idx)); const clearBitAt = (val, idx) => BigInt(val) & ~(1n << BigInt(idx)); const getBitAt = val => idx => (BigInt(val) >> BigInt(idx)) & 1n; const hasBitAt = val => idx => ((BigInt(val) >> BigInt(idx)) & 1n) === 1n; // ----------------------------------------------------------------[ Utility ]-- const makeArr = n => Array(n).fill(0); const reverse = x => Array.from(x).reduce((p, c) => [c, ...p], []); const numToLine = width => int => { const test = hasBitAt(int); const looper = makeArr(width); return reverse(looper.map((_, i) => test(i) ? alive : dead)).join(''); } // -------------------------------------------------------------------[ Main ]-- const displayCA = (rule, width, lines, startIndex) => { const result = []; result.push(`Rule:${rule} Width:${width} Gen:${lines}\n`) const ruleTest = hasBitAt(rule); const lineLoop = makeArr(lines); const looper = makeArr(width); const pLine = numToLine(width); let nTarget = setBitAt(0n, startIndex); result.push(pLine(nTarget)); lineLoop.forEach(() => { const bitTest = getBitAt(nTarget); looper.forEach((e, i) => { const l = bitTest(i === 0 ? width - 1 : i - 1); const m = bitTest(i); const r = bitTest(i === width - 1 ? 0 : i + 1); nTarget = ruleTest( parseInt([l, m, r].join(''), 2)) ? setBitAt(nTarget, i) : clearBitAt(nTarget, i); }); result.push(pLine(nTarget)); }); return result.join('\n'); } displayCA(90, 57, 31, 28);
Empty directory
JavaScript
Starting with a path to some directory, determine whether the directory is empty. An empty directory contains no files nor subdirectories. With [[Unix]] or [[Windows]] systems, every directory contains an entry for "." and almost every directory contains ".." (except for a root directory); an empty directory contains no other entries.
The ECMAScript standard itself defines no IO interface – the following example makes use of the Node.js file IO library.
Equilibrium index
JavaScript
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices. For example, in a sequence A: ::::: A_0 = -7 ::::: A_1 = 1 ::::: A_2 = 5 ::::: A_3 = 2 ::::: A_4 = -4 ::::: A_5 = 3 ::::: A_6 = 0 3 is an equilibrium index, because: ::::: A_0 + A_1 + A_2 = A_4 + A_5 + A_6 6 is also an equilibrium index, because: ::::: A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0 (sum of zero elements is zero) 7 is not an equilibrium index, because it is not a valid index of sequence A. ;Task; Write a function that, given a sequence, returns its equilibrium indices (if any). Assume that the sequence may be very long.
function equilibrium(a) { var N = a.length, i, l = [], r = [], e = [] for (l[0] = a[0], r[N - 1] = a[N - 1], i = 1; i<N; i++) l[i] = l[i - 1] + a[i], r[N - i - 1] = r[N - i] + a[N - i - 1] for (i = 0; i < N; i++) if (l[i] === r[i]) e.push(i) return e } // test & output [ [-7, 1, 5, 2, -4, 3, 0], // 3, 6 [2, 4, 6], // empty [2, 9, 2], // 1 [1, -1, 1, -1, 1, -1, 1], // 0,1,2,3,4,5,6 [1], // 0 [] // empty ].forEach(function(x) { console.log(equilibrium(x)) });
Esthetic numbers
JavaScript
An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1. ;E.G. :* '''12''' is an esthetic number. One and two differ by 1. :* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour. :* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. ;Task :* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. :* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) :* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''. :* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''. ;Related task: * numbers with equal rises and falls ;See also: :;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 :;*Numbers Aplenty - Esthetic numbers :;*Geeks for Geeks - Stepping numbers
function isEsthetic(inp, base = 10) { let arr = inp.toString(base).split(''); if (arr.length == 1) return false; for (let i = 0; i < arr.length; i++) arr[i] = parseInt(arr[i], base); for (i = 0; i < arr.length-1; i++) if (Math.abs(arr[i]-arr[i+1]) !== 1) return false; return true; } function collectEsthetics(base, range) { let out = [], x; if (range) { for (x = range[0]; x < range[1]; x++) if (isEsthetic(x)) out.push(x); return out; } else { x = 1; while (out.length < base*6) { s = x.toString(base); if (isEsthetic(s, base)) out.push(s.toUpperCase()); x++; } return out.slice(base*4); } } // main let d = new Date(); for (let x = 2; x <= 36; x++) { // we put b17 .. b36 on top, because we can console.log(`${x}:`); console.log( collectEsthetics(x), (new Date() - d) / 1000 + ' s'); } console.log( collectEsthetics(10, [1000, 9999]), (new Date() - d) / 1000 + ' s' ); console.log( collectEsthetics(10, [1e8, 1.3e8]), (new Date() - d) / 1000 + ' s' );
Esthetic numbers
JavaScript from Haskell
An '''esthetic number''' is a positive integer where every adjacent digit differs from its neighbour by 1. ;E.G. :* '''12''' is an esthetic number. One and two differ by 1. :* '''5654''' is an esthetic number. Each digit is exactly 1 away from its neighbour. :* '''890''' is '''not''' an esthetic number. Nine and zero differ by 9. These examples are nominally in base 10 but the concept extends easily to numbers in other bases. Traditionally, single digit numbers ''are'' included in esthetic numbers; zero may or may not be. For our purposes, for this task, do not include zero (0) as an esthetic number. Do not include numbers with leading zeros. Esthetic numbers are also sometimes referred to as stepping numbers. ;Task :* Write a routine (function, procedure, whatever) to find esthetic numbers in a given base. :* Use that routine to find esthetic numbers in bases '''2''' through '''16''' and display, here on this page, the esthectic numbers from index '''(base x 4)''' through index '''(base x 6)''', inclusive. (E.G. for base 2: 8th through 12th, for base 6: 24th through 36th, etc.) :* Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1000''' and '''9999'''. :* Stretch: Find and display, here on this page, the '''base 10''' esthetic numbers with a magnitude between '''1.0e8''' and '''1.3e8'''. ;Related task: * numbers with equal rises and falls ;See also: :;*OEIS A033075 - Positive numbers n such that all pairs of consecutive decimal digits differ by 1 :;*Numbers Aplenty - Esthetic numbers :;*Geeks for Geeks - Stepping numbers
(() => { "use strict"; // -------- ESTHETIC NUMBERS IN A GIVEN BASE --------- // estheticNumbersInBase :: Int -> [Int] const estheticNumbersInBase = b => // An infinite sequence of numbers which // are esthetic in the given base. tail(fmapGen(x => x[0])( iterate(([, queue]) => { const [num, lsd] = queue[0]; const newDigits = [lsd - 1, lsd + 1] .flatMap( d => (d < b && d >= 0) ? ( [d] ) : [] ); return Tuple(num)( queue.slice(1).concat( newDigits.flatMap(d => [ Tuple((num * b) + d)(d) ]) ) ); })( Tuple()( enumFromTo(1)(b - 1).flatMap( d => [Tuple(d)(d)] ) ) ) )); // ---------------------- TESTS ---------------------- const main = () => { const samples = b => { const i = b * 4, j = b * 6; return unlines([ `Esthetics [${i}..${j}] for base ${b}:`, ...chunksOf(10)( compose(drop(i - 1), take(j))( estheticNumbersInBase(b) ).map(n => n.toString(b)) ) .map(unwords) ]); }; const takeInRange = ([a, b]) => compose( dropWhile(x => x < a), takeWhileGen(x => x <= b) ); return [ enumFromTo(2)(16) .map(samples) .join("\n\n"), [ Tuple(1000)(9999), Tuple(100000000)(130000000) ] .map( ([lo, hi]) => unlines([ `Base 10 Esthetics in range [${lo}..${hi}]:`, unlines( chunksOf(6)( takeInRange([lo, hi])( estheticNumbersInBase(10) ) ) .map(unwords) ) ]) ).join("\n\n") ].join("\n\n"); }; // --------------------- GENERIC --------------------- // Tuple (,) :: a -> b -> (a, b) const Tuple = a => b => ({ type: "Tuple", "0": a, "1": b, length: 2, *[Symbol.iterator]() { for (const k in this) { if (!isNaN(k)) { yield this[k]; } } } }); // chunksOf :: Int -> [a] -> [[a]] const chunksOf = n => { // xs split into sublists of length n. // The last sublist will be short if n // does not evenly divide the length of xs . const go = xs => { const chunk = xs.slice(0, n); return 0 < chunk.length ? ( [chunk].concat( go(xs.slice(n)) ) ) : []; }; return go; }; // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (...fs) => // A function defined by the right-to-left // composition of all the functions in fs. fs.reduce( (f, g) => x => f(g(x)), x => x ); // drop :: Int -> [a] -> [a] // drop :: Int -> Generator [a] -> Generator [a] // drop :: Int -> String -> String const drop = n => xs => Infinity > length(xs) ? ( xs.slice(n) ) : (take(n)(xs), xs); // dropWhile :: (a -> Bool) -> [a] -> [a] // dropWhile :: (Char -> Bool) -> String -> String const dropWhile = p => // The suffix remaining after takeWhile p xs. xs => { const n = xs.length; return xs.slice( 0 < n ? until( i => n === i || !p(xs[i]) )(i => 1 + i)(0) : 0 ); }; // enumFromTo :: Int -> Int -> [Int] const enumFromTo = m => n => Array.from({ length: 1 + n - m }, (_, i) => m + i); // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b] const fmapGen = f => // The map of f over a stream of generator values. function* (gen) { let v = gen.next(); while (!v.done) { yield f(v.value); v = gen.next(); } }; // iterate :: (a -> a) -> a -> Gen [a] const iterate = f => // An infinite list of repeated // applications of f to x. function* (x) { let v = x; while (true) { yield v; v = f(v); } }; // length :: [a] -> Int const length = xs => // Returns Infinity over objects without finite // length. This enables zip and zipWith to choose // the shorter argument when one is non-finite, // like cycle, repeat etc "GeneratorFunction" !== xs.constructor .constructor.name ? ( xs.length ) : Infinity; // tail :: [a] -> [a] const tail = xs => // A new list consisting of all // items of xs except the first. "GeneratorFunction" !== xs.constructor .constructor.name ? ( (ys => 0 < ys.length ? ys.slice(1) : [])( xs ) ) : (take(1)(xs), xs); // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = n => // The first n elements of a list, // string of characters, or stream. xs => "GeneratorFunction" !== xs .constructor.constructor.name ? ( xs.slice(0, n) ) : Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; }).flat(); // takeWhileGen :: (a -> Bool) -> Gen [a] -> [a] const takeWhileGen = p => xs => { const ys = []; let nxt = xs.next(), v = nxt.value; while (!nxt.done && p(v)) { ys.push(v); nxt = xs.next(); v = nxt.value; } return ys; }; // unlines :: [String] -> String const unlines = xs => // A single string formed by the intercalation // of a list of strings with the newline character. xs.join("\n"); // until :: (a -> Bool) -> (a -> a) -> a -> a const until = p => // The value resulting from repeated applications // of f to the seed value x, terminating when // that result returns true for the predicate p. f => x => { let v = x; while (!p(v)) { v = f(v); } return v; }; // unwords :: [String] -> String const unwords = xs => // A space-separated string derived // from a list of words. xs.join(" "); // MAIN --- return main(); })();
Euler's sum of powers conjecture
JavaScript
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. This conjecture is called Euler's sum of powers conjecture and can be stated as such: :At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk. In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250. The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here. Related tasks are: * [[Pythagorean quadruples]]. * [[Pythagorean triples]].
var eulers_sum_of_powers = function (iMaxN) { var aPow5 = []; var oPow5ToN = {}; for (var iP = 0; iP <= iMaxN; iP++) { var iPow5 = Math.pow(iP, 5); aPow5.push(iPow5); oPow5ToN[iPow5] = iP; } for (var i0 = 1; i0 <= iMaxN; i0++) { for (var i1 = 1; i1 <= i0; i1++) { for (var i2 = 1; i2 <= i1; i2++) { for (var i3 = 1; i3 <= i2; i3++) { var iPow5Sum = aPow5[i0] + aPow5[i1] + aPow5[i2] + aPow5[i3]; if (typeof oPow5ToN[iPow5Sum] != 'undefined') { return { i0: i0, i1: i1,l i2: i2, i3: i3, iSum: oPow5ToN[iPow5Sum] }; } } } } } }; var oResult = eulers_sum_of_powers(250); console.log(oResult.i0 + '^5 + ' + oResult.i1 + '^5 + ' + oResult.i2 + '^5 + ' + oResult.i3 + '^5 = ' + oResult.iSum + '^5');
Euler's sum of powers conjecture
JavaScript from Haskell
There is a conjecture in mathematics that held for over two hundred years before it was disproved by the finding of a counterexample in 1966 by Lander and Parkin. This conjecture is called Euler's sum of powers conjecture and can be stated as such: :At least k positive kth powers are required to sum to a kth power, except for the trivial case of one kth power: yk = yk. In 1966, Leon J. Lander and Thomas R. Parkin used a brute-force search on a CDC 6600 computer restricting numbers to those less than 250. The task consists in writing a program to search for an integer solution of x_0^5 + x_1^5 + x_2^5 + x_3^5 = y^5 where all x_i and y are distinct integers between 0 and 250 (exclusive). Show an answer here. Related tasks are: * [[Pythagorean quadruples]]. * [[Pythagorean triples]].
(() => { 'use strict'; const main = () => { const iFrom = 1, iTo = 249, xs = enumFromTo(1, 249), p5 = x => Math.pow(x, 5); const // powerMap :: Dict Int Int powerMap = mapFromList( zip(map(p5, xs), xs) ), // sumMap :: Dict Int (Int, Int) sumMap = mapFromList( bind( xs, x => bind( tail(xs), y => Tuple( p5(x) + p5(y), Tuple(x, y) ) ) ) ); // mbExample :: Maybe (Int, Int) const mbExample = find( tpl => member(fst(tpl) - snd(tpl), sumMap), bind( map(x => parseInt(x, 10), keys(powerMap) ), p => bind( takeWhile( x => x < p, map(x => parseInt(x, 10), keys(sumMap) ) ), s => [Tuple(p, s)] ) ) ); // showExample :: (Int, Int) -> String const showExample = tpl => { const [p, s] = Array.from(tpl); const [a, b] = Array.from(sumMap[p - s]); const [c, d] = Array.from(sumMap[s]); return 'Counter-example found:\n' + intercalate( '^5 + ', map(str, [a, b, c, d]) ) + '^5 = ' + str(powerMap[p]) + '^5'; }; return maybe( 'No counter-example found', showExample, mbExample ); }; // GENERIC FUNCTIONS ---------------------------------- // Just :: a -> Maybe a const Just = x => ({ type: 'Maybe', Nothing: false, Just: x }); // Nothing :: Maybe a const Nothing = () => ({ type: 'Maybe', Nothing: true, }); // Tuple (,) :: a -> b -> (a, b) const Tuple = (a, b) => ({ type: 'Tuple', '0': a, '1': b, length: 2 }); // bind (>>=) :: [a] -> (a -> [b]) -> [b] const bind = (xs, mf) => [].concat.apply([], xs.map(mf)); // concat :: [[a]] -> [a] // concat :: [String] -> String const concat = xs => 0 < xs.length ? (() => { const unit = 'string' !== typeof xs[0] ? ( [] ) : ''; return unit.concat.apply(unit, xs); })() : []; // enumFromTo :: (Int, Int) -> [Int] const enumFromTo = (m, n) => Array.from({ length: 1 + n - m }, (_, i) => m + i); // find :: (a -> Bool) -> [a] -> Maybe a const find = (p, xs) => { for (let i = 0, lng = xs.length; i < lng; i++) { if (p(xs[i])) return Just(xs[i]); } return Nothing(); }; // fst :: (a, b) -> a const fst = tpl => tpl[0]; // intercalate :: [a] -> [[a]] -> [a] // intercalate :: String -> [String] -> String const intercalate = (sep, xs) => 0 < xs.length && 'string' === typeof sep && 'string' === typeof xs[0] ? ( xs.join(sep) ) : concat(intersperse(sep, xs)); // intersperse(0, [1,2,3]) -> [1, 0, 2, 0, 3] // intersperse :: a -> [a] -> [a] // intersperse :: Char -> String -> String const intersperse = (sep, xs) => { const bln = 'string' === typeof xs; return xs.length > 1 ? ( (bln ? concat : x => x)( (bln ? ( xs.split('') ) : xs) .slice(1) .reduce((a, x) => a.concat([sep, x]), [xs[0]]) )) : xs; }; // keys :: Dict -> [String] const keys = Object.keys; // Returns Infinity over objects without finite length. // This enables zip and zipWith to choose the shorter // argument when one is non-finite, like cycle, repeat etc // length :: [a] -> Int const length = xs => (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity; // map :: (a -> b) -> [a] -> [b] const map = (f, xs) => (Array.isArray(xs) ? ( xs ) : xs.split('')).map(f); // mapFromList :: [(k, v)] -> Dict const mapFromList = kvs => kvs.reduce( (a, kv) => { const k = kv[0]; return Object.assign(a, { [ (('string' === typeof k) && k) || JSON.stringify(k) ]: kv[1] }); }, {} ); // Default value (v) if m.Nothing, or f(m.Just) // maybe :: b -> (a -> b) -> Maybe a -> b const maybe = (v, f, m) => m.Nothing ? v : f(m.Just); // member :: Key -> Dict -> Bool const member = (k, dct) => k in dct; // snd :: (a, b) -> b const snd = tpl => tpl[1]; // str :: a -> String const str = x => x.toString(); // tail :: [a] -> [a] const tail = xs => 0 < xs.length ? xs.slice(1) : []; // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = (n, xs) => 'GeneratorFunction' !== xs.constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; })); // takeWhile :: (a -> Bool) -> [a] -> [a] // takeWhile :: (Char -> Bool) -> String -> String const takeWhile = (p, xs) => xs.constructor.constructor.name !== 'GeneratorFunction' ? (() => { const lng = xs.length; return 0 < lng ? xs.slice( 0, until( i => lng === i || !p(xs[i]), i => 1 + i, 0 ) ) : []; })() : takeWhileGen(p, xs); // until :: (a -> Bool) -> (a -> a) -> a -> a const until = (p, f, x) => { let v = x; while (!p(v)) v = f(v); return v; }; // Use of `take` and `length` here allows for zipping with non-finite // lists - i.e. generators like cycle, repeat, iterate. // zip :: [a] -> [b] -> [(a, b)] const zip = (xs, ys) => { const lng = Math.min(length(xs), length(ys)); return Infinity !== lng ? (() => { const bs = take(lng, ys); return take(lng, xs).map((x, i) => Tuple(x, bs[i])); })() : zipGen(xs, ys); }; // MAIN --- return main(); })();
Even or odd
JavaScript
Test whether an integer is even or odd. There is more than one way to solve this task: * Use the even and odd predicates, if the language provides them. * Check the least significant digit. With binary integers, ''i iff ''i'' is even, or equals 1 iff ''i'' is odd. * Divide ''i'' by 2. The remainder equals 0 iff ''i'' is even. The remainder equals +1 or -1 iff ''i'' is odd. * Use modular congruences: ** ''i'' 0 (mod 2) iff ''i'' is even. ** ''i'' 1 (mod 2) iff ''i'' is odd.
(() => { 'use strict'; // even : Integral a => a -> Bool const even = x => (x % 2) === 0; // odd : Integral a => a -> Bool const odd = x => !even(x); // TEST ---------------------------------------- // range :: Int -> Int -> [Int] const range = (m, n) => Array.from({ length: Math.floor(n - m) + 1 }, (_, i) => m + i); // show :: a -> String const show = JSON.stringify; // xs :: [Int] const xs = range(-6, 6); return show([xs.filter(even), xs.filter(odd)]); })();
Evolutionary algorithm
JavaScript
Starting with: * The target string: "METHINKS IT IS LIKE A WEASEL". * An array of random characters chosen from the set of upper-case letters together with the space, and of the same length as the target string. (Call it the parent). * A fitness function that computes the 'closeness' of its argument to the target string. * A mutate function that given a string and a mutation rate returns a copy of the string, with some characters probably mutated. * While the parent is not yet the target: :* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. :* Assess the fitness of the parent and all the copies to the target and make the most fit string the new parent, discarding the others. :* repeat until the parent converges, (hopefully), to the target. ;See also: * Wikipedia entry: Weasel algorithm. * Wikipedia entry: Evolutionary algorithm. Note: to aid comparison, try and ensure the variables and functions mentioned in the task description appear in solutions A cursory examination of a few of the solutions reveals that the instructions have not been followed rigorously in some solutions. Specifically, * While the parent is not yet the target: :* copy the parent C times, each time allowing some random probability that another character might be substituted using mutate. Note that some of the the solutions given retain characters in the mutated string that are ''correct'' in the target string. However, the instruction above does not state to retain any of the characters while performing the mutation. Although some may believe to do so is implied from the use of "converges" (:* repeat until the parent converges, (hopefully), to the target. Strictly speaking, the new parent should be selected from the new pool of mutations, and then the new parent used to generate the next set of mutations with parent characters getting retained only by ''not'' being mutated. It then becomes possible that the new set of mutations has no member that is fitter than the parent! As illustration of this error, the code for 8th has the following remark. Create a new string based on the TOS, '''changing randomly any characters which don't already match the target''': ''NOTE:'' this has been changed, the 8th version is completely random now Clearly, this algo will be applying the mutation function only to the parent characters that don't match to the target characters! To ensure that the new parent is never less fit than the prior parent, both the parent and all of the latest mutations are subjected to the fitness test to select the next parent.
// ------------------------------------- Cross-browser Compatibility ------------------------------------- /* Compatibility code to reduce an array * Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce */ if (!Array.prototype.reduce) { Array.prototype.reduce = function (fun /*, initialValue */ ) { "use strict"; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") throw new TypeError(); // no value to return if no initial value and an empty array if (len == 0 && arguments.length == 1) throw new TypeError(); var k = 0; var accumulator; if (arguments.length >= 2) { accumulator = arguments[1]; } else { do { if (k in t) { accumulator = t[k++]; break; } // if array contains no values, no initial value to return if (++k >= len) throw new TypeError(); } while (true); } while (k < len) { if (k in t) accumulator = fun.call(undefined, accumulator, t[k], k, t); k++; } return accumulator; }; } /* Compatibility code to map an array * Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Map */ if (!Array.prototype.map) { Array.prototype.map = function (fun /*, thisp */ ) { "use strict"; if (this === void 0 || this === null) throw new TypeError(); var t = Object(this); var len = t.length >>> 0; if (typeof fun !== "function") throw new TypeError(); var res = new Array(len); var thisp = arguments[1]; for (var i = 0; i < len; i++) { if (i in t) res[i] = fun.call(thisp, t[i], i, t); } return res; }; } /* ------------------------------------- Generator ------------------------------------- * Generates a fixed length gene sequence via a gene strategy object. * The gene strategy object must have two functions: * - "create": returns create a new gene * - "mutate(existingGene)": returns mutation of an existing gene */ function Generator(length, mutationRate, geneStrategy) { this.size = length; this.mutationRate = mutationRate; this.geneStrategy = geneStrategy; } Generator.prototype.spawn = function () { var genes = [], x; for (x = 0; x < this.size; x += 1) { genes.push(this.geneStrategy.create()); } return genes; }; Generator.prototype.mutate = function (parent) { return parent.map(function (char) { if (Math.random() > this.mutationRate) { return char; } return this.geneStrategy.mutate(char); }, this); }; /* ------------------------------------- Population ------------------------------------- * Helper class that holds and spawns a new population. */ function Population(size, generator) { this.size = size; this.generator = generator; this.population = []; // Build initial popuation; for (var x = 0; x < this.size; x += 1) { this.population.push(this.generator.spawn()); } } Population.prototype.spawn = function (parent) { this.population = []; for (var x = 0; x < this.size; x += 1) { this.population.push(this.generator.mutate(parent)); } }; /* ------------------------------------- Evolver ------------------------------------- * Attempts to converge a population based a fitness strategy object. * The fitness strategy object must have three function * - "score(individual)": returns a score for an individual. * - "compare(scoreA, scoreB)": return true if scoreA is better (ie more fit) then scoreB * - "done( score )": return true if score is acceptable (ie we have successfully converged). */ function Evolver(size, generator, fitness) { this.done = false; this.fitness = fitness; this.population = new Population(size, generator); } Evolver.prototype.getFittest = function () { return this.population.population.reduce(function (best, individual) { var currentScore = this.fitness.score(individual); if (best === null || this.fitness.compare(currentScore, best.score)) { return { score: currentScore, individual: individual }; } else { return best; } }, null); }; Evolver.prototype.doGeneration = function () { this.fittest = this.getFittest(); this.done = this.fitness.done(this.fittest.score); if (!this.done) { this.population.spawn(this.fittest.individual); } }; Evolver.prototype.run = function (onCheckpoint, checkPointFrequency) { checkPointFrequency = checkPointFrequency || 10; // Default to Checkpoints every 10 generations var generation = 0; while (!this.done) { this.doGeneration(); if (generation % checkPointFrequency === 0) { onCheckpoint(generation, this.fittest); } generation += 1; } onCheckpoint(generation, this.fittest); return this.fittest; }; // ------------------------------------- Exports ------------------------------------- window.Generator = Generator; window.Evolver = Evolver; // helper utitlity to combine elements of two arrays. Array.prototype.zip = function (b, func) { var result = [], max = Math.max(this.length, b.length), x; for (x = 0; x < max; x += 1) { result.push(func(this[x], b[x])); } return result; }; var target = "METHINKS IT IS LIKE A WEASEL", geneStrategy, fitness, target, generator, evolver, result; geneStrategy = { // The allowed character set (as an array) characterSet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ ".split(""), /* Pick a random character from the characterSet */ create: function getRandomGene() { var randomNumber = Math.floor(Math.random() * this.characterSet.length); return this.characterSet[randomNumber]; } }; geneStrategy.mutate = geneStrategy.create; // Our mutation stragtegy is to simply get a random gene fitness = { // The target (as an array of characters) target: target.split(""), equal: function (geneA, geneB) { return (geneA === geneB ? 0 : 1); }, sum: function (runningTotal, value) { return runningTotal + value; }, /* We give one point to for each corect letter */ score: function (genes) { var diff = genes.zip(this.target, this.equal); // create an array of ones and zeros return diff.reduce(this.sum, 0); // Sum the array values together. }, compare: function (scoreA, scoreB) { return scoreA <= scoreB; // Lower scores are better }, done: function (score) { return score === 0; // We have matched the target string. } }; generator = new Generator(target.length, 0.05, geneStrategy); evolver = new Evolver(100, generator, fitness); function showProgress(generation, fittest) { document.write("Generation: " + generation + ", Best: " + fittest.individual.join("") + ", fitness:" + fittest.score + "<br>"); } result = evolver.run(showProgress);
Execute HQ9+
JavaScript
Implement a ''' [[HQ9+]] ''' interpreter or compiler.
function hq9plus(code) { var out = ''; var acc = 0; for (var i=0; i<code.length; i++) { switch (code.charAt(i)) { case 'H': out += "hello, world\n"; break; case 'Q': out += code + "\n"; break; case '9': for (var j=99; j>1; j--) { out += j + " bottles of beer on the wall, " + j + " bottles of beer.\n"; out += "Take one down and pass it around, " + (j-1) + " bottles of beer.\n\n"; } out += "1 bottle of beer on the wall, 1 bottle of beer.\n" + "Take one down and pass it around, no more bottles of beer on the wall.\n\n" + "No more bottles of beer on the wall, no more bottles of beer.\n" + "Go to the store and buy some more, 99 bottles of beer on the wall.\n"; break; case '+': acc++; break; } } return out; }
FASTA format
JavaScript
In FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. ;Task: Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE >Rosetta_Example_2 THERECANBESEVERAL LINESBUTTHEYALLMUST BECONCATENATED
const fs = require("fs"); const readline = require("readline"); const args = process.argv.slice(2); if (!args.length) { console.error("must supply file name"); process.exit(1); } const fname = args[0]; const readInterface = readline.createInterface({ input: fs.createReadStream(fname), console: false, }); let sep = ""; readInterface.on("line", (line) => { if (line.startsWith(">")) { process.stdout.write(sep); sep = "\n"; process.stdout.write(line.substring(1) + ": "); } else { process.stdout.write(line); } }); readInterface.on("close", () => process.stdout.write("\n"));
Fairshare between two and more
JavaScript
The [[Thue-Morse]] sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour the team that goes first as much if the penalty takers take turns according to the Thue-Morse sequence and took 2^n penalties) The Thue-Morse sequence of ones-and-zeroes can be generated by: :''"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"'' ;Sharing fairly between two or more: Use this method: :''When counting base '''b''', the digit sum modulo '''b''' is the Thue-Morse sequence of fairer sharing between '''b''' people.'' ;Task Counting from zero; using a function/method/routine to express an integer count in base '''b''', sum the digits modulo '''b''' to produce the next member of the Thue-Morse fairshare series for '''b''' people. Show the first 25 terms of the fairshare sequence: :* For two people: :* For three people :* For five people :* For eleven people ;Related tasks: :* [[Non-decimal radices/Convert]] :* [[Thue-Morse]] ;See also: :* A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences(r) (OEIS(r))
(() => { 'use strict'; // thueMorse :: Int -> [Int] const thueMorse = base => // Thue-Morse sequence for a given base fmapGen(baseDigitsSumModBase(base))( enumFrom(0) ) // baseDigitsSumModBase :: Int -> Int -> Int const baseDigitsSumModBase = base => // For any integer n, the sum of its digits // in a given base, modulo that base. n => sum(unfoldl( x => 0 < x ? ( Just(quotRem(x)(base)) ) : Nothing() )(n)) % base // ------------------------TEST------------------------ const main = () => console.log( fTable( 'First 25 fairshare terms for a given number of players:' )(str)( xs => '[' + map( compose(justifyRight(2)(' '), str) )(xs) + ' ]' )( compose(take(25), thueMorse) )([2, 3, 5, 11]) ); // -----------------GENERIC FUNCTIONS------------------ // Just :: a -> Maybe a const Just = x => ({ type: 'Maybe', Nothing: false, Just: x }); // Nothing :: Maybe a const Nothing = () => ({ type: 'Maybe', Nothing: true, }); // Tuple (,) :: a -> b -> (a, b) const Tuple = a => b => ({ type: 'Tuple', '0': a, '1': b, length: 2 }); // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (...fs) => x => fs.reduceRight((a, f) => f(a), x); // enumFrom :: Enum a => a -> [a] function* enumFrom(x) { // A non-finite succession of enumerable // values, starting with the value x. let v = x; while (true) { yield v; v = 1 + v; } } // fTable :: String -> (a -> String) -> (b -> String) // -> (a -> b) -> [a] -> String const fTable = s => xShow => fxShow => f => xs => { // Heading -> x display function -> // fx display function -> // f -> values -> tabular string const ys = xs.map(xShow), w = Math.max(...ys.map(length)); return s + '\n' + zipWith( a => b => a.padStart(w, ' ') + ' -> ' + b )(ys)( xs.map(x => fxShow(f(x))) ).join('\n'); }; // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b] const fmapGen = f => function*(gen) { let v = take(1)(gen); while (0 < v.length) { yield(f(v[0])) v = take(1)(gen) } }; // justifyRight :: Int -> Char -> String -> String const justifyRight = n => // The string s, preceded by enough padding (with // the character c) to reach the string length n. c => s => n > s.length ? ( s.padStart(n, c) ) : s; // length :: [a] -> Int const length = xs => // Returns Infinity over objects without finite // length. This enables zip and zipWith to choose // the shorter argument when one is non-finite, // like cycle, repeat etc (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity; // map :: (a -> b) -> [a] -> [b] const map = f => // The list obtained by applying f to each element of xs. // (The image of xs under f). xs => (Array.isArray(xs) ? ( xs ) : xs.split('')).map(f); // quotRem :: Int -> Int -> (Int, Int) const quotRem = m => n => Tuple(Math.floor(m / n))( m % n ); // str :: a -> String const str = x => x.toString(); // sum :: [Num] -> Num const sum = xs => // The numeric sum of all values in xs. xs.reduce((a, x) => a + x, 0); // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = n => // The first n elements of a list, // string of characters, or stream. xs => 'GeneratorFunction' !== xs .constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; })); // unfoldl :: (b -> Maybe (b, a)) -> b -> [a] const unfoldl = f => v => { // Dual to reduce or foldl. // Where these reduce a list to a summary value, unfoldl // builds a list from a seed value. // Where f returns Just(a, b), a is appended to the list, // and the residual b is used as the argument for the next // application of f. // Where f returns Nothing, the completed list is returned. let xr = [v, v], xs = []; while (true) { const mb = f(xr[0]); if (mb.Nothing) { return xs } else { xr = mb.Just; xs = [xr[1]].concat(xs); } } }; // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => xs => ys => { const lng = Math.min(length(xs), length(ys)), vs = take(lng)(ys); return take(lng)(xs) .map((x, i) => f(x)(vs[i])); }; // MAIN --- return main(); })();
Fast Fourier transform
JavaScript
Calculate the FFT (Fast Fourier Transform) of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude (i.e.: sqrt(re2 + im2)) of the complex result. The classic version is the recursive Cooley-Tukey FFT. Wikipedia has pseudo-code for that. Further optimizations are possible but not required.
/* complex fast fourier transform and inverse from http://rosettacode.org/wiki/Fast_Fourier_transform#C.2B.2B */ function icfft(amplitudes) { var N = amplitudes.length; var iN = 1 / N; //conjugate if imaginary part is not 0 for(var i = 0 ; i < N; ++i) if(amplitudes[i] instanceof Complex) amplitudes[i].im = -amplitudes[i].im; //apply fourier transform amplitudes = cfft(amplitudes) for(var i = 0 ; i < N; ++i) { //conjugate again amplitudes[i].im = -amplitudes[i].im; //scale amplitudes[i].re *= iN; amplitudes[i].im *= iN; } return amplitudes; } function cfft(amplitudes) { var N = amplitudes.length; if( N <= 1 ) return amplitudes; var hN = N / 2; var even = []; var odd = []; even.length = hN; odd.length = hN; for(var i = 0; i < hN; ++i) { even[i] = amplitudes[i*2]; odd[i] = amplitudes[i*2+1]; } even = cfft(even); odd = cfft(odd); var a = -2*Math.PI; for(var k = 0; k < hN; ++k) { if(!(even[k] instanceof Complex)) even[k] = new Complex(even[k], 0); if(!(odd[k] instanceof Complex)) odd[k] = new Complex(odd[k], 0); var p = k/N; var t = new Complex(0, a * p); t.cexp(t).mul(odd[k], t); amplitudes[k] = even[k].add(t, odd[k]); amplitudes[k + hN] = even[k].sub(t, even[k]); } return amplitudes; } //test code //console.log( cfft([1,1,1,1,0,0,0,0]) ); //console.log( icfft(cfft([1,1,1,1,0,0,0,0])) );
Fibonacci n-step number sequences
JavaScript
These number series are an expansion of the ordinary [[Fibonacci sequence]] where: # For n = 2 we have the Fibonacci sequence; with initial values [1, 1] and F_k^2 = F_{k-1}^2 + F_{k-2}^2 # For n = 3 we have the tribonacci sequence; with initial values [1, 1, 2] and F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3 # For n = 4 we have the tetranacci sequence; with initial values [1, 1, 2, 4] and F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4... # For general n>2 we have the Fibonacci n-step sequence - F_k^n; with initial values of the first n values of the (n-1)'th Fibonacci n-step sequence F_k^{n-1}; and k'th value of this n'th sequence being F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}} For small values of n, Greek numeric prefixes are sometimes used to individually name each series. :::: {| style="text-align: left;" border="4" cellpadding="2" cellspacing="2" |+ Fibonacci n-step sequences |- style="background-color: rgb(255, 204, 255);" ! n !! Series name !! Values |- | 2 || fibonacci || 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... |- | 3 || tribonacci || 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... |- | 4 || tetranacci || 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... |- | 5 || pentanacci || 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... |- | 6 || hexanacci || 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... |- | 7 || heptanacci || 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... |- | 8 || octonacci || 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... |- | 9 || nonanacci || 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... |- | 10 || decanacci || 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... |} Allied sequences can be generated where the initial values are changed: : '''The Lucas series''' sums the two preceding values like the fibonacci series for n=2 but uses [2, 1] as its initial values. ;Task: # Write a function to generate Fibonacci n-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series. # Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences. ;Related tasks: * [[Fibonacci sequence]] * Wolfram Mathworld * [[Hofstadter Q sequence]] * [[Leonardo numbers]] ;Also see: * Lucas Numbers - Numberphile (Video) * Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video) * Wikipedia, Lucas number * MathWorld, Fibonacci Number * Some identities for r-Fibonacci numbers * OEIS Fibonacci numbers * OEIS Lucas numbers
function fib(arity, len) { return nacci(nacci([1,1], arity, arity), arity, len); } function lucas(arity, len) { return nacci(nacci([2,1], arity, arity), arity, len); } function nacci(a, arity, len) { while (a.length < len) { var sum = 0; for (var i = Math.max(0, a.length - arity); i < a.length; i++) sum += a[i]; a.push(sum); } return a; } function main() { for (var arity = 2; arity <= 10; arity++) console.log("fib(" + arity + "): " + fib(arity, 15)); for (var arity = 2; arity <= 10; arity++) console.log("lucas(" + arity + "): " + lucas(arity, 15)); } main();
Fibonacci word
JavaScript
The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here: Define F_Word1 as '''1''' Define F_Word2 as '''0''' Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: '''01''' Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2 ;Task: Perform the above steps for n = 37. You may display the first few but not the larger values of n. {Doing so will get the task's author into trouble with them what be (again!).} Instead, create a table for F_Words '''1''' to '''37''' which shows: ::* The number of characters in the word ::* The word's [[Entropy]] ;Related tasks: * Fibonacci word/fractal * [[Entropy]] * [[Entropy/Narcissist]]
//makes outputting a table possible in environments //that don't support console.table() function console_table(xs) { function pad(n,s) { var res = s; for (var i = s.length; i < n; i++) res += " "; return res; } if (xs.length === 0) console.log("No data"); else { var widths = []; var cells = []; for (var i = 0; i <= xs.length; i++) cells.push([]); for (var s in xs[0]) { var len = s.length; cells[0].push(s); for (var i = 0; i < xs.length; i++) { var ss = "" + xs[i][s]; len = Math.max(len, ss.length); cells[i+1].push(ss); } widths.push(len); } var s = ""; for (var x = 0; x < cells.length; x++) { for (var y = 0; y < widths.length; y++) s += "|" + pad(widths[y], cells[x][y]); s += "|\n"; } console.log(s); } } //returns the entropy of a string as a number function entropy(s) { //create an object containing each individual char //and the amount of iterations per char function prob(s) { var h = Object.create(null); s.split('').forEach(function(c) { h[c] && h[c]++ || (h[c] = 1); }); return h; } s = s.toString(); //just in case var e = 0, l = s.length, h = prob(s); for (var i in h ) { var p = h[i]/l; e -= p * Math.log(p) / Math.log(2); } return e; } //creates Fibonacci Word to n as described on Rosetta Code //see rosettacode.org/wiki/Fibonacci_word function fibWord(n) { var wOne = "1", wTwo = "0", wNth = [wOne, wTwo], w = "", o = []; for (var i = 0; i < n; i++) { if (i === 0 || i === 1) { w = wNth[i]; } else { w = wNth[i - 1] + wNth[i - 2]; wNth.push(w); } var l = w.length; var e = entropy(w); if (l <= 21) { o.push({ N: i + 1, Length: l, Entropy: e, Word: w }); } else { o.push({ N: i + 1, Length: l, Entropy: e, Word: "..." }); } } try { console.table(o); } catch (err) { console_table(o); } } fibWord(37);
File extension is in extensions list
JavaScript
Checking if a file is in a certain category of file formats with known extensions (e.g. archive files, or image files) is a common problem in practice, and may be approached differently from extracting and outputting an arbitrary extension ''(see e.g. FileNameExtensionFilter in Java)''. It also requires less assumptions about the format of an extension, because the calling code can decide what extensions are valid. For these reasons, this task exists in addition to the [[Extract file extension]] task. ;Related tasks: * [[Extract file extension]] * [[String matching]]
function fileExtensionInExtensionsList(filename) { let foundIt = false; let filenameLC = filename.toLowerCase(); let extensions = ["zip", "rar", "7z", "gz", "archive", "A##" ,"tar.bz2"]; extensions.forEach(extension => { if (filenameLC.endsWith("." + extension.toLowerCase())) { foundIt = true; } } ); return foundIt; } // perform tests below var fileNamesToTest = [ "MyData.a##" ,"MyData.tar.Gz" ,"MyData.gzip" ,"MyData.7z.backup" ,"MyData..." ,"MyData" ,"MyData_v1.0.tar.bz2" ,"MyData_v1.0.bz2" ]; fileNamesToTest.forEach(filename => { console.log(filename + " -> " + fileExtensionInExtensionsList(filename)); });
Find limit of recursion
JavaScript
{{selection|Short Circuit|Console Program Basics}} ;Task: Find the limit of recursion.
function recurse(depth) { try { return recurse(depth + 1); } catch(ex) { return depth; } } var maxRecursion = recurse(1); document.write("Recursion depth on this system is " + maxRecursion);
Find palindromic numbers in both binary and ternary bases
JavaScript from Haskell
* Find and show (in decimal) the first six numbers (non-negative integers) that are palindromes in ''both'': :::* base 2 :::* base 3 * Display '''0''' (zero) as the first number found, even though some other definitions ignore it. * Optionally, show the decimal number found in its binary and ternary form. * Show all output here. It's permissible to assume the first two numbers and simply list them. ;See also * Sequence A60792, numbers that are palindromic in bases 2 and 3 on ''The On-Line Encyclopedia of Integer Sequences''.
(() => { 'use strict'; // GENERIC FUNCTIONS // range :: Int -> Int -> [Int] const range = (m, n) => Array.from({ length: Math.floor(n - m) + 1 }, (_, i) => m + i); // compose :: (b -> c) -> (a -> b) -> (a -> c) const compose = (f, g) => x => f(g(x)); // listApply :: [(a -> b)] -> [a] -> [b] const listApply = (fs, xs) => [].concat.apply([], fs.map(f => [].concat.apply([], xs.map(x => [f(x)])))); // pure :: a -> [a] const pure = x => [x]; // curry :: Function -> Function const curry = (f, ...args) => { const go = xs => xs.length >= f.length ? (f.apply(null, xs)) : function () { return go(xs.concat([].slice.apply(arguments))); }; return go([].slice.call(args, 1)); }; // transpose :: [[a]] -> [[a]] const transpose = xs => xs[0].map((_, iCol) => xs.map(row => row[iCol])); // reverse :: [a] -> [a] const reverse = xs => typeof xs === 'string' ? ( xs.split('') .reverse() .join('') ) : xs.slice(0) .reverse(); // take :: Int -> [a] -> [a] const take = (n, xs) => xs.slice(0, n); // drop :: Int -> [a] -> [a] const drop = (n, xs) => xs.slice(n); // maximum :: [a] -> a const maximum = xs => xs.reduce((a, x) => (x > a || a === undefined ? x : a), undefined); // quotRem :: Integral a => a -> a -> (a, a) const quotRem = (m, n) => [Math.floor(m / n), m % n]; // length :: [a] -> Int const length = xs => xs.length; // justifyLeft :: Int -> Char -> Text -> Text const justifyLeft = (n, cFiller, strText) => n > strText.length ? ( (strText + cFiller.repeat(n)) .substr(0, n) ) : strText; // unwords :: [String] -> String const unwords = xs => xs.join(' '); // unlines :: [String] -> String const unlines = xs => xs.join('\n'); // BASES AND PALINDROMES // show, showBinary, showTernary :: Int -> String const show = n => n.toString(10); const showBinary = n => n.toString(2); const showTernary = n => n.toString(3); // readBase3 :: String -> Int const readBase3 = s => parseInt(s, 3); // base3Palindrome :: Int -> String const base3Palindrome = n => { const s = showTernary(n); return s + '1' + reverse(s); }; // isBinPal :: Int -> Bool const isBinPal = n => { const s = showBinary(n), [q, r] = quotRem(s.length, 2); return (r !== 0) && drop(q + 1, s) === reverse(take(q, s)); }; // solutions :: [Int] const solutions = [0, 1].concat(range(1, 10E5) .map(compose(readBase3, base3Palindrome)) .filter(isBinPal)); // TABULATION // cols :: [[Int]] const cols = transpose( [ ['Decimal', 'Ternary', 'Binary'] ].concat( solutions.map( compose( xs => listApply([show, showTernary, showBinary], xs), pure ) ) ) ); return unlines( transpose(cols.map(col => col.map( curry(justifyLeft)(maximum(col.map(length)) + 1, ' ') ))) .map(unwords)); })();
Find the intersection of two lines
JavaScript from Haskell
Finding the intersection of two lines that are in the same plane is an important topic in collision detection.[http://mathworld.wolfram.com/Line-LineIntersection.html] ;Task: Find the point of intersection of two lines in 2D. The 1st line passes though (4,0) and (6,10) . The 2nd line passes though (0,3) and (10,7) .
(() => { 'use strict'; // INTERSECTION OF TWO LINES ---------------------------------------------- // intersection :: Line -> Line -> Either String (Float, Float) const intersection = (ab, pq) => { const delta = f => x => f(fst(x)) - f(snd(x)), [abDX, pqDX, abDY, pqDY] = apList( [delta(fst), delta(snd)], [ab, pq] ), determinant = abDX * pqDY - abDY * pqDX; return determinant !== 0 ? Right((() => { const [abD, pqD] = map( ([a, b]) => fst(a) * snd(b) - fst(b) * snd(a), [ab, pq] ); return apList( [([pq, ab]) => (abD * pq - ab * pqD) / determinant ], [ [pqDX, abDX], [pqDY, abDY] ] ); })()) : Left('(Parallel lines – no intersection)'); }; // GENERIC FUNCTIONS ------------------------------------------------------ // Left :: a -> Either a b const Left = x => ({ type: 'Either', Left: x }); // Right :: b -> Either a b const Right = x => ({ type: 'Either', Right: x }); // A list of functions applied to a list of arguments // <*> :: [(a -> b)] -> [a] -> [b] const apList = (fs, xs) => // [].concat.apply([], fs.map(f => // [].concat.apply([], xs.map(x => [f(x)])))); // fst :: (a, b) -> a const fst = tpl => tpl[0]; // map :: (a -> b) -> [a] -> [b] const map = (f, xs) => xs.map(f); // snd :: (a, b) -> b const snd = tpl => tpl[1]; // show :: a -> String const show = x => JSON.stringify(x); //, null, 2); // TEST -------------------------------------------------- // lrIntersection ::Either String Point const lrIntersection = intersection([ [4.0, 0.0], [6.0, 10.0] ], [ [0.0, 3.0], [10.0, 7.0] ]); return show(lrIntersection.Left || lrIntersection.Right); })();
Find the last Sunday of each month
JavaScript
Write a program or a script that returns the last Sundays of each month of a given year. The year may be given through any simple input method in your language (command line, std in, etc). Example of an expected output: ./last_sundays 2013 2013-01-27 2013-02-24 2013-03-31 2013-04-28 2013-05-26 2013-06-30 2013-07-28 2013-08-25 2013-09-29 2013-10-27 2013-11-24 2013-12-29 ;Related tasks * [[Day of the week]] * [[Five weekends]] * [[Last Friday of each month]]
function lastSundayOfEachMonths(year) { var lastDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; var sundays = []; var date, month; if (year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0)) { lastDay[2] = 29; } for (date = new Date(), month = 0; month < 12; month += 1) { date.setFullYear(year, month, lastDay[month]); date.setDate(date.getDate() - date.getDay()); sundays.push(date.toISOString().substring(0, 10)); } return sundays; } console.log(lastSundayOfEachMonths(2013).join('\n'));
Find the missing permutation
JavaScript
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed. ;Task: Find that missing permutation. ;Methods: * Obvious method: enumerate all permutations of '''A''', '''B''', '''C''', and '''D''', and then look for the missing permutation. * alternate method: Hint: if all permutations were shown above, how many times would '''A''' appear in each position? What is the ''parity'' of this number? * another alternate method: Hint: if you add up the letter values of each column, does a missing letter '''A''', '''B''', '''C''', and '''D''' from each column cause the total value for each column to be unique? ;Related task: * [[Permutations]])
(function (strList) { // [a] -> [[a]] function permutations(xs) { return xs.length ? ( chain(xs, function (x) { return chain(permutations(deleted(x, xs)), function (ys) { return [[x].concat(ys).join('')]; }) })) : [[]]; } // Monadic bind/chain for lists // [a] -> (a -> b) -> [b] function chain(xs, f) { return [].concat.apply([], xs.map(f)); } // a -> [a] -> [a] function deleted(x, xs) { return xs.length ? ( x === xs[0] ? xs.slice(1) : [xs[0]].concat( deleted(x, xs.slice(1)) ) ) : []; } // Provided subset var lstSubSet = strList.split('\n'); // Any missing permutations // (we can use fold/reduce, filter, or chain (concat map) here) return chain(permutations('ABCD'.split('')), function (x) { return lstSubSet.indexOf(x) === -1 ? [x] : []; }); })( 'ABCD\nCABD\nACDB\nDACB\nBCDA\nACBD\nADCB\nCDAB\nDABC\nBCAD\nCADB\n\ CDBA\nCBAD\nABDC\nADBC\nBDCA\nDCBA\nBACD\nBADC\nBDAC\nCBDA\nDBCA\nDCAB' );
Find the missing permutation
JavaScript from Haskell
ABCD CABD ACDB DACB BCDA ACBD ADCB CDAB DABC BCAD CADB CDBA CBAD ABDC ADBC BDCA DCBA BACD BADC BDAC CBDA DBCA DCAB Listed above are all-but-one of the permutations of the symbols '''A''', '''B''', '''C''', and '''D''', ''except'' for one permutation that's ''not'' listed. ;Task: Find that missing permutation. ;Methods: * Obvious method: enumerate all permutations of '''A''', '''B''', '''C''', and '''D''', and then look for the missing permutation. * alternate method: Hint: if all permutations were shown above, how many times would '''A''' appear in each position? What is the ''parity'' of this number? * another alternate method: Hint: if you add up the letter values of each column, does a missing letter '''A''', '''B''', '''C''', and '''D''' from each column cause the total value for each column to be unique? ;Related task: * [[Permutations]])
(() => { 'use strict'; // MISSING PERMUTATION --------------------------------------------------- // missingPermutation :: [String] -> String const missingPermutation = xs => map( // Rarest letter, compose([ sort, group, curry(minimumBy)(comparing(length)), head ]), // in each column. transpose(map(stringChars, xs)) ) .join(''); // GENERIC FUNCTIONAL PRIMITIVES ----------------------------------------- // transpose :: [[a]] -> [[a]] const transpose = xs => xs[0].map((_, iCol) => xs.map(row => row[iCol])); // sort :: Ord a => [a] -> [a] const sort = xs => xs.sort(); // group :: Eq a => [a] -> [[a]] const group = xs => groupBy((a, b) => a === b, xs); // groupBy :: (a -> a -> Bool) -> [a] -> [[a]] const groupBy = (f, xs) => { const dct = xs.slice(1) .reduce((a, x) => { const h = a.active.length > 0 ? a.active[0] : undefined, blnGroup = h !== undefined && f(h, x); return { active: blnGroup ? a.active.concat(x) : [x], sofar: blnGroup ? a.sofar : a.sofar.concat([a.active]) }; }, { active: xs.length > 0 ? [xs[0]] : [], sofar: [] }); return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []); }; // length :: [a] -> Int const length = xs => xs.length; // comparing :: (a -> b) -> (a -> a -> Ordering) const comparing = f => (x, y) => { const a = f(x), b = f(y); return a < b ? -1 : a > b ? 1 : 0 }; // minimumBy :: (a -> a -> Ordering) -> [a] -> a const minimumBy = (f, xs) => xs.reduce((a, x) => a === undefined ? x : ( f(x, a) < 0 ? x : a ), undefined); // head :: [a] -> a const head = xs => xs.length ? xs[0] : undefined; // map :: (a -> b) -> [a] -> [b] const map = (f, xs) => xs.map(f) // compose :: [(a -> a)] -> (a -> a) const compose = fs => x => fs.reduce((a, f) => f(a), x); // curry :: ((a, b) -> c) -> a -> b -> c const curry = f => a => b => f(a, b); // stringChars :: String -> [Char] const stringChars = s => s.split(''); // TEST ------------------------------------------------------------------ return missingPermutation(["ABCD", "CABD", "ACDB", "DACB", "BCDA", "ACBD", "ADCB", "CDAB", "DABC", "BCAD", "CADB", "CDBA", "CBAD", "ABDC", "ADBC", "BDCA", "DCBA", "BACD", "BADC", "BDAC", "CBDA", "DBCA", "DCAB" ]); // -> "DBAC" })();
First-class functions/Use numbers analogously
JavaScript
In [[First-class functions]], a language is showing how its manipulation of functions is similar to its manipulation of other types. This tasks aim is to compare and contrast a language's implementation of first class functions, with its normal handling of numbers. Write a program to create an ordered collection of a mixture of literally typed and expressions producing a real number, together with another ordered collection of their multiplicative inverses. Try and use the following pseudo-code to generate the numbers for the ordered collections: x = 2.0 xi = 0.5 y = 4.0 yi = 0.25 z = x + y zi = 1.0 / ( x + y ) Create a function ''multiplier'', that given two numbers as arguments returns a function that when called with one argument, returns the result of multiplying the two arguments to the call to multiplier that created it and the argument in the call: new_function = multiplier(n1,n2) # where new_function(m) returns the result of n1 * n2 * m Applying the multiplier of a number and its inverse from the two ordered collections of numbers in pairs, show that the result in each case is one. '''Compare and contrast the resultant program with the corresponding entry in [[First-class functions]].''' They should be close. To paraphrase the task description: Do what was done before, but with numbers rather than functions
const x = 2.0; const xi = 0.5; const y = 4.0; const yi = 0.25; const z = x + y; const zi = 1.0 / (x + y); const pairs = [[x, xi], [y, yi], [z, zi]]; const testVal = 0.5; const multiplier = (a, b) => m => a * b * m; const test = () => { return pairs.map(([a, b]) => { const f = multiplier(a, b); const result = f(testVal); return `${a} * ${b} * ${testVal} = ${result}`; }); } test().join('\n');
First perfect square in base n with n unique digits
JavaScript from Python
Find the first perfect square in a given base '''N''' that has at least '''N''' digits and exactly '''N''' ''significant unique'' digits when expressed in base '''N'''. E.G. In base '''10''', the first perfect square with at least '''10''' unique digits is '''1026753849''' ('''320432'''). You may use analytical methods to reduce the search space, but the code must do a search. Do not use magic numbers or just feed the code the answer to verify it is correct. ;Task * Find and display here, on this page, the first perfect square in base '''N''', with '''N''' significant unique digits when expressed in base '''N''', for each of base '''2''' through '''12'''. Display each number in the base '''N''' for which it was calculated. * (optional) Do the same for bases '''13''' through '''16'''. * (stretch goal) Continue on for bases '''17''' - '''??''' (Big Integer math) ;See also: ;* OEIS A260182: smallest square that is pandigital in base n. ;Related task ;* [[Casting out nines]]
(() => { 'use strict'; // allDigitSquare :: Int -> Int const allDigitSquare = base => { const bools = replicate(base, false); return untilSucc( allDigitsUsedAtBase(base, bools), ceil(sqrt(parseInt( '10' + '0123456789abcdef'.slice(2, base), base ))) ); }; // allDigitsUsedAtBase :: Int -> [Bool] -> Int -> Bool const allDigitsUsedAtBase = (base, bools) => n => { // Fusion of representing the square of integer N at a given base // with checking whether all digits of that base contribute to N^2. // Sets the bool at a digit position to True when used. // True if all digit positions have been used. const ds = bools.slice(0); let x = n * n; while (x) { ds[x % base] = true; x = floor(x / base); } return ds.every(x => x) }; // showBaseSquare :: Int -> String const showBaseSquare = b => { const q = allDigitSquare(b); return justifyRight(2, ' ', str(b)) + ' -> ' + justifyRight(8, ' ', showIntAtBase(b, digit, q, '')) + ' -> ' + showIntAtBase(b, digit, q * q, ''); }; // TEST ----------------------------------------------- const main = () => { // 1-12 only - by 15 the squares are truncated by // JS integer limits. // Returning values through console.log – // in separate events to avoid asynchronous disorder. print('Smallest perfect squares using all digits in bases 2-12:\n') (id > 0 ? chars.substr(id, 1) : " ") print('Base Root Square') print(showBaseSquare(2)); print(showBaseSquare(3)); print(showBaseSquare(4)); print(showBaseSquare(5)); print(showBaseSquare(6)); print(showBaseSquare(7)); print(showBaseSquare(8)); print(showBaseSquare(9)); print(showBaseSquare(10)); print(showBaseSquare(11)); print(showBaseSquare(12)); }; // GENERIC FUNCTIONS ---------------------------------- const ceil = Math.ceil, floor = Math.floor, sqrt = Math.sqrt; // Tuple (,) :: a -> b -> (a, b) const Tuple = (a, b) => ({ type: 'Tuple', '0': a, '1': b, length: 2 }); // digit :: Int -> Char const digit = n => // Digit character for given integer. '0123456789abcdef' [n]; // enumFromTo :: (Int, Int) -> [Int] const enumFromTo = (m, n) => Array.from({ length: 1 + n - m }, (_, i) => m + i); // justifyRight :: Int -> Char -> String -> String const justifyRight = (n, cFiller, s) => n > s.length ? ( s.padStart(n, cFiller) ) : s; // print :: a -> IO () const print = x => console.log(x) // quotRem :: Int -> Int -> (Int, Int) const quotRem = (m, n) => Tuple(Math.floor(m / n), m % n); // replicate :: Int -> a -> [a] const replicate = (n, x) => Array.from({ length: n }, () => x); // showIntAtBase :: Int -> (Int -> Char) -> Int -> String -> String const showIntAtBase = (base, toChr, n, rs) => { const go = ([n, d], r) => { const r_ = toChr(d) + r; return 0 !== n ? ( go(Array.from(quotRem(n, base)), r_) ) : r_; }; return 1 >= base ? ( 'error: showIntAtBase applied to unsupported base' ) : 0 > n ? ( 'error: showIntAtBase applied to negative number' ) : go(Array.from(quotRem(n, base)), rs); }; // Abbreviation for quick testing - any 2nd arg interpreted as indent size // sj :: a -> String function sj() { const args = Array.from(arguments); return JSON.stringify.apply( null, 1 < args.length && !isNaN(args[0]) ? [ args[1], null, args[0] ] : [args[0], null, 2] ); } // str :: a -> String const str = x => x.toString(); // untilSucc :: (Int -> Bool) -> Int -> Int const untilSucc = (p, x) => { // The first in a chain of successive integers // for which p(x) returns true. let v = x; while (!p(v)) v = 1 + v; return v; }; // MAIN --- return main(); })();
Fivenum
JavaScript
Many big data or scientific programs use boxplots to show distributions of data. In addition, sometimes saving large arrays for boxplots can be impractical and use extreme amounts of RAM. It can be useful to save large arrays as arrays with five numbers to save memory. For example, the '''R''' programming language implements Tukey's five-number summary as the '''fivenum''' function. ;Task: Given an array of numbers, compute the five-number summary. ;Note: While these five numbers can be used to draw a boxplot, statistical packages will typically need extra data. Moreover, while there is a consensus about the "box" of the boxplot, there are variations among statistical packages for the whiskers.
function median(arr) { let mid = Math.floor(arr.length / 2); return (arr.length % 2 == 0) ? (arr[mid-1] + arr[mid]) / 2 : arr[mid]; } Array.prototype.fiveNums = function() { this.sort(function(a, b) { return a - b} ); let mid = Math.floor(this.length / 2), loQ = (this.length % 2 == 0) ? this.slice(0, mid) : this.slice(0, mid+1), hiQ = this.slice(mid); return [ this[0], median(loQ), median(this), median(hiQ), this[this.length-1] ]; } // testing let test = [15, 6, 42, 41, 7, 36, 49, 40, 39, 47, 43]; console.log( test.fiveNums() ); test = [0, 0, 1, 2, 63, 61, 27, 13]; console.log( test.fiveNums() ); test = [ 0.14082834, 0.09748790, 1.73131507, 0.87636009, -1.95059594, 0.73438555, -0.03035726, 1.46675970, -0.74621349, -0.72588772, 0.63905160, 0.61501527, -0.98983780, -1.00447874, -0.62759469, 0.66206163, 1.04312009, -0.10305385, 0.75775634, 0.32566578]; console.log( test.fiveNums() );
Flatten a list
JavaScript
Write a function to flatten the nesting in an arbitrary list of values. Your program should work on the equivalent of this list: [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] Where the correct result would be the list: [1, 2, 3, 4, 5, 6, 7, 8] ;Related task: * [[Tree traversal]]
(function () { 'use strict'; // flatten :: Tree a -> [a] function flatten(t) { return (t instanceof Array ? concatMap(flatten, t) : t); } // concatMap :: (a -> [b]) -> [a] -> [b] function concatMap(f, xs) { return [].concat.apply([], xs.map(f)); } return flatten( [[1], 2, [[3, 4], 5], [[[]]], [[[6]]], 7, 8, []] ); })();
Flipping bits game
JavaScript
The game: Given an '''NxN''' square array of zeroes or ones in an initial configuration, and a target configuration of zeroes and ones. The game is to transform one to the other in as few moves as possible by inverting whole numbered rows or whole lettered columns at once (as one move). In an inversion. any '''1''' becomes '''0''', and any '''0''' becomes '''1''' for that whole row or column. ;Task: Create a program to score for the Flipping bits game. # The game should create an original random target configuration and a starting configuration. # Ensure that the starting position is ''never'' the target position. # The target position must be guaranteed as reachable from the starting position. (One possible way to do this is to generate the start position by legal flips from a random target position. The flips will always be reversible back to the target from the given start position). # The number of moves taken so far should be shown. Show an example of a short game here, on this page, for a '''3x3''' array of bits.
function numOfRows(board) { return board.length; } function numOfCols(board) { return board[0].length; } function boardToString(board) { // First the top-header var header = ' '; for (var c = 0; c < numOfCols(board); c++) header += c + ' '; // Then the side-header + board var sideboard = []; for (var r = 0; r < numOfRows(board); r++) { sideboard.push(r + ' [' + board[r].join(' ') + ']'); } return header + '\n' + sideboard.join('\n'); } function flipRow(board, row) { for (var c = 0; c < numOfCols(board); c++) { board[row][c] = 1 - board[row][c]; } } function flipCol(board, col) { for (var r = 0; r < numOfRows(board); r++) { board[r][col] = 1 - board[r][col]; } } function playFlippingBitsGame(rows, cols) { rows = rows | 3; cols = cols | 3; var targetBoard = []; var manipulatedBoard = []; // Randomly generate two identical boards. for (var r = 0; r < rows; r++) { targetBoard.push([]); manipulatedBoard.push([]); for (var c = 0; c < cols; c++) { targetBoard[r].push(Math.floor(Math.random() * 2)); manipulatedBoard[r].push(targetBoard[r][c]); } } // Naive-scramble one of the boards. while (boardToString(targetBoard) == boardToString(manipulatedBoard)) { var scrambles = rows * cols; while (scrambles-- > 0) { if (0 == Math.floor(Math.random() * 2)) { flipRow(manipulatedBoard, Math.floor(Math.random() * rows)); } else { flipCol(manipulatedBoard, Math.floor(Math.random() * cols)); } } } // Get the user to solve. alert( 'Try to match both boards.\n' + 'Enter `r<num>` or `c<num>` to manipulate a row or col or enter `q` to quit.' ); var input = '', letter, num, moves = 0; while (boardToString(targetBoard) != boardToString(manipulatedBoard) && input != 'q') { input = prompt( 'Target:\n' + boardToString(targetBoard) + '\n\n\n' + 'Board:\n' + boardToString(manipulatedBoard) ); try { letter = input.charAt(0); num = parseInt(input.slice(1)); if (letter == 'q') break; if (isNaN(num) || (letter != 'r' && letter != 'c') || (letter == 'r' && num >= rows) || (letter == 'c' && num >= cols) ) { throw new Error(''); } if (letter == 'r') { flipRow(manipulatedBoard, num); } else { flipCol(manipulatedBoard, num); } moves++; } catch(e) { alert('Uh-oh, there seems to have been an input error'); } } if (input == 'q') { alert('~~ Thanks for playing ~~'); } else { alert('Completed in ' + moves + ' moves.'); } }
Floyd's triangle
JavaScript
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where * the first row is '''1''' (unity) * successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ;Task: :# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows). :# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
(function () { 'use strict'; // FLOYD's TRIANGLE ------------------------------------------------------- // floyd :: Int -> [[Int]] function floyd(n) { return snd(mapAccumL(function (start, row) { return [start + row + 1, enumFromTo(start, start + row)]; }, 1, enumFromTo(0, n - 1))); }; // showFloyd :: [[Int]] -> String function showFloyd(xss) { var ws = map(compose([succ, length, show]), last(xss)); return unlines(map(function (xs) { return concat(zipWith(function (w, x) { return justifyRight(w, ' ', show(x)); }, ws, xs)); }, xss)); }; // GENERIC FUNCTIONS ------------------------------------------------------ // compose :: [(a -> a)] -> (a -> a) function compose(fs) { return function (x) { return fs.reduceRight(function (a, f) { return f(a); }, x); }; }; // concat :: [[a]] -> [a] | [String] -> String function concat(xs) { if (xs.length > 0) { var unit = typeof xs[0] === 'string' ? '' : []; return unit.concat.apply(unit, xs); } else return []; }; // enumFromTo :: Int -> Int -> [Int] function enumFromTo(m, n) { return Array.from({ length: Math.floor(n - m) + 1 }, function (_, i) { return m + i; }); }; // justifyRight :: Int -> Char -> Text -> Text function justifyRight(n, cFiller, strText) { return n > strText.length ? (cFiller.repeat(n) + strText) .slice(-n) : strText; }; // last :: [a] -> a function last(xs) { return xs.length ? xs.slice(-1)[0] : undefined; }; // length :: [a] -> Int function length(xs) { return xs.length; }; // map :: (a -> b) -> [a] -> [b] function map(f, xs) { return xs.map(f); }; // 'The mapAccumL function behaves like a combination of map and foldl; // it applies a function to each element of a list, passing an accumulating // parameter from left to right, and returning a final value of this // accumulator together with the new list.' (See hoogle ) // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) function mapAccumL(f, acc, xs) { return xs.reduce(function (a, x) { var pair = f(a[0], x); return [pair[0], a[1].concat([pair[1]])]; }, [acc, []]); }; // show :: // (a -> String) f, Num n => // a -> maybe f -> maybe n -> String var show = JSON.stringify; // snd :: (a, b) -> b function snd(tpl) { return Array.isArray(tpl) ? tpl[1] : undefined; }; // succ :: Int -> Int function succ(x) { return x + 1; }; // unlines :: [String] -> String function unlines(xs) { return xs.join('\n'); }; // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] function zipWith(f, xs, ys) { var ny = ys.length; return (xs.length <= ny ? xs : xs.slice(0, ny)) .map(function (x, i) { return f(x, ys[i]); }); }; // TEST ( n=5 and n=14 rows ) --------------------------------------------- return unlines(map(function (n) { return showFloyd(floyd(n)) + '\n'; }, [5, 14])); })();
Floyd's triangle
JavaScript from Haskell
Floyd's triangle lists the natural numbers in a right triangle aligned to the left where * the first row is '''1''' (unity) * successive rows start towards the left with the next number followed by successive naturals listing one more number than the line above. The first few lines of a Floyd triangle looks like this: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ;Task: :# Write a program to generate and display here the first n lines of a Floyd triangle. (Use n=5 and n=14 rows). :# Ensure that when displayed in a mono-space font, the numbers line up in vertical columns as shown and that only one space separates numbers of the last row.
(() => { 'use strict'; // FLOYD's TRIANGLE ------------------------------------------------------- // floyd :: Int -> [[Int]] const floyd = n => snd(mapAccumL( (start, row) => [start + row + 1, enumFromTo(start, start + row)], 1, enumFromTo(0, n - 1) )); // showFloyd :: [[Int]] -> String const showFloyd = xss => { const ws = map(compose([succ, length, show]), last(xss)); return unlines( map(xs => concat(zipWith( (w, x) => justifyRight(w, ' ', show(x)), ws, xs )), xss ) ); }; // GENERIC FUNCTIONS ------------------------------------------------------ // compose :: [(a -> a)] -> (a -> a) const compose = fs => x => fs.reduceRight((a, f) => f(a), x); // concat :: [[a]] -> [a] | [String] -> String const concat = xs => { if (xs.length > 0) { const unit = typeof xs[0] === 'string' ? '' : []; return unit.concat.apply(unit, xs); } else return []; }; // enumFromTo :: Int -> Int -> [Int] const enumFromTo = (m, n) => Array.from({ length: Math.floor(n - m) + 1 }, (_, i) => m + i); // justifyRight :: Int -> Char -> Text -> Text const justifyRight = (n, cFiller, strText) => n > strText.length ? ( (cFiller.repeat(n) + strText) .slice(-n) ) : strText; // last :: [a] -> a const last = xs => xs.length ? xs.slice(-1)[0] : undefined; // length :: [a] -> Int const length = xs => xs.length; // map :: (a -> b) -> [a] -> [b] const map = (f, xs) => xs.map(f) // 'The mapAccumL function behaves like a combination of map and foldl; // it applies a function to each element of a list, passing an accumulating // parameter from left to right, and returning a final value of this // accumulator together with the new list.' (See hoogle ) // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) const mapAccumL = (f, acc, xs) => xs.reduce((a, x) => { const pair = f(a[0], x); return [pair[0], a[1].concat([pair[1]])]; }, [acc, []]); // show :: // (a -> String) f, Num n => // a -> maybe f -> maybe n -> String const show = JSON.stringify; // snd :: (a, b) -> b const snd = tpl => Array.isArray(tpl) ? tpl[1] : undefined; // succ :: Int -> Int const succ = x => x + 1 // unlines :: [String] -> String const unlines = xs => xs.join('\n'); // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = (f, xs, ys) => { const ny = ys.length; return (xs.length <= ny ? xs : xs.slice(0, ny)) .map((x, i) => f(x, ys[i])); }; // TEST ( n=5 and n=14 rows ) --------------------------------------------- return unlines(map(n => showFloyd(floyd(n)) + '\n', [5, 14])) })();
Four bit adder
JavaScript
"''Simulate''" a four-bit adder. This design can be realized using four 1-bit full adders. Each of these 1-bit full adders can be built with two gate. ; Finally a half adder can be made using an ''xor'' gate and an ''and'' gate. The ''xor'' gate can be made using two ''not''s, two ''and''s and one ''or''. '''Not''', '''or''' and '''and''', the only allowed "gates" for the task, can be "imitated" by using the bitwise operators of your language. If there is not a ''bit type'' in your language, to be sure that the ''not'' does not "invert" all the other bits of the basic type (e.g. a byte) we are not interested in, you can use an extra ''nand'' (''and'' then ''not'') with the constant '''1''' on one input. Instead of optimizing and reducing the number of gates used for the final 4-bit adder, build it in the most straightforward way, ''connecting'' the other "constructive blocks", in turn made of "simpler" and "smaller" ones. {| |+Schematics of the "constructive blocks" !(Xor gate with ANDs, ORs and NOTs) ! (A half adder) ! (A full adder) ! (A 4-bit adder) |- |Xor gate done with ands, ors and nots |A half adder |A full adder |A 4-bit adder |} Solutions should try to be as descriptive as possible, making it as easy as possible to identify "connections" between higher-order "blocks". It is not mandatory to replicate the syntax of higher-order blocks in the atomic "gate" blocks, i.e. basic "gate" operations can be performed as usual bitwise operations, or they can be "wrapped" in a ''block'' in order to expose the same syntax of higher-order blocks, at implementers' choice. To test the implementation, show the sum of two four-bit numbers (in binary).
// basic building blocks allowed by the rules are ~, &, and |, we'll fake these // in a way that makes what they do (at least when you use them) more obvious // than the other available options do. function not(a) { if (arePseudoBin(a)) return a == 1 ? 0 : 1; } function and(a, b) { if (arePseudoBin(a, b)) return a + b < 2 ? 0 : 1; } function nand(a, b) { if (arePseudoBin(a, b)) return not(and(a, b)); } function or(a, b) { if (arePseudoBin(a, b)) return nand(nand(a,a), nand(b,b)); } function xor(a, b) { if (arePseudoBin(a, b)) return nand(nand(nand(a,b), a), nand(nand(a,b), b)); } function halfAdder(a, b) { if (arePseudoBin(a, b)) return { carry: and(a, b), sum: xor(a, b) }; } function fullAdder(a, b, c) { if (arePseudoBin(a, b, c)) { var h0 = halfAdder(a, b), h1 = halfAdder(h0.sum, c); return {carry: or(h0.carry, h1.carry), sum: h1.sum }; } } function fourBitAdder(a, b) { if (typeof a.length == 'undefined' || typeof b.length == 'undefined') throw new Error('bad values'); // not sure if the rules allow this, but we need to pad the values // if they're too short and trim them if they're too long var inA = Array(4), inB = Array(4), out = Array(4), i = 4, pass; while (i--) { inA[i] = a[i] != 1 ? 0 : 1; inB[i] = b[i] != 1 ? 0 : 1; } // now we can start adding... I'd prefer to do this in a loop, // but that wouldn't be "connecting the other 'constructive blocks', // in turn made of 'simpler' and 'smaller' ones" pass = halfAdder(inA[3], inB[3]); out[3] = pass.sum; pass = fullAdder(inA[2], inB[2], pass.carry); out[2] = pass.sum; pass = fullAdder(inA[1], inB[1], pass.carry); out[1] = pass.sum; pass = fullAdder(inA[0], inB[0], pass.carry); out[0] = pass.sum; return out.join(''); }
Four is magic
JavaScript
Write a subroutine, function, whatever it may be called in your language, that takes an integer number and returns an English text sequence starting with the English cardinal representation of that integer, the word 'is' and then the English cardinal representation of the count of characters that made up the first word, followed by a comma. Continue the sequence by using the previous count word as the first word of the next phrase, append 'is' and the cardinal count of the letters in ''that'' word. Continue until you reach four. Since four has four characters, finish by adding the words 'four is magic' and a period. All integers will eventually wind up at four. For instance, suppose your are given the integer '''3'''. Convert '''3''' to '''Three''', add ''' is ''', then the cardinal character count of three, or '''five''', with a comma to separate if from the next phrase. Continue the sequence '''five is four,''' (five has four letters), and finally, '''four is magic.''' '''Three is five, five is four, four is magic.''' For reference, here are outputs for 0 through 9. Zero is four, four is magic. One is three, three is five, five is four, four is magic. Two is three, three is five, five is four, four is magic. Three is five, five is four, four is magic. Four is magic. Five is four, four is magic. Six is three, three is five, five is four, four is magic. Seven is five, five is four, four is magic. Eight is five, five is four, four is magic. Nine is four, four is magic. ;Some task guidelines: :* You may assume the input will only contain integer numbers. :* Cardinal numbers between 20 and 100 may use either hyphens or spaces as word separators but they must use a word separator. ('''23''' is '''twenty three''' or '''twenty-three''' not '''twentythree'''.) :* Cardinal number conversions should follow the English short scale. (billion is 1e9, trillion is 1e12, etc.) :* Cardinal numbers should not include commas. ('''20140''' is '''twenty thousand one hundred forty''' not '''twenty thousand, one hundred forty'''.) :* When converted to a string, '''100''' should be '''one hundred''', not '''a hundred''' or '''hundred''', '''1000''' should be '''one thousand''', not '''a thousand''' or '''thousand'''. :* When converted to a string, there should be no '''and''' in the cardinal string. '''130''' should be '''one hundred thirty''' not '''one hundred and thirty'''. :* When counting characters, count ''all'' of the characters in the cardinal number including spaces and hyphens. '''One hundred fifty-one''' should be '''21''' not '''18'''. :* The output should follow the format "N is K, K is M, M is ... four is magic." (unless the input is 4, in which case the output should simply be "four is magic.") :* The output can either be the return value from the function, or be displayed from within the function. :* You are encouraged, though not mandated to use proper sentence capitalization. :* You may optionally support negative numbers. '''-7''' is '''negative seven'''. :* Show the output here for a small representative sample of values, at least 5 but no more than 25. You are free to choose which which numbers to use for output demonstration. You can choose to use a library, (module, external routine, whatever) to do the cardinal conversions as long as the code is easily and freely available to the public. If you roll your own, make the routine accept at minimum any integer from 0 up to 999999. If you use a pre-made library, support at least up to unsigned 64 bit integers. (or the largest integer supported in your language if it is less.) Four is magic is a popular code-golf task. '''This is not code golf.''' Write legible, idiomatic and well formatted code. ;Related tasks: :* [[Four is the number of_letters in the ...]] :* [[Look-and-say sequence]] :* [[Number names]] :* [[Self-describing numbers]] :* [[Summarize and say sequence]] :* [[Spelling of ordinal numbers]] :* [[De Bruijn sequences]]
const reverseOrderedNumberToTextMap = (function () { const rawNumberToTextMapping = { // Ported over from the Python solution. [1n]: "one", [2n]: "two", [3n]: "three", [4n]: "four", [5n]: "five", [6n]: "six", [7n]: "seven", [8n]: "eight", [9n]: "nine", [10n]: "ten", [11n]: "eleven", [12n]: "twelve", [13n]: "thirteen", [14n]: "fourteen", [15n]: "fifteen", [16n]: "sixteen", [17n]: "seventeen", [18n]: "eighteen", [19n]: "nineteen", [20n]: "twenty", [30n]: "thirty", [40n]: "forty", [50n]: "fifty", [60n]: "sixty", [70n]: "seventy", [80n]: "eighty", [90n]: "ninety", [100n]: "hundred", [1000n]: "thousand", [10n ** 6n]: "million", [10n ** 9n]: "billion", [10n ** 12n]: "trillion", [10n ** 15n]: "quadrillion", [10n ** 18n]: "quintillion", [10n ** 21n]: "sextillion", [10n ** 24n]: "septillion", [10n ** 27n]: "octillion", [10n ** 30n]: "nonillion", [10n ** 33n]: "decillion", [10n ** 36n]: "undecillion", [10n ** 39n]: "duodecillion", [10n ** 42n]: "tredecillion", [10n ** 45n]: "quattuordecillion", [10n ** 48n]: "quinquadecillion", [10n ** 51n]: "sedecillion", [10n ** 54n]: "septendecillion", [10n ** 57n]: "octodecillion", [10n ** 60n]: "novendecillion", [10n ** 63n]: "vigintillion", [10n ** 66n]: "unvigintillion", [10n ** 69n]: "duovigintillion", [10n ** 72n]: "tresvigintillion", [10n ** 75n]: "quattuorvigintillion", [10n ** 78n]: "quinquavigintillion", [10n ** 81n]: "sesvigintillion", [10n ** 84n]: "septemvigintillion", [10n ** 87n]: "octovigintillion", [10n ** 90n]: "novemvigintillion", [10n ** 93n]: "trigintillion", [10n ** 96n]: "untrigintillion", [10n ** 99n]: "duotrigintillion", [10n ** 102n]: "trestrigintillion", [10n ** 105n]: "quattuortrigintillion", [10n ** 108n]: "quinquatrigintillion", [10n ** 111n]: "sestrigintillion", [10n ** 114n]: "septentrigintillion", [10n ** 117n]: "octotrigintillion", [10n ** 120n]: "noventrigintillion", [10n ** 123n]: "quadragintillion", [10n ** 153n]: "quinquagintillion", [10n ** 183n]: "sexagintillion", [10n ** 213n]: "septuagintillion", [10n ** 243n]: "octogintillion", [10n ** 273n]: "nonagintillion", [10n ** 303n]: "centillion", [10n ** 306n]: "uncentillion", [10n ** 309n]: "duocentillion", [10n ** 312n]: "trescentillion", [10n ** 333n]: "decicentillion", [10n ** 336n]: "undecicentillion", [10n ** 363n]: "viginticentillion", [10n ** 366n]: "unviginticentillion", [10n ** 393n]: "trigintacentillion", [10n ** 423n]: "quadragintacentillion", [10n ** 453n]: "quinquagintacentillion", [10n ** 483n]: "sexagintacentillion", [10n ** 513n]: "septuagintacentillion", [10n ** 543n]: "octogintacentillion", [10n ** 573n]: "nonagintacentillion", [10n ** 603n]: "ducentillion", [10n ** 903n]: "trecentillion", [10n ** 1203n]: "quadringentillion", [10n ** 1503n]: "quingentillion", [10n ** 1803n]: "sescentillion", [10n ** 2103n]: "septingentillion", [10n ** 2403n]: "octingentillion", [10n ** 2703n]: "nongentillion", [10n ** 3003n]: "millinillion" }; return new Map(Object.entries(rawNumberToTextMapping) .sort((a, b) => BigInt(a[0]) > BigInt(b[0]) ? -1 : 1) .map(numberAndText => [BigInt(numberAndText[0]), numberAndText[1]])); })(); function getCardinalRepresentation(number) { if (number == 0n) { return "zero"; } function* generateCardinalRepresentationTokens(number) { if (number <= 0n) { yield "negative"; number *= -1n; } for (const [currentEntryNumber, currentEntryText] of reverseOrderedNumberToTextMap.entries()) { if (number >= currentEntryNumber) { if (currentEntryNumber >= 100n) { yield* generateCardinalRepresentationTokens(number / currentEntryNumber); } yield currentEntryText; number -= currentEntryNumber; } } } return [...generateCardinalRepresentationTokens(number)].join(" "); } function* generateFourIsMagicParts(number) { if (typeof number != "bigint") { number = BigInt(number); } if (number == 4n) { yield "four is magic"; } else { const cardinalRepresentation = getCardinalRepresentation(number); yield `${cardinalRepresentation} is ${getCardinalRepresentation(BigInt(cardinalRepresentation.length))}`; yield* generateFourIsMagicParts(cardinalRepresentation.length); } } function capitalizeFirstLetter(str) { return str.replace(/^([a-z])/, chr => chr.toUpperCase()); } function fourIsMagic(number) { return capitalizeFirstLetter(`${[...generateFourIsMagicParts(number)].join(", ")}.`); } [ 0, -150, 210, 10n ** 2703n + 1225n, 4, -4, 10n ** 3003n + 42n ].map(fourIsMagic).join("\n\n");
Function prototype
JavaScript
Some languages provide the facility to declare functions and subroutines through the use of function prototyping. ;Task: Demonstrate the methods available for declaring prototypes within the language. The provided solutions should include: * An explanation of any placement restrictions for prototype declarations * A prototype declaration for a function that does not require arguments * A prototype declaration for a function that requires two arguments * A prototype declaration for a function that utilizes varargs * A prototype declaration for a function that utilizes optional arguments * A prototype declaration for a function that utilizes named parameters * Example of prototype declarations for subroutines or procedures (if these differ from functions) * An explanation and example of any special forms of prototyping not covered by the above Languages that do not provide function prototyping facilities should be omitted from this task.
// A prototype declaration for a function that does not require arguments function List() {} List.prototype.push = function() { return [].push.apply(this, arguments); }; List.prototype.pop = function() { return [].pop.call(this); }; var l = new List(); l.push(5); l.length; // 1 l[0]; 5 l.pop(); // 5 l.length; // 0 // A prototype declaration for a function that utilizes varargs function List() { this.push.apply(this, arguments); } List.prototype.push = function() { return [].push.apply(this, arguments); }; List.prototype.pop = function() { return [].pop.call(this); }; var l = new List(5, 10, 15); l.length; // 3 l[0]; 5 l.pop(); // 15 l.length; // 2
Functional coverage tree
JavaScript
Functional coverage is a measure of how much a particular function of a system has been verified as correct. It is used heavily in tracking the completeness of the verification of complex System on Chip (SoC) integrated circuits, where it can also be used to track how well the functional ''requirements'' of the system have been verified. This task uses a sub-set of the calculations sometimes used in tracking functional coverage but uses a more familiar(?) scenario. ;Task Description: The head of the clean-up crews for "The Men in a very dark shade of grey when viewed at night" has been tasked with managing the cleansing of two properties after an incident involving aliens. She arranges the task hierarchically with a manager for the crews working on each house who return with a breakdown of how they will report on progress in each house. The overall hierarchy of (sub)tasks is as follows, cleaning house1 bedrooms bathrooms bathroom1 bathroom2 outside lavatory attic kitchen living rooms lounge dining room conservatory playroom basement garage garden house2 upstairs bedrooms suite 1 suite 2 bedroom 3 bedroom 4 bathroom toilet attics groundfloor kitchen living rooms lounge dining room conservatory playroom wet room & toilet garage garden hot tub suite basement cellars wine cellar cinema The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit. Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0. NAME_HIERARCHY |WEIGHT |COVERAGE | cleaning | | | house1 |40 | | bedrooms | |0.25 | bathrooms | | | bathroom1 | |0.5 | bathroom2 | | | outside_lavatory | |1 | attic | |0.75 | kitchen | |0.1 | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | |1 | basement | | | garage | | | garden | |0.8 | house2 |60 | | upstairs | | | bedrooms | | | suite_1 | | | suite_2 | | | bedroom_3 | | | bedroom_4 | | | bathroom | | | toilet | | | attics | |0.6 | groundfloor | | | kitchen | | | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | | | wet_room_&_toilet | | | garage | | | garden | |0.9 | hot_tub_suite | |1 | basement | | | cellars | |1 | wine_cellar | |1 | cinema | |0.75 | ;Calculation: The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree. '''The task is to''' calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes. ;Extra Credit: After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1-coverage for any node, by the product of the `powers` of its parent nodes from the top down to the node. The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children. The pseudo code would be: method delta_calculation(this, power): sum_of_weights = sum(node.weight for node in children) this.delta = (1 - this.coverage) * power for node in self.children: node.delta_calculation(power * node.weight / sum_of_weights) return this.delta Followed by a call to: top.delta_calculation(power=1) '''Note:''' to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
Parsing the outline text to a tree structure, and traversing this with two computations (one bottom-up, and one top-down), before serialising the updated tree to a new outline text.
Functional coverage tree
JavaScript from Python
Functional coverage is a measure of how much a particular function of a system has been verified as correct. It is used heavily in tracking the completeness of the verification of complex System on Chip (SoC) integrated circuits, where it can also be used to track how well the functional ''requirements'' of the system have been verified. This task uses a sub-set of the calculations sometimes used in tracking functional coverage but uses a more familiar(?) scenario. ;Task Description: The head of the clean-up crews for "The Men in a very dark shade of grey when viewed at night" has been tasked with managing the cleansing of two properties after an incident involving aliens. She arranges the task hierarchically with a manager for the crews working on each house who return with a breakdown of how they will report on progress in each house. The overall hierarchy of (sub)tasks is as follows, cleaning house1 bedrooms bathrooms bathroom1 bathroom2 outside lavatory attic kitchen living rooms lounge dining room conservatory playroom basement garage garden house2 upstairs bedrooms suite 1 suite 2 bedroom 3 bedroom 4 bathroom toilet attics groundfloor kitchen living rooms lounge dining room conservatory playroom wet room & toilet garage garden hot tub suite basement cellars wine cellar cinema The head of cleanup knows that her managers will report fractional completion of leaf tasks (tasks with no child tasks of their own), and she knows that she will want to modify the weight of values of completion as she sees fit. Some time into the cleaning, and some coverage reports have come in and she thinks see needs to weight the big house2 60-40 with respect to coverage from house1 She prefers a tabular view of her data where missing weights are assumed to be 1.0 and missing coverage 0.0. NAME_HIERARCHY |WEIGHT |COVERAGE | cleaning | | | house1 |40 | | bedrooms | |0.25 | bathrooms | | | bathroom1 | |0.5 | bathroom2 | | | outside_lavatory | |1 | attic | |0.75 | kitchen | |0.1 | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | |1 | basement | | | garage | | | garden | |0.8 | house2 |60 | | upstairs | | | bedrooms | | | suite_1 | | | suite_2 | | | bedroom_3 | | | bedroom_4 | | | bathroom | | | toilet | | | attics | |0.6 | groundfloor | | | kitchen | | | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | | | wet_room_&_toilet | | | garage | | | garden | |0.9 | hot_tub_suite | |1 | basement | | | cellars | |1 | wine_cellar | |1 | cinema | |0.75 | ;Calculation: The coverage of a node in the tree is calculated as the weighted average of the coverage of its children evaluated bottom-upwards in the tree. '''The task is to''' calculate the overall coverage of the cleaning task and display the coverage at all levels of the hierarchy on this page, in a manner that visually shows the hierarchy, weights and coverage of all nodes. ;Extra Credit: After calculating the coverage for all nodes, one can also calculate the additional/delta top level coverage that would occur if any (sub)task were to be fully covered from its current fractional coverage. This is done by multiplying the extra coverage that could be gained 1-coverage for any node, by the product of the `powers` of its parent nodes from the top down to the node. The power of a direct child of any parent is given by the power of the parent multiplied by the weight of the child divided by the sum of the weights of all the direct children. The pseudo code would be: method delta_calculation(this, power): sum_of_weights = sum(node.weight for node in children) this.delta = (1 - this.coverage) * power for node in self.children: node.delta_calculation(power * node.weight / sum_of_weights) return this.delta Followed by a call to: top.delta_calculation(power=1) '''Note:''' to aid in getting the data into your program you might want to use an alternative, more functional description of the starting data given on the discussion page.
(() => { 'use strict'; // updatedCoverageOutline :: String -> String const updatedCoverageOutline = outlineText => { const delimiter = '|', indentedLines = indentLevelsFromLines(lines(outlineText)), columns = init(tokenizeWith(delimiter)(snd(indentedLines[0]))); // SERIALISATION OF UPDATED PARSE TREE (TO NEW OUTLINE TEXT) return tabulation(delimiter)( columns.concat('SHARE OF RESIDUE\n') ) + unlines( indentedLinesFromTree( showCoverage(delimiter))(' ')( // TWO TRAVERSAL COMPUTATIONS withResidueShares(1.0)( foldTree(weightedCoverage)( // PARSE TREE (FROM OUTLINE TEXT) fmapTree(compose( partialRecord, tokenizeWith(delimiter) ))(fst( forestFromLineIndents(tail(indentedLines)) )) ) )) ); }; // TEST ----------------------------------------------- // main :: IO () const main = () => console.log( // strOutline is included as literal text // at the foot of this code listing. updatedCoverageOutline(strOutline) ); // COVERAGE AND SHARES OF RESIDUE --------------------- // weightedCoverage :: Dict -> Forest Dict -> Tree Dict const weightedCoverage = x => xs => { const cws = map(compose( fanArrow(x => x.coverage)(x => x.weight), root ))(xs), totalWeight = cws.reduce((a, tpl) => a + snd(tpl), 0); return Node( insertDict('coverage')( cws.reduce((a, tpl) => { const [c, w] = Array.from(tpl); return a + (c * w); }, x.coverage) / ( 0 < totalWeight ? totalWeight : 1 ) )(x) )(xs); }; // withResidueShares :: Float -> Tree Dict -> Tree Dict const withResidueShares = shareOfTotal => tree => { const go = fraction => node => { const nodeRoot = node.root, forest = node.nest, weights = forest.map(x => x.root.weight), weightTotal = sum(weights); return Node( insertDict('share')( fraction * (1 - nodeRoot.coverage) )(nodeRoot) )( zipWith(go)( weights.map(w => fraction * (w / weightTotal)) )(forest) ); }; return go(shareOfTotal)(tree); }; // OUTLINE PARSED TO TREE ----------------------------- // forestFromLineIndents :: [(Int, String)] -> [Tree String] const forestFromLineIndents = tuples => { const go = xs => 0 < xs.length ? (() => { const [n, s] = Array.from(xs[0]); // Lines indented under this line, // tupled with all the rest. const [firstTreeLines, rest] = Array.from( span(x => n < x[0])(xs.slice(1)) ); // This first tree, and then the rest. return [Node(s)(go(firstTreeLines))] .concat(go(rest)); })() : []; return go(tuples); }; // indentLevelsFromLines :: [String] -> [(Int, String)] const indentLevelsFromLines = xs => { const indentTextPairs = xs.map(compose( firstArrow(length), span(isSpace) )), indentUnit = minimum(indentTextPairs.flatMap(pair => { const w = fst(pair); return 0 < w ? [w] : []; })); return indentTextPairs.map( firstArrow(flip(div)(indentUnit)) ); }; // partialRecord :: [String] -> Dict const partialRecord = xs => { const [name, weightText, coverageText] = take(3)( xs.concat(['', '', '']) ); return { name: name || '?', weight: parseFloat(weightText) || 1.0, coverage: parseFloat(coverageText) || 0.0, share: 0.0 }; }; // tokenizeWith :: String -> String -> [String] const tokenizeWith = delimiter => // A sequence of trimmed tokens obtained by // splitting s on the supplied delimiter. s => s.split(delimiter).map(x => x.trim()); // TREE SERIALIZED TO OUTLINE ------------------------- // indentedLinesFromTree :: (String -> a -> String) -> // String -> Tree a -> [String] const indentedLinesFromTree = showRoot => strTab => tree => { const go = indent => node => [showRoot(indent)(node.root)] .concat(node.nest.flatMap(go(strTab + indent))); return go('')(tree); }; // showN :: Int -> Float -> String const showN = p => n => justifyRight(7)(' ')(n.toFixed(p)); // showCoverage :: String -> String -> Dict -> String const showCoverage = delimiter => indent => x => tabulation(delimiter)( [indent + x.name, showN(0)(x.weight)] .concat([x.coverage, x.share].map(showN(4))) ); // tabulation :: String -> [String] -> String const tabulation = delimiter => // Up to 4 tokens drawn from the argument list, // as a single string with fixed left-justified // white-space widths, between delimiters. compose( intercalate(delimiter + ' '), zipWith(flip(justifyLeft)(' '))([31, 9, 9, 9]) ); // GENERIC AND REUSABLE FUNCTIONS --------------------- // Node :: a -> [Tree a] -> Tree a const Node = v => xs => ({ type: 'Node', root: v, // any type of value (consistent across tree) nest: xs || [] }); // Tuple (,) :: a -> b -> (a, b) const Tuple = a => b => ({ type: 'Tuple', '0': a, '1': b, length: 2 }); // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (...fs) => x => fs.reduceRight((a, f) => f(a), x); // concat :: [[a]] -> [a] // concat :: [String] -> String const concat = xs => 0 < xs.length ? (() => { const unit = 'string' !== typeof xs[0] ? ( [] ) : ''; return unit.concat.apply(unit, xs); })() : []; // div :: Int -> Int -> Int const div = x => y => Math.floor(x / y); // either :: (a -> c) -> (b -> c) -> Either a b -> c const either = fl => fr => e => 'Either' === e.type ? ( undefined !== e.Left ? ( fl(e.Left) ) : fr(e.Right) ) : undefined; // Compose a function from a simple value to a tuple of // the separate outputs of two different functions // fanArrow (&&&) :: (a -> b) -> (a -> c) -> (a -> (b, c)) const fanArrow = f => g => x => Tuple(f(x))( g(x) ); // Lift a simple function to one which applies to a tuple, // transforming only the first item of the tuple // firstArrow :: (a -> b) -> ((a, c) -> (b, c)) const firstArrow = f => xy => Tuple(f(xy[0]))( xy[1] ); // flip :: (a -> b -> c) -> b -> a -> c const flip = f => 1 < f.length ? ( (a, b) => f(b, a) ) : (x => y => f(y)(x)); // fmapTree :: (a -> b) -> Tree a -> Tree b const fmapTree = f => tree => { const go = node => Node(f(node.root))( node.nest.map(go) ); return go(tree); }; // foldTree :: (a -> [b] -> b) -> Tree a -> b const foldTree = f => tree => { const go = node => f(node.root)( node.nest.map(go) ); return go(tree); }; // foldl1 :: (a -> a -> a) -> [a] -> a const foldl1 = f => xs => 1 < xs.length ? xs.slice(1) .reduce(uncurry(f), xs[0]) : xs[0]; // fst :: (a, b) -> a const fst = tpl => tpl[0]; // init :: [a] -> [a] const init = xs => 0 < xs.length ? ( xs.slice(0, -1) ) : undefined; // insertDict :: String -> a -> Dict -> Dict const insertDict = k => v => dct => Object.assign({}, dct, { [k]: v }); // intercalate :: [a] -> [[a]] -> [a] // intercalate :: String -> [String] -> String const intercalate = sep => xs => xs.join(sep); // isSpace :: Char -> Bool const isSpace = c => /\s/.test(c); // justifyLeft :: Int -> Char -> String -> String const justifyLeft = n => cFiller => s => n > s.length ? ( s.padEnd(n, cFiller) ) : s; // justifyRight :: Int -> Char -> String -> String const justifyRight = n => cFiller => s => n > s.length ? ( s.padStart(n, cFiller) ) : s; // length :: [a] -> Int const length = xs => (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity; // lines :: String -> [String] const lines = s => s.split(/[\r\n]/); // map :: (a -> b) -> [a] -> [b] const map = f => xs => (Array.isArray(xs) ? ( xs ) : xs.split('')).map(f); // minimum :: Ord a => [a] -> a const minimum = xs => 0 < xs.length ? ( foldl1(a => x => x < a ? x : a)(xs) ) : undefined; // root :: Tree a -> a const root = tree => tree.root; // showLog :: a -> IO () const showLog = (...args) => console.log( args .map(JSON.stringify) .join(' -> ') ); // snd :: (a, b) -> b const snd = tpl => tpl[1]; // span :: (a -> Bool) -> [a] -> ([a], [a]) const span = p => xs => { const iLast = xs.length - 1; return splitAt( until(i => iLast < i || !p(xs[i]))( succ )(0) )(xs); }; // splitAt :: Int -> [a] -> ([a], [a]) const splitAt = n => xs => Tuple(xs.slice(0, n))( xs.slice(n) ); // succ :: Enum a => a -> a const succ = x => 1 + x; // sum :: [Num] -> Num const sum = xs => xs.reduce((a, x) => a + x, 0); // tail :: [a] -> [a] const tail = xs => 0 < xs.length ? xs.slice(1) : []; // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = n => xs => 'GeneratorFunction' !== xs.constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; })); // uncurry :: (a -> b -> c) -> ((a, b) -> c) const uncurry = f => (x, y) => f(x)(y); // unlines :: [String] -> String const unlines = xs => xs.join('\n'); // until :: (a -> Bool) -> (a -> a) -> a -> a const until = p => f => x => { let v = x; while (!p(v)) v = f(v); return v; }; // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => xs => ys => xs.slice( 0, Math.min(xs.length, ys.length) ).map((x, i) => f(x)(ys[i])); // SOURCE OUTLINE ----------------------------------------- const strOutline = `NAME_HIERARCHY |WEIGHT |COVERAGE | cleaning | | | house1 |40 | | bedrooms | |0.25 | bathrooms | | | bathroom1 | |0.5 | bathroom2 | | | outside_lavatory | |1 | attic | |0.75 | kitchen | |0.1 | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | |1 | basement | | | garage | | | garden | |0.8 | house2 |60 | | upstairs | | | bedrooms | | | suite_1 | | | suite_2 | | | bedroom_3 | | | bedroom_4 | | | bathroom | | | toilet | | | attics | |0.6 | groundfloor | | | kitchen | | | living_rooms | | | lounge | | | dining_room | | | conservatory | | | playroom | | | wet_room_&_toilet | | | garage | | | garden | |0.9 | hot_tub_suite | |1 | basement | | | cellars | |1 | wine_cellar | |1 | cinema | |0.75 |`; // MAIN --- return main(); })();
Fusc sequence
Javascript from Python
Definitions: The '''fusc''' integer sequence is defined as: ::* fusc(0) = 0 ::* fusc(1) = 1 ::* for '''n'''>1, the '''n'''th term is defined as: ::::* if '''n''' is even; fusc(n) = fusc(n/2) ::::* if '''n''' is odd; fusc(n) = fusc((n-1)/2) + fusc((n+1)/2) Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above). ;An observation: :::::* fusc(A) = fusc(B) where '''A''' is some non-negative integer expressed in binary, and where '''B''' is the binary value of '''A''' reversed. Fusc numbers are also known as: ::* fusc function (named by Dijkstra, 1982) ::* Stern's Diatomic series (although it starts with unity, not zero) ::* Stern-Brocot sequence (although it starts with unity, not zero) ;Task: ::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format. ::* show the fusc number (and its index) whose length is greater than any previous fusc number length. ::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.) ::* show all numbers with commas (if appropriate). ::* show all output here. ;Related task: ::* RosettaCode Stern-Brocot sequence ;Also see: ::* the MathWorld entry: Stern's Diatomic Series. ::* the OEIS entry: A2487.
(() => { "use strict"; // ---------------------- FUSC ----------------------- // fusc :: Int -> Int const fusc = i => { const go = n => 0 === n ? [ 1, 0 ] : (() => { const [x, y] = go(Math.floor(n / 2)); return 0 === n % 2 ? ( [x + y, y] ) : [x, x + y]; })(); return 1 > i ? ( 0 ) : go(i - 1)[0]; }; // ---------------------- TEST ----------------------- const main = () => { const terms = enumFromTo(0)(60).map(fusc); return [ "First 61 terms:", `[${terms.join(",")}]`, "", "(Index, Value):", firstWidths(5).reduce( (a, x) => [x.slice(1), ...a], [] ) .map(([i, x]) => `(${i}, ${x})`) .join("\n") ] .join("\n"); }; // firstWidths :: Int -> [(Int, Int)] const firstWidths = n => { const nxtWidth = xs => { const fi = fanArrow(fusc)(x => x), [w, i] = xs[0], [x, j] = Array.from( until( v => w <= `${v[0]}`.length )( v => fi(1 + v[1]) )(fi(i)) ); return [ [1 + w, j, x], ...xs ]; }; return until(x => n < x[0][0])( nxtWidth )([ [2, 0, 0] ]); }; // ---------------- GENERIC FUNCTIONS ---------------- // enumFromTo :: Int -> Int -> [Int] const enumFromTo = m => n => Array.from({ length: 1 + n - m }, (_, i) => m + i); // fanArrow (&&&) :: // (a -> b) -> (a -> c) -> (a -> (b, c)) const fanArrow = f => // A combined function, given f and g, // from x to a tuple of (f(x), g(x)) // ((,) . f <*> g) g => x => [f(x), g(x)]; // until :: (a -> Bool) -> (a -> a) -> a -> a const until = p => // The value resulting from successive applications // of f to f(x), starting with a seed value x, // and terminating when the result returns true // for the predicate p. f => { const go = x => p(x) ? x : go(f(x)); return go; }; // MAIN --- return main(); })();
Gaussian elimination
JavaScript
Solve '''Ax=b''' using Gaussian elimination then backwards substitution. '''A''' being an '''n''' by '''n''' matrix. Also, '''x''' and '''b''' are '''n''' by '''1''' vectors. To improve accuracy, please use partial pivoting and scaling. ;See also: :* the Wikipedia entry: Gaussian elimination
// Lower Upper Solver function lusolve(A, b, update) { var lu = ludcmp(A, update) if (lu === undefined) return // Singular Matrix! return lubksb(lu, b, update) } // Lower Upper Decomposition function ludcmp(A, update) { // A is a matrix that we want to decompose into Lower and Upper matrices. var d = true var n = A.length var idx = new Array(n) // Output vector with row permutations from partial pivoting var vv = new Array(n) // Scaling information for (var i=0; i<n; i++) { var max = 0 for (var j=0; j<n; j++) { var temp = Math.abs(A[i][j]) if (temp > max) max = temp } if (max == 0) return // Singular Matrix! vv[i] = 1 / max // Scaling } if (!update) { // make a copy of A var Acpy = new Array(n) for (var i=0; i<n; i++) { var Ai = A[i] Acpyi = new Array(Ai.length) for (j=0; j<Ai.length; j+=1) Acpyi[j] = Ai[j] Acpy[i] = Acpyi } A = Acpy } var tiny = 1e-20 // in case pivot element is zero for (var i=0; ; i++) { for (var j=0; j<i; j++) { var sum = A[j][i] for (var k=0; k<j; k++) sum -= A[j][k] * A[k][i]; A[j][i] = sum } var jmax = 0 var max = 0; for (var j=i; j<n; j++) { var sum = A[j][i] for (var k=0; k<i; k++) sum -= A[j][k] * A[k][i]; A[j][i] = sum var temp = vv[j] * Math.abs(sum) if (temp >= max) { max = temp jmax = j } } if (i <= jmax) { for (var j=0; j<n; j++) { var temp = A[jmax][j] A[jmax][j] = A[i][j] A[i][j] = temp } d = !d; vv[jmax] = vv[i] } idx[i] = jmax; if (i == n-1) break; var temp = A[i][i] if (temp == 0) A[i][i] = temp = tiny temp = 1 / temp for (var j=i+1; j<n; j++) A[j][i] *= temp } return {A:A, idx:idx, d:d} } // Lower Upper Back Substitution function lubksb(lu, b, update) { // solves the set of n linear equations A*x = b. // lu is the object containing A, idx and d as determined by the routine ludcmp. var A = lu.A var idx = lu.idx var n = idx.length if (!update) { // make a copy of b var bcpy = new Array(n) for (var i=0; i<b.length; i+=1) bcpy[i] = b[i] b = bcpy } for (var ii=-1, i=0; i<n; i++) { var ix = idx[i] var sum = b[ix] b[ix] = b[i] if (ii > -1) for (var j=ii; j<i; j++) sum -= A[i][j] * b[j] else if (sum) ii = i b[i] = sum } for (var i=n-1; i>=0; i--) { var sum = b[i] for (var j=i+1; j<n; j++) sum -= A[i][j] * b[j] b[i] = sum / A[i][i] } return b // solution vector x } document.write( lusolve( [ [1.00, 0.00, 0.00, 0.00, 0.00, 0.00], [1.00, 0.63, 0.39, 0.25, 0.16, 0.10], [1.00, 1.26, 1.58, 1.98, 2.49, 3.13], [1.00, 1.88, 3.55, 6.70, 12.62, 23.80], [1.00, 2.51, 6.32, 15.88, 39.90, 100.28], [1.00, 3.14, 9.87, 31.01, 97.41, 306.02] ], [-0.01, 0.61, 0.91, 0.99, 0.60, 0.02] ) )
Generate Chess960 starting position
JavaScript
Bobby Fischer. Unlike other variants of the game, Chess960 does not require a different material, but instead relies on a random initial position, with a few constraints: * as in the standard chess game, all eight white pawns must be placed on the second rank. * White pieces must stand on the first rank as in the standard game, in random column order but with the two following constraints: ** the bishops must be placed on opposite color squares (i.e. they must be an odd number of spaces apart or there must be an even number of spaces between them) ** the King must be between two rooks (with any number of other pieces between them all) * Black pawns and pieces must be placed respectively on the seventh and eighth ranks, mirroring the white pawns and pieces, just as in the standard game. (That is, their positions are not independently randomized.) With those constraints there are '''960''' possible starting positions, thus the name of the variant. ;Task: The purpose of this task is to write a program that can randomly generate any one of the 960 Chess960 initial positions. You will show the result as the first rank displayed with Chess symbols in Unicode: or with the letters '''K'''ing '''Q'''ueen '''R'''ook '''B'''ishop k'''N'''ight.
function ch960startPos() { var rank = new Array(8), // randomizer (our die) d = function(num) { return Math.floor(Math.random() * ++num) }, emptySquares = function() { var arr = []; for (var i = 0; i < 8; i++) if (rank[i] == undefined) arr.push(i); return arr; }; // place one bishop on any black square rank[d(2) * 2] = "♗"; // place the other bishop on any white square rank[d(2) * 2 + 1] = "♗"; // place the queen on any empty square rank[emptySquares()[d(5)]] = "♕"; // place one knight on any empty square rank[emptySquares()[d(4)]] = "♘"; // place the other knight on any empty square rank[emptySquares()[d(3)]] = "♘"; // place the rooks and the king on the squares left, king in the middle for (var x = 1; x <= 3; x++) rank[emptySquares()[0]] = x==2 ? "♔" : "♖"; return rank; } // testing (10 times) for (var x = 1; x <= 10; x++) console.log(ch960startPos().join(" | "));
Generate random chess position
JavaScript
Generate a random chess position in FEN format. The position does not have to be realistic or even balanced, but it must comply to the following rules: :* there is one and only one king of each color (one black king and one white king); :* the kings must not be placed on adjacent squares; :* there can not be any pawn in the promotion square (no white pawn in the eighth rank, and no black pawn in the first rank); :* including the kings, up to 32 pieces of either color can be placed. :* There is no requirement for material balance between sides. :* The picking of pieces does not have to comply to a regular chess set --- there can be five knights, twenty rooks, whatever ... as long as the total number of pieces do not exceed thirty-two. :* it is white's turn. :* It's assumed that both sides have lost castling rights and that there is no possibility for ''en passant'' (the FEN should thus end in w - - 0 1). No requirement is made regarding the probability distribution of your method, but your program should be able to span a reasonably representative sample of all possible positions. For instance, programs that would always generate positions with say five pieces on the board, or with kings on a corner, would not be considered truly random.
Array.prototype.shuffle = function() { for (let i = this.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); [this[i], this[j]] = [this[j], this[i]]; } } function randomFEN() { let board = []; for (let x = 0; x < 8; x++) board.push('. . . . . . . .'.split(' ')); function getRandPos() { return [Math.floor(Math.random() * 8), Math.floor(Math.random() * 8)]; } function isOccupied(pos) { return board[pos[0]][pos[1]] != '.'; } function isAdjacent(pos1, pos2) { if (pos1[0] == pos2[0] || pos1[0] == pos2[0]-1 || pos1[0] == pos2[0]+1) if (pos1[1] == pos2[1] || pos1[1] == pos2[1]-1 || pos1[1] == pos2[1]+1) return true; return false; } // place kings let wk, bk; do { wk = getRandPos(); bk = getRandPos(); } while (isAdjacent(wk, bk)); board[wk[0]][wk[1]] = 'K'; board[bk[0]][bk[1]] = 'k'; // get peaces let peaces = []; let names = 'PRNBQ'; function pick() { for (x = 1; x < Math.floor(Math.random() * 32); x++) peaces.push(names[Math.floor(Math.random() * names.length)]); } pick(); names = names.toLowerCase(); pick(); peaces.shuffle(); // place peaces while (peaces.length > 0) { let p = peaces.shift(), pos; // paws: cannot be placed in bottom or top row if (p == 'p' || p == 'P') do { pos = getRandPos() } while (isOccupied(pos) || pos[0] == 0 || pos[0] == 7); // everything else else do { pos = getRandPos(); } while (isOccupied(pos)); board[pos[0]][pos[1]] = p; } // write FEN let fen = []; for (x = 0; x < board.length; x++) { let str ='', buf = 0; for (let y = 0; y < board[x].length; y++) if (board[x][y] == '.') buf++; else { if (buf > 0) { str += buf; buf = 0; } str += board[x][y]; } if (buf > 0) str += buf; fen.push(str); } fen = fen.join('/') + ' w - - 0 1'; console.table(board); // for demonstrating purpose return fen; } // example console.log(randomFEN());
Generator/Exponential
JavaScript from Python
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided. Generators are often built on top of coroutines or objects so that the internal state of the object is handled "naturally". Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state. ;Task: * Create a function that returns a generation of the m'th powers of the positive integers starting from zero, in order, and without obvious or simple upper limit. (Any upper limit to the generator should not be stated in the source but should be down to factors such as the languages natural integer size limit or computational time/size). * Use it to create a generator of: :::* Squares. :::* Cubes. * Create a new generator that filters all cubes from the generator of squares. * Drop the first 20 values from this last generator of filtered results, and then show the next 10 values. Note that this task ''requires'' the use of generators in the calculation of the result. ;Also see: * Generator
(() => { 'use strict'; // main :: IO() const main = () => { // powers :: Gen [Int] const powers = n => fmapGen( x => Math.pow(x, n), enumFrom(0) ); // xs :: [Int] const xs = take(10, drop(20, differenceGen( powers(2), powers(3) ) )); console.log(xs); // -> [529,576,625,676,784,841,900,961,1024,1089] }; // GENERIC FUNCTIONS ---------------------------------- // Just :: a -> Maybe a const Just = x => ({ type: 'Maybe', Nothing: false, Just: x }); // Nothing :: Maybe a const Nothing = () => ({ type: 'Maybe', Nothing: true, }); // Tuple (,) :: a -> b -> (a, b) const Tuple = (a, b) => ({ type: 'Tuple', '0': a, '1': b, length: 2 }); // differenceGen :: Gen [a] -> Gen [a] -> Gen [a] function* differenceGen(ga, gb) { // All values of generator stream a except any // already seen in generator stream b. const stream = zipGen(ga, gb), sb = new Set([]); let xy = take(1, stream); while (0 < xy.length) { const [x, y] = Array.from(xy[0]); sb.add(y); if (!sb.has(x)) yield x; xy = take(1, stream); } }; // drop :: Int -> [a] -> [a] // drop :: Int -> Generator [a] -> Generator [a] // drop :: Int -> String -> String const drop = (n, xs) => Infinity > length(xs) ? ( xs.slice(n) ) : (take(n, xs), xs); // enumFrom :: Enum a => a -> [a] function* enumFrom(x) { let v = x; while (true) { yield v; v = 1 + v; } } // fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b] function* fmapGen(f, gen) { let v = take(1, gen); while (0 < v.length) { yield(f(v[0])) v = take(1, gen) } } // fst :: (a, b) -> a const fst = tpl => tpl[0]; // Returns Infinity over objects without finite length. // This enables zip and zipWith to choose the shorter // argument when one is non-finite, like cycle, repeat etc // length :: [a] -> Int const length = xs => (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity; // snd :: (a, b) -> b const snd = tpl => tpl[1]; // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = (n, xs) => 'GeneratorFunction' !== xs.constructor.constructor.name ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; })); // uncons :: [a] -> Maybe (a, [a]) const uncons = xs => { const lng = length(xs); return (0 < lng) ? ( lng < Infinity ? ( Just(Tuple(xs[0], xs.slice(1))) // Finite list ) : (() => { const nxt = take(1, xs); return 0 < nxt.length ? ( Just(Tuple(nxt[0], xs)) ) : Nothing(); })() // Lazy generator ) : Nothing(); }; // zipGen :: Gen [a] -> Gen [b] -> Gen [(a, b)] const zipGen = (ga, gb) => { function* go(ma, mb) { let a = ma, b = mb; while (!a.Nothing && !b.Nothing) { let ta = a.Just, tb = b.Just yield(Tuple(fst(ta), fst(tb))); a = uncons(snd(ta)); b = uncons(snd(tb)); } } return go(uncons(ga), uncons(gb)); }; // MAIN --- return main(); })();
Gotchas
Javascript
Definition In programming, a '''gotcha''' is a valid construct in a system, program or programming language that works as documented but is counter-intuitive and almost invites mistakes because it is both easy to invoke and unexpected or unreasonable in its outcome. ;Task Give an example or examples of common gotchas in your programming language and what, if anything, can be done to defend against it or them without using special tools.
===Equality Comparisons=== The normal equality operator (<code>==</code>) is very infamous for its strange results when comparing two variables of different types. Javascript has a complicated set of type coercion rules, which was intended to simplify comparisons between integers and floating point, integers and their string representations (e.g. 2 == '2'), etc. However, this is often frustrating for the programmer when they want to know if two variables are equal and also have the same data type. The strict equality (<code>===</code>) operator will always return false if the variables are of two different types. Many new programmers are taught to always use <code>===</code> to avoid subtle bugs in their programs.
Gray code
Javascript
Karnaugh maps in order from left to right or top to bottom. Create functions to encode a number to and decode a number from Gray code. Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary). There are many possible Gray codes. The following encodes what is called "binary reflected Gray code." Encoding (MSB is bit 0, b is binary, g is Gray code): if b[i-1] = 1 g[i] = not b[i] else g[i] = b[i] Or: g = b xor (b logically right shifted 1 time) Decoding (MSB is bit 0, b is binary, g is Gray code): b[0] = g[0] for other bits: b[i] = g[i] xor b[i-1] ;Reference * Converting Between Gray and Binary Codes. It includes step-by-step animations.
import printf from 'printf' // Module must be installed with npm first import * as gray from './gray-code.js' console.log( 'Number\t' + 'Binary\t' + 'Gray Code\t' + 'Decoded Gray Code' ) for (let number = 0; number < 32; number++) { const grayCode = gray.encode(number) const decodedGrayCode = gray.decode(grayCode) console.log(printf( '%2d\t%05d\t%05d\t\t%2d', number, number.toString(2), grayCode.toString(2), decodedGrayCode )) }
Greatest subsequential sum
JavaScript
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.
function MaximumSubsequence(population) { var maxValue = 0; var subsequence = []; for (var i = 0, len = population.length; i < len; i++) { for (var j = i; j <= len; j++) { var subsequence = population.slice(i, j); var value = sumValues(subsequence); if (value > maxValue) { maxValue = value; greatest = subsequence; }; } } return greatest; } function sumValues(arr) { var result = 0; for (var i = 0, len = arr.length; i < len; i++) { result += arr[i]; } return result; }
Greatest subsequential sum
JavaScript from Haskell
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one. An empty subsequence is considered to have the sum of '''0'''; thus if all elements are negative, the result must be the empty sequence.
(() => { // maxSubseq :: [Int] -> (Int, [Int]) const maxSubseq = xs => snd(xs.reduce((tpl, x) => { const [m1, m2] = Array.from(fst(tpl)), high = max( Tuple(0, []), Tuple(m1 + x, m2.concat(x)) ); return Tuple(high, max(snd(tpl), high)); }, Tuple(Tuple(0, []), Tuple(0, [])))); // TEST ----------------------------------------------- // main :: IO () const main = () => { const mx = maxSubseq([-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]); showLog(snd(mx), fst(mx)) } // [3,5,6,-2,-1,4] -> 15 // GENERIC FUNCTIONS ---------------------------------- // fst :: (a, b) -> a const fst = tpl => tpl[0]; // gt :: Ord a => a -> a -> Bool const gt = (x, y) => 'Tuple' === x.type ? ( x[0] > y[0] ) : (x > y); // max :: Ord a => a -> a -> a const max = (a, b) => gt(b, a) ? b : a; // showLog :: a -> IO () const showLog = (...args) => console.log( args .map(JSON.stringify) .join(' -> ') ); // snd :: (a, b) -> b const snd = tpl => tpl[1]; // Tuple (,) :: a -> b -> (a, b) const Tuple = (a, b) => ({ type: 'Tuple', '0': a, '1': b, length: 2 }); // MAIN --- return main(); })();
Greyscale bars/Display
JavaScript
The task is to display a series of vertical greyscale bars (contrast bars) with a sufficient number of bars to span the entire width of the display. For the top quarter of the display, the left hand bar should be black, and we then incrementally step through six shades of grey until we have a white bar on the right hand side of the display. (This gives a total of 8 bars) For the second quarter down, we start with white and step down through 14 shades of gray, getting darker until we have black on the right hand side of the display. (This gives a total of 16 bars). Halfway down the display, we start with black, and produce 32 bars, ending in white, and for the last quarter, we start with white and step through 62 shades of grey, before finally arriving at black in the bottom right hand corner, producing a total of 64 bars for the bottom quarter.
<html><body> <script type="text/javascript"> var width = 640; var height = 400; var c = document.createElement("canvas"); c.setAttribute('id', 'myCanvas'); c.setAttribute('style', 'border:1px solid black;'); c.setAttribute('width', width); c.setAttribute('height', height); document.body.appendChild(c); var ctx = document.getElementById('myCanvas').getContext("2d"); var columnCount = 8; // number of columns var rowCount = 4; // number of rows var direction = 1; // 1 = from left to right, 0 = from right to left var blackLeft = 1; // black is left: 1 = true, 0 = false for(var j = 0; j < rowCount; j++){ for(var i = 0; i < columnCount; i++){ ctx.fillStyle = 'rgba(0,0,0,'+ (blackLeft-(1/(columnCount-1)*i))*direction +')'; ctx.fillRect( (width/columnCount)*i,(height/rowCount)*j, (width/columnCount),(height/rowCount) ); } columnCount *= 2; direction *= -1; blackLeft = blackLeft ? 0 : 1; } </script> </body></html>
Hailstone sequence
JavaScript
The Hailstone sequence of numbers can be generated from a starting positive integer, n by: * If n is '''1''' then the sequence ends. * If n is '''even''' then the next n of the sequence = n/2 * If n is '''odd''' then the next n of the sequence = (3 * n) + 1 The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates. This sequence was named by Lothar Collatz in 1937 (or possibly in 1939), and is also known as (the): :::* hailstone sequence, hailstone numbers :::* 3x + 2 mapping, 3n + 1 problem :::* Collatz sequence :::* Hasse's algorithm :::* Kakutani's problem :::* Syracuse algorithm, Syracuse problem :::* Thwaites conjecture :::* Ulam's problem The hailstone sequence is also known as ''hailstone numbers'' (because the values are usually subject to multiple descents and ascents like hailstones in a cloud). ;Task: # Create a routine to generate the hailstone sequence for a number. # Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 # Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. (But don't show the actual sequence!) ;See also: * xkcd (humourous). * The Notorious Collatz conjecture Terence Tao, UCLA (Presentation, pdf). * The Simplest Math Problem No One Can Solve Veritasium (video, sponsored).
function hailstone (n) { var seq = [n]; while (n > 1) { n = n % 2 ? 3 * n + 1 : n / 2; seq.push(n); } return seq; } // task 2: verify the sequence for n = 27 var h = hailstone(27), hLen = h.length; print("sequence 27 is (" + h.slice(0, 4).join(", ") + " ... " + h.slice(hLen - 4, hLen).join(", ") + "). length: " + hLen); // task 3: find the longest sequence for n < 100000 for (var n, max = 0, i = 100000; --i;) { var seq = hailstone(i), sLen = seq.length; if (sLen > max) { n = i; max = sLen; } } print("longest sequence: " + max + " numbers for starting point " + n);
Harshad or Niven series
JavaScript
The Harshad or Niven numbers are positive integers >= 1 that are divisible by the sum of their digits. For example, '''42''' is a Harshad number as '''42''' is divisible by ('''4''' + '''2''') without remainder. Assume that the series is defined as the numbers in increasing order. ;Task: The task is to create a function/method/procedure to generate successive members of the Harshad sequence. Use it to: ::* list the first '''20''' members of the sequence, and ::* list the first Harshad number greater than '''1000'''. Show your output here. ;Related task :* Increasing gaps between consecutive Niven numbers ;See also * OEIS: A005349
function isHarshad(n) { var s = 0; var n_str = new String(n); for (var i = 0; i < n_str.length; ++i) { s += parseInt(n_str.charAt(i)); } return n % s === 0; } var count = 0; var harshads = []; for (var n = 1; count < 20; ++n) { if (isHarshad(n)) { count++; harshads.push(n); } } console.log(harshads.join(" ")); var h = 1000; while (!isHarshad(++h)); console.log(h);
Hash join
JavaScript
{| class="wikitable" |- ! Input ! Output |- | {| style="border:none; border-collapse:collapse;" |- | style="border:none" | ''A'' = | style="border:none" | {| class="wikitable" |- ! Age !! Name |- | 27 || Jonah |- | 18 || Alan |- | 28 || Glory |- | 18 || Popeye |- | 28 || Alan |} | style="border:none; padding-left:1.5em;" rowspan="2" | | style="border:none" | ''B'' = | style="border:none" | {| class="wikitable" |- ! Character !! Nemesis |- | Jonah || Whales |- | Jonah || Spiders |- | Alan || Ghosts |- | Alan || Zombies |- | Glory || Buffy |} |- | style="border:none" | ''jA'' = | style="border:none" | Name (i.e. column 1) | style="border:none" | ''jB'' = | style="border:none" | Character (i.e. column 0) |} | {| class="wikitable" style="margin-left:1em" |- ! A.Age !! A.Name !! B.Character !! B.Nemesis |- | 27 || Jonah || Jonah || Whales |- | 27 || Jonah || Jonah || Spiders |- | 18 || Alan || Alan || Ghosts |- | 18 || Alan || Alan || Zombies |- | 28 || Glory || Glory || Buffy |- | 28 || Alan || Alan || Ghosts |- | 28 || Alan || Alan || Zombies |} |} The order of the rows in the output table is not significant. If you're using numerically indexed arrays to represent table rows (rather than referring to columns by name), you could represent the output rows in the form [[27, "Jonah"], ["Jonah", "Whales"]].
(() => { 'use strict'; // hashJoin :: [Dict] -> [Dict] -> String -> [Dict] let hashJoin = (tblA, tblB, strJoin) => { let [jA, jB] = strJoin.split('='), M = tblB.reduce((a, x) => { let id = x[jB]; return ( a[id] ? a[id].push(x) : a[id] = [x], a ); }, {}); return tblA.reduce((a, x) => { let match = M[x[jA]]; return match ? ( a.concat(match.map(row => dictConcat(x, row))) ) : a; }, []); }, // dictConcat :: Dict -> Dict -> Dict dictConcat = (dctA, dctB) => { let ok = Object.keys; return ok(dctB).reduce( (a, k) => (a['B_' + k] = dctB[k]) && a, ok(dctA).reduce( (a, k) => (a['A_' + k] = dctA[k]) && a, {} ) ); }; // TEST let lstA = [ { age: 27, name: 'Jonah' }, { age: 18, name: 'Alan' }, { age: 28, name: 'Glory' }, { age: 18, name: 'Popeye' }, { age: 28, name: 'Alan' } ], lstB = [ { character: 'Jonah', nemesis: 'Whales' }, { character: 'Jonah', nemesis: 'Spiders' }, { character: 'Alan', nemesis: 'Ghosts' }, { character:'Alan', nemesis: 'Zombies' }, { character: 'Glory', nemesis: 'Buffy' }, { character: 'Bob', nemesis: 'foo' } ]; return hashJoin(lstA, lstB, 'name=character'); })();
Haversine formula
JavaScript from Java
{{Wikipedia}} The '''haversine formula''' is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes. It is a special case of a more general formula in spherical trigonometry, the '''law of haversines''', relating the sides and angles of spherical "triangles". ;Task: Implement a great-circle distance function, or use a library function, to show the great-circle distance between: * Nashville International Airport (BNA) in Nashville, TN, USA, which is: '''N''' 36deg7.2', '''W''' 86deg40.2' (36.12, -86.67) -and- * Los Angeles International Airport (LAX) in Los Angeles, CA, USA, which is: '''N''' 33deg56.4', '''W''' 118deg24.0' (33.94, -118.40) User Kaimbridge clarified on the Talk page: -- 6371.0 km is the authalic radius based on/extracted from surface area; -- 6372.8 km is an approximation of the radius of the average circumference (i.e., the average great-elliptic or great-circle radius), where the boundaries are the meridian (6367.45 km) and the equator (6378.14 km). Using either of these values results, of course, in differing distances: 6371.0 km -> 2886.44444283798329974715782394574671655 km; 6372.8 km -> 2887.25995060711033944886005029688505340 km; (results extended for accuracy check: Given that the radii are only approximations anyways, .01' 1.0621333 km and .001" .00177 km, practical precision required is certainly no greater than about .0000001----i.e., .1 mm!) As distances are segments of great circles/circumferences, it is recommended that the latter value (r = 6372.8 km) be used (which most of the given solutions have already adopted, anyways). Most of the examples below adopted Kaimbridge's recommended value of 6372.8 km for the earth radius. However, the derivation of this ellipsoidal quadratic mean radius is wrong (the averaging over azimuth is biased). When applying these examples in real applications, it is better to use the mean earth radius, 6371 km. This value is recommended by the International Union of Geodesy and Geophysics and it minimizes the RMS relative error between the great circle and geodesic distance.
function haversine() { var radians = Array.prototype.map.call(arguments, function(deg) { return deg/180.0 * Math.PI; }); var lat1 = radians[0], lon1 = radians[1], lat2 = radians[2], lon2 = radians[3]; var R = 6372.8; // km var dLat = lat2 - lat1; var dLon = lon2 - lon1; var a = Math.sin(dLat / 2) * Math.sin(dLat /2) + Math.sin(dLon / 2) * Math.sin(dLon /2) * Math.cos(lat1) * Math.cos(lat2); var c = 2 * Math.asin(Math.sqrt(a)); return R * c; } console.log(haversine(36.12, -86.67, 33.94, -118.40));
Here document
JavaScript
A ''here document'' (or "heredoc") is a way of specifying a text block, preserving the line breaks, indentation and other whitespace within the text. Depending on the language being used, a ''here document'' is constructed using a command followed by "<<" (or some other symbol) followed by a token string. The text block will then start on the next line, and will be followed by the chosen token at the beginning of the following line, which is used to mark the end of the text block. ;Task: Demonstrate the use of ''here documents'' within the language. ;Related task: * [[Documentation]]
const myVar = 123; const tempLit = `Here is some multi-line string. And here is the value of "myVar": ${myVar} That's all.`; console.log(tempLit)
Heronian triangles
JavaScript
Hero's formula for the area of a triangle given the length of its three sides ''a'', ''b'', and ''c'' is given by: :::: A = \sqrt{s(s-a)(s-b)(s-c)}, where ''s'' is half the perimeter of the triangle; that is, :::: s=\frac{a+b+c}{2}. '''Heronian triangles''' are triangles whose sides ''and area'' are all integers. : An example is the triangle with sides '''3, 4, 5''' whose area is '''6''' (and whose perimeter is '''12'''). Note that any triangle whose sides are all an integer multiple of '''3, 4, 5'''; such as '''6, 8, 10,''' will also be a Heronian triangle. Define a '''Primitive Heronian triangle''' as a Heronian triangle where the greatest common divisor of all three sides is '''1''' (unity). This will exclude, for example, triangle '''6, 8, 10.''' ;Task: # Create a named function/method/procedure/... that implements Hero's formula. # Use the function to generate all the ''primitive'' Heronian triangles with sides <= 200. # Show the count of how many triangles are found. # Order the triangles by first increasing area, then by increasing perimeter, then by increasing maximum side lengths # Show the first ten ordered triangles in a table of sides, perimeter, and area. # Show a similar ordered table for those triangles with area = 210 Show all output here. '''Note''': when generating triangles it may help to restrict a <= b <= c
window.onload = function(){ var list = []; var j = 0; for(var c = 1; c <= 200; c++) for(var b = 1; b <= c; b++) for(var a = 1; a <= b; a++) if(gcd(gcd(a, b), c) == 1 && isHeron(heronArea(a, b, c))) list[j++] = new Array(a, b, c, a + b + c, heronArea(a, b, c)); sort(list); document.write("<h2>Primitive Heronian triangles with sides up to 200: " + list.length + "</h2><h3>First ten when ordered by increasing area, then perimeter:</h3><table><tr><th>Sides</th><th>Perimeter</th><th>Area</th><tr>"); for(var i = 0; i < 10; i++) document.write("<tr><td>" + list[i][0] + " x " + list[i][1] + " x " + list[i][2] + "</td><td>" + list[i][3] + "</td><td>" + list[i][4] + "</td></tr>"); document.write("</table><h3>Area = 210</h3><table><tr><th>Sides</th><th>Perimeter</th><th>Area</th><tr>"); for(var i = 0; i < list.length; i++) if(list[i][4] == 210) document.write("<tr><td>" + list[i][0] + " x " + list[i][1] + " x " + list[i][2] + "</td><td>" + list[i][3] + "</td><td>" + list[i][4] + "</td></tr>"); function heronArea(a, b, c){ var s = (a + b + c)/ 2; return Math.sqrt(s *(s -a)*(s - b)*(s - c)); } function isHeron(h){ return h % 1 == 0 && h > 0; } function gcd(a, b){ var leftover = 1, dividend = a > b ? a : b, divisor = a > b ? b : a; while(leftover != 0){ leftover = dividend % divisor; if(leftover > 0){ dividend = divisor; divisor = leftover; } } return divisor; } function sort(list){ var swapped = true; var temp = []; while(swapped){ swapped = false; for(var i = 1; i < list.length; i++){ if(list[i][4] < list[i - 1][4] || list[i][4] == list[i - 1][4] && list[i][3] < list[i - 1][3]){ temp = list[i]; list[i] = list[i - 1]; list[i - 1] = temp; swapped = true; } } } } }
Hofstadter-Conway $10,000 sequence
JavaScript
The definition of the sequence is colloquially described as: * Starting with the list [1,1], * Take the last number in the list so far: 1, I'll call it x. * Count forward x places from the beginning of the list to find the first number to add (1) * Count backward x places from the end of the list to find the second number to add (1) * Add the two indexed numbers from the list and the result becomes the next number in the list (1+1) * This would then produce [1,1,2] where 2 is the third element of the sequence. Note that indexing for the description above starts from alternately the left and right ends of the list and starts from an index of ''one''. A less wordy description of the sequence is: a(1)=a(2)=1 a(n)=a(a(n-1))+a(n-a(n-1)) The sequence begins: 1, 1, 2, 2, 3, 4, 4, 4, 5, ... Interesting features of the sequence are that: * a(n)/n tends to 0.5 as n grows towards infinity. * a(n)/n where n is a power of 2 is 0.5 * For n>4 the maximal value of a(n)/n between successive powers of 2 decreases. a(n) / n for n in 1..256 The sequence is so named because John Conway offered a prize of $10,000 to the first person who could find the first position, p in the sequence where |a(n)/n| < 0.55 for all n > p It was later found that Hofstadter had also done prior work on the sequence. The 'prize' was won quite quickly by Dr. Colin L. Mallows who proved the properties of the sequence and allowed him to find the value of n (which is much smaller than the 3,173,375,556 quoted in the NYT article). ;Task: # Create a routine to generate members of the Hofstadter-Conway $10,000 sequence. # Use it to show the maxima of a(n)/n between successive powers of two up to 2**20 # As a stretch goal: compute the value of n that would have won the prize and confirm it is true for n up to 2**20 ;Also see: * Conways Challenge Sequence, Mallows' own account. * Mathworld Article.
var hofst_10k = function(n) { var memo = [1, 1]; var a = function(n) { var result = memo[n-1]; if (typeof result !== 'number') { result = a(a(n-1))+a(n-a(n-1)); memo[n-1] = result; } return result; } return a; }(); var maxima_between_twos = function(exp) { var current_max = 0; for(var i = Math.pow(2,exp)+1; i < Math.pow(2,exp+1); i += 1) { current_max = Math.max(current_max, hofst_10k(i)/i); } return current_max; } for(var i = 1; i <= 20; i += 1) { console.log("Maxima between 2^"+i+"-2^"+(i+1)+" is: "+maxima_between_twos(i)+"\n"); }
Hofstadter Figure-Figure sequences
JavaScript from Ruby
These two sequences of positive integers are defined as: :::: \begin{align} R(1)&=1\ ;\ S(1)=2 \\ R(n)&=R(n-1)+S(n-1), \quad n>1. \end{align} The sequence S(n) is further defined as the sequence of positive integers '''''not''''' present in R(n). Sequence R starts: 1, 3, 7, 12, 18, ... Sequence S starts: 2, 4, 5, 6, 8, ... ;Task: # Create two functions named '''ffr''' and '''ffs''' that when given '''n''' return '''R(n)''' or '''S(n)''' respectively.(Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors). # No maximum value for '''n''' should be assumed. # Calculate and show that the first ten values of '''R''' are: 1, 3, 7, 12, 18, 26, 35, 45, 56, and 69 # Calculate and show that the first 40 values of '''ffr''' plus the first 960 values of '''ffs''' include all the integers from 1 to 1000 exactly once. ;References: * Sloane's A005228 and A030124. * Wolfram MathWorld * Wikipedia: Hofstadter Figure-Figure sequences.
var R = [null, 1]; var S = [null, 2]; var extend_sequences = function (n) { var current = Math.max(R[R.length-1],S[S.length-1]); var i; while (R.length <= n || S.length <= n) { i = Math.min(R.length, S.length) - 1; current += 1; if (current === R[i] + S[i]) { R.push(current); } else { S.push(current); } } } var ffr = function(n) { extend_sequences(n); return R[n]; }; var ffs = function(n) { extend_sequences(n); return S[n]; }; for (var i = 1; i <=10; i += 1) { console.log('R('+ i +') = ' + ffr(i)); } var int_array = []; for (var i = 1; i <= 40; i += 1) { int_array.push(ffr(i)); } for (var i = 1; i <= 960; i += 1) { int_array.push(ffs(i)); } int_array.sort(function(a,b){return a-b;}); for (var i = 1; i <= 1000; i += 1) { if (int_array[i-1] !== i) { throw "Something's wrong!" } else { console.log("1000 integer check ok."); } }
Hofstadter Q sequence
JavaScript
The Hofstadter Q sequence is defined as: :: \begin{align} Q(1)&=Q(2)=1, \\ Q(n)&=Q\big(n-Q(n-1)\big)+Q\big(n-Q(n-2)\big), \quad n>2. \end{align} It is defined like the [[Fibonacci sequence]], but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence. ;Task: * Confirm and display that the first ten terms of the sequence are: 1, 1, 2, 3, 3, 4, 5, 5, 6, and 6 * Confirm and display that the 1000th term is: 502 ;Optional extra credit * Count and display how many times a member of the sequence is less than its preceding term for terms up to and including the 100,000th term. * Ensure that the extra credit solution ''safely'' handles being initially asked for an '''n'''th term where '''n''' is large. (This point is to ensure that caching and/or recursion limits, if it is a concern, is correctly handled).
var hofstadterQ = function() { var memo = [1,1,1]; var Q = function (n) { var result = memo[n]; if (typeof result !== 'number') { result = Q(n - Q(n-1)) + Q(n - Q(n-2)); memo[n] = result; } return result; }; return Q; }(); for (var i = 1; i <=10; i += 1) { console.log('Q('+ i +') = ' + hofstadterQ(i)); } console.log('Q(1000) = ' + hofstadterQ(1000));
Horner's rule for polynomial evaluation
JavaScript from Haskell
A fast scheme for evaluating a polynomial such as: : -19+7x-4x^2+6x^3\, when : x=3\;. is to arrange the computation as follows: : ((((0) x + 6) x + (-4)) x + 7) x + (-19)\; And compute the result from the innermost brackets outwards as in this pseudocode: coefficients ''':=''' [-19, 7, -4, 6] ''# list coefficients of all x^0..x^n in order'' x ''':=''' 3 accumulator ''':=''' 0 '''for''' i '''in''' ''length''(coefficients) '''downto''' 1 '''do''' ''# Assumes 1-based indexing for arrays'' accumulator ''':=''' ( accumulator * x ) + coefficients[i] '''done''' ''# accumulator now has the answer'' '''Task Description''' :Create a routine that takes a list of coefficients of a polynomial in order of increasing powers of x; together with a value of x to compute its value at, and return the value of the polynomial at that value using Horner's rule. Cf. [[Formal power series]]
function horner(coeffs, x) { return coeffs.reduceRight( function(acc, coeff) { return(acc * x + coeff) }, 0); } console.log(horner([-19,7,-4,6],3)); // ==> 128
Identity matrix
JavaScript
Build an identity matrix of a size known at run-time. An ''identity matrix'' is a square matrix of size '''''n'' x ''n''''', where the diagonal elements are all '''1'''s (ones), and all the other elements are all '''0'''s (zeroes). I_n = \begin{bmatrix} 1 & 0 & 0 & \cdots & 0 \\ 0 & 1 & 0 & \cdots & 0 \\ 0 & 0 & 1 & \cdots & 0 \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 & 0 & \cdots & 1 \\ \end{bmatrix} ;Related tasks: * [[Spiral matrix]] * [[Zig-zag matrix]] * [[Ulam_spiral_(for_primes)]]
(() => { // identityMatrix :: Int -> [[Int]] const identityMatrix = n => Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => i !== j ? 0 : 1)); // ----------------------- TEST ------------------------ return identityMatrix(5) .map(JSON.stringify) .join('\n'); })();
Include a file
JavaScript
Demonstrate the language's ability to include source code from other files. ;See Also * [[Compiler/Simple file inclusion pre processor]]
var s = document.createElement('script'); s.type = 'application/javascript'; // path to the desired file s.src = 'http://code.jquery.com/jquery-1.6.2.js'; document.body.appendChild(s);
Intersecting number wheels
JavaScript
A number wheel has: * A ''name'' which is an uppercase letter. * A set of ordered ''values'' which are either ''numbers'' or ''names''. A ''number'' is generated/yielded from a named wheel by: :1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel": ::1.a If the value is a number, yield it. ::1.b If the value is a name, yield the next value from the named wheel ::1.c Advance the position of this wheel. Given the wheel : A: 1 2 3 the number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ... '''Note:''' When more than one wheel is defined as a set of intersecting wheels then the first named wheel is assumed to be the one that values are generated from. ;Examples: Given the wheels: A: 1 B 2 B: 3 4 The series of numbers generated starts: 1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2... The intersections of number wheels can be more complex, (and might loop forever), and wheels may be multiply connected. '''Note:''' If a named wheel is referenced more than once by one or many other wheels, then there is only one position of the wheel that is advanced by each and all references to it. E.g. A: 1 D D D: 6 7 8 Generates: 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ... ;Task: Generate and show the first twenty terms of the sequence of numbers generated from these groups: Intersecting Number Wheel group: A: 1 2 3 Intersecting Number Wheel group: A: 1 B 2 B: 3 4 Intersecting Number Wheel group: A: 1 D D D: 6 7 8 Intersecting Number Wheel group: A: 1 B C B: 3 4 C: 5 B Show your output here, on this page.
Map-accumulation of a recursive digit-search, over an array of given length and arbitrary contents.
Intersecting number wheels
JavaScript from Python
A number wheel has: * A ''name'' which is an uppercase letter. * A set of ordered ''values'' which are either ''numbers'' or ''names''. A ''number'' is generated/yielded from a named wheel by: :1. Starting at the first value of the named wheel and advancing through subsequent values and wrapping around to the first value to form a "wheel": ::1.a If the value is a number, yield it. ::1.b If the value is a name, yield the next value from the named wheel ::1.c Advance the position of this wheel. Given the wheel : A: 1 2 3 the number 1 is first generated, then 2, then 3, 1, 2, 3, 1, ... '''Note:''' When more than one wheel is defined as a set of intersecting wheels then the first named wheel is assumed to be the one that values are generated from. ;Examples: Given the wheels: A: 1 B 2 B: 3 4 The series of numbers generated starts: 1, 3, 2, 1, 4, 2, 1, 3, 2, 1, 4, 2, 1, 3, 2... The intersections of number wheels can be more complex, (and might loop forever), and wheels may be multiply connected. '''Note:''' If a named wheel is referenced more than once by one or many other wheels, then there is only one position of the wheel that is advanced by each and all references to it. E.g. A: 1 D D D: 6 7 8 Generates: 1 6 7 1 8 6 1 7 8 1 6 7 1 8 6 1 7 8 1 6 ... ;Task: Generate and show the first twenty terms of the sequence of numbers generated from these groups: Intersecting Number Wheel group: A: 1 2 3 Intersecting Number Wheel group: A: 1 B 2 B: 3 4 Intersecting Number Wheel group: A: 1 D D D: 6 7 8 Intersecting Number Wheel group: A: 1 B C B: 3 4 C: 5 B Show your output here, on this page.
(() => { 'use strict'; // main :: IO () const main = () => { // clockWorkTick :: Dict -> (Dict, Char) const clockWorkTick = wheelMap => { // The new configuration of the wheels, tupled with // a digit found by recursive descent from a single // click of the first wheel. const click = wheels => wheelName => { const wheel = wheels[wheelName] || ['?'], v = wheel[0]; return bool(click)(Tuple)(isDigit(v) || '?' === v)( insertDict(wheelName)( leftRotate(wheel) )(wheels) )(v); }; return click(wheelMap)('A'); }; // leftRotate ::[a] -> [a] const leftRotate = xs => // The head of the list appended // to the tail of of the list. 0 < xs.length ? ( xs.slice(1).concat(xs[0]) ) : []; // TEST ------------------------------------------- // State of each wheel-set after 20 clicks, // paired with the resulting series of characters. const tuple = uncurry(Tuple); const wheelLists = [ [tuple('A', '123')], [tuple('A', '1B2'), tuple('B', '34')], [tuple('A', '1DD'), tuple('D', '678')], [tuple('A', '1BC'), tuple('B', '34'), tuple('C', '5B')] ]; console.log([ 'Series and state of each wheel-set after 20 clicks:\n', unlines( map(tuples => showWheels( mapAccumL( compose(constant, clockWorkTick) )(dictFromList(tuples))(replicate(20)('')) ))(wheelLists) ), '\nInitial state of each wheel-set:\n', map(map(compose( JSON.stringify, dictFromList, x => [Array.from(x)] )))(wheelLists).join('\n') ].join('\n')); }; // DISPLAY FORMATTING --------------------------------- // showWheels :: (Dict, [Char]) -> String const showWheels = tpl => JSON.stringify( Array.from(secondArrow(concat)(tpl)) ); // GENERIC FUNCTIONS ---------------------------------- // Tuple (,) :: a -> b -> (a, b) const Tuple = a => b => ({ type: 'Tuple', '0': a, '1': b, length: 2 }); // bool :: a -> a -> Bool -> a const bool = f => t => p => p ? t : f; // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (...fs) => x => fs.reduceRight((a, f) => f(a), x); // concat :: [[a]] -> [a] // concat :: [String] -> String const concat = xs => 0 < xs.length ? (() => { const unit = 'string' !== typeof xs[0] ? ( [] ) : ''; return unit.concat.apply(unit, xs); })() : []; // constant :: a -> b -> a const constant = k => _ => k; // dictFromList :: [(k, v)] -> Dict const dictFromList = kvs => Object.fromEntries(kvs); // secondArrow :: (a -> b) -> ((c, a) -> (c, b)) const secondArrow = f => xy => // A function over a simple value lifted // to a function over a tuple. // f (a, b) -> (a, f(b)) Tuple(xy[0])( f(xy[1]) ); // insertDict :: String -> a -> Dict -> Dict const insertDict = k => v => dct => Object.assign({}, dct, { [k]: v }); // isDigit :: Char -> Bool const isDigit = c => { const n = c.codePointAt(0); return 48 <= n && 57 >= n; }; // map :: (a -> b) -> [a] -> [b] const map = f => xs => (Array.isArray(xs) ? ( xs ) : xs.split('')).map(f); // Map-accumulation is a combination of map and a catamorphism; // it applies a function to each element of a list, passing an // accumulating parameter from left to right, and returning a final // value of this accumulator together with the new list. // mapAccumL :: (acc -> x -> (acc, y)) -> acc -> [x] -> (acc, [y]) const mapAccumL = f => acc => xs => xs.reduce((a, x) => { const pair = f(a[0])(x); return Tuple(pair[0])(a[1].concat(pair[1])); }, Tuple(acc)([])); // replicate :: Int -> a -> [a] const replicate = n => x => Array.from({ length: n }, () => x); // uncurry :: (a -> b -> c) -> ((a, b) -> c) const uncurry = f => (x, y) => f(x)(y); // unlines :: [String] -> String const unlines = xs => xs.join('\n'); // MAIN --- return main(); })();
JSON
JavaScript
Load a JSON string into a data structure. Also, create a new data structure and serialize it into JSON. Use objects and arrays (as appropriate for your language) and make sure your JSON is valid (https://jsonformatter.org).
var data = JSON.parse('{ "foo": 1, "bar": [10, "apples"] }'); var sample = { "blue": [1,2], "ocean": "water" }; var json_string = JSON.stringify(sample);
Jewels and stones
Javascript
Create a function which takes two string parameters: 'stones' and 'jewels' and returns an integer. Both strings can contain any number of upper or lower case letters. However, in the case of 'jewels', all letters must be distinct. The function should count (and return) how many 'stones' are 'jewels' or, in other words, how many letters in 'stones' are also letters in 'jewels'. Note that: :# Only letters in the ISO basic Latin alphabet i.e. 'A to Z' or 'a to z' need be considered. :# A lower case letter is considered to be different from its upper case equivalent for this purpose, i.e., 'a' != 'A'. :# The parameters do not need to have exactly the same names. :# Validating the arguments is unnecessary. So, for example, if passed "aAAbbbb" for 'stones' and "aA" for 'jewels', the function should return 3. This task was inspired by this problem.
(() => { // jewelCount :: String -> String -> Int const jewelCount = (j, s) => { const js = j.split(''); return s.split('') .reduce((a, c) => js.includes(c) ? a + 1 : a, 0) }; // TEST ----------------------------------------------- return [ ['aA', 'aAAbbbb'], ['z', 'ZZ'] ] .map(x => jewelCount(...x)) })();
Julia set
JavaScript
Task Generate and draw a Julia set. ;Related tasks * Mandelbrot Set
var maxIterations = 450, minX = -.5, maxX = .5, minY = -.5, maxY = .5, wid, hei, ctx, jsX = 0.285, jsY = 0.01; function remap( x, t1, t2, s1, s2 ) { var f = ( x - t1 ) / ( t2 - t1 ), g = f * ( s2 - s1 ) + s1; return g; } function getColor( c ) { var r, g, b, p = c / 32, l = ~~( p * 6 ), o = p * 6 - l, q = 1 - o; switch( l % 6 ) { case 0: r = 1; g = o; b = 0; break; case 1: r = q; g = 1; b = 0; break; case 2: r = 0; g = 1; b = o; break; case 3: r = 0; g = q; b = 1; break; case 4: r = o; g = 0; b = 1; break; case 5: r = 1; g = 0; b = q; break; } var c = "#" + ( "00" + ( ~~( r * 255 ) ).toString( 16 ) ).slice( -2 ) + ( "00" + ( ~~( g * 255 ) ).toString( 16 ) ).slice( -2 ) + ( "00" + ( ~~( b * 255 ) ).toString( 16 ) ).slice( -2 ); return (c); } function drawFractal() { var a, as, za, b, bs, zb, cnt, clr for( var j = 0; j < hei; j++ ) { for( var i = 0; i < wid; i++ ) { a = remap( i, 0, wid, minX, maxX ) b = remap( j, 0, hei, minY, maxY ) cnt = 0; while( ++cnt < maxIterations ) { za = a * a; zb = b * b; if( za + zb > 4 ) break; as = za - zb; bs = 2 * a * b; a = as + jsX; b = bs + jsY; } if( cnt < maxIterations ) { ctx.fillStyle = getColor( cnt ); } ctx.fillRect( i, j, 1, 1 ); } } } function init() { var canvas = document.createElement( "canvas" ); wid = hei = 800; canvas.width = wid; canvas.height = hei; ctx = canvas.getContext( "2d" ); ctx.fillStyle = "black"; ctx.fillRect( 0, 0, wid, hei ); document.body.appendChild( canvas ); drawFractal(); }
Kaprekar numbers
JavaScript
A positive integer is a Kaprekar number if: * It is '''1''' (unity) * The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive. ;Example Kaprekar numbers: * 2223 is a Kaprekar number, as 2223 * 2223 = 4941729, 4941729 may be split to 494 and 1729, and 494 + 1729 = 2223. * The series of Kaprekar numbers is known as A006886, and begins as 1, 9, 45, 55, .... ;Example process: 10000 (1002) splitting from left to right: * The first split is [1, 0000], and is invalid; the 0000 element consists entirely of 0s, and 0 is not considered positive. * Slight optimization opportunity: When splitting from left to right, once the right part consists entirely of 0s, no further testing is needed; all further splits would also be invalid. ;Task: Generate and show all Kaprekar numbers less than 10,000. ;Extra credit: Optionally, count (and report the count of) how many Kaprekar numbers are less than 1,000,000. ;Extra extra credit: The concept of Kaprekar numbers is not limited to base 10 (i.e. decimal numbers); if you can, show that Kaprekar numbers exist in other bases too. For this purpose, do the following: * Find all Kaprekar numbers for base 17 between 1 and 1,000,000 (one million); * Display each of them in base 10 representation; * Optionally, using base 17 representation (use letters 'a' to 'g' for digits 10(10) to 16(10)), display each of the numbers, its square, and where to split the square. For example, 225(10) is "d4" in base 17, its square "a52g", and a5(17) + 2g(17) = d4(17), so the display would be something like:225 d4 a52g a5 + 2g ;Reference: * The Kaprekar Numbers by Douglas E. Iannucci (2000). PDF version ;Related task: * [[Casting out nines]]
function kaprekar( s, e, bs, pbs ) { bs = bs || 10; pbs = pbs || 10 const toString = n => n.toString(pbs).toUpperCase() document.write('start:',toString(s), ' end:',toString(e), ' base:',bs, ' printBase:',pbs, '<br>' ) for (var k=0, n=s; n<=e; n+=1) if (isKaprekar(n, bs)) k+=1, document.write(toString(n), ' ') document.write('<br>found ', k, ' numbers<br><br>') } kaprekar( 1, 99 ) kaprekar( 1, 255, 16) kaprekar( 1, 255, 16, 16) kaprekar( 1, 288, 17, 17)
Kernighans large earthquake problem
JavaScript
Brian Kernighan, in a lecture at the University of Nottingham, described a problem on which this task is based. ;Problem: You are given a a data file of thousands of lines; each of three `whitespace` separated fields: a date, a one word name and the magnitude of the event. Example lines from the file would be lines like: 8/27/1883 Krakatoa 8.8 5/18/1980 MountStHelens 7.6 3/13/2009 CostaRica 5.1 ;Task: * Create a program or script invocation to find all the events with magnitude greater than 6 * Assuming an appropriate name e.g. "data.txt" for the file: :# Either: Show how your program is invoked to process a data file of that name. :# Or: Incorporate the file name into the program, (as it is assumed that the program is single use).
const fs = require("fs"); const readline = require("readline"); const args = process.argv.slice(2); if (!args.length) { console.error("must supply file name"); process.exit(1); } const fname = args[0]; const readInterface = readline.createInterface({ input: fs.createReadStream(fname), console: false, }); readInterface.on("line", (line) => { const fields = line.split(/\s+/); if (+fields[fields.length - 1] > 6) { console.log(line); } });
Keyboard input/Obtain a Y or N response
JavaScript
Obtain a valid '''Y''' or '''N''' response from the [[input device::keyboard]]. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing '''Y''' or '''N''' key-press from being evaluated. The response should be obtained as soon as '''Y''' or '''N''' are pressed, and there should be no need to press an enter key.
const readline = require('readline'); readline.emitKeypressEvents(process.stdin); process.stdin.setRawMode(true); var wait_key = async function() { return await new Promise(function(resolve,reject) { var key_listen = function(str,key) { process.stdin.removeListener('keypress', key_listen); resolve(str); } process.stdin.on('keypress', key_listen); }); } var done = function() { process.exit(); } var go = async function() { do { console.log('Press any key...'); var key = await wait_key(); console.log("Key pressed is",key); await new Promise(function(resolve) { setTimeout(resolve,1000); }); } while(key != 'y'); done(); } go();
Knight's tour
Javascript
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position. Input and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard. Input: starting square Output: move sequence ;Related tasks * [[A* search algorithm]] * [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
class KnightTour { constructor() { this.width = 856; this.height = 856; this.cellCount = 8; this.size = 0; this.knightPiece = "\u2658"; this.knightPos = { x: 0, y: 0 }; this.ctx = null; this.step = this.width / this.cellCount; this.lastTime = 0; this.wait; this.delay; this.success; this.jumps; this.directions = []; this.visited = []; this.path = []; document.getElementById("start").addEventListener("click", () => { this.startHtml(); }); this.init(); this.drawBoard(); } drawBoard() { let a = false, xx, yy; for (let y = 0; y < this.cellCount; y++) { for (let x = 0; x < this.cellCount; x++) { if (a) { this.ctx.fillStyle = "#607db8"; } else { this.ctx.fillStyle = "#aecaf0"; } a = !a; xx = x * this.step; yy = y * this.step; this.ctx.fillRect(xx, yy, xx + this.step, yy + this.step); } if (!(this.cellCount & 1)) a = !a; } if (this.path.length) { const s = this.step >> 1; this.ctx.lineWidth = 3; this.ctx.fillStyle = "black"; this.ctx.beginPath(); this.ctx.moveTo(this.step * this.knightPos.x + s, this.step * this.knightPos.y + s); let a, b, v = this.path.length - 1; for (; v > -1; v--) { a = this.path[v].pos.x * this.step + s; b = this.path[v].pos.y * this.step + s; this.ctx.lineTo(a, b); this.ctx.fillRect(a - 5, b - 5, 10, 10); } this.ctx.stroke(); } } createMoves(pos) { const possibles = []; let x = 0, y = 0, m = 0, l = this.directions.length; for (; m < l; m++) { x = pos.x + this.directions[m].x; y = pos.y + this.directions[m].y; if (x > -1 && x < this.cellCount && y > -1 && y < this.cellCount && !this.visited[x + y * this.cellCount]) { possibles.push({ x, y }) } } return possibles; } warnsdorff(pos) { const possibles = this.createMoves(pos); if (possibles.length < 1) return []; const moves = []; for (let p = 0, l = possibles.length; p < l; p++) { let ps = this.createMoves(possibles[p]); moves.push({ len: ps.length, pos: possibles[p] }); } moves.sort((a, b) => { return b.len - a.len; }); return moves; } startHtml() { this.cellCount = parseInt(document.getElementById("cellCount").value); this.size = Math.floor(this.width / this.cellCount) this.wait = this.delay = parseInt(document.getElementById("delay").value); this.step = this.width / this.cellCount; this.ctx.font = this.size + "px Arial"; document.getElementById("log").innerText = ""; document.getElementById("path").innerText = ""; this.path = []; this.jumps = 1; this.success = true; this.visited = []; const cnt = this.cellCount * this.cellCount; for (let a = 0; a < cnt; a++) { this.visited.push(false); } const kx = parseInt(document.getElementById("knightx").value), ky = parseInt(document.getElementById("knighty").value); this.knightPos = { x: (kx > this.cellCount || kx < 0) ? Math.floor(Math.random() * this.cellCount) : kx, y: (ky > this.cellCount || ky < 0) ? Math.floor(Math.random() * this.cellCount) : ky }; this.mainLoop = (time = 0) => { const dif = time - this.lastTime; this.lastTime = time; this.wait -= dif; if (this.wait > 0) { requestAnimationFrame(this.mainLoop); return; } this.wait = this.delay; let moves; if (this.success) { moves = this.warnsdorff(this.knightPos); } else { if (this.path.length > 0) { const path = this.path[this.path.length - 1]; moves = path.m; if (moves.length < 1) this.path.pop(); this.knightPos = path.pos this.visited[this.knightPos.x + this.knightPos.y * this.cellCount] = false; this.jumps--; this.wait = this.delay; } else { document.getElementById("log").innerText = "Can't find a solution!"; return; } } this.drawBoard(); const ft = this.step - (this.step >> 3); this.ctx.fillStyle = "#000"; this.ctx.fillText(this.knightPiece, this.knightPos.x * this.step, this.knightPos.y * this.step + ft); if (moves.length < 1) { if (this.jumps === this.cellCount * this.cellCount) { document.getElementById("log").innerText = "Tour finished!"; let str = ""; for (let z of this.path) { str += `${1 + z.pos.x + z.pos.y * this.cellCount}, `; } str += `${1 + this.knightPos.x + this.knightPos.y * this.cellCount}`; document.getElementById("path").innerText = str; return; } else { this.success = false; } } else { this.visited[this.knightPos.x + this.knightPos.y * this.cellCount] = true; const move = moves.pop(); this.path.push({ pos: this.knightPos, m: moves }); this.knightPos = move.pos this.success = true; this.jumps++; } requestAnimationFrame(this.mainLoop); }; this.mainLoop(); } init() { const canvas = document.createElement("canvas"); canvas.id = "cv"; canvas.width = this.width; canvas.height = this.height; this.ctx = canvas.getContext("2d"); document.getElementById("out").appendChild(canvas); this.directions = [{ x: -1, y: -2 }, { x: -2, y: -1 }, { x: 1, y: -2 }, { x: 2, y: -1 }, { x: -1, y: 2 }, { x: -2, y: 1 }, { x: 1, y: 2 }, { x: 2, y: 1 } ]; } } new KnightTour();
Knight's tour
Javascript from Haskell
Task Problem: you have a standard 8x8 chessboard, empty but for a single knight on some square. Your task is to emit a series of legal knight moves that result in the knight visiting every square on the chessboard exactly once. Note that it is ''not'' a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position. Input and output may be textual or graphical, according to the conventions of the programming environment. If textual, squares should be indicated in algebraic notation. The output should indicate the order in which the knight visits the squares, starting with the initial position. The form of the output may be a diagram of the board with the squares numbered according to visitation sequence, or a textual list of algebraic coordinates in order, or even an actual animation of the knight moving around the chessboard. Input: starting square Output: move sequence ;Related tasks * [[A* search algorithm]] * [[N-queens problem]] * [[Solve a Hidato puzzle]] * [[Solve a Holy Knight's tour]] * [[Solve a Hopido puzzle]] * [[Solve a Numbrix puzzle]] * [[Solve the no connection puzzle]]
(() => { 'use strict'; // knightsTour :: Int -> [(Int, Int)] -> [(Int, Int)] const knightsTour = rowLength => moves => { const go = path => { const findMoves = xy => difference(knightMoves(xy), path), warnsdorff = minimumBy( comparing(compose(length, findMoves)) ), options = findMoves(path[0]); return 0 < options.length ? ( go([warnsdorff(options)].concat(path)) ) : reverse(path); }; // board :: [[(Int, Int)]] const board = concatMap( col => concatMap( row => [ [col, row] ], enumFromTo(1, rowLength)), enumFromTo(1, rowLength) ); // knightMoves :: (Int, Int) -> [(Int, Int)] const knightMoves = ([x, y]) => concatMap( ([dx, dy]) => { const ab = [x + dx, y + dy]; return elem(ab, board) ? ( [ab] ) : []; }, [ [-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1] ] ); return go(moves); }; // TEST ----------------------------------------------- // main :: IO() const main = () => { // boardSize :: Int const boardSize = 8; // tour :: [(Int, Int)] const tour = knightsTour(boardSize)( [fromAlgebraic('e5')] ); // report :: String const report = '(Board size ' + boardSize + '*' + boardSize + ')\n\n' + 'Route: \n\n' + showRoute(boardSize)(tour) + '\n\n' + 'Coverage and order: \n\n' + showCoverage(boardSize)(tour) + '\n\n'; return ( console.log(report), report ); } // DISPLAY -------------------------------------------- // algebraic :: (Int, Int) -> String const algebraic = ([x, y]) => chr(x + 96) + y.toString(); // fromAlgebraic :: String -> (Int, Int) const fromAlgebraic = s => 2 <= s.length ? ( [ord(s[0]) - 96, parseInt(s.slice(1))] ) : undefined; // showCoverage :: Int -> [(Int, Int)] -> String const showCoverage = rowLength => xys => { const intMax = xys.length, w = 1 + intMax.toString().length return unlines(map(concat, chunksOf( rowLength, map(composeList([justifyRight(w, ' '), str, fst]), sortBy( mappendComparing([ compose(fst, snd), compose(snd, snd) ]), zip(enumFromTo(1, intMax), xys) ) ) ) )); }; // showRoute :: Int -> [(Int, Int)] -> String const showRoute = rowLength => xys => { const w = 1 + rowLength.toString().length; return unlines(map( xs => xs.join(' -> '), chunksOf( rowLength, map(compose(justifyRight(w, ' '), algebraic), xys) ) )); }; // GENERIC FUNCTIONS ---------------------------------- // Tuple (,) :: a -> b -> (a, b) const Tuple = (a, b) => ({ type: 'Tuple', '0': a, '1': b, length: 2 }); // chr :: Int -> Char const chr = x => String.fromCodePoint(x); // chunksOf :: Int -> [a] -> [[a]] const chunksOf = (n, xs) => enumFromThenTo(0, n, xs.length - 1) .reduce( (a, i) => a.concat([xs.slice(i, (n + i))]), [] ); // compare :: a -> a -> Ordering const compare = (a, b) => a < b ? -1 : (a > b ? 1 : 0); // comparing :: (a -> b) -> (a -> a -> Ordering) const comparing = f => (x, y) => { const a = f(x), b = f(y); return a < b ? -1 : (a > b ? 1 : 0); }; // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (f, g) => x => f(g(x)); // composeList :: [(a -> a)] -> (a -> a) const composeList = fs => x => fs.reduceRight((a, f) => f(a), x, fs); // concat :: [[a]] -> [a] // concat :: [String] -> String const concat = xs => 0 < xs.length ? (() => { const unit = 'string' !== typeof xs[0] ? ( [] ) : ''; return unit.concat.apply(unit, xs); })() : []; // concatMap :: (a -> [b]) -> [a] -> [b] const concatMap = (f, xs) => xs.reduce((a, x) => a.concat(f(x)), []); // difference :: Eq a => [a] -> [a] -> [a] const difference = (xs, ys) => { const s = new Set(ys.map(str)); return xs.filter(x => !s.has(str(x))); }; // elem :: Eq a => a -> [a] -> Bool const elem = (x, xs) => xs.some(eq(x)) // enumFromThenTo :: Int -> Int -> Int -> [Int] const enumFromThenTo = (x1, x2, y) => { const d = x2 - x1; return Array.from({ length: Math.floor(y - x2) / d + 2 }, (_, i) => x1 + (d * i)); }; // enumFromTo :: Int -> Int -> [Int] const enumFromTo = (m, n) => Array.from({ length: 1 + n - m }, (_, i) => m + i); // eq (==) :: Eq a => a -> a -> Bool const eq = a => b => { const t = typeof a; return t !== typeof b ? ( false ) : 'object' !== t ? ( 'function' !== t ? ( a === b ) : a.toString() === b.toString() ) : (() => { const kvs = Object.entries(a); return kvs.length !== Object.keys(b).length ? ( false ) : kvs.every(([k, v]) => eq(v)(b[k])); })(); }; // fst :: (a, b) -> a const fst = tpl => tpl[0]; // justifyRight :: Int -> Char -> String -> String const justifyRight = (n, cFiller) => s => n > s.length ? ( s.padStart(n, cFiller) ) : s; // length :: [a] -> Int const length = xs => (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity; // map :: (a -> b) -> [a] -> [b] const map = (f, xs) => (Array.isArray(xs) ? ( xs ) : xs.split('')).map(f); // mappendComparing :: [(a -> b)] -> (a -> a -> Ordering) const mappendComparing = fs => (x, y) => fs.reduce( (ordr, f) => (ordr || compare(f(x), f(y))), 0 ); // minimumBy :: (a -> a -> Ordering) -> [a] -> a const minimumBy = f => xs => xs.reduce((a, x) => undefined === a ? x : ( 0 > f(x, a) ? x : a ), undefined); // ord :: Char -> Int const ord = c => c.codePointAt(0); // reverse :: [a] -> [a] const reverse = xs => 'string' !== typeof xs ? ( xs.slice(0).reverse() ) : xs.split('').reverse().join(''); // snd :: (a, b) -> b const snd = tpl => tpl[1]; // sortBy :: (a -> a -> Ordering) -> [a] -> [a] const sortBy = (f, xs) => xs.slice() .sort(f); // str :: a -> String const str = x => x.toString(); // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = (n, xs) => xs.slice(0, n); // unlines :: [String] -> String const unlines = xs => xs.join('\n'); // Use of `take` and `length` here allows for zipping with non-finite // lists - i.e. generators like cycle, repeat, iterate. // zip :: [a] -> [b] -> [(a, b)] const zip = (xs, ys) => { const lng = Math.min(length(xs), length(ys)); const bs = take(lng, ys); return take(lng, xs).map((x, i) => Tuple(x, bs[i])); }; // MAIN --- return main(); })();
Koch curve
JavaScript
Draw a Koch curve. See details: Koch curve
Generates SVG. To view, save to a file with the extension '.svg', and open in a browser.
Koch curve
JavaScript from Haskell
Draw a Koch curve. See details: Koch curve
(() => { 'use strict'; // kochSnowflake :: Int -> (Float, Float) -> (Float, Float) // -> [(Float, Float)] const kochSnowflake = n => a => b => { // List of points on a Koch snowflake of order n, derived // from an equilateral triangle with base a b. const points = [a, equilateralApex(a)(b), b]; return concat( zipWith(kochCurve(n))(points)( points.slice(1).concat([points[0]]) ) ); }; // koch :: Int -> (Float, Float) -> (Float, Float) // -> [(Float, Float)] const kochCurve = n => ab => xy => { // A Koch curve of order N, starting at the point // (a, b), and ending at the point (x, y). const go = n => ([ab, xy]) => 0 !== n ? (() => { const [mp, mq] = midThirdOfLine(ab)(xy); const points = [ ab, mp, equilateralApex(mp)(mq), mq, xy ]; return zip(points)(points.slice(1)) .flatMap(go(n - 1)) })() : [xy]; return [ab].concat(go(n)([ab, xy])); }; // equilateralApex :: (Float, Float) -> (Float, Float) -> (Float, Float) const equilateralApex = p => q => rotatedPoint(Math.PI / 3)(p)(q); // rotatedPoint :: Float -> (Float, Float) -> // (Float, Float) -> (Float, Float) const rotatedPoint = theta => ([ox, oy]) => ([a, b]) => { // The point ab rotated theta radians // around the origin xy. const [dx, dy] = rotatedVector(theta)( [a - ox, oy - b] ); return [ox + dx, oy - dy]; }; // rotatedVector :: Float -> (Float, Float) -> (Float, Float) const rotatedVector = theta => ([x, y]) => // The vector xy rotated by theta radians. [ x * Math.cos(theta) - y * Math.sin(theta), x * Math.sin(theta) + y * Math.cos(theta) ]; // midThirdOfLine :: (Float, Float) -> (Float, Float) // -> ((Float, Float), (Float, Float)) const midThirdOfLine = ab => xy => { // Second of three equal segments of // the line between ab and xy. const vector = zipWith(dx => x => (dx - x) / 3)(xy)(ab), f = zipWith(add)(vector), p = f(ab); return [p, f(p)]; }; // TEST ----------------------------------------------- // main :: IO () const main = () => // SVG showing a Koch snowflake of order 4. console.log( svgFromPoints(1024)( kochSnowflake(5)( [200, 600] )([800, 600]) ) ); // SVG ---------------------------------------------- // svgFromPoints :: Int -> [(Int, Int)] -> String const svgFromPoints = w => ps => [ '<svg xmlns="http://www.w3.org/2000/svg"', `width="500" height="500" viewBox="5 5 ${w} ${w}">`, `<path d="M${ ps.flatMap(p => p.map(n => n.toFixed(2))).join(' ') }" `, 'stroke-width="2" stroke="red" fill="transparent"/>', '</svg>' ].join('\n'); // GENERIC -------------------------------------------- // add :: Num -> Num -> Num const add = a => b => a + b; // concat :: [[a]] -> [a] const concat = xs => [].concat.apply([], xs); // zip :: [a] -> [b] -> [(a, b)] const zip = xs => ys => xs.slice( 0, Math.min(xs.length, ys.length) ).map((x, i) => [x, ys[i]]); // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = f => xs => ys => xs.slice( 0, Math.min(xs.length, ys.length) ).map((x, i) => f(x)(ys[i])); // MAIN --- return main(); })();
Largest int from concatenated ints
JavaScript
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer. Use the following two sets of integers as tests and show your program output here. :::::* {1, 34, 3, 98, 9, 76, 45, 4} :::::* {54, 546, 548, 60} ;Possible algorithms: # A solution could be found by trying all combinations and return the best. # Another way to solve this is to note that in the best arrangement, for any two adjacent original integers '''X''' and '''Y''', the concatenation '''X''' followed by '''Y''' will be numerically greater than or equal to the concatenation '''Y''' followed by '''X. # Yet another way to solve this is to pad the integers to the same size by repeating the digits then sort using these repeated integers as a sort key. ;See also: * Algorithms: What is the most efficient way to arrange the given numbers to form the biggest number? * Constructing the largest number possible by rearranging a list
(function () { 'use strict'; // maxCombine :: [Int] -> Int function maxCombine(xs) { return parseInt( xs.sort( function (x, y) { var a = x.toString(), b = y.toString(), ab = parseInt(a + b), ba = parseInt(b + a); return ab > ba ? -1 : (ab < ba ? 1 : 0); } ) .join(''), 10 ); } return [ [1, 34, 3, 98, 9, 76, 45, 4], [54, 546, 548, 60] ].map(maxCombine); })();
Law of cosines - triples
JavaScript
The Law of cosines states that for an angle g, (gamma) of any triangle, if the sides adjacent to the angle are A and B and the side opposite is C; then the lengths of the sides are related by this formula: A2 + B2 - 2ABcos(g) = C2 ;Specific angles: For an angle of of '''90o''' this becomes the more familiar "Pythagoras equation": A2 + B2 = C2 For an angle of '''60o''' this becomes the less familiar equation: A2 + B2 - AB = C2 And finally for an angle of '''120o''' this becomes the equation: A2 + B2 + AB = C2 ;Task: * Find all integer solutions (in order) to the three specific cases, distinguishing between each angle being considered. * Restrain all sides to the integers '''1..13''' inclusive. * Show how many results there are for each of the three angles mentioned above. * Display results on this page. Note: Triangles with the same length sides but different order are to be treated as the same. ;Optional Extra credit: * How many 60deg integer triples are there for sides in the range 1..10_000 ''where the sides are not all of the same length''. ;Related Task * [[Pythagorean triples]] ;See also: * Visualising Pythagoras: ultimate proofs and crazy contortions Mathlogger Video
(() => { 'use strict'; // main :: IO () const main = () => { const f90 = dct => x2 => dct[x2], f60 = dct => (x2, ab) => dct[x2 - ab], f120 = dct => (x2, ab) => dct[x2 + ab], f60unequal = dct => (x2, ab, a, b) => (a !== b) ? ( dct[x2 - ab] ) : undefined; // triangles :: Dict -> (Int -> Int -> Int -> Int -> Maybe Int) // -> [String] const triangles = (f, n) => { const xs = enumFromTo(1, n), fr = f(xs.reduce((a, x) => (a[x * x] = x, a), {})), gc = xs.reduce((a, _) => a, {}), setSoln = new Set(); return ( xs.forEach( a => { const a2 = a * a; enumFromTo(1, 1 + a).forEach( b => { const suma2b2 = a2 + b * b, c = fr(suma2b2, a * b, a, b); if (undefined !== c) { setSoln.add([a, b, c].sort()) }; } ); } ), Array.from(setSoln.keys()) ); }; const result = 'Triangles of maximum side 13:\n\n' + unlines( zipWith( (s, f) => { const ks = triangles(f, 13); return ks.length.toString() + ' solutions for ' + s + ' degrees:\n' + unlines(ks) + '\n'; }, ['120', '90', '60'], [f120, f90, f60] ) ) + '\nUneven triangles of maximum side 10000. Total:\n' + triangles(f60unequal, 10000).length return ( //console.log(result), result ); }; // GENERIC FUNCTIONS ---------------------------- // concatMap :: (a -> [b]) -> [a] -> [b] const concatMap = (f, xs) => xs.reduce((a, x) => a.concat(f(x)), []); // enumFromTo :: Int -> Int -> [Int] const enumFromTo = (m, n) => m <= n ? iterateUntil( x => n <= x, x => 1 + x, m ) : []; // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a] const iterateUntil = (p, f, x) => { const vs = [x]; let h = x; while (!p(h))(h = f(h), vs.push(h)); return vs; }; // Returns Infinity over objects without finite length // this enables zip and zipWith to choose the shorter // argument when one non-finite like cycle, repeat etc // length :: [a] -> Int const length = xs => xs.length || Infinity; // take :: Int -> [a] -> [a] // take :: Int -> String -> String const take = (n, xs) => xs.constructor.constructor.name !== 'GeneratorFunction' ? ( xs.slice(0, n) ) : [].concat.apply([], Array.from({ length: n }, () => { const x = xs.next(); return x.done ? [] : [x.value]; })); // unlines :: [String] -> String const unlines = xs => xs.join('\n'); // Use of `take` and `length` here allows zipping with non-finite lists // i.e. generators like cycle, repeat, iterate. // Use of `take` and `length` here allows zipping with non-finite lists // i.e. generators like cycle, repeat, iterate. // zipWith :: (a -> b -> c) -> [a] -> [b] -> [c] const zipWith = (f, xs, ys) => { const lng = Math.min(length(xs), length(ys)), as = take(lng, xs), bs = take(lng, ys); return Array.from({ length: lng }, (_, i) => f(as[i], bs[i], i)); }; // MAIN --- return main(); })();
Least common multiple
JavaScript
Compute the least common multiple (LCM) of two integers. Given ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors. ;Example: The least common multiple of '''12''' and '''18''' is '''36''', because: :* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and :* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and :* there is no positive integer less than '''36''' that has both factors. As a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero. One way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''. If you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''. :::: \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)} One can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''. ;Related task :* greatest common divisor. ;See also: * MathWorld entry: Least Common Multiple. * Wikipedia entry: Least common multiple.
function LCM(A) // A is an integer array (e.g. [-50,25,-45,-18,90,447]) { var n = A.length, a = Math.abs(A[0]); for (var i = 1; i < n; i++) { var b = Math.abs(A[i]), c = a; while (a && b){ a > b ? a %= b : b %= a; } a = Math.abs(c*A[i])/(a+b); } return a; } /* For example: LCM([-50,25,-45,-18,90,447]) -> 67050 */
Least common multiple
JavaScript from Haskell
Compute the least common multiple (LCM) of two integers. Given ''m'' and ''n'', the least common multiple is the smallest positive integer that has both ''m'' and ''n'' as factors. ;Example: The least common multiple of '''12''' and '''18''' is '''36''', because: :* '''12''' is a factor ('''12''' x '''3''' = '''36'''), and :* '''18''' is a factor ('''18''' x '''2''' = '''36'''), and :* there is no positive integer less than '''36''' that has both factors. As a special case, if either ''m'' or ''n'' is zero, then the least common multiple is zero. One way to calculate the least common multiple is to iterate all the multiples of ''m'', until you find one that is also a multiple of ''n''. If you already have ''gcd'' for [[greatest common divisor]], then this formula calculates ''lcm''. :::: \operatorname{lcm}(m, n) = \frac{|m \times n|}{\operatorname{gcd}(m, n)} One can also find ''lcm'' by merging the [[prime decomposition]]s of both ''m'' and ''n''. ;Related task :* greatest common divisor. ;See also: * MathWorld entry: Least Common Multiple. * Wikipedia entry: Least common multiple.
(() => { 'use strict'; // gcd :: Integral a => a -> a -> a let gcd = (x, y) => { let _gcd = (a, b) => (b === 0 ? a : _gcd(b, a % b)), abs = Math.abs; return _gcd(abs(x), abs(y)); } // lcm :: Integral a => a -> a -> a let lcm = (x, y) => x === 0 || y === 0 ? 0 : Math.abs(Math.floor(x / gcd(x, y)) * y); // TEST return lcm(12, 18); })();
Levenshtein distance
JavaScript
{{Wikipedia}} In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. ;Example: The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits: ::# '''k'''itten '''s'''itten (substitution of 'k' with 's') ::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i') ::# sittin sittin'''g''' (insert 'g' at the end). ''The Levenshtein distance between "'''rosettacode'''", "'''raisethysword'''" is '''8'''. ''The distance between two strings is same as that when both strings are reversed.'' ;Task: Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between "kitten" and "sitting". ;Related task: * [[Longest common subsequence]]
function levenshtein(a, b) { var t = [], u, i, j, m = a.length, n = b.length; if (!m) { return n; } if (!n) { return m; } for (j = 0; j <= n; j++) { t[j] = j; } for (i = 1; i <= m; i++) { for (u = [i], j = 1; j <= n; j++) { u[j] = a[i - 1] === b[j - 1] ? t[j - 1] : Math.min(t[j - 1], t[j], u[j - 1]) + 1; } t = u; } return u[n]; } // tests [ ['', '', 0], ['yo', '', 2], ['', 'yo', 2], ['yo', 'yo', 0], ['tier', 'tor', 2], ['saturday', 'sunday', 3], ['mist', 'dist', 1], ['tier', 'tor', 2], ['kitten', 'sitting', 3], ['stop', 'tops', 2], ['rosettacode', 'raisethysword', 8], ['mississippi', 'swiss miss', 8] ].forEach(function(v) { var a = v[0], b = v[1], t = v[2], d = levenshtein(a, b); if (d !== t) { console.log('levenstein("' + a + '","' + b + '") was ' + d + ' should be ' + t); } });
Levenshtein distance
JavaScript from Haskell
{{Wikipedia}} In information theory and computer science, the '''Levenshtein distance''' is a edit distance). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character. ;Example: The Levenshtein distance between "'''kitten'''" and "'''sitting'''" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits: ::# '''k'''itten '''s'''itten (substitution of 'k' with 's') ::# sitt'''e'''n sitt'''i'''n (substitution of 'e' with 'i') ::# sittin sittin'''g''' (insert 'g' at the end). ''The Levenshtein distance between "'''rosettacode'''", "'''raisethysword'''" is '''8'''. ''The distance between two strings is same as that when both strings are reversed.'' ;Task: Implements a Levenshtein distance function, or uses a library function, to show the Levenshtein distance between "kitten" and "sitting". ;Related task: * [[Longest common subsequence]]
(() => { 'use strict'; // levenshtein :: String -> String -> Int const levenshtein = sa => sb => { const cs = chars(sa); const go = (ns, c) => { const calc = z => tpl => { const [c1, x, y] = Array.from(tpl); return minimum([ succ(y), succ(z), x + (c !== c1 ? 1 : 0) ]); }; const [n, ns1] = [ns[0], ns.slice(1)]; return scanl(calc)(succ(n))( zip3(cs)(ns)(ns1) ); }; return last( chars(sb).reduce( go, enumFromTo(0)(cs.length) ) ); }; // ----------------------- TEST ------------------------ const main = () => [ ["kitten", "sitting"], ["sitting", "kitten"], ["rosettacode", "raisethysword"], ["raisethysword", "rosettacode"] ].map(uncurry(levenshtein)); // ----------------- GENERIC FUNCTIONS ----------------- // Tuple (,) :: a -> b -> (a, b) const Tuple = a => b => ({ type: 'Tuple', '0': a, '1': b, length: 2 }); // TupleN :: a -> b ... -> (a, b ... ) function TupleN() { const args = Array.from(arguments), n = args.length; return 2 < n ? Object.assign( args.reduce((a, x, i) => Object.assign(a, { [i]: x }), { type: 'Tuple' + n.toString(), length: n }) ) : args.reduce((f, x) => f(x), Tuple); }; // chars :: String -> [Char] const chars = s => s.split(''); // enumFromTo :: Int -> Int -> [Int] const enumFromTo = m => n => Array.from({ length: 1 + n - m }, (_, i) => m + i); // last :: [a] -> a const last = xs => ( // The last item of a list. ys => 0 < ys.length ? ( ys.slice(-1)[0] ) : undefined )(xs); // minimum :: Ord a => [a] -> a const minimum = xs => ( // The least value of xs. ys => 0 < ys.length ? ( ys.slice(1) .reduce((a, y) => y < a ? y : a, ys[0]) ) : undefined )(xs); // length :: [a] -> Int const length = xs => // Returns Infinity over objects without finite // length. This enables zip and zipWith to choose // the shorter argument when one is non-finite, // like cycle, repeat etc 'GeneratorFunction' !== xs.constructor.constructor.name ? ( xs.length ) : Infinity; // scanl :: (b -> a -> b) -> b -> [a] -> [b] const scanl = f => startValue => xs => xs.reduce((a, x) => { const v = f(a[0])(x); return Tuple(v)(a[1].concat(v)); }, Tuple(startValue)([startValue]))[1]; // succ :: Enum a => a -> a const succ = x => 1 + x; // uncurry :: (a -> b -> c) -> ((a, b) -> c) const uncurry = f => // A function over a pair, derived // from a curried function. function () { const args = arguments, xy = Boolean(args.length % 2) ? ( args[0] ) : args; return f(xy[0])(xy[1]); }; // zip3 :: [a] -> [b] -> [c] -> [(a, b, c)] const zip3 = xs => ys => zs => xs .slice(0, Math.min(...[xs, ys, zs].map(length))) .map((x, i) => TupleN(x, ys[i], zs[i])); // MAIN --- return JSON.stringify(main()) })();
List rooted trees
Javascript
You came back from grocery shopping. After putting away all the goods, you are left with a pile of plastic bags, which you want to save for later use, so you take one bag and stuff all the others into it, and throw it under the sink. In doing so, you realize that there are various ways of nesting the bags, with all bags viewed as identical. If we use a matching pair of parentheses to represent a bag, the ways are: For 1 bag, there's one way: () <- a bag for 2 bags, there's one way: (()) <- one bag in another for 3 bags, there are two: ((())) <- 3 bags nested Russian doll style (()()) <- 2 bags side by side, inside the third for 4 bags, four: (()()()) ((())()) ((()())) (((()))) Note that because all bags are identical, the two 4-bag strings ((())()) and (()(())) represent the same configuration. It's easy to see that each configuration for ''n'' bags represents a ''n''-node rooted tree, where a bag is a tree node, and a bag with its content forms a subtree. The outermost bag is the tree root. Number of configurations for given ''n'' is given by OEIS A81. ;Task: Write a program that, when given ''n'', enumerates all ways of nesting ''n'' bags. You can use the parentheses notation above, or any tree representation that's unambiguous and preferably intuitive. This task asks for enumeration of trees only; for counting solutions without enumeration, that OEIS page lists various formulas, but that's not encouraged by this task, especially if implementing it would significantly increase code size. As an example output, run 5 bags. There should be 9 ways.
(() => { 'use strict'; const main = () => bagPatterns(5) .join('\n'); // BAG PATTERNS --------------------------------------- // bagPatterns :: Int -> [String] const bagPatterns = n => nub(map( composeList([ commasFromTree, depthSortedTree, treeFromParentIndices ]), parentIndexPermutations(n) )); // parentIndexPermutations :: Int -> [[Int]] const parentIndexPermutations = n => sequenceA( map(curry(enumFromToInt)(0), enumFromToInt(0, n - 2) ) ); // treeFromParentIndices :: [Int] -> Tree Int const treeFromParentIndices = pxs => { const go = (tree, tplIP) => Node( tree.root, tree.root === snd(tplIP) ? ( tree.nest.concat(Node(fst(tplIP)), []) ) : map(t => go(t, tplIP), tree.nest) ); return foldl( go, Node(0, []), zip(enumFromToInt(1, pxs.length), pxs) ); }; // Siblings sorted by descendant count // depthSortedTree :: Tree a -> Tree Int const depthSortedTree = t => { const go = tree => isNull(tree.nest) ? ( Node(0, []) ) : (() => { const xs = map(go, tree.nest); return Node( 1 + foldl((a, x) => a + x.root, 0, xs), sortBy(flip(comparing(x => x.root)), xs) ); })(); return go(t); }; // Serialisation of the tree structure // commasFromTree :: Tree a -> String const commasFromTree = tree => { const go = t => `(${concat(map(go, t.nest))})` return go(tree); }; // GENERIC FUNCTIONS -------------------------------------- // Node :: a -> [Tree a] -> Tree a const Node = (v, xs) => ({ type: 'Node', root: v, // any type of value (but must be consistent across tree) nest: xs || [] }); // Tuple (,) :: a -> b -> (a, b) const Tuple = (a, b) => ({ type: 'Tuple', '0': a, '1': b, length: 2 }); // comparing :: (a -> b) -> (a -> a -> Ordering) const comparing = f => (x, y) => { const a = f(x), b = f(y); return a < b ? -1 : (a > b ? 1 : 0); }; // composeList :: [(a -> a)] -> (a -> a) const composeList = fs => x => fs.reduceRight((a, f) => f(a), x, fs); // concat :: [[a]] -> [a] // concat :: [String] -> String const concat = xs => xs.length > 0 ? (() => { const unit = typeof xs[0] === 'string' ? '' : []; return unit.concat.apply(unit, xs); })() : []; // concatMap :: (a -> [b]) -> [a] -> [b] const concatMap = (f, xs) => [] .concat.apply( [], (Array.isArray(xs) ? ( xs ) : xs.split('')).map(f) ); // cons :: a -> [a] -> [a] const cons = (x, xs) => [x].concat(xs); // Flexibly handles two or more arguments, applying // the function directly if the argument array is complete, // or recursing with a concatenation of any existing and // newly supplied arguments, if gaps remain. // curry :: ((a, b) -> c) -> a -> b -> c const curry = (f, ...args) => { const go = xs => xs.length >= f.length ? ( f.apply(null, xs) ) : function() { return go(xs.concat(Array.from(arguments))); }; return go(args); }; // enumFromToInt :: Int -> Int -> [Int] const enumFromToInt = (m, n) => n >= m ? ( iterateUntil(x => x >= n, x => 1 + x, m) ) : []; // flip :: (a -> b -> c) -> b -> a -> c const flip = f => (a, b) => f.apply(null, [b, a]); // foldl :: (a -> b -> a) -> a -> [b] -> a const foldl = (f, a, xs) => xs.reduce(f, a); // fst :: (a, b) -> a const fst = tpl => tpl[0]; // isNull :: [a] -> Bool // isNull :: String -> Bool const isNull = xs => Array.isArray(xs) || typeof xs === 'string' ? ( xs.length < 1 ) : undefined; // iterateUntil :: (a -> Bool) -> (a -> a) -> a -> [a] const iterateUntil = (p, f, x) => { let vs = [x], h = x; while (!p(h))(h = f(h), vs.push(h)); return vs; }; // liftA2List :: (a -> b -> c) -> [a] -> [b] -> [c] const liftA2List = (f, xs, ys) => concatMap(x => concatMap(y => [f(x, y)], ys), xs); // map :: (a -> b) -> [a] -> [b] const map = (f, xs) => xs.map(f); // nub :: [a] -> [a] const nub = xs => nubBy((a, b) => a === b, xs); // nubBy :: (a -> a -> Bool) -> [a] -> [a] const nubBy = (p, xs) => { const go = xs => xs.length > 0 ? (() => { const x = xs[0]; return [x].concat( go(xs.slice(1) .filter(y => !p(x, y)) ) ) })() : []; return go(xs); }; // sequenceA :: (Applicative f, Traversable t) => t (f a) -> f (t a) const sequenceA = tfa => traverseList(x => x, tfa); // traverseList :: (Applicative f) => (a -> f b) -> [a] -> f [b] const traverseList = (f, xs) => { const lng = xs.length; return 0 < lng ? (() => { const vLast = f(xs[lng - 1]), t = vLast.type || 'List'; return xs.slice(0, -1).reduceRight( (ys, x) => liftA2List(cons, f(x), ys), liftA2List(cons, vLast, [[]]) ); })() : [ [] ]; }; // snd :: (a, b) -> b const snd = tpl => tpl[1]; // sortBy :: (a -> a -> Ordering) -> [a] -> [a] const sortBy = (f, xs) => xs.slice() .sort(f); // zip :: [a] -> [b] -> [(a, b)] const zip = (xs, ys) => xs.slice(0, Math.min(xs.length, ys.length)) .map((x, i) => Tuple(x, ys[i])); // MAIN --- return main() })();
Long year
JavaScript from TypeScript
Most years have 52 weeks, some have 53, according to ISO8601. ;Task: Write a function which determines if a given year is long (53 weeks) or not, and demonstrate it.
const isLongYear = (year) => { const jan1 = new Date(year, 0, 1); const dec31 = new Date(year, 11, 31); return (4 == jan1.getDay() || 4 == dec31.getDay()) } for (let y = 1995; y <= 2045; y++) { if (isLongYear(y)) { console.log(y) } }
Longest common subsequence
JavaScript from Java
'''Introduction''' Define a ''subsequence'' to be any output string obtained by deleting zero or more symbols from an input string. The '''Longest Common Subsequence''' ('''LCS''') is a subsequence of maximum length common to two or more strings. Let ''A'' ''A''[0]... ''A''[m - 1] and ''B'' ''B''[0]... ''B''[n - 1], m < n be strings drawn from an alphabet S of size s, containing every distinct symbol in A + B. An ordered pair (i, j) will be referred to as a match if ''A''[i] = ''B''[j], where 0 <= i < m and 0 <= j < n. The set of matches '''M''' defines a relation over matches: '''M'''[i, j] = (i, j) '''M'''. Define a ''non-strict'' product-order (<=) over ordered pairs, such that (i1, j1) <= (i2, j2) = i1 <= i2 and j1 <= j2. We define (>=) similarly. We say ordered pairs p1 and p2 are ''comparable'' if either p1 <= p2 or p1 >= p2 holds. If i1 < i2 and j2 < j1 (or i2 < i1 and j1 < j2) then neither p1 <= p2 nor p1 >= p2 are possible, and we say p1 and p2 are ''incomparable''. Define the ''strict'' product-order (<) over ordered pairs, such that (i1, j1) < (i2, j2) = i1 < i2 and j1 < j2. We define (>) similarly. A chain '''C''' is a subset of '''M''' consisting of at least one element m; and where either m1 < m2 or m1 > m2 for every pair of distinct elements m1 and m2. An antichain '''D''' is any subset of '''M''' in which every pair of distinct elements m1 and m2 are incomparable. A chain can be visualized as a strictly increasing curve that passes through matches (i, j) in the m*n coordinate space of '''M'''[i, j]. Every Common Sequence of length ''q'' corresponds to a chain of cardinality ''q'', over the set of matches '''M'''. Thus, finding an LCS can be restated as the problem of finding a chain of maximum cardinality ''p''. According to [Dilworth 1950], this cardinality ''p'' equals the minimum number of disjoint antichains into which '''M''' can be decomposed. Note that such a decomposition into the minimal number p of disjoint antichains may not be unique. '''Background''' Where the number of symbols appearing in matches is small relative to the length of the input strings, reuse of the symbols increases; and the number of matches will tend towards O(''m*n'') quadratic growth. This occurs, for example, in the Bioinformatics application of nucleotide and protein sequencing. The divide-and-conquer approach of [Hirschberg 1975] limits the space required to O(''n''). However, this approach requires O(''m*n'') time even in the best case. This quadratic time dependency may become prohibitive, given very long input strings. Thus, heuristics are often favored over optimal Dynamic Programming solutions. In the application of comparing file revisions, records from the input files form a large symbol space; and the number of symbols approaches the length of the LCS. In this case the number of matches reduces to linear, O(''n'') growth. A binary search optimization due to [Hunt and Szymanski 1977] can be applied to the basic Dynamic Programming approach, resulting in an expected performance of O(''n log m''). Performance can degrade to O(''m*n log m'') time in the worst case, as the number of matches grows to O(''m*n''). '''Note''' [Rick 2000] describes a linear-space algorithm with a time bound of O(''n*s + p*min(m, n - p)''). '''Legend''' A, B are input strings of lengths m, n respectively p is the length of the LCS M is the set of matches (i, j) such that A[i] = B[j] r is the magnitude of M s is the magnitude of the alphabet S of distinct symbols in A + B '''References''' [Dilworth 1950] "A decomposition theorem for partially ordered sets" by Robert P. Dilworth, published January 1950, Annals of Mathematics [Volume 51, Number 1, ''pp.'' 161-166] [Goeman and Clausen 2002] "A New Practical Linear Space Algorithm for the Longest Common Subsequence Problem" by Heiko Goeman and Michael Clausen, published 2002, Kybernetika [Volume 38, Issue 1, ''pp.'' 45-66] [Hirschberg 1975] "A linear space algorithm for computing maximal common subsequences" by Daniel S. Hirschberg, published June 1975 Communications of the ACM [Volume 18, Number 6, ''pp.'' 341-343] [Hunt and McIlroy 1976] "An Algorithm for Differential File Comparison" by James W. Hunt and M. Douglas McIlroy, June 1976 Computing Science Technical Report, Bell Laboratories 41 [Hunt and Szymanski 1977] "A Fast Algorithm for Computing Longest Common Subsequences" by James W. Hunt and Thomas G. Szymanski, published May 1977 Communications of the ACM [Volume 20, Number 5, ''pp.'' 350-353] [Rick 2000] "Simple and fast linear space computation of longest common subsequences" by Claus Rick, received 17 March 2000, Information Processing Letters, Elsevier Science [Volume 75, ''pp.'' 275-281] '''Examples''' The sequences "1234" and "1224533324" have an LCS of "1234": '''1234''' '''12'''245'''3'''332'''4''' For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest": '''t'''hi'''si'''sa'''test''' '''t'''e'''s'''t'''i'''ng123'''test'''ing In this puzzle, your code only needs to deal with strings. Write a function which returns an LCS of two strings (case-sensitive). You don't need to show multiple LCS's. For more information on this problem please see Wikipedia.
function lcs_greedy(x,y){ var p1, i, idx, symbols = {}, r = 0, p = 0, l = 0, m = x.length, n = y.length, s = new Buffer((m < n) ? n : m); p1 = popsym(0); for (i = 0; i < m; i++) { p = (r === p) ? p1 : popsym(i); p1 = popsym(i + 1); if (p > p1) { i += 1; idx = p1; } else { idx = p; } if (idx === n) { p = popsym(i); } else { r = idx; s[l] = x.charCodeAt(i); l += 1; } } return s.toString('utf8', 0, l); function popsym(index) { var s = x[index], pos = symbols[s] + 1; pos = y.indexOf(s, ((pos > r) ? pos : r)); if (pos === -1) { pos = n; } symbols[s] = pos; return pos; } }
Longest common substring
JavaScript from Haskell
Write a function that returns the longest common substring of two strings. Use it within a program that demonstrates sample output from the function, which will consist of the longest common substring between "thisisatest" and "testing123testing". Note that substrings are consecutive characters within a string. This distinguishes them from subsequences, which is any sequence of characters within a string, even if there are extraneous characters in between them. Hence, the [[longest common subsequence]] between "thisisatest" and "testing123testing" is "tsitest", whereas the longest common sub''string'' is just "test". ;References: *Generalize Suffix Tree *[[Ukkonen's Suffix Tree Construction]]
(() => { 'use strict'; // longestCommon :: String -> String -> String const longestCommon = (s1, s2) => maximumBy( comparing(length), intersect(...apList( [s => map( concat, concatMap(tails, compose(tail, inits)(s)) )], [s1, s2] )) ); // main :: IO () const main = () => console.log( longestCommon( "testing123testing", "thisisatest" ) ); // GENERIC FUNCTIONS ---------------------------- // Each member of a list of functions applied to each // of a list of arguments, deriving a list of new values. // apList (<*>) :: [(a -> b)] -> [a] -> [b] const apList = (fs, xs) => // fs.reduce((a, f) => a.concat( xs.reduce((a, x) => a.concat([f(x)]), []) ), []); // comparing :: (a -> b) -> (a -> a -> Ordering) const comparing = f => (x, y) => { const a = f(x), b = f(y); return a < b ? -1 : (a > b ? 1 : 0); }; // compose (<<<) :: (b -> c) -> (a -> b) -> a -> c const compose = (f, g) => x => f(g(x)); // concat :: [[a]] -> [a] // concat :: [String] -> String const concat = xs => 0 < xs.length ? (() => { const unit = 'string' !== typeof xs[0] ? ( [] ) : ''; return unit.concat.apply(unit, xs); })() : []; // concatMap :: (a -> [b]) -> [a] -> [b] const concatMap = (f, xs) => xs.reduce((a, x) => a.concat(f(x)), []); // inits([1, 2, 3]) -> [[], [1], [1, 2], [1, 2, 3] // inits('abc') -> ["", "a", "ab", "abc"] // inits :: [a] -> [[a]] // inits :: String -> [String] const inits = xs => [ [] ] .concat(('string' === typeof xs ? xs.split('') : xs) .map((_, i, lst) => lst.slice(0, i + 1))); // intersect :: (Eq a) => [a] -> [a] -> [a] const intersect = (xs, ys) => xs.filter(x => -1 !== ys.indexOf(x)); // Returns Infinity over objects without finite length. // This enables zip and zipWith to choose the shorter // argument when one is non-finite, like cycle, repeat etc // length :: [a] -> Int const length = xs => (Array.isArray(xs) || 'string' === typeof xs) ? ( xs.length ) : Infinity; // map :: (a -> b) -> [a] -> [b] const map = (f, xs) => xs.map(f); // maximumBy :: (a -> a -> Ordering) -> [a] -> a const maximumBy = (f, xs) => 0 < xs.length ? ( xs.slice(1) .reduce((a, x) => 0 < f(x, a) ? x : a, xs[0]) ) : undefined; // tail :: [a] -> [a] const tail = xs => 0 < xs.length ? xs.slice(1) : []; // tails :: [a] -> [[a]] const tails = xs => { const es = ('string' === typeof xs) ? ( xs.split('') ) : xs; return es.map((_, i) => es.slice(i)) .concat([ [] ]); }; // MAIN --- return main(); })();
Longest increasing subsequence
JavaScript
Calculate and show here a longest increasing subsequence of the list: :\{3, 2, 6, 4, 5, 1\} And of the list: :\{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15\} Note that a list may have more than one subsequence that is of the maximum length. ;Ref: # Dynamic Programming #1: Longest Increasing Subsequence on YouTube # An efficient solution can be based on Patience sorting.
function getLis(input) { if (input.length === 0) { return []; } var lisLenPerIndex = []; let max = { index: 0, length: 1 }; for (var i = 0; i < input.length; i++) { lisLenPerIndex[i] = 1; for (var j = i - 1; j >= 0; j--) { if (input[i] > input[j] && lisLenPerIndex[j] >= lisLenPerIndex[i]) { var length = lisLenPerIndex[i] = lisLenPerIndex[j] + 1; if (length > max.length) { max = { index: i, length }; } } } } var lis = [input[max.index]]; for (var i = max.index; i >= 0 && max.length !== 0; i--) { if (input[max.index] > input[i] && lisLenPerIndex[i] === max.length - 1) { lis.unshift(input[i]); max.length--; } } return lis; } console.log(getLongestIncreasingSubsequence([0, 7, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15])); console.log(getLongestIncreasingSubsequence([3, 2, 6, 4, 5, 1]));
Lucky and even lucky numbers
JavaScript
Note that in the following explanation list indices are assumed to start at ''one''. ;Definition of lucky numbers ''Lucky numbers'' are positive integers that are formed by: # Form a list of all the positive odd integers > 01, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39 ... # Return the first number from the list (which is '''1'''). # (Loop begins here) #* Note then return the second number from the list (which is '''3'''). #* Discard every third, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33, 37, 39, 43, 45, 49, 51, 55, 57 ... # (Expanding the loop a few more times...) #* Note then return the third number from the list (which is '''7'''). #* Discard every 7th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 27, 31, 33, 37, 43, 45, 49, 51, 55, 57, 63, 67 ... #* Note then return the 4th number from the list (which is '''9'''). #* Discard every 9th, (as noted), number from the list to form the new list1, 3, 7, 9, 13, 15, 21, 25, 31, 33, 37, 43, 45, 49, 51, 55, 63, 67, 69, 73 ... #* Take the 5th, i.e. '''13'''. Remove every 13th. #* Take the 6th, i.e. '''15'''. Remove every 15th. #* Take the 7th, i.e. '''21'''. Remove every 21th. #* Take the 8th, i.e. '''25'''. Remove every 25th. # (Rule for the loop) #* Note the nth, which is m. #* Remove every mth. #* Increment n. ;Definition of even lucky numbers This follows the same rules as the definition of lucky numbers above ''except for the very first step'': # Form a list of all the positive '''even''' integers > 02, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40 ... # Return the first number from the list (which is '''2'''). # (Loop begins here) #* Note then return the second number from the list (which is '''4'''). #* Discard every 4th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 14, 18, 20, 22, 26, 28, 30, 34, 36, 38, 42, 44, 46, 50, 52 ... # (Expanding the loop a few more times...) #* Note then return the third number from the list (which is '''6'''). #* Discard every 6th, (as noted), number from the list to form the new list2, 4, 6, 10, 12, 18, 20, 22, 26, 28, 34, 36, 38, 42, 44, 50, 52, 54, 58, 60 ... #* Take the 4th, i.e. '''10'''. Remove every 10th. #* Take the 5th, i.e. '''12'''. Remove every 12th. # (Rule for the loop) #* Note the nth, which is m. #* Remove every mth. #* Increment n. ;Task requirements * Write one or two subroutines (functions) to generate ''lucky numbers'' and ''even lucky numbers'' * Write a command-line interface to allow selection of which kind of numbers and which number(s). Since input is from the command line, tests should be made for the common errors: ** missing arguments ** too many arguments ** number (or numbers) aren't legal ** misspelled argument ('''lucky''' or '''evenLucky''') * The command line handling should: ** support mixed case handling of the (non-numeric) arguments ** support printing a particular number ** support printing a range of numbers by their index ** support printing a range of numbers by their values * The resulting list of numbers should be printed on a single line. The program should support the arguments: what is displayed (on a single line) argument(s) (optional verbiage is encouraged) +-------------------+----------------------------------------------------+ | j | Jth lucky number | | j , lucky | Jth lucky number | | j , evenLucky | Jth even lucky number | | | | | j k | Jth through Kth (inclusive) lucky numbers | | j k lucky | Jth through Kth (inclusive) lucky numbers | | j k evenLucky | Jth through Kth (inclusive) even lucky numbers | | | | | j -k | all lucky numbers in the range j --> |k| | | j -k lucky | all lucky numbers in the range j --> |k| | | j -k evenLucky | all even lucky numbers in the range j --> |k| | +-------------------+----------------------------------------------------+ where |k| is the absolute value of k Demonstrate the program by: * showing the first twenty ''lucky'' numbers * showing the first twenty ''even lucky'' numbers * showing all ''lucky'' numbers between 6,000 and 6,100 (inclusive) * showing all ''even lucky'' numbers in the same range as above * showing the 10,000th ''lucky'' number (extra credit) * showing the 10,000th ''even lucky'' number (extra credit) ;See also: * This task is related to the [[Sieve of Eratosthenes]] task. * OEIS Wiki Lucky numbers. * Sequence A000959 lucky numbers on The On-Line Encyclopedia of Integer Sequences. * Sequence A045954 even lucky numbers or ELN on The On-Line Encyclopedia of Integer Sequences. * Entry lucky numbers on The Eric Weisstein's World of Mathematics.
function luckyNumbers(opts={}) { /**************************************************************************\ | OPTIONS | |**************************************************************************| | even ...... boolean ............. return even/uneven numbers | | (default: false) | | | | nth ....... number ............... return nth number | | | | through ... number ............... return numbers from #1 to number | | OR array[from, to] ... return numbers on index | | from array[from] to array[to] | | | | range ..... array[from, to] ...... return numbers between from and to | \**************************************************************************/ opts.even = opts.even || false; if (typeof opts.through == 'number') opts.through = [0, opts.through]; let out = [], x = opts.even ? 2 : 1, max = opts.range ? opts.range[1] * 3 : opts.through ? opts.through[1] * 12 : opts.nth ? opts.nth * 15 : 2000; for (x; x <= max; x = x+2) out.push(x); // fill for (x = 1; x < Math.floor(out.length / 2); x++) { // sieve let i = out.length; while (i--) (i+1) % out[x] == 0 && out.splice(i, 1); } if (opts.nth) return out[opts.nth-1]; if (opts.through) return out.slice(opts.through[0], opts.through[1]); if (opts.range) return out.filter(function(val) { return val >= opts.range[0] && val <= opts.range[1]; }); return out; } /* TESTING */ // blank console.log( luckyNumbers() ); // showing the first twenty lucky numbers console.log( luckyNumbers({through: 20}) ); // showing the first twenty even lucky numbers console.log( luckyNumbers({even: true, through: 20}) ); // showing all lucky numbers between 6,000 and 6,100 (inclusive) console.log( luckyNumbers({range: [6000, 6100]}) ); // showing all even lucky numbers in the same range as above console.log( luckyNumbers({even: true, range: [6000, 6100]}) ); // showing the 10,000th lucky number (extra credit) console.log( luckyNumbers({nth: 10000}) ); // showing the 10,000th even lucky number (extra credit) console.log( luckyNumbers({even: true, nth: 10000}) );
MAC vendor lookup
Javascript
Every connected device around the world comes with a unique Media Access Control address, or a MAC address. A common task a network administrator may come across is being able to identify a network device's manufacturer when given only a MAC address. ;Task: Interface with one (or numerous) APIs that exist on the internet and retrieve the device manufacturer based on a supplied MAC address. A MAC address that does not return a valid result should return the String "N/A". An error related to the network connectivity or the API should return a null result. Many implementations on this page use http://api.macvendors.com/ which, as of 19th September 2021, is throttling requests. After only 2 calls, the following response is returned for all subsequent requests. If you are planning to use the same provider or going to run the examples on this page, consider building in a delay between two calls. '''{"errors":{"detail":"Too Many Requests","message":"Please slow down your requests or upgrade your plan at https://macvendors.com"}}'''
var mac = "88:53:2E:67:07:BE"; function findmac(){ window.open("http://api.macvendors.com/" + mac); } findmac();
MD4
JavaScript
Find the MD4 message digest of a string of [[octet]]s. Use the ASCII encoded string "Rosetta Code" (without quotes). You may either call an MD4 library, or implement MD4 in your language. '''MD4''' is an obsolete hash function that computes a 128-bit message digest that sometimes appears in obsolete protocols. RFC 1320 specifies the MD4 algorithm. RFC 6150 declares that MD4 is obsolete.
const md4func = () => { const hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */ const b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */ const chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */ const tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef"; /** * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ const safe_add = (x, y) => { const lsw = (x & 0xFFFF) + (y & 0xFFFF); const msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); }; /** * Bitwise rotate a 32-bit number to the left. */ const rol = (num, cnt) => (num << cnt) | (num >>> (32 - cnt)); /** * Convert a string to an array of little-endian words * If chrsz is ASCII, characters >255 have their hi-byte silently ignored. */ const str2binl = str => { const bin = Array(); const mask = (1 << chrsz) - 1; for (let i = 0; i < str.length * chrsz; i += chrsz) bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32); return bin; }; /** * Convert an array of little-endian words to a string */ const binl2str = bin => { let str = ""; const mask = (1 << chrsz) - 1; for (let i = 0; i < bin.length * 32; i += chrsz) str += String.fromCharCode((bin[i >> 5] >>> (i % 32)) & mask); return str; }; /** * Convert an array of little-endian words to a hex string. */ const binl2hex = binarray => { let str = ""; for (let i = 0; i < binarray.length * 4; i++) { str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF); } return str; }; /** * Convert an array of little-endian words to a base-64 string */ const binl2b64 = binarray => { let str = ""; for (let i = 0; i < binarray.length * 4; i += 3) { const triplet = (((binarray[i >> 2] >> 8 * (i % 4)) & 0xFF) << 16) | (((binarray[i + 1 >> 2] >> 8 * ((i + 1) % 4)) & 0xFF) << 8) | ((binarray[i + 2 >> 2] >> 8 * ((i + 2) % 4)) & 0xFF); for (let j = 0; j < 4; j++) { if (i * 8 + j * 6 > binarray.length * 32) str += b64pad; else str += tab.charAt((triplet >> 6 * (3 - j)) & 0x3F); } } return str; }; /** * Calculate the MD4 of an array of little-endian words, and a bit length */ const core_md4 = (x, len) => { x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; let a = 1732584193; let b = -271733879; let c = -1732584194; let d = 271733878; for (let i = 0; i < x.length; i += 16) { const olda = a; const oldb = b; const oldc = c; const oldd = d; a = md4_ff(a, b, c, d, x[i], 3); d = md4_ff(d, a, b, c, x[i + 1], 7); c = md4_ff(c, d, a, b, x[i + 2], 11); b = md4_ff(b, c, d, a, x[i + 3], 19); a = md4_ff(a, b, c, d, x[i + 4], 3); d = md4_ff(d, a, b, c, x[i + 5], 7); c = md4_ff(c, d, a, b, x[i + 6], 11); b = md4_ff(b, c, d, a, x[i + 7], 19); a = md4_ff(a, b, c, d, x[i + 8], 3); d = md4_ff(d, a, b, c, x[i + 9], 7); c = md4_ff(c, d, a, b, x[i + 10], 11); b = md4_ff(b, c, d, a, x[i + 11], 19); a = md4_ff(a, b, c, d, x[i + 12], 3); d = md4_ff(d, a, b, c, x[i + 13], 7); c = md4_ff(c, d, a, b, x[i + 14], 11); b = md4_ff(b, c, d, a, x[i + 15], 19); a = md4_gg(a, b, c, d, x[i], 3); d = md4_gg(d, a, b, c, x[i + 4], 5); c = md4_gg(c, d, a, b, x[i + 8], 9); b = md4_gg(b, c, d, a, x[i + 12], 13); a = md4_gg(a, b, c, d, x[i + 1], 3); d = md4_gg(d, a, b, c, x[i + 5], 5); c = md4_gg(c, d, a, b, x[i + 9], 9); b = md4_gg(b, c, d, a, x[i + 13], 13); a = md4_gg(a, b, c, d, x[i + 2], 3); d = md4_gg(d, a, b, c, x[i + 6], 5); c = md4_gg(c, d, a, b, x[i + 10], 9); b = md4_gg(b, c, d, a, x[i + 14], 13); a = md4_gg(a, b, c, d, x[i + 3], 3); d = md4_gg(d, a, b, c, x[i + 7], 5); c = md4_gg(c, d, a, b, x[i + 11], 9); b = md4_gg(b, c, d, a, x[i + 15], 13); a = md4_hh(a, b, c, d, x[i], 3); d = md4_hh(d, a, b, c, x[i + 8], 9); c = md4_hh(c, d, a, b, x[i + 4], 11); b = md4_hh(b, c, d, a, x[i + 12], 15); a = md4_hh(a, b, c, d, x[i + 2], 3); d = md4_hh(d, a, b, c, x[i + 10], 9); c = md4_hh(c, d, a, b, x[i + 6], 11); b = md4_hh(b, c, d, a, x[i + 14], 15); a = md4_hh(a, b, c, d, x[i + 1], 3); d = md4_hh(d, a, b, c, x[i + 9], 9); c = md4_hh(c, d, a, b, x[i + 5], 11); b = md4_hh(b, c, d, a, x[i + 13], 15); a = md4_hh(a, b, c, d, x[i + 3], 3); d = md4_hh(d, a, b, c, x[i + 11], 9); c = md4_hh(c, d, a, b, x[i + 7], 11); b = md4_hh(b, c, d, a, x[i + 15], 15); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return Array(a, b, c, d); }; /** * These functions implement the basic operation for each round of the * algorithm. */ const md4_cmn = (q, a, b, x, s, t) => safe_add( rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); const md4_ff = (a, b, c, d, x, s) => md4_cmn( (b & c) | ((~b) & d), a, 0, x, s, 0); const md4_gg = (a, b, c, d, x, s) => md4_cmn( (b & c) | (b & d) | (c & d), a, 0, x, s, 1518500249); const md4_hh = (a, b, c, d, x, s) => md4_cmn( b ^ c ^ d, a, 0, x, s, 1859775393); /** * Calculate the HMAC-MD4, of a key and some data */ const core_hmac_md4 = (key, data) => { let bkey = str2binl(key); if (bkey.length > 16) { bkey = core_md4(bkey, key.length * chrsz) } const ipad = Array(16); const opad = Array(16); for (let i = 0; i < 16; i++) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } const hash = core_md4( ipad.concat(str2binl(data)), 512 + data.length * chrsz); return core_md4(opad.concat(hash), 512 + 128); }; /** * These are the functions you'll usually want to call */ return { hex_md4: s => binl2hex(core_md4(str2binl(s), s.length * chrsz)), b64_md4: s => binl2b64(core_md4(str2binl(s), s.length * chrsz)), str_md4: s => binl2str(core_md4(str2binl(s), s.length * chrsz)), hex_hmac_md4: (key, data) => binl2hex(core_hmac_md4(key, data)), b64_hmac_md4: (key, data) => binl2b64(core_hmac_md4(key, data)), str_hmac_md4: (key, data) => binl2str(core_hmac_md4(key, data)), }; }; const md4 = md4func(); console.log(md4.hex_md4('Rosetta Code'));
Magic 8-ball
JavaScript
Create Magic 8-Ball. See details at: Magic 8-Ball.
//console var answers = [ "It is certain", "It is decidedly so", "Without a doubt", "Yes, definitely", "You may rely on it", "As I see it, yes", "Most likely", "Outlook good", "Signs point to yes", "Yes", "Reply hazy, try again", "Ask again later", "Better not tell you now", "Cannot predict now", "Concentrate and ask again", "Don't bet on it", "My reply is no", "My sources say no", "Outlook not so good", "Very doubtful"]) console.log("ASK ANY QUESTION TO THE MAGIC 8-BALL AND YOU SHALL RECEIVE AN ANSWER!") for(;;){ var answer = prompt("question:") console.log(answer) console.log(answers[Math.floor(Math.random()*answers.length)]); }