Skip to content

elementary algorithm JavaScript solutions added #86

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions elementaryAlgo/alternateCap.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Write a function `alternatingCaps` that accepts a sentence string as an argument. The function should
// return the sentence where words alternate between lowercase and uppercase.
const alternatingCaps = (words) => {
let result = "";
let arraySplit = words.split(" ");
for (let i = 0; i < arraySplit.length; i++) {
let word = arraySplit[i];
if (i % 2 === 0) {
result += word.toLowerCase() + " ";
} else {
result += word.toUpperCase() + " ";
}
}
return result;
};
console.log(alternatingCaps("take them to school")); // 'take THEM to SCHOOL'
console.log(alternatingCaps("What did ThEy EAT before?")); // 'what DID they EAT before?'
19 changes: 19 additions & 0 deletions elementaryAlgo/bleepVowels.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Write a function `bleepVowels` that accepts a string as an argument. The function should return
// a new string where all vowels are replaced with `*`s. Vowels are the letters a, e, i, o, u.
function bleepVowels(str) {
let array = ["a", "e", "i", "o", "u"];
let result = "";
for (let i = 0; i < str.length; i++) {
let char = str[i];
if (array.indexOf(char) > -1) {
result += "*";
} else {
result += char;
}
}
return result;
}
console.log(bleepVowels("skateboard")); // 'sk*t*b**rd'
console.log(bleepVowels("slipper")); // 'sl*pp*r'
console.log(bleepVowels("range")); // 'r*ng*'
console.log(bleepVowels("brisk morning")); // 'br*sk m*rn*ng'
16 changes: 16 additions & 0 deletions elementaryAlgo/chooseDivisible.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Write a function `chooseDivisibles(numbers, target)` that accepts an array of numbers and a
// target number as arguments. The function should return an array containing elements of the original
// array that are divisible by the target.
const chooseDivisibles = (numbers, target) => {
let result = [];
for (let i = 0; i < numbers.length; i++) {
let num = numbers[i];
if (num % target === 0) {
result.push(num);
}
}
return result;
};
console.log(chooseDivisibles([40, 7, 22, 20, 24], 4)); // [40, 20, 24]
console.log(chooseDivisibles([9, 33, 8, 17], 3)); // [9, 33]
console.log(chooseDivisibles([4, 25, 1000], 10)); // [1000]
21 changes: 21 additions & 0 deletions elementaryAlgo/commonElement.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Write a function `commonElements` that accepts two arrays as arguments. The function should return
// a new array containing the elements that are found in both of the input arrays. The order of
// the elements in the output array doesn't matter as long as the function returns the correct elements.
const commonElements = (array1, array2) => {
let result = [];
let set1 = new Set(array1);
let set2 = new Set(array2);
for (let elem of set1) {
if (set2.has(elem)) {
result.push(elem);
}
}
return result;
};
let arr1 = ["a", "c", "d", "b"];
let arr2 = ["b", "a", "y"];
console.log(commonElements(arr1, arr2)); // ['a', 'b']

let arr3 = [4, 7];
let arr4 = [32, 7, 1, 4];
console.log(commonElements(arr3, arr4)); // [4, 7]
15 changes: 15 additions & 0 deletions elementaryAlgo/divisors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Write a function `divisors` that accepts a number as an argument. The function should return an
// array containing all positive numbers that can divide into the argument.
function divisors(num) {
let result = [];
for (let i = 1; i <= num; i++) {
let eachNum = i;
if (num % eachNum === 0) {
result.push(eachNum);
}
}
return result;
}
console.log(divisors(15)); // [1, 3, 5, 15]
console.log(divisors(7)); // [1, 7]
console.log(divisors(24)); // [1, 2, 3, 4, 6, 8, 12, 24]
17 changes: 17 additions & 0 deletions elementaryAlgo/filterLongWords.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Write a function `filterLongWords` that accepts an array of strings as an argument. The function
// should return a new array containing only the strings that are less than 5 characters long.
function filterLongWords(array) {
let result = [];
for (let i = 0; i < array.length; i++) {
let word = array[i];
if (word.length < 5) {
result.push(word);
}
}
return result;
}
console.log(filterLongWords(["kale", "cat", "retro", "axe", "heirloom"]));
// ['kale', 'cat', 'axe']

console.log(filterLongWords(["disrupt", "pour", "trade", "pic"]));
// ['pour', 'pic']
18 changes: 18 additions & 0 deletions elementaryAlgo/lengthiestWord.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Write a function `lengthiestWord` that accepts a sentence string as an argument. The function should
// return the longest word of the sentence. If there is a tie, return the word that appears later
// in the sentence.
const lengthiestWord = (words) => {
let arrayWord = words.split(" ");
let lengthiest = arrayWord[0];
for (let i = 1; i < arrayWord.length; i++) {
let word = arrayWord[i];
if (lengthiest.length <= word.length) {
lengthiest = word;
}
}
return lengthiest;
};
console.log(lengthiestWord("I am pretty hungry")); // 'hungry'
console.log(lengthiestWord("we should think outside of the box")); // 'outside'
console.log(lengthiestWord("down the rabbit hole")); // 'rabbit'
console.log(lengthiestWord("simmer down")); // 'simmer'
15 changes: 15 additions & 0 deletions elementaryAlgo/makeAcronyms.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Write a function `makeAcronym` that accepts a sentence string as an argument. The function should
// return a string containing the first character of each word in the sentence.
const makeAcronym = (words) => {
let arrayWord = words.split(" ");
let result = "";
for (let i = 0; i < arrayWord.length; i++) {
let word = arrayWord[i][0];
result += word.toUpperCase();
}
return result;
};
console.log(makeAcronym("New York")); // NY
console.log(makeAcronym("same stuff different day")); // SSDD
console.log(makeAcronym("Laugh out loud")); // LOL
console.log(makeAcronym("don't over think stuff")); // DOTS
37 changes: 37 additions & 0 deletions elementaryAlgo/makeMatrix.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Write a function `makeMatrix(m, n, value)` that accepts three arguments. The function should return
// a 2-dimensional array of height `m` and width `n` that contains the `value` as every element.
const makeMatrix = (m, n, value) => {
let matrix = [];
for (let i = 0; i < m; i++) {
let row = [];
for (let j = 0; j < n; j++) {
row.push(value);
}
matrix.push(row);
}
return matrix;
};
// const makeMatrix = (m, n, value) => {
// let matrix = Array.from(Array(m), () => Array(n).fill(value));
// return matrix
// };
console.log(makeMatrix(3, 5, null));
// [
// [ null, null, null, null, null ],
// [ null, null, null, null, null ],
// [ null, null, null, null, null ]
// ]

console.log(makeMatrix(4, 2, "x"));
// [
// [ 'x', 'x' ],
// [ 'x', 'x' ],
// [ 'x', 'x' ],
// [ 'x', 'x' ]
// ]

console.log(makeMatrix(2, 2, 0));
// [
// [ 0, 0 ],
// [ 0, 0 ]
// ]
14 changes: 14 additions & 0 deletions elementaryAlgo/maximum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Write a function `maximum` that accepts an array of numbers as an argument. The function should
// return the largest number of the array. If the array is empty, then the function should return null.
const maximum = (array) => {
if (array.length === 0) return null;
let max = array[0];
for (let i = 1; i < array.length; i++) {
let elem = array[i];
max = Math.max(max, elem);
}
return max;
};
console.log(maximum([5, 6, 3, 7])); // 7
console.log(maximum([17, 15, 19, 11, 2])); // 19
console.log(maximum([])); // null
13 changes: 13 additions & 0 deletions elementaryAlgo/numOdd.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Write a function `numOdds` that accepts an array of numbers as an argument. The function should
// return a number representing the count of odd elements in the array.
function numOdds(array) {
let count = 0;
for (let i = 0; i < array.length; i++) {
let num = array[i];
if (num % 2 === 1) count++;
}
return count;
}
console.log(numOdds([4, 7, 2, 5, 9])); // 3
console.log(numOdds([11, 31, 58, 99, 21, 60])); // 4
console.log(numOdds([100, 40, 4])); // 0
13 changes: 13 additions & 0 deletions elementaryAlgo/numberRange.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Write a function `numberRange(min, max, step)` that accepts three numbers as arguments, `min`,
// `max`, and `step`. The function should return all numbers between `min` and `max` at `step` intervals.
// `min` and `max` are inclusive.
const numberRange = (min, max, step) => {
let result = [];
for (let i = min; i <= max; i += step) {
result.push(i);
}
return result;
};
console.log(numberRange(10, 40, 5)); // [10, 15, 20, 25, 30, 35, 40]
console.log(numberRange(14, 24, 3)); // [14, 17, 20, 23]
console.log(numberRange(8, 35, 6)); // [8, 14, 20, 26, 32]
26 changes: 26 additions & 0 deletions elementaryAlgo/pairPrint.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Write a function `pairPrint` that accepts an array as an argument. The function should print
// all unique pairs of elements in the array. The function doesn't need to return any value. It
// should just print to the terminal.
function pairPrint(arr) {
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
console.log(arr[i], arr[j]);
}
}
}


pairPrint(["artichoke", "broccoli", "carrot", "daikon"]);
// prints
// artichoke - broccoli
// artichoke - carrot
// artichoke - daikon
// broccoli - carrot
// broccoli - daikon
// carrot - daikon

//pairPrint(["apple", "banana", "clementine"]);
// prints
// apple - banana
// apple - clementine
// banana - clementine
36 changes: 36 additions & 0 deletions elementaryAlgo/print2d.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Write a function `print2d` that accepts a two-dimensional array as an argument. The function
// should print all inner elements of the array.
const print2d = (array) => {
for (let i = 0; i < array.length; i++) {
let innerElem = array[i];
for (let j = 0; j < innerElem.length; j++) {
console.log(innerElem[j]);
}
}
};
let array1 = [
["a", "b", "c", "d"],
["e", "f"],
["g", "h", "i"],
];
print2d(array1);
// prints
// a
// b
// c
// d
// e
// f
// g
// h
// i

let array2 = [[9, 3, 4], [11], [42, 100]];
print2d(array2);
// prints
// 9
// 3
// 4
// 11
// 42
// 100
32 changes: 32 additions & 0 deletions elementaryAlgo/printCombination.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Write a function `printCombinations`that accepts two arrays as arguments. The function should
// print all combinations of the elements generated by taking an element from the first array and
// and an element from the second array. The function doesn't need to return any value. It
// should just print to the terminal.
function printCombinations(array1, array2) {
for (let i = 0; i < array1.length; i++) {
const element1 = array1[i];
for (let j = 0; j < array2.length; j++) {
let element2 = array2[j];
console.log(element1, element2);
}
}
}

let colors = ["gray", "cream", "cyan"];
let clothes = ["shirt", "flannel"];

printCombinations(colors, clothes);
// prints
// gray shirt
// gray flannel
// cream shirt
// cream flannel
// cyan shirt
// cyan flannel

//printCombinations(["hot", "cold"], ["soup", "tea"]);
// prints
// hot soup
// hot tea
// cold soup
// cold tea
20 changes: 20 additions & 0 deletions elementaryAlgo/recursionArray.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
//Given an array of integers, write a function that return the sum all of it element using recursion
const sum = (array) => {
if (array.length === 0) return 0;
let rest = array.slice(1);
return array[0] + sum(rest);
};
console.log(sum([2, 5, 6, 8, 9]));
//Time: O(n^2)
//Space: O(n)
// can improve our space complexity like this
const sumImprove = (array) => {
return _sum(array, 0);
};
const _sum = (array, idx) => {
if (array.length === idx) return 0;
return array[idx] + _sum(array, idx + 1);
};
console.log(sumImprove([2, 5, 6, 8, 9]));
//Time: O(n)
//Space: O(n)
18 changes: 18 additions & 0 deletions elementaryAlgo/removeFirstVowel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Write a function `removeFirstVowel` that accepts a string as an argument. The function should return
// the string with it's first vowel removed.
const removeFirstVowel = (words) => {
let vowels = ["a", "e", "i", "o", "u"];
for (let i = 0; i < words.length; i++) {
let word = words[i];
if (vowels.includes(word)) {
let copy = words.split("");
copy.splice(i, 1);
return copy.join("");
}
}
return words;
};
console.log(removeFirstVowel("volcano")); // 'vlcano'
console.log(removeFirstVowel("celery")); // 'clery'
console.log(removeFirstVowel("juice")); // 'jice'
console.log(removeFirstVowel("ghshsh"));
15 changes: 15 additions & 0 deletions elementaryAlgo/removeShortWords.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Write a function `removeShortWords` that accepts a sentence string as an argument. The function
// should return a new sentence where all of the words shorter than 4 characters are removed.
const removeShortWords = (words) => {
let result = "";
let arrayWords = words.split(" ");
for (let i = 0; i < arrayWords.length; i++) {
let word = arrayWords[i];
if (word.length < 4) continue;
else result += word + " ";
}
return result;
};
console.log(removeShortWords("knock on the door will you")); // 'knock door will'
console.log(removeShortWords("a terrible plan")); // 'terrible plan'
console.log(removeShortWords("run faster that way")); // 'faster that'
12 changes: 12 additions & 0 deletions elementaryAlgo/reverseArray.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Write a function `reverseArray` that accepts an array as an argument. The function should return a
// array containing the elements of the original array in reverse order.
const reverseArray = (array) => {
let result = [];
for (let i = array.length - 1; i >= 0; i--) {
let element = array[i];
result.push(element);
}
return result;
};
console.log(reverseArray(["zero", "one", "two", "three"])); // ['three', 'two', 'one', 'zero']
console.log(reverseArray([7, 1, 8])); // [8, 1, 7]
Loading