Scotch.io Flashcards

1
Q
  1. 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

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’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
  1. 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++)

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
  1. 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)

A

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’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
  1. 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(‘ ‘))

A

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!’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q
  1. 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))

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q
  1. 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++)

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q
  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)

A

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’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q
  1. 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)

A

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’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q
  1. 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)

A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q
  1. 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’)

A

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’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q
  1. 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)

A

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]])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q
  1. 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)

A

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]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q
  1. 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)

A

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])

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q
  1. 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)

A

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))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q
  1. 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:
A

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)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q
  1. Given an integer, return an integer that has the reverse ordering of that which was received.
A

function reverseString(text){
return […text].reduce((acc, c) => c + acc, ‘’)
}

function reverseInteger(num){
let reversedInteger = parseInt(reverseString(num.toString()))

return reversedInteger * Math.sign(num) }

reverseInteger(-123)
// console.log(-321)

17
Q
  1. Given an array of two numbers, return the cumulative sum of the two numbers and all the numbers between them
A

function rangeSum1(arr){
let sum = 0
for(let i = arr[0]; i <= arr[1]; i++){
sum += i
}
return sum
}

rangeSum1([1,9])
// console.log(45)