Scotch.io Flashcards
- Reverse String - Given a string of text, write an algorithm that returns the text received in a reversed format.
(split string and then use reduce c + acc with ‘’ as reducer)
a. function reverseString6(str){
return str.split(‘’).reduce((acc, c) => c + acc, ‘’)
}
b. function reverseString7(str){
return […str].reduce((acc, c) => c + acc, ‘’)
}
reversedString1(‘algorithms’)
console.log(‘smhtirogla’)
- Vowels Counter - Given a string of text containing 0 or more vowels, count the number of vowels that can be found within the text.
(create array of vowels, loop over string to see if vowels array contains any letters from string => vowelsCounter++)
const vowelsCounter2 = (text) => {
let matchingInstances = text.match(/[aeiou]/gi)
if(matchingInstances){ return matchingInstances.length } else { return 0 } }
vowelsCounter2(‘hello how are you’)
console.log(7)
- Max Recurring Chars - Given a string of text, find and return the most recurring character.
(initialise charMap={}, maxCharValue=0 and maxChar=‘’; for…of loop over string using if/else to find if each char in string is a direct property on object. If yes, charMap[char]++, if not charMap[char] = 1. For…in loop on charMap. If charMap[char] > maxCharValue, it becomes maxCharValue and also maxChar, which is returned as max recurring char)
const maxRecurringChar1 = (text) => {
let charMap = {}
let maxCharValue = 0
let maxChar = ‘’
for(let char of text){ if(charMap.hasOwnProperty(char)){ charMap[char]++ } else { charMap[char] = 1 } } for(let char in charMap){ if(charMap[char] > maxCharValue){ maxCharValue = charMap[char] maxChar = char } } return maxChar }
maxRecurringChar1(‘hello how are you’)
console.log(‘o’)
- Capitalise Sentence - Given a sentence containing two or more words, return the equivalent of the sentence when capitalised.
(lowercase and split string in wordsArray. initialise new array as capsArray to equal wordsArray being mapped over. Uppercase [0] and slice(1) the rest of the array. return capsArray.join(‘ ‘))
const capSentence2 = text => {
let wordsArray = text.toLowerCase().split(‘ ‘)
let capsArray = wordsArray.map(word => {
return word[0].toUpperCase() + word.slice(1)
})
return capsArray.join(‘ ‘)
}
capSentence1(‘the tales of scotch!’)
console.log(‘The Tales Of Scotch!’)
- Palindromes - Given a string of text, return true or false indicating whether or not the text is a palindrome.
(lowercase and split string; return on split string using .every() method with letter and index as parameters; if every letter is the same as split array[split array.length - index - 1]
(or the method chaining intuitive approach, although that’s slower))
const palindromeChecker3 = (text) => {
let textLen = text.length
for(let i = 0; i < textLen / 2; i++){
if(text[i] !== text[textLen - 1 - i]){
return false
}
}
return true
}
palindromeChecker1(‘racecar’)
console.log(true)
- Hamming Distance - Given two strings of equal length, calculate and return the hamming distance.
(distance = 0; if both strings are same length, go to for loop, else return ‘Strings are not the same length’; loop through string length in lowercase, if a[i] !== b[i] then distance++)
function hammingDistance(stringA, stringB) {
let distance = 0
if(stringA.length === stringB.length){ for(let i = 0; i < stringA.length; i++){ if(stringA[i].toLowerCase() != stringB[i].toLowerCase()){ distance++ } } return distance } else { return 'Strings are not the same length' } }
hammingDistance(‘helloq’, ‘hellop’)
console.log(1)
- Find Longest Word in String - Given a sentence, return the longest word in the string.
(let result = split string then reduce with maxLength, c as parameters; if c.length > maxLength.length, return c, else return maxLength; return result)
function longestWord1(text) {
let longest = ‘’
let newText = text.split(‘ ‘)
for(let i = 0; i < newText.length; i++){ if(newText[i].length > longest.length){ longest = newText[i] } } return longest }
function longestWord2(text){
let result = text.split(‘ ‘).reduce((maxLength, c) => {
if(c.length > maxLength.length){
return c
} else {
return maxLength
}
}, ‘’)
return result
}
longestWord1(‘Top Shelf Web Development Training on Scotch’)
console.log(‘Development’)
- Search and Replace - Receiving a sentence, a word in the sentence and a replacement for that word as arguments, perform a search and replace on the sentence using the arguments provided and return the new
(if first char of word being replaced === first char of word being replaced uppercase, newWord has first char changed to uppercase, else if the same but for lowercase; return string .replace() word, newWord)
function searchReplace1(str, word, newWord){
if(word[0] === word[0].toUpperCase()){
newWord = newWord[0].toUpperCase() + newWord.slice(1)
}
return str.replace(word, newWord)
}
searchReplace1(‘hello how are you’, ‘hello’, ‘hi’)
console.log(‘hi how are you’)
- Anagrams - Given two strings, write an algorithm to check if they are anagrams of each other. Return true if they pass the test and false if they don’t.
(createCharMap fun, charMap = {}, loop over char of string, if charMap object hasOwnProperty of char, charMap[char]++, else charMap[char] = 1, return charMap; if a.length === b.length, let stringMapA = createCharMap(a), let stringMapB = createCharMap(b)(else return false), for in loop stringMapA, if stringMapA[char] !== stringMapB[char], return false, if all values match, return true)
function isAnagram(stringA, stringB){
function createCharMap(text){
let charMap = {}
for(let char of text){ if(charMap.hasOwnProperty(char)){ charMap[char]++ } else { charMap[char] = 1 } } return charMap } if(stringA.length === stringB.length){ let stringAMap = createCharMap(stringA) let stringBMap = createCharMap(stringB) for(let char in stringAMap){ if(stringAMap[char] !== stringBMap[char]){ return false } } return true } else { return false } }
isAnagram(‘friday’, ‘dayfri’)
console.log(true)
- Pig Latin - Translate the provided string to Pig Latin by following the rules below:
For words that begin with consonant sounds, the consonant before the initial vowel should be moved to the end of the word sequence and “ay” affixed. E.g: “pig” = “igpay”
For words that begin with consonant clusters, the clusters should be moved to the end of the word sequence and “ay” affixed. E.g: “glove” = “oveglay”
For words that begin with vowel sounds, simply add “way” to the end of the word. E.g: “explain” = “explainway”
(initialise array of vowels, vowelIndex = 0; if vowels includes string[0], return string + ‘way’, else for of loop through char of string, if vowels array includes char, vowelsIndex = string .indexOf (char), then break loop; return string.slice(vowelIndex) + string.slice(0, vowelIndex) + ‘ay’)
function pigLatin1(str){
str.toLowerCase()
const vowels = [“a”, “e”, “i”, “o”, “u”];
let vowelIndex = 0
if(vowels.includes(str[0])){ return str + 'way' } else { for(let char of str){ if(vowels.includes(char)){ vowelIndex = str.indexOf(char) break } } return str.slice(vowelIndex) + str.slice(0, vowelIndex) + 'ay' } }
pigLatin1(‘friday’)
console.log(‘idayfray’)
- Given an array and a chunk size, divide the array into many sub-arrays where each sub-array has the specified length.
(initialise newArray; for loop over array, i += size, initialise chunk = array.slice(i, i + size), newArray.push(chunk), return newArray)
function chunkArray3(array, size){
let newArray = []
for(let i = 0; i < array.length; i += size){ let chunk = array.slice(i, i + size) newArray.push(chunk) } return newArray }
chunkArray1([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], 5)
// console.log([[1,2,3,4,5], [6,7,8,9,10], [11,12,13]])
- Given two or more arrays, write a function that combines their elements into one array without any repetition.
(initialise jointArray = []; forEach …arrays parameter, spreading […arrays, …jointArray] into jointArray; filter jointArray for items in jointArray.indexOf(item) === index
[…new Set([…jointArray])] also possible but slower)
function mergeArrays2(…arrays){
let jointArray = []
arrays.forEach(array => jointArray = [...array, ...jointArray]) return jointArray.filter((item, index) => jointArray.indexOf(item) === index) }
console.log(mergeArrays2([12, 2, 31, 104, 50], [1, 2, 3, 104, 5]))
// [1, 2, 3, 104, 5, 12, 31, 50]
- Given an array, remove all falsy values from the array and return an array of only truthy values.
(initialise newArr = []; for of loop of array, if element, push it to newArr; return newArr
filter() also possible, only 5% slower)
function falsyBouncer1(array){
let newArr = []
for(element of array){ if(element){ newArr.push(element) } } return newArr }
falsyBouncer([1, ‘hello’, false, 0, ‘’, true])
console.log([1, ‘hello’, true])
- Return the lowest index at which a value (second argument) i.e num should be inserted into an array (first argument) i.e arr once it has been sorted. The returned value should be a number.
(sort array; initialise position = 0; loop over sorted array, if num > sortedArray[i], position++; return position)
function whereIBelong1(array, num){
let position = 0
let sortedArr = array.sort((a, b) => a - b)
for(let i = 0; i < sortedArr.length; i++){ if(num > sortedArr[i]){ position++ } } return position }
console.log(whereIBelong([12, 2, 31, 104, 50], 6))
- Return the first element from the given array that passes the test specified by the provided function. Both the array and function are passed into the function as arguments as shown below:
function arrayFilter1(arr, func){
for(let elem of arr){
if(func(elem)){
return elem
}
}
return undefined
}
arrayFilter1([1, 2, 3, 4], (v) => v % 2 === 0
// console.log(2)