Skip to content

Commit 0b04869

Browse files
author
koalamango
committed
initial commit
1 parent 4ee785d commit 0b04869

13 files changed

+344
-2
lines changed

.gitignore

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
.DS_Store
4+
.env*
5+
.idea/
6+

README.md

+97-2
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,97 @@
1-
# javascript-algorithms
2-
✨ Algorithms in JavaScript
1+
# Common Algorithms in JavaScript
2+
3+
4+
#### What's an algorithm?
5+
6+
> An algorithm is a set of instruction to solve problems.
7+
8+
Still confused? [Watch the video](https://www.youtube.com/watch?v=6hfOvs8pY1k)
9+
of Professor David J. Malan explains how algorithms can be used in seemingly
10+
simple situations and also complex ones.
11+
12+
#### List of common algorithms
13+
14+
* [Fizz Buzz](src/fizzbuzz.js)
15+
16+
Fizz-Buzz is a group word game for children to teach them about division.
17+
Players take turns to count incrementally, replacing any multiple of three
18+
with the word "fizz", and any multiple of five with the word "buzz".
19+
20+
* [Two Sum](src/TwoSum.js)
21+
22+
You are given an array of n integers and a number k. Determine whether there is a pair
23+
of elements in the array that sums to exactly k. For example, given the array [1, 3, 7] and
24+
k = 8, the answer is "yes" but given k = 6 the answer is "no"
25+
26+
* [Harmless Ransom Note](src/HarmlessRansomNote.js)
27+
28+
The harmless ransom note is simply a note made of words cut out from a magazine text.
29+
30+
You have been given two strings. You have to find out whether you can make up the
31+
first string with the words present in the second string.
32+
33+
* [Is Palindrome](src/IsPalindrome.js)
34+
35+
A palindrome is a word, phrase, number or sequence of words that reads the same backward
36+
as forward. Punctuation and spaces between the words or lettering is allowed.
37+
38+
* [Caesar Cipher](src/CaesarCipher.js)
39+
40+
Caesar cipher is to replace each plaintext letter with a different one a fixed number of
41+
places down the alphabet. The cipher illustrated here uses a left shift of three, so that
42+
(for example) each occurrence of E in the plaintext becomes B in the ciphertext.
43+
44+
* [Reverse Words](src/ReverseWords.js)
45+
46+
Reverse the string without using array.prototype.reverse().
47+
48+
* [Reverse Array In Place](src/ReverseArrayInPlace.js)
49+
50+
Reverse the order of the elements of an array.
51+
52+
* [Mean Median Mode](src/MeanMedianMode.js)
53+
54+
Calculate the mean, median, or mode of a data set!
55+
56+
* [Fibonacci](src/Fibonacci.js)
57+
58+
The Fibonacci Sequence is the series of numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, . . .
59+
Each subsequent number is the sum of the previous two.
60+
61+
Write a function to return an n element in Fibonacci sequence
62+
63+
* [Sieve of Eratosthenes](src/SieveOfEratosthenes.js)
64+
65+
In mathematics, the sieve of Eratosthenes is an ancient algorithm for finding all prime
66+
numbers up to any given limit. It does so by iteratively marking as composite (i.e.,
67+
not prime) the multiples of each prime, starting with the first prime number, 2.
68+
69+
Given a number n, print all primes smaller than or equal to n. It is also given that n
70+
is a small number.
71+
72+
* [Max Stock Profit](src/MaxStockProfit.js)
73+
74+
Given an array of stock prices over time, need to figure out the best buy and sell price
75+
so that we get the maximum profit. The selling should occur after buying of the stock.
76+
77+
78+
* Plurality (winner take all)
79+
80+
In the plurality vote, every voter gets to vote for one candidate. At the end
81+
of the election, whichever candidate has the greatest number of votes is
82+
declared the winner of the election.
83+
84+
* Runoff
85+
86+
In a ranked-choice system, voters can vote for more than one candidate. Instead
87+
of just voting for their top choice, they can rank the candidates in order of
88+
preference.
89+
90+
* Readability
91+
* Liner Search
92+
* Binary Search
93+
* Bubble Sort
94+
* Selection Sort
95+
* Insertion Sort
96+
* Recursion
97+
* Merge Sort

src/CaesarCipher.js

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
function caesarCipher(str,num) {
2+
num = num % 26;
3+
var lowerCaseString = str.toLowerCase();
4+
var alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('');
5+
var newString = '';
6+
7+
for (var i = 0; i < lowerCaseString.length; i++) {
8+
var currentLetter = lowerCaseString[i];
9+
if (currentLetter === ' ') {
10+
newString += currentLetter;
11+
continue;
12+
}
13+
var currentIndex = alphabet.indexOf(currentLetter);
14+
var newIndex = currentIndex + num;
15+
if (newIndex > 25) newIndex = newIndex - 26;
16+
if (newIndex < 0) newIndex = 26 + newIndex;
17+
if (str[i] === str[i].toUpperCase()) {
18+
newString += alphabet[newIndex].toUpperCase();
19+
}
20+
else newString += alphabet[newIndex];
21+
};
22+
23+
return newString;
24+
}
25+
caesarCipher('Sunny Day', 2);

src/Fibonacci.js

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
function fibonacci(index, cache) {
2+
cache = cache || [];
3+
if (cache[index]) return cache[index];
4+
else {
5+
if (index < 3) return 1;
6+
else {
7+
cache[index] = fibonacci(index - 1, cache) + fibonacci(index - 2, cache);
8+
}
9+
}
10+
return cache[index];
11+
}
12+
13+
fibonacci(500);

src/HarmlessRansomNote.js

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
function harmlessRansomNote(noteText, magazineText) {
2+
var noteArr = noteText.split(' ');
3+
var magazineArr = magazineText.split(' ');
4+
var magazineObj = {};
5+
6+
magazineArr.forEach(word => {
7+
if (!magazineObj[word]) magazineObj[word] = 0;
8+
magazineObj[word]++;
9+
});
10+
11+
var noteIsPossible = true;
12+
noteArr.forEach(word => {
13+
if (magazineObj[word]) {
14+
magazineObj[word]--;
15+
if (magazineObj[word] < 0) noteIsPossible = false;
16+
}
17+
else noteIsPossible = false;
18+
});
19+
20+
return noteIsPossible;
21+
}
22+
23+
harmlessRansomNote('Here is the secret message');

src/IsPalindrome.js

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
function isPalindrome(string) {
2+
string = string.toLowerCase();
3+
var charactersArr = string.split('');
4+
var validCharacters = 'abcdefghijklmnopqrstuvwxyz'.split('');
5+
6+
var lettersArr = [];
7+
charactersArr.forEach(char => {
8+
if (validCharacters.indexOf(char) > -1) lettersArr.push(char);
9+
});
10+
11+
return lettersArr.join('') === lettersArr.reverse().join('');
12+
}
13+
14+
isPalindrome("Madam, I'm Adam");

src/MaxStockProfit.js

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
function maxStockProfit (pricesArr) {
2+
var maxProfit = -1;
3+
var buyPrice = 0;
4+
var sellPrice = 0;
5+
6+
var changeBuyPrice = true;
7+
8+
for (var i = 0; i < pricesArr.length; i++) {
9+
if (changeBuyPrice) buyPrice = pricesArr[i];
10+
sellPrice = pricesArr[i + 1];
11+
12+
if (sellPrice < buyPrice) {
13+
changeBuyPrice = true;
14+
}
15+
else {
16+
var tempProfit = sellPrice - buyPrice;
17+
if (tempProfit > maxProfit) maxProfit = tempProfit;
18+
changeBuyPrice = false;
19+
}
20+
}
21+
22+
return maxProfit;
23+
}
24+
25+
maxStockProfit([10, 18, 4, 5, 9, 6, 16, 12]);

src/MeanMedianMode.js

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
function meanMedianMode(array) {
2+
return {
3+
mean: getMean(array),
4+
median: getMedian(array),
5+
mode: getMode(array)
6+
}
7+
}
8+
9+
function getMean(array) {
10+
var sum = 0;
11+
12+
array.forEach(num => {
13+
sum += num;
14+
});
15+
16+
var mean = sum / array.length;
17+
return mean;
18+
}
19+
20+
function getMedian(array) {
21+
array.sort(function(a, b){return a-b});
22+
var median;
23+
24+
if (array.length % 2 !== 0) {
25+
median = array[Math.floor(array.length / 2)];
26+
}
27+
else {
28+
var mid1 = array[(array.length / 2) - 1];
29+
var mid2 = array[array.length / 2];
30+
median = (mid1 + mid2) / 2;
31+
}
32+
33+
return median;
34+
}
35+
36+
function getMode(array) {
37+
var modeObj = {};
38+
39+
// create modeObj
40+
array.forEach(num => {
41+
if (!modeObj[num]) modeObj[num] = 0;
42+
modeObj[num]++;
43+
});
44+
45+
// create array of mode/s
46+
var maxFrequency = 0;
47+
var modes = [];
48+
for (var num in modeObj) {
49+
if (modeObj[num] > maxFrequency) {
50+
modes = [num];
51+
maxFrequency = modeObj[num];
52+
}
53+
else if (modeObj[num] === maxFrequency) modes.push(num);
54+
}
55+
// if every value appears same amount of times
56+
if (modes.length === Object.keys(modeObj).length) modes = [];
57+
return modes;
58+
}
59+
60+
61+
meanMedianMode([9,10,23,10,23,9]);

src/ReverseArrayInPlace.js

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
function reverseArrayInPlace(arr) {
2+
for (var i = 0; i < arr.length / 2; i++) {
3+
var tempVar = arr[i];
4+
arr[i] = arr[arr.length - 1 - i];
5+
arr[arr.length - 1 - i] = tempVar;
6+
}
7+
8+
return arr;
9+
}
10+
11+
reverseArrayInPlace([1, 2, 3, 4, 5, 6, 7, 8]);

src/ReverseWords.js

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
function reverseWords(string) {
2+
var wordsArr = string.split(' ');
3+
var reversedWordsArr = [];
4+
5+
wordsArr.forEach(word => {
6+
var reversedWord = '';
7+
for (var i = word.length - 1; i >= 0; i--) {
8+
reversedWord += word[i];
9+
};
10+
reversedWordsArr.push(reversedWord);
11+
});
12+
13+
return reversedWordsArr.join(' ');
14+
}
15+
16+
reverseWords('Algorithm in JavaScript');

src/SieveOfEratosthenes.js

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
function sieveOfEratosthenes(n) {
2+
var primes = [];
3+
for (var i = 0; i <= n; i++) {
4+
primes[i] = true;
5+
}
6+
7+
primes[0] = false;
8+
primes[1] = false;
9+
10+
for (var i = 2; i <= Math.sqrt(n); i++) {
11+
for (j = 2; i * j <= n; j++) {
12+
primes[i * j] = false;
13+
}
14+
}
15+
16+
var result = [];
17+
for (var i = 0; i < primes.length; i++) {
18+
if (primes[i]) result.push(i);
19+
}
20+
21+
return result;
22+
}
23+
24+
sieveOfEratosthenes(49);

src/TwoSum.js

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
function twoSum(numArray, sum) {
2+
let pairs = [];
3+
let hashtable = [];
4+
5+
for (let i = 0; i < numArray.length; i++) {
6+
let currNum = numArray[i];
7+
let counterpart = sum - currNum;
8+
if (hashtable.indexOf(counterpart) !== -1) {
9+
pairs.push([currNum, counterpart]);
10+
}
11+
hashtable.push(currNum);
12+
}
13+
14+
return pairs;
15+
}
16+
17+
twoSum([1, 6, 4, 5, 3, 3], 7);
18+
// return [ [ 6, 1 ], [ 3, 4 ], [ 3, 4 ] ]
19+

src/fizzbuzz.js

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
function fizzBuzz(num) {
2+
for (let i = 1; i <= num; i++) {
3+
if (i % 15 === 0) console.log('FizzBuzz');
4+
else if (i % 3 === 0) console.log('Fizz');
5+
else if (i % 5 === 0) console.log('Buzz');
6+
else console.log(i);
7+
}
8+
}
9+
10+
fizzBuzz(30);

0 commit comments

Comments
 (0)