Merge pull request #138 from cclauss/standard

Apply the JavaScript Standard Style
This commit is contained in:
Christian Clauss
2020-05-03 14:41:18 +02:00
committed by GitHub
47 changed files with 2240 additions and 2371 deletions

View File

@ -1,4 +1,4 @@
function euclideanGCDRecursive(first, second) { function euclideanGCDRecursive (first, second) {
/* /*
Calculates GCD of two numbers using Euclidean Recursive Algorithm Calculates GCD of two numbers using Euclidean Recursive Algorithm
:param first: First number :param first: First number
@ -6,13 +6,13 @@ function euclideanGCDRecursive(first, second) {
:return: GCD of the numbers :return: GCD of the numbers
*/ */
if (second === 0) { if (second === 0) {
return first; return first
} else { } else {
return euclideanGCDRecursive(second, (first % second)); return euclideanGCDRecursive(second, (first % second))
} }
} }
function euclideanGCDIterative(first, second) { function euclideanGCDIterative (first, second) {
/* /*
Calculates GCD of two numbers using Euclidean Iterative Algorithm Calculates GCD of two numbers using Euclidean Iterative Algorithm
:param first: First number :param first: First number
@ -20,18 +20,18 @@ function euclideanGCDIterative(first, second) {
:return: GCD of the numbers :return: GCD of the numbers
*/ */
while (second !== 0) { while (second !== 0) {
let temp = second; const temp = second
second = first % second; second = first % second
first = temp; first = temp
} }
return first; return first
} }
function main() { function main () {
let first = 20; const first = 20
let second = 30; const second = 30
console.log('Recursive GCD for %d and %d is %d', first, second, euclideanGCDRecursive(first, second)); console.log('Recursive GCD for %d and %d is %d', first, second, euclideanGCDRecursive(first, second))
console.log('Iterative GCD for %d and %d is %d', first, second, euclideanGCDIterative(first, second)); console.log('Iterative GCD for %d and %d is %d', first, second, euclideanGCDIterative(first, second))
} }
main(); main()

View File

@ -3,7 +3,7 @@ function KadaneAlgo (array) {
let maxSum = 0 let maxSum = 0
for (var i = 0; i < array.length; i++) { for (var i = 0; i < array.length; i++) {
cummulativeSum = cummulativeSum + array[i] cummulativeSum = cummulativeSum + array[i]
if(cummulativeSum < 0 ) { if (cummulativeSum < 0) {
cummulativeSum = 0 cummulativeSum = 0
} }
if (maxSum < cummulativeSum) { if (maxSum < cummulativeSum) {
@ -13,8 +13,8 @@ function KadaneAlgo (array) {
return maxSum return maxSum
// This function returns largest sum contigous sum in a array // This function returns largest sum contigous sum in a array
} }
function main() { function main () {
var myArray = [1,2,3,4,-6] var myArray = [1, 2, 3, 4, -6]
var result = KadaneAlgo(myArray) var result = KadaneAlgo(myArray)
console.log(result) console.log(result)
} }

View File

@ -8,18 +8,18 @@
// of the input value n, it is exponential in the size of n as // of the input value n, it is exponential in the size of n as
// a function of the number of input bits // a function of the number of input bits
function fib(n) { function fib (n) {
var table = []; var table = []
table.push(1); table.push(1)
table.push(1); table.push(1)
for (var i = 2; i < n; ++i) { for (var i = 2; i < n; ++i) {
table.push(table[i - 1] + table[i - 2]); table.push(table[i - 1] + table[i - 2])
} }
console.log("Fibonacci #%d = %d", n, table[n - 1]); console.log('Fibonacci #%d = %d', n, table[n - 1])
} }
fib(1); fib(1)
fib(2); fib(2)
fib(200); fib(200)
fib(5); fib(5)
fib(10); fib(10)

View File

@ -1,31 +1,31 @@
function sieveOfEratosthenes(n) { function sieveOfEratosthenes (n) {
/* /*
* Calculates prime numbers till a number n * Calculates prime numbers till a number n
* :param n: Number upto which to calculate primes * :param n: Number upto which to calculate primes
* :return: A boolean list contaning only primes * :return: A boolean list contaning only primes
*/ */
let primes = new Array(n + 1); const primes = new Array(n + 1)
primes.fill(true); // set all as true initially primes.fill(true) // set all as true initially
primes[0] = primes[1] = false; // Handling case for 0 and 1 primes[0] = primes[1] = false // Handling case for 0 and 1
let sqrtn = Math.ceil(Math.sqrt(n)); const sqrtn = Math.ceil(Math.sqrt(n))
for (let i = 2; i <= sqrtn; i++) { for (let i = 2; i <= sqrtn; i++) {
if (primes[i]) { if (primes[i]) {
for (let j = 2 * i; j <= n; j += i) { for (let j = 2 * i; j <= n; j += i) {
primes[j] = false; primes[j] = false
} }
} }
} }
return primes; return primes
} }
function main() { function main () {
let n = 69; // number till where we wish to find primes const n = 69 // number till where we wish to find primes
let primes = sieveOfEratosthenes(n); const primes = sieveOfEratosthenes(n)
for (let i = 2; i <= n; i++) { for (let i = 2; i <= n; i++) {
if (primes[i]) { if (primes[i]) {
console.log(i); console.log(i)
} }
} }
} }
main(); main()

View File

@ -11,28 +11,26 @@
* @param {String} str - string to be decrypted * @param {String} str - string to be decrypted
* @return {String} decrypted string * @return {String} decrypted string
*/ */
function rot13(str) { function rot13 (str) {
let response = []; const response = []
let strLength = str.length; const strLength = str.length
for (let i = 0; i < strLength; i++) { for (let i = 0; i < strLength; i++) {
const char = str.charCodeAt(i); const char = str.charCodeAt(i)
if (char < 65 || (char > 90 && char < 97) || char > 122) { if (char < 65 || (char > 90 && char < 97) || char > 122) {
response.push(str.charAt(i)); response.push(str.charAt(i))
} else if ((char > 77 && char <= 90) || (char > 109 && char <= 122)) { } else if ((char > 77 && char <= 90) || (char > 109 && char <= 122)) {
response.push(String.fromCharCode(str.charCodeAt(i) - 13)); response.push(String.fromCharCode(str.charCodeAt(i) - 13))
} else { } else {
response.push(String.fromCharCode(str.charCodeAt(i) + 13)); response.push(String.fromCharCode(str.charCodeAt(i) + 13))
} }
} }
return response.join(""); return response.join('')
} }
// Caesars Cipher Example // Caesars Cipher Example
const encryptedString = "Uryyb Jbeyq"; const encryptedString = 'Uryyb Jbeyq'
const decryptedString = rot13(encryptedString); const decryptedString = rot13(encryptedString)
console.log(decryptedString); // Hello World console.log(decryptedString) // Hello World

View File

@ -2,156 +2,121 @@
Find and retrieve the encryption key automatically Find and retrieve the encryption key automatically
Note: This is a draft version, please help to modify, Thanks! Note: This is a draft version, please help to modify, Thanks!
******************************************************/ ******************************************************/
function keyFinder(str){ // str is used to get the input of encrypted string function keyFinder (str) { // str is used to get the input of encrypted string
const wordbank =["I ","You ","We ","They ","He ","She ","It "," the ","The "," of "," is ","Is "," am ","Am "," are ","Are "," have ","Have "," has ","Has "," may ","May "," be ","Be "]; const wordbank = ['I ', 'You ', 'We ', 'They ', 'He ', 'She ', 'It ', ' the ', 'The ', ' of ', ' is ', 'Is ', ' am ', 'Am ', ' are ', 'Are ', ' have ', 'Have ', ' has ', 'Has ', ' may ', 'May ', ' be ', 'Be ']
//let wordbankelementCounter = 0; // let wordbankelementCounter = 0;
//let key = 0; // return zero means the key can not be found // let key = 0; // return zero means the key can not be found
let inStr = str.toString(); //convert the input to String const inStr = str.toString() // convert the input to String
let outStr = ""; // store the output value let outStr = '' // store the output value
let outStrElement = ""; // temporary store the word inside the outStr, it is used for comparison let outStrElement = '' // temporary store the word inside the outStr, it is used for comparison
for (let k=0; k<26; k++){ //try the number of key shifted, the sum of character from a-z or A-Z is 26 for (let k = 0; k < 26; k++) { // try the number of key shifted, the sum of character from a-z or A-Z is 26
outStr = caesarCipherEncodeAndDecodeEngine(inStr,k); // use the encrytpion engine to decrypt the input string outStr = caesarCipherEncodeAndDecodeEngine(inStr, k) // use the encrytpion engine to decrypt the input string
//loop through the whole input string
for ( let s=0; s < outStr.length; s++){
for ( let i=0; i < wordbank.length; i++){
// loop through the whole input string
for (let s = 0; s < outStr.length; s++) {
for (let i = 0; i < wordbank.length; i++) {
// initialize the outStrElement which is a temp output string for comparison, // initialize the outStrElement which is a temp output string for comparison,
// use a loop to find the next digit of wordbank element and compare with outStr's digit // use a loop to find the next digit of wordbank element and compare with outStr's digit
for ( let w=0; w < wordbank[i].length; w++){ for (let w = 0; w < wordbank[i].length; w++) {
outStrElement += outStr[ s + w ]; outStrElement += outStr[s + w]
} }
//console.log( k + outStrElement + wordbank[i] );//debug // console.log( k + outStrElement + wordbank[i] );//debug
// this part need to be optimize with the calculation of the number of occurance of word's probabilities // this part need to be optimize with the calculation of the number of occurance of word's probabilities
// linked list will be used in the next stage of development to calculate the number of occurace of the key // linked list will be used in the next stage of development to calculate the number of occurace of the key
if (wordbank[i] == outStrElement){ if (wordbank[i] == outStrElement) {
return k; // return the key number if founded return k // return the key number if founded
} }
outStrElement = ""; //reset the temp word outStrElement = '' // reset the temp word
} // end for ( let i=0; i < wordbank.length; i++) } // end for ( let i=0; i < wordbank.length; i++)
} }
} }
return 0; // return 0 if found nothing return 0 // return 0 if found nothing
} }
/* this sub-function is used to assist the keyfinder to find the key */ /* this sub-function is used to assist the keyfinder to find the key */
function caesarCipherEncodeAndDecodeEngine(inStr, numShifted) function caesarCipherEncodeAndDecodeEngine (inStr, numShifted) {
{ const shiftNum = numShifted
let shiftNum = numShifted; let charCode = 0
let charCode = 0; let outStr = ''
let outStr = ""; let shftedcharCode = 0
let shftedcharCode = 0; let result = 0
let result = 0;
for (let i=0; i<inStr.length; i++){ for (let i = 0; i < inStr.length; i++) {
charCode = inStr[i].charCodeAt()
shftedcharCode = charCode + shiftNum
result = charCode
charCode = inStr[i].charCodeAt(); if ((charCode >= 48 && charCode <= 57)) {
shftedcharCode = charCode + shiftNum; if (shftedcharCode < 48) {
result = charCode; let diff = Math.abs(48 - 1 - shftedcharCode) % 10
if ( (charCode>=48 && charCode<=57)) while (diff >= 10) {
{ diff = diff % 10
if ( shftedcharCode < 48 ){
let diff = Math.abs(48-1-shftedcharCode)%10;
while( diff >= 10){
diff = diff%10;
} }
document.getElementById("diffID").innerHTML = diff; document.getElementById('diffID').innerHTML = diff
shftedcharCode = 57-diff; shftedcharCode = 57 - diff
result = shftedcharCode; result = shftedcharCode
} else if (shftedcharCode >= 48 && shftedcharCode <= 57) {
result = shftedcharCode
} else if (shftedcharCode > 57) {
let diff = Math.abs(57 + 1 - shftedcharCode) % 10
while (diff >= 10) {
diff = diff % 10
} }
document.getElementById('diffID').innerHTML = diff
else if ( shftedcharCode>=48 && shftedcharCode<=57 ){ shftedcharCode = 48 + diff
result = shftedcharCode;
result = shftedcharCode
} }
} else if ((charCode >= 65 && charCode <= 90)) {
if (shftedcharCode <= 64) {
let diff = Math.abs(65 - 1 - shftedcharCode) % 26
else if ( shftedcharCode > 57 ){ while ((diff % 26) >= 26) {
diff = diff % 26
let diff = Math.abs(57+1-shftedcharCode)%10;
while( diff >= 10){
diff = diff%10;
} }
document.getElementById("diffID").innerHTML = diff; shftedcharCode = 90 - diff
result = shftedcharCode
} else if (shftedcharCode >= 65 && shftedcharCode <= 90) {
result = shftedcharCode
} else if (shftedcharCode > 90) {
let diff = Math.abs(shftedcharCode - 1 - 90) % 26
shftedcharCode = 48+diff; while ((diff % 26) >= 26) {
diff = diff % 26
result = shftedcharCode;
} }
shftedcharCode = 65 + diff
result = shftedcharCode
} }
} else if ((charCode >= 97 && charCode <= 122)) {
if (shftedcharCode <= 96) {
let diff = Math.abs(97 - 1 - shftedcharCode) % 26
else if ( (charCode>=65 && charCode<=90) ) while ((diff % 26) >= 26) {
{ diff = diff % 26
if (shftedcharCode <=64 ){
let diff = Math.abs(65-1-shftedcharCode)%26;
while( (diff%26) >= 26){
diff = diff%26;
}
shftedcharCode = 90-diff;
result = shftedcharCode;
} }
shftedcharCode = 122 - diff
result = shftedcharCode
} else if (shftedcharCode >= 97 && shftedcharCode <= 122) {
result = shftedcharCode
} else if (shftedcharCode > 122) {
let diff = Math.abs(shftedcharCode - 1 - 122) % 26
else if ( shftedcharCode>=65 && shftedcharCode<=90 ){ while ((diff % 26) >= 26) {
result = shftedcharCode; diff = diff % 26
} }
shftedcharCode = 97 + diff
else if (shftedcharCode>90 ){ result = shftedcharCode
let diff = Math.abs(shftedcharCode-1-90)%26;
while( (diff%26) >= 26){
diff = diff%26;
} }
shftedcharCode = 65+diff;
result = shftedcharCode;
} }
outStr = outStr + String.fromCharCode(parseInt(result))
} }
return outStr
else if ( (charCode>=97 && charCode<=122))
{
if ( shftedcharCode<=96 ){
let diff = Math.abs(97-1-shftedcharCode)%26;
while( (diff%26) >= 26){
diff = diff%26;
}
shftedcharCode = 122-diff;
result = shftedcharCode;
}
else if ( shftedcharCode>=97 && shftedcharCode<=122 ){
result = shftedcharCode;
}
else if (shftedcharCode>122 ){
let diff = Math.abs(shftedcharCode-1-122)%26;
while( (diff%26) >= 26){
diff = diff%26;
}
shftedcharCode = 97+diff;
result = shftedcharCode;
}
}
outStr = outStr + String.fromCharCode(parseInt(result));
}
return outStr;
} }

View File

@ -3,8 +3,8 @@
* @param {String} character - character to check * @param {String} character - character to check
* @return {object} An array with the character or null if isn't a letter * @return {object} An array with the character or null if isn't a letter
*/ */
function isLetter(str) { function isLetter (str) {
return str.length === 1 && str.match(/[a-zA-Z]/i); return str.length === 1 && str.match(/[a-zA-Z]/i)
} }
/** /**
@ -12,12 +12,12 @@ function isLetter(str) {
* @param {String} character - character to check * @param {String} character - character to check
* @return {Boolean} result of the checking * @return {Boolean} result of the checking
*/ */
function isUpperCase(character){ function isUpperCase (character) {
if (character == character.toUpperCase()) { if (character == character.toUpperCase()) {
return true; return true
} }
if (character == character.toLowerCase()){ if (character == character.toLowerCase()) {
return false; return false
} }
} }
@ -27,25 +27,23 @@ function isUpperCase(character){
* @param {String} key - key for encrypt * @param {String} key - key for encrypt
* @return {String} result - encrypted string * @return {String} result - encrypted string
*/ */
function encrypt(message, key) function encrypt (message, key) {
{ let result = ''
let result = "";
for (let i = 0, j = 0; i < message.length; i++) { for (let i = 0, j = 0; i < message.length; i++) {
let c = message.charAt(i); const c = message.charAt(i)
if (isLetter(c)){ if (isLetter(c)) {
if(isUpperCase(c)) { if (isUpperCase(c)) {
result += String.fromCharCode((c.charCodeAt(0) + key.toUpperCase().charCodeAt(j) - 2 * 65) % 26 + 65); // A: 65 result += String.fromCharCode((c.charCodeAt(0) + key.toUpperCase().charCodeAt(j) - 2 * 65) % 26 + 65) // A: 65
} else { } else {
result += String.fromCharCode((c.charCodeAt(0) + key.toLowerCase().charCodeAt(j) - 2 * 97) % 26 + 97); // a: 97 result += String.fromCharCode((c.charCodeAt(0) + key.toLowerCase().charCodeAt(j) - 2 * 97) % 26 + 97) // a: 97
} }
} else { } else {
result+=c; result += c
} }
j = ++j % key.length; j = ++j % key.length
} }
return result; return result
} }
/** /**
@ -54,28 +52,27 @@ function encrypt(message, key)
* @param {String} key - key for decrypt * @param {String} key - key for decrypt
* @return {String} result - decrypted string * @return {String} result - decrypted string
*/ */
function decrypt(message, key) function decrypt (message, key) {
{ let result = ''
let result ="";
for(let i = 0, j = 0; i < message.length; i++){ for (let i = 0, j = 0; i < message.length; i++) {
let c = message.charAt(i); const c = message.charAt(i)
if (isLetter(c)){ if (isLetter(c)) {
if(isUpperCase(c)) { if (isUpperCase(c)) {
result += String.fromCharCode(90-(25-(c.charCodeAt(0)-key.toUpperCase().charCodeAt(j)))%26); result += String.fromCharCode(90 - (25 - (c.charCodeAt(0) - key.toUpperCase().charCodeAt(j))) % 26)
} else { } else {
result += String.fromCharCode(122-(25-(c.charCodeAt(0)-key.toLowerCase().charCodeAt(j)))%26); result += String.fromCharCode(122 - (25 - (c.charCodeAt(0) - key.toLowerCase().charCodeAt(j))) % 26)
} }
} else { } else {
result+=c; result += c
} }
j = ++j % key.length; j = ++j % key.length
} }
return result; return result
} }
let messageEncrypt = encrypt('Hello World!', 'code'); const messageEncrypt = encrypt('Hello World!', 'code')
console.log(messageEncrypt); // "Jhpnr Yrvng!" console.log(messageEncrypt) // "Jhpnr Yrvng!"
let messageDecrypt = decrypt('Jsopq Zstzg!', 'code'); const messageDecrypt = decrypt('Jsopq Zstzg!', 'code')
console.log(messageDecrypt); // "Hello World!" console.log(messageDecrypt) // "Hello World!"

View File

@ -1,12 +1,12 @@
function decimalToBinary(num) { function decimalToBinary (num) {
var bin = []; var bin = []
while (num > 0) { while (num > 0) {
bin.unshift(num % 2); bin.unshift(num % 2)
num >>= 1; // basically /= 2 without remainder if any num >>= 1 // basically /= 2 without remainder if any
} }
console.log("The decimal in binary is " + bin.join("")); console.log('The decimal in binary is ' + bin.join(''))
} }
decimalToBinary(2); decimalToBinary(2)
decimalToBinary(7); decimalToBinary(7)
decimalToBinary(35); decimalToBinary(35)

View File

@ -1,24 +1,24 @@
function intToHex(num){ function intToHex (num) {
switch(num){ switch (num) {
case 10: return "A"; case 10: return 'A'
case 11: return "B"; case 11: return 'B'
case 12: return "C"; case 12: return 'C'
case 13: return "D"; case 13: return 'D'
case 14: return "E"; case 14: return 'E'
case 15: return "F"; case 15: return 'F'
} }
return num; return num
} }
function decimalToHex(num){ function decimalToHex (num) {
let hex_out = []; const hex_out = []
while(num > 15) { while (num > 15) {
hex_out.push(intToHex(num%16)); hex_out.push(intToHex(num % 16))
num = Math.floor(num / 16); num = Math.floor(num / 16)
} }
return intToHex(num) + hex_out.join(""); return intToHex(num) + hex_out.join('')
} }
// test cases // test cases
console.log(decimalToHex(999098) === "F3EBA"); console.log(decimalToHex(999098) === 'F3EBA')
console.log(decimalToHex(123) === "7B"); console.log(decimalToHex(123) === '7B')

View File

@ -1,15 +1,15 @@
function decimalToOctal(num) { function decimalToOctal (num) {
var oct = 0,c=0; var oct = 0; var c = 0
while (num > 0) { while (num > 0) {
var r=num%8; var r = num % 8
oct=oct+(r*Math.pow(10,c++)); oct = oct + (r * Math.pow(10, c++))
num =Math.floor(num/ 8); // basically /= 8 without remainder if any num = Math.floor(num / 8) // basically /= 8 without remainder if any
} }
console.log("The decimal in octal is " + oct); console.log('The decimal in octal is ' + oct)
} }
decimalToOctal(2); decimalToOctal(2)
decimalToOctal(8); decimalToOctal(8)
decimalToOctal(65); decimalToOctal(65)
decimalToOctal(216); decimalToOctal(216)
decimalToOctal(512); decimalToOctal(512)

View File

@ -1,46 +1,40 @@
class Graph { class Graph {
constructor () {
constructor() {
this.adjacencyMap = {} this.adjacencyMap = {}
} }
addVertex(v) { addVertex (v) {
this.adjacencyMap[v] = []; this.adjacencyMap[v] = []
} }
containsVertex(vertex) { containsVertex (vertex) {
return typeof (this.adjacencyMap[vertex]) !== "undefined" return typeof (this.adjacencyMap[vertex]) !== 'undefined'
} }
addEdge(v, w) { addEdge (v, w) {
let result = false let result = false
if (this.containsVertex(v) && this.containsVertex(w)) { if (this.containsVertex(v) && this.containsVertex(w)) {
this.adjacencyMap[v].push(w); this.adjacencyMap[v].push(w)
this.adjacencyMap[w].push(v); this.adjacencyMap[w].push(v)
result = true result = true
} }
return result return result
} }
printGraph () {
const keys = Object.keys(this.adjacencyMap)
printGraph() { for (const i of keys) {
let keys = Object.keys(this.adjacencyMap); const values = this.adjacencyMap[i]
for (let i of keys) { let vertex = ''
let values = this.adjacencyMap[i]; for (const j of values) { vertex += j + ' ' }
let vertex = ""; console.log(i + ' -> ' + vertex)
for (let j of values)
vertex += j + " ";
console.log(i + " -> " + vertex);
} }
} }
} }
const example = () => { const example = () => {
let g = new Graph() const g = new Graph()
g.addVertex(1) g.addVertex(1)
g.addVertex(2) g.addVertex(2)
g.addVertex(3) g.addVertex(3)

View File

@ -12,117 +12,115 @@
// Functions: insert, delete, peek, isEmpty, print, heapSort, sink // Functions: insert, delete, peek, isEmpty, print, heapSort, sink
class MinPriorityQueue { class MinPriorityQueue {
// calss the constructor and initializes the capacity // calss the constructor and initializes the capacity
constructor(c) { constructor (c) {
this.heap = []; this.heap = []
this.capacity = c; this.capacity = c
this.size = 0; this.size = 0
} }
// inserts the key at the end and rearranges it // inserts the key at the end and rearranges it
// so that the binary heap is in appropriate order // so that the binary heap is in appropriate order
insert(key) { insert (key) {
if (this.isFull()) return; if (this.isFull()) return
this.heap[this.size + 1] = key; this.heap[this.size + 1] = key
let k = this.size + 1; let k = this.size + 1
while (k > 1) { while (k > 1) {
if (this.heap[k] < this.heap[Math.floor(k / 2)]) { if (this.heap[k] < this.heap[Math.floor(k / 2)]) {
let temp = this.heap[k]; const temp = this.heap[k]
this.heap[k] = this.heap[Math.floor(k / 2)]; this.heap[k] = this.heap[Math.floor(k / 2)]
this.heap[Math.floor(k / 2)] = temp; this.heap[Math.floor(k / 2)] = temp
} }
k = Math.floor(k / 2); k = Math.floor(k / 2)
} }
this.size++; this.size++
} }
// returns the highest priority value // returns the highest priority value
peek() { peek () {
return this.heap[1]; return this.heap[1]
} }
// returns boolean value whether the heap is empty or not // returns boolean value whether the heap is empty or not
isEmpty() { isEmpty () {
if (0 == this.size) return true; if (this.size == 0) return true
return false; return false
} }
// returns boolean value whether the heap is full or not // returns boolean value whether the heap is full or not
isFull() { isFull () {
if (this.size == this.capacity) return true; if (this.size == this.capacity) return true
return false; return false
} }
// prints the heap // prints the heap
print() { print () {
console.log(this.heap.slice(1)); console.log(this.heap.slice(1))
} }
// heap sorting can be done by performing // heap sorting can be done by performing
// delete function to the number of times of the size of the heap // delete function to the number of times of the size of the heap
// it returns reverse sort because it is a min priority queue // it returns reverse sort because it is a min priority queue
heapSort() { heapSort () {
for (let i = 1; i < this.capacity; i++) { for (let i = 1; i < this.capacity; i++) {
this.delete(); this.delete()
} }
} }
// this function reorders the heap after every delete function // this function reorders the heap after every delete function
sink() { sink () {
let k = 1; let k = 1
while (2 * k <= this.size || 2 * k + 1 <= this.size) { while (2 * k <= this.size || 2 * k + 1 <= this.size) {
let minIndex; let minIndex
if (this.heap[2 * k] >= this.heap[k]) { if (this.heap[2 * k] >= this.heap[k]) {
if (2 * k + 1 <= this.size && this.heap[2*k+1] >= this.heap[k]) { if (2 * k + 1 <= this.size && this.heap[2 * k + 1] >= this.heap[k]) {
break; break
} } else if (2 * k + 1 > this.size) {
else if(2*k+1 > this.size){ break
break;
} }
} }
if (2 * k + 1 > this.size) { if (2 * k + 1 > this.size) {
minIndex = this.heap[2 * k] < this.heap[k] ? 2 * k : k; minIndex = this.heap[2 * k] < this.heap[k] ? 2 * k : k
} else { } else {
if ( if (
this.heap[k] > this.heap[2 * k] || this.heap[k] > this.heap[2 * k] ||
this.heap[k] > this.heap[2 * k + 1] this.heap[k] > this.heap[2 * k + 1]
) { ) {
minIndex = minIndex =
this.heap[2 * k] < this.heap[2 * k + 1] ? 2 * k : 2 * k + 1; this.heap[2 * k] < this.heap[2 * k + 1] ? 2 * k : 2 * k + 1
} else { } else {
minIndex = k; minIndex = k
} }
} }
let temp = this.heap[k]; const temp = this.heap[k]
this.heap[k] = this.heap[minIndex]; this.heap[k] = this.heap[minIndex]
this.heap[minIndex] = temp; this.heap[minIndex] = temp
k = minIndex; k = minIndex
} }
} }
// deletes the highest priority value from the heap // deletes the highest priority value from the heap
delete() { delete () {
let min = this.heap[1]; const min = this.heap[1]
this.heap[1] = this.heap[this.size]; this.heap[1] = this.heap[this.size]
this.heap[this.size] = min; this.heap[this.size] = min
this.size--; this.size--
this.sink(); this.sink()
return min; return min
} }
} }
// testing // testing
q = new MinPriorityQueue(8); q = new MinPriorityQueue(8)
q.insert(5); q.insert(5)
q.insert(2); q.insert(2)
q.insert(4); q.insert(4)
q.insert(1); q.insert(1)
q.insert(7); q.insert(7)
q.insert(6); q.insert(6)
q.insert(3); q.insert(3)
q.insert(8); q.insert(8)
q.print(); // [ 1, 2, 3, 5, 7, 6, 4, 8 ] q.print() // [ 1, 2, 3, 5, 7, 6, 4, 8 ]
q.heapSort(); q.heapSort()
q.print(); // [ 8, 7, 6, 5, 4, 3, 2, 1 ] q.print() // [ 8, 7, 6, 5, 4, 3, 2, 1 ]

View File

@ -1,197 +1,195 @@
//Hamza chabchoub contribution for a university project // Hamza chabchoub contribution for a university project
function doubleLinkedList() { function doubleLinkedList () {
let Node = function(element) { const Node = function (element) {
this.element = element; this.element = element
this.next = null; this.next = null
this.prev = null; this.prev = null
} }
let length = 0; let length = 0
let head = null; let head = null
let tail = null; let tail = null
//Add new element // Add new element
this.append = function(element) { this.append = function (element) {
let node = new Node(element); const node = new Node(element)
if(!head){ if (!head) {
head = node; head = node
tail = node; tail = node
}else{ } else {
node.prev = tail; node.prev = tail
tail.next = node; tail.next = node
tail = node; tail = node
} }
length++; length++
} }
// Add element
this.insert = function (position, element) {
// Check of out-of-bound values
if (position >= 0 && position <= length) {
const node = new Node(element)
let current = head
let previous
let index = 0
//Add element if (position === 0) {
this.insert = function(position, element) { if (!head) {
head = node
//Check of out-of-bound values tail = node
if(position >= 0 && position <= length){ } else {
let node = new Node(element), node.next = current
current = head, current.prev = node
previous, head = node
index = 0;
if(position === 0){
if(!head){
head = node;
tail = node;
}else{
node.next = current;
current.prev = node;
head = node;
} }
}else if(position === length){ } else if (position === length) {
current = tail; current = tail
current.next = node; current.next = node
node.prev = current; node.prev = current
tail = node; tail = node
}else{ } else {
while(index++ < position){ while (index++ < position) {
previous = current; previous = current
current = current.next; current = current.next
} }
node.next = current; node.next = current
previous.next = node; previous.next = node
//New // New
current.prev = node; current.prev = node
node.prev = previous; node.prev = previous
} }
length++; length++
return true; return true
}else{ } else {
return false; return false
} }
} }
//Remove element at any position // Remove element at any position
this.removeAt = function(position){ this.removeAt = function (position) {
//look for out-of-bounds value // look for out-of-bounds value
if(position > -1 && position < length){ if (position > -1 && position < length) {
let current = head, previous, index = 0; let current = head; let previous; let index = 0
//Removing first item // Removing first item
if(position === 0){ if (position === 0) {
head = current.next; head = current.next
//if there is only one item, update tail //NEW // if there is only one item, update tail //NEW
if(length === 1){ if (length === 1) {
tail = null; tail = null
}else{ } else {
head.prev = null; head.prev = null
} }
}else if(position === length - 1){ } else if (position === length - 1) {
current = tail; current = tail
tail = current.prev; tail = current.prev
tail.next = null; tail.next = null
}else{ } else {
while(index++ < position){ while (index++ < position) {
previous = current; previous = current
current = current.next; current = current.next
} }
//link previous with current's next - skip it // link previous with current's next - skip it
previous.next = current.next; previous.next = current.next
current.next.prev = previous; current.next.prev = previous
} }
length--; length--
return current.element; return current.element
}else{ } else {
return null; return null
} }
} }
//Get the indexOf item // Get the indexOf item
this.indexOf = function(elm){ this.indexOf = function (elm) {
let current = head, let current = head
index = -1; let index = -1
//If element found then return its position // If element found then return its position
while(current){ while (current) {
if(elm === current.element){ if (elm === current.element) {
return ++index; return ++index
} }
index++; index++
current = current.next; current = current.next
} }
//Else return -1 // Else return -1
return -1; return -1
}; }
//Find the item in the list // Find the item in the list
this.isPresent = (elm) => { this.isPresent = (elm) => {
return this.indexOf(elm) !== -1; return this.indexOf(elm) !== -1
}; }
//Delete an item from the list // Delete an item from the list
this.delete = (elm) => { this.delete = (elm) => {
return this.removeAt(this.indexOf(elm)); return this.removeAt(this.indexOf(elm))
};
//Delete first item from the list
this.deleteHead = function(){
this.removeAt(0);
} }
//Delete last item from the list // Delete first item from the list
this.deleteTail = function(){ this.deleteHead = function () {
this.removeAt(length-1); this.removeAt(0)
} }
//Print item of the string // Delete last item from the list
this.toString = function(){ this.deleteTail = function () {
let current = head, this.removeAt(length - 1)
string = '';
while(current){
string += current.element + (current.next ? '\n' : '');
current = current.next;
} }
return string; // Print item of the string
}; this.toString = function () {
let current = head
let string = ''
//Convert list to array while (current) {
this.toArray = function(){ string += current.element + (current.next ? '\n' : '')
let arr = [], current = current.next
current = head;
while(current){
arr.push(current.element);
current = current.next;
} }
return arr; return string
};
//Check if list is empty
this.isEmpty = function(){
return length === 0;
};
//Get the size of the list
this.size = function(){
return length;
} }
//Get the head // Convert list to array
this.getHead = function() { this.toArray = function () {
return head; const arr = []
let current = head
while (current) {
arr.push(current.element)
current = current.next
} }
//Get the tail return arr
this.getTail = function() {
return tail;
} }
// Check if list is empty
this.isEmpty = function () {
return length === 0
} }
// Get the size of the list
this.size = function () {
return length
}
// Get the head
this.getHead = function () {
return head
}
// Get the tail
this.getTail = function () {
return tail
}
}

View File

@ -6,212 +6,204 @@
* a singly linked list. * a singly linked list.
*/ */
//Functions - add, remove, indexOf, elementAt, addAt, removeAt, view // Functions - add, remove, indexOf, elementAt, addAt, removeAt, view
// class LinkedList and constructor // class LinkedList and constructor
//Creates a LinkedList // Creates a LinkedList
var LinkedList = (function () { var LinkedList = (function () {
function LinkedList () {
function LinkedList() { // Length of linklist and head is null at start
//Length of linklist and head is null at start this.length = 0
this.length = 0; this.head = null
this.head = null;
} }
// class node (constructor) // class node (constructor)
//Creating Node with element's value // Creating Node with element's value
var Node = (function () { var Node = (function () {
function Node(element) { function Node (element) {
this.element = element; this.element = element
this.next = null; this.next = null
} }
return Node; return Node
}()); }())
//Returns length // Returns length
LinkedList.prototype.size = function () { LinkedList.prototype.size = function () {
return this.length; return this.length
}; }
//Returns the head // Returns the head
LinkedList.prototype.head = function () { LinkedList.prototype.head = function () {
return this.head; return this.head
}; }
//Creates a node and adds it to linklist // Creates a node and adds it to linklist
LinkedList.prototype.add = function (element) { LinkedList.prototype.add = function (element) {
var node = new Node(element); var node = new Node(element)
//Check if its the first element // Check if its the first element
if (this.head === null) { if (this.head === null) {
this.head = node; this.head = node
} } else {
else { var currentNode = this.head
var currentNode = this.head;
//Loop till there is node present in the list // Loop till there is node present in the list
while (currentNode.next) { while (currentNode.next) {
currentNode = currentNode.next; currentNode = currentNode.next
} }
//Adding node to the end of the list // Adding node to the end of the list
currentNode.next = node; currentNode.next = node
}
// Increment the length
this.length++
} }
//Increment the length
this.length++;
};
//Removes the node with the value as param // Removes the node with the value as param
LinkedList.prototype.remove = function (element) { LinkedList.prototype.remove = function (element) {
var currentNode = this.head; var currentNode = this.head
var previousNode; var previousNode
//Check if the head node is the element to remove // Check if the head node is the element to remove
if (currentNode.element === element) { if (currentNode.element === element) {
this.head = currentNode.next; this.head = currentNode.next
} } else {
else { // Check which node is the node to remove
//Check which node is the node to remove
while (currentNode.element !== element) { while (currentNode.element !== element) {
previousNode = currentNode; previousNode = currentNode
currentNode = currentNode.next; currentNode = currentNode.next
} }
//Removing the currentNode // Removing the currentNode
previousNode.next = currentNode.next; previousNode.next = currentNode.next
} }
//Decrementing the length // Decrementing the length
this.length--; this.length--
}; }
//Return if the list is empty // Return if the list is empty
LinkedList.prototype.isEmpty = function () { LinkedList.prototype.isEmpty = function () {
return this.length === 0; return this.length === 0
}; }
//Returns the index of the element passed as param otherwise -1 // Returns the index of the element passed as param otherwise -1
LinkedList.prototype.indexOf = function (element) { LinkedList.prototype.indexOf = function (element) {
var currentNode = this.head; var currentNode = this.head
var index = -1; var index = -1
while (currentNode) { while (currentNode) {
index++; index++
//Checking if the node is the element we are searching for // Checking if the node is the element we are searching for
if (currentNode.element === element) { if (currentNode.element === element) {
return index + 1; return index + 1
} }
currentNode = currentNode.next; currentNode = currentNode.next
} }
return -1; return -1
}; }
//Returns the element at an index // Returns the element at an index
LinkedList.prototype.elementAt = function (index) { LinkedList.prototype.elementAt = function (index) {
var currentNode = this.head; var currentNode = this.head
var count = 0; var count = 0
while (count < index) { while (count < index) {
count++; count++
currentNode = currentNode.next; currentNode = currentNode.next
}
return currentNode.element
} }
return currentNode.element;
};
//Adds the element at specified index // Adds the element at specified index
LinkedList.prototype.addAt = function (index, element) { LinkedList.prototype.addAt = function (index, element) {
index--; index--
var node = new Node(element); var node = new Node(element)
var currentNode = this.head; var currentNode = this.head
var previousNode; var previousNode
var currentIndex = 0; var currentIndex = 0
//Check if index is out of bounds of list // Check if index is out of bounds of list
if (index > this.length) { if (index > this.length) {
return false; return false
} }
//Check if index is the start of list // Check if index is the start of list
if (index === 0) { if (index === 0) {
node.next = currentNode; node.next = currentNode
this.head = node; this.head = node
} } else {
else {
while (currentIndex < index) { while (currentIndex < index) {
currentIndex++; currentIndex++
previousNode = currentNode; previousNode = currentNode
currentNode = currentNode.next; currentNode = currentNode.next
} }
//Adding the node at specified index // Adding the node at specified index
node.next = currentNode; node.next = currentNode
previousNode.next = node; previousNode.next = node
} }
//Incrementing the length // Incrementing the length
this.length++; this.length++
return true; return true
}; }
//Removes the node at specified index // Removes the node at specified index
LinkedList.prototype.removeAt = function (index) { LinkedList.prototype.removeAt = function (index) {
index--; index--
var currentNode = this.head; var currentNode = this.head
var previousNode; var previousNode
var currentIndex = 0; var currentIndex = 0
//Check if index is present in list // Check if index is present in list
if (index < 0 || index >= this.length) { if (index < 0 || index >= this.length) {
return null; return null
} }
//Check if element is the first element // Check if element is the first element
if (index === 0) { if (index === 0) {
this.head = currentNode.next; this.head = currentNode.next
} } else {
else {
while (currentIndex < index) { while (currentIndex < index) {
currentIndex++; currentIndex++
previousNode = currentNode; previousNode = currentNode
currentNode = currentNode.next; currentNode = currentNode.next
} }
previousNode.next = currentNode.next; previousNode.next = currentNode.next
} }
//Decrementing the length // Decrementing the length
this.length--; this.length--
return currentNode.element; return currentNode.element
}; }
//Function to view the LinkedList // Function to view the LinkedList
LinkedList.prototype.view = function () { LinkedList.prototype.view = function () {
var currentNode = this.head; var currentNode = this.head
var count = 0; var count = 0
while (count < this.length) { while (count < this.length) {
count++; count++
console.log(currentNode.element); console.log(currentNode.element)
currentNode = currentNode.next; currentNode = currentNode.next
}
} }
};
// returns the constructor // returns the constructor
return LinkedList; return LinkedList
}())
}()); // Implementation of LinkedList
var linklist = new LinkedList()
//Implementation of LinkedList linklist.add(2)
var linklist = new LinkedList(); linklist.add(5)
linklist.add(2); linklist.add(8)
linklist.add(5); linklist.add(12)
linklist.add(8); linklist.add(17)
linklist.add(12); console.log(linklist.size())
linklist.add(17); console.log(linklist.removeAt(4))
console.log(linklist.size()); linklist.addAt(4, 15)
console.log(linklist.removeAt(4)); console.log(linklist.indexOf(8))
linklist.addAt(4, 15); console.log(linklist.size())
console.log(linklist.indexOf(8)); linklist.view()
console.log(linklist.size());
linklist.view();

View File

@ -5,80 +5,76 @@
* implementation uses an array to store the queue. * implementation uses an array to store the queue.
*/ */
//Functions: enqueue, dequeue, peek, view, length // Functions: enqueue, dequeue, peek, view, length
var Queue = (function () { var Queue = (function () {
// constructor // constructor
function Queue() { function Queue () {
// This is the array representation of the queue
//This is the array representation of the queue this.queue = []
this.queue = [];
} }
// methods // methods
//Add a value to the end of the queue // Add a value to the end of the queue
Queue.prototype.enqueue = function (item) { Queue.prototype.enqueue = function (item) {
this.queue[this.queue.length] = item; this.queue[this.queue.length] = item
};
//Removes the value at the front of the queue
Queue.prototype.dequeue = function () {
if (this.queue.length === 0) {
throw "Queue is Empty";
} }
var result = this.queue[0]; // Removes the value at the front of the queue
this.queue.splice(0, 1); //remove the item at position 0 from the array Queue.prototype.dequeue = function () {
if (this.queue.length === 0) {
throw 'Queue is Empty'
}
return result; var result = this.queue[0]
}; this.queue.splice(0, 1) // remove the item at position 0 from the array
//Return the length of the queue return result
}
// Return the length of the queue
Queue.prototype.length = function () { Queue.prototype.length = function () {
return this.queue.length; return this.queue.length
}; }
//Return the item at the front of the queue // Return the item at the front of the queue
Queue.prototype.peek = function () { Queue.prototype.peek = function () {
return this.queue[0]; return this.queue[0]
}; }
//List all the items in the queue // List all the items in the queue
Queue.prototype.view = function () { Queue.prototype.view = function () {
console.log(this.queue); console.log(this.queue)
}; }
return Queue; return Queue
}())
}()); // Implementation
var myQueue = new Queue()
//Implementation myQueue.enqueue(1)
var myQueue = new Queue(); myQueue.enqueue(5)
myQueue.enqueue(76)
myQueue.enqueue(69)
myQueue.enqueue(32)
myQueue.enqueue(54)
myQueue.enqueue(1); myQueue.view()
myQueue.enqueue(5);
myQueue.enqueue(76);
myQueue.enqueue(69);
myQueue.enqueue(32);
myQueue.enqueue(54);
myQueue.view(); console.log('Length: ' + myQueue.length())
console.log('Front item: ' + myQueue.peek())
console.log("Length: " + myQueue.length()); console.log('Removed ' + myQueue.dequeue() + ' from front.')
console.log("Front item: " + myQueue.peek()); console.log('New front item: ' + myQueue.peek())
console.log("Removed " + myQueue.dequeue() + " from front."); console.log('Removed ' + myQueue.dequeue() + ' from front.')
console.log("New front item: " + myQueue.peek()); console.log('New front item: ' + myQueue.peek())
console.log("Removed " + myQueue.dequeue() + " from front."); myQueue.enqueue(55)
console.log("New front item: " + myQueue.peek()); console.log('Inserted 55')
myQueue.enqueue(55); console.log('New front item: ' + myQueue.peek())
console.log("Inserted 55");
console.log("New front item: " + myQueue.peek());
for (var i = 0; i < 5; i++) { for (var i = 0; i < 5; i++) {
myQueue.dequeue(); myQueue.dequeue()
myQueue.view(); myQueue.view()
} }
//console.log(myQueue.dequeue()); // throws exception! // console.log(myQueue.dequeue()); // throws exception!

View File

@ -7,69 +7,66 @@
// Functions: push, pop, peek, view, length // Functions: push, pop, peek, view, length
//Creates a stack constructor // Creates a stack constructor
var Stack = (function () { var Stack = (function () {
function Stack () {
function Stack() { // The top of the Stack
//The top of the Stack this.top = 0
this.top = 0; // The array representation of the stack
//The array representation of the stack this.stack = new Array()
this.stack = new Array();
} }
//Adds a value onto the end of the stack // Adds a value onto the end of the stack
Stack.prototype.push = function (value) { Stack.prototype.push = function (value) {
this.stack[this.top] = value; this.stack[this.top] = value
this.top++; this.top++
}; }
//Removes and returns the value at the end of the stack // Removes and returns the value at the end of the stack
Stack.prototype.pop = function () { Stack.prototype.pop = function () {
if (this.top === 0) { if (this.top === 0) {
return "Stack is Empty"; return 'Stack is Empty'
} }
this.top--; this.top--
var result = this.stack[this.top]; var result = this.stack[this.top]
delete this.stack[this.top]; delete this.stack[this.top]
return result; return result
}; }
//Returns the size of the stack // Returns the size of the stack
Stack.prototype.size = function () { Stack.prototype.size = function () {
return this.top; return this.top
};
//Returns the value at the end of the stack
Stack.prototype.peek = function () {
return this.stack[this.top - 1];
} }
//To see all the elements in the stack // Returns the value at the end of the stack
Stack.prototype.peek = function () {
return this.stack[this.top - 1]
}
// To see all the elements in the stack
Stack.prototype.view = function () { Stack.prototype.view = function () {
for (var i = 0; i < this.top; i++) for (var i = 0; i < this.top; i++) { console.log(this.stack[i]) }
console.log(this.stack[i]); }
};
return Stack; return Stack
}())
}()); // Implementation
var myStack = new Stack()
//Implementation myStack.push(1)
var myStack = new Stack(); myStack.push(5)
myStack.push(76)
myStack.push(1); myStack.push(69)
myStack.push(5); myStack.push(32)
myStack.push(76); myStack.push(54)
myStack.push(69); console.log(myStack.size())
myStack.push(32); console.log(myStack.peek())
myStack.push(54); console.log(myStack.pop())
console.log(myStack.size()); console.log(myStack.peek())
console.log(myStack.peek()); console.log(myStack.pop())
console.log(myStack.pop()); console.log(myStack.peek())
console.log(myStack.peek()); myStack.push(55)
console.log(myStack.pop()); console.log(myStack.peek())
console.log(myStack.peek()); myStack.view()
myStack.push(55);
console.log(myStack.peek());
myStack.view();

View File

@ -1,4 +1,4 @@
/*Binary Search Tree!! /* Binary Search Tree!!
* *
* Nodes that will go on the Binary Tree. * Nodes that will go on the Binary Tree.
* They consist of the data in them, the node to the left, the node * They consist of the data in them, the node to the left, the node
@ -13,104 +13,102 @@
// class Node // class Node
var Node = (function () { var Node = (function () {
// Node in the tree // Node in the tree
function Node(val) { function Node (val) {
this.value = val; this.value = val
this.left = null; this.left = null
this.right = null; this.right = null
} }
// Search the tree for a value // Search the tree for a value
Node.prototype.search = function (val) { Node.prototype.search = function (val) {
if (this.value == val) { if (this.value == val) {
return this; return this
} else if (val < this.value && this.left != null) { } else if (val < this.value && this.left != null) {
return this.left.search(val); return this.left.search(val)
} else if (val > this.value && this.right != null) { } else if (val > this.value && this.right != null) {
return this.right.search(val); return this.right.search(val)
}
return null
} }
return null;
};
// Visit a node // Visit a node
Node.prototype.visit = function () { Node.prototype.visit = function () {
// Recursively go left // Recursively go left
if (this.left != null) { if (this.left != null) {
this.left.visit(); this.left.visit()
} }
// Print out value // Print out value
console.log(this.value); console.log(this.value)
// Recursively go right // Recursively go right
if (this.right != null) { if (this.right != null) {
this.right.visit(); this.right.visit()
}
} }
};
// Add a node // Add a node
Node.prototype.addNode = function (n) { Node.prototype.addNode = function (n) {
if (n.value < this.value) { if (n.value < this.value) {
if (this.left == null) { if (this.left == null) {
this.left = n; this.left = n
} else { } else {
this.left.addNode(n) this.left.addNode(n)
} }
} else if (n.value > this.value) { } else if (n.value > this.value) {
if (this.right == null) { if (this.right == null) {
this.right = n; this.right = n
} else { } else {
this.right.addNode(n); this.right.addNode(n)
}
} }
} }
};
// returns the constructor // returns the constructor
return Node; return Node
}()); }())
// class Tree // class Tree
var Tree = (function () { var Tree = (function () {
function Tree() { function Tree () {
// Just store the root // Just store the root
this.root = null; this.root = null
}; };
// Inorder traversal // Inorder traversal
Tree.prototype.traverse = function () { Tree.prototype.traverse = function () {
this.root.visit(); this.root.visit()
}; }
// Start by searching the root // Start by searching the root
Tree.prototype.search = function (val) { Tree.prototype.search = function (val) {
let found = this.root.search(val); const found = this.root.search(val)
if (found === null) { if (found === null) {
console.log(val + " not found"); console.log(val + ' not found')
} else {
console.log('Found:' + found.value)
} }
else {
console.log("Found:" + found.value);
} }
};
// Add a new value to the tree // Add a new value to the tree
Tree.prototype.addValue = function (val) { Tree.prototype.addValue = function (val) {
let n = new Node(val); const n = new Node(val)
if (this.root == null) { if (this.root == null) {
this.root = n; this.root = n
} else { } else {
this.root.addNode(n); this.root.addNode(n)
}
} }
};
// returns the constructor // returns the constructor
return Tree; return Tree
}()); }())
//Implementation of BST // Implementation of BST
var bst = new Tree(); var bst = new Tree()
bst.addValue(6); bst.addValue(6)
bst.addValue(3); bst.addValue(3)
bst.addValue(9); bst.addValue(9)
bst.addValue(2); bst.addValue(2)
bst.addValue(8); bst.addValue(8)
bst.addValue(4); bst.addValue(4)
bst.traverse(); bst.traverse()
bst.search(8); bst.search(8)

View File

@ -1,12 +1,12 @@
//================================================================ //= ===============================================================
// SHA1.js // SHA1.js
// //
// Module that replicates the SHA-1 Cryptographic Hash // Module that replicates the SHA-1 Cryptographic Hash
// function in Javascript. // function in Javascript.
//================================================================ //= ===============================================================
//main variables // main variables
const CHAR_SIZE = 8; const CHAR_SIZE = 8
/** /**
* Adds padding to binary/hex string represention * Adds padding to binary/hex string represention
@ -18,12 +18,12 @@ const CHAR_SIZE = 8;
* @example * @example
* pad("10011", 8); // "00010011" * pad("10011", 8); // "00010011"
*/ */
function pad(str, bits) { function pad (str, bits) {
let res = str; let res = str
while (res.length % bits !== 0) { while (res.length % bits !== 0) {
res = "0" + res; res = '0' + res
} }
return res; return res
} }
/** /**
@ -36,12 +36,12 @@ function pad(str, bits) {
* @example * @example
* chunkify("this is a test", 2); // ["th", "is", " i", "s ", "a ", "te", "st"] * chunkify("this is a test", 2); // ["th", "is", " i", "s ", "a ", "te", "st"]
*/ */
function chunkify(str, size) { function chunkify (str, size) {
let chunks = []; const chunks = []
for (let i = 0; i < str.length; i += size) { for (let i = 0; i < str.length; i += size) {
chunks.push(str.slice(i, i + size)); chunks.push(str.slice(i, i + size))
} }
return chunks; return chunks
} }
/** /**
@ -54,8 +54,8 @@ function chunkify(str, size) {
* @example * @example
* rotateLeft("1011", 3); // "1101" * rotateLeft("1011", 3); // "1101"
*/ */
function rotateLeft(bits, turns) { function rotateLeft (bits, turns) {
return bits.substr(turns) + bits.substr(0, turns); return bits.substr(turns) + bits.substr(0, turns)
} }
/** /**
@ -64,27 +64,27 @@ function rotateLeft(bits, turns) {
* @param {string} message - message to pre-process * @param {string} message - message to pre-process
* @return {string} - processed message * @return {string} - processed message
*/ */
function preProcess(message) { function preProcess (message) {
//convert message to binary representation padded to // convert message to binary representation padded to
//8 bits, and add 1 // 8 bits, and add 1
let m = message.split("") let m = message.split('')
.map(e => e.charCodeAt(0)) .map(e => e.charCodeAt(0))
.map(e => e.toString(2)) .map(e => e.toString(2))
.map(e => pad(e, 8)) .map(e => pad(e, 8))
.join("") + "1"; .join('') + '1'
//extend message by adding empty bits (0) // extend message by adding empty bits (0)
while (m.length % 512 !== 448) { while (m.length % 512 !== 448) {
m += "0"; m += '0'
} }
//length of message in binary, padded, and extended // length of message in binary, padded, and extended
//to a 64 bit representation // to a 64 bit representation
let ml = (message.length * CHAR_SIZE).toString(2); let ml = (message.length * CHAR_SIZE).toString(2)
ml = pad(ml, 8); ml = pad(ml, 8)
ml = "0".repeat(64 - ml.length) + ml; ml = '0'.repeat(64 - ml.length) + ml
return m + ml; return m + ml
} }
/** /**
@ -93,90 +93,85 @@ function preProcess(message) {
* @param {string} message - message to hash * @param {string} message - message to hash
* @return {string} - message digest (hash value) * @return {string} - message digest (hash value)
*/ */
function SHA1(message) { function SHA1 (message) {
//main variables // main variables
let H0 = 0x67452301; let H0 = 0x67452301
let H1 = 0xEFCDAB89; let H1 = 0xEFCDAB89
let H2 = 0x98BADCFE; let H2 = 0x98BADCFE
let H3 = 0x10325476; let H3 = 0x10325476
let H4 = 0xC3D2E1F0; let H4 = 0xC3D2E1F0
//pre-process message and split into 512 bit chunks // pre-process message and split into 512 bit chunks
let bits = preProcess(message); const bits = preProcess(message)
let chunks = chunkify(bits, 512); const chunks = chunkify(bits, 512)
chunks.forEach(function(chunk, i) { chunks.forEach(function (chunk, i) {
//break each chunk into 16 32-bit words // break each chunk into 16 32-bit words
let words = chunkify(chunk, 32); const words = chunkify(chunk, 32)
//extend 16 32-bit words to 80 32-bit words // extend 16 32-bit words to 80 32-bit words
for (let i = 16; i < 80; i++) { for (let i = 16; i < 80; i++) {
let val = [words[i - 3], words[i - 8], words[i - 14], words[i - 16]] const val = [words[i - 3], words[i - 8], words[i - 14], words[i - 16]]
.map(e => parseInt(e, 2)) .map(e => parseInt(e, 2))
.reduce((acc, curr) => curr ^ acc, 0); .reduce((acc, curr) => curr ^ acc, 0)
let bin = (val >>> 0).toString(2); const bin = (val >>> 0).toString(2)
let paddedBin = pad(bin, 32); const paddedBin = pad(bin, 32)
let word = rotateLeft(paddedBin, 1); const word = rotateLeft(paddedBin, 1)
words.push(word); words.push(word)
} }
//initialize variables for this chunk // initialize variables for this chunk
let [a, b, c, d, e] = [H0, H1, H2, H3, H4]; let [a, b, c, d, e] = [H0, H1, H2, H3, H4]
for (let i = 0; i < 80; i++) { for (let i = 0; i < 80; i++) {
let f, k; let f, k
if (i < 20) { if (i < 20) {
f = (b & c) | (~b & d); f = (b & c) | (~b & d)
k = 0x5A827999; k = 0x5A827999
} else if (i < 40) {
f = b ^ c ^ d
k = 0x6ED9EBA1
} else if (i < 60) {
f = (b & c) | (b & d) | (c & d)
k = 0x8F1BBCDC
} else {
f = b ^ c ^ d
k = 0xCA62C1D6
} }
else if (i < 40) { // make sure f is unsigned
f = b ^ c ^ d; f >>>= 0
k = 0x6ED9EBA1;
}
else if (i < 60) {
f = (b & c) | (b & d) | (c & d);
k = 0x8F1BBCDC;
}
else {
f = b ^ c ^ d;
k = 0xCA62C1D6;
}
//make sure f is unsigned
f >>>= 0;
let aRot = rotateLeft(pad(a.toString(2), 32), 5);
let aInt = parseInt(aRot, 2) >>> 0;
let wordInt = parseInt(words[i], 2) >>> 0;
let t = aInt + f + e + k + wordInt;
e = d >>> 0;
d = c >>> 0;
let bRot = rotateLeft(pad(b.toString(2), 32), 30);
c = parseInt(bRot, 2) >>> 0;
b = a >>> 0;
a = t >>> 0;
const aRot = rotateLeft(pad(a.toString(2), 32), 5)
const aInt = parseInt(aRot, 2) >>> 0
const wordInt = parseInt(words[i], 2) >>> 0
const t = aInt + f + e + k + wordInt
e = d >>> 0
d = c >>> 0
const bRot = rotateLeft(pad(b.toString(2), 32), 30)
c = parseInt(bRot, 2) >>> 0
b = a >>> 0
a = t >>> 0
} }
//add values for this chunk to main hash variables (unsigned) // add values for this chunk to main hash variables (unsigned)
H0 = (H0 + a) >>> 0; H0 = (H0 + a) >>> 0
H1 = (H1 + b) >>> 0; H1 = (H1 + b) >>> 0
H2 = (H2 + c) >>> 0; H2 = (H2 + c) >>> 0
H3 = (H3 + d) >>> 0; H3 = (H3 + d) >>> 0
H4 = (H4 + e) >>> 0; H4 = (H4 + e) >>> 0
}); })
//combine hash values of main hash variables and return // combine hash values of main hash variables and return
let HH = [H0, H1, H2, H3, H4] const HH = [H0, H1, H2, H3, H4]
.map(e => e.toString(16)) .map(e => e.toString(16))
.map(e => pad(e, 8)) .map(e => pad(e, 8))
.join(""); .join('')
return HH; return HH
} }
console.log(SHA1("A Test")); console.log(SHA1('A Test'))
console.log(SHA1("A Test")); console.log(SHA1('A Test'))
//export SHA1 function
module.exports = SHA1;
// export SHA1 function
module.exports = SHA1

View File

@ -1,12 +1,12 @@
//================================================================ //= ===============================================================
// SHA256.js // SHA256.js
// //
// Module that replicates the SHA-256 Cryptographic Hash // Module that replicates the SHA-256 Cryptographic Hash
// function in Javascript. // function in Javascript.
//================================================================ //= ===============================================================
//main variables // main variables
const CHAR_SIZE = 8; const CHAR_SIZE = 8
const K = [ const K = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
@ -17,7 +17,7 @@ const K = [
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
]; ]
/** /**
* Adds padding to binary/hex string represention * Adds padding to binary/hex string represention
@ -29,12 +29,12 @@ const K = [
* @example * @example
* pad("10011", 8); // "00010011" * pad("10011", 8); // "00010011"
*/ */
function pad(str, bits) { function pad (str, bits) {
let res = str; let res = str
while (res.length % bits !== 0) { while (res.length % bits !== 0) {
res = "0" + res; res = '0' + res
} }
return res; return res
} }
/** /**
@ -47,12 +47,12 @@ function pad(str, bits) {
* @example * @example
* chunkify("this is a test", 2); // ["th", "is", " i", "s ", "a ", "te", "st"] * chunkify("this is a test", 2); // ["th", "is", " i", "s ", "a ", "te", "st"]
*/ */
function chunkify(str, size) { function chunkify (str, size) {
let chunks = []; const chunks = []
for (let i = 0; i < str.length; i += size) { for (let i = 0; i < str.length; i += size) {
chunks.push(str.slice(i, i + size)); chunks.push(str.slice(i, i + size))
} }
return chunks; return chunks
} }
/** /**
@ -65,8 +65,8 @@ function chunkify(str, size) {
* @example * @example
* rotateLeft("1011", 3); // "1101" * rotateLeft("1011", 3); // "1101"
*/ */
function rotateRight(bits, turns) { function rotateRight (bits, turns) {
return bits.substr(bits.length - turns) + bits.substr(0, bits.length - turns); return bits.substr(bits.length - turns) + bits.substr(0, bits.length - turns)
} }
/** /**
@ -75,27 +75,27 @@ function rotateRight(bits, turns) {
* @param {string} message - message to pre-process * @param {string} message - message to pre-process
* @return {string} - processed message * @return {string} - processed message
*/ */
function preProcess(message) { function preProcess (message) {
//covert message to binary representation padded to // covert message to binary representation padded to
//8 bits, and add 1 // 8 bits, and add 1
let m = message.split("") let m = message.split('')
.map(e => e.charCodeAt(0)) .map(e => e.charCodeAt(0))
.map(e => e.toString(2)) .map(e => e.toString(2))
.map(e => pad(e, 8)) .map(e => pad(e, 8))
.join("") + "1"; .join('') + '1'
//extend message by adding empty bits (0) // extend message by adding empty bits (0)
while (m.length % 512 !== 448) { while (m.length % 512 !== 448) {
m += "0"; m += '0'
} }
//length of message in binary, padded, and extended // length of message in binary, padded, and extended
//to a 64 bit representation // to a 64 bit representation
let ml = (message.length * CHAR_SIZE).toString(2); let ml = (message.length * CHAR_SIZE).toString(2)
ml = pad(ml, 8); ml = pad(ml, 8)
ml = "0".repeat(64 - ml.length) + ml; ml = '0'.repeat(64 - ml.length) + ml
return m + ml; return m + ml
} }
/** /**
@ -104,85 +104,85 @@ function preProcess(message) {
* @param {string} message - message to hash * @param {string} message - message to hash
* @return {string} - message digest (hash value) * @return {string} - message digest (hash value)
*/ */
function SHA256(message) { function SHA256 (message) {
//initial hash variables // initial hash variables
let H0 = 0x6a09e667; let H0 = 0x6a09e667
let H1 = 0xbb67ae85; let H1 = 0xbb67ae85
let H2 = 0x3c6ef372; let H2 = 0x3c6ef372
let H3 = 0xa54ff53a; let H3 = 0xa54ff53a
let H4 = 0x510e527f; let H4 = 0x510e527f
let H5 = 0x9b05688c; let H5 = 0x9b05688c
let H6 = 0x1f83d9ab; let H6 = 0x1f83d9ab
let H7 = 0x5be0cd19; let H7 = 0x5be0cd19
//pre-process message and split into 512 bit chunks // pre-process message and split into 512 bit chunks
let bits = preProcess(message); const bits = preProcess(message)
let chunks = chunkify(bits, 512); const chunks = chunkify(bits, 512)
chunks.forEach(function(chunk, i) { chunks.forEach(function (chunk, i) {
//break each chunk into 16 32-bit words // break each chunk into 16 32-bit words
let words = chunkify(chunk, 32); const words = chunkify(chunk, 32)
//extend 16 32-bit words to 80 32-bit words // extend 16 32-bit words to 80 32-bit words
for (let i = 16; i < 64; i++) { for (let i = 16; i < 64; i++) {
const W1 = words[i - 15]; const W1 = words[i - 15]
const W2 = words[i - 2]; const W2 = words[i - 2]
const R1 = rotateRight(W1, 7); const R1 = rotateRight(W1, 7)
const R2 = rotateRight(W1, 18); const R2 = rotateRight(W1, 18)
const R3 = rotateRight(W2, 17); const R3 = rotateRight(W2, 17)
const R4 = rotateRight(W2, 19); const R4 = rotateRight(W2, 19)
const S0 = parseInt(R1, 2) ^ parseInt(R2, 2) ^ (parseInt(W1, 2) >>> 3); const S0 = parseInt(R1, 2) ^ parseInt(R2, 2) ^ (parseInt(W1, 2) >>> 3)
const S1 = parseInt(R3, 2) ^ parseInt(R4, 2) ^ (parseInt(W2, 2) >>> 10); const S1 = parseInt(R3, 2) ^ parseInt(R4, 2) ^ (parseInt(W2, 2) >>> 10)
const val = parseInt(words[i - 16], 2) + S0 + parseInt(words[i - 7], 2) + S1; const val = parseInt(words[i - 16], 2) + S0 + parseInt(words[i - 7], 2) + S1
words[i] = pad((val >>> 0).toString(2), 32); words[i] = pad((val >>> 0).toString(2), 32)
} }
//initialize variables for this chunk // initialize variables for this chunk
let [a, b, c, d, e, f, g, h] = [H0, H1, H2, H3, H4, H5, H6, H7]; let [a, b, c, d, e, f, g, h] = [H0, H1, H2, H3, H4, H5, H6, H7]
for (let i = 0; i < 64; i++) { for (let i = 0; i < 64; i++) {
const S1 = [6, 11, 25] const S1 = [6, 11, 25]
.map(turns => rotateRight(pad(e.toString(2), 32), turns)) .map(turns => rotateRight(pad(e.toString(2), 32), turns))
.map(bitstring => parseInt(bitstring, 2)) .map(bitstring => parseInt(bitstring, 2))
.reduce((acc, curr) => acc ^ curr, 0) >>> 0; .reduce((acc, curr) => acc ^ curr, 0) >>> 0
const CH = ((e & f) ^ (~e & g)) >>> 0; const CH = ((e & f) ^ (~e & g)) >>> 0
const temp1 = (h + S1 + CH + K[i] + parseInt(words[i], 2)) >>> 0; const temp1 = (h + S1 + CH + K[i] + parseInt(words[i], 2)) >>> 0
const S0 = [2, 13, 22] const S0 = [2, 13, 22]
.map(turns => rotateRight(pad(a.toString(2), 32), turns)) .map(turns => rotateRight(pad(a.toString(2), 32), turns))
.map(bitstring => parseInt(bitstring, 2)) .map(bitstring => parseInt(bitstring, 2))
.reduce((acc, curr) => acc ^ curr, 0) >>> 0; .reduce((acc, curr) => acc ^ curr, 0) >>> 0
const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0; const maj = ((a & b) ^ (a & c) ^ (b & c)) >>> 0
const temp2 = (S0 + maj) >>> 0; const temp2 = (S0 + maj) >>> 0
h = g; h = g
g = f; g = f
f = e; f = e
e = (d + temp1) >>> 0; e = (d + temp1) >>> 0
d = c; d = c
c = b; c = b
b = a; b = a
a = (temp1 + temp2) >>> 0; a = (temp1 + temp2) >>> 0
} }
//add values for this chunk to main hash variables (unsigned) // add values for this chunk to main hash variables (unsigned)
H0 = (H0 + a) >>> 0; H0 = (H0 + a) >>> 0
H1 = (H1 + b) >>> 0; H1 = (H1 + b) >>> 0
H2 = (H2 + c) >>> 0; H2 = (H2 + c) >>> 0
H3 = (H3 + d) >>> 0; H3 = (H3 + d) >>> 0
H4 = (H4 + e) >>> 0; H4 = (H4 + e) >>> 0
H5 = (H5 + f) >>> 0; H5 = (H5 + f) >>> 0
H6 = (H6 + g) >>> 0; H6 = (H6 + g) >>> 0
H7 = (H7 + h) >>> 0; H7 = (H7 + h) >>> 0
}); })
//combine hash values of main hash variables and return // combine hash values of main hash variables and return
let HH = [H0, H1, H2, H3, H4, H5, H6, H7] const HH = [H0, H1, H2, H3, H4, H5, H6, H7]
.map(e => e.toString(16)) .map(e => e.toString(16))
.map(e => pad(e, 8)) .map(e => pad(e, 8))
.join(""); .join('')
return HH; return HH
} }
//export SHA256 function // export SHA256 function
module.exports = SHA256; module.exports = SHA256

View File

@ -1,27 +1,26 @@
/*Binary Search-Search a sorted array by repeatedly dividing the search interval /* Binary Search-Search a sorted array by repeatedly dividing the search interval
* in half. Begin with an interval covering the whole array. If the value of the * in half. Begin with an interval covering the whole array. If the value of the
* search key is less than the item in the middle of the interval, narrow the interval * search key is less than the item in the middle of the interval, narrow the interval
* to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the * to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the
* value is found or the interval is empty. * value is found or the interval is empty.
*/ */
function binarySearch(arr, i) { function binarySearch (arr, i) {
var mid = Math.floor(arr.length / 2); var mid = Math.floor(arr.length / 2)
if (arr[mid] === i) { if (arr[mid] === i) {
console.log("match", arr[mid], i); console.log('match', arr[mid], i)
return arr[mid]; return arr[mid]
} else if (arr[mid] < i && arr.length > 1) { } else if (arr[mid] < i && arr.length > 1) {
binarySearch(arr.splice(mid, Number.MAX_VALUE), i); binarySearch(arr.splice(mid, Number.MAX_VALUE), i)
} else if (arr[mid] > i && arr.length > 1) { } else if (arr[mid] > i && arr.length > 1) {
binarySearch(arr.splice(0, mid), i); binarySearch(arr.splice(0, mid), i)
} else { } else {
console.log("not found", i); console.log('not found', i)
return -1; return -1
} }
} }
var ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
binarySearch(ar, 3); binarySearch(ar, 3)
binarySearch(ar, 7); binarySearch(ar, 7)
binarySearch(ar, 13); binarySearch(ar, 13)

View File

@ -6,30 +6,30 @@
*/ */
const jumpSearch = (arr, value) => { const jumpSearch = (arr, value) => {
const length = arr.length; const length = arr.length
let step = Math.floor(Math.sqrt(length)); let step = Math.floor(Math.sqrt(length))
let lowerBound = 0; let lowerBound = 0
while (arr[Math.min(step, length) - 1] < value) { while (arr[Math.min(step, length) - 1] < value) {
lowerBound = step; lowerBound = step
step += step; step += step
if (lowerBound >= length) { if (lowerBound >= length) {
return -1; return -1
} }
} }
const upperBound = Math.min(step, length); const upperBound = Math.min(step, length)
while (arr[lowerBound] < value) { while (arr[lowerBound] < value) {
lowerBound++; lowerBound++
if (lowerBound === upperBound) { if (lowerBound === upperBound) {
return -1; return -1
} }
} }
if (arr[lowerBound] === value) { if (arr[lowerBound] === value) {
return lowerBound; return lowerBound
} }
return -1; return -1
} }
const arr = [0,0,4,7,10,23,34,40,55,68,77,90] const arr = [0, 0, 4, 7, 10, 23, 34, 40, 55, 68, 77, 90]
jumpSearch(arr,4); jumpSearch(arr, 4)
jumpSearch(arr,34); jumpSearch(arr, 34)
jumpSearch(arr,77); jumpSearch(arr, 77)

View File

@ -4,24 +4,24 @@
* for the target value until a match is found or until all the elements * for the target value until a match is found or until all the elements
* have been searched. * have been searched.
*/ */
function SearchArray(searchNum, ar) { function SearchArray (searchNum, ar) {
var position = Search(ar, searchNum); var position = Search(ar, searchNum)
if (position != -1) { if (position != -1) {
console.log("The element was found at " + (position + 1)); console.log('The element was found at ' + (position + 1))
} else { } else {
console.log("The element not found"); console.log('The element not found')
} }
} }
// Search “theArray” for the specified “key” value // Search “theArray” for the specified “key” value
function Search(theArray, key) { function Search (theArray, key) {
for (var n = 0; n < theArray.length; n++) for (var n = 0; n < theArray.length; n++) {
if (theArray[n] == key) if (theArray[n] == key) { return n }
return n; }
return -1; return -1
} }
var ar = [1, 2, 3, 4, 5, 6, 7, 8, 9]; var ar = [1, 2, 3, 4, 5, 6, 7, 8, 9]
SearchArray(3, ar); SearchArray(3, ar)
SearchArray(4, ar); SearchArray(4, ar)
SearchArray(11, ar); SearchArray(11, ar)

View File

@ -1,59 +1,58 @@
function TopologicalSorter() { function TopologicalSorter () {
var graph = {}, var graph = {}
isVisitedNode, var isVisitedNode
finishTimeCount, var finishTimeCount
finishingTimeList, var finishingTimeList
nextNode; var nextNode
this.addOrder = function (nodeA, nodeB) { this.addOrder = function (nodeA, nodeB) {
nodeA = String(nodeA); nodeA = String(nodeA)
nodeB = String(nodeB); nodeB = String(nodeB)
graph[nodeA] = graph[nodeA] || []; graph[nodeA] = graph[nodeA] || []
graph[nodeA].push(nodeB); graph[nodeA].push(nodeB)
} }
this.sortAndGetOrderedItems = function () { this.sortAndGetOrderedItems = function () {
isVisitedNode = Object.create(null); isVisitedNode = Object.create(null)
finishTimeCount = 0; finishTimeCount = 0
finishingTimeList = []; finishingTimeList = []
for (var node in graph) { for (var node in graph) {
if (graph.hasOwnProperty(node) && !isVisitedNode[node]) { if (graph.hasOwnProperty(node) && !isVisitedNode[node]) {
dfsTraverse(node); dfsTraverse(node)
} }
} }
finishingTimeList.sort(function (item1, item2) { finishingTimeList.sort(function (item1, item2) {
return item1.finishTime > item2.finishTime ? -1 : 1; return item1.finishTime > item2.finishTime ? -1 : 1
}); })
return finishingTimeList.map(function (value) { return value.node }) return finishingTimeList.map(function (value) { return value.node })
} }
function dfsTraverse(node) { function dfsTraverse (node) {
isVisitedNode[node] = true; isVisitedNode[node] = true
if (graph[node]) { if (graph[node]) {
for (var i = 0; i < graph[node].length; i++) { for (var i = 0; i < graph[node].length; i++) {
nextNode = graph[node][i]; nextNode = graph[node][i]
if (isVisitedNode[nextNode]) continue; if (isVisitedNode[nextNode]) continue
dfsTraverse(nextNode); dfsTraverse(nextNode)
} }
} }
finishingTimeList.push({ finishingTimeList.push({
node: node, node: node,
finishTime: ++finishTimeCount finishTime: ++finishTimeCount
}); })
} }
} }
/* TEST */ /* TEST */
var topoSorter = new TopologicalSorter(); var topoSorter = new TopologicalSorter()
topoSorter.addOrder(5, 2); topoSorter.addOrder(5, 2)
topoSorter.addOrder(5, 0); topoSorter.addOrder(5, 0)
topoSorter.addOrder(4, 0); topoSorter.addOrder(4, 0)
topoSorter.addOrder(4, 1); topoSorter.addOrder(4, 1)
topoSorter.addOrder(2, 3); topoSorter.addOrder(2, 3)
topoSorter.addOrder(3, 1); topoSorter.addOrder(3, 1)
console.log(topoSorter.sortAndGetOrderedItems()); console.log(topoSorter.sortAndGetOrderedItems())

View File

@ -3,53 +3,49 @@
* sorted in ascending order. * sorted in ascending order.
*/ */
Array.prototype.isSorted = function () { Array.prototype.isSorted = function () {
const length = this.length
let length = this.length;
if (length < 2) { if (length < 2) {
return true; return true
} }
for (let i = 0; i < length - 1; i++) { for (let i = 0; i < length - 1; i++) {
if (this[i] > this[i + 1]) { if (this[i] > this[i + 1]) {
return false; return false
} }
} }
return true; return true
}; }
/* /*
* A simple helper function to shuffle the array randomly in place. * A simple helper function to shuffle the array randomly in place.
*/ */
Array.prototype.shuffle = function () { Array.prototype.shuffle = function () {
for (let i = this.length - 1; i; i--) { for (let i = this.length - 1; i; i--) {
let m = Math.floor(Math.random() * i); const m = Math.floor(Math.random() * i)
let n = this[i - 1]; const n = this[i - 1]
this[i - 1] = this[m]; this[i - 1] = this[m]
this[m] = n; this[m] = n
} }
}
};
/* /*
* Implementation of the bogosort algorithm. This sorting algorithm randomly * Implementation of the bogosort algorithm. This sorting algorithm randomly
* rearranges the array until it is sorted. * rearranges the array until it is sorted.
* For more information see: https://en.wikipedia.org/wiki/Bogosort * For more information see: https://en.wikipedia.org/wiki/Bogosort
*/ */
function bogoSort(items) { function bogoSort (items) {
while (!items.isSorted()) { while (!items.isSorted()) {
items.shuffle() items.shuffle()
} }
return items; return items
} }
//Implementation of bogoSort // Implementation of bogoSort
var ar = [5, 6, 7, 8, 1, 2, 12, 14]; var ar = [5, 6, 7, 8, 1, 2, 12, 14]
//Array before Sort // Array before Sort
console.log(ar); console.log(ar)
bogoSort(ar); bogoSort(ar)
//Array after sort // Array after sort
console.log(ar); console.log(ar)

View File

@ -11,52 +11,50 @@ Time Complexity of Solution:
Best Case O(n); Average Case O(n); Worst Case O(n) Best Case O(n); Average Case O(n); Worst Case O(n)
*/ */
function bucketSort(list, size){ function bucketSort (list, size) {
if (undefined === size) {
if(undefined === size){ size = 5
size = 5;
} }
if(list.length === 0){ if (list.length === 0) {
return list; return list
} }
let min = list[0]; let min = list[0]
let max = list[0]; let max = list[0]
// find min and max // find min and max
for(let iList = 0; iList < list.length; iList++){ for (let iList = 0; iList < list.length; iList++) {
if (list[iList] < min) {
if(list[iList] < min){ min = list[iList]
min = list[iList]; } else if (list[iList] > max) {
} else if(list[iList] > max){ max = list[iList]
max = list[iList];
} }
} }
// how many buckets we need // how many buckets we need
let count = Math.floor((max - min) / size) + 1; const count = Math.floor((max - min) / size) + 1
// create buckets // create buckets
let buckets = []; const buckets = []
for(let iCount = 0; iCount < count; iCount++){ for (let iCount = 0; iCount < count; iCount++) {
buckets.push([]); buckets.push([])
} }
// bucket fill // bucket fill
for(let iBucket = 0; iBucket < list.length; iBucket++){ for (let iBucket = 0; iBucket < list.length; iBucket++) {
let key = Math.floor((list[iBucket] - min) / size); const key = Math.floor((list[iBucket] - min) / size)
buckets[key].push(list[iBucket]); buckets[key].push(list[iBucket])
} }
let sorted = []; const sorted = []
// now sort every bucket and merge it to the sorted list // now sort every bucket and merge it to the sorted list
for(let iBucket = 0; iBucket < buckets.length; iBucket++){ for (let iBucket = 0; iBucket < buckets.length; iBucket++) {
let arr = buckets[iBucket].sort(); const arr = buckets[iBucket].sort()
for(let iSorted = 0; iSorted < arr.length; iSorted++){ for (let iSorted = 0; iSorted < arr.length; iSorted++) {
sorted.push(arr[iSorted]); sorted.push(arr[iSorted])
} }
} }
return sorted; return sorted
} }
let arrOrignal = [5, 6, 7, 8, 1, 2, 12, 14]; const arrOrignal = [5, 6, 7, 8, 1, 2, 12, 14]
//Array before Sort // Array before Sort
console.log(arrOrignal); console.log(arrOrignal)
arrSorted = bucketSort(arrOrignal); arrSorted = bucketSort(arrOrignal)
//Array after sort // Array after sort
console.log(arrSorted); console.log(arrSorted)

View File

@ -4,42 +4,41 @@
* more information: https://en.wikipedia.org/wiki/Bubble_sort * more information: https://en.wikipedia.org/wiki/Bubble_sort
* *
*/ */
function cocktailShakerSort(items) { function cocktailShakerSort (items) {
for (let i = items.length - 1; i > 0; i--) { for (let i = items.length - 1; i > 0; i--) {
let swapped = false; let swapped = false
let temp, j; let temp, j
// backwards // backwards
for (j = items.length -1; j > i; j--) { for (j = items.length - 1; j > i; j--) {
if (items[j] < items[j - 1]) { if (items[j] < items[j - 1]) {
temp = items[j]; temp = items[j]
items[j] = items[j - 1]; items[j] = items[j - 1]
items[j - 1] = temp; items[j - 1] = temp
swapped = true; swapped = true
} }
} }
//forwards // forwards
for (j = 0; j < i; j++) { for (j = 0; j < i; j++) {
if (items[j] > items[j + 1]) { if (items[j] > items[j + 1]) {
temp = items[j]; temp = items[j]
items[j] = items[j + 1]; items[j] = items[j + 1]
items[j + 1] = temp; items[j + 1] = temp
swapped = true; swapped = true
} }
} }
if (!swapped) { if (!swapped) {
return; return
} }
} }
} }
//Implementation of cocktailShakerSort // Implementation of cocktailShakerSort
var ar = [5, 6, 7, 8, 1, 2, 12, 14]; var ar = [5, 6, 7, 8, 1, 2, 12, 14]
//Array before Sort // Array before Sort
console.log(ar); console.log(ar)
cocktailShakerSort(ar); cocktailShakerSort(ar)
//Array after sort // Array after sort
console.log(ar); console.log(ar)

View File

@ -14,40 +14,37 @@ elements goes down (for each iteration of outer loop) in steps of
a "shrink factor" k: [ n/k, n/k2, n/k3, ..., 1 ]. a "shrink factor" k: [ n/k, n/k2, n/k3, ..., 1 ].
*/ */
function combSort(list) { function combSort (list) {
if (list.length === 0) { if (list.length === 0) {
return list; return list
} }
let shrink = 1.3; const shrink = 1.3
let gap = list.length; let gap = list.length
let isSwapped = true; let isSwapped = true
let i = 0 let i = 0
while (gap > 1 || isSwapped) { while (gap > 1 || isSwapped) {
// Update the gap value for a next comb // Update the gap value for a next comb
gap = parseInt(parseFloat(gap) / shrink, 10); gap = parseInt(parseFloat(gap) / shrink, 10)
isSwapped = false isSwapped = false
i = 0 i = 0
while (gap + i < list.length) { while (gap + i < list.length) {
if (list[i] > list[i + gap]) { if (list[i] > list[i + gap]) {
const value = list[i]
let value = list[i]; list[i] = list[i + gap]
list[i] = list[i + gap]; list[i + gap] = value
list[i + gap] = value; isSwapped = true
isSwapped = true;
} }
i += 1 i += 1
} }
} }
return list return list
} }
let arrOrignal = [5, 6, 7, 8, 1, 2, 12, 14]; const arrOrignal = [5, 6, 7, 8, 1, 2, 12, 14]
//Array before Sort // Array before Sort
console.log(arrOrignal); console.log(arrOrignal)
arrSorted = combSort(arrOrignal); arrSorted = combSort(arrOrignal)
//Array after sort // Array after sort
console.log(arrSorted); console.log(arrSorted)

View File

@ -5,33 +5,33 @@
* counting sort visualization: https://www.cs.usfca.edu/~galles/visualization/CountingSort.html * counting sort visualization: https://www.cs.usfca.edu/~galles/visualization/CountingSort.html
*/ */
function countingSort(arr, min, max) { function countingSort (arr, min, max) {
let i; let i
let z = 0; let z = 0
const count = []; const count = []
for (i = min; i <= max; i++) { for (i = min; i <= max; i++) {
count[i] = 0; count[i] = 0
} }
for (i = 0; i < arr.length; i++) { for (i = 0; i < arr.length; i++) {
count[arr[i]]++; count[arr[i]]++
} }
for (i = min; i <= max; i++) { for (i = min; i <= max; i++) {
while (count[i]-- > 0) { while (count[i]-- > 0) {
arr[z++] = i; arr[z++] = i
} }
} }
return arr; return arr
} }
const arr = [3, 0, 2, 5, 4, 1]; const arr = [3, 0, 2, 5, 4, 1]
// Array before Sort // Array before Sort
console.log("-----before sorting-----"); console.log('-----before sorting-----')
console.log(arr); console.log(arr)
// Array after sort // Array after sort
console.log("-----after sorting-----"); console.log('-----after sorting-----')
console.log(countingSort(arr, 0, 5)); console.log(countingSort(arr, 0, 5))

View File

@ -5,58 +5,54 @@ number of writes to the original array, unlike any other in-place sorting
algorithm. It is based on the idea that the permutation to be sorted can algorithm. It is based on the idea that the permutation to be sorted can
be factored into cycles, which can individually be rotated to give a sorted result. be factored into cycles, which can individually be rotated to give a sorted result.
*/ */
function cycleSort(list) { function cycleSort (list) {
let writes = 0
let writes = 0;
for (let cycleStart = 0; cycleStart < list.length; cycleStart++) { for (let cycleStart = 0; cycleStart < list.length; cycleStart++) {
let value = list[cycleStart]
let value = list[cycleStart]; let position = cycleStart
let position = cycleStart;
// search position // search position
for (let i = cycleStart+1; i < list.length; i++) { for (let i = cycleStart + 1; i < list.length; i++) {
if (list[i] < value) { if (list[i] < value) {
position++; position++
} }
} }
// if its the same continue // if its the same continue
if (position == cycleStart) { if (position == cycleStart) {
continue; continue
} }
while (value == list[position]) { while (value == list[position]) {
position++; position++
} }
let oldValue = list[position]; const oldValue = list[position]
list[position] = value; list[position] = value
value = oldValue; value = oldValue
writes++; writes++
// rotate the rest // rotate the rest
while (position != cycleStart) { while (position != cycleStart) {
position = cycleStart; position = cycleStart
for (let i = cycleStart +1; i < list.length; i++) { for (let i = cycleStart + 1; i < list.length; i++) {
if (list[i] < value) { if (list[i] < value) {
position++; position++
} }
} }
while (value == list[position]) { while (value == list[position]) {
position++; position++
} }
let oldValueCycle = list[position]; const oldValueCycle = list[position]
list[position] = value; list[position] = value
value = oldValueCycle; value = oldValueCycle
writes++; writes++
} }
} }
return writes; return writes
} }
let arrOrignal = [5, 6, 7, 8, 1, 2,12, 14]; const arrOrignal = [5, 6, 7, 8, 1, 2, 12, 14]
//Array before Sort // Array before Sort
console.log(arrOrignal); console.log(arrOrignal)
cycleSort(arrOrignal); cycleSort(arrOrignal)
//Array after sort // Array after sort
console.log(arrOrignal); console.log(arrOrignal)

View File

@ -4,82 +4,82 @@
* more information: https://en.wikipedia.org/wiki/Flashsort * more information: https://en.wikipedia.org/wiki/Flashsort
*/ */
function flashSort(arr) { function flashSort (arr) {
let max = 0, min = arr[0]; let max = 0; let min = arr[0]
let n = arr.length; const n = arr.length
let m = ~~(0.45 * n); const m = ~~(0.45 * n)
let l = new Array(m); const l = new Array(m)
for (let i = 1; i < n; ++i) { for (let i = 1; i < n; ++i) {
if (arr[i] < min) { if (arr[i] < min) {
min = arr[i]; min = arr[i]
} }
if (arr[i] > arr[max]) { if (arr[i] > arr[max]) {
max = i; max = i
} }
} }
if (min === arr[max]) { if (min === arr[max]) {
return arr; return arr
} }
let c1 = (m - 1) / (arr[max] - min); const c1 = (m - 1) / (arr[max] - min)
for (let k = 0; k < m; k++) { for (let k = 0; k < m; k++) {
l[k] = 0; l[k] = 0
} }
for (let j = 0; j < n; ++j) { for (let j = 0; j < n; ++j) {
let k = ~~(c1 * (arr[j] - min)); const k = ~~(c1 * (arr[j] - min))
++l[k]; ++l[k]
} }
for (let p = 1; p < m; ++p) { for (let p = 1; p < m; ++p) {
l[p] = l[p] + l[p - 1]; l[p] = l[p] + l[p - 1]
} }
let hold = arr[max]; let hold = arr[max]
arr[max] = arr[0]; arr[max] = arr[0]
arr[0] = hold; arr[0] = hold
// permutation // permutation
let move = 0, t, flash; let move = 0; let t; let flash
let j = 0; let j = 0
let k = m - 1; let k = m - 1
while (move < (n - 1)) { while (move < (n - 1)) {
while (j > (l[k] - 1)) { while (j > (l[k] - 1)) {
++j; ++j
k = ~~(c1 * (arr[j] - min)); k = ~~(c1 * (arr[j] - min))
} }
if (k < 0) break; if (k < 0) break
flash = arr[j]; flash = arr[j]
while (j !== l[k]) { while (j !== l[k]) {
k = ~~(c1 * (flash - min)); k = ~~(c1 * (flash - min))
hold = arr[t = --l[k]]; hold = arr[t = --l[k]]
arr[t] = flash; arr[t] = flash
flash = hold; flash = hold
++move; ++move
} }
} }
// insertion // insertion
for (j = 1; j < n; j++) { for (j = 1; j < n; j++) {
hold = arr[j]; hold = arr[j]
let i = j - 1; let i = j - 1
while (i >= 0 && arr[i] > hold) { while (i >= 0 && arr[i] > hold) {
arr[i + 1] = arr[i--]; arr[i + 1] = arr[i--]
} }
arr[i + 1] = hold; arr[i + 1] = hold
} }
return arr; return arr
} }
const array = [3, 0, 2, 5, -1, 4, 1, -2]; const array = [3, 0, 2, 5, -1, 4, 1, -2]
// Array before Sort // Array before Sort
console.log("-----before sorting-----"); console.log('-----before sorting-----')
console.log(array); console.log(array)
// Array after sort // Array after sort
console.log("-----after sorting-----"); console.log('-----after sorting-----')
console.log(flashSort(array)); console.log(flashSort(array))

View File

@ -3,34 +3,31 @@
* more information: https://en.wikipedia.org/wiki/Gnome_sort * more information: https://en.wikipedia.org/wiki/Gnome_sort
* *
*/ */
function gnomeSort(items) { function gnomeSort (items) {
if (items.length <= 1) { if (items.length <= 1) {
return
return;
} }
let i = 1; let i = 1
while (i < items.length) { while (i < items.length) {
if (items[i - 1] <= items[i]) { if (items[i - 1] <= items[i]) {
i++; i++
} else { } else {
let temp = items[i]; const temp = items[i]
items[i] = items[i - 1]; items[i] = items[i - 1]
items[i - 1] = temp; items[i - 1] = temp
i = Math.max(1, i - 1); i = Math.max(1, i - 1)
} }
} }
} }
//Implementation of gnomeSort // Implementation of gnomeSort
var ar = [5, 6, 7, 8, 1, 2, 12, 14]; var ar = [5, 6, 7, 8, 1, 2, 12, 14]
//Array before Sort // Array before Sort
console.log(ar); console.log(ar)
gnomeSort(ar); gnomeSort(ar)
//Array after sort // Array after sort
console.log(ar); console.log(ar)

View File

@ -6,54 +6,52 @@
* Source: https://en.wikipedia.org/wiki/Heap_(data_structure) * Source: https://en.wikipedia.org/wiki/Heap_(data_structure)
*/ */
Array.prototype.heapify = function (index, heapSize) { Array.prototype.heapify = function (index, heapSize) {
let largest = index
let largest = index; const leftIndex = 2 * index + 1
let leftIndex = 2 * index + 1; const rightIndex = 2 * index + 2
let rightIndex = 2 * index + 2;
if (leftIndex < heapSize && this[leftIndex] > this[largest]) { if (leftIndex < heapSize && this[leftIndex] > this[largest]) {
largest = leftIndex; largest = leftIndex
} }
if (rightIndex < heapSize && this[rightIndex] > this[largest]) { if (rightIndex < heapSize && this[rightIndex] > this[largest]) {
largest = rightIndex; largest = rightIndex
} }
if (largest !== index) { if (largest !== index) {
let temp = this[largest]; const temp = this[largest]
this[largest] = this[index]; this[largest] = this[index]
this[index] = temp; this[index] = temp
this.heapify(largest, heapSize); this.heapify(largest, heapSize)
} }
}; }
/* /*
* Heap sort sorts an array by building a heap from the array and * Heap sort sorts an array by building a heap from the array and
* utilizing the heap property. * utilizing the heap property.
* For more information see: https://en.wikipedia.org/wiki/Heapsort * For more information see: https://en.wikipedia.org/wiki/Heapsort
*/ */
function heapSort(items) { function heapSort (items) {
const length = items.length
let length = items.length;
for (let i = Math.floor(length / 2) - 1; i > -1; i--) { for (let i = Math.floor(length / 2) - 1; i > -1; i--) {
items.heapify(i, length); items.heapify(i, length)
} }
for (let j = length -1; j > 0; j--) { for (let j = length - 1; j > 0; j--) {
let tmp = items[0]; const tmp = items[0]
items[0] = items[j]; items[0] = items[j]
items[j] = tmp; items[j] = tmp
items.heapify(0, j); items.heapify(0, j)
} }
return items; return items
} }
//Implementation of heapSort // Implementation of heapSort
var ar = [5, 6, 7, 8, 1, 2, 12, 14]; var ar = [5, 6, 7, 8, 1, 2, 12, 14]
//Array before Sort // Array before Sort
console.log(ar); console.log(ar)
heapSort(ar); heapSort(ar)
//Array after sort // Array after sort
console.log(ar); console.log(ar)

View File

@ -1,24 +1,24 @@
/*In insertion sort, we divide the initial unsorted array into two parts; /* In insertion sort, we divide the initial unsorted array into two parts;
* sorted part and unsorted part. Initially the sorted part just has one * sorted part and unsorted part. Initially the sorted part just has one
* element (Array of only 1 element is a sorted array). We then pick up * element (Array of only 1 element is a sorted array). We then pick up
* element one by one from unsorted part; insert into the sorted part at * element one by one from unsorted part; insert into the sorted part at
* the correct position and expand sorted part one element at a time. * the correct position and expand sorted part one element at a time.
*/ */
function insertionSort(unsortedList) { function insertionSort (unsortedList) {
var len = unsortedList.length; var len = unsortedList.length
for (var i = 1; i < len; i++) { for (var i = 1; i < len; i++) {
var tmp = unsortedList[i]; //Copy of the current element. var tmp = unsortedList[i] // Copy of the current element.
/*Check through the sorted part and compare with the number in tmp. If large, shift the number*/ /* Check through the sorted part and compare with the number in tmp. If large, shift the number */
for (var j = i - 1; j >= 0 && (unsortedList[j] > tmp); j--) { for (var j = i - 1; j >= 0 && (unsortedList[j] > tmp); j--) {
//Shift the number // Shift the number
unsortedList[j + 1] = unsortedList[j]; unsortedList[j + 1] = unsortedList[j]
} }
//Insert the copied number at the correct position // Insert the copied number at the correct position
//in sorted part. // in sorted part.
unsortedList[j + 1] = tmp; unsortedList[j + 1] = tmp
} }
} }
var arr = [5, 3, 1, 2, 4, 8, 3, 8]; var arr = [5, 3, 1, 2, 4, 8, 3, 8]
insertionSort(arr); insertionSort(arr)
console.log(arr); console.log(arr)

View File

@ -13,17 +13,17 @@
* @param {Array} list2 - sublist to break down * @param {Array} list2 - sublist to break down
* @return {Array} merged list * @return {Array} merged list
*/ */
function merge(list1, list2) { function merge (list1, list2) {
var results = []; var results = []
while(list1.length && list2.length) { while (list1.length && list2.length) {
if (list1[0] <= list2[0]) { if (list1[0] <= list2[0]) {
results.push(list1.shift()); results.push(list1.shift())
} else { } else {
results.push(list2.shift()); results.push(list2.shift())
} }
} }
return results.concat(list1, list2); return results.concat(list1, list2)
} }
/** /**
@ -31,19 +31,18 @@ function merge(list1, list2) {
* @param {Array} list - list to be sorted * @param {Array} list - list to be sorted
* @return {Array} sorted list * @return {Array} sorted list
*/ */
function mergeSort(list) { function mergeSort (list) {
if (list.length < 2) return list; if (list.length < 2) return list
var listHalf = Math.floor(list.length/2); var listHalf = Math.floor(list.length / 2)
var subList1 = list.slice(0, listHalf); var subList1 = list.slice(0, listHalf)
var subList2 = list.slice(listHalf, list.length); var subList2 = list.slice(listHalf, list.length)
return merge(mergeSort(subList1), mergeSort(subList2)); return merge(mergeSort(subList1), mergeSort(subList2))
} }
// Merge Sort Example // Merge Sort Example
var unsortedArray = [10, 5, 3, 8, 2, 6, 4, 7, 9, 1]; var unsortedArray = [10, 5, 3, 8, 2, 6, 4, 7, 9, 1]
var sortedArray = mergeSort(unsortedArray); var sortedArray = mergeSort(unsortedArray)
console.log('Before:', unsortedArray, 'After:', sortedArray);
console.log('Before:', unsortedArray, 'After:', sortedArray)

View File

@ -2,37 +2,36 @@
* Quick sort is a comparison sorting algorithm that uses a divide and conquer strategy. * Quick sort is a comparison sorting algorithm that uses a divide and conquer strategy.
* For more information see here: https://en.wikipedia.org/wiki/Quicksort * For more information see here: https://en.wikipedia.org/wiki/Quicksort
*/ */
function quickSort(items) { function quickSort (items) {
var length = items.length
var length = items.length;
if (length <= 1) { if (length <= 1) {
return items; return items
} }
var PIVOT = items[0]; var PIVOT = items[0]
var GREATER = []; var GREATER = []
var LESSER = []; var LESSER = []
for (var i = 1; i < length; i++) { for (var i = 1; i < length; i++) {
if (items[i] > PIVOT) { if (items[i] > PIVOT) {
GREATER.push(items[i]); GREATER.push(items[i])
} else { } else {
LESSER.push(items[i]); LESSER.push(items[i])
} }
} }
var sorted = quickSort(LESSER); var sorted = quickSort(LESSER)
sorted.push(PIVOT); sorted.push(PIVOT)
sorted = sorted.concat(quickSort(GREATER)); sorted = sorted.concat(quickSort(GREATER))
return sorted; return sorted
} }
//Implementation of quick sort // Implementation of quick sort
var ar = [0, 5, 3, 2, 2]; var ar = [0, 5, 3, 2, 2]
//Array before Sort // Array before Sort
console.log(ar); console.log(ar)
ar = quickSort(ar); ar = quickSort(ar)
//Array after sort // Array after sort
console.log(ar); console.log(ar)

View File

@ -4,50 +4,49 @@
* significant position. * significant position.
* For more information see: https://en.wikipedia.org/wiki/Radix_sort * For more information see: https://en.wikipedia.org/wiki/Radix_sort
*/ */
function radixSort(items, RADIX) { function radixSort (items, RADIX) {
// default radix is then because we usually count to base 10
//default radix is then because we usually count to base 10
if (RADIX === undefined || RADIX < 1) { if (RADIX === undefined || RADIX < 1) {
RADIX = 10; RADIX = 10
} }
var maxLength = false; var maxLength = false
var placement = 1; var placement = 1
while (!maxLength) { while (!maxLength) {
maxLength = true; maxLength = true
var buckets = []; var buckets = []
for (var i = 0; i < RADIX; i++) { for (var i = 0; i < RADIX; i++) {
buckets.push([]); buckets.push([])
} }
for (var j = 0; j < items.length; j++) { for (var j = 0; j < items.length; j++) {
var tmp = items[j] / placement; var tmp = items[j] / placement
buckets[Math.floor(tmp % RADIX)].push(items[j]); buckets[Math.floor(tmp % RADIX)].push(items[j])
if (maxLength && tmp > 0) { if (maxLength && tmp > 0) {
maxLength = false; maxLength = false
} }
} }
var a = 0; var a = 0
for (var b = 0; b < RADIX; b++) { for (var b = 0; b < RADIX; b++) {
var buck = buckets[b]; var buck = buckets[b]
for (var k = 0; k < buck.length; k++) { for (var k = 0; k < buck.length; k++) {
items[a] = buck[k]; items[a] = buck[k]
a++; a++
} }
} }
placement *= RADIX; placement *= RADIX
} }
return items; return items
} }
//Implementation of radixSort // Implementation of radixSort
var ar = [5, 6, 7, 8, 1, 2, 12, 14]; var ar = [5, 6, 7, 8, 1, 2, 12, 14]
//Array before Sort // Array before Sort
console.log(ar); console.log(ar)
radixSort(ar); radixSort(ar)
//Array after sort // Array after sort
console.log(ar); console.log(ar)

View File

@ -1,4 +1,4 @@
/*The selection sort algorithm sorts an array by repeatedly finding the minimum element /* The selection sort algorithm sorts an array by repeatedly finding the minimum element
*(considering ascending order) from unsorted part and putting it at the beginning. The *(considering ascending order) from unsorted part and putting it at the beginning. The
*algorithm maintains two subarrays in a given array. *algorithm maintains two subarrays in a given array.
*1) The subarray which is already sorted. *1) The subarray which is already sorted.
@ -7,31 +7,31 @@
*In every iteration of selection sort, the minimum element (considering ascending order) *In every iteration of selection sort, the minimum element (considering ascending order)
*from the unsorted subarray is picked and moved to the sorted subarray. *from the unsorted subarray is picked and moved to the sorted subarray.
*/ */
function selectionSort(items) { function selectionSort (items) {
var length = items.length; var length = items.length
for (var i = 0; i < length - 1; i++) { for (var i = 0; i < length - 1; i++) {
//Number of passes // Number of passes
var min = i; //min holds the current minimum number position for each pass; i holds the Initial min number var min = i // min holds the current minimum number position for each pass; i holds the Initial min number
for (var j = i + 1; j < length; j++) { //Note that j = i + 1 as we only need to go through unsorted array for (var j = i + 1; j < length; j++) { // Note that j = i + 1 as we only need to go through unsorted array
if (items[j] < items[min]) { //Compare the numbers if (items[j] < items[min]) { // Compare the numbers
min = j; //Change the current min number position if a smaller num is found min = j // Change the current min number position if a smaller num is found
} }
} }
if (min != i) { if (min != i) {
//After each pass, if the current min num != initial min num, exchange the position. // After each pass, if the current min num != initial min num, exchange the position.
//Swap the numbers // Swap the numbers
var tmp = items[i]; var tmp = items[i]
items[i] = items[min]; items[i] = items[min]
items[min] = tmp; items[min] = tmp
} }
} }
} }
//Implementation of Selection Sort // Implementation of Selection Sort
var ar = [5, 6, 7, 8, 1, 2, 12, 14]; var ar = [5, 6, 7, 8, 1, 2, 12, 14]
//Array before Sort // Array before Sort
console.log(ar); console.log(ar)
selectionSort(ar); selectionSort(ar)
//Array after sort // Array after sort
console.log(ar); console.log(ar)

View File

@ -3,38 +3,34 @@
* more information: https://en.wikipedia.org/wiki/Shellsort * more information: https://en.wikipedia.org/wiki/Shellsort
* *
*/ */
function shellSort(items) { function shellSort (items) {
var interval = 1
var interval = 1;
while (interval < items.length / 3) { while (interval < items.length / 3) {
interval = interval * 3 + 1
interval = interval * 3 + 1;
} }
while (interval > 0) { while (interval > 0) {
for (var outer = interval; outer < items.length; outer++) { for (var outer = interval; outer < items.length; outer++) {
var value = items[outer]
var value = items[outer]; var inner = outer
var inner = outer;
while (inner > interval - 1 && items[inner - interval] >= value) { while (inner > interval - 1 && items[inner - interval] >= value) {
items[inner] = items[inner - interval]; items[inner] = items[inner - interval]
inner = inner - interval; inner = inner - interval
} }
items[inner] = value; items[inner] = value
} }
interval = (interval - 1) / 3; interval = (interval - 1) / 3
} }
return items; return items
} }
//Implementation of shellSort // Implementation of shellSort
var ar = [5, 6, 7, 8, 1, 2, 12, 14]; var ar = [5, 6, 7, 8, 1, 2, 12, 14]
//Array before Sort // Array before Sort
console.log(ar); console.log(ar)
shellSort(ar); shellSort(ar)
//Array after sort // Array after sort
console.log(ar); console.log(ar)

View File

@ -6,21 +6,21 @@
Array.prototype.wiggleSort = function () { Array.prototype.wiggleSort = function () {
for (let i = 0; i < this.length; ++i) { for (let i = 0; i < this.length; ++i) {
const shouldNotBeLessThan = i % 2; const shouldNotBeLessThan = i % 2
const isLessThan = this[i] < this[i + 1]; const isLessThan = this[i] < this[i + 1]
if (shouldNotBeLessThan && isLessThan) { if (shouldNotBeLessThan && isLessThan) {
[this[i], this[i + 1]] = [this[i + 1], this[i]]; [this[i], this[i + 1]] = [this[i + 1], this[i]]
} }
} }
return this; return this
}; }
//Implementation of wiggle sort // Implementation of wiggle sort
var arr = [3, 5, 2, 1, 6, 4]; var arr = [3, 5, 2, 1, 6, 4]
//Array before Wiggle Sort // Array before Wiggle Sort
console.log(arr); //[3, 5, 2, 1, 6, 4] console.log(arr) // [3, 5, 2, 1, 6, 4]
arr.wiggleSort() arr.wiggleSort()
//Array after wiggle sort // Array after wiggle sort
console.log(arr); // [ 3, 5, 2, 6, 1, 4 ] console.log(arr) // [ 3, 5, 2, 6, 1, 4 ]

View File

@ -13,195 +13,184 @@ var LinearAlgebra;
*/ */
var Vector = /** @class */ (function () { var Vector = /** @class */ (function () {
// constructor // constructor
function Vector(N, comps) { function Vector (N, comps) {
if (comps === void 0) { comps = []; } if (comps === void 0) { comps = [] }
this.components = new Array(N); this.components = new Array(N)
if (comps.length == 0) { if (comps.length == 0) {
for (var i = 0; i < N; i++) { for (var i = 0; i < N; i++) {
this.components[i] = 0.0; this.components[i] = 0.0
} }
} } else {
else {
if (N == comps.length) { if (N == comps.length) {
this.components = comps; this.components = comps
} } else {
else { throw 'Vector: invalide size!'
throw "Vector: invalide size!";
} }
} }
} // end of constructor } // end of constructor
// returns the size of this vector. // returns the size of this vector.
// not the eulidean length! // not the eulidean length!
Vector.prototype.size = function () { Vector.prototype.size = function () {
return this.components.length; return this.components.length
}; }
// computes the eulidean length. // computes the eulidean length.
Vector.prototype.eulideanLength = function () { Vector.prototype.eulideanLength = function () {
var sum = 0; var sum = 0
for (var i = 0; i < this.components.length; i++) { for (var i = 0; i < this.components.length; i++) {
sum += this.components[i] * this.components[i]; sum += this.components[i] * this.components[i]
}
return Math.sqrt(sum)
} }
return Math.sqrt(sum);
};
// getter for the components of the vector. // getter for the components of the vector.
// returns a specified component (index) // returns a specified component (index)
Vector.prototype.component = function (index) { Vector.prototype.component = function (index) {
return this.components[index]; return this.components[index]
}; }
// setter for a specified component of this vector. // setter for a specified component of this vector.
Vector.prototype.changeComponent = function (index, value) { Vector.prototype.changeComponent = function (index, value) {
if (index >= 0 && index < this.components.length) { if (index >= 0 && index < this.components.length) {
this.components[index] = value; this.components[index] = value
} else {
throw 'changeComponent: index out of bounds!'
} }
else {
throw "changeComponent: index out of bounds!";
} }
};
// vector addition // vector addition
Vector.prototype.add = function (other) { Vector.prototype.add = function (other) {
if (this.size() == other.size()) { if (this.size() == other.size()) {
var SIZE = this.size(); var SIZE = this.size()
var ans = new Vector(SIZE); var ans = new Vector(SIZE)
for (var i = 0; i < SIZE; i++) { for (var i = 0; i < SIZE; i++) {
ans.changeComponent(i, (this.components[i] + other.component(i))); ans.changeComponent(i, (this.components[i] + other.component(i)))
} }
return ans; return ans
} else {
throw 'add: vector must have same size!'
} }
else {
throw "add: vector must have same size!";
} }
};
// vector subtraction // vector subtraction
Vector.prototype.sub = function (other) { Vector.prototype.sub = function (other) {
if (this.size() == other.size()) { if (this.size() == other.size()) {
var SIZE = this.size(); var SIZE = this.size()
var ans = new Vector(SIZE); var ans = new Vector(SIZE)
for (var i = 0; i < SIZE; i++) { for (var i = 0; i < SIZE; i++) {
ans.changeComponent(i, (this.components[i] - other.component(i))); ans.changeComponent(i, (this.components[i] - other.component(i)))
} }
return ans; return ans
} else {
throw 'add: vector must have same size!'
} }
else {
throw "add: vector must have same size!";
} }
};
// dot-product // dot-product
Vector.prototype.dot = function (other) { Vector.prototype.dot = function (other) {
var sum = 0; var sum = 0
if (other.size() == this.size()) { if (other.size() == this.size()) {
var SIZE = other.size(); var SIZE = other.size()
for (var i = 0; i < SIZE; i++) { for (var i = 0; i < SIZE; i++) {
sum += this.components[i] * other.component(i); sum += this.components[i] * other.component(i)
} }
return sum; return sum
} else {
throw 'dot: vectors must have same size!'
} }
else {
throw "dot: vectors must have same size!";
} }
};
// scalar multiplication // scalar multiplication
Vector.prototype.scalar = function (s) { Vector.prototype.scalar = function (s) {
var SIZE = this.size(); var SIZE = this.size()
var ans = new Vector(SIZE); var ans = new Vector(SIZE)
for (var i = 0; i < SIZE; i++) { for (var i = 0; i < SIZE; i++) {
ans.changeComponent(i, (this.components[i] * s)); ans.changeComponent(i, (this.components[i] * s))
}
return ans
} }
return ans;
};
// returns a string representation of this vector. // returns a string representation of this vector.
Vector.prototype.toString = function () { Vector.prototype.toString = function () {
var ans = "("; var ans = '('
var SIZE = this.components.length; var SIZE = this.components.length
for (var i = 0; i < SIZE; i++) { for (var i = 0; i < SIZE; i++) {
if (i < SIZE - 1) { if (i < SIZE - 1) {
ans += this.components[i] + ","; ans += this.components[i] + ','
} } else {
else { ans += this.components[i] + ')'
ans += this.components[i] + ")";
} }
} }
return ans; return ans
}; }
// converts this vector in a unit basis vector and returns it. // converts this vector in a unit basis vector and returns it.
// the One is on position 'pos' // the One is on position 'pos'
Vector.prototype.createUnitBasis = function (pos) { Vector.prototype.createUnitBasis = function (pos) {
if (pos >= 0 && pos < this.components.length) { if (pos >= 0 && pos < this.components.length) {
for (var i = 0; i < this.components.length; i++) { for (var i = 0; i < this.components.length; i++) {
if (i == pos) { if (i == pos) {
this.components[i] = 1.0; this.components[i] = 1.0
} } else {
else { this.components[i] = 0.0
this.components[i] = 0.0;
} }
} }
} else {
throw 'createUnitBasis: index out of bounds'
} }
else { return this
throw "createUnitBasis: index out of bounds";
} }
return this;
};
// normalizes this vector and returns it. // normalizes this vector and returns it.
Vector.prototype.norm = function () { Vector.prototype.norm = function () {
var SIZE = this.size(); var SIZE = this.size()
var quotient = 1.0 / this.eulideanLength(); var quotient = 1.0 / this.eulideanLength()
for (var i = 0; i < SIZE; i++) { for (var i = 0; i < SIZE; i++) {
this.components[i] = this.components[i] * quotient; this.components[i] = this.components[i] * quotient
}
return this
} }
return this;
};
// returns true if the vectors are equal otherwise false. // returns true if the vectors are equal otherwise false.
Vector.prototype.equal = function (other) { Vector.prototype.equal = function (other) {
var ans = true; var ans = true
var SIZE = this.size(); var SIZE = this.size()
var EPSILON = 0.001; var EPSILON = 0.001
if (SIZE == other.size()) { if (SIZE == other.size()) {
for (var i = 0; i < SIZE; i++) { for (var i = 0; i < SIZE; i++) {
if (Math.abs(this.components[i] - other.component(i)) > EPSILON) { if (Math.abs(this.components[i] - other.component(i)) > EPSILON) {
ans = false; ans = false
} }
} }
} else {
ans = false
} }
else { return ans
ans = false;
} }
return ans; return Vector
}; }()) // end of class Vector
return Vector; LinearAlgebra.Vector = Vector
}()); // end of class Vector
LinearAlgebra.Vector = Vector;
// -------------- global functions --------------------------------- // -------------- global functions ---------------------------------
// returns a unit basis vector of size N with a One on position 'pos' // returns a unit basis vector of size N with a One on position 'pos'
function unitBasisVector(N, pos) { function unitBasisVector (N, pos) {
var ans = new Vector(N); var ans = new Vector(N)
for (var i = 0; i < N; i++) { for (var i = 0; i < N; i++) {
if (i == pos) { if (i == pos) {
ans.changeComponent(i, 1.0); ans.changeComponent(i, 1.0)
} } else {
else { ans.changeComponent(i, 0)
ans.changeComponent(i, 0);
} }
} }
return ans; return ans
} }
LinearAlgebra.unitBasisVector = unitBasisVector; LinearAlgebra.unitBasisVector = unitBasisVector
// returns a random vector with integer components (between 'a' and 'b') of size N. // returns a random vector with integer components (between 'a' and 'b') of size N.
function randomVectorInt(N, a, b) { function randomVectorInt (N, a, b) {
var ans = new Vector(N); var ans = new Vector(N)
for (var i = 0; i < N; i++) { for (var i = 0; i < N; i++) {
ans.changeComponent(i, (Math.floor((Math.random() * b) + a))); ans.changeComponent(i, (Math.floor((Math.random() * b) + a)))
} }
return ans; return ans
} }
LinearAlgebra.randomVectorInt = randomVectorInt; LinearAlgebra.randomVectorInt = randomVectorInt
// returns a random vector with floating point components (between 'a' and 'b') of size N. // returns a random vector with floating point components (between 'a' and 'b') of size N.
function randomVectorFloat(N, a, b) { function randomVectorFloat (N, a, b) {
var ans = new Vector(N); var ans = new Vector(N)
for (var i = 0; i < N; i++) { for (var i = 0; i < N; i++) {
ans.changeComponent(i, ((Math.random() * b) + a)); ans.changeComponent(i, ((Math.random() * b) + a))
} }
return ans; return ans
} }
LinearAlgebra.randomVectorFloat = randomVectorFloat; LinearAlgebra.randomVectorFloat = randomVectorFloat
// ------------------ end of global functions ----------------------------- // ------------------ end of global functions -----------------------------
/* /*
class: Matrix class: Matrix
@ -209,117 +198,110 @@ var LinearAlgebra;
*/ */
var Matrix = /** @class */ (function () { var Matrix = /** @class */ (function () {
// constructor for zero-matrix or fix number matrix. // constructor for zero-matrix or fix number matrix.
function Matrix(row, col, comps) { function Matrix (row, col, comps) {
if (comps === void 0) { comps = []; } if (comps === void 0) { comps = [] }
if (comps.length == 0) { if (comps.length == 0) {
this.matrix = new Array(); this.matrix = new Array()
var rowVector = new Array(); var rowVector = new Array()
for (var i = 0; i < row; i++) { for (var i = 0; i < row; i++) {
for (var j = 0; j < col; j++) { for (var j = 0; j < col; j++) {
rowVector[j] = 0; rowVector[j] = 0
} }
this.matrix[i] = rowVector; this.matrix[i] = rowVector
rowVector = new Array(); rowVector = new Array()
} }
} else {
this.matrix = comps
} }
else { this.rows = row
this.matrix = comps; this.cols = col
}
this.rows = row;
this.cols = col;
} }
// returns the specified component. // returns the specified component.
Matrix.prototype.component = function (x, y) { Matrix.prototype.component = function (x, y) {
if (x >= 0 && x < this.rows && y >= 0 && y < this.cols) { if (x >= 0 && x < this.rows && y >= 0 && y < this.cols) {
return this.matrix[x][y]; return this.matrix[x][y]
} else {
throw new Error('component: index out of bounds')
} }
else {
throw new Error("component: index out of bounds");
} }
};
// changes the specified component with value 'value'. // changes the specified component with value 'value'.
Matrix.prototype.changeComponent = function (x, y, value) { Matrix.prototype.changeComponent = function (x, y, value) {
if (x >= 0 && x < this.rows && y >= 0 && y < this.cols) { if (x >= 0 && x < this.rows && y >= 0 && y < this.cols) {
this.matrix[x][y] = value; this.matrix[x][y] = value
} else {
throw new Error('changeComponent: index out of bounds')
} }
else {
throw new Error("changeComponent: index out of bounds");
} }
};
// returns a string representation of this matrix. // returns a string representation of this matrix.
Matrix.prototype.toString = function () { Matrix.prototype.toString = function () {
var ans = ""; var ans = ''
for (var i = 0; i < this.rows; i++) { for (var i = 0; i < this.rows; i++) {
ans += "|"; ans += '|'
for (var j = 0; j < this.cols; j++) { for (var j = 0; j < this.cols; j++) {
if (j < this.cols - 1) { if (j < this.cols - 1) {
ans += this.matrix[i][j] + ","; ans += this.matrix[i][j] + ','
} } else {
else {
if (i < this.rows - 1) { if (i < this.rows - 1) {
ans += this.matrix[i][j] + "|\n"; ans += this.matrix[i][j] + '|\n'
} } else {
else { ans += this.matrix[i][j] + '|'
ans += this.matrix[i][j] + "|";
} }
} }
} }
} }
return ans; return ans
}; }
// returns the dimension rows x cols as number array // returns the dimension rows x cols as number array
Matrix.prototype.dimension = function () { Matrix.prototype.dimension = function () {
var ans = new Array(); var ans = new Array()
ans[0] = this.rows; ans[0] = this.rows
ans[1] = this.cols; ans[1] = this.cols
return ans; return ans
}; }
// matrix addition. returns the result. // matrix addition. returns the result.
Matrix.prototype.add = function (other) { Matrix.prototype.add = function (other) {
if (this.rows == other.dimension()[0] if (this.rows == other.dimension()[0] &&
&& this.cols == other.dimension()[1]) { this.cols == other.dimension()[1]) {
var ans = new Matrix(this.rows, this.cols); var ans = new Matrix(this.rows, this.cols)
for (var i = 0; i < this.rows; i++) { for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.cols; j++) { for (var j = 0; j < this.cols; j++) {
ans.changeComponent(i, j, (this.matrix[i][j] + other.component(i, j))); ans.changeComponent(i, j, (this.matrix[i][j] + other.component(i, j)))
} }
} }
return ans; return ans
} else {
throw new Error('add: matrices must have same dimension!')
} }
else {
throw new Error("add: matrices must have same dimension!");
} }
};
// returns true if the matrices are equal, otherwise false. // returns true if the matrices are equal, otherwise false.
Matrix.prototype.equal = function (other) { Matrix.prototype.equal = function (other) {
var ans = true; var ans = true
var EPSILON = 0.001; var EPSILON = 0.001
if (this.rows == other.dimension()[0] if (this.rows == other.dimension()[0] &&
&& this.cols == other.dimension()[1]) { this.cols == other.dimension()[1]) {
for (var i = 0; i < this.rows; i++) { for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.cols; j++) { for (var j = 0; j < this.cols; j++) {
if (Math.abs(this.matrix[i][j] - other.component(i, j)) > EPSILON) { if (Math.abs(this.matrix[i][j] - other.component(i, j)) > EPSILON) {
ans = false; ans = false
} }
} }
} }
} else {
ans = false
} }
else { return ans
ans = false;
} }
return ans;
};
// matrix-scalar multiplication // matrix-scalar multiplication
Matrix.prototype.scalar = function (c) { Matrix.prototype.scalar = function (c) {
var ans = new Matrix(this.rows, this.cols); var ans = new Matrix(this.rows, this.cols)
for (var i = 0; i < this.rows; i++) { for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.cols; j++) { for (var j = 0; j < this.cols; j++) {
ans.changeComponent(i, j, (this.matrix[i][j] * c)); ans.changeComponent(i, j, (this.matrix[i][j] * c))
} }
} }
return ans; return ans
}; }
return Matrix; return Matrix
}()); // end of class Matrix }()) // end of class Matrix
LinearAlgebra.Matrix = Matrix; LinearAlgebra.Matrix = Matrix
})(LinearAlgebra || (LinearAlgebra = {})); // end of namespace LinearAlgebra })(LinearAlgebra || (LinearAlgebra = {})) // end of namespace LinearAlgebra

View File

@ -6,11 +6,11 @@
The tests use javascript test-framework mocha The tests use javascript test-framework mocha
*/ */
var assert = require('assert'); var assert = require('assert')
var fs = require('fs'); var fs = require('fs')
// file is included here // file is included here
eval(fs.readFileSync('src/la_lib.js') + ''); eval(fs.readFileSync('src/la_lib.js') + '')
// Tests goes here // Tests goes here
@ -18,153 +18,152 @@ eval(fs.readFileSync('src/la_lib.js') + '');
describe('Create Vectors', function () { describe('Create Vectors', function () {
describe('#toString()', function () { describe('#toString()', function () {
it('should return a string representation', function () { it('should return a string representation', function () {
assert.equal((new LinearAlgebra.Vector(3, [1, 2, 3])).toString(), "(1,2,3)"); assert.equal((new LinearAlgebra.Vector(3, [1, 2, 3])).toString(), '(1,2,3)')
}); })
}); })
describe("#unitBasisVector()", function () { describe('#unitBasisVector()', function () {
it("should return a unit basis vector", function () { it('should return a unit basis vector', function () {
assert.equal(LinearAlgebra.unitBasisVector(3, 1).toString(), "(0,1,0)"); assert.equal(LinearAlgebra.unitBasisVector(3, 1).toString(), '(0,1,0)')
}); })
}); })
}); })
// operations on it. // operations on it.
describe("Vector operations", function () { describe('Vector operations', function () {
describe("#add()", function () { describe('#add()', function () {
it("should return vector (2,4,6)", function () { it('should return vector (2,4,6)', function () {
var x = new LinearAlgebra.Vector(3, [1, 2, 3]); var x = new LinearAlgebra.Vector(3, [1, 2, 3])
var y = new LinearAlgebra.Vector(3, [1, 2, 3]); var y = new LinearAlgebra.Vector(3, [1, 2, 3])
assert.equal((x.add(y)).toString(), "(2,4,6)"); assert.equal((x.add(y)).toString(), '(2,4,6)')
});
});
describe("#sub()", function () {
it("should return vector (0,0,0)", function () {
var x = new LinearAlgebra.Vector(3, [1, 2, 3]);
var y = new LinearAlgebra.Vector(3, [1, 2, 3]);
assert.equal((x.sub(y)).toString(), "(0,0,0)");
});
});
describe("#dot()", function () {
it("should return the dot-product", function () {
var x = new LinearAlgebra.Vector(3, [1, 2, 3]);
var y = new LinearAlgebra.Vector(3, [5, 6, 7]);
assert.equal(x.dot(y), 38);
});
});
describe("#scalar()", function () {
it("should return the scalar product", function () {
var x = new LinearAlgebra.Vector(3, [1, 2, 3]);
assert.equal(x.scalar(2).toString(), "(2,4,6)");
});
});
describe("#norm()", function () {
it("should return the normalizes vector", function () {
var x = new LinearAlgebra.Vector(4, [9, 0, 3, 1]);
var y = x.norm();
assert.ok(Math.abs(y.component(0) - (9.0 / Math.sqrt(91))) <= 0.01);
});
});
describe("#eulideanLength()", function () {
it("should return the eulidean length of the vector", function () {
var x = new LinearAlgebra.Vector(3, [1, 2, 2]);
assert.ok(Math.abs(x.eulideanLength() - 3) <= 0.001);
});
});
describe("#size()", function () {
it("should return the size (not eulidean length!) of the vector", function () {
var x = LinearAlgebra.randomVectorInt(10, 1, 5);
assert.equal(x.size(), 10);
});
});
describe("#equal()", function () {
it("should compares two vectors", function () {
var x = new LinearAlgebra.Vector(3, [1, 2, 2]);
var y = new LinearAlgebra.Vector(3, [1, 2, 3]);
assert.ok(x.equal(x));
assert.ok(!x.equal(y));
});
});
});
describe("Methods on vectors", function () {
describe("#component()", function () {
it("should return the specified component", function () {
var x = new LinearAlgebra.Vector(3, [1, 2, 2]);
assert.equal(x.component(1), 2);
});
});
describe("#changeComponent()", function () {
it("should return the changed vector", function () {
var x = new LinearAlgebra.Vector(3, [1, 2, 2]);
x.changeComponent(1, 5);
assert.equal(x.toString(), "(1,5,2)");
});
});
describe("#toString()", function () {
it("should return a string representation of the vector", function () {
var x = new LinearAlgebra.Vector(4, [9, 0, 3, 1]);
assert.equal(x.toString(), "(9,0,3,1)");
});
});
});
describe("class Matrix", function () {
describe("#component()", function () {
it("should return the specified component", function () {
var A = new LinearAlgebra.Matrix(2, 2);
assert.equal(A.component(0, 1), 0);
var B = new LinearAlgebra.Matrix(2, 2, [[1, 2], [3, 4]]);
assert.equal(B.component(1, 0), 3);
});
});
describe("#toString()", function () {
it("should return a string representation of the matrix", function () {
var A = new LinearAlgebra.Matrix(2, 2, [[1, 2], [3, 4]]);
assert.equal(A.toString(), "|1,2|\n|3,4|");
});
});
describe("#dimension()", function () {
it("should return the dimension of the matrix as number array", function () {
var A = new LinearAlgebra.Matrix(3, 2, [[1, 2], [3, 4], [5, 6]]);
assert.equal(A.dimension()[0], 3);
assert.equal(A.dimension()[1], 2);
});
});
describe("#changeComponent()", function () {
it("should change the specified component of the matrix", function () {
var A = new LinearAlgebra.Matrix(3, 2, [[1, 2], [3, 4], [5, 6]]);
A.changeComponent(1, 0, 5);
assert.equal(A.component(1, 0), 5);
});
});
describe("#equal()", function () {
it("should compares the matrices", function () {
var A = new LinearAlgebra.Matrix(3, 2, [[1, 2], [3, 4], [5, 6]]);
var B = new LinearAlgebra.Matrix(3, 2, [[1, 2], [3, 4], [5, 6]]);
var C = new LinearAlgebra.Matrix(2, 2, [[1, 2], [3, 4]]);
var D = new LinearAlgebra.Matrix(2, 2, [[1, 2], [5, 4]]);
assert.ok(A.equal(B));
assert.ok(!A.equal(C));
assert.ok(!C.equal(D));
});
});
describe("#add()", function () {
it("should return the result of the matrix addition", function () {
var A = new LinearAlgebra.Matrix(3, 2, [[1, 2], [3, 4], [5, 6]]);
var B = new LinearAlgebra.Matrix(3, 2, [[1, 2], [3, 4], [5, 6]]);
var C = A.add(B);
assert.equal(C.component(1, 0), 6);
assert.equal(C.component(1, 1), 8);
assert.equal(C.component(0, 0), 2);
});
});
describe("#scalar()", function () {
it("should return the result of the matrix-scalar multiplication", function () {
var A = new LinearAlgebra.Matrix(3, 2, [[1, 2], [3, 4], [5, 6]]);
var B = A.scalar(2);
var C = new LinearAlgebra.Matrix(3, 2, [[2, 4], [6, 8], [10, 12]]);
assert.ok(B.equal(C));
});
}) })
}); })
describe('#sub()', function () {
it('should return vector (0,0,0)', function () {
var x = new LinearAlgebra.Vector(3, [1, 2, 3])
var y = new LinearAlgebra.Vector(3, [1, 2, 3])
assert.equal((x.sub(y)).toString(), '(0,0,0)')
})
})
describe('#dot()', function () {
it('should return the dot-product', function () {
var x = new LinearAlgebra.Vector(3, [1, 2, 3])
var y = new LinearAlgebra.Vector(3, [5, 6, 7])
assert.equal(x.dot(y), 38)
})
})
describe('#scalar()', function () {
it('should return the scalar product', function () {
var x = new LinearAlgebra.Vector(3, [1, 2, 3])
assert.equal(x.scalar(2).toString(), '(2,4,6)')
})
})
describe('#norm()', function () {
it('should return the normalizes vector', function () {
var x = new LinearAlgebra.Vector(4, [9, 0, 3, 1])
var y = x.norm()
assert.ok(Math.abs(y.component(0) - (9.0 / Math.sqrt(91))) <= 0.01)
})
})
describe('#eulideanLength()', function () {
it('should return the eulidean length of the vector', function () {
var x = new LinearAlgebra.Vector(3, [1, 2, 2])
assert.ok(Math.abs(x.eulideanLength() - 3) <= 0.001)
})
})
describe('#size()', function () {
it('should return the size (not eulidean length!) of the vector', function () {
var x = LinearAlgebra.randomVectorInt(10, 1, 5)
assert.equal(x.size(), 10)
})
})
describe('#equal()', function () {
it('should compares two vectors', function () {
var x = new LinearAlgebra.Vector(3, [1, 2, 2])
var y = new LinearAlgebra.Vector(3, [1, 2, 3])
assert.ok(x.equal(x))
assert.ok(!x.equal(y))
})
})
})
describe('Methods on vectors', function () {
describe('#component()', function () {
it('should return the specified component', function () {
var x = new LinearAlgebra.Vector(3, [1, 2, 2])
assert.equal(x.component(1), 2)
})
})
describe('#changeComponent()', function () {
it('should return the changed vector', function () {
var x = new LinearAlgebra.Vector(3, [1, 2, 2])
x.changeComponent(1, 5)
assert.equal(x.toString(), '(1,5,2)')
})
})
describe('#toString()', function () {
it('should return a string representation of the vector', function () {
var x = new LinearAlgebra.Vector(4, [9, 0, 3, 1])
assert.equal(x.toString(), '(9,0,3,1)')
})
})
})
describe('class Matrix', function () {
describe('#component()', function () {
it('should return the specified component', function () {
var A = new LinearAlgebra.Matrix(2, 2)
assert.equal(A.component(0, 1), 0)
var B = new LinearAlgebra.Matrix(2, 2, [[1, 2], [3, 4]])
assert.equal(B.component(1, 0), 3)
})
})
describe('#toString()', function () {
it('should return a string representation of the matrix', function () {
var A = new LinearAlgebra.Matrix(2, 2, [[1, 2], [3, 4]])
assert.equal(A.toString(), '|1,2|\n|3,4|')
})
})
describe('#dimension()', function () {
it('should return the dimension of the matrix as number array', function () {
var A = new LinearAlgebra.Matrix(3, 2, [[1, 2], [3, 4], [5, 6]])
assert.equal(A.dimension()[0], 3)
assert.equal(A.dimension()[1], 2)
})
})
describe('#changeComponent()', function () {
it('should change the specified component of the matrix', function () {
var A = new LinearAlgebra.Matrix(3, 2, [[1, 2], [3, 4], [5, 6]])
A.changeComponent(1, 0, 5)
assert.equal(A.component(1, 0), 5)
})
})
describe('#equal()', function () {
it('should compares the matrices', function () {
var A = new LinearAlgebra.Matrix(3, 2, [[1, 2], [3, 4], [5, 6]])
var B = new LinearAlgebra.Matrix(3, 2, [[1, 2], [3, 4], [5, 6]])
var C = new LinearAlgebra.Matrix(2, 2, [[1, 2], [3, 4]])
var D = new LinearAlgebra.Matrix(2, 2, [[1, 2], [5, 4]])
assert.ok(A.equal(B))
assert.ok(!A.equal(C))
assert.ok(!C.equal(D))
})
})
describe('#add()', function () {
it('should return the result of the matrix addition', function () {
var A = new LinearAlgebra.Matrix(3, 2, [[1, 2], [3, 4], [5, 6]])
var B = new LinearAlgebra.Matrix(3, 2, [[1, 2], [3, 4], [5, 6]])
var C = A.add(B)
assert.equal(C.component(1, 0), 6)
assert.equal(C.component(1, 1), 8)
assert.equal(C.component(0, 0), 2)
})
})
describe('#scalar()', function () {
it('should return the result of the matrix-scalar multiplication', function () {
var A = new LinearAlgebra.Matrix(3, 2, [[1, 2], [3, 4], [5, 6]])
var B = A.scalar(2)
var C = new LinearAlgebra.Matrix(3, 2, [[2, 4], [6, 8], [10, 12]])
assert.ok(B.equal(C))
})
})
})

View File

@ -1,71 +1,66 @@
// starting at s // starting at s
function solve(graph, s) { function solve (graph, s) {
var solutions = {}; var solutions = {}
solutions[s] = []; solutions[s] = []
solutions[s].dist = 0; solutions[s].dist = 0
while(true) { while (true) {
var p = null; var p = null
var neighbor = null; var neighbor = null
var dist = Infinity; var dist = Infinity
for (var n in solutions) {
if (!solutions[n]) { continue }
var ndist = solutions[n].dist
var adj = graph[n]
for(var n in solutions) { for (var a in adj) {
if(!solutions[n]) if (solutions[a]) { continue }
continue
var ndist = solutions[n].dist;
var adj = graph[n];
for(var a in adj) { var d = adj[a] + ndist
if (d < dist) {
if(solutions[a]) p = solutions[n]
continue; neighbor = a
dist = d
var d = adj[a] + ndist;
if(d < dist) {
p = solutions[n];
neighbor = a;
dist = d;
} }
} }
} }
//no more solutions // no more solutions
if(dist === Infinity) { if (dist === Infinity) {
break; break
} }
//extend parent's solution path // extend parent's solution path
solutions[neighbor] = p.concat(neighbor); solutions[neighbor] = p.concat(neighbor)
//extend parent's cost // extend parent's cost
solutions[neighbor].dist = dist; solutions[neighbor].dist = dist
} }
return solutions; return solutions
} }
//create graph // create graph
var graph = {}; var graph = {}
var layout = { var layout = {
'R': ['2'], R: ['2'],
'2': ['3','4'], 2: ['3', '4'],
'3': ['4','6','13'], 3: ['4', '6', '13'],
'4': ['5','8'], 4: ['5', '8'],
'5': ['7','11'], 5: ['7', '11'],
'6': ['13','15'], 6: ['13', '15'],
'7': ['10'], 7: ['10'],
'8': ['11','13'], 8: ['11', '13'],
'9': ['14'], 9: ['14'],
'10': [], 10: [],
'11': ['12'], 11: ['12'],
'12': [], 12: [],
'13': ['14'], 13: ['14'],
'14': [], 14: [],
'15': [] 15: []
} }
//convert uni-directional to bi-directional graph // convert uni-directional to bi-directional graph
// var graph = { // var graph = {
// a: {e:1, b:1, g:3}, // a: {e:1, b:1, g:3},
// b: {a:1, c:1}, // b: {a:1, c:1},
@ -77,27 +72,25 @@ var layout = {
// h: {f:1} // h: {f:1}
// }; // };
for(var id in layout) { for (var id in layout) {
if(!graph[id]) if (!graph[id]) { graph[id] = {} }
graph[id] = {}; layout[id].forEach(function (aid) {
layout[id].forEach(function(aid) { graph[id][aid] = 1
graph[id][aid] = 1; if (!graph[aid]) { graph[aid] = {} }
if(!graph[aid]) graph[aid][id] = 1
graph[aid] = {}; })
graph[aid][id] = 1;
});
} }
//choose start node // choose start node
var start = '10'; var start = '10'
//get all solutions // get all solutions
var solutions = solve(graph, start); var solutions = solve(graph, start)
console.log("From '"+start+"' to"); console.log("From '" + start + "' to")
//display solutions // display solutions
for(var s in solutions) { for (var s in solutions) {
if(!solutions[s]) continue; if (!solutions[s]) continue
console.log(" -> " + s + ": [" + solutions[s].join(", ") + "] (dist:" + solutions[s].dist + ")"); console.log(' -> ' + s + ': [' + solutions[s].join(', ') + '] (dist:' + solutions[s].dist + ')')
} }
// From '10' to // From '10' to

View File

@ -11,9 +11,9 @@
https://en.wikipedia.org/wiki/Absolute_value https://en.wikipedia.org/wiki/Absolute_value
*/ */
function abs_val(num) { function abs_val (num) {
// Find absolute value of `num`. // Find absolute value of `num`.
"use strict"; 'use strict'
if (num < 0) { if (num < 0) {
return -num return -num
} }
@ -22,5 +22,5 @@ function abs_val(num) {
} }
// Run `abs` function to find absolute value of two numbers. // Run `abs` function to find absolute value of two numbers.
console.log("The absolute value of -34 is " + abs_val(-34)); console.log('The absolute value of -34 is ' + abs_val(-34))
console.log("The absolute value of 34 is " + abs_val(34)); console.log('The absolute value of 34 is ' + abs_val(34))

View File

@ -11,20 +11,20 @@
https://en.wikipedia.org/wiki/Mean https://en.wikipedia.org/wiki/Mean
*/ */
function mean(nums) { function mean (nums) {
"use strict"; 'use strict'
var sum = 0; var sum = 0
var avg; var avg
// This loop sums all values in the 'nums' array. // This loop sums all values in the 'nums' array.
nums.forEach(function (current) { nums.forEach(function (current) {
sum += current; sum += current
}); })
// Divide sum by the length of the 'nums' array. // Divide sum by the length of the 'nums' array.
avg = sum / nums.length; avg = sum / nums.length
return avg; return avg
} }
// Run `mean` Function to find average of a list of numbers. // Run `mean` Function to find average of a list of numbers.
console.log(mean([2, 4, 6, 8, 20, 50, 70])); console.log(mean([2, 4, 6, 8, 20, 50, 70]))

View File

@ -11,42 +11,42 @@
https://en.wikipedia.org/wiki/factorial https://en.wikipedia.org/wiki/factorial
*/ */
"use strict"; 'use strict'
function calc_range(num) { function calc_range (num) {
// Generate a range of numbers from 1 to `num`. // Generate a range of numbers from 1 to `num`.
var i = 1; var i = 1
var range = []; var range = []
while (i <= num) { while (i <= num) {
range.push(i); range.push(i)
i += 1; i += 1
} }
return range; return range
} }
function calc_factorial(num) { function calc_factorial (num) {
var factorial; var factorial
var range = calc_range(num); var range = calc_range(num)
// Check if the number is negative, positive, null, undefined, or zero // Check if the number is negative, positive, null, undefined, or zero
if (num < 0) { if (num < 0) {
return "Sorry, factorial does not exist for negative numbers."; return 'Sorry, factorial does not exist for negative numbers.'
} }
if (num === null || num === undefined) { if (num === null || num === undefined) {
return "Sorry, factorial does not exist for null or undefined numbers."; return 'Sorry, factorial does not exist for null or undefined numbers.'
} }
if (num === 0) { if (num === 0) {
return "The factorial of 0 is 1."; return 'The factorial of 0 is 1.'
} }
if (num > 0) { if (num > 0) {
factorial = 1; factorial = 1
range.forEach(function (i) { range.forEach(function (i) {
factorial = factorial * i; factorial = factorial * i
}); })
return "The factorial of " + num + " is " + factorial; return 'The factorial of ' + num + ' is ' + factorial
} }
} }
// Run `factorial` Function to find average of a list of numbers. // Run `factorial` Function to find average of a list of numbers.
var num = prompt("Enter a number: "); var num = prompt('Enter a number: ')
alert(calc_factorial(num)); alert(calc_factorial(num))

View File

@ -9,30 +9,30 @@
https://en.wikipedia.org/wiki/Least_common_multiple https://en.wikipedia.org/wiki/Least_common_multiple
*/ */
"use strict"; 'use strict'
// Find the LCM of two numbers. // Find the LCM of two numbers.
function find_lcm(num_1, num_2) { function find_lcm (num_1, num_2) {
var max_num; var max_num
var lcm; var lcm
// Check to see whether num_1 or num_2 is larger. // Check to see whether num_1 or num_2 is larger.
if (num_1 > num_2) { if (num_1 > num_2) {
max_num = num_1; max_num = num_1
} else { } else {
max_num = num_2; max_num = num_2
} }
lcm = max_num; lcm = max_num
while (true) { while (true) {
if ((lcm % num_1 === 0) && (lcm % num_2 === 0)) { if ((lcm % num_1 === 0) && (lcm % num_2 === 0)) {
break; break
} }
lcm += max_num; lcm += max_num
} }
return lcm; return lcm
} }
// Run `find_lcm` Function // Run `find_lcm` Function
var num_1 = 12; var num_1 = 12
var num_2 = 76; var num_2 = 76
console.log(find_lcm(num_1, num_2)); console.log(find_lcm(num_1, num_2))

View File

@ -2,10 +2,9 @@
class Graph { class Graph {
// defining vertex array and // defining vertex array and
// adjacent list // adjacent list
constructor(noOfVertices) constructor (noOfVertices) {
{ this.noOfVertices = noOfVertices
this.noOfVertices = noOfVertices; this.AdjList = new Map()
this.AdjList = new Map();
} }
// functions to be implemented // functions to be implemented
@ -23,7 +22,7 @@ addVertex(v)
{ {
// initialize the adjacent list with a // initialize the adjacent list with a
// null array // null array
this.AdjList.set(v, []); this.AdjList.set(v, [])
} }
// add edge to the graph // add edge to the graph
@ -31,57 +30,53 @@ addEdge(v, w)
{ {
// get the list for vertex v and put the // get the list for vertex v and put the
// vertex w denoting edge between v and w // vertex w denoting edge between v and w
this.AdjList.get(v).push(w); this.AdjList.get(v).push(w)
// Since graph is undirected, // Since graph is undirected,
// add an edge from w to v also // add an edge from w to v also
this.AdjList.get(w).push(v); this.AdjList.get(w).push(v)
} }
// Prints the vertex and adjacency list // Prints the vertex and adjacency list
printGraph() printGraph()
{ {
// get all the vertices // get all the vertices
var get_keys = this.AdjList.keys(); var get_keys = this.AdjList.keys()
// iterate over the vertices // iterate over the vertices
for (var i of get_keys) for (var i of get_keys) {
{
// great the corresponding adjacency list // great the corresponding adjacency list
// for the vertex // for the vertex
var get_values = this.AdjList.get(i); var get_values = this.AdjList.get(i)
var conc = ""; var conc = ''
// iterate over the adjacency list // iterate over the adjacency list
// concatenate the values into a string // concatenate the values into a string
for (var j of get_values) for (var j of get_values) { conc += j + ' ' }
conc += j + " ";
// print the vertex and its adjacency list // print the vertex and its adjacency list
console.log(i + " -> " + conc); console.log(i + ' -> ' + conc)
} }
} }
// Example // Example
var graph = new Graph(6); var graph = new Graph(6)
var vertices = [ 'A', 'B', 'C', 'D', 'E', 'F' ]; var vertices = ['A', 'B', 'C', 'D', 'E', 'F']
// adding vertices // adding vertices
for (var i = 0; i < vertices.length; i++) { for (var i = 0; i < vertices.length; i++) {
g.addVertex(vertices[i]); g.addVertex(vertices[i])
} }
// adding edges // adding edges
g.addEdge('A', 'B'); g.addEdge('A', 'B')
g.addEdge('A', 'D'); g.addEdge('A', 'D')
g.addEdge('A', 'E'); g.addEdge('A', 'E')
g.addEdge('B', 'C'); g.addEdge('B', 'C')
g.addEdge('D', 'E'); g.addEdge('D', 'E')
g.addEdge('E', 'F'); g.addEdge('E', 'F')
g.addEdge('E', 'C'); g.addEdge('E', 'C')
g.addEdge('C', 'F'); g.addEdge('C', 'F')
// prints all vertex and // prints all vertex and
// its adjacency list // its adjacency list
@ -91,4 +86,4 @@ g.addEdge('C', 'F');
// D -> A E // D -> A E
// E -> A D F C // E -> A D F C
// F -> E C // F -> E C
g.printGraph(); g.printGraph()