Exercises Flashcards

1
Q
A

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;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Q

A

function hexadecimalToIntegers(inputString) {
console.log(parseInt(inputString, 16));
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

An Array of Numbers

A

The previous way with numbers
or

function digitList(number) {
let numberStringArray = String(number).split(“”);
let numberArray = [];

return numberArray.map(x => number(x));
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

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

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Q

A

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;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Don’t use push/pop
Try it with just index assignment

A

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;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Try using Regex for the case identification

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Try using:
- charcode to convert to number
- calculation based “concatenation”
- stepwise based “concatenation”

A

(stepwise based “concatenation”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

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?”

A

function searchWord(word, text) {
let regex = new RegExp(\\b${word}\\b, “gi”);
return text.replace(regex, **${word.toUpperCase()}**);
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

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)

A

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;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

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.

A

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;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Write a Fibonacci sequence equation with just a regular loop (hint don’t need a “storecurrent” variable)

A

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];
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

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.

A

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];
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

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

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

fridayThe13ths(1986); // 1
fridayThe13ths(2015); // 3
fridayThe13ths(2017); // 2
https://launchschool.com/exercises/071f5a1a

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

triangle(60, 70, 50); // “acute”
triangle(30, 90, 60); // “right”
triangle(120, 50, 10); // “obtuse”
triangle(0, 90, 90); // “invalid”
triangle(50, 50, 50); // “invalid”

A

function triangle(angle1, angle2, angle3) {
const angles = [angle1, angle2, angle3];
if (isValid(angles)) {
return getTriangleType(angles);
} else {
return “invalid”;
}
}

function isValid(angles) {
const totalAngle = angles.reduce((total, angle) => total + angle);

const allNonZero = angles.every(angle => angle > 0);

return totalAngle === 180 && allNonZero;
}

function getTriangleType(angles) {
if (angles.some(testRightTriangle)) {
return “right”;
} else if (angles.every(testAcuteTriangle)) {
return “acute”;
} else {
return “obtuse”;
}
}

function testRightTriangle(angle) {
return angle === 90;
}

function testAcuteTriangle(angle) {
return angle < 90;
}

17
Q

featured(12); // 21
featured(20); // 21
featured(21); // 35
featured(997); // 1029
featured(1029); // 1043
featured(999999); // 1023547
featured(999999987); // 1023456987
featured(9876543186); // 9876543201
featured(9876543200); // 9876543201
featured(9876543201); // “There is no possible number that fulfills those requirements.”

A

function featured(number) {
const MAX_FEATURED = 9876543201;
let featuredNum = toOddMultipleOf7(number);

do {
if (allUnique(featuredNum)) {
return featuredNum;
}

featuredNum += 14;   } while (featuredNum <= MAX_FEATURED);

return ‘There is no possible number that fulfills those requirements.’;
}

function toOddMultipleOf7(number) {
do {
number += 1;
} while (number % 2 === 0 || number % 7 !== 0);

return number;
}

function allUnique(number) {
let digits = String(number).split(‘’);
let seen = {};

for (let idx = 0; idx < digits.length; idx += 1) {
if (seen[digits[idx]]) {
return false;
}

seen[digits[idx]] = true;   }

return true;
}

18
Q

console.log(sumSquareDifference(3)); // 22 –> (1 + 2 + 3)2 - (12 + 22 + 32)
console.log(sumSquareDifference(10)); // 2640
console.log(sumSquareDifference(1)); // 0
console.log(sumSquareDifference(100)); // 25164150

A

console.log(sumSquareDifference(3)); // 22 –> (1 + 2 + 3)2 - (12 + 22 + 32)
console.log(sumSquareDifference(10)); // 2640
console.log(sumSquareDifference(1)); // 0
console.log(sumSquareDifference(100)); // 25164150

function sumSquareDifference(number) {
return sumOfSequenceSquared(number) - sequenceSquaresSummed(number);
}

function sumOfSequenceSquared(number) {
if (number <= 1) {
return number;
} else {
return (number ** 3) + sumOfSequenceSquared(number - 1);
}
}

function sequenceSquaresSummed(number) {
if (number <= 1) {
return number;
} else {
return (number ** 2) + sequenceSquaresSummed(number - 1);
}
}

19
Q

Write a program that prints the longest sentence in a string based on the number of words. Sentences may end with periods (.), exclamation points (!), or question marks (?). You should treat any sequence of characters that are not spaces or sentence-ending characters as a word. Thus, – should count as a word. Log the longest sentence and its word count to the console. Pay attention to the expected output, and be sure you preserve the punctuation from the end of the sentence. Note that this problem is about manipulating and processing strings. As such, every detail about the string matters (e.g., case, punctuation, tabs, spaces, etc.).

Here for copyable stuff:
https://launchschool.com/exercises/a89915a7

A

let sentences = text.match(/\w.*?[.!?]/g);

let longest = sentences.reduce(
function(longest, sentence) {
let length = sentence.split(/\s/).length;
if (length > longest.length) {
return { text: sentence, length: length };
} else {
return longest;
}
},
{ text: “”, length: 0 }
);

console.log(longest.text + “\n”);
console.log(“The longest sentence has “ + longest.length + “ words.\n”);
}

20
Q

https://launchschool.com/exercises/d219156d
B:O X:K D:Q C:P N:A
G:T R:E F:S J:W H:U
V:I L:Y Z:M

Try it with regular expressions where the blocks are regular expressions.
isBlockWord(‘BATCH’); // true
isBlockWord(‘BUTCH’); // false
isBlockWord(‘jest’); // true

A

function isBlockWord(word) {
let blocks = [‘BO’, ‘XK’, ‘DQ’, ‘CP’, ‘NA’, ‘GT’, ‘RE’, ‘FS’, ‘JW’, ‘HU’, ‘VI’, ‘LY’, ‘ZM’];
let letters = word.split(“”);

for (let index = 0; index < letters.length; index += 1) {
let matchingBlock = blocks.filter(block => {
return block.indexOf(letters[index].toUpperCase()) > -1;
})[0];

if (matchingBlock === undefined) {
  return false;
} else {
  blocks.splice(blocks.indexOf(matchingBlock), 1);
}   }

return true;
}

21
Q

https://launchschool.com/exercises/02297071
diamond(9);
// logs
*
*
***
**
*
***
**
*
****
**

*

A

function diamond(n) {
numberSequence(n).forEach(number => {
console.log(${" ".repeat((n - number) / 2)}${"*".repeat(number)});
});
}

function numberSequence(n) {
let result = [];
let increment = 2;
let number = 1;

while (number > 0) {
result.push(number);
if (number === n) {
increment = -2;
}
number += increment;
}

return result;
}

22
Q

Get every consecutive combination of [1, 2, 3]

like:
1, 12, 13, 2, 23, 3

A

for (let startingIndex = 0; startingIndex < integerString.length; startingIndex++) {
for (let endIndex = startingIndex + 1; endIndex <= integerString.length; endIndex++) {
combinationsArray.push(+integerString.slice(startingIndex, endIndex));
}
}