Skip to content

Instantly share code, notes, and snippets.

@indutny
Last active July 19, 2017 07:57
Show Gist options
  • Save indutny/33c760e00926d72f53fb59e0a8a9a888 to your computer and use it in GitHub Desktop.
Save indutny/33c760e00926d72f53fb59e0a8a9a888 to your computer and use it in GitHub Desktop.
'use strict';
// Quiz:
//
// Implement `solution` function using only calls to API methods below and no
// other JS primitives (even math).
//
// Correct implementation will print "Success!" once executed
//
function solution(initial) {
return initial;
}
check(solution([ [ +1, 1, 2, 3, 4 ], [ -1, 3, 4, 1, 2 ] ]));
//
// API
//
// Example:
//
// join([ [ +1, 1, 2, 3, 4] , [ +1, 4, 3, 2, 1 ] ],
// [ [ -1, 1, 2, 3, 4] ])
//
// Result:
//
// [ [ +1, 4, 3, 2, 1 ] ]
//
function join(a, b) {
const res = a.concat(b);
res.sort((a, b) => {
for (let i = 1; i <= 4; i++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
return a[0] - b[0];
});
return res.reduce((acc, curr) => {
if (acc.length === 0)
return [ curr ];
const last = acc[acc.length - 1];
const same = last.slice(1).every((val, i) => {
return val === curr[i + 1];
});
if (!same)
return acc.concat([ curr ]);
last[0] += curr[0];
return acc;
}, []).filter(item => item[0] !== 0);
}
// Replace +1234 at `at` with:
// -1342 -1423
function b(arr, at) {
const res = [];
arr.forEach((item, i) => {
if (at !== undefined && i !== at)
return res.push(item);
res.push(
[ -item[0], item[1], item[3], item[4], item[2] ],
[ -item[0], item[1], item[4], item[2], item[3] ]
);
});
return join([], res);
}
// Replace +1234 at `at` with:
// -2134
function s1(arr, at) {
return join([], arr.map((item, i) => {
if (at !== undefined && i !== at)
return item;
return [ -item[0], item[2], item[1], item[3], item[4] ];
}));
}
// Replace +1234 at `at` with:
// -1243
function s2(arr, at) {
return join([], arr.map((item, i) => {
if (at !== undefined && i !== at)
return item;
return [ -item[0], item[1], item[2], item[4], item[3] ];
}));
}
// Swap `i` with `j` in all numbers
function swap(arr, i, j) {
return arr.map((item) => {
return [ item[0] ].concat(item.slice(1).map((value) => {
if (value === i)
return j;
else if (value === j)
return i;
else
return value;
}));
});
}
function inspect(arr) {
console.log(arr.map((item) => {
const multiplier = item[0];
const prefix = multiplier === 1 ? '+' :
multiplier === -1 ? '-' :
multiplier.toString() + ' * ';
return prefix + item.slice(1).join('');
}).join(' '));
}
function check(arr) {
if (arr.length === 0)
return console.log('Success!');
inspect(arr);
throw new Error('Solution incomplete, must return empty array');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment