Exercises Flashcards
const DIGITS = [‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’];
function integerToString(number) {
let result = ‘’;
do {
let remainder = number % 10;
number = Math.floor(number / 10);
result = DIGITS[remainder] + result; } while (number > 0);
return result;
}
Q
function hexadecimalToIntegers(inputString) {
console.log(parseInt(inputString, 16));
}
An Array of Numbers
The previous way with numbers
or
function digitList(number) {
let numberStringArray = String(number).split(“”);
let numberArray = [];
return numberArray.map(x => number(x));
}
Try with and without date object
https://launchschool.com/exercises/a8ee10fc
console.log(timeOfDay(0));
console.log(timeOfDay(-3));
console.log(timeOfDay(35));
console.log(timeOfDay(-1437));
console.log(timeOfDay(3000));
console.log(timeOfDay(800));
console.log(timeOfDay(-4231));
Without:
function timeOfDay(minSinceMidnight) {
const MINUTES_PER_HOUR = 60;
const HOURS_PER_DAY = 24;
let minSinceLastMidnight = minSinceMidnight
% (MINUTES_PER_HOUR * HOURS_PER_DAY);
if (Math.sign(minSinceLastMidnight) === -1) {
minSinceLastMidnight =
(HOURS_PER_DAY * MINUTES_PER_HOUR) + minSinceLastMidnight;
}
let hours = Math.floor(minSinceLastMidnight / 60);
let minutes = minSinceLastMidnight % 60;
console.log(String(hours).padStart(2, ‘0’) + ‘:’ + String(minutes).padStart(2, ‘0’));
return String(hours).padStart(2, ‘0’) + ‘:’ + String(minutes).padStart(2, ‘0’);
}
Q
with date object:
const MS_PER_SECOND = 1000;
const SECONDS_PER_MINUTE = 60;
const msSinceMidnight = minutesSinceMidnight *
(MS_PER_SECOND * SECONDS_PER_MINUTE);
let timeAtMidnight = new Date(‘2020-01-01’);
let timeSinceMidnight = new Date(timeAtMidnight.getTime() + msSinceMidnight);
let hours = String(timeSinceMidnight.getUTCHours()).padStart(2, ‘0’);
let minutes = String(timeSinceMidnight.getUTCMinutes()).padStart(2, ‘0’);
console.log( hours + ‘:’ + minutes);
return hours + ‘:’ + minutes;
Don’t use push/pop
Try it with just index assignment
function reverse(array) {
let leftIndex = 0;
let rightIndex = array.length - 1;
while (leftIndex < array.length / 2) {
[array[leftIndex], array[rightIndex]] =
[array[rightIndex], array[leftIndex]];
leftIndex += 1;
rightIndex -= 1;
}
return array;
}
Try using Regex for the case identification
function letterCaseCount(string) {
let lowercaseChars = string.match(/[a-z]/g) || [];
let uppercaseChars = string.match(/[A-Z]/g) || [];
let neitherChars = string.match(/[^a-z]/gi) || [];
return {
lowercase: lowercaseChars.length,
uppercase: uppercaseChars.length,
neither: neitherChars.length
};
}
In the second solution, we use regular expressions to count each of the three types of characters. If you are not familiar with regular expression, here’s a brief explanation of the patterns we use:
/[a-z]/g : Checks whether the character is a lowercase letter between ‘a’ and ‘z’.
/[A-Z]/g : Checks whether the character is an uppercase letter between ‘A’ and ‘Z’.
/[^a-z]/gi : Checks whether the character is neither an uppercase nor a lowercase letter.
g : Tells the regex engine to search the entire string.
i : Tells the regex engine to ignore case.
Try using:
- charcode to convert to number
- calculation based “concatenation”
- stepwise based “concatenation”
(stepwise based “concatenation”)
Highlight sed with SED
const text = ‘Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Sed quis autem vel est, iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur blasedbla?’;
searchWord(‘sed’, text);
// returns
// “SED ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, SED quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, SED quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? SED quis autem vel est, iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur blasedbla?”
function searchWord(word, text) {
let regex = new RegExp(\\b${word}\\b
, “gi”);
return text.replace(regex, **${word.toUpperCase()}**
);
}
Make this work:
minilang(‘PRINT’);
// 0
minilang(‘5 PUSH 3 MULT PRINT’);
// 15
minilang(‘5 PRINT PUSH 3 PRINT ADD PRINT’);
// 5
// 3
// 8
minilang(‘5 PUSH POP PRINT’);
// 5
minilang(‘3 PUSH 4 PUSH 5 PUSH PRINT ADD PRINT POP PRINT ADD PRINT’);
// 5
// 10
// 4
// 7
minilang(‘3 PUSH PUSH 7 DIV MULT PRINT’);
// 6
minilang(‘4 PUSH PUSH 7 REMAINDER MULT PRINT’);
// 12
minilang(‘-3 PUSH 5 SUB PRINT’);
// 8
minilang(‘6 PUSH’);
// (nothing is printed because the program
argument has no PRINT
commands)
function minilang(program) {
let stack = [];
let register = 0;
program.split(“ “).forEach(token => {
switch (token) {
case “ADD”:
register += stack.pop();
break;
case “DIV”:
register = Math.floor(register / stack.pop());
break;
case “MULT”:
register *= stack.pop();
break;
case “REMAINDER”:
register = Math.floor(register % stack.pop());
break;
case “SUB”:
register -= stack.pop();
break;
case “PUSH”:
stack.push(register);
break;
case “POP”:
register = stack.pop();
break;
case “PRINT”:
console.log(register);
break;
default:
register = Number(token);
}
});
return register;
}
Write an equation that gives the digit in a Fibonacci sequence of a number of a given length (hint you don’t have to use an array to store the sequence)
findFibonacciIndexByLength(2n) === 7n; // 1 1 2 3 5 8 13
findFibonacciIndexByLength(3n) === 12n; // 1 1 2 3 5 8 13 21 34 55 89 144
findFibonacciIndexByLength(10n) === 45n;
findFibonacciIndexByLength(16n) === 74n;
findFibonacciIndexByLength(100n) === 476n;
findFibonacciIndexByLength(1000n) === 4782n;
findFibonacciIndexByLength(10000n) === 47847n;
// The last example may take a minute to run.
function findFibonacciIndexByLength(length) {
let first = 1n;
let second = 1n;
let count = 2n;
let fibonacci;
do {
fibonacci = first + second;
count += 1n;
first = second;
second = fibonacci;
} while (String(fibonacci).length < length);
return count;
}
Write a Fibonacci sequence equation with just a regular loop (hint don’t need a “storecurrent” variable)
function fibonacci(nth) {
let previousTwo = [1, 1];
for (let counter = 3; counter <= nth; counter += 1) {
previousTwo = [previousTwo[1], previousTwo[0] + previousTwo[1]];
}
return previousTwo[1];
}
Write a Fibonacci sequence equation with a recursive function.
Then write a Fibonacci sequence with a memory component so it doesn’t have to calculate the same thing multiple times. It checks whether the calcuation has already been done.
With memory:
let memo = {};
function fibonacci(nth) {
if (nth <= 2) {
return 1;
} else if (memo[nth]) {
return memo[nth];
} else {
memo[nth] = fibonacci(nth - 1) + fibonacci(nth - 2);
return memo[nth];
}
}
letterPercentages(‘abCdef 123’);
// { lowercase: “50.00”, uppercase: “10.00”, neither: “40.00” }
letterPercentages(‘AbCd +Ef’);
// { lowercase: “37.50”, uppercase: “37.50”, neither: “25.00” }
letterPercentages(‘123’);
// { lowercase: “0.00”, uppercase: “0.00”, neither: “100.00” }
https://launchschool.com/exercises/71983fb9
function letterPercentages(string) {
let count = string.length;
return {
lowercase: (((string.match(/[a-z]/g) || []).length / count) * 100).toFixed(
2
),
uppercase: (((string.match(/[A-Z]/g) || []).length / count) * 100).toFixed(
2
),
neither: (((string.match(/[^a-z]/gi) || []).length / count) * 100).toFixed(
2
)
};
}
fridayThe13ths(1986); // 1
fridayThe13ths(2015); // 3
fridayThe13ths(2017); // 2
https://launchschool.com/exercises/071f5a1a
function fridayThe13ths(year) {
let thirteenths = [];
for (let month = 0; month < 12; month += 1) {
thirteenths.push(new Date(year, month, 13));
}
return thirteenths.reduce((count, day) => {
return day.getDay() === 5 ? (count + 1) : count;
}, 0);
}