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

@ -6,9 +6,9 @@ function euclideanGCDRecursive(first, second) {
:return: GCD of the numbers
*/
if (second === 0) {
return first;
return first
} else {
return euclideanGCDRecursive(second, (first % second));
return euclideanGCDRecursive(second, (first % second))
}
}
@ -20,18 +20,18 @@ function euclideanGCDIterative(first, second) {
:return: GCD of the numbers
*/
while (second !== 0) {
let temp = second;
second = first % second;
first = temp;
const temp = second
second = first % second
first = temp
}
return first;
return first
}
function main () {
let first = 20;
let second = 30;
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));
const first = 20
const second = 30
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))
}
main();
main()

View File

@ -9,17 +9,17 @@
// a function of the number of input bits
function fib (n) {
var table = [];
table.push(1);
table.push(1);
var table = []
table.push(1)
table.push(1)
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(2);
fib(200);
fib(5);
fib(10);
fib(1)
fib(2)
fib(200)
fib(5)
fib(10)

View File

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

View File

@ -12,27 +12,25 @@
* @return {String} decrypted string
*/
function rot13 (str) {
let response = [];
let strLength = str.length;
const response = []
const strLength = str.length
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) {
response.push(str.charAt(i));
response.push(str.charAt(i))
} 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 {
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
const encryptedString = "Uryyb Jbeyq";
const decryptedString = rot13(encryptedString);
const encryptedString = 'Uryyb Jbeyq'
const decryptedString = rot13(encryptedString)
console.log(decryptedString); // Hello World
console.log(decryptedString) // Hello World

View File

@ -3,24 +3,22 @@ Find and retrieve the encryption key automatically
Note: This is a draft version, please help to modify, Thanks!
******************************************************/
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 key = 0; // return zero means the key can not be found
let inStr = str.toString(); //convert the input to String
let outStr = ""; // store the output value
let outStrElement = ""; // temporary store the word inside the outStr, it is used for comparison
const inStr = str.toString() // convert the input to String
let outStr = '' // store the output value
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
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++) {
// 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
for (let w = 0; w < wordbank[i].length; w++) {
outStrElement += outStr[ s + w ];
outStrElement += outStr[s + w]
}
// console.log( k + outStrElement + wordbank[i] );//debug
@ -28,130 +26,97 @@ function keyFinder(str){ // str is used to get the input of encrypted string
// 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
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++)
}
}
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 */
function caesarCipherEncodeAndDecodeEngine(inStr, numShifted)
{
let shiftNum = numShifted;
let charCode = 0;
let outStr = "";
let shftedcharCode = 0;
let result = 0;
function caesarCipherEncodeAndDecodeEngine (inStr, numShifted) {
const shiftNum = numShifted
let charCode = 0
let outStr = ''
let shftedcharCode = 0
let result = 0
for (let i = 0; i < inStr.length; i++) {
charCode = inStr[i].charCodeAt()
shftedcharCode = charCode + shiftNum
result = charCode
charCode = inStr[i].charCodeAt();
shftedcharCode = charCode + shiftNum;
result = charCode;
if ( (charCode>=48 && charCode<=57))
{
if ((charCode >= 48 && charCode <= 57)) {
if (shftedcharCode < 48) {
let diff = Math.abs(48-1-shftedcharCode)%10;
let diff = Math.abs(48 - 1 - shftedcharCode) % 10
while (diff >= 10) {
diff = diff%10;
diff = diff % 10
}
document.getElementById("diffID").innerHTML = diff;
document.getElementById('diffID').innerHTML = diff
shftedcharCode = 57-diff;
shftedcharCode = 57 - diff
result = shftedcharCode;
}
else if ( shftedcharCode>=48 && shftedcharCode<=57 ){
result = shftedcharCode;
}
else if ( shftedcharCode > 57 ){
let diff = Math.abs(57+1-shftedcharCode)%10;
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;
diff = diff % 10
}
document.getElementById("diffID").innerHTML = diff;
document.getElementById('diffID').innerHTML = diff
shftedcharCode = 48+diff;
shftedcharCode = 48 + diff
result = shftedcharCode;
result = shftedcharCode
}
}
else if ( (charCode>=65 && charCode<=90) )
{
} else if ((charCode >= 65 && charCode <= 90)) {
if (shftedcharCode <= 64) {
let diff = Math.abs(65-1-shftedcharCode)%26;
let diff = Math.abs(65 - 1 - shftedcharCode) % 26
while ((diff % 26) >= 26) {
diff = diff%26;
diff = diff % 26
}
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 = 90 - diff
result = shftedcharCode
} else if (shftedcharCode >= 65 && shftedcharCode <= 90) {
result = shftedcharCode
} else if (shftedcharCode > 90) {
let diff = Math.abs(shftedcharCode - 1 - 90) % 26
while ((diff % 26) >= 26) {
diff = diff%26;
diff = diff % 26
}
shftedcharCode = 65+diff;
result = shftedcharCode;
shftedcharCode = 65 + diff
result = shftedcharCode
}
}
else if ( (charCode>=97 && charCode<=122))
{
} else if ((charCode >= 97 && charCode <= 122)) {
if (shftedcharCode <= 96) {
let diff = Math.abs(97-1-shftedcharCode)%26;
let diff = Math.abs(97 - 1 - shftedcharCode) % 26
while ((diff % 26) >= 26) {
diff = diff%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;
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;
diff = diff % 26
}
shftedcharCode = 97+diff;
result = shftedcharCode;
shftedcharCode = 97 + diff
result = shftedcharCode
}
}
outStr = outStr + String.fromCharCode(parseInt(result));
outStr = outStr + String.fromCharCode(parseInt(result))
}
return outStr;
return outStr
}

View File

@ -4,7 +4,7 @@
* @return {object} An array with the character or null if isn't a letter
*/
function isLetter (str) {
return str.length === 1 && str.match(/[a-zA-Z]/i);
return str.length === 1 && str.match(/[a-zA-Z]/i)
}
/**
@ -14,10 +14,10 @@ function isLetter(str) {
*/
function isUpperCase (character) {
if (character == character.toUpperCase()) {
return true;
return true
}
if (character == character.toLowerCase()) {
return false;
return false
}
}
@ -27,25 +27,23 @@ function isUpperCase(character){
* @param {String} key - key for encrypt
* @return {String} result - encrypted string
*/
function encrypt(message, key)
{
let result = "";
function encrypt (message, key) {
let result = ''
for (let i = 0, j = 0; i < message.length; i++) {
let c = message.charAt(i);
const c = message.charAt(i)
if (isLetter(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 {
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 {
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
* @return {String} result - decrypted string
*/
function decrypt(message, key)
{
let result ="";
function decrypt (message, key) {
let result = ''
for (let i = 0, j = 0; i < message.length; i++) {
let c = message.charAt(i);
const c = message.charAt(i)
if (isLetter(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 {
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 {
result+=c;
result += c
}
j = ++j % key.length;
j = ++j % key.length
}
return result;
return result
}
let messageEncrypt = encrypt('Hello World!', 'code');
console.log(messageEncrypt); // "Jhpnr Yrvng!"
const messageEncrypt = encrypt('Hello World!', 'code')
console.log(messageEncrypt) // "Jhpnr Yrvng!"
let messageDecrypt = decrypt('Jsopq Zstzg!', 'code');
console.log(messageDecrypt); // "Hello World!"
const messageDecrypt = decrypt('Jsopq Zstzg!', 'code')
console.log(messageDecrypt) // "Hello World!"

View File

@ -1,12 +1,12 @@
function decimalToBinary (num) {
var bin = [];
var bin = []
while (num > 0) {
bin.unshift(num % 2);
num >>= 1; // basically /= 2 without remainder if any
bin.unshift(num % 2)
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(7);
decimalToBinary(35);
decimalToBinary(2)
decimalToBinary(7)
decimalToBinary(35)

View File

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

View File

@ -1,15 +1,15 @@
function decimalToOctal (num) {
var oct = 0,c=0;
var oct = 0; var c = 0
while (num > 0) {
var r=num%8;
oct=oct+(r*Math.pow(10,c++));
num =Math.floor(num/ 8); // basically /= 8 without remainder if any
var r = num % 8
oct = oct + (r * Math.pow(10, c++))
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(8);
decimalToOctal(65);
decimalToOctal(216);
decimalToOctal(512);
decimalToOctal(2)
decimalToOctal(8)
decimalToOctal(65)
decimalToOctal(216)
decimalToOctal(512)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -14,103 +14,101 @@
var Node = (function () {
// Node in the tree
function Node (val) {
this.value = val;
this.left = null;
this.right = null;
this.value = val
this.left = null
this.right = null
}
// Search the tree for a value
Node.prototype.search = function (val) {
if (this.value == val) {
return this;
return this
} 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) {
return this.right.search(val);
return this.right.search(val)
}
return null
}
return null;
};
// Visit a node
Node.prototype.visit = function () {
// Recursively go left
if (this.left != null) {
this.left.visit();
this.left.visit()
}
// Print out value
console.log(this.value);
console.log(this.value)
// Recursively go right
if (this.right != null) {
this.right.visit();
this.right.visit()
}
}
};
// Add a node
Node.prototype.addNode = function (n) {
if (n.value < this.value) {
if (this.left == null) {
this.left = n;
this.left = n
} else {
this.left.addNode(n)
}
} else if (n.value > this.value) {
if (this.right == null) {
this.right = n;
this.right = n
} else {
this.right.addNode(n);
this.right.addNode(n)
}
}
}
};
// returns the constructor
return Node;
}());
return Node
}())
// class Tree
var Tree = (function () {
function Tree () {
// Just store the root
this.root = null;
this.root = null
};
// Inorder traversal
Tree.prototype.traverse = function () {
this.root.visit();
};
this.root.visit()
}
// Start by searching the root
Tree.prototype.search = function (val) {
let found = this.root.search(val);
const found = this.root.search(val)
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
Tree.prototype.addValue = function (val) {
let n = new Node(val);
const n = new Node(val)
if (this.root == null) {
this.root = n;
this.root = n
} else {
this.root.addNode(n);
this.root.addNode(n)
}
}
};
// returns the constructor
return Tree;
}());
return Tree
}())
// Implementation of BST
var bst = new Tree();
bst.addValue(6);
bst.addValue(3);
bst.addValue(9);
bst.addValue(2);
bst.addValue(8);
bst.addValue(4);
bst.traverse();
bst.search(8);
var bst = new Tree()
bst.addValue(6)
bst.addValue(3)
bst.addValue(9)
bst.addValue(2)
bst.addValue(8)
bst.addValue(4)
bst.traverse()
bst.search(8)

View File

@ -6,7 +6,7 @@
//= ===============================================================
// main variables
const CHAR_SIZE = 8;
const CHAR_SIZE = 8
/**
* Adds padding to binary/hex string represention
@ -19,11 +19,11 @@ const CHAR_SIZE = 8;
* pad("10011", 8); // "00010011"
*/
function pad (str, bits) {
let res = str;
let res = str
while (res.length % bits !== 0) {
res = "0" + res;
res = '0' + res
}
return res;
return res
}
/**
@ -37,11 +37,11 @@ function pad(str, bits) {
* chunkify("this is a test", 2); // ["th", "is", " i", "s ", "a ", "te", "st"]
*/
function chunkify (str, size) {
let chunks = [];
const chunks = []
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
}
/**
@ -55,7 +55,7 @@ function chunkify(str, size) {
* rotateLeft("1011", 3); // "1101"
*/
function rotateLeft (bits, turns) {
return bits.substr(turns) + bits.substr(0, turns);
return bits.substr(turns) + bits.substr(0, turns)
}
/**
@ -67,24 +67,24 @@ function rotateLeft(bits, turns) {
function preProcess (message) {
// convert message to binary representation padded to
// 8 bits, and add 1
let m = message.split("")
let m = message.split('')
.map(e => e.charCodeAt(0))
.map(e => e.toString(2))
.map(e => pad(e, 8))
.join("") + "1";
.join('') + '1'
// extend message by adding empty bits (0)
while (m.length % 512 !== 448) {
m += "0";
m += '0'
}
// length of message in binary, padded, and extended
// to a 64 bit representation
let ml = (message.length * CHAR_SIZE).toString(2);
ml = pad(ml, 8);
ml = "0".repeat(64 - ml.length) + ml;
let ml = (message.length * CHAR_SIZE).toString(2)
ml = pad(ml, 8)
ml = '0'.repeat(64 - ml.length) + ml
return m + ml;
return m + ml
}
/**
@ -95,88 +95,83 @@ function preProcess(message) {
*/
function SHA1 (message) {
// main variables
let H0 = 0x67452301;
let H1 = 0xEFCDAB89;
let H2 = 0x98BADCFE;
let H3 = 0x10325476;
let H4 = 0xC3D2E1F0;
let H0 = 0x67452301
let H1 = 0xEFCDAB89
let H2 = 0x98BADCFE
let H3 = 0x10325476
let H4 = 0xC3D2E1F0
// pre-process message and split into 512 bit chunks
let bits = preProcess(message);
let chunks = chunkify(bits, 512);
const bits = preProcess(message)
const chunks = chunkify(bits, 512)
chunks.forEach(function (chunk, i) {
// 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
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))
.reduce((acc, curr) => curr ^ acc, 0);
let bin = (val >>> 0).toString(2);
let paddedBin = pad(bin, 32);
let word = rotateLeft(paddedBin, 1);
words.push(word);
.reduce((acc, curr) => curr ^ acc, 0)
const bin = (val >>> 0).toString(2)
const paddedBin = pad(bin, 32)
const word = rotateLeft(paddedBin, 1)
words.push(word)
}
// 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++) {
let f, k;
let f, k
if (i < 20) {
f = (b & c) | (~b & d);
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;
f = (b & c) | (~b & d)
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
}
// 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;
f >>>= 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)
H0 = (H0 + a) >>> 0;
H1 = (H1 + b) >>> 0;
H2 = (H2 + c) >>> 0;
H3 = (H3 + d) >>> 0;
H4 = (H4 + e) >>> 0;
});
H0 = (H0 + a) >>> 0
H1 = (H1 + b) >>> 0
H2 = (H2 + c) >>> 0
H3 = (H3 + d) >>> 0
H4 = (H4 + e) >>> 0
})
// 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 => 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;
module.exports = SHA1

View File

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

View File

@ -6,22 +6,21 @@
*/
function binarySearch (arr, i) {
var mid = Math.floor(arr.length / 2);
var mid = Math.floor(arr.length / 2)
if (arr[mid] === i) {
console.log("match", arr[mid], i);
return arr[mid];
console.log('match', arr[mid], i)
return arr[mid]
} 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) {
binarySearch(arr.splice(0, mid), i);
binarySearch(arr.splice(0, mid), i)
} else {
console.log("not found", i);
return -1;
console.log('not found', i)
return -1
}
}
}
var ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
binarySearch(ar, 3);
binarySearch(ar, 7);
binarySearch(ar, 13);
var ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
binarySearch(ar, 3)
binarySearch(ar, 7)
binarySearch(ar, 13)

View File

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

View File

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

View File

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

View File

@ -3,34 +3,31 @@
* sorted in ascending order.
*/
Array.prototype.isSorted = function () {
let length = this.length;
const length = this.length
if (length < 2) {
return true;
return true
}
for (let i = 0; i < length - 1; i++) {
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.
*/
Array.prototype.shuffle = function () {
for (let i = this.length - 1; i; i--) {
let m = Math.floor(Math.random() * i);
let n = this[i - 1];
this[i - 1] = this[m];
this[m] = n;
const m = Math.floor(Math.random() * i)
const n = this[i - 1]
this[i - 1] = this[m]
this[m] = n
}
}
};
/*
* Implementation of the bogosort algorithm. This sorting algorithm randomly
@ -38,18 +35,17 @@ Array.prototype.shuffle = function () {
* For more information see: https://en.wikipedia.org/wiki/Bogosort
*/
function bogoSort (items) {
while (!items.isSorted()) {
items.shuffle()
}
return items;
return items
}
// 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
console.log(ar);
bogoSort(ar);
console.log(ar)
bogoSort(ar)
// Array after sort
console.log(ar);
console.log(ar)

View File

@ -12,51 +12,49 @@ Best Case O(n); Average Case O(n); Worst Case O(n)
*/
function bucketSort (list, size) {
if (undefined === size) {
size = 5;
size = 5
}
if (list.length === 0) {
return list;
return list
}
let min = list[0];
let max = list[0];
let min = list[0]
let max = list[0]
// find min and max
for (let iList = 0; iList < list.length; iList++) {
if (list[iList] < min) {
min = list[iList];
min = list[iList]
} else if (list[iList] > max) {
max = list[iList];
max = list[iList]
}
}
// how many buckets we need
let count = Math.floor((max - min) / size) + 1;
const count = Math.floor((max - min) / size) + 1
// create buckets
let buckets = [];
const buckets = []
for (let iCount = 0; iCount < count; iCount++) {
buckets.push([]);
buckets.push([])
}
// bucket fill
for (let iBucket = 0; iBucket < list.length; iBucket++) {
let key = Math.floor((list[iBucket] - min) / size);
buckets[key].push(list[iBucket]);
const key = Math.floor((list[iBucket] - min) / size)
buckets[key].push(list[iBucket])
}
let sorted = [];
const sorted = []
// now sort every bucket and merge it to the sorted list
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++) {
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
console.log(arrOrignal);
arrSorted = bucketSort(arrOrignal);
console.log(arrOrignal)
arrSorted = bucketSort(arrOrignal)
// Array after sort
console.log(arrSorted);
console.log(arrSorted)

View File

@ -5,41 +5,40 @@
*
*/
function cocktailShakerSort (items) {
for (let i = items.length - 1; i > 0; i--) {
let swapped = false;
let temp, j;
let swapped = false
let temp, j
// backwards
for (j = items.length - 1; j > i; j--) {
if (items[j] < items[j - 1]) {
temp = items[j];
items[j] = items[j - 1];
items[j - 1] = temp;
swapped = true;
temp = items[j]
items[j] = items[j - 1]
items[j - 1] = temp
swapped = true
}
}
// forwards
for (j = 0; j < i; j++) {
if (items[j] > items[j + 1]) {
temp = items[j];
items[j] = items[j + 1];
items[j + 1] = temp;
swapped = true;
temp = items[j]
items[j] = items[j + 1]
items[j + 1] = temp
swapped = true
}
}
if (!swapped) {
return;
return
}
}
}
// 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
console.log(ar);
cocktailShakerSort(ar);
console.log(ar)
cocktailShakerSort(ar)
// Array after sort
console.log(ar);
console.log(ar)

View File

@ -15,39 +15,36 @@ a "shrink factor" k: [ n/k, n/k2, n/k3, ..., 1 ].
*/
function combSort (list) {
if (list.length === 0) {
return list;
return list
}
let shrink = 1.3;
let gap = list.length;
let isSwapped = true;
const shrink = 1.3
let gap = list.length
let isSwapped = true
let i = 0
while (gap > 1 || isSwapped) {
// Update the gap value for a next comb
gap = parseInt(parseFloat(gap) / shrink, 10);
gap = parseInt(parseFloat(gap) / shrink, 10)
isSwapped = false
i = 0
while (gap + i < list.length) {
if (list[i] > list[i + gap]) {
let value = list[i];
list[i] = list[i + gap];
list[i + gap] = value;
isSwapped = true;
const value = list[i]
list[i] = list[i + gap]
list[i + gap] = value
isSwapped = true
}
i += 1
}
}
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
console.log(arrOrignal);
arrSorted = combSort(arrOrignal);
console.log(arrOrignal)
arrSorted = combSort(arrOrignal)
// Array after sort
console.log(arrSorted);
console.log(arrSorted)

View File

@ -6,32 +6,32 @@
*/
function countingSort (arr, min, max) {
let i;
let z = 0;
const count = [];
let i
let z = 0
const count = []
for (i = min; i <= max; i++) {
count[i] = 0;
count[i] = 0
}
for (i = 0; i < arr.length; i++) {
count[arr[i]]++;
count[arr[i]]++
}
for (i = min; i <= max; i++) {
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
console.log("-----before sorting-----");
console.log(arr);
console.log('-----before sorting-----')
console.log(arr)
// Array after sort
console.log("-----after sorting-----");
console.log(countingSort(arr, 0, 5));
console.log('-----after sorting-----')
console.log(countingSort(arr, 0, 5))

View File

@ -6,57 +6,53 @@ 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.
*/
function cycleSort (list) {
let writes = 0;
let writes = 0
for (let cycleStart = 0; cycleStart < list.length; cycleStart++) {
let value = list[cycleStart];
let position = cycleStart;
let value = list[cycleStart]
let position = cycleStart
// search position
for (let i = cycleStart + 1; i < list.length; i++) {
if (list[i] < value) {
position++;
position++
}
}
// if its the same continue
if (position == cycleStart) {
continue;
continue
}
while (value == list[position]) {
position++;
position++
}
let oldValue = list[position];
list[position] = value;
value = oldValue;
writes++;
const oldValue = list[position]
list[position] = value
value = oldValue
writes++
// rotate the rest
while (position != cycleStart) {
position = cycleStart;
position = cycleStart
for (let i = cycleStart + 1; i < list.length; i++) {
if (list[i] < value) {
position++;
position++
}
}
while (value == list[position]) {
position++;
position++
}
let oldValueCycle = list[position];
list[position] = value;
value = oldValueCycle;
writes++;
const oldValueCycle = list[position]
list[position] = value
value = oldValueCycle
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
console.log(arrOrignal);
cycleSort(arrOrignal);
console.log(arrOrignal)
cycleSort(arrOrignal)
// Array after sort
console.log(arrOrignal);
console.log(arrOrignal)

View File

@ -5,81 +5,81 @@
*/
function flashSort (arr) {
let max = 0, min = arr[0];
let n = arr.length;
let m = ~~(0.45 * n);
let l = new Array(m);
let max = 0; let min = arr[0]
const n = arr.length
const m = ~~(0.45 * n)
const l = new Array(m)
for (let i = 1; i < n; ++i) {
if (arr[i] < min) {
min = arr[i];
min = arr[i]
}
if (arr[i] > arr[max]) {
max = i;
max = i
}
}
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++) {
l[k] = 0;
l[k] = 0
}
for (let j = 0; j < n; ++j) {
let k = ~~(c1 * (arr[j] - min));
++l[k];
const k = ~~(c1 * (arr[j] - min))
++l[k]
}
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];
arr[max] = arr[0];
arr[0] = hold;
let hold = arr[max]
arr[max] = arr[0]
arr[0] = hold
// permutation
let move = 0, t, flash;
let j = 0;
let k = m - 1;
let move = 0; let t; let flash
let j = 0
let k = m - 1
while (move < (n - 1)) {
while (j > (l[k] - 1)) {
++j;
k = ~~(c1 * (arr[j] - min));
++j
k = ~~(c1 * (arr[j] - min))
}
if (k < 0) break;
flash = arr[j];
if (k < 0) break
flash = arr[j]
while (j !== l[k]) {
k = ~~(c1 * (flash - min));
hold = arr[t = --l[k]];
arr[t] = flash;
flash = hold;
++move;
k = ~~(c1 * (flash - min))
hold = arr[t = --l[k]]
arr[t] = flash
flash = hold
++move
}
}
// insertion
for (j = 1; j < n; j++) {
hold = arr[j];
let i = j - 1;
hold = arr[j]
let i = j - 1
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
console.log("-----before sorting-----");
console.log(array);
console.log('-----before sorting-----')
console.log(array)
// Array after sort
console.log("-----after sorting-----");
console.log(flashSort(array));
console.log('-----after sorting-----')
console.log(flashSort(array))

View File

@ -4,33 +4,30 @@
*
*/
function gnomeSort (items) {
if (items.length <= 1) {
return;
return
}
let i = 1;
let i = 1
while (i < items.length) {
if (items[i - 1] <= items[i]) {
i++;
i++
} else {
let temp = items[i];
items[i] = items[i - 1];
items[i - 1] = temp;
const temp = items[i]
items[i] = items[i - 1]
items[i - 1] = temp
i = Math.max(1, i - 1);
i = Math.max(1, i - 1)
}
}
}
// 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
console.log(ar);
gnomeSort(ar);
console.log(ar)
gnomeSort(ar)
// Array after sort
console.log(ar);
console.log(ar)

View File

@ -6,27 +6,26 @@
* Source: https://en.wikipedia.org/wiki/Heap_(data_structure)
*/
Array.prototype.heapify = function (index, heapSize) {
let largest = index;
let leftIndex = 2 * index + 1;
let rightIndex = 2 * index + 2;
let largest = index
const leftIndex = 2 * index + 1
const rightIndex = 2 * index + 2
if (leftIndex < heapSize && this[leftIndex] > this[largest]) {
largest = leftIndex;
largest = leftIndex
}
if (rightIndex < heapSize && this[rightIndex] > this[largest]) {
largest = rightIndex;
largest = rightIndex
}
if (largest !== index) {
let temp = this[largest];
this[largest] = this[index];
this[index] = temp;
const temp = this[largest]
this[largest] = this[index]
this[index] = temp
this.heapify(largest, heapSize);
this.heapify(largest, heapSize)
}
}
};
/*
* Heap sort sorts an array by building a heap from the array and
@ -34,26 +33,25 @@ Array.prototype.heapify = function (index, heapSize) {
* For more information see: https://en.wikipedia.org/wiki/Heapsort
*/
function heapSort (items) {
let length = items.length;
const length = items.length
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--) {
let tmp = items[0];
items[0] = items[j];
items[j] = tmp;
items.heapify(0, j);
const tmp = items[0]
items[0] = items[j]
items[j] = tmp
items.heapify(0, j)
}
return items;
return items
}
// 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
console.log(ar);
heapSort(ar);
console.log(ar)
heapSort(ar)
// Array after sort
console.log(ar);
console.log(ar)

View File

@ -5,20 +5,20 @@
* the correct position and expand sorted part one element at a time.
*/
function insertionSort (unsortedList) {
var len = unsortedList.length;
var len = unsortedList.length
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 */
for (var j = i - 1; j >= 0 && (unsortedList[j] > tmp); j--) {
// Shift the number
unsortedList[j + 1] = unsortedList[j];
unsortedList[j + 1] = unsortedList[j]
}
// Insert the copied number at the correct position
// in sorted part.
unsortedList[j + 1] = tmp;
unsortedList[j + 1] = tmp
}
}
var arr = [5, 3, 1, 2, 4, 8, 3, 8];
insertionSort(arr);
console.log(arr);
var arr = [5, 3, 1, 2, 4, 8, 3, 8]
insertionSort(arr)
console.log(arr)

View File

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

View File

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

View File

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

View File

@ -8,30 +8,30 @@
*from the unsorted subarray is picked and moved to the sorted subarray.
*/
function selectionSort (items) {
var length = items.length;
var length = items.length
for (var i = 0; i < length - 1; i++) {
// 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
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) {
// After each pass, if the current min num != initial min num, exchange the position.
// Swap the numbers
var tmp = items[i];
items[i] = items[min];
items[min] = tmp;
var tmp = items[i]
items[i] = items[min]
items[min] = tmp
}
}
}
// 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
console.log(ar);
selectionSort(ar);
console.log(ar)
selectionSort(ar)
// Array after sort
console.log(ar);
console.log(ar)

View File

@ -4,37 +4,33 @@
*
*/
function shellSort (items) {
var interval = 1;
var interval = 1
while (interval < items.length / 3) {
interval = interval * 3 + 1;
interval = interval * 3 + 1
}
while (interval > 0) {
for (var outer = interval; outer < items.length; outer++) {
var value = items[outer];
var inner = outer;
var value = items[outer]
var inner = outer
while (inner > interval - 1 && items[inner - interval] >= value) {
items[inner] = items[inner - interval];
inner = inner - interval;
items[inner] = items[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
var ar = [5, 6, 7, 8, 1, 2, 12, 14];
var ar = [5, 6, 7, 8, 1, 2, 12, 14]
// Array before Sort
console.log(ar);
shellSort(ar);
console.log(ar)
shellSort(ar)
// Array after sort
console.log(ar);
console.log(ar)

View File

@ -6,21 +6,21 @@
Array.prototype.wiggleSort = function () {
for (let i = 0; i < this.length; ++i) {
const shouldNotBeLessThan = i % 2;
const isLessThan = this[i] < this[i + 1];
const shouldNotBeLessThan = i % 2
const isLessThan = this[i] < this[i + 1]
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
var arr = [3, 5, 2, 1, 6, 4];
var arr = [3, 5, 2, 1, 6, 4]
// Array before Wiggle Sort
console.log(arr); //[3, 5, 2, 1, 6, 4]
console.log(arr) // [3, 5, 2, 1, 6, 4]
arr.wiggleSort()
// Array after wiggle sort
console.log(arr); // [ 3, 5, 2, 6, 1, 4 ]
console.log(arr) // [ 3, 5, 2, 6, 1, 4 ]

View File

@ -14,194 +14,183 @@ var LinearAlgebra;
var Vector = /** @class */ (function () {
// constructor
function Vector (N, comps) {
if (comps === void 0) { comps = []; }
this.components = new Array(N);
if (comps === void 0) { comps = [] }
this.components = new Array(N)
if (comps.length == 0) {
for (var i = 0; i < N; i++) {
this.components[i] = 0.0;
this.components[i] = 0.0
}
}
else {
} else {
if (N == comps.length) {
this.components = comps;
}
else {
throw "Vector: invalide size!";
this.components = comps
} else {
throw 'Vector: invalide size!'
}
}
} // end of constructor
// returns the size of this vector.
// not the eulidean length!
Vector.prototype.size = function () {
return this.components.length;
};
return this.components.length
}
// computes the eulidean length.
Vector.prototype.eulideanLength = function () {
var sum = 0;
var sum = 0
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.
// returns a specified component (index)
Vector.prototype.component = function (index) {
return this.components[index];
};
return this.components[index]
}
// setter for a specified component of this vector.
Vector.prototype.changeComponent = function (index, value) {
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.prototype.add = function (other) {
if (this.size() == other.size()) {
var SIZE = this.size();
var ans = new Vector(SIZE);
var SIZE = this.size()
var ans = new Vector(SIZE)
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.prototype.sub = function (other) {
if (this.size() == other.size()) {
var SIZE = this.size();
var ans = new Vector(SIZE);
var SIZE = this.size()
var ans = new Vector(SIZE)
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
Vector.prototype.dot = function (other) {
var sum = 0;
var sum = 0
if (other.size() == this.size()) {
var SIZE = other.size();
var SIZE = other.size()
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
Vector.prototype.scalar = function (s) {
var SIZE = this.size();
var ans = new Vector(SIZE);
var SIZE = this.size()
var ans = new Vector(SIZE)
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.
Vector.prototype.toString = function () {
var ans = "(";
var SIZE = this.components.length;
var ans = '('
var SIZE = this.components.length
for (var i = 0; i < SIZE; i++) {
if (i < SIZE - 1) {
ans += this.components[i] + ",";
}
else {
ans += this.components[i] + ")";
ans += this.components[i] + ','
} else {
ans += this.components[i] + ')'
}
}
return ans;
};
return ans
}
// converts this vector in a unit basis vector and returns it.
// the One is on position 'pos'
Vector.prototype.createUnitBasis = function (pos) {
if (pos >= 0 && pos < this.components.length) {
for (var i = 0; i < this.components.length; i++) {
if (i == pos) {
this.components[i] = 1.0;
}
else {
this.components[i] = 0.0;
this.components[i] = 1.0
} else {
this.components[i] = 0.0
}
}
} else {
throw 'createUnitBasis: index out of bounds'
}
else {
throw "createUnitBasis: index out of bounds";
return this
}
return this;
};
// normalizes this vector and returns it.
Vector.prototype.norm = function () {
var SIZE = this.size();
var quotient = 1.0 / this.eulideanLength();
var SIZE = this.size()
var quotient = 1.0 / this.eulideanLength()
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.
Vector.prototype.equal = function (other) {
var ans = true;
var SIZE = this.size();
var EPSILON = 0.001;
var ans = true
var SIZE = this.size()
var EPSILON = 0.001
if (SIZE == other.size()) {
for (var i = 0; i < SIZE; i++) {
if (Math.abs(this.components[i] - other.component(i)) > EPSILON) {
ans = false;
ans = false
}
}
} else {
ans = false
}
else {
ans = false;
return ans
}
return ans;
};
return Vector;
}()); // end of class Vector
LinearAlgebra.Vector = Vector;
return Vector
}()) // end of class Vector
LinearAlgebra.Vector = Vector
// -------------- global functions ---------------------------------
// returns a unit basis vector of size N with a One on position 'pos'
function unitBasisVector (N, pos) {
var ans = new Vector(N);
var ans = new Vector(N)
for (var i = 0; i < N; i++) {
if (i == pos) {
ans.changeComponent(i, 1.0);
}
else {
ans.changeComponent(i, 0);
ans.changeComponent(i, 1.0)
} else {
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.
function randomVectorInt (N, a, b) {
var ans = new Vector(N);
var ans = new Vector(N)
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.
function randomVectorFloat (N, a, b) {
var ans = new Vector(N);
var ans = new Vector(N)
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 -----------------------------
/*
class: Matrix
@ -210,116 +199,109 @@ var LinearAlgebra;
var Matrix = /** @class */ (function () {
// constructor for zero-matrix or fix number matrix.
function Matrix (row, col, comps) {
if (comps === void 0) { comps = []; }
if (comps === void 0) { comps = [] }
if (comps.length == 0) {
this.matrix = new Array();
var rowVector = new Array();
this.matrix = new Array()
var rowVector = new Array()
for (var i = 0; i < row; i++) {
for (var j = 0; j < col; j++) {
rowVector[j] = 0;
rowVector[j] = 0
}
this.matrix[i] = rowVector;
rowVector = new Array();
this.matrix[i] = rowVector
rowVector = new Array()
}
} else {
this.matrix = comps
}
else {
this.matrix = comps;
}
this.rows = row;
this.cols = col;
this.rows = row
this.cols = col
}
// returns the specified component.
Matrix.prototype.component = function (x, y) {
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'.
Matrix.prototype.changeComponent = function (x, y, value) {
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.
Matrix.prototype.toString = function () {
var ans = "";
var ans = ''
for (var i = 0; i < this.rows; i++) {
ans += "|";
ans += '|'
for (var j = 0; j < this.cols; j++) {
if (j < this.cols - 1) {
ans += this.matrix[i][j] + ",";
}
else {
ans += this.matrix[i][j] + ','
} else {
if (i < this.rows - 1) {
ans += this.matrix[i][j] + "|\n";
}
else {
ans += this.matrix[i][j] + "|";
ans += this.matrix[i][j] + '|\n'
} else {
ans += this.matrix[i][j] + '|'
}
}
}
}
return ans;
};
return ans
}
// returns the dimension rows x cols as number array
Matrix.prototype.dimension = function () {
var ans = new Array();
ans[0] = this.rows;
ans[1] = this.cols;
return ans;
};
var ans = new Array()
ans[0] = this.rows
ans[1] = this.cols
return ans
}
// matrix addition. returns the result.
Matrix.prototype.add = function (other) {
if (this.rows == other.dimension()[0]
&& this.cols == other.dimension()[1]) {
var ans = new Matrix(this.rows, this.cols);
if (this.rows == other.dimension()[0] &&
this.cols == other.dimension()[1]) {
var ans = new Matrix(this.rows, this.cols)
for (var i = 0; i < this.rows; i++) {
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.
Matrix.prototype.equal = function (other) {
var ans = true;
var EPSILON = 0.001;
if (this.rows == other.dimension()[0]
&& this.cols == other.dimension()[1]) {
var ans = true
var EPSILON = 0.001
if (this.rows == other.dimension()[0] &&
this.cols == other.dimension()[1]) {
for (var i = 0; i < this.rows; i++) {
for (var j = 0; j < this.cols; j++) {
if (Math.abs(this.matrix[i][j] - other.component(i, j)) > EPSILON) {
ans = false;
ans = false
}
}
}
} else {
ans = false
}
else {
ans = false;
return ans
}
return ans;
};
// matrix-scalar multiplication
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 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 Matrix;
}()); // end of class Matrix
LinearAlgebra.Matrix = Matrix;
})(LinearAlgebra || (LinearAlgebra = {})); // end of namespace LinearAlgebra
return ans
}
return Matrix
}()) // end of class Matrix
LinearAlgebra.Matrix = Matrix
})(LinearAlgebra || (LinearAlgebra = {})) // end of namespace LinearAlgebra

View File

@ -6,11 +6,11 @@
The tests use javascript test-framework mocha
*/
var assert = require('assert');
var fs = require('fs');
var assert = require('assert')
var fs = require('fs')
// file is included here
eval(fs.readFileSync('src/la_lib.js') + '');
eval(fs.readFileSync('src/la_lib.js') + '')
// Tests goes here
@ -18,153 +18,152 @@ eval(fs.readFileSync('src/la_lib.js') + '');
describe('Create Vectors', function () {
describe('#toString()', function () {
it('should return a string representation', function () {
assert.equal((new LinearAlgebra.Vector(3, [1, 2, 3])).toString(), "(1,2,3)");
});
});
describe("#unitBasisVector()", function () {
it("should return a unit basis vector", function () {
assert.equal(LinearAlgebra.unitBasisVector(3, 1).toString(), "(0,1,0)");
});
});
});
assert.equal((new LinearAlgebra.Vector(3, [1, 2, 3])).toString(), '(1,2,3)')
})
})
describe('#unitBasisVector()', function () {
it('should return a unit basis vector', function () {
assert.equal(LinearAlgebra.unitBasisVector(3, 1).toString(), '(0,1,0)')
})
})
})
// operations on it.
describe("Vector operations", function () {
describe("#add()", function () {
it("should return vector (2,4,6)", function () {
var x = 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)");
});
});
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('Vector operations', function () {
describe('#add()', function () {
it('should return vector (2,4,6)', function () {
var x = 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)')
})
})
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,68 +1,63 @@
// starting at s
function solve (graph, s) {
var solutions = {};
solutions[s] = [];
solutions[s].dist = 0;
var solutions = {}
solutions[s] = []
solutions[s].dist = 0
while (true) {
var p = null;
var neighbor = null;
var dist = Infinity;
var p = null
var neighbor = null
var dist = Infinity
for (var n in solutions) {
if(!solutions[n])
continue
var ndist = solutions[n].dist;
var adj = graph[n];
if (!solutions[n]) { continue }
var ndist = solutions[n].dist
var adj = graph[n]
for (var a in adj) {
if (solutions[a]) { continue }
if(solutions[a])
continue;
var d = adj[a] + ndist;
var d = adj[a] + ndist
if (d < dist) {
p = solutions[n];
neighbor = a;
dist = d;
p = solutions[n]
neighbor = a
dist = d
}
}
}
// no more solutions
if (dist === Infinity) {
break;
break
}
// extend parent's solution path
solutions[neighbor] = p.concat(neighbor);
solutions[neighbor] = p.concat(neighbor)
// extend parent's cost
solutions[neighbor].dist = dist;
solutions[neighbor].dist = dist
}
return solutions;
return solutions
}
// create graph
var graph = {};
var graph = {}
var layout = {
'R': ['2'],
'2': ['3','4'],
'3': ['4','6','13'],
'4': ['5','8'],
'5': ['7','11'],
'6': ['13','15'],
'7': ['10'],
'8': ['11','13'],
'9': ['14'],
'10': [],
'11': ['12'],
'12': [],
'13': ['14'],
'14': [],
'15': []
R: ['2'],
2: ['3', '4'],
3: ['4', '6', '13'],
4: ['5', '8'],
5: ['7', '11'],
6: ['13', '15'],
7: ['10'],
8: ['11', '13'],
9: ['14'],
10: [],
11: ['12'],
12: [],
13: ['14'],
14: [],
15: []
}
// convert uni-directional to bi-directional graph
@ -78,26 +73,24 @@ var layout = {
// };
for (var id in layout) {
if(!graph[id])
graph[id] = {};
if (!graph[id]) { graph[id] = {} }
layout[id].forEach(function (aid) {
graph[id][aid] = 1;
if(!graph[aid])
graph[aid] = {};
graph[aid][id] = 1;
});
graph[id][aid] = 1
if (!graph[aid]) { graph[aid] = {} }
graph[aid][id] = 1
})
}
// choose start node
var start = '10';
var start = '10'
// 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
for (var s in solutions) {
if(!solutions[s]) continue;
console.log(" -> " + s + ": [" + solutions[s].join(", ") + "] (dist:" + solutions[s].dist + ")");
if (!solutions[s]) continue
console.log(' -> ' + s + ': [' + solutions[s].join(', ') + '] (dist:' + solutions[s].dist + ')')
}
// From '10' to

View File

@ -13,7 +13,7 @@
function abs_val (num) {
// Find absolute value of `num`.
"use strict";
'use strict'
if (num < 0) {
return -num
}
@ -22,5 +22,5 @@ function abs_val(num) {
}
// 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

@ -12,19 +12,19 @@
*/
function mean (nums) {
"use strict";
var sum = 0;
var avg;
'use strict'
var sum = 0
var avg
// This loop sums all values in the 'nums' array.
nums.forEach(function (current) {
sum += current;
});
sum += current
})
// Divide sum by the length of the 'nums' array.
avg = sum / nums.length;
return avg;
avg = sum / nums.length
return avg
}
// 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
*/
"use strict";
'use strict'
function calc_range (num) {
// Generate a range of numbers from 1 to `num`.
var i = 1;
var range = [];
var i = 1
var range = []
while (i <= num) {
range.push(i);
i += 1;
range.push(i)
i += 1
}
return range;
return range
}
function calc_factorial (num) {
var factorial;
var range = calc_range(num);
var factorial
var range = calc_range(num)
// Check if the number is negative, positive, null, undefined, or zero
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) {
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) {
return "The factorial of 0 is 1.";
return 'The factorial of 0 is 1.'
}
if (num > 0) {
factorial = 1;
factorial = 1
range.forEach(function (i) {
factorial = factorial * i;
});
return "The factorial of " + num + " is " + factorial;
factorial = factorial * i
})
return 'The factorial of ' + num + ' is ' + factorial
}
}
// Run `factorial` Function to find average of a list of numbers.
var num = prompt("Enter a number: ");
alert(calc_factorial(num));
var num = prompt('Enter a number: ')
alert(calc_factorial(num))

View File

@ -9,30 +9,30 @@
https://en.wikipedia.org/wiki/Least_common_multiple
*/
"use strict";
'use strict'
// Find the LCM of two numbers.
function find_lcm (num_1, num_2) {
var max_num;
var lcm;
var max_num
var lcm
// Check to see whether num_1 or num_2 is larger.
if (num_1 > num_2) {
max_num = num_1;
max_num = num_1
} else {
max_num = num_2;
max_num = num_2
}
lcm = max_num;
lcm = max_num
while (true) {
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
var num_1 = 12;
var num_2 = 76;
console.log(find_lcm(num_1, num_2));
var num_1 = 12
var num_2 = 76
console.log(find_lcm(num_1, num_2))

View File

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