Skip to content

Instantly share code, notes, and snippets.

@kageurufu
Created May 8, 2015 21:57
Show Gist options
  • Save kageurufu/be74075ac46f09a2a432 to your computer and use it in GitHub Desktop.
Save kageurufu/be74075ac46f09a2a432 to your computer and use it in GitHub Desktop.
// Problem 1
function forSum(arr) {
var sum = 0, i;
for(i = 0; i < arr.length; arr++) {
sum += arr[i];
}
return sum
}
function whileSum(arr) {
var sum = 0, i = arr.length;
while (i--) sum += arr[i];
return sum
}
function recSum(arr, i) {
i = i === undefined ? 0 : i;
return arr[i] + recSum(arr, i + 1);
}
// Problem 2
function joinArr(a1, a2) {
if(a1.length !== a2.length) throw 'Arrays must be same length';
var na = [];
for(var i = 0; i < a1.length; i++) {
na.push(a1[i]);
na.push(a2[i]);
}
return na;
}
// Problem 3
function fib(n) {
var a = 0,
b = 1,
z = 0,
fiba = [];
for(var i = 0; i < n; i ++) {
fiba.push(a);
z = a;
a += b;
b = z;
}
return fiba;
}
// Problem 4
function biggestPossibleNumber(arr) {
return parseInt(arr
.map(function(c) { return c.toString(); })
.sort().reverse()
.reduce(function(p, c) { return p + "" + c; }));
}
// Problem 5
function sumTo100() {
var v = ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
ops = ['', '-', '+'],
i = 0; //Bitmask, 00 00 00 00 00 00 00 00
// Each bit pair, in dec, is the index of the op between n and n+1
// 00 - ''
// 01 - '-'
// 10 - '+'
// 11 - skip somehow?
function pad(s) {
while(s.length < 8) {
s = "0" + s;
}
return s;
}
function op(bitmask, pair) {
val = pad(bitmask.toString(3))[pair];
return ops[val];
}
while(i.toString(3).length <= 8) {
//We still have combos to try
// 1 o1 2 .. o8 9
var calc = '';
for(var h = 0; h < 8; h++) {
calc += v[h] + op(i, h);
}
calc += v[8];
if(eval(calc) === 100) console.log(calc);
i++;
}
}
sumTo100()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment