Skip to content

Instantly share code, notes, and snippets.

@ugate
Last active July 16, 2020 20:31
Show Gist options
  • Save ugate/639fc90e2733f835ab1fddb103c2914a to your computer and use it in GitHub Desktop.
Save ugate/639fc90e2733f835ab1fddb103c2914a to your computer and use it in GitHub Desktop.
Coding Challenges (Arrays)
/**
* Checks an array for duplicates
* @param {*[]} arr The array to check for duplicates
* @returns {Boolean} True when there are duplicates, false when there are none
*/
function hasDuplicate(arr) {
for (let i = 0, j, ln = arr.length; i < ln; ++i) {
for (j = i + 1; j < ln; ++j) {
if (arr[i] === arr[j]) return true;
}
}
return false;
}
// optimized
function containsDuplicate(nums) {
nums.sort();
for (let i = 1, prev = nums[0], curr, ln = nums.length; i < ln; ++i) {
curr = nums[i];
if (curr === prev) return true;
prev = curr;
}
return false;
};
// not working yet
function intersection(a, b) {
const ints = [];
for (let i = 0, al = a.length, bl = b.length; i < al; ++i) {
if (b.includes(a[i]) && ints.length < bl) {
ints.push(a[i]);
}
}
return ints;//a.filter((x => b.includes(x));
}
console.clear();
console.log(`===================================`);
var x = [1,2,2,1], y = [2,2];
console.log(x, y);
console.log('FINAL ===>', intersection(x,y)); //[2,2]
var x = [4,9,5], y = [9,4,9,8,4];
console.log(x, y);
console.log('FINAL ===>', intersection(x,y));// [4,9]
var x = [1,2,2,1], y = [2];
console.log(x, y);
console.log('FINAL ===>', intersection(x,y));// [2]
var x = [61,24,20,58,95,53,17,32,45,85,70,20,83,62,35,89,5,95,12,86,58,77,30,64,46,13,5,92,67,40,20,38,31,18,89,85,7,30,67,34,62,35,47,98,3,41,53,26,66,40,54,44,57,46,70,60,4,63,82,42,65,59,17,98,29,72,1,96,82,66,98,6,92,31,43,81,88,60,10,55,66,82,0,79,11,81];
var y = [5,25,4,39,57,49,93,79,7,8,49,89,2,7,73,88,45,15,34,92,84,38,85,34,16,6,99,0,2,36,68,52,73,50,77,44,61,48];
var x = [1,2,2,1], y = [2];
console.log(x, y);
console.log('FINAL ===>', intersection(x,y));// [5,4,57,79,7,89,88,45,34,92,38,85,6,0,77,44,61]
/**
* @example
* occurrencesRanks([2,4,0,-10,4,10,5,2,1,1,-100,2,-100]);
* // result will be:
* // [ [2,3], [4,2], [1,2], [-100,2], [0,1], [-10,1],
* // [10,1], [5,1]
* // ]
* @param {*[]} arr The array that contains the items that will
* be ranked
* @returns {*[]} A multi-dimensional array that is sorted
* by the array's most frequently occurring item to the
* lowest. Each item in the array will contain a two item
* array where the
* __1st__ entry is the passed array's value and the
* __2nd__ entry is the number of times it occurred in the
* array.
*/
function occurrencesRanks(arr) {
const map = new Map();
for (let item of arr) {
map.set(item, (map.has(item) ? map.get(item) : 0) + 1);
}
const ranked = [...map].sort((a, b) => b[1] - a[1]);
return ranked;
}
/**
* Extracts an array's most frequently occurring item by a
* given rank
* @example
* // result will be [0,1] since it is the 3rd most
* // frequently occurring item in the passed array
* occurrencesRank([2,4,0,-10,4,10,5,2,1,1,-100,2,-100], 3);
* @param {*[]} arr The array that contains the items that will
* be ranked
* @param {Integer} rank The occurrence rank that will be used
* @returns {*[]} A two item array where the
* __1st__ entry is the passed array's value and the
* __2nd__ entry is the number of times it occurred in the
* array.
*/
function occurrencesRank(arr, rank) {
if (rank > arr.length) return;
const ranked = occurrencesRanks(arr);
if (rank > ranked.length) return;
let prev = 0, rnkCnt = 1;
for (let rnk of ranked) {
if (prev && prev[1] === rnk[1]) continue;
if (rnkCnt === rank) return rnk;
rnkCnt++;
prev = rnk;
}
}
/**
* Removes duplicate entries in an array (in-place w/o generating another array)
* @param {*[]} arr The array where duplicates will be removed
* @returns {Integer} The new length of the array after removal
*/
function removeDuplicates(arr) {
for (let i = 0, si = 0, cnt; i < arr.length; ++i) {
if (arr[i] === arr[i + 1]) continue;
cnt = i - si;
if (cnt > 0) {
arr.splice(si, cnt);
i -= cnt;
si = i + 1;
} else if (arr[i] !== arr[i + 1]) {
si++;
}
}
return arr.length;
}
// return [...new Set(nums)];
// optimized
function removeDuplicates2(nums) {
let len = nums.length;
if (len === 1) return 1;
let index = 0;
let val = nums[0];
for(let i = 1; i < len; ++i) {
if (val === nums[i]) continue;
index++;
nums[index] = val = nums[i];
}
return index+1;
}
console.clear();
console.log(`===================================`);
var x = [1,1,1,2,2,2,3,4];
console.log(x);
removeDuplicates(x);
console.log('FINAL ===>', x);
console.log(`===================================`);
var x = [1,2,2,2,3,4,4];
console.log(x);
removeDuplicates(x);
console.log('FINAL ===>', x);
console.log(`===================================`);
var x = [1,1,1,2,3,3,4];
console.log(x);
removeDuplicates(x);
console.log('FINAL ===>', x);
console.log(`===================================`);
var x = [1,2,2,3,4];
console.log(x);
removeDuplicates(x);
console.log('FINAL ===>', x);
console.log(`===================================`);
var x = [1,1,2,3,4,4];
console.log(x);
removeDuplicates(x);
console.log('FINAL ===>', x);
/**
* Shifts an array to the right or left by a given amount via an array copy
* or in-place
* @param {*[]} arr The array to shift
* @param {Integer} amt The number of array elements to shift by
* @param {Boolean} [left] Truthy to shift to the left, otherwise, shifts
* elements to the right
* @param {Boolean} [copy] Truthy to make a copy of the array when shifting
* or falsy to shift the passed array in-place. __NOTE: The lower the `amt`
* the _faster_ the shift will be in-place versus making a copy. The reverse
* is also true- the higher the `amt` the _faster_ the copy will be versus
* shifting in-place.__
* @returns {*[]} Either the passed array (in-place) or a newly shifted array
* (copy)
*/
function shift(arr, amt, left, copy) {
if (copy) { // copy is faster
let count = amt > arr.length ? amt % arr.length : amt;
return arr.concat(arr.splice(0, (left ? count : arr.length - count)));
}
while (amt > 0) {
if (left) arr.push(arr.shift());
else arr.unshift(arr.pop());
--amt;
}
return arr;
}
console.clear();
var x = [1,2,3,4,5,6,7], amt = 2;
console.log('->', x);
console.log(`shift right by ${amt} (copy)`, shift([1,2,3,4,5,6,7], amt, false, true));
console.log(`shift right by ${amt} (in place)`, shift([1,2,3,4,5,6,7], amt));
console.log(`===================================`);
var x = [1,2,3,4,5,6,7], amt = 8;
console.log(`shift right by ${amt} (copy)`, shift([1,2,3,4,5,6,7], amt, false, true));
console.log(`shift right by ${amt} (in place)`, shift([1,2,3,4,5,6,7], amt));
/**
* Sorts an array of numbers so that all the zeros are at the end of the array
* @param {Integer[]} nums The numbers to sort
*/
function sortZeroEnd(nums) {
return nums.sort(function(a, b) {
if (a !== 0 && b === 0) return -1;
if (a === 0 && b !== 0) return 1;
return a - b;
});
}
/**
* Moves all the zeros to the end of the array while maintaining order
* @param {Integer[]} nums The numbers to be evaluated
* @returns {Integer[]} The passed nums
*/
function moveZerosEnd(nums) {
for (let i = 0, ln = nums.length; i < ln; ++i) {
if (nums[i] === 0) {
nums.push(nums.splice(i, 1)[0]);
--ln;
if (nums[i] === 0) --i;
}
}
return nums;
}
console.clear();
console.log(`===================================`);
var x = [0,1,0,3,12], y = [1,3,12,0,0];
console.log(x, '===>', y);
console.log('FINAL ===>', sortZeroEnd(x));
console.log(`===================================`);
var x = [0,0,1], y = [1,0,0];
console.log(x, '===>', y);
console.log('FINAL ===>', moveZerosEnd(x));
console.log(`===================================`);
var x = [0,1,0,3,12], y = [1,3,12,0,0];
console.log(x, '===>', y);
console.log('FINAL ===>', moveZerosEnd(x));
/**
* Determines the total increase between numbers in an array
* @param {*[]} arr The array that will be evaluated
* @returns {Integer} The total increase
*/
function maxProfit(arr) {
let max = 0;
for (let i = 1, ln = arr.length; i < ln; ++i) {
if (arr[i] > arr[i - 1]) {
max += arr[i] - arr[i - 1];
}
}
return max;
}
console.clear();
var x = [7,1,5,3,6,4];
console.log(x);
console.log('EXPECTED 7 ===>', maxProfit(x));
console.log(`===================================`);
var x = [1,2,3,4,5];
console.log(x);
console.log('EXPECTED 4 ===>', maxProfit(x));
console.log(`===================================`);
var x = [7,6,4,3,1];
console.log(x);
console.log('EXPECTED 0 ===>', maxProfit(x));
console.log(`===================================`);
var x = [1,1,5,3,9,4];
console.log(x);
console.log('EXPECTED 10 ===>', maxProfit(x));
console.log(`===================================`);
var x = [6,2,3,4,7];
console.log(x);
console.log('EXPECTED 5 ===>', maxProfit(x));
/**
* Returns the 1st unique number in an array
* @param {Integer[]} arr The array to evaluate
* @returns {Integer} The unique number in the array (or zero when none)
*/
function uniqueNumber(nums) {
let unique;
for (let num of nums) {
unique ^= num;
}
return unique;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment