Skip to content

Instantly share code, notes, and snippets.

@micromaomao
Created June 2, 2019 03:03
Show Gist options
  • Save micromaomao/b249ed0603b1f0d69935d054ed59ac08 to your computer and use it in GitHub Desktop.
Save micromaomao/b249ed0603b1f0d69935d054ed59ac08 to your computer and use it in GitHub Desktop.
/*
* Problem 1
*
* Write three functions that compute the sum of the numbers in a given list using a for-loop, a while-loop, and recursion.
*/
/**
* Sum a integer list using `for`.
* @param list array list to sum
* @return the sum.
*/
function sum_for(list) {
if (!Array.isArray(list)) {
throw new Error("list is not a array.");
}
var sum = 0;
for (var i = 0; i < list.length; i ++) {
var num = list[i];
if (typeof num != "number" || parseInt(num) != num) {
throw new Error("list[" + pos + "] is not a integer.");
}
sum += num;
}
return sum;
}
/**
* Sum a integer list using `while`.
* @param list array list to sum
* @return the sum.
*/
function sum_while(list) {
if (!Array.isArray(list)) {
throw new Error("list is not a array.");
}
var sum = 0, i = 0;
while (i < list.length) {
var num = list[i];
if (typeof num != "number" || parseInt(num) != num) {
throw new Error("list[" + pos + "] is not a integer.");
}
sum += num;
i ++;
}
return sum;
}
/**
* Sum a integer list recursively.
* @param list array list to sum
* @param pos integer starting position, default 0
* @return the sum.
*/
function sum_rec(list, pos) {
if (typeof pos == "undefined")
pos = 0;
if (!Array.isArray(list)) {
throw new Error("list is not a array.");
}
if (typeof pos != "number" || pos < 0) {
throw new Error("pos invalid.");
}
if (list.length == 0) {
return 0;
}
if (pos >= list.length) {
throw new Error("pos index out of range.");
}
if (typeof list[pos] != "number" || parseInt(list[pos]) != list[pos]) {
throw new Error("list[" + pos + "] is not a integer.");
}
if (pos == list.length - 1) {
return list[pos];
}
return sum_rec(list, pos + 1) + list[pos];
}
/**
* Test for a function that sum a list of integer.
* @param sumFunc function the function to test
* @param successful function callback when test is successfully finished. ( without any error. )
* @param failed function callback when there is any error. The function will get the list of error
* as it's first argument, and put `successful` as it's second argument.
*/
function test(sumFunc, successful, failed) {
var errors = [];
function assert(bool, errMsg) {
if (!bool) {
errors.push(new Error(errMsg));
}
}
assert(sumFunc([0]) == 0);
assert(sumFunc([]) == 0);
assert(sumFunc([-1]) == -1);
assert(sumFunc([1]) == 1);
assert(sumFunc([1, 2, -2]) == 1);
function tryError() {
assert(false, "Didn't throw error when the array contains non-integer.");
}
try {
sumFunc(["not integer"]);
tryError();
} catch (e) {}
try {
sumFunc([8, 0.2]);
tryError();
} catch (e) {}
try {
sumFunc(20);
assert(false, "Didn't throw error when the first argument isn't a array.");
} catch (e) {}
try {
sumFunc();
assert(false, "Didn't throw error when there is no first argument.");
} catch (e) {}
if (errors.length > 0) {
failed(errors, successful);
} else {
successful();
}
}
function onError(errors, cont) {
errors.forEach(function (e) { console.error(e); });
cont();
}
test(sum_for, function () {
test(sum_while, function () {
test(sum_rec, function () {
console.log("All test successfully finished.");
}, onError);
}, onError);
}, onError)
/*
* Problem 2
*
* Write a function that combines two lists by alternatingly taking elements. For example: given the
* two lists [a, b, c] and [1, 2, 3], the function should return [a, 1, b, 2, c, 3].
*/
/**
* a function that combines two lists by alternatingly taking elements.
* @param a array the first list
* @param b array the second list
*/
function altJoin(a, b) {
if (!Array.isArray(a) || !Array.isArray(b)) {
throw new Error("Both a and b must be a Array.");
}
var result = [];
for (var i = 0; i < a.length; i ++) {
result.push(a[i]);
if (i < b.length)
result.push(b[i]);
}
for (; i < b.length; i ++) {
result.push(b[i]);
}
return result;
}
/**
* Test for a function that combines two lists by alternatingly taking elements.
* @param func function the function to test
* @param successful function callback when test is successfully finished. ( without any error. )
* @param failed function callback when there is any error. The function will get the list of error
* as it's first argument, and put `successful` as it's second argument.
*/
function test(func, successful, failed) {
var errors = [];
Array.prototype.equalsTo = function (b) {
if (this === b) return true;
if (!Array.isArray(b)) return false;
if (b.length != this.length) return false;
for (var i = 0; i < b.length; i ++) {
if (this[i] !== b[i]) {
return false;
}
}
return true;
}
function assert(bool, errMsg) {
if (!bool) {
errors.push(new Error(errMsg));
}
}
var a = 0, b = 1, c = 2, d = 3;
assert(func([] , [] ).equalsTo([]));
debugger;
assert(func([a], [] ).equalsTo([a]));
assert(func([] , [b]).equalsTo([b]));
assert(func([a], [b]).equalsTo([a, b]));
assert(func([b], [a]).equalsTo([b, a]));
assert(func([], [a, b]).equalsTo([a, b]));
assert(func([a, b], [c, d]).equalsTo([a, c, b, d]));
assert(func([a], [b, c, d]).equalsTo([a, b, c, d]));
assert(func([a, b], [c]).equalsTo([a, c, b]));
assert(func([c], [a, b]).equalsTo([c, a, b]));
function tryError() {
assert(false, "Didn't throw error when a or b is not an Array.");
}
try {
func();
tryError();
} catch (e) {}
try {
func(undefined, []);
tryError();
} catch (e) {}
try {
func([], undefined);
tryError();
} catch (e) {}
if (errors.length > 0) {
failed(errors, successful);
} else {
successful();
}
}
test(altJoin, function () {
console.log("Test successfully finished.");
}, function (errors) {
errors.forEach(function (e) { console.error(e); });
})
#!/usr/bin/python3
#
# Problem 3
#
# Write a function that computes the list of the first 100 Fibonacci numbers. By definition,
# the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is
# the sum of the previous two. As an example, here are the first 10 Fibonnaci numbers:
# 0, 1, 1, 2, 3, 5, 8, 13, 21, and 34.
# function that computes the list of the first 100 Fibonacci numbers.
def fibonacci100():
numbers = [0] * 100;
numbers[0] = 0
numbers[1] = 1
for i in range(2, 100):
numbers[i] = numbers[i - 1] + numbers[i - 2];
return numbers;
print(fibonacci100());
/*
* Problem 4
*
* Write a function that given a list of non negative integers, arranges them such that they form
* the largest possible number. For example, given [50, 2, 1, 9], the largest formed number is 95021.
*/
/**
* A function that given
* @param list Array a list of non negative integers
* @return Integer a arrangement such that they form the largest possible number
*/
function largestArrangement(list) {
if (!Array.isArray(list))
throw new Error("list is not an array.");
if (list.length == 0)
throw new Error("list must contain integer.");
list.sort(function(a, b) {
if (!Number.isInteger(a) || !Number.isInteger(b) || a < 0 || b < 0) {
throw new Error("Number(s) not valid.");
}
var ab = parseInt(a.toString() + b.toString());
var ba = parseInt(b.toString() + a.toString());
return ab > ba ? -1 : ab === ba ? 0 : 1;
});
return parseInt(list.join(""));
}
/**
* Test for the function
* @param func function the function to test
* @param successful function callback when test is successfully finished. ( without any error. )
* @param failed function callback when there is any error. The function will get the list of error
* as it's first argument, and put `successful` as it's second argument.
*/
function test(func, successful, failed) {
var errors = [];
function assert(bool, errMsg) {
if (!bool) {
errors.push(new Error(errMsg));
}
}
assert(func([1]) === 1);
assert(func([0, 1]) === 10);
assert(func([50, 2, 1, 9]) === 95021);
assert(func([28, 2, 1, 9]) === 92821);
assert(func([5, 50, 56]) === 56550);
assert(func([420, 42, 423]) === 42423420);
function tryError() {
assert(false, "Didn't throw error given invalid input.");
}
try {
func([2, -1, 3]);
tryError();
} catch (e) {}
try {
func([]);
tryError();
} catch (e) {}
try {
func();
tryError();
} catch (e) {}
try {
func([2, "x", 3]);
tryError();
} catch (e) {}
if (errors.length > 0) {
failed(errors, successful);
} else {
successful();
}
}
test(largestArrangement, function () {
console.log("Test successfully finished.");
}, function (errors) {
errors.forEach(function (e) { console.error(e); });
})
/*
* Problem 5
*
* Write a program that outputs all possibilities to put + or - or nothing between
* the numbers 1, 2, ..., 9 (in this order) such that the result is always 100.
* For example: 1 + 2 + 34 – 5 + 67 – 8 + 9 = 100.
*/
function test(configureNo) {
var conf = configureNo.toString(3).replace(/0/g, " ").replace(/1/g, "+").replace(/2/g, "-");
if (conf.length > 8)
throw new Error("configureNo invalid.");
if (conf.length < 8) {
conf = new Array(8 - conf.length + 1).join(" ") + conf;
}
if (conf.length !== 8) {
throw new Error("Strange bug.");
}
var expr = "";
for(var i = 0; i < 9; i ++) {
expr += (i + 1).toString();
if (i == 8)
break;
switch(conf[i]) {
case " ":
break;
case "+":
expr += " + ";
break;
case "-":
expr += " - ";
break;
}
}
if (eval("(" + expr + ")") === 100) {
return expr;
} else {
return false;
}
}
for(var i = 0; i < Math.pow(3, 8); i ++) {
var res = test(i);
if (res) {
console.log(res + " == 100 ( config # " + i + " )");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment