Skip to content

Instantly share code, notes, and snippets.

@ark234
Last active January 22, 2018 15:43
Show Gist options
  • Save ark234/766f593402e9c5304ef625d7c15b24c3 to your computer and use it in GitHub Desktop.
Save ark234/766f593402e9c5304ef625d7c15b24c3 to your computer and use it in GitHub Desktop.
1/22 classroom exercise
// Stock Market Profit
// Source: InterviewCake
// Write an function called getMaxProfit that takes in an array of stock prices and returns the best profit you could have made from 1 purchase and 1 sale. The prices in the array are in the sequence in which they were purchased and can only be sold after it was first purchased.
// Input: getMaxProfit([10, 7, 5, 8, 11, 9])
// Output: 6 ..this is the result of 11 - 5
const getMaxProfit = arr => {
let max_profit = 0;
for (let i = 1; i < arr.length; i++) { // buy
for (let j = i; j < arr.length; j++) { // sell
if (arr[j] - arr[i] > max_profit) { // buy low, sell high
max_profit = arr[j] - arr[i];
}
}
}
return max_profit;
}
// DNA Strings
// Source: CodeWars
// In DNA strings, symbols "A" and "T" are complements of each other, as are "C" and "G".
// Write a function called dnaTransform that takes in a DNA string returns a string that represents it's compliment.
// Input: dnaTransform("ATTGC")
// Output: "TAACG"
const dnaTransform = str => {
const complement = {
"A": "T",
"T": "A",
"C": "G",
"G": "C"
}
return str
.split('')
.map(el => {
if(el in complement) { return complement[el] }
})
.join('');
}
// Randomize An Array
// Source: Fisher-Yates Shuffle
// Write a function called shuffle that given an array, randomizes the position of the elements and returns the new array.
// Input: shuffle(['a','b','c','d'])
// Possible Output: ['b','d','a','c']
const getRandomInt = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
const shuffle = array => {
const upper = array.length;
let temp, rand;
for (let lower = 0; lower < upper; lower++) {
temp = array[lower];
rand = getRandomInt(lower, length); // generate random index in moving range
array[lower] = array[rand];
array[rand] = temp;
}
return array;
}
// Find The Products
// Source: InterviewCake
// Write a function called getProducts that takes in an array of n numbers and
// for each index finds the product of every integer except the integer at that index.
// Input: getProducts([1,2,3,4])
// Output: [ 24, 12, 8, 6 ]
const getProducts = arr => {
const arr2 = [];
for (let i = 0; i < arr.length; i++) {
let temp = arr.slice();
temp.splice(i,1);
arr2.push(temp.reduce((curr, acc) => {
return acc * curr;
}, 1));
}
return arr2;
}
// Factorial
// Source: HackerRank
// Given a number, print its factoral.
// Input: 5
// Output: 120 (54321)
const factorial = num => {
let result = 1;
for (let i = num; i > 0; i--) {
result *= i;
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment