-
-
Save realinit/9e84aa862b94531ff39b452751c761c0 to your computer and use it in GitHub Desktop.
Arrays with one Misc
This file contains hidden or 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
function createAndInitialize2DArray(size) { | |
// catch a bug & fix me! | |
var defaultValue = 0; | |
var twoDimensionalArray = []; | |
function initOneDArray() { | |
var row = []; | |
for (var i = 0; i < size; i++) { | |
row.push(defaultValue); | |
} | |
return row; | |
} | |
for (var j = 0; j < size; j++) { | |
twoDimensionalArray.push(initOneDArray()); | |
} | |
return twoDimensionalArray; | |
} | |
var matrix = createAndInitialize2DArray(3); | |
console.log(matrix); // [[0, 0, 0], [0, 0, 0], [0, 0, 0]] | |
matrix[0][0] = 89; | |
console.log(matrix); // [[89, 0, 0], [89, 0, 0], [89, 0, 0]] |
This file contains hidden or 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
function createAndInitialize2DArray (size) { | |
// catch a bug & fix me! | |
var defaultValue = 0; | |
var row = []; | |
var twoDimensionalArray = []; | |
for (var i = 0; i < size; i++) { | |
row.push(defaultValue); | |
} | |
for (var j = 0; j < size; j++) { | |
twoDimensionalArray.push(row); | |
} | |
return twoDimensionalArray; | |
} | |
var matrix = createAndInitialize2DArray(3); | |
console.log(matrix); // [[0, 0, 0], [0, 0, 0], [0, 0, 0]] | |
matrix[0][0] = 89; | |
console.log(matrix); // [[89, 0, 0], [89, 0, 0], [89, 0, 0]] | |
This file contains hidden or 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
function createAndInitialize2DArray (size) { | |
var twoDimensionalArray = new Array(size); | |
for(var i = 0; i < size; i++) { | |
twoDimensionalArray[i] = new Array(size).fill(0); | |
} | |
return twoDimensionalArray; | |
} | |
var matrix = createAndInitialize2DArray(3); | |
console.log(matrix); // [[0, 0, 0], [0, 0, 0], [0, 0, 0]] | |
matrix[0][0] = 89; | |
console.log(matrix); // [[89, 0, 0], [0, 0, 0], [0, 0, 0]] | |
This file contains hidden or 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
var cards = ['Heart5', 'Diamond6', 'Club7', 'Spade8']; | |
console.log(cards.toString()); // Heart5,Diamond6,Club7,Spade8 | |
This file contains hidden or 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
function arrayToString(arr) { | |
var str = ''; | |
arr.forEach(function(i, index) { | |
str += i; | |
if (index != (arr.length - 1)) { | |
str += ','; | |
}; | |
}); | |
return str; | |
} | |
var cards = ['Heart5', 'Diamond6', 'Club7', 'Spade8']; | |
console.log(arrayToString(arr)); // Heart5, Diamond6, Club7, Spade8 | |
This file contains hidden or 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
var nestedArray = [ 1, 2, 3, [4, 5, 6,'abc', [7, 8, 9, []]] ]; | |
var sum = 0; | |
var count = 0; | |
var avg = 0; | |
nestedArray.forEach(function calculateAverage(element) { | |
if('number' === typeof element) { | |
sum += element; | |
count++; | |
avg = sum / count; | |
} | |
if(Array.isArray(element)) { | |
element.forEach(calculateAverage); | |
} | |
} | |
); | |
console.log('Sum = ', sum); // 45 | |
console.log('Count = ', count); // 9 | |
console.log('Average = ', avg); // 5 | |
This file contains hidden or 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
function combination (arr) { | |
let i, j, temp | |
let result = [] | |
let arrLen = arr.length | |
let power = Math.pow | |
let combinations = power(2, arrLen) | |
// Time & Space Complexity O (n * 2^n) | |
for (i = 0; i < combinations; i++) { | |
temp = '' | |
for (j = 0; j < arrLen; j++) { | |
// & is bitwise AND | |
if ((i & power(2, j))) { | |
temp += arr[j] | |
} | |
} | |
result.push(temp) | |
} | |
return result | |
} | |
console.log(combination([1, 2, 3])) // [ "", "1", "2", "12", "3", "13", "23", "123" ] | |
This file contains hidden or 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
function rangeValidator (num, lowerBound, upperBound) { | |
return ((num >= lowerBound) && (num <= upperBound)) ? true : false; | |
} | |
function coutSumOfDiceRolls (str) { | |
if('string' === typeof str) { | |
var splitterArray = str.split('d'); | |
var dice = +splitterArray[0]; | |
var sides = +splitterArray[1]; | |
var diceUpperBound = 1000; | |
var sidesUpperBound = 100; | |
var diceLowerBound = 1; | |
var sidesLowerBoud = 2; | |
if (!rangeValidator(dice, diceLowerBound, diceUpperBound)) { | |
console.warn('Number of Dices are out of range. Please provide number of dices in the range [1, 1000]'); | |
return 0; | |
} | |
if (!rangeValidator(sides, sidesLowerBoud, sidesUpperBound)) { | |
console.warn('Number of sides of a dice are out of range. Please provide number of sides of a dice in the range [2, 100]'); | |
return 0; | |
} | |
var sum = 0; | |
for(var i = 1; i <= dice; i++) { | |
// Math.floor(Math.random() * (max - min + 1)) + min; | |
sum += Math.floor(Math.random() * (sides - 1)) + 2; | |
} | |
return sum; | |
} else { | |
console.warn('Please call coutSumOfDiceRolls function with a string argument in the following format {digit}d{digit} format'); | |
return 0; | |
} | |
} | |
console.log(coutSumOfDiceRolls('1d6')); // Output will be between [2, 6] | |
console.log(coutSumOfDiceRolls('3d18')); // Output will be between [6, 54] | |
console.log(coutSumOfDiceRolls('300d1800')); // Number of sides of a dice are out of range. Please provide number of sides of a dice in the range [2, 100] | |
console.log(coutSumOfDiceRolls('3000d18')); // Number of Dices are out of range. Please provide number of dices in the range [1, 1000] | |
console.log(coutSumOfDiceRolls(321)); // Please call coutSumOfDiceRolls function with a string argument in the following format {digit}d{digit} format | |
This file contains hidden or 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
const countNegative = ( M, n, m ) => { | |
var count = 0; | |
// start from top right | |
var i = 0; | |
var j = m - 1; | |
while ( j >= 0 && i < n ) { | |
if ( M[i][j] < 0 ) { | |
// last negative number is at index j. Hence, there j + 1 negative numebrs at index i | |
count += (j + 1); | |
// Move to the next row | |
i += 1; | |
} else { | |
// Move to the next column | |
j -= 1; | |
} | |
} | |
return count; | |
}; | |
var M = [ | |
[-3, -2, -1, 1], | |
[-2, -12, 3, 4], | |
[4, 5, 7, 8] | |
]; | |
console.log(countNegative(M, 3, 4)); // 5 |
This file contains hidden or 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
'use strict'; | |
function createPascalTriangle (numRows) { | |
var pascalTriangle = []; | |
for (var i = 0; i < numRows; i++) { | |
pascalTriangle[i] = new Array(i+1); | |
for (var j = 0; j < i+1; j++) { | |
if (j === 0 || j === i) { | |
pascalTriangle[i][j] = 1; | |
} else { | |
pascalTriangle[i][j] = pascalTriangle[i-1][j-1] + pascalTriangle[i-1][j]; | |
} | |
} | |
} | |
return pascalTriangle; | |
} | |
console.table(createPascalTriangle(6)); | |
This file contains hidden or 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
'use strict'; | |
function deDuplicate(data) { | |
var result = []; | |
data.forEach(function(element) { | |
if (result.indexOf(element) === -1) { | |
result.push(element); | |
} | |
}); | |
return result; | |
} | |
console.log(deDuplicate([])); // [] | |
console.log(deDuplicate([1, 1, 1])); // [1] | |
console.log(deDuplicate([1, 2, 3, 1, 2])); // [1, 2, 3] |
This file contains hidden or 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
'use strict'; | |
var invalidEntries; | |
function filterByID(element) { | |
if (element.id && ('number' === typeof element.id)) { | |
return true; | |
} | |
invalidEntries++; | |
return false; | |
} | |
function filterByExtension(element) { | |
if (element.path && ('string' === typeof element.path)) { | |
var pathArr = element.path.split('.'); | |
var extension = pathArr[pathArr.length - 1]; | |
if (extension === 'txt') { | |
return true; | |
} | |
} | |
invalidEntries++; | |
return false; | |
} | |
function sortByID(arr) { | |
return arr.sort(function(first, second) { | |
return (first.id - second.id); | |
}); | |
} | |
var files = [{ | |
id: 15, | |
path: 'foo.txt' | |
}, { | |
id: 1, | |
path: 'bar.1.txt' | |
}, { | |
id: 3, | |
path: 'mine.txt' | |
}, { | |
id: 2, | |
path: 'yours.txt' | |
}, { | |
id: 4, | |
path: 'yours.txt.diff' | |
}, { | |
id: undefined, | |
path: null | |
}, { | |
id: null, | |
path: null | |
}, { | |
path: 'foo.bar.txt' | |
}]; | |
(function(files) { | |
invalidEntries = 0; | |
var sortedAndFilterededArr = files | |
.filter(filterByID) | |
.filter(filterByExtension) | |
.sort(function(first, second) { | |
return first.id - second.id; | |
}); | |
console.log('Number of Invalid Entries = ', invalidEntries); // 7 | |
console.log('Filtered And Sorted Array \n', sortedAndFilterededArr); | |
/* [ | |
{id: 1, path:'bar.1.txt'}, | |
{id: 2, path:'yours.txt'}, | |
{id: 3, path:'mine.txt'}, | |
{id: 15, path:'foo.txt'} | |
]; | |
*/ | |
})(files); | |
This file contains hidden or 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
function findDuplicates(data) { | |
let result = []; | |
data.forEach(function(element, index) { | |
// Find if there is a duplicate or not | |
if (data.indexOf(element, index + 1) > -1) { | |
// Find if the element is already in the result array or not | |
if (result.indexOf(element) === -1) { | |
result.push(element); | |
} | |
} | |
}); | |
return result; | |
} | |
console.log( findDuplicates([]) ); // [] | |
console.log( findDuplicates([1, 1, 1]) ); // [1] | |
console.log( findDuplicates([1, 2, 3, 1, 2, 1]) ); // [1, 2] | |
This file contains hidden or 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
function findFirstUniqueCharacter( inputString ) { | |
let freqCounter = []; | |
// The issue using Map data structure is during the retrival. As it does not gaurantee the keys will be retrived in the same order as they were inserted | |
// Hence, we use an array of frequency counter. But in this array keys are found using the ascii values of the character. | |
inputString.split('').forEach(ch => { | |
if (!freqCounter[ch]) | |
freqCounter[ch] = 1; | |
else | |
freqCounter[ch]++; | |
}); | |
// Observe this array. It's kinda Map only. | |
console.log(freqCounter); | |
for (let i = 0; i < inputString.length - 1; i++) { | |
let ch = inputString[i]; | |
if (freqCounter[ch] == 1) | |
return ch; | |
} | |
return 'No Unique Character Found'; | |
} | |
console.log(findFirstUniqueCharacter('foobar')); // f | |
console.log(findFirstUniqueCharacter('aabbccdef')); // d | |
console.log(findFirstUniqueCharacter('aabbcc')); // 'No Unique Character Found' |
This file contains hidden or 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
function twoDiff(arr, target) { | |
let map = {} | |
for (let i = 0; i < arr.length; i++) { | |
let sub = arr[i] - target | |
let add = arr[i] + target | |
if ( map[sub] || map[add] ) { | |
return true | |
} else { | |
map[arr[i]] = true | |
} | |
} | |
return false | |
} | |
console.log( twoDiff([1,2,3,4,5], 3) ) // true | |
console.log( twoDiff([5,4,3,2,1], 7) ) // false | |
console.log( twoDiff([5,4,3,2,1], 2) ) // true |
This file contains hidden or 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
'use strict'; | |
function findPivot(arr, low, high) { | |
if (high < low) { | |
return -1; | |
} | |
if (high == low) { | |
return low; | |
} | |
let mid = Math.floor((low + high) / 2); | |
if (mid < high && arr[mid] > arr[mid + 1]) | |
return mid; | |
if (mid > low && arr[mid] < arr[mid - 1]) | |
return (mid - 1); | |
if (arr[low] >= arr[mid]) | |
return findPivot(arr, low, mid - 1); | |
return findPivot(arr, mid + 1, high); | |
} | |
console.log(findPivot([8, 9, 10, 1, 2, 3], 0, 5)); // 2 'index of 10' | |
console.log(findPivot([8, 9, 10, 11, 12, 1, 2, 3], 0, 7)); // 4 'index of 12' | |
This file contains hidden or 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
(function() { | |
var i, fizzBuzz; | |
for(i = 1; i <= 100; i++) { | |
fizzBuzz = ''; | |
if(!(i % 3)) { | |
fizzBuzz += 'Fizz'; | |
} | |
if(!(i % 5)) { | |
fizzBuzz += 'Buzz'; | |
} | |
console.log(fizzBuzz || i); | |
} | |
})(); | |
This file contains hidden or 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
'use strict'; | |
function flatten (arr, result) { | |
var result = result || []; | |
arr.forEach(function(i) { | |
Array.isArray(i) ? flatten(i, result): result.push(i); | |
}); | |
return result; | |
} | |
console.log(flatten([1, 2, 3, [4, 5], [6, [7, 8]]])); | |
This file contains hidden or 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
'use strict'; | |
var flattenArr = []; | |
function flatten(numbers) { | |
// Declarative way of solving the problem | |
numbers.forEach(function(number) { | |
Array.isArray(number) ? flatten(number) : flattenArr.push(number); | |
}); | |
return flattenArr; | |
} | |
var unflatternArr = [1, 2, 3, [4, 5], [6, [7, 8]]]; | |
console.log(flatten(unflatternArr)); // [1, 2, 3, 4, 5, 6, 7, 8] | |
This file contains hidden or 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
'use strict'; | |
var flattenArr = []; | |
function flatten(numbers) { | |
var numbersLen = numbers.length; | |
// Imperative way of solving the problem | |
for (var i = 0; i < numbersLen; i++) { | |
Array.isArray(numbers[i]) ? flatten(numbers[i]) : flattenArr.push(numbers[i]); | |
} | |
return flattenArr; | |
} | |
var unflatternArr = [1, 2, 3, [4, 5], [6, [7, 8]]]; | |
console.log(flatten(unflatternArr)); // [1, 2, 3, 4, 5, 6, 7, 8] | |
This file contains hidden or 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
function increment ( numbers ) { | |
let iterator = numbers.length - 1 | |
while ( iterator >= 0 ) { | |
let num = numbers[ iterator ] | |
num++ | |
if (num > 0 && num <= 9) { | |
numbers[ iterator ] = num | |
break | |
} else { | |
numbers[ iterator ] = 0 | |
if ( iterator == 0 ) { // For the [ 9, 9, 9 ] case | |
numbers.unshift(1) | |
break | |
} | |
iterator-- | |
} | |
} | |
return numbers | |
} | |
console.log(increment([ 2, 7, 2 ])) // [ 2, 7, 3 ] | |
console.log(increment([ 2, 7, 9 ])) // [2, 8, 0] | |
console.log(increment([ 2, 9, 9 ])) // [3, 0, 0] | |
console.log(increment([ 9, 9, 9 ])) // [1, 0, 0, 0] | |
This file contains hidden or 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
const lengthofLargestSubarrayWithContinuousElements = (arr) => { | |
arr.sort() | |
let count = [] | |
let inLen = arr.length | |
let j = 0 | |
let initalCount = 1 | |
for (let i = 0; i < inLen; i++) { | |
while( (arr[i] + 1) == arr[i+1] ) { | |
count[j] = initalCount + 1 | |
initalCount++ | |
i++ | |
} | |
initalCount = 1 | |
j++ | |
} | |
// filter null elements from an array | |
count = count.filter(Number) | |
return Math.max(...count) | |
}; | |
console.log(lengthofLargestSubarrayWithContinuousElements([4, 2, 1, 20])) // 2 | |
console.log(lengthofLargestSubarrayWithContinuousElements([2, 4, 3])) // 3 | |
console.log(lengthofLargestSubarrayWithContinuousElements([1, 563, 585, 571, 90, 92, 94, 93, 91, 45])) // 5 | |
This file contains hidden or 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
/** | |
* @param {string} s | |
* @return {number} | |
*/ | |
function lengthOfLongestSubstring (s) { | |
// Base cases | |
if (s.length <= 1) | |
return s.length | |
var loop; | |
var subStr; | |
var iterator; | |
var length = 0; | |
// Iterate over the string | |
for (var i = 0; i < s.length; i++) { | |
iterator = i; | |
loop = true; | |
subStr = ''; | |
// Given the current character, iterate over the remaining string to the right of that character | |
while (loop) { | |
subStr += s[iterator]; | |
iterator++; | |
if (subStr.includes(s[iterator]) || iterator >= s.length) { | |
loop = false; | |
if (subStr.length > length) { | |
length = subStr.length; | |
} | |
} | |
} | |
} | |
return length; | |
} | |
lengthOfLongestSubstring("abcabcbb"); // 3 | |
lengthOfLongestSubstring("bbbbb"); // 1 | |
lengthOfLongestSubstring("pwwkew"); // 3 |
This file contains hidden or 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
var input = [{ | |
'name': 'event1', | |
'time': 1000 | |
}, { | |
'name': 'event2', | |
'time': 2000 | |
}, { | |
'name': 'event3', | |
'time': 3000 | |
}]; | |
var i = 0; | |
var inputLength = input.length; | |
function iterate() { | |
if (i < inputLength) { | |
var currentElement = input[i]; | |
console.log(`${currentElement.name} Started.`); | |
setTimeout( function () { | |
console.log(`${currentElement.name} Ended.`); | |
iterate(); | |
}, currentElement.time); | |
} | |
i++; | |
} | |
iterate(); |
This file contains hidden or 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
var unSortedArr = [2, 3, 2, 5, 4, 5, 5, 9, 6, 8, 8, 7]; | |
var sum = 10; | |
function pairMatchingSum (arr, sum) { | |
var start, end, tempSum; | |
var i = 0 ; | |
var j = arr.length - 1; | |
// Create a new Map instance | |
var s = new Map(); | |
var sortedArr = arr.sort(); | |
while (i !== j) { | |
start = sortedArr[i]; | |
end = sortedArr[j]; | |
tempSum = start + end; | |
if (tempSum === sum) { | |
// Add matching pair to the Map. Map does not allow duplicate keys. | |
s.set(start +'-'+ end, true); | |
i++; | |
j--; | |
} else if (tempSum > sum) { | |
j--; | |
} else { | |
i++; | |
} | |
} | |
console.log("Pairs matching the input sum in the given array without duplicates = ", [...s.keys()]); | |
// Pairs matching the input sum in the given array without duplicates = ["2-8", "3-7", "4-6", "5-5"] | |
} | |
pairMatchingSum(unSortedArr, sum); | |
This file contains hidden or 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
var unSortedArr = [2, 3, 2, 5, 4, 5, 5, 5, 5, 9, 6, 8, 8, 7]; | |
var sum = 10; | |
function pairMatchingSum (arr, sum) { | |
var start, end, tempSum; | |
var i = 0 ; | |
var j = arr.length - 1; | |
// Create a new Object instance | |
var s = {}; | |
var sortedArr = arr.sort(); | |
while (i !== j) { | |
start = sortedArr[i]; | |
end = sortedArr[j]; | |
tempSum = start + end; | |
if (tempSum === sum) { | |
// Add matching pair to the Object. Object does not allow duplicate keys. | |
s[start +'-'+ end] = true; | |
i++; | |
j--; | |
} else if (tempSum > sum) { | |
j--; | |
} else { | |
i++; | |
} | |
} | |
console.log("Pairs matching the input sum in the given array without duplicates = ", Object.keys(s)); | |
// Pairs matching the input sum in the given array without duplicates = [ '2-8', '3-7', '4-6', '5-5' ] | |
} | |
pairMatchingSum(unSortedArr, sum); | |
This file contains hidden or 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
'use strict'; | |
function swap (alphabets, index1, index2) { | |
var temp = alphabets[index1]; | |
alphabets[index1] = alphabets[index2]; | |
alphabets[index2] = temp; | |
return alphabets; | |
} | |
function permute (alphabets, startIndex, endIndex) { | |
if (startIndex === endIndex) { | |
console.log(alphabets.join('')); | |
} else { | |
var i; | |
for (i = startIndex; i <= endIndex; i++) { | |
swap(alphabets, startIndex, i); | |
permute(alphabets, startIndex + 1, endIndex); | |
swap(alphabets, i, startIndex); // backtrack | |
} | |
} | |
} | |
var alphabets = ['A','B','C']; | |
permute(alphabets, 0, alphabets.length-1); // ABC, ACB, BAC, BCA, CBA, CAB | |
This file contains hidden or 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
function productPuzzle(data) { | |
var len = data.length | |
var left = new Array(len) | |
var right = new Array(len) | |
// prepare the left array | |
left[0] = 1 | |
for(let i = 1; i < len; i++) | |
left[i] = left[i-1] * data[i-1] | |
console.log(left) // [ 1, 1, 2, 6 ] | |
// prepare the right array | |
right[len-1] = 1 | |
for (let j = len-2; j >= 0; j-- ) | |
right[j] = right[j+1] * data[j+1] | |
console.log(right) // [ 24, 12, 4, 1 ] | |
return data.map((el, index) => { | |
return left[index] * right[index] | |
}) | |
} | |
console.log(productPuzzle([1, 2, 3, 4])) // [ 24, 12, 8, 6 ] | |
This file contains hidden or 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
function removeDuplicates(cards) { | |
var uniqueCards = {}; | |
cards.forEach(function(i) { | |
if(!uniqueCards[i]) { | |
uniqueCards[i] = true; | |
} | |
}); | |
return Object.keys(uniqueCards); | |
} | |
var cards = ['Heart5', 'Diamond6', 'Club7', 'Spade8', 'Diamond6', 'Club7']; | |
console.log(removeDuplicates(cards)); // ['Heart5', 'Diamond6', 'Club7', 'Spade8'] | |
This file contains hidden or 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
'use strict'; | |
function removeDuplicates(cards) { | |
return cards.filter(function(val, index, self) { | |
return self.indexOf(val) === index; | |
}); | |
} | |
var cards = ['Heart5', 'Diamond6', 'Club7', 'Spade8', 'Diamond6', 'Club7']; | |
console.log(removeDuplicates(cards)); // ['Heart5', 'Diamond6', 'Club7', 'Spade8'] | |
This file contains hidden or 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
'use strict'; | |
function removeDuplicates(cards) { | |
var uniq = []; | |
cards.forEach(function(val) { | |
if (uniq.indexOf(val) === -1) { | |
uniq.push(val); | |
} | |
}); | |
return uniq; | |
} | |
var cards = ['Heart5', 'Diamond6', 'Club7', 'Spade8', 'Diamond6', 'Club7']; | |
console.log(removeDuplicates(cards)); // ['Heart5', 'Diamond6', 'Club7', 'Spade8'] | |
This file contains hidden or 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
'use strict'; | |
function removeDuplicates(cards) { | |
return cards.filter(function(val, index, self) { | |
return self.indexOf(val, index + 1) === -1; | |
}); | |
} | |
var cards = ['Heart5', 'Diamond6', 'Club7', 'Spade8', 'Diamond6', 'Club7']; | |
console.log(removeDuplicates(cards)); // ['Heart5', 'Diamond6', 'Club7', 'Spade8'] |
This file contains hidden or 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
function transformData (endo) { | |
var tra = {}; | |
endo.forEach(function(el) { | |
if (tra[el.skill]) { | |
tra[el.skill].push(el.user); | |
} else { | |
tra[el.skill] = []; | |
tra[el.skill].push(el.user); | |
} | |
}); | |
var res = Object.keys(tra).map(function(key) { | |
var obj = {}; | |
obj['skills'] = key; | |
obj['values'] = tra[key]; | |
return obj; | |
}); | |
console.log(res); | |
} | |
transformData(endorsements); | |
This file contains hidden or 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
'use strict'; | |
function updateFruitsCollection (fruits, fruit) { | |
if (fruits.indexOf(fruit) === -1) { | |
fruits.push(fruit); | |
console.log('New fruits collection is : ' + fruits); | |
} else if (fruits.indexOf(fruit) > -1) { | |
console.log('Fruit already exist in the fruits collection'); | |
} | |
} | |
var fruits = ['strawberries', 'kiwi', 'guava', 'avocado']; | |
updateFruitsCollection(fruits, 'banana'); // New fruits collection is : strawberries,kiwi,guava,avocado,banana | |
updateFruitsCollection(fruits, 'kiwi'); // Fruit already exist in the fruits collection | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment