O(n) because whole array will be searched; it is searched from front to back.
Created
December 13, 2017 10:11
-
-
Save steventswu/25e0e31424b1cc9c8cf0c10e8cd6cbac to your computer and use it in GitHub Desktop.
Oursky Developer Pre-Test Answer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Returns true if the 2nd array is a subset of 1st array. False otherwise. | |
*/ | |
function isSubet (arr1, arr2) { | |
return arr2.every(function (val) { | |
return arr1.indexOf(val) >= 0; | |
}); | |
} | |
/* Example of how the above function works | |
*/ | |
var x = ['A', 'B', 'C']; | |
var y = ['A', 'A', 'B', 'C']; | |
console.log(isSubet(x, y)); // true |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Write a function that takes an array of integers as input. For each integer, output the next | |
fibonacci number. | |
*/ | |
var arr1 = [1,9,21]; | |
for(i = 0; i < arr1.length; i++) { | |
console.log(nextFibonacci(arr1[i])); | |
} | |
function nextFibonacci(num) { | |
var fib = []; | |
fib[0] = 0; | |
fib[1] = 1; | |
for (var i = 2; i <= num; i++) { | |
fib[i] = fib[i - 1] + fib[i - 2]; | |
if (fib[i] > num) { | |
return fib[i]; | |
} | |
} | |
if (fib[i - 1] < num) { | |
return fib[i - 1] + num; | |
} | |
if (fib[i] = num - 1) { | |
return fib[i - 1] + fib[i - 2]; | |
} | |
if (fib[i - 1]) { | |
return num + num; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* This code encountered a scoping issue. We can't use var because the i variable | |
will be out of scope. There are two methods to solve the issue: | |
1. use let | |
2. use IIFE | |
*/ | |
// Method 1 uses let | |
function createArrayOfFunctions(y) { | |
var arr = []; | |
for(let i = 0; i<y; i++) { | |
arr[i] = function(x) { return x + i; }; | |
} | |
return arr; | |
} | |
// Method 2 uses IIFE | |
function createArrayOfFunctions(y) { | |
var arr = []; | |
for(var i = 0; i<y; i++) { | |
(function() { | |
var _i = i; | |
arr[_i] = function(x) { return x + i; }; | |
})(); | |
} | |
return arr; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment