mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 16:26:47 +08:00
npx standard --fix
This commit is contained in:
@ -1,37 +1,37 @@
|
||||
function euclideanGCDRecursive(first, second) {
|
||||
/*
|
||||
function euclideanGCDRecursive (first, second) {
|
||||
/*
|
||||
Calculates GCD of two numbers using Euclidean Recursive Algorithm
|
||||
:param first: First number
|
||||
:param second: Second number
|
||||
:return: GCD of the numbers
|
||||
*/
|
||||
if (second === 0) {
|
||||
return first;
|
||||
} else {
|
||||
return euclideanGCDRecursive(second, (first % second));
|
||||
}
|
||||
if (second === 0) {
|
||||
return first
|
||||
} else {
|
||||
return euclideanGCDRecursive(second, (first % second))
|
||||
}
|
||||
}
|
||||
|
||||
function euclideanGCDIterative(first, second) {
|
||||
/*
|
||||
function euclideanGCDIterative (first, second) {
|
||||
/*
|
||||
Calculates GCD of two numbers using Euclidean Iterative Algorithm
|
||||
:param first: First number
|
||||
:param second: Second number
|
||||
:return: GCD of the numbers
|
||||
*/
|
||||
while (second !== 0) {
|
||||
let temp = second;
|
||||
second = first % second;
|
||||
first = temp;
|
||||
}
|
||||
return first;
|
||||
while (second !== 0) {
|
||||
const temp = second
|
||||
second = first % second
|
||||
first = temp
|
||||
}
|
||||
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));
|
||||
function main () {
|
||||
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()
|
||||
|
@ -1,21 +1,21 @@
|
||||
function KadaneAlgo (array) {
|
||||
let cummulativeSum = 0
|
||||
let maxSum = 0
|
||||
for (var i = 0; i < array.length; i++) {
|
||||
cummulativeSum = cummulativeSum + array[i]
|
||||
if(cummulativeSum < 0 ) {
|
||||
cummulativeSum = 0
|
||||
}
|
||||
if (maxSum < cummulativeSum) {
|
||||
maxSum = cummulativeSum
|
||||
}
|
||||
let cummulativeSum = 0
|
||||
let maxSum = 0
|
||||
for (var i = 0; i < array.length; i++) {
|
||||
cummulativeSum = cummulativeSum + array[i]
|
||||
if (cummulativeSum < 0) {
|
||||
cummulativeSum = 0
|
||||
}
|
||||
return maxSum
|
||||
// This function returns largest sum contigous sum in a array
|
||||
if (maxSum < cummulativeSum) {
|
||||
maxSum = cummulativeSum
|
||||
}
|
||||
}
|
||||
return maxSum
|
||||
// This function returns largest sum contigous sum in a array
|
||||
}
|
||||
function main() {
|
||||
var myArray = [1,2,3,4,-6]
|
||||
var result = KadaneAlgo(myArray)
|
||||
console.log(result)
|
||||
function main () {
|
||||
var myArray = [1, 2, 3, 4, -6]
|
||||
var result = KadaneAlgo(myArray)
|
||||
console.log(result)
|
||||
}
|
||||
main()
|
||||
main()
|
||||
|
@ -8,18 +8,18 @@
|
||||
// of the input value n, it is exponential in the size of n as
|
||||
// a function of the number of input bits
|
||||
|
||||
function fib(n) {
|
||||
var table = [];
|
||||
table.push(1);
|
||||
table.push(1);
|
||||
for (var i = 2; i < n; ++i) {
|
||||
table.push(table[i - 1] + table[i - 2]);
|
||||
}
|
||||
console.log("Fibonacci #%d = %d", n, table[n - 1]);
|
||||
function fib (n) {
|
||||
var table = []
|
||||
table.push(1)
|
||||
table.push(1)
|
||||
for (var i = 2; i < n; ++i) {
|
||||
table.push(table[i - 1] + table[i - 2])
|
||||
}
|
||||
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)
|
||||
|
@ -1,31 +1,31 @@
|
||||
function sieveOfEratosthenes(n) {
|
||||
/*
|
||||
function sieveOfEratosthenes (n) {
|
||||
/*
|
||||
* Calculates prime numbers till a number 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));
|
||||
for (let i = 2; i <= sqrtn; i++) {
|
||||
if (primes[i]) {
|
||||
for (let j = 2 * i; j <= n; j += i) {
|
||||
primes[j] = false;
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
return primes;
|
||||
}
|
||||
return primes
|
||||
}
|
||||
|
||||
function main() {
|
||||
let n = 69; // number till where we wish to find primes
|
||||
let primes = sieveOfEratosthenes(n);
|
||||
for (let i = 2; i <= n; i++) {
|
||||
if (primes[i]) {
|
||||
console.log(i);
|
||||
}
|
||||
function main () {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
main()
|
||||
|
@ -11,28 +11,26 @@
|
||||
* @param {String} str - string to be decrypted
|
||||
* @return {String} decrypted string
|
||||
*/
|
||||
function rot13(str) {
|
||||
let response = [];
|
||||
let strLength = str.length;
|
||||
function rot13 (str) {
|
||||
const response = []
|
||||
const strLength = str.length
|
||||
|
||||
for (let i = 0; i < strLength; i++) {
|
||||
const char = str.charCodeAt(i);
|
||||
|
||||
if (char < 65 || (char > 90 && char < 97) || char > 122) {
|
||||
response.push(str.charAt(i));
|
||||
} else if ((char > 77 && char <= 90) || (char > 109 && char <= 122)) {
|
||||
response.push(String.fromCharCode(str.charCodeAt(i) - 13));
|
||||
} else {
|
||||
response.push(String.fromCharCode(str.charCodeAt(i) + 13));
|
||||
}
|
||||
for (let i = 0; i < strLength; i++) {
|
||||
const char = str.charCodeAt(i)
|
||||
|
||||
if (char < 65 || (char > 90 && char < 97) || char > 122) {
|
||||
response.push(str.charAt(i))
|
||||
} else if ((char > 77 && char <= 90) || (char > 109 && char <= 122)) {
|
||||
response.push(String.fromCharCode(str.charCodeAt(i) - 13))
|
||||
} else {
|
||||
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
|
||||
|
@ -1,157 +1,122 @@
|
||||
/******************************************************
|
||||
Find and retrieve the encryption key automatically
|
||||
Find and retrieve the encryption key automatically
|
||||
Note: This is a draft version, please help to modify, Thanks!
|
||||
******************************************************/
|
||||
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 "];
|
||||
//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
|
||||
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
|
||||
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 ']
|
||||
// let wordbankelementCounter = 0;
|
||||
// let key = 0; // return zero means the key can not be found
|
||||
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
|
||||
|
||||
//loop through the whole input string
|
||||
for ( let s=0; s < outStr.length; s++){
|
||||
// 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]
|
||||
}
|
||||
|
||||
for ( let i=0; i < wordbank.length; i++){
|
||||
// console.log( k + outStrElement + wordbank[i] );//debug
|
||||
|
||||
// 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 ];
|
||||
}
|
||||
// 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
|
||||
}
|
||||
|
||||
//console.log( k + outStrElement + wordbank[i] );//debug
|
||||
|
||||
// this part need to be optimize with the calculation of the number of occurance of word's probabilities
|
||||
// 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
|
||||
}
|
||||
|
||||
outStrElement = ""; //reset the temp word
|
||||
|
||||
} // end for ( let i=0; i < wordbank.length; i++)
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
return 0; // return 0 if found nothing
|
||||
outStrElement = '' // reset the temp word
|
||||
} // end for ( let i=0; i < wordbank.length; i++)
|
||||
}
|
||||
}
|
||||
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++){
|
||||
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 (shftedcharCode < 48) {
|
||||
let diff = Math.abs(48 - 1 - shftedcharCode) % 10
|
||||
|
||||
if ( (charCode>=48 && charCode<=57))
|
||||
{
|
||||
if ( shftedcharCode < 48 ){
|
||||
while (diff >= 10) {
|
||||
diff = diff % 10
|
||||
}
|
||||
document.getElementById('diffID').innerHTML = diff
|
||||
|
||||
let diff = Math.abs(48-1-shftedcharCode)%10;
|
||||
shftedcharCode = 57 - diff
|
||||
|
||||
while( diff >= 10){
|
||||
diff = diff%10;
|
||||
}
|
||||
document.getElementById("diffID").innerHTML = diff;
|
||||
result = shftedcharCode
|
||||
} else if (shftedcharCode >= 48 && shftedcharCode <= 57) {
|
||||
result = shftedcharCode
|
||||
} else if (shftedcharCode > 57) {
|
||||
let diff = Math.abs(57 + 1 - shftedcharCode) % 10
|
||||
|
||||
shftedcharCode = 57-diff;
|
||||
|
||||
result = shftedcharCode;
|
||||
}
|
||||
while (diff >= 10) {
|
||||
diff = diff % 10
|
||||
}
|
||||
document.getElementById('diffID').innerHTML = diff
|
||||
|
||||
else if ( shftedcharCode>=48 && shftedcharCode<=57 ){
|
||||
result = shftedcharCode;
|
||||
}
|
||||
shftedcharCode = 48 + diff
|
||||
|
||||
else if ( shftedcharCode > 57 ){
|
||||
result = shftedcharCode
|
||||
}
|
||||
} else if ((charCode >= 65 && charCode <= 90)) {
|
||||
if (shftedcharCode <= 64) {
|
||||
let diff = Math.abs(65 - 1 - shftedcharCode) % 26
|
||||
|
||||
let diff = Math.abs(57+1-shftedcharCode)%10;
|
||||
while ((diff % 26) >= 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
|
||||
|
||||
while( diff >= 10){
|
||||
diff = diff%10;
|
||||
}
|
||||
document.getElementById("diffID").innerHTML = diff;
|
||||
while ((diff % 26) >= 26) {
|
||||
diff = diff % 26
|
||||
}
|
||||
shftedcharCode = 65 + diff
|
||||
result = shftedcharCode
|
||||
}
|
||||
} else if ((charCode >= 97 && charCode <= 122)) {
|
||||
if (shftedcharCode <= 96) {
|
||||
let diff = Math.abs(97 - 1 - shftedcharCode) % 26
|
||||
|
||||
shftedcharCode = 48+diff;
|
||||
while ((diff % 26) >= 26) {
|
||||
diff = diff % 26
|
||||
}
|
||||
shftedcharCode = 122 - diff
|
||||
result = shftedcharCode
|
||||
} else if (shftedcharCode >= 97 && shftedcharCode <= 122) {
|
||||
result = shftedcharCode
|
||||
} else if (shftedcharCode > 122) {
|
||||
let diff = Math.abs(shftedcharCode - 1 - 122) % 26
|
||||
|
||||
result = shftedcharCode;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
else if ( (charCode>=65 && charCode<=90) )
|
||||
{
|
||||
|
||||
if (shftedcharCode <=64 ){
|
||||
|
||||
let diff = Math.abs(65-1-shftedcharCode)%26;
|
||||
|
||||
while( (diff%26) >= 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;
|
||||
|
||||
while( (diff%26) >= 26){
|
||||
diff = diff%26;
|
||||
}
|
||||
shftedcharCode = 65+diff;
|
||||
result = shftedcharCode;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
else if ( (charCode>=97 && charCode<=122))
|
||||
{
|
||||
if ( shftedcharCode<=96 ){
|
||||
|
||||
let diff = Math.abs(97-1-shftedcharCode)%26;
|
||||
|
||||
while( (diff%26) >= 26){
|
||||
diff = diff%26;
|
||||
}
|
||||
shftedcharCode = 122-diff;
|
||||
result = shftedcharCode;
|
||||
}
|
||||
|
||||
else if ( shftedcharCode>=97 && shftedcharCode<=122 ){
|
||||
result = shftedcharCode;
|
||||
}
|
||||
|
||||
else if (shftedcharCode>122 ){
|
||||
let diff = Math.abs(shftedcharCode-1-122)%26;
|
||||
|
||||
while( (diff%26) >= 26){
|
||||
diff = diff%26;
|
||||
}
|
||||
shftedcharCode = 97+diff;
|
||||
result = shftedcharCode;
|
||||
}
|
||||
|
||||
}
|
||||
outStr = outStr + String.fromCharCode(parseInt(result));
|
||||
}
|
||||
return outStr;
|
||||
while ((diff % 26) >= 26) {
|
||||
diff = diff % 26
|
||||
}
|
||||
shftedcharCode = 97 + diff
|
||||
result = shftedcharCode
|
||||
}
|
||||
}
|
||||
outStr = outStr + String.fromCharCode(parseInt(result))
|
||||
}
|
||||
return outStr
|
||||
}
|
||||
|
@ -3,8 +3,8 @@
|
||||
* @param {String} character - character to check
|
||||
* @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);
|
||||
function isLetter (str) {
|
||||
return str.length === 1 && str.match(/[a-zA-Z]/i)
|
||||
}
|
||||
|
||||
/**
|
||||
@ -12,12 +12,12 @@ function isLetter(str) {
|
||||
* @param {String} character - character to check
|
||||
* @return {Boolean} result of the checking
|
||||
*/
|
||||
function isUpperCase(character){
|
||||
function isUpperCase (character) {
|
||||
if (character == character.toUpperCase()) {
|
||||
return true;
|
||||
return true
|
||||
}
|
||||
if (character == character.toLowerCase()){
|
||||
return false;
|
||||
if (character == character.toLowerCase()) {
|
||||
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);
|
||||
if (isLetter(c)){
|
||||
if(isUpperCase(c)) {
|
||||
result += String.fromCharCode((c.charCodeAt(0) + key.toUpperCase().charCodeAt(j) - 2 * 65) % 26 + 65); // A: 65
|
||||
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
|
||||
} 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);
|
||||
if (isLetter(c)){
|
||||
if(isUpperCase(c)) {
|
||||
result += String.fromCharCode(90-(25-(c.charCodeAt(0)-key.toUpperCase().charCodeAt(j)))%26);
|
||||
for (let i = 0, j = 0; i < message.length; 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)
|
||||
} 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!"
|
||||
|
@ -1,12 +1,12 @@
|
||||
function decimalToBinary(num) {
|
||||
var bin = [];
|
||||
function decimalToBinary (num) {
|
||||
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)
|
||||
|
@ -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";
|
||||
}
|
||||
return num;
|
||||
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'
|
||||
}
|
||||
return num
|
||||
}
|
||||
|
||||
function decimalToHex(num){
|
||||
let hex_out = [];
|
||||
while(num > 15) {
|
||||
hex_out.push(intToHex(num%16));
|
||||
num = Math.floor(num / 16);
|
||||
}
|
||||
return intToHex(num) + hex_out.join("");
|
||||
function decimalToHex (num) {
|
||||
const hex_out = []
|
||||
while (num > 15) {
|
||||
hex_out.push(intToHex(num % 16))
|
||||
num = Math.floor(num / 16)
|
||||
}
|
||||
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')
|
||||
|
@ -1,15 +1,15 @@
|
||||
function decimalToOctal(num) {
|
||||
var oct = 0,c=0;
|
||||
function decimalToOctal (num) {
|
||||
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)
|
||||
|
@ -1,50 +1,44 @@
|
||||
|
||||
class Graph {
|
||||
constructor () {
|
||||
this.adjacencyMap = {}
|
||||
}
|
||||
|
||||
constructor() {
|
||||
this.adjacencyMap = {}
|
||||
addVertex (v) {
|
||||
this.adjacencyMap[v] = []
|
||||
}
|
||||
|
||||
containsVertex (vertex) {
|
||||
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)
|
||||
result = true
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
addVertex(v) {
|
||||
this.adjacencyMap[v] = [];
|
||||
printGraph () {
|
||||
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)
|
||||
}
|
||||
|
||||
containsVertex(vertex) {
|
||||
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);
|
||||
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 example = () => {
|
||||
let g = new Graph()
|
||||
g.addVertex(1)
|
||||
g.addVertex(2)
|
||||
g.addVertex(3)
|
||||
g.addEdge(1, 2)
|
||||
g.addEdge(1, 3)
|
||||
g.printGraph()
|
||||
}
|
||||
const g = new Graph()
|
||||
g.addVertex(1)
|
||||
g.addVertex(2)
|
||||
g.addVertex(3)
|
||||
g.addEdge(1, 2)
|
||||
g.addEdge(1, 3)
|
||||
g.printGraph()
|
||||
}
|
||||
|
@ -1,8 +1,8 @@
|
||||
|
||||
/* Minimum Priority Queue
|
||||
* It is a part of heap data structure
|
||||
* A heap is a specific tree based data structure
|
||||
* in which all the nodes of tree are in a specific order.
|
||||
* A heap is a specific tree based data structure
|
||||
* in which all the nodes of tree are in a specific order.
|
||||
* that is the children are arranged in some
|
||||
* respect of their parents, can either be greater
|
||||
* or less than the parent. This makes it a min priority queue
|
||||
@ -12,117 +12,115 @@
|
||||
// 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;
|
||||
// calss the constructor and initializes the capacity
|
||||
constructor (c) {
|
||||
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;
|
||||
// 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
|
||||
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];
|
||||
// returns the highest priority value
|
||||
peek () {
|
||||
return this.heap[1]
|
||||
}
|
||||
|
||||
// returns boolean value whether the heap is empty or not
|
||||
isEmpty() {
|
||||
if (0 == this.size) return true;
|
||||
return false;
|
||||
// returns boolean value whether the heap is empty or not
|
||||
isEmpty () {
|
||||
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;
|
||||
// returns boolean value whether the heap is full or not
|
||||
isFull () {
|
||||
if (this.size == this.capacity) return true
|
||||
return false
|
||||
}
|
||||
|
||||
// prints the heap
|
||||
print() {
|
||||
console.log(this.heap.slice(1));
|
||||
// prints the heap
|
||||
print () {
|
||||
console.log(this.heap.slice(1))
|
||||
}
|
||||
|
||||
// heap sorting can be done by performing
|
||||
// delete function to the number of times of the size of the heap
|
||||
// it returns reverse sort because it is a min priority queue
|
||||
heapSort() {
|
||||
// heap sorting can be done by performing
|
||||
// delete function to the number of times of the size of the heap
|
||||
// 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;
|
||||
// this function reorders the heap after every delete function
|
||||
sink () {
|
||||
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;
|
||||
}
|
||||
if (2 * k + 1 <= this.size && this.heap[2 * k + 1] >= this.heap[k]) {
|
||||
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;
|
||||
// deletes the highest priority value from the heap
|
||||
delete () {
|
||||
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 ]
|
||||
|
@ -1,197 +1,195 @@
|
||||
//Hamza chabchoub contribution for a university project
|
||||
function doubleLinkedList() {
|
||||
let Node = function(element) {
|
||||
this.element = element;
|
||||
this.next = null;
|
||||
this.prev = null;
|
||||
// Hamza chabchoub contribution for a university project
|
||||
function doubleLinkedList () {
|
||||
const Node = function (element) {
|
||||
this.element = element
|
||||
this.next = null
|
||||
this.prev = null
|
||||
}
|
||||
|
||||
let length = 0
|
||||
let head = null
|
||||
let tail = null
|
||||
|
||||
// Add new element
|
||||
this.append = function (element) {
|
||||
const node = new Node(element)
|
||||
|
||||
if (!head) {
|
||||
head = node
|
||||
tail = node
|
||||
} else {
|
||||
node.prev = tail
|
||||
tail.next = node
|
||||
tail = node
|
||||
}
|
||||
|
||||
let length = 0;
|
||||
let head = null;
|
||||
let tail = null;
|
||||
|
||||
//Add new element
|
||||
this.append = function(element) {
|
||||
let node = new Node(element);
|
||||
|
||||
if(!head){
|
||||
head = node;
|
||||
tail = node;
|
||||
}else{
|
||||
node.prev = tail;
|
||||
tail.next = node;
|
||||
tail = node;
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
if(position === 0){
|
||||
if(!head){
|
||||
head = node;
|
||||
tail = node;
|
||||
}else{
|
||||
node.next = current;
|
||||
current.prev = node;
|
||||
head = node;
|
||||
}
|
||||
}else if(position === length){
|
||||
current = tail;
|
||||
current.next = node;
|
||||
node.prev = current;
|
||||
tail = node;
|
||||
}else{
|
||||
while(index++ < position){
|
||||
previous = current;
|
||||
current = current.next;
|
||||
}
|
||||
|
||||
node.next = current;
|
||||
previous.next = node;
|
||||
|
||||
//New
|
||||
current.prev = node;
|
||||
node.prev = previous;
|
||||
|
||||
length++
|
||||
}
|
||||
|
||||
// Add element
|
||||
this.insert = function (position, element) {
|
||||
// Check of out-of-bound values
|
||||
if (position >= 0 && position <= length) {
|
||||
const node = new Node(element)
|
||||
let current = head
|
||||
let previous
|
||||
let index = 0
|
||||
|
||||
if (position === 0) {
|
||||
if (!head) {
|
||||
head = node
|
||||
tail = node
|
||||
} else {
|
||||
node.next = current
|
||||
current.prev = node
|
||||
head = node
|
||||
}
|
||||
|
||||
length++;
|
||||
return true;
|
||||
}else{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
//Remove element at any position
|
||||
this.removeAt = function(position){
|
||||
//look for out-of-bounds value
|
||||
if(position > -1 && position < length){
|
||||
let current = head, previous, index = 0;
|
||||
|
||||
//Removing first item
|
||||
if(position === 0){
|
||||
head = current.next;
|
||||
|
||||
//if there is only one item, update tail //NEW
|
||||
if(length === 1){
|
||||
tail = null;
|
||||
}else{
|
||||
head.prev = null;
|
||||
}
|
||||
}else if(position === length - 1){
|
||||
current = tail;
|
||||
tail = current.prev;
|
||||
tail.next = null;
|
||||
}else{
|
||||
while(index++ < position){
|
||||
previous = current;
|
||||
current = current.next;
|
||||
}
|
||||
|
||||
//link previous with current's next - skip it
|
||||
previous.next = current.next;
|
||||
current.next.prev = previous;
|
||||
} else if (position === length) {
|
||||
current = tail
|
||||
current.next = node
|
||||
node.prev = current
|
||||
tail = node
|
||||
} else {
|
||||
while (index++ < position) {
|
||||
previous = current
|
||||
current = current.next
|
||||
}
|
||||
|
||||
length--;
|
||||
return current.element;
|
||||
}else{
|
||||
return null;
|
||||
|
||||
node.next = current
|
||||
previous.next = node
|
||||
|
||||
// New
|
||||
current.prev = node
|
||||
node.prev = previous
|
||||
}
|
||||
|
||||
length++
|
||||
return true
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
|
||||
//Get the indexOf item
|
||||
this.indexOf = function(elm){
|
||||
let current = head,
|
||||
index = -1;
|
||||
|
||||
//If element found then return its position
|
||||
while(current){
|
||||
if(elm === current.element){
|
||||
return ++index;
|
||||
}
|
||||
|
||||
// Remove element at any position
|
||||
this.removeAt = function (position) {
|
||||
// look for out-of-bounds value
|
||||
if (position > -1 && position < length) {
|
||||
let current = head; let previous; let index = 0
|
||||
|
||||
// Removing first item
|
||||
if (position === 0) {
|
||||
head = current.next
|
||||
|
||||
// if there is only one item, update tail //NEW
|
||||
if (length === 1) {
|
||||
tail = null
|
||||
} else {
|
||||
head.prev = null
|
||||
}
|
||||
|
||||
index++;
|
||||
current = current.next;
|
||||
}
|
||||
|
||||
//Else return -1
|
||||
return -1;
|
||||
};
|
||||
|
||||
//Find the item in the list
|
||||
this.isPresent = (elm) => {
|
||||
return this.indexOf(elm) !== -1;
|
||||
};
|
||||
|
||||
//Delete an item from the list
|
||||
this.delete = (elm) => {
|
||||
return this.removeAt(this.indexOf(elm));
|
||||
};
|
||||
|
||||
//Delete first item from the list
|
||||
this.deleteHead = function(){
|
||||
this.removeAt(0);
|
||||
}
|
||||
|
||||
//Delete last item from the list
|
||||
this.deleteTail = function(){
|
||||
this.removeAt(length-1);
|
||||
}
|
||||
|
||||
//Print item of the string
|
||||
this.toString = function(){
|
||||
let current = head,
|
||||
string = '';
|
||||
|
||||
while(current){
|
||||
string += current.element + (current.next ? '\n' : '');
|
||||
current = current.next;
|
||||
} else if (position === length - 1) {
|
||||
current = tail
|
||||
tail = current.prev
|
||||
tail.next = null
|
||||
} else {
|
||||
while (index++ < position) {
|
||||
previous = current
|
||||
current = current.next
|
||||
}
|
||||
|
||||
// link previous with current's next - skip it
|
||||
previous.next = current.next
|
||||
current.next.prev = previous
|
||||
}
|
||||
|
||||
return string;
|
||||
};
|
||||
|
||||
//Convert list to array
|
||||
this.toArray = function(){
|
||||
let arr = [],
|
||||
current = head;
|
||||
|
||||
while(current){
|
||||
arr.push(current.element);
|
||||
current = current.next;
|
||||
|
||||
length--
|
||||
return current.element
|
||||
} else {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Get the indexOf item
|
||||
this.indexOf = function (elm) {
|
||||
let current = head
|
||||
let index = -1
|
||||
|
||||
// If element found then return its position
|
||||
while (current) {
|
||||
if (elm === current.element) {
|
||||
return ++index
|
||||
}
|
||||
|
||||
return arr;
|
||||
};
|
||||
|
||||
//Check if list is empty
|
||||
this.isEmpty = function(){
|
||||
return length === 0;
|
||||
};
|
||||
|
||||
//Get the size of the list
|
||||
this.size = function(){
|
||||
return length;
|
||||
|
||||
index++
|
||||
current = current.next
|
||||
}
|
||||
|
||||
//Get the head
|
||||
this.getHead = function() {
|
||||
return head;
|
||||
|
||||
// Else return -1
|
||||
return -1
|
||||
}
|
||||
|
||||
// Find the item in the list
|
||||
this.isPresent = (elm) => {
|
||||
return this.indexOf(elm) !== -1
|
||||
}
|
||||
|
||||
// Delete an item from the list
|
||||
this.delete = (elm) => {
|
||||
return this.removeAt(this.indexOf(elm))
|
||||
}
|
||||
|
||||
// Delete first item from the list
|
||||
this.deleteHead = function () {
|
||||
this.removeAt(0)
|
||||
}
|
||||
|
||||
// Delete last item from the list
|
||||
this.deleteTail = function () {
|
||||
this.removeAt(length - 1)
|
||||
}
|
||||
|
||||
// Print item of the string
|
||||
this.toString = function () {
|
||||
let current = head
|
||||
let string = ''
|
||||
|
||||
while (current) {
|
||||
string += current.element + (current.next ? '\n' : '')
|
||||
current = current.next
|
||||
}
|
||||
|
||||
//Get the tail
|
||||
this.getTail = function() {
|
||||
return tail;
|
||||
|
||||
return string
|
||||
}
|
||||
|
||||
// Convert list to array
|
||||
this.toArray = function () {
|
||||
const arr = []
|
||||
let current = head
|
||||
|
||||
while (current) {
|
||||
arr.push(current.element)
|
||||
current = current.next
|
||||
}
|
||||
}
|
||||
|
||||
return arr
|
||||
}
|
||||
|
||||
// Check if list is empty
|
||||
this.isEmpty = function () {
|
||||
return length === 0
|
||||
}
|
||||
|
||||
// Get the size of the list
|
||||
this.size = function () {
|
||||
return length
|
||||
}
|
||||
|
||||
// Get the head
|
||||
this.getHead = function () {
|
||||
return head
|
||||
}
|
||||
|
||||
// Get the tail
|
||||
this.getTail = function () {
|
||||
return tail
|
||||
}
|
||||
}
|
||||
|
@ -6,212 +6,204 @@
|
||||
* a singly linked list.
|
||||
*/
|
||||
|
||||
//Functions - add, remove, indexOf, elementAt, addAt, removeAt, view
|
||||
// Functions - add, remove, indexOf, elementAt, addAt, removeAt, view
|
||||
|
||||
// class LinkedList and constructor
|
||||
//Creates a LinkedList
|
||||
// Creates a LinkedList
|
||||
var LinkedList = (function () {
|
||||
|
||||
function LinkedList() {
|
||||
//Length of linklist and head is null at start
|
||||
this.length = 0;
|
||||
this.head = null;
|
||||
|
||||
function LinkedList () {
|
||||
// Length of linklist and head is null at start
|
||||
this.length = 0
|
||||
this.head = null
|
||||
}
|
||||
|
||||
// class node (constructor)
|
||||
//Creating Node with element's value
|
||||
// Creating Node with element's value
|
||||
var Node = (function () {
|
||||
function Node(element) {
|
||||
this.element = element;
|
||||
this.next = null;
|
||||
function Node (element) {
|
||||
this.element = element
|
||||
this.next = null
|
||||
}
|
||||
return Node;
|
||||
}());
|
||||
return Node
|
||||
}())
|
||||
|
||||
//Returns length
|
||||
// Returns length
|
||||
LinkedList.prototype.size = function () {
|
||||
return this.length;
|
||||
};
|
||||
return this.length
|
||||
}
|
||||
|
||||
//Returns the head
|
||||
// Returns the head
|
||||
LinkedList.prototype.head = function () {
|
||||
return this.head;
|
||||
};
|
||||
return this.head
|
||||
}
|
||||
|
||||
//Creates a node and adds it to linklist
|
||||
// Creates a node and adds it to linklist
|
||||
LinkedList.prototype.add = function (element) {
|
||||
var node = new Node(element);
|
||||
//Check if its the first 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
|
||||
// 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;
|
||||
// Adding node to the end of the list
|
||||
currentNode.next = node
|
||||
}
|
||||
//Increment the length
|
||||
this.length++;
|
||||
};
|
||||
// Increment the length
|
||||
this.length++
|
||||
}
|
||||
|
||||
//Removes the node with the value as param
|
||||
// Removes the node with the value as param
|
||||
LinkedList.prototype.remove = function (element) {
|
||||
var currentNode = this.head;
|
||||
var previousNode;
|
||||
var currentNode = this.head
|
||||
var previousNode
|
||||
|
||||
//Check if the head node is the element to remove
|
||||
// Check if the head node is the element to remove
|
||||
if (currentNode.element === element) {
|
||||
this.head = currentNode.next;
|
||||
}
|
||||
else {
|
||||
|
||||
//Check which node is the node to remove
|
||||
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;
|
||||
// Removing the currentNode
|
||||
previousNode.next = currentNode.next
|
||||
}
|
||||
|
||||
//Decrementing the length
|
||||
this.length--;
|
||||
};
|
||||
// Decrementing the length
|
||||
this.length--
|
||||
}
|
||||
|
||||
//Return if the list is empty
|
||||
// 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
|
||||
// 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
|
||||
// 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
|
||||
// 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
|
||||
// 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
|
||||
// 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
|
||||
// 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;
|
||||
// Adding the node at specified index
|
||||
node.next = currentNode
|
||||
previousNode.next = node
|
||||
}
|
||||
|
||||
//Incrementing the length
|
||||
this.length++;
|
||||
return true;
|
||||
};
|
||||
// Incrementing the length
|
||||
this.length++
|
||||
return true
|
||||
}
|
||||
|
||||
//Removes the node at specified index
|
||||
// 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
|
||||
// Check if index is present in list
|
||||
if (index < 0 || index >= this.length) {
|
||||
return null;
|
||||
return null
|
||||
}
|
||||
|
||||
//Check if element is the first element
|
||||
// Check if element is the first element
|
||||
if (index === 0) {
|
||||
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;
|
||||
};
|
||||
// Decrementing the length
|
||||
this.length--
|
||||
return currentNode.element
|
||||
}
|
||||
|
||||
//Function to view the LinkedList
|
||||
// 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();
|
||||
// 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()
|
||||
|
@ -5,80 +5,76 @@
|
||||
* implementation uses an array to store the queue.
|
||||
*/
|
||||
|
||||
//Functions: enqueue, dequeue, peek, view, length
|
||||
// Functions: enqueue, dequeue, peek, view, length
|
||||
|
||||
var Queue = (function () {
|
||||
|
||||
// constructor
|
||||
function Queue() {
|
||||
|
||||
//This is the array representation of the queue
|
||||
this.queue = [];
|
||||
|
||||
function Queue () {
|
||||
// This is the array representation of the queue
|
||||
this.queue = []
|
||||
}
|
||||
|
||||
// methods
|
||||
//Add a value to the end of the 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
|
||||
// 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
|
||||
// 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
|
||||
// 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
|
||||
// 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()
|
||||
|
||||
//Implementation
|
||||
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!
|
||||
// console.log(myQueue.dequeue()); // throws exception!
|
||||
|
@ -7,69 +7,66 @@
|
||||
|
||||
// Functions: push, pop, peek, view, length
|
||||
|
||||
//Creates a stack constructor
|
||||
// Creates a stack constructor
|
||||
var Stack = (function () {
|
||||
|
||||
function Stack() {
|
||||
//The top of the Stack
|
||||
this.top = 0;
|
||||
//The array representation of the stack
|
||||
this.stack = new Array();
|
||||
function Stack () {
|
||||
// The top of the Stack
|
||||
this.top = 0
|
||||
// The array representation of the stack
|
||||
this.stack = new Array()
|
||||
}
|
||||
|
||||
//Adds a value onto the end of the stack
|
||||
// Adds a value onto the end of the stack
|
||||
Stack.prototype.push = function (value) {
|
||||
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
|
||||
// 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;
|
||||
};
|
||||
|
||||
//Returns the size of the stack
|
||||
Stack.prototype.size = function () {
|
||||
return this.top;
|
||||
};
|
||||
|
||||
//Returns the value at the end of the stack
|
||||
Stack.prototype.peek = function () {
|
||||
return this.stack[this.top - 1];
|
||||
this.top--
|
||||
var result = this.stack[this.top]
|
||||
delete this.stack[this.top]
|
||||
return result
|
||||
}
|
||||
|
||||
//To see all the elements in the stack
|
||||
// Returns the size of the stack
|
||||
Stack.prototype.size = function () {
|
||||
return this.top
|
||||
}
|
||||
|
||||
// Returns the value at the end of the stack
|
||||
Stack.prototype.peek = function () {
|
||||
return this.stack[this.top - 1]
|
||||
}
|
||||
|
||||
// To see all the elements in the stack
|
||||
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()
|
||||
|
||||
//Implementation
|
||||
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()
|
||||
|
@ -1,4 +1,4 @@
|
||||
/*Binary Search Tree!!
|
||||
/* Binary Search Tree!!
|
||||
*
|
||||
* Nodes that will go on the Binary Tree.
|
||||
* They consist of the data in them, the node to the left, the node
|
||||
@ -13,104 +13,102 @@
|
||||
// class Node
|
||||
var Node = (function () {
|
||||
// Node in the tree
|
||||
function Node(val) {
|
||||
this.value = val;
|
||||
this.left = null;
|
||||
this.right = null;
|
||||
function Node (val) {
|
||||
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() {
|
||||
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);
|
||||
// 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)
|
||||
|
219
Hashes/SHA1.js
219
Hashes/SHA1.js
@ -1,12 +1,12 @@
|
||||
//================================================================
|
||||
//= ===============================================================
|
||||
// SHA1.js
|
||||
//
|
||||
// Module that replicates the SHA-1 Cryptographic Hash
|
||||
// Module that replicates the SHA-1 Cryptographic Hash
|
||||
// function in Javascript.
|
||||
//================================================================
|
||||
//= ===============================================================
|
||||
|
||||
//main variables
|
||||
const CHAR_SIZE = 8;
|
||||
// main variables
|
||||
const CHAR_SIZE = 8
|
||||
|
||||
/**
|
||||
* Adds padding to binary/hex string represention
|
||||
@ -18,12 +18,12 @@ const CHAR_SIZE = 8;
|
||||
* @example
|
||||
* pad("10011", 8); // "00010011"
|
||||
*/
|
||||
function pad(str, bits) {
|
||||
let res = str;
|
||||
while (res.length % bits !== 0) {
|
||||
res = "0" + res;
|
||||
}
|
||||
return res;
|
||||
function pad (str, bits) {
|
||||
let res = str
|
||||
while (res.length % bits !== 0) {
|
||||
res = '0' + res
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
/**
|
||||
@ -36,12 +36,12 @@ function pad(str, bits) {
|
||||
* @example
|
||||
* chunkify("this is a test", 2); // ["th", "is", " i", "s ", "a ", "te", "st"]
|
||||
*/
|
||||
function chunkify(str, size) {
|
||||
let chunks = [];
|
||||
for (let i = 0; i < str.length; i += size) {
|
||||
chunks.push(str.slice(i, i + size));
|
||||
}
|
||||
return chunks;
|
||||
function chunkify (str, size) {
|
||||
const chunks = []
|
||||
for (let i = 0; i < str.length; i += size) {
|
||||
chunks.push(str.slice(i, i + size))
|
||||
}
|
||||
return chunks
|
||||
}
|
||||
|
||||
/**
|
||||
@ -54,8 +54,8 @@ function chunkify(str, size) {
|
||||
* @example
|
||||
* rotateLeft("1011", 3); // "1101"
|
||||
*/
|
||||
function rotateLeft(bits, turns) {
|
||||
return bits.substr(turns) + bits.substr(0, turns);
|
||||
function rotateLeft (bits, turns) {
|
||||
return bits.substr(turns) + bits.substr(0, turns)
|
||||
}
|
||||
|
||||
/**
|
||||
@ -64,27 +64,27 @@ function rotateLeft(bits, turns) {
|
||||
* @param {string} message - message to pre-process
|
||||
* @return {string} - processed message
|
||||
*/
|
||||
function preProcess(message) {
|
||||
//convert message to binary representation padded to
|
||||
//8 bits, and add 1
|
||||
let m = message.split("")
|
||||
.map(e => e.charCodeAt(0))
|
||||
.map(e => e.toString(2))
|
||||
.map(e => pad(e, 8))
|
||||
.join("") + "1";
|
||||
function preProcess (message) {
|
||||
// convert message to binary representation padded to
|
||||
// 8 bits, and add 1
|
||||
let m = message.split('')
|
||||
.map(e => e.charCodeAt(0))
|
||||
.map(e => e.toString(2))
|
||||
.map(e => pad(e, 8))
|
||||
.join('') + '1'
|
||||
|
||||
//extend message by adding empty bits (0)
|
||||
while (m.length % 512 !== 448) {
|
||||
m += "0";
|
||||
}
|
||||
// extend message by adding empty bits (0)
|
||||
while (m.length % 512 !== 448) {
|
||||
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;
|
||||
// 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
|
||||
|
||||
return m + ml;
|
||||
return m + ml
|
||||
}
|
||||
|
||||
/**
|
||||
@ -93,90 +93,85 @@ function preProcess(message) {
|
||||
* @param {string} message - message to hash
|
||||
* @return {string} - message digest (hash value)
|
||||
*/
|
||||
function SHA1(message) {
|
||||
//main variables
|
||||
let H0 = 0x67452301;
|
||||
let H1 = 0xEFCDAB89;
|
||||
let H2 = 0x98BADCFE;
|
||||
let H3 = 0x10325476;
|
||||
let H4 = 0xC3D2E1F0;
|
||||
function SHA1 (message) {
|
||||
// main variables
|
||||
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);
|
||||
|
||||
chunks.forEach(function(chunk, i) {
|
||||
//break each chunk into 16 32-bit words
|
||||
let words = chunkify(chunk, 32);
|
||||
// pre-process message and split into 512 bit chunks
|
||||
const bits = preProcess(message)
|
||||
const chunks = chunkify(bits, 512)
|
||||
|
||||
//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]]
|
||||
.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);
|
||||
}
|
||||
chunks.forEach(function (chunk, i) {
|
||||
// break each chunk into 16 32-bit words
|
||||
const words = chunkify(chunk, 32)
|
||||
|
||||
//initialize variables for this chunk
|
||||
let [a, b, c, d, e] = [H0, H1, H2, H3, H4];
|
||||
// extend 16 32-bit words to 80 32-bit words
|
||||
for (let i = 16; i < 80; i++) {
|
||||
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)
|
||||
const bin = (val >>> 0).toString(2)
|
||||
const paddedBin = pad(bin, 32)
|
||||
const word = rotateLeft(paddedBin, 1)
|
||||
words.push(word)
|
||||
}
|
||||
|
||||
for (let i = 0; i < 80; i++) {
|
||||
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;
|
||||
}
|
||||
//make sure f is unsigned
|
||||
f >>>= 0;
|
||||
// initialize variables for this chunk
|
||||
let [a, b, c, d, e] = [H0, H1, H2, H3, H4]
|
||||
|
||||
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;
|
||||
for (let i = 0; i < 80; i++) {
|
||||
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
|
||||
}
|
||||
// make sure f is unsigned
|
||||
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;
|
||||
});
|
||||
// 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
|
||||
})
|
||||
|
||||
//combine hash values of main hash variables and return
|
||||
let HH = [H0, H1, H2, H3, H4]
|
||||
.map(e => e.toString(16))
|
||||
.map(e => pad(e, 8))
|
||||
.join("");
|
||||
// combine hash values of main hash variables and return
|
||||
const HH = [H0, H1, H2, H3, H4]
|
||||
.map(e => e.toString(16))
|
||||
.map(e => pad(e, 8))
|
||||
.join('')
|
||||
|
||||
return HH;
|
||||
return HH
|
||||
}
|
||||
|
||||
console.log(SHA1("A Test"));
|
||||
console.log(SHA1("A Test"));
|
||||
|
||||
//export SHA1 function
|
||||
module.exports = SHA1;
|
||||
console.log(SHA1('A Test'))
|
||||
console.log(SHA1('A Test'))
|
||||
|
||||
// export SHA1 function
|
||||
module.exports = SHA1
|
||||
|
224
Hashes/SHA256.js
224
Hashes/SHA256.js
@ -1,23 +1,23 @@
|
||||
//================================================================
|
||||
//= ===============================================================
|
||||
// SHA256.js
|
||||
//
|
||||
// Module that replicates the SHA-256 Cryptographic Hash
|
||||
// Module that replicates the SHA-256 Cryptographic Hash
|
||||
// function in Javascript.
|
||||
//================================================================
|
||||
//= ===============================================================
|
||||
|
||||
//main variables
|
||||
const CHAR_SIZE = 8;
|
||||
// main variables
|
||||
const CHAR_SIZE = 8
|
||||
|
||||
const K = [
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
||||
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
||||
];
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
||||
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
||||
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
||||
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
||||
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
|
||||
@ -29,12 +29,12 @@ const K = [
|
||||
* @example
|
||||
* pad("10011", 8); // "00010011"
|
||||
*/
|
||||
function pad(str, bits) {
|
||||
let res = str;
|
||||
while (res.length % bits !== 0) {
|
||||
res = "0" + res;
|
||||
}
|
||||
return res;
|
||||
function pad (str, bits) {
|
||||
let res = str
|
||||
while (res.length % bits !== 0) {
|
||||
res = '0' + res
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
/**
|
||||
@ -47,12 +47,12 @@ function pad(str, bits) {
|
||||
* @example
|
||||
* chunkify("this is a test", 2); // ["th", "is", " i", "s ", "a ", "te", "st"]
|
||||
*/
|
||||
function chunkify(str, size) {
|
||||
let chunks = [];
|
||||
for (let i = 0; i < str.length; i += size) {
|
||||
chunks.push(str.slice(i, i + size));
|
||||
}
|
||||
return chunks;
|
||||
function chunkify (str, size) {
|
||||
const chunks = []
|
||||
for (let i = 0; i < str.length; i += size) {
|
||||
chunks.push(str.slice(i, i + size))
|
||||
}
|
||||
return chunks
|
||||
}
|
||||
|
||||
/**
|
||||
@ -65,8 +65,8 @@ function chunkify(str, size) {
|
||||
* @example
|
||||
* rotateLeft("1011", 3); // "1101"
|
||||
*/
|
||||
function rotateRight(bits, turns) {
|
||||
return bits.substr(bits.length - turns) + bits.substr(0, bits.length - turns);
|
||||
function rotateRight (bits, turns) {
|
||||
return bits.substr(bits.length - turns) + bits.substr(0, bits.length - turns)
|
||||
}
|
||||
|
||||
/**
|
||||
@ -75,27 +75,27 @@ function rotateRight(bits, turns) {
|
||||
* @param {string} message - message to pre-process
|
||||
* @return {string} - processed message
|
||||
*/
|
||||
function preProcess(message) {
|
||||
//covert message to binary representation padded to
|
||||
//8 bits, and add 1
|
||||
let m = message.split("")
|
||||
.map(e => e.charCodeAt(0))
|
||||
.map(e => e.toString(2))
|
||||
.map(e => pad(e, 8))
|
||||
.join("") + "1";
|
||||
function preProcess (message) {
|
||||
// covert message to binary representation padded to
|
||||
// 8 bits, and add 1
|
||||
let m = message.split('')
|
||||
.map(e => e.charCodeAt(0))
|
||||
.map(e => e.toString(2))
|
||||
.map(e => pad(e, 8))
|
||||
.join('') + '1'
|
||||
|
||||
//extend message by adding empty bits (0)
|
||||
while (m.length % 512 !== 448) {
|
||||
m += "0";
|
||||
}
|
||||
// extend message by adding empty bits (0)
|
||||
while (m.length % 512 !== 448) {
|
||||
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;
|
||||
// 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
|
||||
|
||||
return m + ml;
|
||||
return m + ml
|
||||
}
|
||||
|
||||
/**
|
||||
@ -104,85 +104,85 @@ function preProcess(message) {
|
||||
* @param {string} message - message to hash
|
||||
* @return {string} - message digest (hash value)
|
||||
*/
|
||||
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;
|
||||
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
|
||||
|
||||
//pre-process message and split into 512 bit chunks
|
||||
let bits = preProcess(message);
|
||||
let chunks = chunkify(bits, 512);
|
||||
|
||||
chunks.forEach(function(chunk, i) {
|
||||
//break each chunk into 16 32-bit words
|
||||
let words = chunkify(chunk, 32);
|
||||
// pre-process message and split into 512 bit chunks
|
||||
const bits = preProcess(message)
|
||||
const chunks = chunkify(bits, 512)
|
||||
|
||||
//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);
|
||||
}
|
||||
chunks.forEach(function (chunk, i) {
|
||||
// break each chunk into 16 32-bit words
|
||||
const words = chunkify(chunk, 32)
|
||||
|
||||
//initialize variables for this chunk
|
||||
let [a, b, c, d, e, f, g, h] = [H0, H1, H2, H3, H4, H5, H6, H7];
|
||||
// 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)
|
||||
}
|
||||
|
||||
for (let i = 0; i < 64; i++) {
|
||||
// initialize variables for this chunk
|
||||
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;
|
||||
});
|
||||
// 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
|
||||
})
|
||||
|
||||
//combine hash values of main hash variables and return
|
||||
let HH = [H0, H1, H2, H3, H4, H5, H6, H7]
|
||||
.map(e => e.toString(16))
|
||||
.map(e => pad(e, 8))
|
||||
.join("");
|
||||
// combine hash values of main hash variables and return
|
||||
const HH = [H0, H1, H2, H3, H4, H5, H6, H7]
|
||||
.map(e => e.toString(16))
|
||||
.map(e => pad(e, 8))
|
||||
.join('')
|
||||
|
||||
return HH;
|
||||
return HH
|
||||
}
|
||||
|
||||
//export SHA256 function
|
||||
module.exports = SHA256;
|
||||
// export SHA256 function
|
||||
module.exports = SHA256
|
||||
|
@ -1,27 +1,26 @@
|
||||
/*Binary Search-Search a sorted array by repeatedly dividing the search interval
|
||||
/* Binary Search-Search a sorted array by repeatedly dividing the search interval
|
||||
* in half. Begin with an interval covering the whole array. If the value of the
|
||||
* search key is less than the item in the middle of the interval, narrow the interval
|
||||
* to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the
|
||||
* value is found or the interval is empty.
|
||||
*/
|
||||
|
||||
function binarySearch(arr, i) {
|
||||
var mid = Math.floor(arr.length / 2);
|
||||
if (arr[mid] === i) {
|
||||
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);
|
||||
} else if (arr[mid] > i && arr.length > 1) {
|
||||
binarySearch(arr.splice(0, mid), i);
|
||||
} else {
|
||||
console.log("not found", i);
|
||||
return -1;
|
||||
}
|
||||
|
||||
function binarySearch (arr, i) {
|
||||
var mid = Math.floor(arr.length / 2)
|
||||
if (arr[mid] === i) {
|
||||
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)
|
||||
} else if (arr[mid] > i && arr.length > 1) {
|
||||
binarySearch(arr.splice(0, mid), i)
|
||||
} else {
|
||||
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)
|
||||
|
@ -1,35 +1,35 @@
|
||||
/* The Jump Search algorithm allows to combine a linear search with a speed optimization.
|
||||
* This means that instead of going 1 by 1, we will increase the step of √n and increase that
|
||||
* This means that instead of going 1 by 1, we will increase the step of √n and increase that
|
||||
* step of √n which make the step getting bigger and bigger.
|
||||
* The asymptotic analysis of Jump Search is o(√n). Like the binary search, it needs to be sorted.
|
||||
* The advantage against binary search is that Jump Search traversed back only once.
|
||||
*/
|
||||
|
||||
const jumpSearch = (arr, value) => {
|
||||
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;
|
||||
if (lowerBound >= length) {
|
||||
return -1;
|
||||
}
|
||||
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
|
||||
if (lowerBound >= length) {
|
||||
return -1
|
||||
}
|
||||
}
|
||||
|
||||
const upperBound = Math.min(step, length);
|
||||
while (arr[lowerBound] < value) {
|
||||
lowerBound++;
|
||||
if (lowerBound === upperBound) {
|
||||
return -1;
|
||||
}
|
||||
const upperBound = Math.min(step, length)
|
||||
while (arr[lowerBound] < value) {
|
||||
lowerBound++
|
||||
if (lowerBound === upperBound) {
|
||||
return -1
|
||||
}
|
||||
if (arr[lowerBound] === value) {
|
||||
return lowerBound;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
if (arr[lowerBound] === value) {
|
||||
return lowerBound
|
||||
}
|
||||
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);
|
||||
const arr = [0, 0, 4, 7, 10, 23, 34, 40, 55, 68, 77, 90]
|
||||
jumpSearch(arr, 4)
|
||||
jumpSearch(arr, 34)
|
||||
jumpSearch(arr, 77)
|
||||
|
@ -4,24 +4,24 @@
|
||||
* for the target value until a match is found or until all the elements
|
||||
* have been searched.
|
||||
*/
|
||||
function SearchArray(searchNum, ar) {
|
||||
var position = Search(ar, searchNum);
|
||||
if (position != -1) {
|
||||
console.log("The element was found at " + (position + 1));
|
||||
} else {
|
||||
console.log("The element not found");
|
||||
}
|
||||
function SearchArray (searchNum, ar) {
|
||||
var position = Search(ar, searchNum)
|
||||
if (position != -1) {
|
||||
console.log('The element was found at ' + (position + 1))
|
||||
} else {
|
||||
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;
|
||||
function Search (theArray, key) {
|
||||
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)
|
||||
|
@ -1,59 +1,58 @@
|
||||
function TopologicalSorter() {
|
||||
var graph = {},
|
||||
isVisitedNode,
|
||||
finishTimeCount,
|
||||
finishingTimeList,
|
||||
nextNode;
|
||||
function TopologicalSorter () {
|
||||
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);
|
||||
}
|
||||
|
||||
this.sortAndGetOrderedItems = function () {
|
||||
isVisitedNode = Object.create(null);
|
||||
finishTimeCount = 0;
|
||||
finishingTimeList = [];
|
||||
this.addOrder = function (nodeA, nodeB) {
|
||||
nodeA = String(nodeA)
|
||||
nodeB = String(nodeB)
|
||||
graph[nodeA] = graph[nodeA] || []
|
||||
graph[nodeA].push(nodeB)
|
||||
}
|
||||
|
||||
for (var node in graph) {
|
||||
if (graph.hasOwnProperty(node) && !isVisitedNode[node]) {
|
||||
dfsTraverse(node);
|
||||
}
|
||||
}
|
||||
this.sortAndGetOrderedItems = function () {
|
||||
isVisitedNode = Object.create(null)
|
||||
finishTimeCount = 0
|
||||
finishingTimeList = []
|
||||
|
||||
finishingTimeList.sort(function (item1, item2) {
|
||||
return item1.finishTime > item2.finishTime ? -1 : 1;
|
||||
});
|
||||
|
||||
return finishingTimeList.map(function (value) { return value.node })
|
||||
for (var node in graph) {
|
||||
if (graph.hasOwnProperty(node) && !isVisitedNode[node]) {
|
||||
dfsTraverse(node)
|
||||
}
|
||||
}
|
||||
|
||||
function dfsTraverse(node) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
finishingTimeList.sort(function (item1, item2) {
|
||||
return item1.finishTime > item2.finishTime ? -1 : 1
|
||||
})
|
||||
|
||||
finishingTimeList.push({
|
||||
node: node,
|
||||
finishTime: ++finishTimeCount
|
||||
});
|
||||
return finishingTimeList.map(function (value) { return value.node })
|
||||
}
|
||||
|
||||
function dfsTraverse (node) {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
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())
|
||||
|
@ -3,53 +3,49 @@
|
||||
* sorted in ascending order.
|
||||
*/
|
||||
Array.prototype.isSorted = function () {
|
||||
const length = this.length
|
||||
|
||||
let length = this.length;
|
||||
if (length < 2) {
|
||||
return true
|
||||
}
|
||||
|
||||
if (length < 2) {
|
||||
return true;
|
||||
for (let i = 0; i < length - 1; i++) {
|
||||
if (this[i] > this[i + 1]) {
|
||||
return false
|
||||
}
|
||||
|
||||
for (let i = 0; i < length - 1; i++) {
|
||||
if (this[i] > this[i + 1]) {
|
||||
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;
|
||||
}
|
||||
|
||||
};
|
||||
for (let i = this.length - 1; i; i--) {
|
||||
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
|
||||
* rearranges the array until it is sorted.
|
||||
* For more information see: https://en.wikipedia.org/wiki/Bogosort
|
||||
*/
|
||||
function bogoSort(items) {
|
||||
|
||||
while (!items.isSorted()) {
|
||||
items.shuffle()
|
||||
}
|
||||
return items;
|
||||
function bogoSort (items) {
|
||||
while (!items.isSorted()) {
|
||||
items.shuffle()
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
//Implementation of bogoSort
|
||||
// Implementation of bogoSort
|
||||
|
||||
var ar = [5, 6, 7, 8, 1, 2, 12, 14];
|
||||
//Array before Sort
|
||||
console.log(ar);
|
||||
bogoSort(ar);
|
||||
//Array after sort
|
||||
console.log(ar);
|
||||
var ar = [5, 6, 7, 8, 1, 2, 12, 14]
|
||||
// Array before Sort
|
||||
console.log(ar)
|
||||
bogoSort(ar)
|
||||
// Array after sort
|
||||
console.log(ar)
|
||||
|
@ -1,4 +1,4 @@
|
||||
/*
|
||||
/*
|
||||
Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works by distributing the
|
||||
elements of an array into a number of buckets. Each bucket is then sorted individually, either using
|
||||
a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a
|
||||
@ -11,52 +11,50 @@ Time Complexity of Solution:
|
||||
Best Case O(n); Average Case O(n); Worst Case O(n)
|
||||
|
||||
*/
|
||||
function bucketSort(list, size){
|
||||
|
||||
if(undefined === size){
|
||||
size = 5;
|
||||
function bucketSort (list, size) {
|
||||
if (undefined === size) {
|
||||
size = 5
|
||||
}
|
||||
if (list.length === 0) {
|
||||
return list
|
||||
}
|
||||
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]
|
||||
} else if (list[iList] > max) {
|
||||
max = list[iList]
|
||||
}
|
||||
if(list.length === 0){
|
||||
return list;
|
||||
}
|
||||
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];
|
||||
} else if(list[iList] > max){
|
||||
max = list[iList];
|
||||
}
|
||||
}
|
||||
// how many buckets we need
|
||||
let count = Math.floor((max - min) / size) + 1;
|
||||
}
|
||||
// how many buckets we need
|
||||
const count = Math.floor((max - min) / size) + 1
|
||||
|
||||
// create buckets
|
||||
let buckets = [];
|
||||
for(let iCount = 0; iCount < count; iCount++){
|
||||
buckets.push([]);
|
||||
}
|
||||
// create buckets
|
||||
const buckets = []
|
||||
for (let iCount = 0; iCount < count; iCount++) {
|
||||
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]);
|
||||
// bucket fill
|
||||
for (let iBucket = 0; iBucket < list.length; iBucket++) {
|
||||
const key = Math.floor((list[iBucket] - min) / size)
|
||||
buckets[key].push(list[iBucket])
|
||||
}
|
||||
const sorted = []
|
||||
// now sort every bucket and merge it to the sorted list
|
||||
for (let iBucket = 0; iBucket < buckets.length; iBucket++) {
|
||||
const arr = buckets[iBucket].sort()
|
||||
for (let iSorted = 0; iSorted < arr.length; iSorted++) {
|
||||
sorted.push(arr[iSorted])
|
||||
}
|
||||
let 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();
|
||||
for(let iSorted = 0; iSorted < arr.length; iSorted++){
|
||||
sorted.push(arr[iSorted]);
|
||||
}
|
||||
}
|
||||
return sorted;
|
||||
}
|
||||
return sorted
|
||||
}
|
||||
let arrOrignal = [5, 6, 7, 8, 1, 2, 12, 14];
|
||||
//Array before Sort
|
||||
console.log(arrOrignal);
|
||||
arrSorted = bucketSort(arrOrignal);
|
||||
//Array after sort
|
||||
console.log(arrSorted);
|
||||
const arrOrignal = [5, 6, 7, 8, 1, 2, 12, 14]
|
||||
// Array before Sort
|
||||
console.log(arrOrignal)
|
||||
arrSorted = bucketSort(arrOrignal)
|
||||
// Array after sort
|
||||
console.log(arrSorted)
|
||||
|
@ -4,42 +4,41 @@
|
||||
* more information: https://en.wikipedia.org/wiki/Bubble_sort
|
||||
*
|
||||
*/
|
||||
function cocktailShakerSort(items) {
|
||||
function cocktailShakerSort (items) {
|
||||
for (let i = items.length - 1; i > 0; i--) {
|
||||
let swapped = false
|
||||
let temp, j
|
||||
|
||||
for (let i = items.length - 1; i > 0; i--) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
//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;
|
||||
}
|
||||
}
|
||||
if (!swapped) {
|
||||
return;
|
||||
}
|
||||
// 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
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
}
|
||||
if (!swapped) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Implementation of cocktailShakerSort
|
||||
// Implementation of cocktailShakerSort
|
||||
|
||||
var ar = [5, 6, 7, 8, 1, 2, 12, 14];
|
||||
//Array before Sort
|
||||
console.log(ar);
|
||||
cocktailShakerSort(ar);
|
||||
//Array after sort
|
||||
console.log(ar);
|
||||
var ar = [5, 6, 7, 8, 1, 2, 12, 14]
|
||||
// Array before Sort
|
||||
console.log(ar)
|
||||
cocktailShakerSort(ar)
|
||||
// Array after sort
|
||||
console.log(ar)
|
||||
|
@ -1,53 +1,50 @@
|
||||
/*
|
||||
Wikipedia says: Comb sort improves on bubble sort.
|
||||
/*
|
||||
Wikipedia says: Comb sort improves on bubble sort.
|
||||
|
||||
The basic idea is to eliminate turtles, or small values
|
||||
near the end of the list, since in a bubble sort these slow the sorting
|
||||
down tremendously. Rabbits, large values around the beginning of the list,
|
||||
The basic idea is to eliminate turtles, or small values
|
||||
near the end of the list, since in a bubble sort these slow the sorting
|
||||
down tremendously. Rabbits, large values around the beginning of the list,
|
||||
do not pose a problem in bubble sort.
|
||||
|
||||
In bubble sort, when any two elements are compared, they always have a
|
||||
gap (distance from each other) of 1. The basic idea of comb sort is
|
||||
that the gap can be much more than 1. The inner loop of bubble sort,
|
||||
which does the actual swap, is modified such that gap between swapped
|
||||
elements goes down (for each iteration of outer loop) in steps of
|
||||
In bubble sort, when any two elements are compared, they always have a
|
||||
gap (distance from each other) of 1. The basic idea of comb sort is
|
||||
that the gap can be much more than 1. The inner loop of bubble sort,
|
||||
which does the actual swap, is modified such that gap between swapped
|
||||
elements goes down (for each iteration of outer loop) in steps of
|
||||
a "shrink factor" k: [ n/k, n/k2, n/k3, ..., 1 ].
|
||||
|
||||
*/
|
||||
function combSort(list) {
|
||||
|
||||
|
||||
if (list.length === 0) {
|
||||
return list;
|
||||
}
|
||||
let 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);
|
||||
|
||||
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;
|
||||
}
|
||||
i += 1
|
||||
}
|
||||
}
|
||||
function combSort (list) {
|
||||
if (list.length === 0) {
|
||||
return list
|
||||
}
|
||||
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)
|
||||
|
||||
isSwapped = false
|
||||
i = 0
|
||||
|
||||
while (gap + i < list.length) {
|
||||
if (list[i] > list[i + gap]) {
|
||||
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];
|
||||
//Array before Sort
|
||||
console.log(arrOrignal);
|
||||
arrSorted = combSort(arrOrignal);
|
||||
//Array after sort
|
||||
console.log(arrSorted);
|
||||
const arrOrignal = [5, 6, 7, 8, 1, 2, 12, 14]
|
||||
// Array before Sort
|
||||
console.log(arrOrignal)
|
||||
arrSorted = combSort(arrOrignal)
|
||||
// Array after sort
|
||||
console.log(arrSorted)
|
||||
|
@ -5,33 +5,33 @@
|
||||
* counting sort visualization: https://www.cs.usfca.edu/~galles/visualization/CountingSort.html
|
||||
*/
|
||||
|
||||
function countingSort(arr, min, max) {
|
||||
let i;
|
||||
let z = 0;
|
||||
const count = [];
|
||||
|
||||
function countingSort (arr, min, max) {
|
||||
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))
|
||||
|
@ -1,62 +1,58 @@
|
||||
/*
|
||||
Wikipedia says: Cycle sort is an in-place, unstable sorting algorithm,
|
||||
a comparison sort that is theoretically optimal in terms of the total
|
||||
number of writes to the original array, unlike any other in-place sorting
|
||||
algorithm. It is based on the idea that the permutation to be sorted can
|
||||
/*
|
||||
Wikipedia says: Cycle sort is an in-place, unstable sorting algorithm,
|
||||
a comparison sort that is theoretically optimal in terms of the total
|
||||
number of writes to the original array, unlike any other in-place sorting
|
||||
algorithm. It is based on the idea that the permutation to be sorted can
|
||||
be factored into cycles, which can individually be rotated to give a sorted result.
|
||||
*/
|
||||
function cycleSort(list) {
|
||||
function cycleSort (list) {
|
||||
let writes = 0
|
||||
for (let cycleStart = 0; cycleStart < list.length; cycleStart++) {
|
||||
let value = list[cycleStart]
|
||||
let position = cycleStart
|
||||
|
||||
let writes = 0;
|
||||
for (let cycleStart = 0; cycleStart < list.length; cycleStart++) {
|
||||
|
||||
let value = list[cycleStart];
|
||||
let position = cycleStart;
|
||||
|
||||
// search position
|
||||
for (let i = cycleStart+1; i < list.length; i++) {
|
||||
|
||||
if (list[i] < value) {
|
||||
position++;
|
||||
}
|
||||
}
|
||||
// if its the same continue
|
||||
if (position == cycleStart) {
|
||||
continue;
|
||||
}
|
||||
|
||||
while (value == list[position]) {
|
||||
position++;
|
||||
}
|
||||
|
||||
let oldValue = list[position];
|
||||
list[position] = value;
|
||||
value = oldValue;
|
||||
writes++;
|
||||
|
||||
// rotate the rest
|
||||
while (position != cycleStart) {
|
||||
position = cycleStart;
|
||||
for (let i = cycleStart +1; i < list.length; i++) {
|
||||
|
||||
if (list[i] < value) {
|
||||
position++;
|
||||
}
|
||||
}
|
||||
while (value == list[position]) {
|
||||
position++;
|
||||
}
|
||||
let oldValueCycle = list[position];
|
||||
list[position] = value;
|
||||
value = oldValueCycle;
|
||||
writes++;
|
||||
}
|
||||
// search position
|
||||
for (let i = cycleStart + 1; i < list.length; i++) {
|
||||
if (list[i] < value) {
|
||||
position++
|
||||
}
|
||||
}
|
||||
return writes;
|
||||
// if its the same continue
|
||||
if (position == cycleStart) {
|
||||
continue
|
||||
}
|
||||
|
||||
while (value == list[position]) {
|
||||
position++
|
||||
}
|
||||
|
||||
const oldValue = list[position]
|
||||
list[position] = value
|
||||
value = oldValue
|
||||
writes++
|
||||
|
||||
// rotate the rest
|
||||
while (position != cycleStart) {
|
||||
position = cycleStart
|
||||
for (let i = cycleStart + 1; i < list.length; i++) {
|
||||
if (list[i] < value) {
|
||||
position++
|
||||
}
|
||||
}
|
||||
while (value == list[position]) {
|
||||
position++
|
||||
}
|
||||
const oldValueCycle = list[position]
|
||||
list[position] = value
|
||||
value = oldValueCycle
|
||||
writes++
|
||||
}
|
||||
}
|
||||
return writes
|
||||
}
|
||||
let arrOrignal = [5, 6, 7, 8, 1, 2,12, 14];
|
||||
//Array before Sort
|
||||
console.log(arrOrignal);
|
||||
cycleSort(arrOrignal);
|
||||
//Array after sort
|
||||
console.log(arrOrignal);
|
||||
const arrOrignal = [5, 6, 7, 8, 1, 2, 12, 14]
|
||||
// Array before Sort
|
||||
console.log(arrOrignal)
|
||||
cycleSort(arrOrignal)
|
||||
// Array after sort
|
||||
console.log(arrOrignal)
|
||||
|
@ -4,82 +4,82 @@
|
||||
* more information: https://en.wikipedia.org/wiki/Flashsort
|
||||
*/
|
||||
|
||||
function flashSort(arr) {
|
||||
let max = 0, min = arr[0];
|
||||
let n = arr.length;
|
||||
let m = ~~(0.45 * n);
|
||||
let l = new Array(m);
|
||||
|
||||
function flashSort (arr) {
|
||||
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))
|
||||
|
@ -3,34 +3,31 @@
|
||||
* more information: https://en.wikipedia.org/wiki/Gnome_sort
|
||||
*
|
||||
*/
|
||||
function gnomeSort(items) {
|
||||
function gnomeSort (items) {
|
||||
if (items.length <= 1) {
|
||||
return
|
||||
}
|
||||
|
||||
if (items.length <= 1) {
|
||||
let i = 1
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
let i = 1;
|
||||
|
||||
while (i < items.length) {
|
||||
|
||||
if (items[i - 1] <= items[i]) {
|
||||
i++;
|
||||
} else {
|
||||
let temp = items[i];
|
||||
items[i] = items[i - 1];
|
||||
items[i - 1] = temp;
|
||||
|
||||
i = Math.max(1, i - 1);
|
||||
}
|
||||
while (i < items.length) {
|
||||
if (items[i - 1] <= items[i]) {
|
||||
i++
|
||||
} else {
|
||||
const temp = items[i]
|
||||
items[i] = items[i - 1]
|
||||
items[i - 1] = temp
|
||||
|
||||
i = Math.max(1, i - 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Implementation of gnomeSort
|
||||
// Implementation of gnomeSort
|
||||
|
||||
var ar = [5, 6, 7, 8, 1, 2, 12, 14];
|
||||
//Array before Sort
|
||||
console.log(ar);
|
||||
gnomeSort(ar);
|
||||
//Array after sort
|
||||
console.log(ar);
|
||||
var ar = [5, 6, 7, 8, 1, 2, 12, 14]
|
||||
// Array before Sort
|
||||
console.log(ar)
|
||||
gnomeSort(ar)
|
||||
// Array after sort
|
||||
console.log(ar)
|
||||
|
@ -6,54 +6,52 @@
|
||||
* 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
|
||||
* utilizing the heap property.
|
||||
* For more information see: https://en.wikipedia.org/wiki/Heapsort
|
||||
*/
|
||||
function heapSort(items) {
|
||||
|
||||
let length = items.length;
|
||||
function heapSort (items) {
|
||||
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);
|
||||
for (let j = length - 1; j > 0; j--) {
|
||||
const tmp = items[0]
|
||||
items[0] = items[j]
|
||||
items[j] = tmp
|
||||
items.heapify(0, j)
|
||||
}
|
||||
return items;
|
||||
return items
|
||||
}
|
||||
|
||||
//Implementation of heapSort
|
||||
// Implementation of heapSort
|
||||
|
||||
var ar = [5, 6, 7, 8, 1, 2, 12, 14];
|
||||
//Array before Sort
|
||||
console.log(ar);
|
||||
heapSort(ar);
|
||||
//Array after sort
|
||||
console.log(ar);
|
||||
var ar = [5, 6, 7, 8, 1, 2, 12, 14]
|
||||
// Array before Sort
|
||||
console.log(ar)
|
||||
heapSort(ar)
|
||||
// Array after sort
|
||||
console.log(ar)
|
||||
|
@ -1,24 +1,24 @@
|
||||
/*In insertion sort, we divide the initial unsorted array into two parts;
|
||||
/* In insertion sort, we divide the initial unsorted array into two parts;
|
||||
* sorted part and unsorted part. Initially the sorted part just has one
|
||||
* element (Array of only 1 element is a sorted array). We then pick up
|
||||
* element one by one from unsorted part; insert into the sorted part at
|
||||
* the correct position and expand sorted part one element at a time.
|
||||
*/
|
||||
function insertionSort(unsortedList) {
|
||||
var len = unsortedList.length;
|
||||
function insertionSort (unsortedList) {
|
||||
var len = unsortedList.length
|
||||
for (var i = 1; i < len; i++) {
|
||||
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*/
|
||||
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];
|
||||
// Shift the number
|
||||
unsortedList[j + 1] = unsortedList[j]
|
||||
}
|
||||
//Insert the copied number at the correct position
|
||||
//in sorted part.
|
||||
unsortedList[j + 1] = tmp;
|
||||
// Insert the copied number at the correct position
|
||||
// in sorted part.
|
||||
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)
|
||||
|
@ -1,8 +1,8 @@
|
||||
/**
|
||||
* Merge Sort is an algorithm where the main list is divided down into two half
|
||||
* sized lists, which then have merge sort called on these two smaller lists
|
||||
* sized lists, which then have merge sort called on these two smaller lists
|
||||
* recursively until there is only a sorted list of one.
|
||||
*
|
||||
*
|
||||
* On the way up the recursive calls, the lists will be merged together inserting
|
||||
* the smaller value first, creating a larger sorted list.
|
||||
*/
|
||||
@ -13,17 +13,17 @@
|
||||
* @param {Array} list2 - sublist to break down
|
||||
* @return {Array} merged list
|
||||
*/
|
||||
function merge(list1, list2) {
|
||||
var results = [];
|
||||
function merge (list1, list2) {
|
||||
var results = []
|
||||
|
||||
while(list1.length && list2.length) {
|
||||
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)
|
||||
}
|
||||
|
||||
/**
|
||||
@ -31,19 +31,18 @@ function merge(list1, list2) {
|
||||
* @param {Array} list - list to be sorted
|
||||
* @return {Array} sorted list
|
||||
*/
|
||||
function mergeSort(list) {
|
||||
if (list.length < 2) return list;
|
||||
function mergeSort (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)
|
||||
|
@ -2,37 +2,36 @@
|
||||
* Quick sort is a comparison sorting algorithm that uses a divide and conquer strategy.
|
||||
* For more information see here: https://en.wikipedia.org/wiki/Quicksort
|
||||
*/
|
||||
function quickSort(items) {
|
||||
|
||||
var length = items.length;
|
||||
function quickSort (items) {
|
||||
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));
|
||||
|
||||
return sorted;
|
||||
var sorted = quickSort(LESSER)
|
||||
sorted.push(PIVOT)
|
||||
sorted = sorted.concat(quickSort(GREATER))
|
||||
|
||||
return sorted
|
||||
}
|
||||
|
||||
//Implementation of quick sort
|
||||
// Implementation of quick sort
|
||||
|
||||
var ar = [0, 5, 3, 2, 2];
|
||||
//Array before Sort
|
||||
console.log(ar);
|
||||
ar = quickSort(ar);
|
||||
//Array after sort
|
||||
console.log(ar);
|
||||
var ar = [0, 5, 3, 2, 2]
|
||||
// Array before Sort
|
||||
console.log(ar)
|
||||
ar = quickSort(ar)
|
||||
// Array after sort
|
||||
console.log(ar)
|
||||
|
@ -4,50 +4,49 @@
|
||||
* significant position.
|
||||
* 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
|
||||
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
|
||||
// Implementation of radixSort
|
||||
|
||||
var ar = [5, 6, 7, 8, 1, 2, 12, 14];
|
||||
//Array before Sort
|
||||
console.log(ar);
|
||||
radixSort(ar);
|
||||
//Array after sort
|
||||
console.log(ar);
|
||||
var ar = [5, 6, 7, 8, 1, 2, 12, 14]
|
||||
// Array before Sort
|
||||
console.log(ar)
|
||||
radixSort(ar)
|
||||
// Array after sort
|
||||
console.log(ar)
|
||||
|
@ -1,4 +1,4 @@
|
||||
/*The selection sort algorithm sorts an array by repeatedly finding the minimum element
|
||||
/* The selection sort algorithm sorts an array by repeatedly finding the minimum element
|
||||
*(considering ascending order) from unsorted part and putting it at the beginning. The
|
||||
*algorithm maintains two subarrays in a given array.
|
||||
*1) The subarray which is already sorted.
|
||||
@ -7,31 +7,31 @@
|
||||
*In every iteration of selection sort, the minimum element (considering ascending order)
|
||||
*from the unsorted subarray is picked and moved to the sorted subarray.
|
||||
*/
|
||||
function selectionSort(items) {
|
||||
var length = items.length;
|
||||
function selectionSort (items) {
|
||||
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
|
||||
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
|
||||
// Number of passes
|
||||
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
|
||||
}
|
||||
}
|
||||
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;
|
||||
// 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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//Implementation of Selection Sort
|
||||
// Implementation of Selection Sort
|
||||
|
||||
var ar = [5, 6, 7, 8, 1, 2, 12, 14];
|
||||
//Array before Sort
|
||||
console.log(ar);
|
||||
selectionSort(ar);
|
||||
//Array after sort
|
||||
console.log(ar);
|
||||
var ar = [5, 6, 7, 8, 1, 2, 12, 14]
|
||||
// Array before Sort
|
||||
console.log(ar)
|
||||
selectionSort(ar)
|
||||
// Array after sort
|
||||
console.log(ar)
|
||||
|
@ -3,38 +3,34 @@
|
||||
* more information: https://en.wikipedia.org/wiki/Shellsort
|
||||
*
|
||||
*/
|
||||
function shellSort(items) {
|
||||
function shellSort (items) {
|
||||
var interval = 1
|
||||
|
||||
var interval = 1;
|
||||
while (interval < items.length / 3) {
|
||||
interval = interval * 3 + 1
|
||||
}
|
||||
|
||||
while (interval < items.length / 3) {
|
||||
while (interval > 0) {
|
||||
for (var outer = interval; outer < items.length; outer++) {
|
||||
var value = items[outer]
|
||||
var inner = outer
|
||||
|
||||
interval = interval * 3 + 1;
|
||||
while (inner > interval - 1 && items[inner - interval] >= value) {
|
||||
items[inner] = items[inner - interval]
|
||||
inner = inner - interval
|
||||
}
|
||||
items[inner] = value
|
||||
}
|
||||
|
||||
while (interval > 0) {
|
||||
|
||||
for (var outer = interval; outer < items.length; 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] = value;
|
||||
}
|
||||
interval = (interval - 1) / 3;
|
||||
}
|
||||
return items;
|
||||
interval = (interval - 1) / 3
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
//Implementation of shellSort
|
||||
// Implementation of shellSort
|
||||
|
||||
var ar = [5, 6, 7, 8, 1, 2, 12, 14];
|
||||
//Array before Sort
|
||||
console.log(ar);
|
||||
shellSort(ar);
|
||||
//Array after sort
|
||||
console.log(ar);
|
||||
var ar = [5, 6, 7, 8, 1, 2, 12, 14]
|
||||
// Array before Sort
|
||||
console.log(ar)
|
||||
shellSort(ar)
|
||||
// Array after sort
|
||||
console.log(ar)
|
||||
|
@ -5,22 +5,22 @@
|
||||
*/
|
||||
|
||||
Array.prototype.wiggleSort = function () {
|
||||
for (let i = 0; i < this.length; ++i) {
|
||||
const shouldNotBeLessThan = i % 2;
|
||||
const isLessThan = this[i] < this[i + 1];
|
||||
if (shouldNotBeLessThan && isLessThan) {
|
||||
[this[i], this[i + 1]] = [this[i + 1], this[i]];
|
||||
}
|
||||
for (let i = 0; i < this.length; ++i) {
|
||||
const shouldNotBeLessThan = i % 2
|
||||
const isLessThan = this[i] < this[i + 1]
|
||||
if (shouldNotBeLessThan && isLessThan) {
|
||||
[this[i], this[i + 1]] = [this[i + 1], this[i]]
|
||||
}
|
||||
return this;
|
||||
};
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
//Implementation of wiggle sort
|
||||
// Implementation of wiggle sort
|
||||
|
||||
var arr = [3, 5, 2, 1, 6, 4];
|
||||
//Array before Wiggle Sort
|
||||
console.log(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]
|
||||
|
||||
arr.wiggleSort()
|
||||
//Array after wiggle sort
|
||||
console.log(arr); // [ 3, 5, 2, 6, 1, 4 ]
|
||||
// Array after wiggle sort
|
||||
console.log(arr) // [ 3, 5, 2, 6, 1, 4 ]
|
||||
|
@ -1,325 +1,307 @@
|
||||
/*
|
||||
author: Christian Bender
|
||||
license: MIT-license
|
||||
|
||||
|
||||
The namespace LinearAlgebra contains useful classes and functions for dealing with
|
||||
linear algebra under JavaScript.
|
||||
*/
|
||||
var LinearAlgebra;
|
||||
(function (LinearAlgebra) {
|
||||
/*
|
||||
/*
|
||||
class: Vector
|
||||
This class represents a vector of arbitrary size and operations on it.
|
||||
*/
|
||||
var Vector = /** @class */ (function () {
|
||||
// constructor
|
||||
function Vector(N, comps) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (N == comps.length) {
|
||||
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;
|
||||
};
|
||||
// computes the eulidean length.
|
||||
Vector.prototype.eulideanLength = function () {
|
||||
var sum = 0;
|
||||
for (var i = 0; i < this.components.length; i++) {
|
||||
sum += this.components[i] * this.components[i];
|
||||
}
|
||||
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];
|
||||
};
|
||||
// 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;
|
||||
}
|
||||
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);
|
||||
for (var i = 0; i < SIZE; i++) {
|
||||
ans.changeComponent(i, (this.components[i] + other.component(i)));
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
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);
|
||||
for (var i = 0; i < SIZE; i++) {
|
||||
ans.changeComponent(i, (this.components[i] - other.component(i)));
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
else {
|
||||
throw "add: vector must have same size!";
|
||||
}
|
||||
};
|
||||
// dot-product
|
||||
Vector.prototype.dot = function (other) {
|
||||
var sum = 0;
|
||||
if (other.size() == this.size()) {
|
||||
var SIZE = other.size();
|
||||
for (var i = 0; i < SIZE; i++) {
|
||||
sum += this.components[i] * other.component(i);
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
else {
|
||||
throw "dot: vectors must have same size!";
|
||||
}
|
||||
};
|
||||
// scalar multiplication
|
||||
Vector.prototype.scalar = function (s) {
|
||||
var SIZE = this.size();
|
||||
var ans = new Vector(SIZE);
|
||||
for (var i = 0; i < SIZE; i++) {
|
||||
ans.changeComponent(i, (this.components[i] * s));
|
||||
}
|
||||
return ans;
|
||||
};
|
||||
// returns a string representation of this vector.
|
||||
Vector.prototype.toString = function () {
|
||||
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] + ")";
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw "createUnitBasis: index out of bounds";
|
||||
}
|
||||
return this;
|
||||
};
|
||||
// normalizes this vector and returns it.
|
||||
Vector.prototype.norm = function () {
|
||||
var SIZE = this.size();
|
||||
var quotient = 1.0 / this.eulideanLength();
|
||||
for (var i = 0; i < SIZE; i++) {
|
||||
this.components[i] = this.components[i] * quotient;
|
||||
}
|
||||
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;
|
||||
if (SIZE == other.size()) {
|
||||
for (var i = 0; i < SIZE; i++) {
|
||||
if (Math.abs(this.components[i] - other.component(i)) > EPSILON) {
|
||||
ans = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
ans = false;
|
||||
}
|
||||
return ans;
|
||||
};
|
||||
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 Vector = /** @class */ (function () {
|
||||
// constructor
|
||||
function Vector (N, comps) {
|
||||
if (comps === void 0) { comps = [] }
|
||||
this.components = new Array(N)
|
||||
if (comps.length == 0) {
|
||||
for (var i = 0; i < N; i++) {
|
||||
if (i == pos) {
|
||||
ans.changeComponent(i, 1.0);
|
||||
}
|
||||
else {
|
||||
ans.changeComponent(i, 0);
|
||||
}
|
||||
this.components[i] = 0.0
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
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);
|
||||
for (var i = 0; i < N; i++) {
|
||||
ans.changeComponent(i, (Math.floor((Math.random() * b) + a)));
|
||||
} else {
|
||||
if (N == comps.length) {
|
||||
this.components = comps
|
||||
} else {
|
||||
throw 'Vector: invalide size!'
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
} // end of constructor
|
||||
// returns the size of this vector.
|
||||
// not the eulidean length!
|
||||
Vector.prototype.size = function () {
|
||||
return this.components.length
|
||||
}
|
||||
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);
|
||||
for (var i = 0; i < N; i++) {
|
||||
ans.changeComponent(i, ((Math.random() * b) + a));
|
||||
// computes the eulidean length.
|
||||
Vector.prototype.eulideanLength = function () {
|
||||
var sum = 0
|
||||
for (var i = 0; i < this.components.length; i++) {
|
||||
sum += this.components[i] * this.components[i]
|
||||
}
|
||||
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]
|
||||
}
|
||||
// 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
|
||||
} 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)
|
||||
for (var i = 0; i < SIZE; i++) {
|
||||
ans.changeComponent(i, (this.components[i] + other.component(i)))
|
||||
}
|
||||
return ans;
|
||||
return ans
|
||||
} else {
|
||||
throw 'add: vector must have same size!'
|
||||
}
|
||||
}
|
||||
LinearAlgebra.randomVectorFloat = randomVectorFloat;
|
||||
// ------------------ end of global functions -----------------------------
|
||||
/*
|
||||
// vector subtraction
|
||||
Vector.prototype.sub = function (other) {
|
||||
if (this.size() == other.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)))
|
||||
}
|
||||
return ans
|
||||
} else {
|
||||
throw 'add: vector must have same size!'
|
||||
}
|
||||
}
|
||||
// dot-product
|
||||
Vector.prototype.dot = function (other) {
|
||||
var sum = 0
|
||||
if (other.size() == this.size()) {
|
||||
var SIZE = other.size()
|
||||
for (var i = 0; i < SIZE; i++) {
|
||||
sum += this.components[i] * other.component(i)
|
||||
}
|
||||
return sum
|
||||
} else {
|
||||
throw 'dot: vectors must have same size!'
|
||||
}
|
||||
}
|
||||
// scalar multiplication
|
||||
Vector.prototype.scalar = function (s) {
|
||||
var SIZE = this.size()
|
||||
var ans = new Vector(SIZE)
|
||||
for (var i = 0; i < SIZE; i++) {
|
||||
ans.changeComponent(i, (this.components[i] * s))
|
||||
}
|
||||
return ans
|
||||
}
|
||||
// returns a string representation of this vector.
|
||||
Vector.prototype.toString = function () {
|
||||
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] + ')'
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw 'createUnitBasis: index out of bounds'
|
||||
}
|
||||
return this
|
||||
}
|
||||
// normalizes this vector and returns it.
|
||||
Vector.prototype.norm = function () {
|
||||
var SIZE = this.size()
|
||||
var quotient = 1.0 / this.eulideanLength()
|
||||
for (var i = 0; i < SIZE; i++) {
|
||||
this.components[i] = this.components[i] * quotient
|
||||
}
|
||||
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
|
||||
if (SIZE == other.size()) {
|
||||
for (var i = 0; i < SIZE; i++) {
|
||||
if (Math.abs(this.components[i] - other.component(i)) > EPSILON) {
|
||||
ans = false
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ans = false
|
||||
}
|
||||
return ans
|
||||
}
|
||||
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)
|
||||
for (var i = 0; i < N; i++) {
|
||||
if (i == pos) {
|
||||
ans.changeComponent(i, 1.0)
|
||||
} else {
|
||||
ans.changeComponent(i, 0)
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
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)
|
||||
for (var i = 0; i < N; i++) {
|
||||
ans.changeComponent(i, (Math.floor((Math.random() * b) + a)))
|
||||
}
|
||||
return ans
|
||||
}
|
||||
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)
|
||||
for (var i = 0; i < N; i++) {
|
||||
ans.changeComponent(i, ((Math.random() * b) + a))
|
||||
}
|
||||
return ans
|
||||
}
|
||||
LinearAlgebra.randomVectorFloat = randomVectorFloat
|
||||
// ------------------ end of global functions -----------------------------
|
||||
/*
|
||||
class: Matrix
|
||||
This class represents a matrix of arbitrary size and operations on it.
|
||||
*/
|
||||
var Matrix = /** @class */ (function () {
|
||||
// constructor for zero-matrix or fix number matrix.
|
||||
function Matrix(row, col, comps) {
|
||||
if (comps === void 0) { comps = []; }
|
||||
if (comps.length == 0) {
|
||||
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;
|
||||
}
|
||||
this.matrix[i] = rowVector;
|
||||
rowVector = new Array();
|
||||
}
|
||||
}
|
||||
else {
|
||||
this.matrix = comps;
|
||||
}
|
||||
this.rows = row;
|
||||
this.cols = col;
|
||||
var Matrix = /** @class */ (function () {
|
||||
// constructor for zero-matrix or fix number matrix.
|
||||
function Matrix (row, col, comps) {
|
||||
if (comps === void 0) { comps = [] }
|
||||
if (comps.length == 0) {
|
||||
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
|
||||
}
|
||||
this.matrix[i] = rowVector
|
||||
rowVector = new Array()
|
||||
}
|
||||
// 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];
|
||||
} else {
|
||||
this.matrix = comps
|
||||
}
|
||||
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]
|
||||
} 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
|
||||
} else {
|
||||
throw new Error('changeComponent: index out of bounds')
|
||||
}
|
||||
}
|
||||
// returns a string representation of this matrix.
|
||||
Matrix.prototype.toString = function () {
|
||||
var ans = ''
|
||||
for (var i = 0; i < this.rows; i++) {
|
||||
ans += '|'
|
||||
for (var j = 0; j < this.cols; j++) {
|
||||
if (j < this.cols - 1) {
|
||||
ans += this.matrix[i][j] + ','
|
||||
} else {
|
||||
if (i < this.rows - 1) {
|
||||
ans += this.matrix[i][j] + '|\n'
|
||||
} else {
|
||||
ans += this.matrix[i][j] + '|'
|
||||
}
|
||||
else {
|
||||
throw new Error("component: index out of bounds");
|
||||
}
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
// 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)
|
||||
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)))
|
||||
}
|
||||
}
|
||||
return ans
|
||||
} 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]) {
|
||||
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
|
||||
}
|
||||
};
|
||||
// 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;
|
||||
}
|
||||
else {
|
||||
throw new Error("changeComponent: index out of bounds");
|
||||
}
|
||||
};
|
||||
// returns a string representation of this matrix.
|
||||
Matrix.prototype.toString = function () {
|
||||
var ans = "";
|
||||
for (var i = 0; i < this.rows; i++) {
|
||||
ans += "|";
|
||||
for (var j = 0; j < this.cols; j++) {
|
||||
if (j < this.cols - 1) {
|
||||
ans += this.matrix[i][j] + ",";
|
||||
}
|
||||
else {
|
||||
if (i < this.rows - 1) {
|
||||
ans += this.matrix[i][j] + "|\n";
|
||||
}
|
||||
else {
|
||||
ans += this.matrix[i][j] + "|";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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;
|
||||
};
|
||||
// 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);
|
||||
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)));
|
||||
}
|
||||
}
|
||||
return ans;
|
||||
}
|
||||
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]) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
ans = false;
|
||||
}
|
||||
return ans;
|
||||
};
|
||||
// matrix-scalar multiplication
|
||||
Matrix.prototype.scalar = function (c) {
|
||||
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));
|
||||
}
|
||||
}
|
||||
return ans;
|
||||
};
|
||||
return Matrix;
|
||||
}()); // end of class Matrix
|
||||
LinearAlgebra.Matrix = Matrix;
|
||||
})(LinearAlgebra || (LinearAlgebra = {})); // end of namespace LinearAlgebra
|
||||
}
|
||||
}
|
||||
} else {
|
||||
ans = false
|
||||
}
|
||||
return ans
|
||||
}
|
||||
// matrix-scalar multiplication
|
||||
Matrix.prototype.scalar = function (c) {
|
||||
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))
|
||||
}
|
||||
}
|
||||
return ans
|
||||
}
|
||||
return Matrix
|
||||
}()) // end of class Matrix
|
||||
LinearAlgebra.Matrix = Matrix
|
||||
})(LinearAlgebra || (LinearAlgebra = {})) // end of namespace LinearAlgebra
|
||||
|
@ -6,165 +6,164 @@
|
||||
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
|
||||
|
||||
// creating some vectors
|
||||
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)");
|
||||
});
|
||||
});
|
||||
});
|
||||
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)')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// 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))
|
||||
})
|
||||
})
|
||||
})
|
||||
|
@ -1,71 +1,66 @@
|
||||
// starting at s
|
||||
function solve(graph, s) {
|
||||
var solutions = {};
|
||||
solutions[s] = [];
|
||||
solutions[s].dist = 0;
|
||||
|
||||
while(true) {
|
||||
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];
|
||||
|
||||
for(var a in adj) {
|
||||
function solve (graph, s) {
|
||||
var solutions = {}
|
||||
solutions[s] = []
|
||||
solutions[s].dist = 0
|
||||
|
||||
if(solutions[a])
|
||||
continue;
|
||||
|
||||
var d = adj[a] + ndist;
|
||||
if(d < dist) {
|
||||
|
||||
p = solutions[n];
|
||||
neighbor = a;
|
||||
dist = d;
|
||||
while (true) {
|
||||
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]
|
||||
|
||||
for (var a in adj) {
|
||||
if (solutions[a]) { continue }
|
||||
|
||||
var d = adj[a] + ndist
|
||||
if (d < dist) {
|
||||
p = solutions[n]
|
||||
neighbor = a
|
||||
dist = d
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//no more solutions
|
||||
if(dist === Infinity) {
|
||||
break;
|
||||
|
||||
// no more solutions
|
||||
if (dist === Infinity) {
|
||||
break
|
||||
}
|
||||
|
||||
//extend parent's solution path
|
||||
solutions[neighbor] = p.concat(neighbor);
|
||||
//extend parent's cost
|
||||
solutions[neighbor].dist = dist;
|
||||
|
||||
// extend parent's solution path
|
||||
solutions[neighbor] = p.concat(neighbor)
|
||||
// extend parent's cost
|
||||
solutions[neighbor].dist = dist
|
||||
}
|
||||
|
||||
return solutions;
|
||||
|
||||
return solutions
|
||||
}
|
||||
//create graph
|
||||
var graph = {};
|
||||
// create 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
|
||||
// convert uni-directional to bi-directional graph
|
||||
// var graph = {
|
||||
// a: {e:1, b:1, g:3},
|
||||
// b: {a:1, c:1},
|
||||
@ -77,27 +72,25 @@ var layout = {
|
||||
// h: {f:1}
|
||||
// };
|
||||
|
||||
for(var id in layout) {
|
||||
if(!graph[id])
|
||||
graph[id] = {};
|
||||
layout[id].forEach(function(aid) {
|
||||
graph[id][aid] = 1;
|
||||
if(!graph[aid])
|
||||
graph[aid] = {};
|
||||
graph[aid][id] = 1;
|
||||
});
|
||||
for (var id in layout) {
|
||||
if (!graph[id]) { graph[id] = {} }
|
||||
layout[id].forEach(function (aid) {
|
||||
graph[id][aid] = 1
|
||||
if (!graph[aid]) { graph[aid] = {} }
|
||||
graph[aid][id] = 1
|
||||
})
|
||||
}
|
||||
|
||||
//choose start node
|
||||
var start = '10';
|
||||
//get all solutions
|
||||
var solutions = solve(graph, start);
|
||||
// choose start node
|
||||
var start = '10'
|
||||
// get all solutions
|
||||
var solutions = solve(graph, start)
|
||||
|
||||
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 + ")");
|
||||
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 + ')')
|
||||
}
|
||||
|
||||
// From '10' to
|
||||
|
20
maths/abs.js
20
maths/abs.js
@ -11,16 +11,16 @@
|
||||
https://en.wikipedia.org/wiki/Absolute_value
|
||||
*/
|
||||
|
||||
function abs_val(num) {
|
||||
// Find absolute value of `num`.
|
||||
"use strict";
|
||||
if (num < 0) {
|
||||
return -num
|
||||
}
|
||||
// Executes if condition is not met.
|
||||
return num
|
||||
function abs_val (num) {
|
||||
// Find absolute value of `num`.
|
||||
'use strict'
|
||||
if (num < 0) {
|
||||
return -num
|
||||
}
|
||||
// Executes if condition is not met.
|
||||
return 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))
|
||||
|
@ -11,20 +11,20 @@
|
||||
https://en.wikipedia.org/wiki/Mean
|
||||
*/
|
||||
|
||||
function mean(nums) {
|
||||
"use strict";
|
||||
var sum = 0;
|
||||
var avg;
|
||||
function mean (nums) {
|
||||
'use strict'
|
||||
var sum = 0
|
||||
var avg
|
||||
|
||||
// This loop sums all values in the 'nums' array.
|
||||
nums.forEach(function (current) {
|
||||
sum += current;
|
||||
});
|
||||
// This loop sums all values in the 'nums' array.
|
||||
nums.forEach(function (current) {
|
||||
sum += current
|
||||
})
|
||||
|
||||
// Divide sum by the length of the 'nums' array.
|
||||
avg = sum / nums.length;
|
||||
return avg;
|
||||
// Divide sum by the length of the 'nums' array.
|
||||
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]))
|
||||
|
@ -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 = [];
|
||||
while (i <= num) {
|
||||
range.push(i);
|
||||
i += 1;
|
||||
}
|
||||
return range;
|
||||
function calc_range (num) {
|
||||
// Generate a range of numbers from 1 to `num`.
|
||||
var i = 1
|
||||
var range = []
|
||||
while (i <= num) {
|
||||
range.push(i)
|
||||
i += 1
|
||||
}
|
||||
return range
|
||||
}
|
||||
|
||||
function calc_factorial(num) {
|
||||
var factorial;
|
||||
var range = calc_range(num);
|
||||
function calc_factorial (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.";
|
||||
}
|
||||
if (num === null || num === undefined) {
|
||||
return "Sorry, factorial does not exist for null or undefined numbers.";
|
||||
}
|
||||
if (num === 0) {
|
||||
return "The factorial of 0 is 1.";
|
||||
}
|
||||
if (num > 0) {
|
||||
factorial = 1;
|
||||
range.forEach(function (i) {
|
||||
factorial = factorial * i;
|
||||
});
|
||||
return "The factorial of " + num + " is " + factorial;
|
||||
}
|
||||
// Check if the number is negative, positive, null, undefined, or zero
|
||||
if (num < 0) {
|
||||
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.'
|
||||
}
|
||||
if (num === 0) {
|
||||
return 'The factorial of 0 is 1.'
|
||||
}
|
||||
if (num > 0) {
|
||||
factorial = 1
|
||||
range.forEach(function (i) {
|
||||
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))
|
||||
|
@ -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;
|
||||
// Check to see whether num_1 or num_2 is larger.
|
||||
if (num_1 > num_2) {
|
||||
max_num = num_1;
|
||||
} else {
|
||||
max_num = num_2;
|
||||
}
|
||||
lcm = max_num;
|
||||
function find_lcm (num_1, num_2) {
|
||||
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
|
||||
} else {
|
||||
max_num = num_2
|
||||
}
|
||||
lcm = max_num
|
||||
|
||||
while (true) {
|
||||
if ((lcm % num_1 === 0) && (lcm % num_2 === 0)) {
|
||||
break;
|
||||
}
|
||||
lcm += max_num;
|
||||
while (true) {
|
||||
if ((lcm % num_1 === 0) && (lcm % num_2 === 0)) {
|
||||
break
|
||||
}
|
||||
return lcm;
|
||||
lcm += max_num
|
||||
}
|
||||
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))
|
||||
|
165
maths/graph.js
165
maths/graph.js
@ -1,94 +1,89 @@
|
||||
// create a graph class
|
||||
class Graph {
|
||||
// defining vertex array and
|
||||
// adjacent list
|
||||
constructor(noOfVertices)
|
||||
{
|
||||
this.noOfVertices = noOfVertices;
|
||||
this.AdjList = new Map();
|
||||
}
|
||||
|
||||
// functions to be implemented
|
||||
|
||||
// addVertex(v)
|
||||
// addEdge(v, w)
|
||||
// printGraph()
|
||||
|
||||
// bfs(v)
|
||||
// dfs(v)
|
||||
// create a graph class
|
||||
class Graph {
|
||||
// defining vertex array and
|
||||
// adjacent list
|
||||
constructor (noOfVertices) {
|
||||
this.noOfVertices = noOfVertices
|
||||
this.AdjList = new Map()
|
||||
}
|
||||
|
||||
// functions to be implemented
|
||||
|
||||
// addVertex(v)
|
||||
// addEdge(v, w)
|
||||
// printGraph()
|
||||
|
||||
// bfs(v)
|
||||
// dfs(v)
|
||||
}
|
||||
|
||||
// add vertex to the graph
|
||||
addVertex(v)
|
||||
{
|
||||
// initialize the adjacent list with a
|
||||
// null array
|
||||
this.AdjList.set(v, []);
|
||||
// add vertex to the graph
|
||||
addVertex(v)
|
||||
{
|
||||
// initialize the adjacent list with a
|
||||
// null array
|
||||
this.AdjList.set(v, [])
|
||||
}
|
||||
|
||||
// add edge to the graph
|
||||
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);
|
||||
|
||||
// Since graph is undirected,
|
||||
// add an edge from w to v also
|
||||
this.AdjList.get(w).push(v);
|
||||
}
|
||||
// add edge to the graph
|
||||
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)
|
||||
|
||||
|
||||
// Prints the vertex and adjacency list
|
||||
printGraph()
|
||||
{
|
||||
// get all the vertices
|
||||
var get_keys = this.AdjList.keys();
|
||||
|
||||
// iterate over the vertices
|
||||
for (var i of get_keys)
|
||||
{
|
||||
// great the corresponding adjacency list
|
||||
// for the vertex
|
||||
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 + " ";
|
||||
|
||||
// print the vertex and its adjacency list
|
||||
console.log(i + " -> " + conc);
|
||||
}
|
||||
// Since graph is undirected,
|
||||
// add an edge from w to v also
|
||||
this.AdjList.get(w).push(v)
|
||||
}
|
||||
|
||||
// Prints the vertex and adjacency list
|
||||
printGraph()
|
||||
{
|
||||
// get all the vertices
|
||||
var get_keys = this.AdjList.keys()
|
||||
|
||||
// iterate over the vertices
|
||||
for (var i of get_keys) {
|
||||
// great the corresponding adjacency list
|
||||
// for the vertex
|
||||
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 + ' ' }
|
||||
|
||||
// print the vertex and its adjacency list
|
||||
console.log(i + ' -> ' + conc)
|
||||
}
|
||||
}
|
||||
|
||||
// Example
|
||||
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]);
|
||||
}
|
||||
|
||||
// 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');
|
||||
|
||||
// prints all vertex and
|
||||
// its adjacency list
|
||||
// A -> B D E
|
||||
// B -> A C
|
||||
// C -> B E F
|
||||
// D -> A E
|
||||
// E -> A D F C
|
||||
// F -> E C
|
||||
g.printGraph();
|
||||
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])
|
||||
}
|
||||
|
||||
// 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')
|
||||
|
||||
// prints all vertex and
|
||||
// its adjacency list
|
||||
// A -> B D E
|
||||
// B -> A C
|
||||
// C -> B E F
|
||||
// D -> A E
|
||||
// E -> A D F C
|
||||
// F -> E C
|
||||
g.printGraph()
|
||||
|
Reference in New Issue
Block a user