Skip to content

Commit

Permalink
feat: add algorithmes
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrew authored and Skippia committed Dec 19, 2023
1 parent 47cdaa8 commit 0e7706a
Show file tree
Hide file tree
Showing 26 changed files with 765 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
.vite-ssg-temp
*.local
dist
build
dist-ssr
node_modules
.idea/
Expand Down
16 changes: 16 additions & 0 deletions src/algorithmes/basic/binary-search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Binary Search

function binarySearch(array, value) {
let mediumIdx = Math.floor(array.length / 2)
let middleValue = array[mediumIdx]

if (middleValue == value) return value
if (array.length == 1) return null

if (value < middleValue) {
return binarySearch(array.slice(0, mediumIdx), value)
} else if (value > middleValue) {
return binarySearch(array.slice(mediumIdx, array.length), value)
}
}
/* console.log(binarySearch([5, 7, 12, 16, 36, 39, 42, 56, 71], 56)) */
19 changes: 19 additions & 0 deletions src/algorithmes/basic/breadth-search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// BreadthSearch

function breadthSearch(graph, start, end) {
let queue = [start]
while (queue.length > 0) {
let departurePoint = queue.shift()
if (graph[departurePoint].includes(end)) return true
graph[departurePoint].forEach(point => queue.push(point))
}
return false
}
/* const graph = {}
graph.a = ['b']
graph.b = ['c']
graph.c = ['d']
graph.d = ['e']
graph.e = ['d']
graph.f = ['a']
console.log(breadthSearch(graph, 'a', 'e')) */
44 changes: 44 additions & 0 deletions src/algorithmes/basic/fibonacci-memorized.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// Fibonacci Memorized

const store = {}
function fibonacciMemorized(num, store) {
if (num < 2) return 1
if (store[num]) return store[num]
let result = fibonacciMemorized(num - 1, store) + fibonacciMemorized(num - 2, store)
store[num] = result
return result
}
/* console.log(fibonacciMemorized(5, store)) */

function fibonacci(n) {
let fibonacciSum = 0;
const orderFib = [n];
while (orderFib.length > 0) {
const lastFibonacci = orderFib.pop();
if (!lastFibonacci)
continue;
if (lastFibonacci === 0 || lastFibonacci === 1) {
fibonacciSum++;
continue;
}
orderFib.push(lastFibonacci - 2, lastFibonacci - 1);
}
return fibonacciSum;
}
function cacheDecorator(fn) {
const cache = {};
return function (...args) {
const key = args.join('-');
if (cache[key]) {
console.log('Taken from cache!', key);
return cache[key];
}
const result = fn(...args);
cache[key] = result;
return result;
};
}
const fibonacciMemorized = cacheDecorator(fibonacci);
fibonacciMemorized(37); // ?.
fibonacciMemorized(37); // ?.
export {};
9 changes: 9 additions & 0 deletions src/algorithmes/basic/fibonacci.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@

// Fibonacci

function fibonacci(n) {
if (n == 0) return 0
if (n == 1) return 1
return fibonacci(n - 1) + fibonacci(n - 2)
}
/* console.log(fibonacci(9)) */
37 changes: 37 additions & 0 deletions src/algorithmes/basic/matrix-perimeter.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
const matrix = [
[0, 0, 0],
[1, 1, 0],
[0, 1, 0],
// [1,0,0,1,0],
// [1,0,0,1,0],
// [0,0,0,1,0],
// [1,1,0,1,0],
// [0,1,0,0,0],
]

function findAdjacent(matrix, x, y) {
let removeEdge = 0
// Check vertically adjacent
if (matrix[y + 1][x] === 1)
removeEdge += 2

else if (matrix[y][x + 1] === 1)
removeEdge += 2

return removeEdge
}
function calcPerimeter(matrix) {
let totalEdge = 0

for (let x = 0; x < matrix[0].length - 1; x++) {
for (let y = 0; y < matrix.length - 1; y++) {
if (matrix[y][x] === 1) {
totalEdge += 4 // ?
totalEdge -= findAdjacent(matrix, x, y)
}
}
}
return totalEdge
}

calcPerimeter(matrix) // ?
12 changes: 12 additions & 0 deletions src/algorithmes/basic/palindrom.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Palindrome

function isPalindrome(line) {
const aCodeSymbol = 'a'.charCodeAt(0)
const zCodeSymbol = 'z'.charCodeAt(0)
line = line
.toLowerCase()
.split('').filter(symbol => symbol.charCodeAt(0) >= aCodeSymbol && symbol.charCodeAt(0) <= zCodeSymbol)

return line.join('') == line.reverse().join('')
}
/* console.log(isPalindrome("Madam, I'm, !AdAm")) */
39 changes: 39 additions & 0 deletions src/algorithmes/basic/shortest-way-Dijctra.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// Find the shortest way (Dijctra)

function findShortestWay(graph, start, end, neighbors = {}, passed = []) {
// Write info about close neighbors
Object.keys(graph[start]).forEach(point => {
// If new way faster than old - replace it
if (((neighbors[start] || 0) + graph[start][point]) < (neighbors[point] || Number.POSITIVE_INFINITY)) {
neighbors[point] = (neighbors[start] || 0) + graph[start][point]
}
})
// Check current point as passed
passed.push(start)

// Find way to every neighbor
Object.keys(neighbors).forEach(point => {
// This point weren't passed yet
if (!passed.includes(point)) {
findShortestWay(graph, point, end, neighbors, passed)
}
})
return neighbors
}
/* const graph = {}
graph.a = { b: 2, c: 1 }
graph.b = { f: 7 }
graph.c = { d: 5, e: 2 }
graph.d = { f: 2 }
graph.e = { f: 150 }
graph.f = { g: 1 }
graph.g = {}
// graph.a = { b: 10, e: 30, d: 100 }
// graph.b = { c: 50 }
// graph.c = { d: 10 }
// graph.e = { c: 20, d: 60 }
// graph.d = {}
console.log(findShortestWay(graph, 'a', 'd')) */

//
12 changes: 12 additions & 0 deletions src/algorithmes/caesar-cipher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@

// Caesar Cipher

function caesarCipher(str, num) {
let strArray = str.split(' ')
return strArray.map(word => word.split('').map(symbol => {
if (symbol == symbol.toUpperCase()) return String.fromCharCode((symbol.charCodeAt(0) - 'a'.charCodeAt(0) + num) % 26 + 'a'.charCodeAt(0))
.toUpperCase()
return String.fromCharCode((symbol.charCodeAt(0) - 97 + num) % 26 + 97)
}).join('')).join(' ')
}
/* console.log(caesarCipher('zoo Keeper', 2)) */
20 changes: 20 additions & 0 deletions src/algorithmes/collect-sum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Collect sum

function collectSum(array, sum) {
let results = []
let originDict = {}
array.forEach(digit => {
if (!originDict[digit]) originDict[digit] = 1
else originDict[digit]++
})

array.forEach(digit => {
if (originDict[digit] && array.includes(sum - digit)) {
results.push([digit, sum - digit])
originDict[digit]--
originDict[sum - digit]--
}
})
return results
}
/* console.log(collectSum([1, 5, 2, 3, 4, 7, 6, 5], 9)) */
16 changes: 16 additions & 0 deletions src/algorithmes/fizz-buzz.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Fizz-Buzz

function FizzBuzz(num) {
for (let i = 1; i <= num; i++) {
if (!(i % 5) && !(i % 3)) {
console.log('FizzBuzz')
} else if (i % 3 == 0) {
console.log('Fizz')
} else if (i % 5 == 0) {
console.log('Buzz')
} else {
console.log(i)
}
}
}
/* FizzBuzz(20) */
21 changes: 21 additions & 0 deletions src/algorithmes/harmless-ransom-note.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Harmless Ransom Note

function harmlessRansomNote(noteText, magazineText) {
let noteTextArray = noteText.split(' ')
let magazineTextArray = magazineText.split(' ')
let sourceDict = {}
magazineTextArray.forEach(word => {
if (!sourceDict[word]) sourceDict[word] = 1
else {
sourceDict[word]++
}
})
for (let word of noteTextArray) {
if (!sourceDict[word] || --sourceDict[word] < 0) return false
}
console.log(sourceDict)
return true
}
/* console.log(harmlessRansomNote('from this is a secret note for you from a secret admirer',
'puerto rico is a place of great wonder and excitement it has many secret waterfall locations that i am an admirer of you must hike quite a distance to find the secret places as they are far from populated areas but it is worth the effort a tip i have for you is to go early in the morning when it is not so hot out also note that you must wear hiking boots this is one of the best places i have ever visited')) */

17 changes: 17 additions & 0 deletions src/algorithmes/max-profit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Max profit

function determineProfit(array) {
let minPrice = array[0]
let tomorrowPrice = array[1]
let maxProfit = -1
for (let i = 0; i < array.length - 1; i++) {
tomorrowPrice = array[i + 1]
if (tomorrowPrice - array[i] > maxProfit) {
if (array[i] < minPrice) minPrice = array[i]
maxProfit = tomorrowPrice - minPrice
} else if (array[i + 1] - minPrice > maxProfit) maxProfit = tomorrowPrice - minPrice
}
return maxProfit

}
/* console.log(determineProfit([125, 50, 6, 10, 33, 25, 1])) */
41 changes: 41 additions & 0 deletions src/algorithmes/mean-medium-note.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Mean Median Mode

function MeanMedianMode(array) {
const getMean = array => (array.reduce((prev, cur) => prev + cur, 0) / array.length).toFixed(2)

function getMedian(array) {
const arraySorted = array.sort((a, b) => a - b)
if (array.length % 2 == 1) return arraySorted[Math.floor(array.length / 2)]
let median1 = arraySorted[array.length / 2]
let median2 = arraySorted[array.length / 2 - 1]
return (median1 + median2) / 2
}
function getMode(array) {
let objectDict = {}
array.forEach(word => {
if (!objectDict[word]) objectDict[word] = 0
objectDict[word]++
})

let maxFrequency = 0
let wordFrequency = []
array.forEach(word => {
if (objectDict[word] > maxFrequency) {
maxFrequency = objectDict[word]
wordFrequency = [word]
} else if (objectDict[word] == maxFrequency && !wordFrequency.includes(word)) {
wordFrequency.push(word)
}
})
if (wordFrequency.length == array.length) maxFrequency = null
console.log(objectDict)
return wordFrequency

}
return {
'mean': getMean(array),
'median': getMedian(array),
'mode': getMode(array),
}
}
/* console.log(MeanMedianMode([10, 23, 10, 15, 23, 9])) */
13 changes: 13 additions & 0 deletions src/algorithmes/reverse-array-in-place.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Reverse Array In Place

function reverseArrayInPlace(arr) {
let newArray = []
let l = arr.length
for (let i = 0; i < l / 2; i++) {
newArray[i] = arr[l - i - 1]
newArray[l - i - 1] = arr[i]
}
console.log(newArray)

}
/* reverseArrayInPlace([1, 2, 3, 4, 5]) */
12 changes: 12 additions & 0 deletions src/algorithmes/reverse-words.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Reverse words

function reverseWords(phrase) {
let modifiedPhrase = ''
for (let i = 0; i < phrase.length; i++) {
modifiedPhrase += phrase[phrase.length - i - 1]
}
return modifiedPhrase
}
/* console.log(reverseWords('Coding JavaScript')) */


16 changes: 16 additions & 0 deletions src/algorithmes/sieve-of-eratosthenes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Sieve of Eratosthenes

function primeSieve(n) {
let array = []
for (let i = 1; i < n; i++) array[i] = i + 1

for (let i = 2; i < Math.sqrt(n); i++) {
array = array.map((num, index) => {
if (index + 1 >= i ** 2 && num % i == 0) return false
return num
})
}
return array.filter(num => num != false)

}
/* console.log(primeSieve(120)) */
15 changes: 15 additions & 0 deletions src/algorithmes/sorts/bubble-sort.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Bubble sort

function bubbleSort(array) {
for (let i = 0; i < array.length - 1; i++) {
for (let j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
array[j] += array[j + 1]
array[j + 1] = array[j] - array[j + 1]
array[j] = array[j] - array[j + 1]
}
}
}
return array
}
/* console.log(bubbleSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])) */
Loading

0 comments on commit 0e7706a

Please sign in to comment.