Skip to content

Instantly share code, notes, and snippets.

@rndomhack
Created May 11, 2015 18:36
Show Gist options
  • Save rndomhack/da73fafa345ca4bc9ccd to your computer and use it in GitHub Desktop.
Save rndomhack/da73fafa345ca4bc9ccd to your computer and use it in GitHub Desktop.
I am NOT programmer.
// Q.1
// for loop
function sumForLoop(arr) {
var ret = 0;
for (let i = 0; i < arr.length; ++i) {
ret += arr[i];
}
return ret;
}
// while loop
function sumWhileLoop(arr) {
var ret = 0, i = 0;
while (i < arr.length) {
ret += arr[i];
++i;
}
return ret;
}
// recursive loop
function sumRecursiveLoop(arr, i) {
i = i === void(0) ? 0 : ++i;
var ret = arr[i];
if (arr.length) return ret;
return ret + sumRecursiveLoop(arr, i);
}
// Q.2
function concatList(arr1, arr2) {
var arr = [];
var length = Math.max(arr1.length, arr2.length);
for(let i = 0; i < length; ++i) {
if (i < arr1.length) arr.push(arr1[i]);
if (i < arr2.length) arr.push(arr2[i]);
}
return arr;
}
// Q.3
function fibonacci(arr) {
if (arr === void(0)) arr = [0, 1];
if (arr.length === 100) return arr;
arr.push(arr[arr.length - 2] + arr[arr.length - 1]);
return fibonacci(arr);
}
// Q.4
function sortMax(arr) {
arr = arr.slice();
arr.sort(function(a, b) {
return Math.pow(b, Math.floor(Math.log(a) / Math.LN10) + 1) - Math.pow(a, Math.floor(Math.log(b) / Math.LN10) + 1);
});
return parseInt(arr.join(""));
}
// Q.5
function sumHundred() {
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var times = Math.pow(3, arr.length - 1);
for(let i = 0; i < times; ++i) {
let number = 0,
status = ("0".repeat(arr.length) + i.toString(3)).slice(1 - arr.length).split("");
for(let j = 0, prev = 0; j < arr.length; j++) {
let sign = status[j - 1] === "2" ? -1 : 1,
prevSign = prev < 0 ? -1 : 1,
pre = prev === 0 ? arr[j] * sign : (Math.abs(prev) + arr[j]) * prevSign;
if (status[j] === "0") {
prev = pre * 10;
continue;
}
number += pre;
prev = 0;
}
if (number === 100) {
let ans = "";
arr.forEach((value, index) => {
ans += value;
if (index < status.length) ans += ["", " + ", " - "][parseInt(status[index])];
});
console.log(ans);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment