From fc3176fd1ebeb0f99ed89da2a24352d08538f48a Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Fri, 23 May 2014 06:40:54 -0700 Subject: [PATCH 01/54] Initial commit --- README.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 00000000..b4771d7f --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +javascript-datastructures-algorithms +==================================== + +JavaScript algorithms From 226afc0e9303147bd951b8fdb5175a54ec205524 Mon Sep 17 00:00:00 2001 From: loiane Date: Fri, 6 Jun 2014 21:01:33 -0300 Subject: [PATCH 02/54] added chapter 01 --- chapter01/01-HelloWorld.html | 14 +++++++ chapter01/01-HelloWorld.js | 8 ++++ chapter01/02-Variables.html | 10 +++++ chapter01/02-Variables.js | 15 ++++++++ chapter01/03-Operators.html | 10 +++++ chapter01/03-Operators.js | 49 +++++++++++++++++++++++++ chapter01/04-ConditionalStatements.html | 10 +++++ chapter01/04-ConditionalStatements.js | 41 +++++++++++++++++++++ chapter01/05-Loops.html | 10 +++++ chapter01/05-Loops.js | 23 ++++++++++++ chapter01/06-Functions.html | 10 +++++ chapter01/06-Functions.js | 28 ++++++++++++++ chapter01/07-ObjectOrientedJS.html | 10 +++++ chapter01/07-ObjectOrientedJS.js | 42 +++++++++++++++++++++ 14 files changed, 280 insertions(+) create mode 100644 chapter01/01-HelloWorld.html create mode 100644 chapter01/01-HelloWorld.js create mode 100644 chapter01/02-Variables.html create mode 100644 chapter01/02-Variables.js create mode 100644 chapter01/03-Operators.html create mode 100644 chapter01/03-Operators.js create mode 100644 chapter01/04-ConditionalStatements.html create mode 100644 chapter01/04-ConditionalStatements.js create mode 100644 chapter01/05-Loops.html create mode 100644 chapter01/05-Loops.js create mode 100644 chapter01/06-Functions.html create mode 100644 chapter01/06-Functions.js create mode 100644 chapter01/07-ObjectOrientedJS.html create mode 100644 chapter01/07-ObjectOrientedJS.js diff --git a/chapter01/01-HelloWorld.html b/chapter01/01-HelloWorld.html new file mode 100644 index 00000000..f7eca1bf --- /dev/null +++ b/chapter01/01-HelloWorld.html @@ -0,0 +1,14 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter01/01-HelloWorld.js b/chapter01/01-HelloWorld.js new file mode 100644 index 00000000..89833849 --- /dev/null +++ b/chapter01/01-HelloWorld.js @@ -0,0 +1,8 @@ +function output(t) { + document.write('

' + t + '

'); + return; +} + +alert('Hello, World!'); +console.log('Hello, World!'); +output('Hello, World!'); \ No newline at end of file diff --git a/chapter01/02-Variables.html b/chapter01/02-Variables.html new file mode 100644 index 00000000..f093a684 --- /dev/null +++ b/chapter01/02-Variables.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter01/02-Variables.js b/chapter01/02-Variables.js new file mode 100644 index 00000000..502ad0e9 --- /dev/null +++ b/chapter01/02-Variables.js @@ -0,0 +1,15 @@ +var num = 1; //{1} +num = 3; //{2} + +var price = 1.5; //{3} +var name = 'Packt'; //{4} +var trueValue = true; //{5} +var nullVar = null; //{6} +var und; //7 + +console.log("num: "+ num); +console.log("name: "+ num); +console.log("trueValue: "+ num); +console.log("price: "+ num); +console.log("nullVar: "+ nullVar); +console.log("und: "+ und); \ No newline at end of file diff --git a/chapter01/03-Operators.html b/chapter01/03-Operators.html new file mode 100644 index 00000000..2502aa78 --- /dev/null +++ b/chapter01/03-Operators.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter01/03-Operators.js b/chapter01/03-Operators.js new file mode 100644 index 00000000..3f1a0dcc --- /dev/null +++ b/chapter01/03-Operators.js @@ -0,0 +1,49 @@ +/* Arithmetic operators */ +var num = 0; + +console.log('num value is ' + num); + +num = num + 2; + +console.log('New num value is ' + num); + +num = num * 3; + +console.log('New num value is ' + num); + +num = num / 2; + +console.log('New num value is ' + num); + +num++; + +num--; + +console.log('New num value is ' + num); + +console.log('num mod 2 value is ' + (num % 2)); + + +/* Assignment operators */ +num += 1; +num -= 2; +num *= 3; +num /= 2; +num %= 3; + +console.log('New num value is ' + num); + +/* Assignment operators */ +console.log('num == 1 : ' + (num == 1)); +console.log('num === 1 : ' + (num === 1)); +console.log('num != 1 : ' + (num != 1)); +console.log('num > 1 : ' + (num > 1)); +console.log('num < 1 : ' + (num < 1)); +console.log('num >= 1 : ' + (num >= 1)); +console.log('num <= 1 : ' + (num <= 1)); + + +/* Logical operators */ +console.log('true && false : ' + (true && false)); +console.log('true || false : ' + (true || false)); +console.log('!true : ' + (!true)); \ No newline at end of file diff --git a/chapter01/04-ConditionalStatements.html b/chapter01/04-ConditionalStatements.html new file mode 100644 index 00000000..d1f7d8f0 --- /dev/null +++ b/chapter01/04-ConditionalStatements.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter01/04-ConditionalStatements.js b/chapter01/04-ConditionalStatements.js new file mode 100644 index 00000000..3d9cf0e5 --- /dev/null +++ b/chapter01/04-ConditionalStatements.js @@ -0,0 +1,41 @@ +/* Example 01 - if */ +var num = 1; +if (num == 1) { + console.log("num is equal to 1"); +} + +/* Example 02 - if-else */ +var num = 0; +if (num == 1) { + console.log("num is equal to 1"); +} else { + console.log("num is not equal to 1, the value of num is " + num); +} + +/* Example 03 - if-else-if-else... */ +var month = 5; +if (month == 1) { + console.log("January"); +} else if (month == 2){ + console.log("February"); +} else if (month == 3){ + console.log("March"); +} else { + console.log("Month is not January, February or March"); +} + +/* Example 04 - switch */ +var month = 5; +switch(month) { + case 1: + console.log("January"); + break; + case 2: + console.log("February"); + break; + case 3: + console.log("March"); + break; + default: + console.log("Month is not January, February or March"); +} \ No newline at end of file diff --git a/chapter01/05-Loops.html b/chapter01/05-Loops.html new file mode 100644 index 00000000..0fefd73b --- /dev/null +++ b/chapter01/05-Loops.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter01/05-Loops.js b/chapter01/05-Loops.js new file mode 100644 index 00000000..61cf20cb --- /dev/null +++ b/chapter01/05-Loops.js @@ -0,0 +1,23 @@ +console.log('**** for example ****'); + +/* for - example */ +for (var i=0; i<10; i++) { + console.log(i); +} + +console.log('**** while example ****'); +/* while - example */ +var i = 0; +while(i<10) +{ + console.log(i); + i++; +} + +console.log('**** do-while example ****'); +/* do-while - example */ +var i = 0; +do { + console.log(i); + i++; +} while (i<10) \ No newline at end of file diff --git a/chapter01/06-Functions.html b/chapter01/06-Functions.html new file mode 100644 index 00000000..7468734f --- /dev/null +++ b/chapter01/06-Functions.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter01/06-Functions.js b/chapter01/06-Functions.js new file mode 100644 index 00000000..c307c6d0 --- /dev/null +++ b/chapter01/06-Functions.js @@ -0,0 +1,28 @@ +function sayHello() { + console.log('Hello!'); +} + +sayHello(); + +/* function with parameter */ +function output(text) { + console.log(text); +} + +output('Hello!'); + +output('Hello!', 'Other text'); + +output(); + +/* function using the return statement */ +function sum(num1, num2) { + return num1 + num2; +} + +var result = sum(1,2); +output(result); + + + + diff --git a/chapter01/07-ObjectOrientedJS.html b/chapter01/07-ObjectOrientedJS.html new file mode 100644 index 00000000..91a3b533 --- /dev/null +++ b/chapter01/07-ObjectOrientedJS.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter01/07-ObjectOrientedJS.js b/chapter01/07-ObjectOrientedJS.js new file mode 100644 index 00000000..c67a6c78 --- /dev/null +++ b/chapter01/07-ObjectOrientedJS.js @@ -0,0 +1,42 @@ +/* Object example 1 */ + +var obj = new Object(); + +/* Object example 2 */ + +var obj = {}; + +obj = { + name: { + first: 'Gandalf', + last: 'the Grey' + }, + address: 'Middle Earth' +}; + +/* Object example 3 */ + +function Book(title, pages, isbn){ + this.title = title; + this.pages = pages; + this.isbn = isbn; + this.printIsbn = function(){ + console.log(this.isbn); + } +} + +var book = new Book('title', 'pag', 'isbn'); + +console.log(book.title); //outputs the book title + +book.title = 'new title'; //update the value of the book title + +console.log(book.title); //outputs the updated value + +Book.prototype.printTitle = function(){ + console.log(this.title); +}; + +book.printTitle(); + +book.printIsbn(); \ No newline at end of file From 4cdd1873bf174d921b8e10f04d3af17e72ecdc22 Mon Sep 17 00:00:00 2001 From: loiane Date: Fri, 6 Jun 2014 21:01:40 -0300 Subject: [PATCH 03/54] added git ignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..bc8a670e --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +.idea/* \ No newline at end of file From ebc1b858a28478a1ad811c9f6851e6adcb61737a Mon Sep 17 00:00:00 2001 From: loiane Date: Sat, 14 Jun 2014 08:30:33 -0300 Subject: [PATCH 04/54] added chapter 02 --- chapter02/01-Introduction.html | 10 +++ chapter02/01-Introduction.js | 11 +++ chapter02/02-CreatingAndInitialingArrays.html | 10 +++ chapter02/02-CreatingAndInitialingArrays.js | 31 ++++++++ chapter02/03-AddingRemovingElements.html | 10 +++ chapter02/03-AddingRemovingElements.js | 73 +++++++++++++++++++ .../04-TwoDimensionalMultiDimensional.html | 10 +++ .../04-TwoDimensionalMultiDimensional.js | 62 ++++++++++++++++ chapter02/05-ArrayMethods.html | 10 +++ chapter02/05-ArrayMethods.js | 56 ++++++++++++++ 10 files changed, 283 insertions(+) create mode 100644 chapter02/01-Introduction.html create mode 100644 chapter02/01-Introduction.js create mode 100644 chapter02/02-CreatingAndInitialingArrays.html create mode 100644 chapter02/02-CreatingAndInitialingArrays.js create mode 100644 chapter02/03-AddingRemovingElements.html create mode 100644 chapter02/03-AddingRemovingElements.js create mode 100644 chapter02/04-TwoDimensionalMultiDimensional.html create mode 100644 chapter02/04-TwoDimensionalMultiDimensional.js create mode 100644 chapter02/05-ArrayMethods.html create mode 100644 chapter02/05-ArrayMethods.js diff --git a/chapter02/01-Introduction.html b/chapter02/01-Introduction.html new file mode 100644 index 00000000..86731b13 --- /dev/null +++ b/chapter02/01-Introduction.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter02/01-Introduction.js b/chapter02/01-Introduction.js new file mode 100644 index 00000000..737ad09b --- /dev/null +++ b/chapter02/01-Introduction.js @@ -0,0 +1,11 @@ +var averageTempJan = 31.9; +var averageTempFeb = 35.3; +var averageTempMar = 42.4; +var averageTempApr = 52; +var averageTempMay = 60.8; + +averageTemp[0] = 31.9; +averageTemp[1] = 35.3; +averageTemp[2] = 42.4; +averageTemp[3] = 52; +averageTemp[4] = 60.8; \ No newline at end of file diff --git a/chapter02/02-CreatingAndInitialingArrays.html b/chapter02/02-CreatingAndInitialingArrays.html new file mode 100644 index 00000000..7a51f1c9 --- /dev/null +++ b/chapter02/02-CreatingAndInitialingArrays.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter02/02-CreatingAndInitialingArrays.js b/chapter02/02-CreatingAndInitialingArrays.js new file mode 100644 index 00000000..a3d18fcd --- /dev/null +++ b/chapter02/02-CreatingAndInitialingArrays.js @@ -0,0 +1,31 @@ +var daysOfWeek = []; + +var daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; + +var daysOfWeek = new Array(); //{1} + +var daysOfWeek = new Array(7); //{2} + +console.log(daysOfWeek.length); + +var daysOfWeek = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'); //{3} + +for (var i=0; i + + + + + + + + + \ No newline at end of file diff --git a/chapter02/03-AddingRemovingElements.js b/chapter02/03-AddingRemovingElements.js new file mode 100644 index 00000000..d19aa555 --- /dev/null +++ b/chapter02/03-AddingRemovingElements.js @@ -0,0 +1,73 @@ +function printArray(myArray) { + for (var i=0; i=0; i--){ + numbers[i] = numbers[i-1]; +} + +numbers[0] = -1; + +//printArray(numbers); + +//using method unshift +numbers.unshift(-2); + +//printArray(numbers); + +numbers.unshift(-4, -3); + +//printArray(numbers); + +//**** Removing elements + +numbers.pop(); + +//remove first position manually +/*for (var i=0; i + + + + + + + + + \ No newline at end of file diff --git a/chapter02/04-TwoDimensionalMultiDimensional.js b/chapter02/04-TwoDimensionalMultiDimensional.js new file mode 100644 index 00000000..7830e4d1 --- /dev/null +++ b/chapter02/04-TwoDimensionalMultiDimensional.js @@ -0,0 +1,62 @@ +var averageTempDay1 = [72,75,79,79,81,81]; +var averageTempDay2 = [81,79,75,75,73,72]; + +var averageTemp = []; + +//same as +averageTemp[0] = [72,75,79,79,81,81]; +averageTemp[1] = [81,79,75,75,73,72]; + +function printMatrix(myMatrix) { + for (var i=0; i + + + + + + + + + \ No newline at end of file diff --git a/chapter02/05-ArrayMethods.js b/chapter02/05-ArrayMethods.js new file mode 100644 index 00000000..eff8218b --- /dev/null +++ b/chapter02/05-ArrayMethods.js @@ -0,0 +1,56 @@ +//*** contact +var zero = 0; +var positiveNumbers = [1,2,3]; +var negativeNumbers = [-3,-2,-1]; +var numbers = negativeNumbers.concat(zero, positiveNumbers); + +//document.writeln(numbers); + +//*** every and some +var isEven = function (x) { + // returns true if x is a multiple of 2. + console.log(x); + return (x % 2 == 0) ? true : false; +}; +var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]; + +numbers.every(isEven); //is going to execute the function only once + +console.log('---'); + +numbers.some(isEven); //is going to execute the function twice + +numbers.forEach(function(x){ + console.log((x % 2 == 0)); +}); + +document.writeln(numbers.reverse()); + +//document.writeln('*** filter ***'); + +var evenNumbers = numbers.filter(isEven); + +//document.writeln(evenNumbers); + +document.writeln('*** map ***'); + +//document.writeln(numbers.map(isEven)); + +document.writeln(numbers.sort()); + +document.writeln(numbers.sort(function(a,b){ + return a-b; +})); + +//*** toString +console.log(numbers.toString()); + +console.log(numbers.indexOf(10)); +console.log(numbers.indexOf(100)); + +numbers.push(10); +console.log(numbers.lastIndexOf(10)); +console.log(numbers.lastIndexOf(100)); + +var numbersString = numbers.join('-'); +console.log(numbersString); \ No newline at end of file From e265366a7a5bd981b7ff70ab8d8609221dd68232 Mon Sep 17 00:00:00 2001 From: loiane Date: Mon, 16 Jun 2014 12:02:05 -0300 Subject: [PATCH 05/54] added chapter 03 --- chapter03/01-Stack.html | 10 ++++++ chapter03/01-Stack.js | 28 +++++++++++++++++ chapter03/02-UsingStacks.html | 11 +++++++ chapter03/02-UsingStacks.js | 13 ++++++++ chapter03/03-BalancedSymbols.html | 11 +++++++ chapter03/03-BalancedSymbols.js | 37 ++++++++++++++++++++++ chapter03/04-DecimalToBinary.html | 11 +++++++ chapter03/04-DecimalToBinary.js | 52 +++++++++++++++++++++++++++++++ chapter03/05-TowerOfHanoi.html | 11 +++++++ chapter03/05-TowerOfHanoi.js | 26 ++++++++++++++++ 10 files changed, 210 insertions(+) create mode 100644 chapter03/01-Stack.html create mode 100644 chapter03/01-Stack.js create mode 100644 chapter03/02-UsingStacks.html create mode 100644 chapter03/02-UsingStacks.js create mode 100644 chapter03/03-BalancedSymbols.html create mode 100644 chapter03/03-BalancedSymbols.js create mode 100644 chapter03/04-DecimalToBinary.html create mode 100644 chapter03/04-DecimalToBinary.js create mode 100644 chapter03/05-TowerOfHanoi.html create mode 100644 chapter03/05-TowerOfHanoi.js diff --git a/chapter03/01-Stack.html b/chapter03/01-Stack.html new file mode 100644 index 00000000..e936b4e1 --- /dev/null +++ b/chapter03/01-Stack.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter03/01-Stack.js b/chapter03/01-Stack.js new file mode 100644 index 00000000..139d5fea --- /dev/null +++ b/chapter03/01-Stack.js @@ -0,0 +1,28 @@ +function Stack() { + + this.items = []; + + this.push = function(element){ + this.items.push(element); + }; + + this.pop = function(){ + return this.items.pop(); + }; + + this.peek = function(){ + return this.items[this.items.length-1]; + }; + + this.isEmpty = function(){ + return this.items.length == 0; + }; + + this.size = function(){ + return this.items.length; + }; + + this.print = function(){ + console.log(this.items.toString()); + }; +} \ No newline at end of file diff --git a/chapter03/02-UsingStacks.html b/chapter03/02-UsingStacks.html new file mode 100644 index 00000000..1772e441 --- /dev/null +++ b/chapter03/02-UsingStacks.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter03/02-UsingStacks.js b/chapter03/02-UsingStacks.js new file mode 100644 index 00000000..8e5f5b19 --- /dev/null +++ b/chapter03/02-UsingStacks.js @@ -0,0 +1,13 @@ +var stack = new Stack(); + console.log(stack.isEmpty()); //outputs true + stack.push(5); + stack.push(8); + console.log(stack.peek()); // outputs 8 + stack.push(11); + console.log(stack.size()); // outputs 3 + console.log(stack.isEmpty()); //outputs false + stack.push(15); + stack.pop(); + stack.pop(); + console.log(stack.size()); // outputs 2 + stack.print(); // outputs [5, 8] \ No newline at end of file diff --git a/chapter03/03-BalancedSymbols.html b/chapter03/03-BalancedSymbols.html new file mode 100644 index 00000000..d347fe2e --- /dev/null +++ b/chapter03/03-BalancedSymbols.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter03/03-BalancedSymbols.js b/chapter03/03-BalancedSymbols.js new file mode 100644 index 00000000..6a49ee6b --- /dev/null +++ b/chapter03/03-BalancedSymbols.js @@ -0,0 +1,37 @@ +function matches(open, close){ + var opens = "([{", + closers = ")]}"; + return opens.indexOf(open) == closers.indexOf(close); +} + +function parenthesesChecker(symbols){ + + var stack = new Stack(), + balanced = true, + index = 0, + symbol, top; + + while (index < symbols.length && balanced){ + symbol = symbols.charAt(index); + if (symbol == '('|| symbol == '[' || symbol == '{'){ + stack.push(symbol); + } else { + if (stack.isEmpty()){ + balanced = false; + } else { + top = stack.pop(); + if (!matches(top, symbol)){ + balanced = false; + } + } + } + index++; + } + if (balanced && stack.isEmpty()){ + return true; + } + return false; +} + +console.log(parenthesesChecker('{{([][])}()}')); +console.log(parenthesesChecker('[{()]')); \ No newline at end of file diff --git a/chapter03/04-DecimalToBinary.html b/chapter03/04-DecimalToBinary.html new file mode 100644 index 00000000..a178b773 --- /dev/null +++ b/chapter03/04-DecimalToBinary.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter03/04-DecimalToBinary.js b/chapter03/04-DecimalToBinary.js new file mode 100644 index 00000000..d4695b51 --- /dev/null +++ b/chapter03/04-DecimalToBinary.js @@ -0,0 +1,52 @@ +//233 == 11101001 +//2x(10x10) + 3x(10) + 3x(1) + +function divideBy2(decNumber){ + + var remStack = new Stack(), + rem, + binaryString = ''; + + while (decNumber > 0){ + rem = Math.floor(decNumber % 2); + remStack.push(rem); + decNumber = Math.floor(decNumber / 2); + } + + while (!remStack.isEmpty()){ + binaryString += remStack.pop().toString(); + } + + return binaryString; +} + +console.log(divideBy2(233)); +console.log(divideBy2(10)); +console.log(divideBy2(1000)); + +/* + The folow algorithm converts from base 10 to any base + */ +function baseConverter(decNumber, base){ + + var remStack = new Stack(), + rem, + baseString = '', + digits = '0123456789ABCDEF'; + + while (decNumber > 0){ + rem = Math.floor(decNumber % base); + remStack.push(rem); + decNumber = Math.floor(decNumber / base); + } + + while (!remStack.isEmpty()){ + baseString += digits[remStack.pop()]; + } + + return baseString; +} + +console.log(baseConverter(100345, 2)); +console.log(baseConverter(100345, 8)); +console.log(baseConverter(100345, 16)); \ No newline at end of file diff --git a/chapter03/05-TowerOfHanoi.html b/chapter03/05-TowerOfHanoi.html new file mode 100644 index 00000000..8e11f147 --- /dev/null +++ b/chapter03/05-TowerOfHanoi.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter03/05-TowerOfHanoi.js b/chapter03/05-TowerOfHanoi.js new file mode 100644 index 00000000..34205bc1 --- /dev/null +++ b/chapter03/05-TowerOfHanoi.js @@ -0,0 +1,26 @@ +function towerOfHanoi(n, from, to, helper){ + + if (n > 0){ + towerOfHanoi(n-1, from, helper, to); + to.push(from.pop()); + console.log('-----') + console.log('Source: ' + from.items.toString()); + console.log('Dest: ' + to.items.toString()); + console.log('Helper: ' + helper.items.toString()); + towerOfHanoi(n-1, helper, to, from); + } +} + +var source = new Stack(); +source.push(3); +source.push(2); +source.push(1); + +var dest = new Stack(); +var helper = new Stack(); + +towerOfHanoi(3, source, dest, helper); + +source.print(); +helper.print(); +dest.print(); \ No newline at end of file From 5cc6aa11b8f216554ea09f05853520ee2b17bb23 Mon Sep 17 00:00:00 2001 From: loiane Date: Tue, 24 Jun 2014 11:36:17 -0300 Subject: [PATCH 06/54] added chapter 04 --- chapter04/01-Queue.html | 10 +++++++ chapter04/01-Queue.js | 28 +++++++++++++++++ chapter04/02-UsingQueues.html | 11 +++++++ chapter04/02-UsingQueues.js | 12 ++++++++ chapter04/03-PriorityQueue.html | 10 +++++++ chapter04/03-PriorityQueue.js | 53 +++++++++++++++++++++++++++++++++ chapter04/04-HotPotato.html | 11 +++++++ chapter04/04-HotPotato.js | 23 ++++++++++++++ 8 files changed, 158 insertions(+) create mode 100644 chapter04/01-Queue.html create mode 100644 chapter04/01-Queue.js create mode 100644 chapter04/02-UsingQueues.html create mode 100644 chapter04/02-UsingQueues.js create mode 100644 chapter04/03-PriorityQueue.html create mode 100644 chapter04/03-PriorityQueue.js create mode 100644 chapter04/04-HotPotato.html create mode 100644 chapter04/04-HotPotato.js diff --git a/chapter04/01-Queue.html b/chapter04/01-Queue.html new file mode 100644 index 00000000..4220c419 --- /dev/null +++ b/chapter04/01-Queue.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter04/01-Queue.js b/chapter04/01-Queue.js new file mode 100644 index 00000000..6058724d --- /dev/null +++ b/chapter04/01-Queue.js @@ -0,0 +1,28 @@ +function Queue() { + + this.items = []; + + this.enqueue = function(element){ + this.items.push(element); + }; + + this.dequeue = function(){ + return this.items.shift(); + }; + + this.front = function(){ + return this.items[0]; + }; + + this.isEmpty = function(){ + return this.items.length == 0; + }; + + this.size = function(){ + return this.items.length; + }; + + this.print = function(){ + console.log(this.items.toString()); + }; +} diff --git a/chapter04/02-UsingQueues.html b/chapter04/02-UsingQueues.html new file mode 100644 index 00000000..c39e78b4 --- /dev/null +++ b/chapter04/02-UsingQueues.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter04/02-UsingQueues.js b/chapter04/02-UsingQueues.js new file mode 100644 index 00000000..fcef6c91 --- /dev/null +++ b/chapter04/02-UsingQueues.js @@ -0,0 +1,12 @@ +var queue = new Queue(); +console.log(queue.isEmpty()); //outputs true +queue.enqueue("John"); +queue.enqueue("Jack"); +queue.print(); +queue.enqueue("Camila"); +queue.print(); +console.log(queue.size()); //outputs 3 +console.log(queue.isEmpty()); //outputs false +queue.dequeue(); +queue.dequeue(); +queue.print(); \ No newline at end of file diff --git a/chapter04/03-PriorityQueue.html b/chapter04/03-PriorityQueue.html new file mode 100644 index 00000000..924bf7c4 --- /dev/null +++ b/chapter04/03-PriorityQueue.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter04/03-PriorityQueue.js b/chapter04/03-PriorityQueue.js new file mode 100644 index 00000000..be93eff7 --- /dev/null +++ b/chapter04/03-PriorityQueue.js @@ -0,0 +1,53 @@ +function PriorityQueue() { + + this.items = []; + + function QueueElement (element, priority){ + this.element = element; + this.priority = priority; + } + + this.enqueue = function(element, priority){ + var queueElement = new QueueElement(element, priority); + + if (this.isEmpty()){ + this.items.push(queueElement); + } else { + for (var i=0; i + + + + + + + + + + \ No newline at end of file diff --git a/chapter04/04-HotPotato.js b/chapter04/04-HotPotato.js new file mode 100644 index 00000000..83554a1c --- /dev/null +++ b/chapter04/04-HotPotato.js @@ -0,0 +1,23 @@ +function hotPotato (nameList, num){ + + var queue = new Queue(); + + for (var i=0; i 1){ + for (var i=0; i Date: Wed, 9 Jul 2014 14:53:37 -0300 Subject: [PATCH 07/54] added chapter 05 --- chapter05/01-Linked-List.js | 166 ++++++++++++++++++ chapter05/02-UsingLinkedLists.html | 11 ++ chapter05/02-UsingLinkedLists.js | 32 ++++ chapter05/03-Doubly-Linked-List.js | 212 +++++++++++++++++++++++ chapter05/04-UsingDoublyLinkedLists.html | 11 ++ chapter05/04-UsingDoublyLinkedLists.js | 49 ++++++ chapter05/05-CircularLinkedList.js | 0 chapter05/06-CircularDoublyLinkedList.js | 0 8 files changed, 481 insertions(+) create mode 100644 chapter05/01-Linked-List.js create mode 100644 chapter05/02-UsingLinkedLists.html create mode 100644 chapter05/02-UsingLinkedLists.js create mode 100644 chapter05/03-Doubly-Linked-List.js create mode 100644 chapter05/04-UsingDoublyLinkedLists.html create mode 100644 chapter05/04-UsingDoublyLinkedLists.js create mode 100644 chapter05/05-CircularLinkedList.js create mode 100644 chapter05/06-CircularDoublyLinkedList.js diff --git a/chapter05/01-Linked-List.js b/chapter05/01-Linked-List.js new file mode 100644 index 00000000..483e9f70 --- /dev/null +++ b/chapter05/01-Linked-List.js @@ -0,0 +1,166 @@ +function LinkedList() { + + var Node = function(element){ + + this.element = element; + this.next = null; + }; + + var length = 0; + var head = null; + + this.append = function(element){ + + var node = new Node(element), + current; + + if (head === null){ //first node on list + head = node; + } else { + + current = head; + + //loop the list until find last item + while(current.next){ + current = current.next; + } + + //get last item and assign next to added item to make the link + current.next = node; + } + + length++; //update size of list + }; + + this.insert = function(position, element){ + + //check for out-of-bounds values + if (position >= 0 && position <= length){ + + var node = new Node(element), + current = head, + previous, + index = 0; + + if (position === 0){ //add on first position + + node.next = current; + head = node; + + } else { + while (index++ < position){ + previous = current; + current = current.next; + } + node.next = current; + previous.next = node; + } + + length++; //update size of list + + return true; + + } else { + return false; + } + }; + + this.removeAt = function(position){ + + //check for out-of-bounds values + if (position > -1 && position < length){ + + var current = head, + previous, + index = 0; + + //removing first item + if (position === 0){ + head = current.next; + } else { + + while (index++ < position){ + + previous = current; + current = current.next; + } + + //link previous with current's next - skip it to remove + previous.next = current.next; + } + + length--; + + return current.element; + + } else { + return null; + } + }; + + this.remove = function(element){ + + var index = this.indexOf(element); + return this.removeAt(index); + }; + + this.indexOf = function(element){ + + var current = head, + index = -1; + + //check first item + if (element == current.element){ + return 0; + } + + index++; + + //check in the middle of the list + while(current.next){ + + if (element == current.element){ + return index; + } + + current = current.next; + index++; + } + + //check last item + if (element == current.element){ + return index; + } + + return -1; + }; + + this.isEmpty = function() { + return length === 0; + }; + + this.size = function() { + return length; + }; + + this.getHead = function(){ + return head; + }; + + this.toString = function(){ + + var current = head, + s = current.element; + + while(current.next){ + current = current.next; + s += ', ' + current.element; + } + + return s; + }; + + this.print = function(){ + console.log(this.toString()); + } +} \ No newline at end of file diff --git a/chapter05/02-UsingLinkedLists.html b/chapter05/02-UsingLinkedLists.html new file mode 100644 index 00000000..da977b75 --- /dev/null +++ b/chapter05/02-UsingLinkedLists.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter05/02-UsingLinkedLists.js b/chapter05/02-UsingLinkedLists.js new file mode 100644 index 00000000..9c92c483 --- /dev/null +++ b/chapter05/02-UsingLinkedLists.js @@ -0,0 +1,32 @@ +var list = new LinkedList(); +list.append(15); +list.print(); +console.log(list.indexOf(15)); +list.append(10); +list.print(); +console.log(list.indexOf(10)); +list.append(13); +list.print(); +console.log(list.indexOf(13)); +console.log(list.indexOf(10)); +list.append(11); +list.append(12); +list.print(); +console.log(list.removeAt(1)); +list.print() +console.log(list.removeAt(3)); +list.print(); +list.append(14); +list.print(); +list.insert(0,16); +list.print(); +list.insert(1,17); +list.print(); +list.insert(list.size(),18); +list.print(); +list.remove(16); +list.print(); +list.remove(11); +list.print(); +list.remove(18); +list.print(); \ No newline at end of file diff --git a/chapter05/03-Doubly-Linked-List.js b/chapter05/03-Doubly-Linked-List.js new file mode 100644 index 00000000..0197cb19 --- /dev/null +++ b/chapter05/03-Doubly-Linked-List.js @@ -0,0 +1,212 @@ +function DoublyLinkedList() { + + var Node = function(element){ + + this.element = element; + this.next = null; + this.prev = null; //NEW + }; + + var length = 0; + var head = null; + var tail = null; //NEW + + this.append = function(element){ + + var node = new Node(element), + current; + + if (head === null){ //first node on list + head = node; + tail = node; //NEW + } else { + + //attach to the tail node //NEW + tail.next = node; + node.prev = tail; + tail = node; + } + + length++; //update size of list + }; + + this.insert = function(position, element){ + + //check for out-of-bounds values + if (position >= 0 && position <= length){ + + var node = new Node(element), + current = head, + previous, + index = 0; + + if (position === 0){ //add on first position + + node.next = current; + current.prev = node; //NEW {1} + head = node; + + } else if (position === length-1) { //last item //NEW + + current = tail; // {2} + current.next = node; + node.prev = current; + tail = node; + + } else { + while (index++ < position){ //{3} + previous = current; + current = current.next; + } + node.next = current; + previous.next = node; + + current.prev = node; //NEW + node.prev = previous; //NEW + } + + length++; //update size of list + + return true; + + } else { + return false; + } + }; + + this.removeAt = function(position){ + + //check for out-of-bounds values + if (position > -1 && position < length){ + + var current = head, + previous, + index = 0; + + //removing first item + if (position === 0){ + + head = current.next; // {1} + + //if there is only one item, then we update tail as well //NEW + if (length === 1){ // {2} + tail = null; + } else { + head.prev = null; // {3} + } + + } else if (position === length-1){ //last item //NEW + + current = tail; // {4} + tail = current.prev; + tail.next = null; + + } else { + + while (index++ < position){ // {5} + + previous = current; + current = current.next; + } + + //link previous with current's next - skip it to remove + previous.next = current.next; // {6} + current.next.prev = previous; //NEW + } + + length--; + + return current.element; + + } else { + return null; + } + }; + + this.remove = function(element){ + + var index = this.indexOf(element); + return this.removeAt(index); + }; + + this.indexOf = function(element){ + + var current = head, + index = -1; + + //check first item + if (element == current.element){ + return 0; + } + + index++; + + //check in the middle of the list + while(current.next){ + + if (element == current.element){ + return index; + } + + current = current.next; + index++; + } + + //check last item + if (element == current.element){ + return index; + } + + return -1; + }; + + this.isEmpty = function() { + return length === 0; + }; + + this. size = function() { + return length; + }; + + this.toString = function(){ + + var current = head, + s = current ? current.element : ''; + + while(current && current.next){ + current = current.next; + s += ', ' + current.element; + } + + return s; + }; + + this.inverseToString = function() { + + var current = tail, + s = current ? current.element : ''; + + while(current && current.prev){ + current = current.prev; + s += ', ' + current.element; + } + + return s; + }; + + this.print = function(){ + console.log(this.toString()); + }; + + this.printInverse = function(){ + console.log(this.inverseToString()); + }; + + this.getHead = function(){ + return head; + }; + + this.getTail = function(){ + return tail; + } +} \ No newline at end of file diff --git a/chapter05/04-UsingDoublyLinkedLists.html b/chapter05/04-UsingDoublyLinkedLists.html new file mode 100644 index 00000000..d4b60521 --- /dev/null +++ b/chapter05/04-UsingDoublyLinkedLists.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter05/04-UsingDoublyLinkedLists.js b/chapter05/04-UsingDoublyLinkedLists.js new file mode 100644 index 00000000..31fba8e8 --- /dev/null +++ b/chapter05/04-UsingDoublyLinkedLists.js @@ -0,0 +1,49 @@ +var list = new DoublyLinkedList(); + +list.append(15); +list.print(); +list.printInverse(); + +list.append(16); +list.print(); +list.printInverse(); + +list.append(17); +list.print(); +list.printInverse(); + +list.insert(0,13); +list.print(); +list.printInverse(); + +list.insert(list.size()-1,18); +list.print(); +list.printInverse(); + +list.insert(1,14); +list.print(); +list.printInverse(); + +list.removeAt(0); +list.print(); +list.printInverse(); + +list.removeAt(list.size()-1); +list.print(); +list.printInverse(); + +list.removeAt(1); +list.print(); +list.printInverse(); + +list.remove(16); +list.print(); +list.printInverse(); + +list.remove(14); +list.print(); +list.printInverse(); + +list.remove(17); +list.print(); +list.printInverse(); \ No newline at end of file diff --git a/chapter05/05-CircularLinkedList.js b/chapter05/05-CircularLinkedList.js new file mode 100644 index 00000000..e69de29b diff --git a/chapter05/06-CircularDoublyLinkedList.js b/chapter05/06-CircularDoublyLinkedList.js new file mode 100644 index 00000000..e69de29b From 0a445ccf1f88b8b8419bb5c46319aedd4f5ff4a9 Mon Sep 17 00:00:00 2001 From: loiane Date: Wed, 9 Jul 2014 14:53:44 -0300 Subject: [PATCH 08/54] added chapter 06 --- chapter06/01-Set.js | 135 +++++++++++++++++++++++++++++++++++ chapter06/02-UsingSets.html | 11 +++ chapter06/02-UsingSets.js | 17 +++++ chapter06/03-Operations.html | 11 +++ chapter06/03-Operations.js | 64 +++++++++++++++++ 5 files changed, 238 insertions(+) create mode 100644 chapter06/01-Set.js create mode 100644 chapter06/02-UsingSets.html create mode 100644 chapter06/02-UsingSets.js create mode 100644 chapter06/03-Operations.html create mode 100644 chapter06/03-Operations.js diff --git a/chapter06/01-Set.js b/chapter06/01-Set.js new file mode 100644 index 00000000..7791c03d --- /dev/null +++ b/chapter06/01-Set.js @@ -0,0 +1,135 @@ +/** + * ECMSCRIPT 6 already have a Set class implementation: + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set + * We will try to copy the same functionalities + * @constructor + */ +function Set() { + + var items = {}; + + this.add = function(value){ + if (!this.has(value)){ + items[value] = value; + return true; + } + return false; + }; + + this.remove = function(value){ + if (this.has(value)){ + delete items[value]; + return true; + } + return false; + }; + + this.has = function(value){ + return value in items; + }; + + this.clear = function(){ + items = {}; + }; + + /** + * Modern browsers function + * IE9+, FF4+, Chrome5+, Opera12+, Safari5+ + * @returns {Number} + */ + this.size = function(){ + return Object.keys(items).length; + }; + + /** + * cross browser compatibility - legacy browsers + * for modern browsers use size function + * @returns {number} + */ + this.sizeLegacy = function(){ + var count = 0; + for(var prop in items) { + if(items.hasOwnProperty(prop)) + ++count; + } + return count; + }; + + /** + * Modern browsers function + * IE9+, FF4+, Chrome5+, Opera12+, Safari5+ + * @returns {Array} + */ + this.values = function(){ + return Object.keys(items); + }; + + this.valuesLegacy = function(){ + var keys = []; + for(var key in items){ + keys.push(key); + } + return keys; + }; + + this.getItems = function(){ + return items; + }; + + this.union = function(otherSet){ + var unionSet = new Set(); //{1} + + var values = this.values(); //{2} + for (var i=0; i otherSet.size()){ //{1} + return false; + } else { + var values = this.values(); + for (var i=0; i + + + + + + + + + + \ No newline at end of file diff --git a/chapter06/02-UsingSets.js b/chapter06/02-UsingSets.js new file mode 100644 index 00000000..ebdd0671 --- /dev/null +++ b/chapter06/02-UsingSets.js @@ -0,0 +1,17 @@ +var set = new Set(); + +set.add(1); +console.log(set.values()); //outputs ["1"] +console.log(set.has(1)); //outputs true +console.log(set.size()); //outputs 1 + +set.add(2); +console.log(set.values()); //outputs ["1", "2"] +console.log(set.has(2)); //true +console.log(set.size()); //2 + +set.remove(1); +console.log(set.values()); //outputs ["2"] + +set.remove(2); +console.log(set.values()); //outputs [] \ No newline at end of file diff --git a/chapter06/03-Operations.html b/chapter06/03-Operations.html new file mode 100644 index 00000000..ff01c7ae --- /dev/null +++ b/chapter06/03-Operations.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter06/03-Operations.js b/chapter06/03-Operations.js new file mode 100644 index 00000000..571e34a4 --- /dev/null +++ b/chapter06/03-Operations.js @@ -0,0 +1,64 @@ +//--------- Union ---------- + +var setA = new Set(); +setA.add(1); +setA.add(2); +setA.add(3); + +var setB = new Set(); +setB.add(4); +setB.add(5); +setB.add(6); + +var unionAB = setA.union(setB); +console.log(unionAB.values()); + + +//--------- Intersection ---------- + +var setA = new Set(); +setA.add(1); +setA.add(2); +setA.add(3); + +var setB = new Set(); +setB.add(2); +setB.add(3); +setB.add(4); + +var intersectionAB = setA.intersection(setB); +console.log(intersectionAB.values()); + +//--------- Difference ---------- + +var setA = new Set(); +setA.add(1); +setA.add(2); +setA.add(3); + +var setB = new Set(); +setB.add(2); +setB.add(3); +setB.add(4); + +var differenceAB = setA.difference(setB); +console.log(differenceAB.values()); + +//--------- Subset ---------- + +var setA = new Set(); +setA.add(1); +setA.add(2); + +var setB = new Set(); +setB.add(1); +setB.add(2); +setB.add(3); + +var setC = new Set(); +setC.add(2); +setC.add(3); +setC.add(4); + +console.log(setA.subset(setB)); +console.log(setA.subset(setC)); From 66b57b4bbd7e7259e1045f5d40489c0074b322e5 Mon Sep 17 00:00:00 2001 From: loiane Date: Mon, 14 Jul 2014 14:09:11 -0300 Subject: [PATCH 09/54] added chapter 7 --- chapter07/01-Dictionaries.js | 58 +++++++++++ chapter07/02-UsingDictionaries.html | 11 +++ chapter07/02-UsingDictionaries.js | 19 ++++ chapter07/03-HashTable.js | 46 +++++++++ chapter07/04-UsingHash.html | 11 +++ chapter07/04-UsingHash.js | 29 ++++++ chapter07/05-HashCollisionSeparateChaining.js | 99 +++++++++++++++++++ ...06-UsingHashCollisionSeparateChaining.html | 12 +++ .../06-UsingHashCollisionSeparateChaining.js | 40 ++++++++ chapter07/07-HashCollisionLinearProbing.js | 85 ++++++++++++++++ .../08-UsingHashCollisionLinearProbing.html | 11 +++ .../08-UsingHashCollisionLinearProbing.js | 29 ++++++ 12 files changed, 450 insertions(+) create mode 100644 chapter07/01-Dictionaries.js create mode 100644 chapter07/02-UsingDictionaries.html create mode 100644 chapter07/02-UsingDictionaries.js create mode 100644 chapter07/03-HashTable.js create mode 100644 chapter07/04-UsingHash.html create mode 100644 chapter07/04-UsingHash.js create mode 100644 chapter07/05-HashCollisionSeparateChaining.js create mode 100644 chapter07/06-UsingHashCollisionSeparateChaining.html create mode 100644 chapter07/06-UsingHashCollisionSeparateChaining.js create mode 100644 chapter07/07-HashCollisionLinearProbing.js create mode 100644 chapter07/08-UsingHashCollisionLinearProbing.html create mode 100644 chapter07/08-UsingHashCollisionLinearProbing.js diff --git a/chapter07/01-Dictionaries.js b/chapter07/01-Dictionaries.js new file mode 100644 index 00000000..4f102099 --- /dev/null +++ b/chapter07/01-Dictionaries.js @@ -0,0 +1,58 @@ +function Dictionary(){ + + var items = {}; + + this.set = function(key, value){ + items[key] = value; //{1} + }; + + this.remove = function(key){ + if (this.has(key)){ + delete items[key]; + return true; + } + return false; + }; + + this.has = function(key){ + return key in items; + }; + + this.get = function(key) { + return this.has(key) ? items[key] : undefined; + }; + + this.clear = function(){ + items = {}; + }; + + this.size = function(){ + return Object.keys(items).length; + }; + + this.keys = function(){ + return Object.keys(items); + }; + + this.values = function(){ + var values = []; + for (var k in items) { + if (this.has(k)) { + values.push(items[k]); + } + } + return values; + }; + + this.each = function(fn) { + for (var k in items) { + if (this.has(k)) { + fn(k, items[k]); + } + } + }; + + this.getItems = function(){ + return items; + } +} \ No newline at end of file diff --git a/chapter07/02-UsingDictionaries.html b/chapter07/02-UsingDictionaries.html new file mode 100644 index 00000000..f0f8e0eb --- /dev/null +++ b/chapter07/02-UsingDictionaries.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter07/02-UsingDictionaries.js b/chapter07/02-UsingDictionaries.js new file mode 100644 index 00000000..3fc4db6f --- /dev/null +++ b/chapter07/02-UsingDictionaries.js @@ -0,0 +1,19 @@ +var dictionary = new Dictionary(); + +dictionary.set('Gandalf', 'gandalf@email.com'); +dictionary.set('John', 'johnsnow@email.com'); +dictionary.set('Tyrion', 'tyrion@email.com'); + +console.log(dictionary.has('Gandalf')); //outputs true +console.log(dictionary.size()); //outputs 3 + +console.log(dictionary.keys()); //outputs ["Gandalf", "John", "Tyrion"] +console.log(dictionary.values()); //outputs ["gandalf@email.com", "johnsnow@email.com", "tyrion@email.com"] +console.log(dictionary.get('Tyrion')); //outputs tyrion@email.com + +dictionary.remove('John'); + +console.log(dictionary.keys()); //outputs ["Gandalf", "Tyrion"] +console.log(dictionary.values()); //outputs ["gandalf@email.com", "tyrion@email.com"] + +console.log(dictionary.getItems()); //Object {Gandalf: "gandalf@email.com", Tyrion: "tyrion@email.com"} \ No newline at end of file diff --git a/chapter07/03-HashTable.js b/chapter07/03-HashTable.js new file mode 100644 index 00000000..c72783aa --- /dev/null +++ b/chapter07/03-HashTable.js @@ -0,0 +1,46 @@ +function HashTable() { + + var table = []; + + var loseloseHashCode = function (key) { + var hash = 0; + for (var i = 0; i < key.length; i++) { + hash += key.charCodeAt(i); + } + return hash % 37; + }; + + var djb2HashCode = function (key) { + var hash = 5381; + for (var i = 0; i < key.length; i++) { + hash = hash * 33 + key.charCodeAt(i); + } + return hash % 1013; + }; + + var hashCode = function (key) { + return loseloseHashCode(key); + }; + + this.put = function (key, value) { + var position = hashCode(key); + console.log(position + ' - ' + key); + table[position] = value; + }; + + this.get = function (key) { + return table[hashCode(key)]; + }; + + this.remove = function(key){ + table[hashCode(key)] = undefined; + }; + + this.print = function () { + for (var i = 0; i < table.length; ++i) { + if (table[i] !== undefined) { + console.log(i + ": " + table[i]); + } + } + }; +} \ No newline at end of file diff --git a/chapter07/04-UsingHash.html b/chapter07/04-UsingHash.html new file mode 100644 index 00000000..104be603 --- /dev/null +++ b/chapter07/04-UsingHash.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter07/04-UsingHash.js b/chapter07/04-UsingHash.js new file mode 100644 index 00000000..d0735eeb --- /dev/null +++ b/chapter07/04-UsingHash.js @@ -0,0 +1,29 @@ +var hash = new HashTable(); + +hash.put('Gandalf', 'gandalf@email.com'); +hash.put('John', 'johnsnow@email.com'); +hash.put('Tyrion', 'tyrion@email.com'); +hash.put('Aaron', 'aaron@email.com'); +hash.put('Donnie', 'donnie@email.com'); +hash.put('Ana', 'ana@email.com'); +hash.put('Jonathan', 'jonathan@email.com'); +hash.put('Jamie', 'jamie@email.com'); +hash.put('Sue', 'sue@email.com'); +hash.put('Mindy', 'mindy@email.com'); +hash.put('Paul', 'paul@email.com'); +hash.put('Nathan', 'nathan@email.com'); + +console.log('**** Printing Hash **** '); + +hash.print(); + +console.log('**** Get **** '); + +console.log(hash.get('Gandalf')); +console.log(hash.get('Loiane')); + +console.log('**** Remove **** '); + +hash.remove('Gandalf'); +console.log(hash.get('Gandalf')); +hash.print(); \ No newline at end of file diff --git a/chapter07/05-HashCollisionSeparateChaining.js b/chapter07/05-HashCollisionSeparateChaining.js new file mode 100644 index 00000000..f32833cf --- /dev/null +++ b/chapter07/05-HashCollisionSeparateChaining.js @@ -0,0 +1,99 @@ +function HashTableSeparateChaining(){ + + var table = []; + + var ValuePair = function(key, value){ + this.key = key; + this.value = value; + + this.toString = function() { + return '[' + this.key + ' - ' + this.value + ']'; + } + }; + + var loseloseHashCode = function (key) { + var hash = 0; + for (var i = 0; i < key.length; i++) { + hash += key.charCodeAt(i); + } + return hash % 37; + }; + + var hashCode = function(key){ + return loseloseHashCode(key); + }; + + this.put = function(key, value){ + var position = hashCode(key); + console.log(position + ' - ' + key); + + if (table[position] == undefined) { + table[position] = new LinkedList(); + } + table[position].append(new ValuePair(key, value)); + }; + + this.get = function(key) { + var position = hashCode(key); + + if (table[position] !== undefined && !table[position].isEmpty()){ + + //iterate linked list to find key/value + var current = table[position].getHead(); + + while(current.next){ + if (current.element.key === key){ + return current.element.value; + } + current = current.next; + } + + //check in case first or last element + if (current.element.key === key){ + return current.element.value; + } + } + return undefined; + }; + + this.remove = function(key){ + + var position = hashCode(key); + + if (table[position] !== undefined){ + + //iterate linked list to find key/value + var current = table[position].getHead(); + + while(current.next){ + if (current.element.key === key){ + table[position].remove(current.element); + if (table[position].isEmpty()){ + table[position] = undefined; + } + return true; + } + current = current.next; + } + + //check in case first or last element + if (current.element.key === key){ + table[position].remove(current.element); + if (table[position].isEmpty()){ + table[position] = undefined; + } + return true; + } + } + + return false; + }; + + this.print = function() { + for (var i = 0; i < table.length; ++i) { + if (table[i] !== undefined) { + console.log(table[i].toString()); + } + } + }; +} \ No newline at end of file diff --git a/chapter07/06-UsingHashCollisionSeparateChaining.html b/chapter07/06-UsingHashCollisionSeparateChaining.html new file mode 100644 index 00000000..e1741527 --- /dev/null +++ b/chapter07/06-UsingHashCollisionSeparateChaining.html @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/chapter07/06-UsingHashCollisionSeparateChaining.js b/chapter07/06-UsingHashCollisionSeparateChaining.js new file mode 100644 index 00000000..2a0d3c37 --- /dev/null +++ b/chapter07/06-UsingHashCollisionSeparateChaining.js @@ -0,0 +1,40 @@ +var hashTableSeparateChaining = new HashTableSeparateChaining(); + +hashTableSeparateChaining.put('Gandalf', 'gandalf@email.com'); +hashTableSeparateChaining.put('John', 'johnsnow@email.com'); +hashTableSeparateChaining.put('Tyrion', 'tyrion@email.com'); +hashTableSeparateChaining.put('Aaron', 'aaron@email.com'); +hashTableSeparateChaining.put('Donnie', 'donnie@email.com'); +hashTableSeparateChaining.put('Ana', 'ana@email.com'); +hashTableSeparateChaining.put('Jonathan', 'jonathan@email.com'); +hashTableSeparateChaining.put('Jamie', 'jamie@email.com'); +hashTableSeparateChaining.put('Sue', 'sue@email.com'); +hashTableSeparateChaining.put('Mindy', 'mindy@email.com'); +hashTableSeparateChaining.put('Paul', 'paul@email.com'); +hashTableSeparateChaining.put('Nathan', 'nathan@email.com'); + +console.log('**** Printing Hash **** '); + +hashTableSeparateChaining.print(); + +console.log('**** Get **** '); + +console.log(hashTableSeparateChaining.get('Jamie')); +console.log(hashTableSeparateChaining.get('Sue')); +console.log(hashTableSeparateChaining.get('Jonathan')); +console.log(hashTableSeparateChaining.get('Loiane')); + +console.log('**** Remove **** '); + +console.log(hashTableSeparateChaining.remove('Gandalf')); +console.log(hashTableSeparateChaining.get('Gandalf')); +hashTableSeparateChaining.print(); + +console.log(hashTableSeparateChaining.remove('Sue')); +hashTableSeparateChaining.print(); + +console.log(hashTableSeparateChaining.remove('Jamie')); +hashTableSeparateChaining.print(); + +console.log(hashTableSeparateChaining.remove('Donnie')); +hashTableSeparateChaining.print(); \ No newline at end of file diff --git a/chapter07/07-HashCollisionLinearProbing.js b/chapter07/07-HashCollisionLinearProbing.js new file mode 100644 index 00000000..74fdbac5 --- /dev/null +++ b/chapter07/07-HashCollisionLinearProbing.js @@ -0,0 +1,85 @@ +function HashLinearProbing(){ + + var table = []; + + var ValuePair = function(key, value){ + this.key = key; + this.value = value; + + this.toString = function() { + return '[' + this.key + ' - ' + this.value + ']'; + } + }; + + var loseloseHashCode = function (key) { + var hash = 0; + for (var i = 0; i < key.length; i++) { + hash += key.charCodeAt(i); + } + return hash % 37; + }; + + var hashCode = function(key){ + return loseloseHashCode(key); + }; + + this.put = function(key, value){ + var position = hashCode(key); + console.log(position + ' - ' + key); + + if (table[position] == undefined) { + table[position] = new ValuePair(key, value); + } else { + var index = ++position; + while (table[index] != undefined){ + index++; + } + table[index] = new ValuePair(key, value); + } + }; + + this.get = function(key) { + var position = hashCode(key); + + if (table[position] !== undefined){ + if (table[position].key === key) { + return table[position].value; + } else { + var index = ++position; + while (table[index] === undefined || table[index].key !== key){ + index++; + } + if (table[index].key === key) { + return table[index].value; + } + } + } + return undefined; + }; + + this.remove = function(key){ + var position = hashCode(key); + + if (table[position] !== undefined){ + if (table[position].key === key) { + table[position] = undefined; + } else { + var index = ++position; + while (table[index] === undefined || table[index].key !== key){ + index++; + } + if (table[index].key === key) { + table[index] = undefined; + } + } + } + }; + + this.print = function() { + for (var i = 0; i < table.length; ++i) { + if (table[i] !== undefined) { + console.log(i + ' -> ' + table[i].toString()); + } + } + }; +} \ No newline at end of file diff --git a/chapter07/08-UsingHashCollisionLinearProbing.html b/chapter07/08-UsingHashCollisionLinearProbing.html new file mode 100644 index 00000000..f5fd9ad5 --- /dev/null +++ b/chapter07/08-UsingHashCollisionLinearProbing.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter07/08-UsingHashCollisionLinearProbing.js b/chapter07/08-UsingHashCollisionLinearProbing.js new file mode 100644 index 00000000..902384ee --- /dev/null +++ b/chapter07/08-UsingHashCollisionLinearProbing.js @@ -0,0 +1,29 @@ +var hashLinearProbing = new HashLinearProbing(); + +hashLinearProbing.put('Gandalf', 'gandalf@email.com'); +hashLinearProbing.put('John', 'johnsnow@email.com'); +hashLinearProbing.put('Tyrion', 'tyrion@email.com'); +hashLinearProbing.put('Aaron', 'aaron@email.com'); +hashLinearProbing.put('Donnie', 'donnie@email.com'); +hashLinearProbing.put('Ana', 'ana@email.com'); +hashLinearProbing.put('Jonathan', 'jonathan@email.com'); +hashLinearProbing.put('Jamie', 'jamie@email.com'); +hashLinearProbing.put('Sue', 'sue@email.com'); +hashLinearProbing.put('Mindy', 'mindy@email.com'); +hashLinearProbing.put('Paul', 'paul@email.com'); +hashLinearProbing.put('Nathan', 'nathan@email.com'); + +console.log('**** Printing Hash **** '); + +hashLinearProbing.print(); + +console.log('**** Get **** '); + +console.log(hashLinearProbing.get('Nathan')); +console.log(hashLinearProbing.get('Loiane')); + +console.log('**** Remove **** '); + +hashLinearProbing.remove('Gandalf'); +console.log(hashLinearProbing.get('Gandalf')); +hashLinearProbing.print(); \ No newline at end of file From aea3084d37e35af79c445774e95edeed4ca05f1f Mon Sep 17 00:00:00 2001 From: loiane Date: Mon, 14 Jul 2014 14:09:44 -0300 Subject: [PATCH 10/54] small fixes applied to code - chap 5 --- chapter05/01-Linked-List.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chapter05/01-Linked-List.js b/chapter05/01-Linked-List.js index 483e9f70..be63c981 100644 --- a/chapter05/01-Linked-List.js +++ b/chapter05/01-Linked-List.js @@ -149,7 +149,7 @@ function LinkedList() { this.toString = function(){ - var current = head, + var current = head, s = current.element; while(current.next){ @@ -157,10 +157,10 @@ function LinkedList() { s += ', ' + current.element; } - return s; + return s.toString(); }; this.print = function(){ console.log(this.toString()); - } + }; } \ No newline at end of file From d0f7bbfccef2796bb3f9e5efb7c9757b0f194d44 Mon Sep 17 00:00:00 2001 From: loiane Date: Thu, 24 Jul 2014 11:25:21 -0300 Subject: [PATCH 11/54] added chapter 08 --- chapter08.zip | Bin 0 -> 2596 bytes chapter08/01-BinarySearchTree.js | 181 ++++++++++++++++++++++++ chapter08/02-UsingBinarySearchTree.html | 11 ++ chapter08/02-UsingBinarySearchTree.js | 52 +++++++ chapter08/03-AVLTree.js | 0 chapter08/04-UsingAVLTree.html | 11 ++ chapter08/04-UsingAVLTree.js | 0 7 files changed, 255 insertions(+) create mode 100644 chapter08.zip create mode 100644 chapter08/01-BinarySearchTree.js create mode 100644 chapter08/02-UsingBinarySearchTree.html create mode 100644 chapter08/02-UsingBinarySearchTree.js create mode 100644 chapter08/03-AVLTree.js create mode 100644 chapter08/04-UsingAVLTree.html create mode 100644 chapter08/04-UsingAVLTree.js diff --git a/chapter08.zip b/chapter08.zip new file mode 100644 index 0000000000000000000000000000000000000000..b46214def3ca36afb913311088f6f53986269dac GIT binary patch literal 2596 zcma)7c|4Ts9)GPfO=CMGr>3~bHii*t4wA7XP390rhGYpd*(pmXu55)cTC7n+%$Uxx zjIDICWIL0H%CTk7iH@>msoa?+*Nl5RpYuMS=Y8LQp6_pYzQ6C+0>j4-0a#D$-38;X zKi^&uKooE#IQyM*3qYdOZB9Y~lpVt=(Sl*M$YTLmFwaQl{)8VMz3G z4hXe!a}IDNSO>VdshthnK%*aJqt)5A`Sc@2>(=1C7$-g=wBPi=p@kty!aQGz)|G@- z>tkI((8hJgD_PZTY1w%?;7a$Atb>~4zYcU~lQQr4UUmsu6}mOiuPBH-oj30l+Z6a1 z`nhPk!L_2EzWJRfM8}Cf{cubs=z|#{K6vudFL~pJ1|My99F+sor>-X3C_bn;W$Z~^Wm5pnY=e4O7_sYNL7S&@9n2w0_;X9Aa$PPiYbr=o=I zdFN_CS*%@FYasbe!{Jjun0p5QLX%9kYclj0i#`5iJ*=F&~BE8YllN@@vC zroI*FI6Z(}q~{ppCs0}2P&!63s7nnWpvqDYRki?jOnRw*>Yb$zHf3!7+zF0A< zHb<_tJ3;9At0*5UoV3YbqUL5zjWZv!%^vobP2++3S>Ukt3SPHS!h9d-vJIe3rJ#y!F5v z`k}Q`K>xhg`<8X5v&cCA+3{g)zHkfn(wea%pZQZs_lcpEhTTey1&fmYjeU)B@ozk9 z23+v*$9iSLyo-tGz8<5o?a=NeN* z?s40Xun8pkc>K@I5zcvgZA_hBM*G(pPP(Qc+<=6de9V;%QRh*JmFE+{r4T?zNO*Z0 zdrFhx!jd(aF+5@RWr;+ST(h!td>^|n%BVt`&eZI? zd&Z^k4Bo2B^bj^)dpSzr8XwW=LaEpLgyQY8f>dXENARN-q$4=`yqgSOTTH=Y*IIX3 z8+B@JP5pYd2U!rpH;o7G#k1_ORL8=BB8Of5s=rJ zSQpvoq=w5W)v{6iVNpekN60TT(kfgHAL^2->l^{(aVMrvID#$kiQNn zKe&i?D}QB|VzNK!PN9C!c;|(Gxmg6oz;FDnAs%wEe$Mm8Jy=MG05(NV&0)WDMa!_7 zoc<)aCe*z(gEub5Ee?!c1saAf%6A z!KFTZVR-s)K45K6mMO|&Y;Qm#_eLtMzA{Sljl8PQuJ(< za^-{IIkoT~6W5^4>rOIZd&Xa@_CNwAcA$Kz4BH^z!KFups4ss=y)JpI$hsZb=hGlv z9sua!XWtInI$YzpEnp}2?PwyO))n9S}~*p@P3 ze_JM-z_rW*S)1K39^M^%-?MBeGuGF~;2oOv069#G{(}Il4sY$u z_gKx@8C^jxcy5k^fensx=F4I@Cn@%F node.key){ + return searchNode(node.right, key); + + } else { //element is equal to node.item + return true; + } + }; + + this.inOrderTraverse = function(callback){ + inOrderTraverseNode(root, callback); + }; + + var inOrderTraverseNode = function (node, callback) { + if (node !== null) { + inOrderTraverseNode(node.left, callback); + callback(node.key); + inOrderTraverseNode(node.right, callback); + } + }; + + this.preOrderTraverse = function(callback){ + preOrderTraverseNode(root, callback); + }; + + var preOrderTraverseNode = function (node, callback) { + if (node !== null) { + callback(node.key); + preOrderTraverseNode(node.left, callback); + preOrderTraverseNode(node.right, callback); + } + }; + + this.postOrderTraverse = function(callback){ + postOrderTraverseNode(root, callback); + }; + + var postOrderTraverseNode = function (node, callback) { + if (node !== null) { + postOrderTraverseNode(node.left, callback); + postOrderTraverseNode(node.right, callback); + callback(node.key); + } + }; + + this.min = function() { + return minNode(root); + }; + + var minNode = function (node) { + while (node && node.left !== null) { + node = node.left; + } + + return node.key; + }; + + this.max = function() { + return maxNode(root); + }; + + var maxNode = function (node) { + while (node && node.right !== null) { + node = node.right; + } + + return node.key; + }; + + this.remove = function(element){ + root = removeNode(root, element); + }; + + var findMinNode = function(node){ + while (node && node.left !== null) { + node = node.left; + } + + return node; + }; + + var removeNode = function(node, element){ + + if (node === null){ + return null; + } + + if (element < node.key){ + node.left = removeNode(node.left, element); + return node; + + } else if (element > node.key){ + node.right = removeNode(node.right, element); + return node; + + } else { //element is equal to node.item + + //handle 3 special conditions + //1 - a leaf node + //2 - a node with only 1 child + //3 - a node with 2 children + + //case 1 + if (node.left === null && node.right === null){ + node = null; + return node; + } + + //case 2 + if (node.left === null){ + node = node.right; + return node; + + } else if (node.right === null){ + node = node.left; + return node; + } + + //case 3 + var aux = findMinNode(node.right); + node.key = aux.key; + node.right = removeNode(node.right, aux.key); + return node; + } + }; +} \ No newline at end of file diff --git a/chapter08/02-UsingBinarySearchTree.html b/chapter08/02-UsingBinarySearchTree.html new file mode 100644 index 00000000..ed25a2c4 --- /dev/null +++ b/chapter08/02-UsingBinarySearchTree.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter08/02-UsingBinarySearchTree.js b/chapter08/02-UsingBinarySearchTree.js new file mode 100644 index 00000000..3caef17c --- /dev/null +++ b/chapter08/02-UsingBinarySearchTree.js @@ -0,0 +1,52 @@ +var tree = new BinarySearchTree(); + +tree.insert(11); +tree.insert(7); +tree.insert(15); +tree.insert(5); +tree.insert(3); +tree.insert(9); +tree.insert(8); +tree.insert(10); +tree.insert(13); +tree.insert(12); +tree.insert(14); +tree.insert(20); +tree.insert(18); +tree.insert(25); +tree.insert(6); + +console.log('********* in-order transverse ***********'); +function printNode(value){ + console.log(value); +} +tree.inOrderTraverse(printNode); + +console.log('********* pre-order transverse ***********'); +tree.preOrderTraverse(printNode); + +console.log('********* post-order transverse ***********'); +tree.postOrderTraverse(printNode); + + +console.log('********* max and min ***********'); +console.log(tree.max()); +console.log(tree.min()); +console.log(tree.search(1) ? 'Key 1 found.' : 'Key 1 not found.'); +console.log(tree.search(8) ? 'Key 8 found.' : 'Key 8 not found.'); + + +console.log('********* remove 6 ***********'); +tree.remove(6); +tree.inOrderTraverse(printNode); + +console.log('********* remove 5 ***********'); +tree.remove(5); +tree.inOrderTraverse(printNode); + +console.log('********* remove 15 ***********'); +tree.remove(15); +tree.inOrderTraverse(printNode); + +console.log('********* raw data structure ***********'); +console.log(tree.getRoot()); \ No newline at end of file diff --git a/chapter08/03-AVLTree.js b/chapter08/03-AVLTree.js new file mode 100644 index 00000000..e69de29b diff --git a/chapter08/04-UsingAVLTree.html b/chapter08/04-UsingAVLTree.html new file mode 100644 index 00000000..f7ce18b0 --- /dev/null +++ b/chapter08/04-UsingAVLTree.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter08/04-UsingAVLTree.js b/chapter08/04-UsingAVLTree.js new file mode 100644 index 00000000..e69de29b From fa3a0779295801db2315772e8938b3c2d0e11f19 Mon Sep 17 00:00:00 2001 From: loiane Date: Wed, 30 Jul 2014 20:44:08 -0300 Subject: [PATCH 12/54] added chapter 09 --- chapter08.zip | Bin 2596 -> 0 bytes chapter09/01-Graph.js | 172 ++++++++++++++++++++++++++++++++++ chapter09/02-UsingGraphs.html | 14 +++ chapter09/02-UsingGraphs.js | 97 +++++++++++++++++++ 4 files changed, 283 insertions(+) delete mode 100644 chapter08.zip create mode 100644 chapter09/01-Graph.js create mode 100644 chapter09/02-UsingGraphs.html create mode 100644 chapter09/02-UsingGraphs.js diff --git a/chapter08.zip b/chapter08.zip deleted file mode 100644 index b46214def3ca36afb913311088f6f53986269dac..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 2596 zcma)7c|4Ts9)GPfO=CMGr>3~bHii*t4wA7XP390rhGYpd*(pmXu55)cTC7n+%$Uxx zjIDICWIL0H%CTk7iH@>msoa?+*Nl5RpYuMS=Y8LQp6_pYzQ6C+0>j4-0a#D$-38;X zKi^&uKooE#IQyM*3qYdOZB9Y~lpVt=(Sl*M$YTLmFwaQl{)8VMz3G z4hXe!a}IDNSO>VdshthnK%*aJqt)5A`Sc@2>(=1C7$-g=wBPi=p@kty!aQGz)|G@- z>tkI((8hJgD_PZTY1w%?;7a$Atb>~4zYcU~lQQr4UUmsu6}mOiuPBH-oj30l+Z6a1 z`nhPk!L_2EzWJRfM8}Cf{cubs=z|#{K6vudFL~pJ1|My99F+sor>-X3C_bn;W$Z~^Wm5pnY=e4O7_sYNL7S&@9n2w0_;X9Aa$PPiYbr=o=I zdFN_CS*%@FYasbe!{Jjun0p5QLX%9kYclj0i#`5iJ*=F&~BE8YllN@@vC zroI*FI6Z(}q~{ppCs0}2P&!63s7nnWpvqDYRki?jOnRw*>Yb$zHf3!7+zF0A< zHb<_tJ3;9At0*5UoV3YbqUL5zjWZv!%^vobP2++3S>Ukt3SPHS!h9d-vJIe3rJ#y!F5v z`k}Q`K>xhg`<8X5v&cCA+3{g)zHkfn(wea%pZQZs_lcpEhTTey1&fmYjeU)B@ozk9 z23+v*$9iSLyo-tGz8<5o?a=NeN* z?s40Xun8pkc>K@I5zcvgZA_hBM*G(pPP(Qc+<=6de9V;%QRh*JmFE+{r4T?zNO*Z0 zdrFhx!jd(aF+5@RWr;+ST(h!td>^|n%BVt`&eZI? zd&Z^k4Bo2B^bj^)dpSzr8XwW=LaEpLgyQY8f>dXENARN-q$4=`yqgSOTTH=Y*IIX3 z8+B@JP5pYd2U!rpH;o7G#k1_ORL8=BB8Of5s=rJ zSQpvoq=w5W)v{6iVNpekN60TT(kfgHAL^2->l^{(aVMrvID#$kiQNn zKe&i?D}QB|VzNK!PN9C!c;|(Gxmg6oz;FDnAs%wEe$Mm8Jy=MG05(NV&0)WDMa!_7 zoc<)aCe*z(gEub5Ee?!c1saAf%6A z!KFTZVR-s)K45K6mMO|&Y;Qm#_eLtMzA{Sljl8PQuJ(< za^-{IIkoT~6W5^4>rOIZd&Xa@_CNwAcA$Kz4BH^z!KFups4ss=y)JpI$hsZb=hGlv z9sua!XWtInI$YzpEnp}2?PwyO))n9S}~*p@P3 ze_JM-z_rW*S)1K39^M^%-?MBeGuGF~;2oOv069#G{(}Il4sY$u z_gKx@8C^jxcy5k^fensx=F4I@Cn@%F '; + var neighbors = adjList.get(vertices[i]); + for (var j=0; j + + + + + + + + + + + + + \ No newline at end of file diff --git a/chapter09/02-UsingGraphs.js b/chapter09/02-UsingGraphs.js new file mode 100644 index 00000000..3f143525 --- /dev/null +++ b/chapter09/02-UsingGraphs.js @@ -0,0 +1,97 @@ +var graph = new Graph(); + +var myVertices = ['A','B','C','D','E','F','G','H','I']; + +for (var i=0; i max){ + max = fTimes[myVertices[i]]; + maxName = myVertices[i]; + } + } + s += ' - ' + maxName; + delete fTimes[maxName]; +} +console.log(s); From 3e0fde17683ca5923a2689368290ead4526061a7 Mon Sep 17 00:00:00 2001 From: loiane Date: Fri, 8 Aug 2014 09:59:57 -0300 Subject: [PATCH 13/54] added missing code to chapter 5 --- chapter05/05-CircularLinkedList.js | 187 ++++++++++++++++++++++ chapter05/06-CircularDoublyLinkedList.js | 0 chapter05/06-UsingCircularLinkedList.html | 11 ++ chapter05/06-UsingCircularLinkedList.js | 28 ++++ 4 files changed, 226 insertions(+) delete mode 100644 chapter05/06-CircularDoublyLinkedList.js create mode 100644 chapter05/06-UsingCircularLinkedList.html create mode 100644 chapter05/06-UsingCircularLinkedList.js diff --git a/chapter05/05-CircularLinkedList.js b/chapter05/05-CircularLinkedList.js index e69de29b..590c08f4 100644 --- a/chapter05/05-CircularLinkedList.js +++ b/chapter05/05-CircularLinkedList.js @@ -0,0 +1,187 @@ +function CircularLinkedList() { + + var Node = function(element){ + + this.element = element; + this.next = null; + }; + + var length = 0; + var head = null; + + this.append = function(element){ + + var node = new Node(element), + current; + + if (head === null){ //first node on list + head = node; + } else { + + current = head; + + //loop the list until find last item + while(current.next !== head){ //last element will be head instead of NULL + current = current.next; + } + + //get last item and assign next to added item to make the link + current.next = node; + } + + //set node.next to head - to have circular list + node.next = head; + + length++; //update size of list + }; + + this.insert = function(position, element){ + + //check for out-of-bounds values + if (position >= 0 && position <= length){ + + var node = new Node(element), + current = head, + previous, + index = 0; + + if (position === 0){ //add on first position + + node.next = current; + + //update last element + while(current.next !== head){ //last element will be head instead of NULL + current = current.next; + } + + head = node; + current.next = head; + + } else { + while (index++ < position){ + previous = current; + current = current.next; + } + node.next = current; + previous.next = node; + + if (node.next === null){ //update in case last element + node.next = head; + } + } + + length++; //update size of list + + return true; + + } else { + return false; + } + }; + + this.removeAt = function(position){ + + //check for out-of-bounds values + if (position > -1 && position < length){ + + var current = head, + previous, + index = 0; + + //removing first item + if (position === 0){ + + while(current.next !== head){ //needs to update last element first + current = current.next; + } + + head = head.next; + current.next = head; + + } else { //no need to update last element for circular list + + while (index++ < position){ + + previous = current; + current = current.next; + } + + //link previous with current's next - skip it to remove + previous.next = current.next; + } + + length--; + + return current.element; + + } else { + return null; + } + }; + + this.remove = function(element){ + + var index = this.indexOf(element); + return this.removeAt(index); + }; + + this.indexOf = function(element){ + + var current = head, + index = -1; + + //check first item + if (element == current.element){ + return 0; + } + + index++; + + //check in the middle of the list + while(current.next !== head){ + + if (element == current.element){ + return index; + } + + current = current.next; + index++; + } + + //check last item + if (element == current.element){ + return index; + } + + return -1; + }; + + this.isEmpty = function() { + return length === 0; + }; + + this.size = function() { + return length; + }; + + this.getHead = function(){ + return head; + }; + + this.toString = function(){ + + var current = head, + s = current.element; + + while(current.next !== head){ + current = current.next; + s += ', ' + current.element; + } + + return s.toString(); + }; + + this.print = function(){ + console.log(this.toString()); + }; +} \ No newline at end of file diff --git a/chapter05/06-CircularDoublyLinkedList.js b/chapter05/06-CircularDoublyLinkedList.js deleted file mode 100644 index e69de29b..00000000 diff --git a/chapter05/06-UsingCircularLinkedList.html b/chapter05/06-UsingCircularLinkedList.html new file mode 100644 index 00000000..5a2fbb5d --- /dev/null +++ b/chapter05/06-UsingCircularLinkedList.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter05/06-UsingCircularLinkedList.js b/chapter05/06-UsingCircularLinkedList.js new file mode 100644 index 00000000..33d9f8c9 --- /dev/null +++ b/chapter05/06-UsingCircularLinkedList.js @@ -0,0 +1,28 @@ +var circularLinkedList = new CircularLinkedList(); + +circularLinkedList.append(15); +circularLinkedList.print(); + +circularLinkedList.append(16); +circularLinkedList.print(); + +circularLinkedList.insert(0,14); +circularLinkedList.print(); + +circularLinkedList.insert(1,14.5); +circularLinkedList.print(); + +circularLinkedList.insert(4,17); +circularLinkedList.print(); + +circularLinkedList.removeAt(0); +circularLinkedList.print(); + +circularLinkedList.removeAt(1); +circularLinkedList.print(); + +circularLinkedList.removeAt(2); +circularLinkedList.print(); + +console.log(circularLinkedList.indexOf(14.5)); +console.log(circularLinkedList.indexOf(16)); \ No newline at end of file From ee469697267500aa773dfa3e1d8d2d308fe83381 Mon Sep 17 00:00:00 2001 From: loiane Date: Fri, 8 Aug 2014 10:00:07 -0300 Subject: [PATCH 14/54] added chapter 10 --- chapter10/01-SortingAlgorithms.js | 79 ++++++++++++++++++++++ chapter10/02-TestingSortingAlgorithms.html | 11 +++ chapter10/02-TestingSortingAlgorithms.js | 61 +++++++++++++++++ 3 files changed, 151 insertions(+) create mode 100644 chapter10/01-SortingAlgorithms.js create mode 100644 chapter10/02-TestingSortingAlgorithms.html create mode 100644 chapter10/02-TestingSortingAlgorithms.js diff --git a/chapter10/01-SortingAlgorithms.js b/chapter10/01-SortingAlgorithms.js new file mode 100644 index 00000000..e7a70b08 --- /dev/null +++ b/chapter10/01-SortingAlgorithms.js @@ -0,0 +1,79 @@ +function ArrayList(){ + + var array = []; + + this.insert = function(item){ + array.push(item); + }; + + var swap = function(index1, index2){ + var aux = array[index1]; + array[index1] = array[index2]; + array[index2] = aux; + }; + + this.toString= function(){ + var s = array[0] ? array[0] : ''; + for (var i=1; i array[j+1]){ + swap(j, j+1); + } + } + } + }; + + this.modifiedBubbleSort = function(){ + var length = array.length, + swapped; + + do { + swapped = false; + for (var i=0; i array[i+1]){ + swap(i, i+1); + swapped = true; + } + } + } while (swapped); + + }; + + this.selectionSort = function(){ + var length = array.length, + indexMin; + + for (var i=0; iarray[j]){ + indexMin = j; + } + } + swap(i, indexMin); + } + }; + + this.insertionSort = function(){ + var length = array.length, + j, temp; + for (var i=1; i0 && array[j-1] > temp){ + array[j] = array[j-1]; + j--; + } + array[j] = temp; + } + }; +} \ No newline at end of file diff --git a/chapter10/02-TestingSortingAlgorithms.html b/chapter10/02-TestingSortingAlgorithms.html new file mode 100644 index 00000000..418c547e --- /dev/null +++ b/chapter10/02-TestingSortingAlgorithms.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter10/02-TestingSortingAlgorithms.js b/chapter10/02-TestingSortingAlgorithms.js new file mode 100644 index 00000000..98fc2076 --- /dev/null +++ b/chapter10/02-TestingSortingAlgorithms.js @@ -0,0 +1,61 @@ +function createNonSortedArray(){ + var array = new ArrayList(); + + for (var i = 5; i> 0; i--){ + array.insert(i); + } + + return array; +} + +console.log('********** Bubble Sort **********'); + +var array = createNonSortedArray(); + +console.log(array.toString()); + +array.bubbleSort(); + +console.log(array.toString()); + +console.log('********** Modified Bubble Sort **********'); + +array = createNonSortedArray(); + +console.log(array.toString()); + +array.modifiedBubbleSort(); + +console.log(array.toString()); + +console.log('********** Selection Sort **********'); + +array = createNonSortedArray(); + +console.log(array.toString()); + +array.selectionSort(); + +console.log(array.toString()); + +console.log('********** Insertion Sort **********'); + +array = createNonSortedArray(); + +console.log(array.toString()); + +array.insertionSort(); + +console.log(array.toString()); + +console.log('********** Merge Sort **********'); + +array = createNonSortedArray(); + +console.log(array.toString()); + +array.insertionSort(); + +console.log(array.toString()); + + From 460344223b081f06ec3dd1d710bfd7a25a7416c6 Mon Sep 17 00:00:00 2001 From: loiane Date: Fri, 8 Aug 2014 11:31:08 -0300 Subject: [PATCH 15/54] added chapter 10 --- chapter10/01-SortingAlgorithms.js | 92 +++++++++++++++++++ ...ms.html => 02-UsingSortingAlgorithms.html} | 2 +- ...rithms.js => 02-UsingSortingAlgorithms.js} | 12 ++- 3 files changed, 104 insertions(+), 2 deletions(-) mode change 100644 => 100755 chapter10/01-SortingAlgorithms.js rename chapter10/{02-TestingSortingAlgorithms.html => 02-UsingSortingAlgorithms.html} (69%) mode change 100644 => 100755 rename chapter10/{02-TestingSortingAlgorithms.js => 02-UsingSortingAlgorithms.js} (84%) mode change 100644 => 100755 diff --git a/chapter10/01-SortingAlgorithms.js b/chapter10/01-SortingAlgorithms.js old mode 100644 new mode 100755 index e7a70b08..7d6b0ef2 --- a/chapter10/01-SortingAlgorithms.js +++ b/chapter10/01-SortingAlgorithms.js @@ -76,4 +76,96 @@ function ArrayList(){ array[j] = temp; } }; + + this.mergeSort = function(){ + array = mergeSortRec(array); + }; + + var mergeSortRec = function(array){ + + var length = array.length; + + if(length === 1) { + return array; + } + + var mid = Math.floor(length / 2), + left = array.slice(0, mid), + right = array.slice(mid, length); + + return merge(mergeSortRec(left), mergeSortRec(right)); + }; + + var merge = function(left, right){ + var result = [], + il = 0, + ir = 0; + + while(il < left.length && ir < right.length) { + + if(left[il] < right[ir]) { + result.push(left[il++]); + } else{ + result.push(right[ir++]); + } + } + + while (il < left.length){ + result.push(left[il++]); + } + + while (ir < right.length){ + result.push(right[ir++]); + } + + return result; + }; + + this.quickStort = function(){ + quick(array, 0, array.length - 1); + }; + + var partition = function(array, left, right) { + + var pivot = array[Math.floor((right + left) / 2)], + i = left, + j = right; + + while (i <= j) { + while (array[i] < pivot) { + i++; + } + + while (array[j] > pivot) { + j--; + } + + if (i <= j) { + swap(array, i, j); + i++; + j--; + } + } + + return i; + }; + + var quick = function(array, left, right){ + + var index; + + if (array.length > 1) { + + index = partition(array, left, right); + + if (left < index - 1) { + quick(array, left, index - 1); + } + + if (index < right) { + quick(array, index, right); + } + } + return array; + }; } \ No newline at end of file diff --git a/chapter10/02-TestingSortingAlgorithms.html b/chapter10/02-UsingSortingAlgorithms.html old mode 100644 new mode 100755 similarity index 69% rename from chapter10/02-TestingSortingAlgorithms.html rename to chapter10/02-UsingSortingAlgorithms.html index 418c547e..6fd6bc9e --- a/chapter10/02-TestingSortingAlgorithms.html +++ b/chapter10/02-UsingSortingAlgorithms.html @@ -6,6 +6,6 @@ - + \ No newline at end of file diff --git a/chapter10/02-TestingSortingAlgorithms.js b/chapter10/02-UsingSortingAlgorithms.js old mode 100644 new mode 100755 similarity index 84% rename from chapter10/02-TestingSortingAlgorithms.js rename to chapter10/02-UsingSortingAlgorithms.js index 98fc2076..d833b187 --- a/chapter10/02-TestingSortingAlgorithms.js +++ b/chapter10/02-UsingSortingAlgorithms.js @@ -54,7 +54,17 @@ array = createNonSortedArray(); console.log(array.toString()); -array.insertionSort(); +array.mergeSort(); + +console.log(array.toString()); + +console.log('********** Quick Sort **********'); + +array = createNonSortedArray(); + +console.log(array.toString()); + +array.mergeSort(); console.log(array.toString()); From e7b77097cd7260ce206b511bb5974f9ef1cd36bc Mon Sep 17 00:00:00 2001 From: loiane Date: Fri, 8 Aug 2014 12:10:25 -0300 Subject: [PATCH 16/54] added chapter 10 --- chapter10/01-SortingAlgorithms.js | 10 ++++++++-- chapter10/02-UsingSortingAlgorithms.js | 2 +- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/chapter10/01-SortingAlgorithms.js b/chapter10/01-SortingAlgorithms.js index 7d6b0ef2..eaf35add 100755 --- a/chapter10/01-SortingAlgorithms.js +++ b/chapter10/01-SortingAlgorithms.js @@ -121,7 +121,7 @@ function ArrayList(){ return result; }; - this.quickStort = function(){ + this.quickSort = function(){ quick(array, 0, array.length - 1); }; @@ -141,7 +141,7 @@ function ArrayList(){ } if (i <= j) { - swap(array, i, j); + swapQuickStort(array, i, j); i++; j--; } @@ -150,6 +150,12 @@ function ArrayList(){ return i; }; + var swapQuickStort = function(array, index1, index2){ + var aux = array[index1]; + array[index1] = array[index2]; + array[index2] = aux; + }; + var quick = function(array, left, right){ var index; diff --git a/chapter10/02-UsingSortingAlgorithms.js b/chapter10/02-UsingSortingAlgorithms.js index d833b187..226e5391 100755 --- a/chapter10/02-UsingSortingAlgorithms.js +++ b/chapter10/02-UsingSortingAlgorithms.js @@ -64,7 +64,7 @@ array = createNonSortedArray(); console.log(array.toString()); -array.mergeSort(); +array.quickSort(); console.log(array.toString()); From 648abe9b5bbd4a252113dc16573f9ba1f4d6e6ac Mon Sep 17 00:00:00 2001 From: loiane Date: Fri, 8 Aug 2014 12:15:04 -0300 Subject: [PATCH 17/54] added chapter 11 --- chapter11/01-SearchingAlgorithms.js | 124 +++++++++++++++++++++ chapter11/02-UsingSearchingAlgorithms.html | 11 ++ chapter11/02-UsingSearchingAlgorithms.js | 27 +++++ 3 files changed, 162 insertions(+) create mode 100755 chapter11/01-SearchingAlgorithms.js create mode 100755 chapter11/02-UsingSearchingAlgorithms.html create mode 100755 chapter11/02-UsingSearchingAlgorithms.js diff --git a/chapter11/01-SearchingAlgorithms.js b/chapter11/01-SearchingAlgorithms.js new file mode 100755 index 00000000..ef571b0f --- /dev/null +++ b/chapter11/01-SearchingAlgorithms.js @@ -0,0 +1,124 @@ +function ArrayList(){ + + var array = []; + + this.insert = function(item){ + array.push(item); + }; + + this.toString = function(){ + var s = array[0] ? array[0] : ''; + for (var i=1; i array[i]){ + min = array[i]; + } + } + + return min; + }; + + this.binarySearch = function(item){ + this.quickSort(); + + var low = 0, + high = array.length - 1, + mid, element; + + while (low <= high){ + mid = Math.floor((low + high) / 2); + element = array[mid]; + if (element < item) { + low = mid + 1; + } else if (element > item) { + high = mid - 1; + } else { + return mid; + } + } + return -1; + }; + + this.quickSort = function(){ + quick(array, 0, array.length - 1); + }; + + var partition = function(array, left, right) { + + var pivot = array[Math.floor((right + left) / 2)], + i = left, + j = right; + + while (i <= j) { + while (array[i] < pivot) { + i++; + } + + while (array[j] > pivot) { + j--; + } + + if (i <= j) { + swapQuickStort(array, i, j); + i++; + j--; + } + } + + return i; + }; + + var swapQuickStort = function(array, index1, index2){ + var aux = array[index1]; + array[index1] = array[index2]; + array[index2] = aux; + }; + + var quick = function(array, left, right){ + + var index; + + if (array.length > 1) { + + index = partition(array, left, right); + + if (left < index - 1) { + quick(array, left, index - 1); + } + + if (index < right) { + quick(array, index, right); + } + } + return array; + }; +} \ No newline at end of file diff --git a/chapter11/02-UsingSearchingAlgorithms.html b/chapter11/02-UsingSearchingAlgorithms.html new file mode 100755 index 00000000..45b9269e --- /dev/null +++ b/chapter11/02-UsingSearchingAlgorithms.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter11/02-UsingSearchingAlgorithms.js b/chapter11/02-UsingSearchingAlgorithms.js new file mode 100755 index 00000000..239d5023 --- /dev/null +++ b/chapter11/02-UsingSearchingAlgorithms.js @@ -0,0 +1,27 @@ +function createNonSortedArray(){ + var array = new ArrayList(); + + for (var i = 5; i> 0; i--){ + array.insert(i); + } + + return array; +} + +var array = createNonSortedArray(); + +console.log('********** Sequential Sort #3 **********'); + +console.log(array.sequentialSearch(3)); + +console.log('********** Min **********'); + +console.log(array.findMinValue()); + +console.log('********** Max **********'); + +console.log(array.findMaxValue()); + +console.log('********** Binary Search #3 **********'); + +console.log(array.binarySearch(3)); \ No newline at end of file From c14829b41f92ff07efd77dd7c26197174affb67c Mon Sep 17 00:00:00 2001 From: loiane Date: Sat, 9 Aug 2014 14:06:16 -0300 Subject: [PATCH 18/54] added chapter 10 --- chapter10/01-SortingAlgorithms.js | 41 ++++++++++++++++++-------- chapter10/02-UsingSortingAlgorithms.js | 37 +++++++++++++++++------ 2 files changed, 57 insertions(+), 21 deletions(-) diff --git a/chapter10/01-SortingAlgorithms.js b/chapter10/01-SortingAlgorithms.js index eaf35add..b323c648 100755 --- a/chapter10/01-SortingAlgorithms.js +++ b/chapter10/01-SortingAlgorithms.js @@ -25,7 +25,9 @@ function ArrayList(){ for (var i=0; i array[j+1]){ + console.log('swap ' + array[j] + ' with ' + array[j+1]); swap(j, j+1); } } @@ -33,18 +35,17 @@ function ArrayList(){ }; this.modifiedBubbleSort = function(){ - var length = array.length, - swapped; - - do { - swapped = false; - for (var i=0; i array[i+1]){ - swap(i, i+1); - swapped = true; + var length = array.length; + + for (var i=0; i array[j+1]){ + console.log('swap ' + array[j] + ' with ' + array[j+1]); + swap(j, j+1); } } - } while (swapped); + } }; @@ -52,14 +53,19 @@ function ArrayList(){ var length = array.length, indexMin; - for (var i=0; iarray[j]){ + console.log('new index min ' + array[j]); indexMin = j; } } - swap(i, indexMin); + if (i !== indexMin){ + console.log('swap ' + array[i] + ' with ' + array[indexMin]); + swap(i, indexMin); + } } }; @@ -69,10 +75,13 @@ function ArrayList(){ for (var i=1; i0 && array[j-1] > temp){ + console.log('shift ' + array[j-1]); array[j] = array[j-1]; j--; } + console.log('insert ' + temp); array[j] = temp; } }; @@ -86,6 +95,7 @@ function ArrayList(){ var length = array.length; if(length === 1) { + console.log(array); return array; } @@ -118,6 +128,8 @@ function ArrayList(){ result.push(right[ir++]); } + console.log(result); + return result; }; @@ -131,16 +143,21 @@ function ArrayList(){ i = left, j = right; + console.log('pivot is ' + pivot + '; left is ' + left + '; right is ' + right); + while (i <= j) { while (array[i] < pivot) { i++; + console.log('i = ' + i); } while (array[j] > pivot) { j--; + console.log('j = ' + j); } if (i <= j) { + console.log('swap ' + array[i] + ' with ' + array[j]); swapQuickStort(array, i, j); i++; j--; diff --git a/chapter10/02-UsingSortingAlgorithms.js b/chapter10/02-UsingSortingAlgorithms.js index 226e5391..e09c3e33 100755 --- a/chapter10/02-UsingSortingAlgorithms.js +++ b/chapter10/02-UsingSortingAlgorithms.js @@ -1,16 +1,28 @@ -function createNonSortedArray(){ +function createNonSortedArray(size){ var array = new ArrayList(); - for (var i = 5; i> 0; i--){ + for (var i = size; i> 0; i--){ array.insert(i); } return array; } +function createRandomNonSortedArray(){ + var array = new ArrayList(); + + array.insert(3); + array.insert(5); + array.insert(1); + array.insert(4); + array.insert(2); + + return array; +} + console.log('********** Bubble Sort **********'); -var array = createNonSortedArray(); +var array = createNonSortedArray(5); console.log(array.toString()); @@ -20,7 +32,7 @@ console.log(array.toString()); console.log('********** Modified Bubble Sort **********'); -array = createNonSortedArray(); +array = createNonSortedArray(5); console.log(array.toString()); @@ -30,7 +42,7 @@ console.log(array.toString()); console.log('********** Selection Sort **********'); -array = createNonSortedArray(); +array = createNonSortedArray(5); console.log(array.toString()); @@ -40,7 +52,7 @@ console.log(array.toString()); console.log('********** Insertion Sort **********'); -array = createNonSortedArray(); +array = createRandomNonSortedArray(); console.log(array.toString()); @@ -50,7 +62,7 @@ console.log(array.toString()); console.log('********** Merge Sort **********'); -array = createNonSortedArray(); +array = createNonSortedArray(8); console.log(array.toString()); @@ -59,8 +71,15 @@ array.mergeSort(); console.log(array.toString()); console.log('********** Quick Sort **********'); - -array = createNonSortedArray(); +array = new ArrayList(); + +array.insert(3); +array.insert(5); +array.insert(1); +array.insert(6); +array.insert(4); +array.insert(7); +array.insert(2); console.log(array.toString()); From b99f882fefaeda92d07d02f7bc00ccacbb9fe698 Mon Sep 17 00:00:00 2001 From: loiane Date: Sat, 9 Aug 2014 14:06:23 -0300 Subject: [PATCH 19/54] added chapter 11 --- chapter11/01-SearchingAlgorithms.js | 4 ++++ chapter11/02-UsingSearchingAlgorithms.js | 14 ++++++++++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/chapter11/01-SearchingAlgorithms.js b/chapter11/01-SearchingAlgorithms.js index ef571b0f..0f3a29e2 100755 --- a/chapter11/01-SearchingAlgorithms.js +++ b/chapter11/01-SearchingAlgorithms.js @@ -57,11 +57,15 @@ function ArrayList(){ while (low <= high){ mid = Math.floor((low + high) / 2); element = array[mid]; + console.log('mid element is ' + element); if (element < item) { low = mid + 1; + console.log('low is ' + low); } else if (element > item) { high = mid - 1; + console.log('high is ' + high); } else { + console.log('found it'); return mid; } } diff --git a/chapter11/02-UsingSearchingAlgorithms.js b/chapter11/02-UsingSearchingAlgorithms.js index 239d5023..62201e80 100755 --- a/chapter11/02-UsingSearchingAlgorithms.js +++ b/chapter11/02-UsingSearchingAlgorithms.js @@ -1,14 +1,14 @@ -function createNonSortedArray(){ +function createNonSortedArray(items){ var array = new ArrayList(); - for (var i = 5; i> 0; i--){ + for (var i = items; i> 0; i--){ array.insert(i); } return array; } -var array = createNonSortedArray(); +var array = createNonSortedArray(5); console.log('********** Sequential Sort #3 **********'); @@ -24,4 +24,10 @@ console.log(array.findMaxValue()); console.log('********** Binary Search #3 **********'); -console.log(array.binarySearch(3)); \ No newline at end of file +console.log(array.binarySearch(3)); + +console.log('********** Binary Search #2 **********'); + +var array = createNonSortedArray(8); + +console.log(array.binarySearch(2)); \ No newline at end of file From e9cd528bdc3d4f5519c2da4306e2613dcacdcbeb Mon Sep 17 00:00:00 2001 From: loiane Date: Mon, 11 Aug 2014 10:04:59 -0300 Subject: [PATCH 20/54] added chapter 10 --- ...ms.js => 01-SortingSearchingAlgorithms.js} | 61 +++++++++ chapter10/02-UsingSortingAlgorithms.html | 2 +- chapter10/03-UsingSearchingAlgorithms.html | 11 ++ .../03-UsingSearchingAlgorithms.js | 0 chapter11/01-SearchingAlgorithms.js | 128 ------------------ chapter11/02-UsingSearchingAlgorithms.html | 11 -- 6 files changed, 73 insertions(+), 140 deletions(-) rename chapter10/{01-SortingAlgorithms.js => 01-SortingSearchingAlgorithms.js} (77%) create mode 100755 chapter10/03-UsingSearchingAlgorithms.html rename chapter11/02-UsingSearchingAlgorithms.js => chapter10/03-UsingSearchingAlgorithms.js (100%) delete mode 100755 chapter11/01-SearchingAlgorithms.js delete mode 100755 chapter11/02-UsingSearchingAlgorithms.html diff --git a/chapter10/01-SortingAlgorithms.js b/chapter10/01-SortingSearchingAlgorithms.js similarity index 77% rename from chapter10/01-SortingAlgorithms.js rename to chapter10/01-SortingSearchingAlgorithms.js index b323c648..1204ace2 100755 --- a/chapter10/01-SortingAlgorithms.js +++ b/chapter10/01-SortingSearchingAlgorithms.js @@ -24,6 +24,7 @@ function ArrayList(){ var length = array.length; for (var i=0; i array[j+1]){ @@ -38,6 +39,7 @@ function ArrayList(){ var length = array.length; for (var i=0; i array[j+1]){ @@ -191,4 +193,63 @@ function ArrayList(){ } return array; }; + + this.sequentialSearch = function(item){ + + for (var i=0; i array[i]){ + min = array[i]; + } + } + + return min; + }; + + this.binarySearch = function(item){ + this.quickSort(); + + var low = 0, + high = array.length - 1, + mid, element; + + while (low <= high){ + mid = Math.floor((low + high) / 2); + element = array[mid]; + console.log('mid element is ' + element); + if (element < item) { + low = mid + 1; + console.log('low is ' + low); + } else if (element > item) { + high = mid - 1; + console.log('high is ' + high); + } else { + console.log('found it'); + return mid; + } + } + return -1; + }; + } \ No newline at end of file diff --git a/chapter10/02-UsingSortingAlgorithms.html b/chapter10/02-UsingSortingAlgorithms.html index 6fd6bc9e..7a666fdb 100755 --- a/chapter10/02-UsingSortingAlgorithms.html +++ b/chapter10/02-UsingSortingAlgorithms.html @@ -5,7 +5,7 @@ - + \ No newline at end of file diff --git a/chapter10/03-UsingSearchingAlgorithms.html b/chapter10/03-UsingSearchingAlgorithms.html new file mode 100755 index 00000000..a4e4b6a3 --- /dev/null +++ b/chapter10/03-UsingSearchingAlgorithms.html @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/chapter11/02-UsingSearchingAlgorithms.js b/chapter10/03-UsingSearchingAlgorithms.js similarity index 100% rename from chapter11/02-UsingSearchingAlgorithms.js rename to chapter10/03-UsingSearchingAlgorithms.js diff --git a/chapter11/01-SearchingAlgorithms.js b/chapter11/01-SearchingAlgorithms.js deleted file mode 100755 index 0f3a29e2..00000000 --- a/chapter11/01-SearchingAlgorithms.js +++ /dev/null @@ -1,128 +0,0 @@ -function ArrayList(){ - - var array = []; - - this.insert = function(item){ - array.push(item); - }; - - this.toString = function(){ - var s = array[0] ? array[0] : ''; - for (var i=1; i array[i]){ - min = array[i]; - } - } - - return min; - }; - - this.binarySearch = function(item){ - this.quickSort(); - - var low = 0, - high = array.length - 1, - mid, element; - - while (low <= high){ - mid = Math.floor((low + high) / 2); - element = array[mid]; - console.log('mid element is ' + element); - if (element < item) { - low = mid + 1; - console.log('low is ' + low); - } else if (element > item) { - high = mid - 1; - console.log('high is ' + high); - } else { - console.log('found it'); - return mid; - } - } - return -1; - }; - - this.quickSort = function(){ - quick(array, 0, array.length - 1); - }; - - var partition = function(array, left, right) { - - var pivot = array[Math.floor((right + left) / 2)], - i = left, - j = right; - - while (i <= j) { - while (array[i] < pivot) { - i++; - } - - while (array[j] > pivot) { - j--; - } - - if (i <= j) { - swapQuickStort(array, i, j); - i++; - j--; - } - } - - return i; - }; - - var swapQuickStort = function(array, index1, index2){ - var aux = array[index1]; - array[index1] = array[index2]; - array[index2] = aux; - }; - - var quick = function(array, left, right){ - - var index; - - if (array.length > 1) { - - index = partition(array, left, right); - - if (left < index - 1) { - quick(array, left, index - 1); - } - - if (index < right) { - quick(array, index, right); - } - } - return array; - }; -} \ No newline at end of file diff --git a/chapter11/02-UsingSearchingAlgorithms.html b/chapter11/02-UsingSearchingAlgorithms.html deleted file mode 100755 index 45b9269e..00000000 --- a/chapter11/02-UsingSearchingAlgorithms.html +++ /dev/null @@ -1,11 +0,0 @@ - - - - - - - - - - - \ No newline at end of file From e014ac6b7b1faba831be4d43ae924de41fa929a7 Mon Sep 17 00:00:00 2001 From: loiane Date: Tue, 26 Aug 2014 20:49:45 -0300 Subject: [PATCH 21/54] add chapter 11 --- chapter11/01-Recursion.js | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 chapter11/01-Recursion.js diff --git a/chapter11/01-Recursion.js b/chapter11/01-Recursion.js new file mode 100644 index 00000000..d7348f99 --- /dev/null +++ b/chapter11/01-Recursion.js @@ -0,0 +1,20 @@ +function fibonacci(num){ + if (num === 1 || num === 2){ + return 1; + } + if (num > 2){ + return fibonacci(num - 1) + fibonacci(num - 2); + } +} + +function fib(num){ + var n1 = 1, + n2 = 1, + n = 1; + for (var i = 3; i<=num; i++){ + n = n1 + n2; + n1 = n2; + n2 = n; + } + return n; +} \ No newline at end of file From 7b5bc4770d1c14b4fb4db3b137a561886241d6c9 Mon Sep 17 00:00:00 2001 From: loiane Date: Fri, 29 Aug 2014 13:24:06 -0300 Subject: [PATCH 22/54] added chapter 11 --- chapter11/02-MinCoinChangeDP.html | 10 +++++ chapter11/02-MinCoinChangeDP.js | 38 ++++++++++++++++++ chapter11/BigONotation.html | 10 +++++ chapter11/BigONotation.js | 65 +++++++++++++++++++++++++++++++ chapter11/MinCoinChangeGreedy.js | 11 ++++++ 5 files changed, 134 insertions(+) create mode 100644 chapter11/02-MinCoinChangeDP.html create mode 100644 chapter11/02-MinCoinChangeDP.js create mode 100644 chapter11/BigONotation.html create mode 100644 chapter11/BigONotation.js create mode 100644 chapter11/MinCoinChangeGreedy.js diff --git a/chapter11/02-MinCoinChangeDP.html b/chapter11/02-MinCoinChangeDP.html new file mode 100644 index 00000000..7516a9da --- /dev/null +++ b/chapter11/02-MinCoinChangeDP.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter11/02-MinCoinChangeDP.js b/chapter11/02-MinCoinChangeDP.js new file mode 100644 index 00000000..b9c65506 --- /dev/null +++ b/chapter11/02-MinCoinChangeDP.js @@ -0,0 +1,38 @@ +function MinCoinChange(coins){ + + var coins = coins; + + var cache = {}; + + this.makeChange = function(amount) { + var me = this; + if (!amount) { + return []; + } + if (cache[amount]) { + return cache[amount]; + } + var min = [], newMin, newAmount; + for (var i=0; i= 0){ + newMin = me.makeChange(newAmount); + } + if ( + newAmount >= 0 && + (newMin.length < min.length-1 || !min.length) && + (newMin.length || !newAmount) + ){ + min = [coin].concat(newMin); + console.log('new Min ' + min + ' for ' + amount); + } + } + return (cache[amount] = min); + }; +} + + +var minCoinChange = new MinCoinChange([1, 5, 10, 25]); + +console.log(minCoinChange.makeChange(37)); \ No newline at end of file diff --git a/chapter11/BigONotation.html b/chapter11/BigONotation.html new file mode 100644 index 00000000..ff2919a6 --- /dev/null +++ b/chapter11/BigONotation.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter11/BigONotation.js b/chapter11/BigONotation.js new file mode 100644 index 00000000..8a03acd7 --- /dev/null +++ b/chapter11/BigONotation.js @@ -0,0 +1,65 @@ +//*************** o(1) +function increment(num){ + console.log('cost for increment with input ' + num + ' is 1'); + return ++num; +} + +increment(1); +increment(2); + +//*************** o(n) + +function createNonSortedArray(size){ + var array = [] + + for (var i = size; i> 0; i--){ + array[i] = i; + } + + return array; +} + +function sequentialSearch(array, item){ + var cost = 0; + for (var i=0; i array[j+1]){ + swap(array, j, j+1); + } + } + } + console.log('cost for bubbleSort with input size ' + length + ' is ' + cost); +} + +var array1 = createNonSortedArray(99); +var array2 = createNonSortedArray(999); +var array3 = createNonSortedArray(9999); +bubbleSort(array1); +bubbleSort(array2); +bubbleSort(array3); \ No newline at end of file diff --git a/chapter11/MinCoinChangeGreedy.js b/chapter11/MinCoinChangeGreedy.js new file mode 100644 index 00000000..06f5655c --- /dev/null +++ b/chapter11/MinCoinChangeGreedy.js @@ -0,0 +1,11 @@ +var makeChange = function(amount) { + var change = [], + total = 0; + [25, 10, 5, 1].forEach(function(coin) { + while (total + coin <= amount) { + change.push(coin); + total += coin; + } + }); + return change; +}; \ No newline at end of file From cd4edd01b92b1afd11b22559c1dd9fb40fd58ef8 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Mon, 1 Sep 2014 12:05:00 -0300 Subject: [PATCH 23/54] added chapter 11 --- chapter11/02-MinCoinChangeDP.js | 4 +++- chapter11/MinCoinChangeGreedy.html | 10 +++++++++ chapter11/MinCoinChangeGreedy.js | 35 +++++++++++++++++++++--------- 3 files changed, 38 insertions(+), 11 deletions(-) create mode 100644 chapter11/MinCoinChangeGreedy.html diff --git a/chapter11/02-MinCoinChangeDP.js b/chapter11/02-MinCoinChangeDP.js index b9c65506..75d0bfd2 100644 --- a/chapter11/02-MinCoinChangeDP.js +++ b/chapter11/02-MinCoinChangeDP.js @@ -34,5 +34,7 @@ function MinCoinChange(coins){ var minCoinChange = new MinCoinChange([1, 5, 10, 25]); +console.log(minCoinChange.makeChange(36)); -console.log(minCoinChange.makeChange(37)); \ No newline at end of file +var minCoinChange2 = new MinCoinChange([1, 3, 4]); +console.log(minCoinChange2.makeChange(6)); \ No newline at end of file diff --git a/chapter11/MinCoinChangeGreedy.html b/chapter11/MinCoinChangeGreedy.html new file mode 100644 index 00000000..b1c90657 --- /dev/null +++ b/chapter11/MinCoinChangeGreedy.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter11/MinCoinChangeGreedy.js b/chapter11/MinCoinChangeGreedy.js index 06f5655c..a935c16b 100644 --- a/chapter11/MinCoinChangeGreedy.js +++ b/chapter11/MinCoinChangeGreedy.js @@ -1,11 +1,26 @@ -var makeChange = function(amount) { - var change = [], - total = 0; - [25, 10, 5, 1].forEach(function(coin) { - while (total + coin <= amount) { - change.push(coin); - total += coin; +function MinCoinChange(coins){ + + var coins = coins; + + var cache = {}; + + this.makeChange = function(amount) { + var change = [], + total = 0; + for (var i=coins.length; i>=0; i--){ + var coin = coins[i]; + while (total + coin <= amount) { + change.push(coin); + total += coin; + } } - }); - return change; -}; \ No newline at end of file + return change; + }; +} + + +var minCoinChange = new MinCoinChange([1, 5, 10, 25]); +console.log(minCoinChange.makeChange(36)); + +var minCoinChange2 = new MinCoinChange([1, 3, 4]); +console.log(minCoinChange2.makeChange(6)); \ No newline at end of file From 7db601d32b05d4e004284a2b620883a898a57909 Mon Sep 17 00:00:00 2001 From: loiane Date: Mon, 1 Sep 2014 12:44:49 -0300 Subject: [PATCH 24/54] added chapter 11 --- chapter11/{BigONotation.html => 01-Recursion.html} | 2 +- chapter11/01-Recursion.js | 7 ++++++- chapter11/03-MinCoinChangeGreedy.html | 10 ++++++++++ ...inCoinChangeGreedy.js => 03-MinCoinChangeGreedy.js} | 0 .../{MinCoinChangeGreedy.html => 04-BigONotation.html} | 2 +- chapter11/{BigONotation.js => 04-BigONotation.js} | 2 +- 6 files changed, 19 insertions(+), 4 deletions(-) rename chapter11/{BigONotation.html => 01-Recursion.html} (62%) create mode 100644 chapter11/03-MinCoinChangeGreedy.html rename chapter11/{MinCoinChangeGreedy.js => 03-MinCoinChangeGreedy.js} (100%) rename chapter11/{MinCoinChangeGreedy.html => 04-BigONotation.html} (60%) rename chapter11/{BigONotation.js => 04-BigONotation.js} (98%) diff --git a/chapter11/BigONotation.html b/chapter11/01-Recursion.html similarity index 62% rename from chapter11/BigONotation.html rename to chapter11/01-Recursion.html index ff2919a6..5961583b 100644 --- a/chapter11/BigONotation.html +++ b/chapter11/01-Recursion.html @@ -5,6 +5,6 @@ - + \ No newline at end of file diff --git a/chapter11/01-Recursion.js b/chapter11/01-Recursion.js index d7348f99..bd16253d 100644 --- a/chapter11/01-Recursion.js +++ b/chapter11/01-Recursion.js @@ -1,3 +1,4 @@ +//Recursive solution - DP function fibonacci(num){ if (num === 1 || num === 2){ return 1; @@ -7,6 +8,7 @@ function fibonacci(num){ } } +//Non Recursive solution function fib(num){ var n1 = 1, n2 = 1, @@ -17,4 +19,7 @@ function fib(num){ n2 = n; } return n; -} \ No newline at end of file +} + +console.log(fibonacci(6)); +console.log(fib(6)); \ No newline at end of file diff --git a/chapter11/03-MinCoinChangeGreedy.html b/chapter11/03-MinCoinChangeGreedy.html new file mode 100644 index 00000000..7ebac53d --- /dev/null +++ b/chapter11/03-MinCoinChangeGreedy.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter11/MinCoinChangeGreedy.js b/chapter11/03-MinCoinChangeGreedy.js similarity index 100% rename from chapter11/MinCoinChangeGreedy.js rename to chapter11/03-MinCoinChangeGreedy.js diff --git a/chapter11/MinCoinChangeGreedy.html b/chapter11/04-BigONotation.html similarity index 60% rename from chapter11/MinCoinChangeGreedy.html rename to chapter11/04-BigONotation.html index b1c90657..995ac4d9 100644 --- a/chapter11/MinCoinChangeGreedy.html +++ b/chapter11/04-BigONotation.html @@ -5,6 +5,6 @@ - + \ No newline at end of file diff --git a/chapter11/BigONotation.js b/chapter11/04-BigONotation.js similarity index 98% rename from chapter11/BigONotation.js rename to chapter11/04-BigONotation.js index 8a03acd7..a48bd6ab 100644 --- a/chapter11/BigONotation.js +++ b/chapter11/04-BigONotation.js @@ -10,7 +10,7 @@ increment(2); //*************** o(n) function createNonSortedArray(size){ - var array = [] + var array = []; for (var i = size; i> 0; i--){ array[i] = i; From 2ca9d40ee2ba1ede33ab0f8e414422ed4083ea66 Mon Sep 17 00:00:00 2001 From: loiane Date: Mon, 1 Sep 2014 17:37:28 -0300 Subject: [PATCH 25/54] added big-o notation chart - chapter 11 --- chapter11/bigOChart/chart.js | 37 +++++++ chapter11/bigOChart/index.html | 14 +++ npm-debug.log | 180 +++++++++++++++++++++++++++++++++ 3 files changed, 231 insertions(+) create mode 100644 chapter11/bigOChart/chart.js create mode 100644 chapter11/bigOChart/index.html create mode 100644 npm-debug.log diff --git a/chapter11/bigOChart/chart.js b/chapter11/bigOChart/chart.js new file mode 100644 index 00000000..765794df --- /dev/null +++ b/chapter11/bigOChart/chart.js @@ -0,0 +1,37 @@ +google.load('visualization', '1.0', {'packages':['corechart']}); +google.setOnLoadCallback(drawChart); + +function drawChart() { + + var data = new google.visualization.DataTable(); + data.addColumn('string', 'n'); + data.addColumn('number', 'O(1)'); + data.addColumn('number', 'O(log n)'); + data.addColumn('number', 'O(n)'); + data.addColumn('number', 'O(n log n)'); + data.addColumn('number', 'O(n^2)'); + data.addColumn('number', 'O(2^n)'); + + for (var i = 0; i <= 30; i++) { + data.addRow([i+'', 1, Math.log(i), i, Math.log(i)*i, Math.pow(i,2), Math.pow(2,i)]); + } + + var options = {'title':'Big O Notation Complexity Chart', + 'width':700, + 'height':600, + 'backgroundColor':{stroke:'#CCC',strokeWidth:1}, + 'curveType':'function', + 'hAxis':{ + title:'Elements (n)', + showTextEvery:5 + }, + 'vAxis':{ + title:'Operations', + viewWindowMode:'explicit', + viewWindow:{min:0,max:450} + } + }; + + var chart = new google.visualization.LineChart(document.getElementById('chart_div')); + chart.draw(data, options); +} \ No newline at end of file diff --git a/chapter11/bigOChart/index.html b/chapter11/bigOChart/index.html new file mode 100644 index 00000000..31118263 --- /dev/null +++ b/chapter11/bigOChart/index.html @@ -0,0 +1,14 @@ + + + + + + + + + +
+ + \ No newline at end of file diff --git a/npm-debug.log b/npm-debug.log new file mode 100644 index 00000000..324f5d2d --- /dev/null +++ b/npm-debug.log @@ -0,0 +1,180 @@ +0 info it worked if it ends with ok +1 verbose cli [ 'node', '/usr/local/bin/npm', 'install', 'http-server', '-g' ] +2 info using npm@1.4.23 +3 info using node@v0.10.31 +4 verbose cache add [ 'http-server', null ] +5 verbose cache add name=undefined spec="http-server" args=["http-server",null] +6 verbose parsed url { protocol: null, +6 verbose parsed url slashes: null, +6 verbose parsed url auth: null, +6 verbose parsed url host: null, +6 verbose parsed url port: null, +6 verbose parsed url hostname: null, +6 verbose parsed url hash: null, +6 verbose parsed url search: null, +6 verbose parsed url query: null, +6 verbose parsed url pathname: 'http-server', +6 verbose parsed url path: 'http-server', +6 verbose parsed url href: 'http-server' } +7 silly lockFile ed608307-http-server http-server +8 verbose lock http-server /Users/loiane/.npm/ed608307-http-server.lock +9 silly lockFile ed608307-http-server http-server +10 silly lockFile ed608307-http-server http-server +11 verbose addNamed [ 'http-server', '' ] +12 verbose addNamed [ null, '*' ] +13 silly lockFile 550353c6-http-server http-server@ +14 verbose lock http-server@ /Users/loiane/.npm/550353c6-http-server.lock +15 silly addNameRange { name: 'http-server', range: '*', hasData: false } +16 verbose request where is /http-server +17 verbose request registry https://registry.npmjs.org/ +18 verbose request id 5de596c601e747df +19 verbose url raw /http-server +20 verbose url resolving [ 'https://registry.npmjs.org/', './http-server' ] +21 verbose url resolved https://registry.npmjs.org/http-server +22 verbose request where is https://registry.npmjs.org/http-server +23 info trying registry request attempt 1 at 16:26:40 +24 http GET https://registry.npmjs.org/http-server +25 http 200 https://registry.npmjs.org/http-server +26 silly registry.get cb [ 200, +26 silly registry.get { date: 'Mon, 01 Sep 2014 19:26:41 GMT', +26 silly registry.get server: 'CouchDB/1.5.0 (Erlang OTP/R16B03)', +26 silly registry.get etag: '"GRUZZAK9N6WU29IC3EFS78GW"', +26 silly registry.get 'content-type': 'application/json', +26 silly registry.get 'cache-control': 'max-age=60', +26 silly registry.get 'content-length': '42618', +26 silly registry.get 'accept-ranges': 'bytes', +26 silly registry.get via: '1.1 varnish', +26 silly registry.get age: '942', +26 silly registry.get 'x-served-by': 'cache-iad2134-IAD', +26 silly registry.get 'x-cache': 'HIT', +26 silly registry.get 'x-cache-hits': '1', +26 silly registry.get 'x-timer': 'S1409599601.088721,VS0,VE16', +26 silly registry.get vary: 'Accept', +26 silly registry.get 'keep-alive': 'timeout=10, max=50', +26 silly registry.get connection: 'Keep-Alive' } ] +27 silly addNameRange number 2 { name: 'http-server', range: '*', hasData: true } +28 silly addNameRange versions [ 'http-server', +28 silly addNameRange [ '0.1.0', +28 silly addNameRange '0.1.1', +28 silly addNameRange '0.1.3', +28 silly addNameRange '0.2.1', +28 silly addNameRange '0.2.2', +28 silly addNameRange '0.2.3', +28 silly addNameRange '0.2.4', +28 silly addNameRange '0.2.5', +28 silly addNameRange '0.2.6', +28 silly addNameRange '0.2.9', +28 silly addNameRange '0.3.0', +28 silly addNameRange '0.4.0', +28 silly addNameRange '0.4.1', +28 silly addNameRange '0.5.0', +28 silly addNameRange '0.5.1', +28 silly addNameRange '0.5.2', +28 silly addNameRange '0.5.3', +28 silly addNameRange '0.5.5', +28 silly addNameRange '0.6.0', +28 silly addNameRange '0.6.1' ] ] +29 verbose addNamed [ 'http-server', '0.6.1' ] +30 verbose addNamed [ '0.6.1', '0.6.1' ] +31 silly lockFile 1e2b2518-http-server-0-6-1 http-server@0.6.1 +32 verbose lock http-server@0.6.1 /Users/loiane/.npm/1e2b2518-http-server-0-6-1.lock +33 silly lockFile c3f4b4b6-ttp-server-http-server-0-6-1-tgz https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz +34 verbose lock https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz /Users/loiane/.npm/c3f4b4b6-ttp-server-http-server-0-6-1-tgz.lock +35 verbose addRemoteTarball [ 'https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz', +35 verbose addRemoteTarball '06fce65cf2bd4132a578bdac62ffacb97d613981' ] +36 info retry fetch attempt 1 at 16:26:42 +37 verbose fetch to= /var/folders/p6/h5zxx5c5153gfhgsvg1_s6n80000gn/T/npm-4783-wjg257Iq/registry.npmjs.org/http-server/-/http-server-0.6.1.tgz +38 http GET https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz +39 http 200 https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz +40 silly lockFile c3f4b4b6-ttp-server-http-server-0-6-1-tgz https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz +41 silly lockFile c3f4b4b6-ttp-server-http-server-0-6-1-tgz https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz +42 silly lockFile 1e2b2518-http-server-0-6-1 http-server@0.6.1 +43 silly lockFile 1e2b2518-http-server-0-6-1 http-server@0.6.1 +44 silly lockFile 550353c6-http-server http-server@ +45 silly lockFile 550353c6-http-server http-server@ +46 silly resolved [ { name: 'http-server', +46 silly resolved version: '0.6.1', +46 silly resolved author: { name: 'Nodejitsu', email: 'support@nodejitsu.com' }, +46 silly resolved description: 'a simple zero-configuration command-line http server', +46 silly resolved main: './lib/http-server', +46 silly resolved repository: +46 silly resolved { type: 'git', +46 silly resolved url: 'git://github.com/nodeapps/http-server.git' }, +46 silly resolved keywords: [ 'cli', 'command' ], +46 silly resolved scripts: +46 silly resolved { start: 'node ./bin/http-server', +46 silly resolved test: 'vows --spec --isolate' }, +46 silly resolved contributors: +46 silly resolved [ [Object], +46 silly resolved [Object], +46 silly resolved [Object], +46 silly resolved [Object], +46 silly resolved [Object], +46 silly resolved [Object], +46 silly resolved [Object], +46 silly resolved [Object] ], +46 silly resolved dependencies: +46 silly resolved { colors: '0.6.x', +46 silly resolved optimist: '0.5.x', +46 silly resolved union: '0.3.x', +46 silly resolved ecstatic: '0.4.x', +46 silly resolved portfinder: '0.2.x', +46 silly resolved opener: '~1.3.0' }, +46 silly resolved devDependencies: { vows: '0.7.x', request: '2.21.x' }, +46 silly resolved bugs: { url: 'https://github.com/nodeapps/http-server/issues' }, +46 silly resolved licenses: [ [Object] ], +46 silly resolved analyze: false, +46 silly resolved preferGlobal: 'true', +46 silly resolved bin: { 'http-server': './bin/http-server' }, +46 silly resolved readme: '# http-server: a command-line http server\n\n`http-server` is a simple, zero-configuration command-line http server. It is powerful enough for production usage, but it\'s simple and hackable enough to be used for testing, local development, and learning.\n\n![](https://github.com/nodeapps/http-server/raw/master/screenshots/public.png)\n\n# Installing globally:\n\nInstallation via `npm`. If you don\'t have `npm` yet:\n\n curl https://npmjs.org/install.sh | sh\n \nOnce you have `npm`:\n\n npm install http-server -g\n \nThis will install `http-server` globally so that it may be run from the command line.\n\n## Usage:\n\n http-server [path] [options]\n\n`[path]` defaults to `./public` if the folder exists, and `./` otherwise.\n\n# Installing as a node app\n\n mkdir myapp\n cd myapp/\n jitsu install http-server\n\n*If you do not have `jitsu` installed you can install it via `npm install jitsu -g`*\n\n## Usage\n\n### Starting http-server locally\n\n node bin/http-server\n\n*Now you can visit http://localhost:8080 to view your server*\n\n### Deploy http-server to nodejitsu\n\n jitsu deploy\n\n*You will now be prompted for a `subdomain` to deploy your application on*\n\n## Available Options:\n\n`-p` Port to listen for connections on (defaults to 8080)\n\n`-a` Address to bind to (defaults to \'0.0.0.0\')\n\n`-d` Show directory listings (defaults to \'True\')\n\n`-i` Display autoIndex (defaults to \'True\')\n\n`-e` or `--ext` Default file extension (defaults to \'html\')\n\n`-s` or `--silent` In silent mode, log messages aren\'t logged to the console.\n\n`-h` or `--help` Displays a list of commands and exits.\n\n`-c` Set cache time (in seconds) for cache-control max-age header, e.g. -c10 for 10 seconds. To disable caching, use -c-1.\n', +46 silly resolved readmeFilename: 'README.md', +46 silly resolved homepage: 'https://github.com/nodeapps/http-server', +46 silly resolved _id: 'http-server@0.6.1', +46 silly resolved dist: +46 silly resolved { shasum: '06fce65cf2bd4132a578bdac62ffacb97d613981', +46 silly resolved tarball: 'http://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz' }, +46 silly resolved _from: 'http-server@', +46 silly resolved _npmVersion: '1.3.14', +46 silly resolved _npmUser: { name: 'indexzero', email: 'charlie.robbins@gmail.com' }, +46 silly resolved maintainers: [ [Object], [Object], [Object] ], +46 silly resolved directories: {}, +46 silly resolved _shasum: '06fce65cf2bd4132a578bdac62ffacb97d613981', +46 silly resolved _resolved: 'https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz' } ] +47 info install http-server@0.6.1 into /usr/local/lib +48 info installOne http-server@0.6.1 +49 verbose lib/node_modules/http-server unbuild +50 verbose tar unpack /Users/loiane/.npm/http-server/0.6.1/package.tgz +51 silly lockFile c2cc12bc-cal-lib-node-modules-http-server tar:///usr/local/lib/node_modules/http-server +52 verbose lock tar:///usr/local/lib/node_modules/http-server /Users/loiane/.npm/c2cc12bc-cal-lib-node-modules-http-server.lock +53 silly lockFile 57f8618f-pm-http-server-0-6-1-package-tgz tar:///Users/loiane/.npm/http-server/0.6.1/package.tgz +54 verbose lock tar:///Users/loiane/.npm/http-server/0.6.1/package.tgz /Users/loiane/.npm/57f8618f-pm-http-server-0-6-1-package-tgz.lock +55 silly gunzTarPerm modes [ '755', '644' ] +56 error Error: EACCES, mkdir '/usr/local/lib/node_modules/http-server' +56 error { [Error: EACCES, mkdir '/usr/local/lib/node_modules/http-server'] +56 error errno: 3, +56 error code: 'EACCES', +56 error path: '/usr/local/lib/node_modules/http-server', +56 error fstream_type: 'Directory', +56 error fstream_path: '/usr/local/lib/node_modules/http-server', +56 error fstream_class: 'DirWriter', +56 error fstream_stack: +56 error [ '/usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23', +56 error '/usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:46:53', +56 error 'Object.oncomplete (fs.js:107:15)' ] } +57 error Please try running this command again as root/Administrator. +58 error System Darwin 13.3.0 +59 error command "node" "/usr/local/bin/npm" "install" "http-server" "-g" +60 error cwd /Applications/XAMPP/xamppfiles/htdocs/javascript-datastructures-algorithms +61 error node -v v0.10.31 +62 error npm -v 1.4.23 +63 error path /usr/local/lib/node_modules/http-server +64 error fstream_path /usr/local/lib/node_modules/http-server +65 error fstream_type Directory +66 error fstream_class DirWriter +67 error code EACCES +68 error errno 3 +69 error stack Error: EACCES, mkdir '/usr/local/lib/node_modules/http-server' +70 error fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23 +70 error fstream_stack /usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:46:53 +70 error fstream_stack Object.oncomplete (fs.js:107:15) +71 verbose exit [ 3, true ] From 1e39ccd7dfc90e38074f0b07594a12d1e450c444 Mon Sep 17 00:00:00 2001 From: loiane Date: Thu, 4 Sep 2014 17:49:32 -0300 Subject: [PATCH 26/54] added Fibonacci sequence fix --- chapter02/02-CreatingAndInitialingArrays.js | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/chapter02/02-CreatingAndInitialingArrays.js b/chapter02/02-CreatingAndInitialingArrays.js index a3d18fcd..1b20431e 100644 --- a/chapter02/02-CreatingAndInitialingArrays.js +++ b/chapter02/02-CreatingAndInitialingArrays.js @@ -19,13 +19,16 @@ for (var i=0; i Date: Thu, 4 Sep 2014 17:49:41 -0300 Subject: [PATCH 27/54] added more examples --- chapter02/05-ArrayMethods.js | 73 ++++++++++++++++++++++++++++++++---- 1 file changed, 65 insertions(+), 8 deletions(-) diff --git a/chapter02/05-ArrayMethods.js b/chapter02/05-ArrayMethods.js index eff8218b..7b59b8c0 100644 --- a/chapter02/05-ArrayMethods.js +++ b/chapter02/05-ArrayMethods.js @@ -4,7 +4,9 @@ var positiveNumbers = [1,2,3]; var negativeNumbers = [-3,-2,-1]; var numbers = negativeNumbers.concat(zero, positiveNumbers); -//document.writeln(numbers); +console.log(numbers); + +//console.log(numbers); //*** every and some var isEven = function (x) { @@ -24,24 +26,79 @@ numbers.forEach(function(x){ console.log((x % 2 == 0)); }); -document.writeln(numbers.reverse()); +console.log(numbers.reverse()); -//document.writeln('*** filter ***'); +//console.log('*** filter ***'); var evenNumbers = numbers.filter(isEven); -//document.writeln(evenNumbers); +//console.log(evenNumbers); + +console.log('*** map ***'); -document.writeln('*** map ***'); +//console.log(numbers.map(isEven)); -//document.writeln(numbers.map(isEven)); +console.log(numbers.reduce(function(previous, current, index){ + return previous + current; +})); -document.writeln(numbers.sort()); +console.log(numbers.sort()); -document.writeln(numbers.sort(function(a,b){ +console.log(numbers.sort(function(a,b){ return a-b; })); +function compare(a, b) { + if (a < b) { + return -1; + } + if (a > b) { + return 1; + } + // a must be equal to b + return 0; +} + +console.log(numbers.sort(compare)); + +//Sorting objects + +var friends = [ + {name: 'John', age: 30}, + {name: 'Ana', age: 20}, + {name: 'Chris', age: 25} +]; + +function comparePerson(a, b){ + if (a.age < b.age){ + return -1 + } + if (a.age > b.age){ + return 1 + } + return 0; +} + +console.log(friends.sort(comparePerson)); + +var names =['Ana', 'ana', 'john', 'John']; +console.log(names.sort()); + +console.log(names.sort(function(a, b){ + if (a.toLowerCase() < b.toLowerCase()){ + return -1 + } + if (a.toLowerCase() > b.toLowerCase()){ + return 1 + } + return 0; +})); + +var names2 = ['Maève', 'Maeve']; +console.log(names2.sort(function(a, b){ + return a.localeCompare(b); +})); + //*** toString console.log(numbers.toString()); From 48108dd2a2888f6865f4c316196fad2afdd28ac0 Mon Sep 17 00:00:00 2001 From: loiane Date: Thu, 4 Sep 2014 17:49:54 -0300 Subject: [PATCH 28/54] code refactor --- chapter03/01-Stack.js | 22 +++++++++++++++------- chapter04/01-Queue.js | 18 +++++++++++------- 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/chapter03/01-Stack.js b/chapter03/01-Stack.js index 139d5fea..0cb3960a 100644 --- a/chapter03/01-Stack.js +++ b/chapter03/01-Stack.js @@ -1,28 +1,36 @@ function Stack() { - this.items = []; + var items = []; this.push = function(element){ - this.items.push(element); + items.push(element); }; this.pop = function(){ - return this.items.pop(); + return items.pop(); }; this.peek = function(){ - return this.items[this.items.length-1]; + return items[items.length-1]; }; this.isEmpty = function(){ - return this.items.length == 0; + return items.length == 0; }; this.size = function(){ - return this.items.length; + return items.length; + }; + + this.clear = function(){ + items = []; }; this.print = function(){ - console.log(this.items.toString()); + console.log(items.toString()); + }; + + this.toString = function(){ + return items.toString(); }; } \ No newline at end of file diff --git a/chapter04/01-Queue.js b/chapter04/01-Queue.js index 6058724d..8656893a 100644 --- a/chapter04/01-Queue.js +++ b/chapter04/01-Queue.js @@ -1,28 +1,32 @@ function Queue() { - this.items = []; + var items = []; this.enqueue = function(element){ - this.items.push(element); + items.push(element); }; this.dequeue = function(){ - return this.items.shift(); + return items.shift(); }; this.front = function(){ - return this.items[0]; + return items[0]; }; this.isEmpty = function(){ - return this.items.length == 0; + return items.length == 0; + }; + + this.clear = function(){ + items = []; }; this.size = function(){ - return this.items.length; + return items.length; }; this.print = function(){ - console.log(this.items.toString()); + console.log(items.toString()); }; } From 86ab0e45c82b5864c8d2b82b148fb570bf57d788 Mon Sep 17 00:00:00 2001 From: loiane Date: Thu, 4 Sep 2014 17:50:16 -0300 Subject: [PATCH 29/54] code refactoring --- chapter03/05-TowerOfHanoi.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chapter03/05-TowerOfHanoi.js b/chapter03/05-TowerOfHanoi.js index 34205bc1..255e02fb 100644 --- a/chapter03/05-TowerOfHanoi.js +++ b/chapter03/05-TowerOfHanoi.js @@ -4,9 +4,9 @@ function towerOfHanoi(n, from, to, helper){ towerOfHanoi(n-1, from, helper, to); to.push(from.pop()); console.log('-----') - console.log('Source: ' + from.items.toString()); - console.log('Dest: ' + to.items.toString()); - console.log('Helper: ' + helper.items.toString()); + console.log('Source: ' + from.toString()); + console.log('Dest: ' + to.toString()); + console.log('Helper: ' + helper.toString()); towerOfHanoi(n-1, helper, to, from); } } From a4526c06c9a65779e50b6dd8870a368d4cf61baa Mon Sep 17 00:00:00 2001 From: loiane Date: Thu, 4 Sep 2014 17:51:03 -0300 Subject: [PATCH 30/54] code refactoring and bug fix --- chapter04/03-PriorityQueue.js | 37 +++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/chapter04/03-PriorityQueue.js b/chapter04/03-PriorityQueue.js index be93eff7..b7aa2d6b 100644 --- a/chapter04/03-PriorityQueue.js +++ b/chapter04/03-PriorityQueue.js @@ -1,46 +1,51 @@ function PriorityQueue() { - this.items = []; + var items = []; function QueueElement (element, priority){ - this.element = element; - this.priority = priority; + element = element; + priority = priority; } this.enqueue = function(element, priority){ var queueElement = new QueueElement(element, priority); - if (this.isEmpty()){ - this.items.push(queueElement); + if (isEmpty()){ + items.push(queueElement); } else { - for (var i=0; i Date: Thu, 4 Sep 2014 17:53:07 -0300 Subject: [PATCH 31/54] code refactoring --- chapter04/03-PriorityQueue.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/chapter04/03-PriorityQueue.js b/chapter04/03-PriorityQueue.js index b7aa2d6b..5b6442bb 100644 --- a/chapter04/03-PriorityQueue.js +++ b/chapter04/03-PriorityQueue.js @@ -3,14 +3,14 @@ function PriorityQueue() { var items = []; function QueueElement (element, priority){ - element = element; - priority = priority; + this.element = element; + this.priority = priority; } this.enqueue = function(element, priority){ var queueElement = new QueueElement(element, priority); - if (isEmpty()){ + if (this.isEmpty()){ items.push(queueElement); } else { var added = false; From 573a6b7f4c7ac6eb6ce729415f2bbd6123cfc6e9 Mon Sep 17 00:00:00 2001 From: loiane Date: Sat, 6 Sep 2014 14:48:30 -0300 Subject: [PATCH 32/54] added new examples --- chapter01/02-Variables.js | 30 ++++++++++++++++++++++---- chapter01/03-Operators.js | 23 ++++++++++++++++++-- chapter01/04-TruthyFalsy.html | 10 +++++++++ chapter01/04-TruthyFalsy.js | 23 ++++++++++++++++++++ chapter01/05-EqualsOperators.html | 10 +++++++++ chapter01/05-EqualsOperators.js | 36 +++++++++++++++++++++++++++++++ 6 files changed, 126 insertions(+), 6 deletions(-) create mode 100644 chapter01/04-TruthyFalsy.html create mode 100644 chapter01/04-TruthyFalsy.js create mode 100644 chapter01/05-EqualsOperators.html create mode 100644 chapter01/05-EqualsOperators.js diff --git a/chapter01/02-Variables.js b/chapter01/02-Variables.js index 502ad0e9..e75cf459 100644 --- a/chapter01/02-Variables.js +++ b/chapter01/02-Variables.js @@ -8,8 +8,30 @@ var nullVar = null; //{6} var und; //7 console.log("num: "+ num); -console.log("name: "+ num); -console.log("trueValue: "+ num); -console.log("price: "+ num); +console.log("name: "+ name); +console.log("trueValue: "+ trueValue); +console.log("price: "+ price); console.log("nullVar: "+ nullVar); -console.log("und: "+ und); \ No newline at end of file +console.log("und: "+ und); + +//******* Variable Scope + +var myVariable = 'global'; +myOtherVariable = 'global'; + +function myFunction(){ + var myVariable = 'local'; + return myVariable; +} + +function myOtherFunction(){ + myOtherVariable = 'local'; + return myOtherVariable; +} + +console.log(myVariable); //{1} +console.log(myFunction()); //{2} + +console.log(myOtherVariable); //{3} +console.log(myOtherFunction()); //{4} +console.log(myOtherVariable); //{5} diff --git a/chapter01/03-Operators.js b/chapter01/03-Operators.js index 3f1a0dcc..d1044b92 100644 --- a/chapter01/03-Operators.js +++ b/chapter01/03-Operators.js @@ -42,8 +42,27 @@ console.log('num < 1 : ' + (num < 1)); console.log('num >= 1 : ' + (num >= 1)); console.log('num <= 1 : ' + (num <= 1)); - /* Logical operators */ console.log('true && false : ' + (true && false)); console.log('true || false : ' + (true || false)); -console.log('!true : ' + (!true)); \ No newline at end of file +console.log('!true : ' + (!true)); + +/* Bitwise operators */ +console.log('5 & 1:', (5 & 1)); //same as 0101 & 0001 (result 0001 / 1) +console.log('5 | 1:', (5 | 1)); //same as 0101 | 0001 (result 0101 / 5) +console.log('~ 5:', (~5)); //same as ~0101 (result 1010 / 10) +console.log('5 ^ 1:', (5 ^ 1)); //same as 0101 ^ 0001 (result 0100 / 4) +console.log('5 << 1:', (5 << 1)); //same as 0101 << 1 (result 1010 / 10) +console.log('5 >> 1:', (5 >> 1)); //same as 0101 >> 1 (result 0010 / 2) + +/* typeOf */ +console.log('typeof num:', typeof num); +console.log('typeof Packt:', typeof 'Packt'); +console.log('typeof true:', typeof true); +console.log('typeof [1,2,3]:', typeof [1,2,3]); +console.log('typeof {name:John}:', typeof {name:'John'}); + +/* delete */ +var myObj = {name: 'John', age: 21}; +delete myObj.age; +console.log(myObj); //Object {name: "John"} \ No newline at end of file diff --git a/chapter01/04-TruthyFalsy.html b/chapter01/04-TruthyFalsy.html new file mode 100644 index 00000000..9b20f161 --- /dev/null +++ b/chapter01/04-TruthyFalsy.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter01/04-TruthyFalsy.js b/chapter01/04-TruthyFalsy.js new file mode 100644 index 00000000..d700cd2c --- /dev/null +++ b/chapter01/04-TruthyFalsy.js @@ -0,0 +1,23 @@ +function testTruthy(val){ + return val ? console.log('truthy') : console.log('falsy'); +} + +testTruthy(true); //true +testTruthy(false); //false +testTruthy(new Boolean(false)); //true (object is always true) + +testTruthy(''); //false +testTruthy('Packt'); //true +testTruthy(new String('')); //true (object is always true) + +testTruthy(1); //true +testTruthy(-1); //true +testTruthy(NaN); //false +testTruthy(new Number(NaN)); //true (object is always true) + +testTruthy({}); //true (object is always true) + +var obj = {name:'John'}; +testTruthy(obj); //true +testTruthy(obj.name); //true +testTruthy(obj.age); //age (prop does not exist) \ No newline at end of file diff --git a/chapter01/05-EqualsOperators.html b/chapter01/05-EqualsOperators.html new file mode 100644 index 00000000..bf26fbf3 --- /dev/null +++ b/chapter01/05-EqualsOperators.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/chapter01/05-EqualsOperators.js b/chapter01/05-EqualsOperators.js new file mode 100644 index 00000000..253c21b9 --- /dev/null +++ b/chapter01/05-EqualsOperators.js @@ -0,0 +1,36 @@ +//Packt == true + +console.log('packt' ? true : false); +//outputs true + +console.log('packt' == true); +//1 - converts Boolean using toNumber +//'packt' == 1 +//2 - converts String using toNumber +//NaN == 1 +//outputs false + +console.log('packt' == false); +//1 - converts Boolean using toNumber +//'packt' == 0 +//2 - converts String using toNumber +//NaN == 0 +//outputs false + +console.log([0] == true); +//1 - converts Boolean using toNumber +//[0] == 1 +//2 - converts Object using toPrimitive +//2.1 - [0].valueOf() is not primitive +//2.2 - [0].toString is 0 +//0 == 1 +//outputs false + +//******************************* === +console.log('packt' === true); //false + +console.log('packt' === 'packt'); //true + +var person1 = {name:'John'}; +var person2 = {name:'John'}; +console.log(person1 === person2); //false, different objects \ No newline at end of file From d665cf632947ed66d26b482d957578429d2d9fde Mon Sep 17 00:00:00 2001 From: loiane Date: Sat, 6 Sep 2014 14:48:45 -0300 Subject: [PATCH 33/54] added *.log --- .gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index bc8a670e..6fee6d3a 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -.idea/* \ No newline at end of file +.idea/* +*.log \ No newline at end of file From f4e3adcc454361b0ac583b506e05eabe32bf57d4 Mon Sep 17 00:00:00 2001 From: loiane Date: Sat, 6 Sep 2014 14:48:55 -0300 Subject: [PATCH 34/54] renamed files --- ...nts.html => 06-ConditionalStatements.html} | 2 +- ...tements.js => 06-ConditionalStatements.js} | 22 ++++++++++++++----- chapter01/{05-Loops.html => 07-Loops.html} | 2 +- chapter01/{05-Loops.js => 07-Loops.js} | 0 .../{06-Functions.html => 08-Functions.html} | 2 +- .../{06-Functions.js => 08-Functions.js} | 0 ...ientedJS.html => 09-ObjectOrientedJS.html} | 2 +- ...ctOrientedJS.js => 09-ObjectOrientedJS.js} | 0 8 files changed, 20 insertions(+), 10 deletions(-) rename chapter01/{04-ConditionalStatements.html => 06-ConditionalStatements.html} (64%) rename chapter01/{04-ConditionalStatements.js => 06-ConditionalStatements.js} (75%) rename chapter01/{05-Loops.html => 07-Loops.html} (64%) rename chapter01/{05-Loops.js => 07-Loops.js} (100%) rename chapter01/{06-Functions.html => 08-Functions.html} (62%) rename chapter01/{06-Functions.js => 08-Functions.js} (100%) rename chapter01/{07-ObjectOrientedJS.html => 09-ObjectOrientedJS.html} (63%) rename chapter01/{07-ObjectOrientedJS.js => 09-ObjectOrientedJS.js} (100%) diff --git a/chapter01/04-ConditionalStatements.html b/chapter01/06-ConditionalStatements.html similarity index 64% rename from chapter01/04-ConditionalStatements.html rename to chapter01/06-ConditionalStatements.html index d1f7d8f0..885a409b 100644 --- a/chapter01/04-ConditionalStatements.html +++ b/chapter01/06-ConditionalStatements.html @@ -5,6 +5,6 @@ - + \ No newline at end of file diff --git a/chapter01/04-ConditionalStatements.js b/chapter01/06-ConditionalStatements.js similarity index 75% rename from chapter01/04-ConditionalStatements.js rename to chapter01/06-ConditionalStatements.js index 3d9cf0e5..c7256c80 100644 --- a/chapter01/04-ConditionalStatements.js +++ b/chapter01/06-ConditionalStatements.js @@ -1,12 +1,12 @@ /* Example 01 - if */ var num = 1; -if (num == 1) { +if (num === 1) { console.log("num is equal to 1"); } /* Example 02 - if-else */ var num = 0; -if (num == 1) { +if (num === 1) { console.log("num is equal to 1"); } else { console.log("num is not equal to 1, the value of num is " + num); @@ -14,11 +14,11 @@ if (num == 1) { /* Example 03 - if-else-if-else... */ var month = 5; -if (month == 1) { +if (month === 1) { console.log("January"); -} else if (month == 2){ +} else if (month === 2){ console.log("February"); -} else if (month == 3){ +} else if (month === 3){ console.log("March"); } else { console.log("Month is not January, February or March"); @@ -38,4 +38,14 @@ switch(month) { break; default: console.log("Month is not January, February or March"); -} \ No newline at end of file +} + +/* Example 05 - ternary operator - if..else */ +if (num === 1){ + num--; +} else { + num++; +} + +//is the same as +(num === 1) ? num-- : num++; \ No newline at end of file diff --git a/chapter01/05-Loops.html b/chapter01/07-Loops.html similarity index 64% rename from chapter01/05-Loops.html rename to chapter01/07-Loops.html index 0fefd73b..e87a478f 100644 --- a/chapter01/05-Loops.html +++ b/chapter01/07-Loops.html @@ -5,6 +5,6 @@ - + \ No newline at end of file diff --git a/chapter01/05-Loops.js b/chapter01/07-Loops.js similarity index 100% rename from chapter01/05-Loops.js rename to chapter01/07-Loops.js diff --git a/chapter01/06-Functions.html b/chapter01/08-Functions.html similarity index 62% rename from chapter01/06-Functions.html rename to chapter01/08-Functions.html index 7468734f..cde89bcf 100644 --- a/chapter01/06-Functions.html +++ b/chapter01/08-Functions.html @@ -5,6 +5,6 @@ - + \ No newline at end of file diff --git a/chapter01/06-Functions.js b/chapter01/08-Functions.js similarity index 100% rename from chapter01/06-Functions.js rename to chapter01/08-Functions.js diff --git a/chapter01/07-ObjectOrientedJS.html b/chapter01/09-ObjectOrientedJS.html similarity index 63% rename from chapter01/07-ObjectOrientedJS.html rename to chapter01/09-ObjectOrientedJS.html index 91a3b533..9fef9dab 100644 --- a/chapter01/07-ObjectOrientedJS.html +++ b/chapter01/09-ObjectOrientedJS.html @@ -5,6 +5,6 @@ - + \ No newline at end of file diff --git a/chapter01/07-ObjectOrientedJS.js b/chapter01/09-ObjectOrientedJS.js similarity index 100% rename from chapter01/07-ObjectOrientedJS.js rename to chapter01/09-ObjectOrientedJS.js From bc3158a6f0f20c62b15593003f89b2dfcf99b0be Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 13 Sep 2014 11:23:32 -0300 Subject: [PATCH 35/54] fixed typos and refactored methods --- chapter06/01-Set.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/chapter06/01-Set.js b/chapter06/01-Set.js index 7791c03d..ea1eb6c1 100644 --- a/chapter06/01-Set.js +++ b/chapter06/01-Set.js @@ -25,7 +25,8 @@ function Set() { }; this.has = function(value){ - return value in items; + return items.hasOwnProperty(value); + //return value in items; }; this.clear = function(){ @@ -49,8 +50,7 @@ function Set() { this.sizeLegacy = function(){ var count = 0; for(var prop in items) { - if(items.hasOwnProperty(prop)) - ++count; + ++count; } return count; }; @@ -93,16 +93,16 @@ function Set() { }; this.intersection = function(otherSet){ - var insertectionSet = new Set(); //{1} + var intersectionSet = new Set(); //{1} var values = this.values(); for (var i=0; i Date: Sat, 13 Sep 2014 11:23:57 -0300 Subject: [PATCH 36/54] added one more example --- chapter06/02-UsingSets.js | 1 + 1 file changed, 1 insertion(+) diff --git a/chapter06/02-UsingSets.js b/chapter06/02-UsingSets.js index ebdd0671..2eb0a487 100644 --- a/chapter06/02-UsingSets.js +++ b/chapter06/02-UsingSets.js @@ -9,6 +9,7 @@ set.add(2); console.log(set.values()); //outputs ["1", "2"] console.log(set.has(2)); //true console.log(set.size()); //2 +console.log(set.sizeLegacy()); //3 set.remove(1); console.log(set.values()); //outputs ["2"] From f05375c81589897388db2b0a5af2b7af6e0930ee Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 13 Sep 2014 11:24:10 -0300 Subject: [PATCH 37/54] added example --- chapter06/03-Operations.js | 1 + 1 file changed, 1 insertion(+) diff --git a/chapter06/03-Operations.js b/chapter06/03-Operations.js index 571e34a4..fc866c0c 100644 --- a/chapter06/03-Operations.js +++ b/chapter06/03-Operations.js @@ -6,6 +6,7 @@ setA.add(2); setA.add(3); var setB = new Set(); +setB.add(3); setB.add(4); setB.add(5); setB.add(6); From 54da31ab49019bc0d1b228d61ea323da5c558172 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 13 Sep 2014 16:02:27 -0300 Subject: [PATCH 38/54] fixed code --- chapter06/01-Set.js | 3 ++- chapter07/01-Dictionaries.js | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/chapter06/01-Set.js b/chapter06/01-Set.js index ea1eb6c1..aff644a1 100644 --- a/chapter06/01-Set.js +++ b/chapter06/01-Set.js @@ -50,7 +50,8 @@ function Set() { this.sizeLegacy = function(){ var count = 0; for(var prop in items) { - ++count; + if(items.hasOwnProperty(prop)) + ++count; } return count; }; diff --git a/chapter07/01-Dictionaries.js b/chapter07/01-Dictionaries.js index 4f102099..695209ec 100644 --- a/chapter07/01-Dictionaries.js +++ b/chapter07/01-Dictionaries.js @@ -15,7 +15,8 @@ function Dictionary(){ }; this.has = function(key){ - return key in items; + return items.hasOwnProperty(value); + //return value in items; }; this.get = function(key) { From 0852027e18913830f454c2fdf0a03170c33d501c Mon Sep 17 00:00:00 2001 From: loiane Date: Mon, 15 Sep 2014 20:47:00 -0300 Subject: [PATCH 39/54] simplified toString method --- chapter05/01-Linked-List.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/chapter05/01-Linked-List.js b/chapter05/01-Linked-List.js index be63c981..3df7056f 100644 --- a/chapter05/01-Linked-List.js +++ b/chapter05/01-Linked-List.js @@ -149,15 +149,15 @@ function LinkedList() { this.toString = function(){ - var current = head, - s = current.element; + var current = head, + string = ''; - while(current.next){ + while (current) { + string = current.element; current = current.next; - s += ', ' + current.element; } + return string; - return s.toString(); }; this.print = function(){ From dd6e29bc0d3b491ce27a9fc63a1d7f0d0f4d9f24 Mon Sep 17 00:00:00 2001 From: loiane Date: Mon, 15 Sep 2014 20:47:14 -0300 Subject: [PATCH 40/54] added empty tree constraint --- chapter08/01-BinarySearchTree.js | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/chapter08/01-BinarySearchTree.js b/chapter08/01-BinarySearchTree.js index fe86e8fc..ae813fce 100644 --- a/chapter08/01-BinarySearchTree.js +++ b/chapter08/01-BinarySearchTree.js @@ -103,11 +103,14 @@ function BinarySearchTree() { }; var minNode = function (node) { - while (node && node.left !== null) { - node = node.left; - } + if (node){ + while (node && node.left !== null) { + node = node.left; + } - return node.key; + return node.key; + } + return null; }; this.max = function() { @@ -115,11 +118,14 @@ function BinarySearchTree() { }; var maxNode = function (node) { - while (node && node.right !== null) { - node = node.right; - } + if (node){ + while (node && node.right !== null) { + node = node.right; + } - return node.key; + return node.key; + } + return null; }; this.remove = function(element){ From e52f99f476cee4b1e3e429fcc1b2f6a9f54be876 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Mon, 15 Sep 2014 21:38:10 -0300 Subject: [PATCH 41/54] simplified some methods --- chapter05/01-Linked-List.js | 23 ++++------------------- 1 file changed, 4 insertions(+), 19 deletions(-) diff --git a/chapter05/01-Linked-List.js b/chapter05/01-Linked-List.js index 3df7056f..76556c09 100644 --- a/chapter05/01-Linked-List.js +++ b/chapter05/01-Linked-List.js @@ -107,29 +107,14 @@ function LinkedList() { this.indexOf = function(element){ var current = head, - index = -1; + index = 0; - //check first item - if (element == current.element){ - return 0; - } - - index++; - - //check in the middle of the list - while(current.next){ - - if (element == current.element){ + while (current) { + if (element === current.element) { return index; } - - current = current.next; index++; - } - - //check last item - if (element == current.element){ - return index; + current = current.next; } return -1; From a3ca7bb8f851ef497b5bf41b00917d47178ffb51 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Mon, 15 Sep 2014 21:54:32 -0300 Subject: [PATCH 42/54] added constraint - empty list --- chapter05/03-Doubly-Linked-List.js | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/chapter05/03-Doubly-Linked-List.js b/chapter05/03-Doubly-Linked-List.js index 0197cb19..1ca53298 100644 --- a/chapter05/03-Doubly-Linked-List.js +++ b/chapter05/03-Doubly-Linked-List.js @@ -42,11 +42,16 @@ function DoublyLinkedList() { if (position === 0){ //add on first position - node.next = current; - current.prev = node; //NEW {1} - head = node; + if (!head){ //NEW + head = node; + tail = node; + } else { + node.next = current; + current.prev = node; //NEW {1} + head = node; + } - } else if (position === length-1) { //last item //NEW + } else if (position === length) { //last item //NEW current = tail; // {2} current.next = node; From f6a56ddbfa6592bb9236be245bf8ae9cefa4526c Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Mon, 15 Sep 2014 21:54:37 -0300 Subject: [PATCH 43/54] added new test --- chapter05/04-UsingDoublyLinkedLists.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapter05/04-UsingDoublyLinkedLists.js b/chapter05/04-UsingDoublyLinkedLists.js index 31fba8e8..00534d49 100644 --- a/chapter05/04-UsingDoublyLinkedLists.js +++ b/chapter05/04-UsingDoublyLinkedLists.js @@ -16,7 +16,7 @@ list.insert(0,13); list.print(); list.printInverse(); -list.insert(list.size()-1,18); +list.insert(4,18); list.print(); list.printInverse(); From a124b542f0ff87254ca532ee12245e38359f2b75 Mon Sep 17 00:00:00 2001 From: loiane Date: Tue, 23 Sep 2014 10:23:09 -0300 Subject: [PATCH 44/54] fixed issue --- chapter07/01-Dictionaries.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/chapter07/01-Dictionaries.js b/chapter07/01-Dictionaries.js index 695209ec..ea26cd05 100644 --- a/chapter07/01-Dictionaries.js +++ b/chapter07/01-Dictionaries.js @@ -15,7 +15,7 @@ function Dictionary(){ }; this.has = function(key){ - return items.hasOwnProperty(value); + return items.hasOwnProperty(key); //return value in items; }; From 7f9c822bf579a840516d40bc6d643cccbee5e0a4 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sun, 28 Sep 2014 21:31:52 -0300 Subject: [PATCH 45/54] modified toString --- chapter10/01-SortingSearchingAlgorithms.js | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/chapter10/01-SortingSearchingAlgorithms.js b/chapter10/01-SortingSearchingAlgorithms.js index 1204ace2..b4081024 100755 --- a/chapter10/01-SortingSearchingAlgorithms.js +++ b/chapter10/01-SortingSearchingAlgorithms.js @@ -13,11 +13,7 @@ function ArrayList(){ }; this.toString= function(){ - var s = array[0] ? array[0] : ''; - for (var i=1; i Date: Sun, 28 Sep 2014 21:32:06 -0300 Subject: [PATCH 46/54] added new example to chapter 11 --- chapter11/02-InfiniteRecursion.js | 15 +++++++++++++++ chapter11/05-BigONotation.html | 10 ++++++++++ 2 files changed, 25 insertions(+) create mode 100644 chapter11/02-InfiniteRecursion.js create mode 100644 chapter11/05-BigONotation.html diff --git a/chapter11/02-InfiniteRecursion.js b/chapter11/02-InfiniteRecursion.js new file mode 100644 index 00000000..2ca26d33 --- /dev/null +++ b/chapter11/02-InfiniteRecursion.js @@ -0,0 +1,15 @@ +var i = 0; + +function recursiveFn () { + i++; + recursiveFn(); +} + +try { + recursiveFn(); +} catch (ex) { + alert('i = ' + i + ' error: ' + ex); +} + +//chrome 37 = 20955 RangeError: Maximum call stack size exceeded +//ff 27 = 343429 InternalError: too much recursion \ No newline at end of file diff --git a/chapter11/05-BigONotation.html b/chapter11/05-BigONotation.html new file mode 100644 index 00000000..317a5bfb --- /dev/null +++ b/chapter11/05-BigONotation.html @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file From 87e9c04e5499c1198126fbb9d6f279d34ea1cb62 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sun, 28 Sep 2014 21:32:22 -0300 Subject: [PATCH 47/54] renamed files --- chapter11/{04-BigONotation.html => 02-InfiniteRecursion.html} | 2 +- chapter11/{02-MinCoinChangeDP.html => 03-MinCoinChangeDP.html} | 2 +- chapter11/{02-MinCoinChangeDP.js => 03-MinCoinChangeDP.js} | 0 ...{03-MinCoinChangeGreedy.html => 04-MinCoinChangeGreedy.html} | 2 +- .../{03-MinCoinChangeGreedy.js => 04-MinCoinChangeGreedy.js} | 0 chapter11/{04-BigONotation.js => 05-BigONotation.js} | 0 6 files changed, 3 insertions(+), 3 deletions(-) rename chapter11/{04-BigONotation.html => 02-InfiniteRecursion.html} (60%) rename chapter11/{02-MinCoinChangeDP.html => 03-MinCoinChangeDP.html} (63%) rename chapter11/{02-MinCoinChangeDP.js => 03-MinCoinChangeDP.js} (100%) rename chapter11/{03-MinCoinChangeGreedy.html => 04-MinCoinChangeGreedy.html} (64%) rename chapter11/{03-MinCoinChangeGreedy.js => 04-MinCoinChangeGreedy.js} (100%) rename chapter11/{04-BigONotation.js => 05-BigONotation.js} (100%) diff --git a/chapter11/04-BigONotation.html b/chapter11/02-InfiniteRecursion.html similarity index 60% rename from chapter11/04-BigONotation.html rename to chapter11/02-InfiniteRecursion.html index 995ac4d9..e51a8132 100644 --- a/chapter11/04-BigONotation.html +++ b/chapter11/02-InfiniteRecursion.html @@ -5,6 +5,6 @@ - + \ No newline at end of file diff --git a/chapter11/02-MinCoinChangeDP.html b/chapter11/03-MinCoinChangeDP.html similarity index 63% rename from chapter11/02-MinCoinChangeDP.html rename to chapter11/03-MinCoinChangeDP.html index 7516a9da..c4171470 100644 --- a/chapter11/02-MinCoinChangeDP.html +++ b/chapter11/03-MinCoinChangeDP.html @@ -5,6 +5,6 @@ - + \ No newline at end of file diff --git a/chapter11/02-MinCoinChangeDP.js b/chapter11/03-MinCoinChangeDP.js similarity index 100% rename from chapter11/02-MinCoinChangeDP.js rename to chapter11/03-MinCoinChangeDP.js diff --git a/chapter11/03-MinCoinChangeGreedy.html b/chapter11/04-MinCoinChangeGreedy.html similarity index 64% rename from chapter11/03-MinCoinChangeGreedy.html rename to chapter11/04-MinCoinChangeGreedy.html index 7ebac53d..cc01ddc2 100644 --- a/chapter11/03-MinCoinChangeGreedy.html +++ b/chapter11/04-MinCoinChangeGreedy.html @@ -5,6 +5,6 @@ - + \ No newline at end of file diff --git a/chapter11/03-MinCoinChangeGreedy.js b/chapter11/04-MinCoinChangeGreedy.js similarity index 100% rename from chapter11/03-MinCoinChangeGreedy.js rename to chapter11/04-MinCoinChangeGreedy.js diff --git a/chapter11/04-BigONotation.js b/chapter11/05-BigONotation.js similarity index 100% rename from chapter11/04-BigONotation.js rename to chapter11/05-BigONotation.js From 37e35765cb0ad43b21387e5255a0b554bd87c467 Mon Sep 17 00:00:00 2001 From: Jonathan Haygood Date: Mon, 17 Nov 2014 22:52:03 -0800 Subject: [PATCH 48/54] Add concatenation to toString() A number of different routes could be taken to print out the list. This change will concatenate the string to print each element on a separate line. --- chapter05/01-Linked-List.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapter05/01-Linked-List.js b/chapter05/01-Linked-List.js index 76556c09..d4f4637f 100644 --- a/chapter05/01-Linked-List.js +++ b/chapter05/01-Linked-List.js @@ -138,7 +138,7 @@ function LinkedList() { string = ''; while (current) { - string = current.element; + string += current.element + (current.next ? '\n' : ''); current = current.next; } return string; @@ -148,4 +148,4 @@ function LinkedList() { this.print = function(){ console.log(this.toString()); }; -} \ No newline at end of file +} From 6f8ad8ee7987bd4db793fb3b67021ba6056165d0 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Thu, 29 Jan 2015 09:27:28 -0200 Subject: [PATCH 49/54] fixed - missed array creation. --- chapter02/01-Introduction.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/chapter02/01-Introduction.js b/chapter02/01-Introduction.js index 737ad09b..93d80a8d 100644 --- a/chapter02/01-Introduction.js +++ b/chapter02/01-Introduction.js @@ -4,8 +4,9 @@ var averageTempMar = 42.4; var averageTempApr = 52; var averageTempMay = 60.8; +var averageTemp = []; averageTemp[0] = 31.9; averageTemp[1] = 35.3; averageTemp[2] = 42.4; averageTemp[3] = 52; -averageTemp[4] = 60.8; \ No newline at end of file +averageTemp[4] = 60.8; From 10b0c041a5b9d5530ff9902a1dd51c4d1f6f5cc2 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Wed, 18 Mar 2015 17:47:11 -0300 Subject: [PATCH 50/54] Update README.md --- README.md | 28 ++++++++++++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b4771d7f..8facc4a0 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,28 @@ -javascript-datastructures-algorithms +Learning JavaScript Data Structures and Algorithms ==================================== -JavaScript algorithms +Source code of **Learning JavaScript Data Structures and Algorithms** book. + +Book link: + - [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms) + - [Amazon](http://www.amazon.com/gp/product/1783554878/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1783554878&linkCode=as2&tag=loiagron-20&linkId=7VBQ7OMJ47XY7MUV) + + +###List of Chapters: + +* 1: JAVASCRIPT – A QUICK OVERVIEW +* 2: ARRAYS +* 3: STACKS +* 4: QUEUES +* 5: LINKED LISTS +* 6: SETS +* 7: DICTIONARIES AND HASHES +* 8: TREES +* 9: GRAPHS +* 10: SORTING AND SEARCHING ALGORITHMS +* 11: More about Algorithms (Recursion, Dynamic Programing, Greedy Algorithms and Big-O Notation) - Extra chapter that can be donwloaded from [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms) website +* Apendix A: Big-O Cheat Sheet - Extra chapter that can be donwloaded from [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms) website + +###Found and issue or have a question? + +Please create an [Issue](https://github.com/loiane/javascript-datastructures-algorithms/issues) or [Pull Request](https://github.com/loiane/javascript-datastructures-algorithms/pulls) From a7285d9d526352f7676b47c7b12c283718aa9d57 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Fri, 27 Mar 2015 21:41:28 -0300 Subject: [PATCH 51/54] fixed typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8facc4a0..9712708a 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,6 @@ Book link: * 11: More about Algorithms (Recursion, Dynamic Programing, Greedy Algorithms and Big-O Notation) - Extra chapter that can be donwloaded from [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms) website * Apendix A: Big-O Cheat Sheet - Extra chapter that can be donwloaded from [Packt](https://www.packtpub.com/application-development/learning-javascript-data-structures-and-algorithms) website -###Found and issue or have a question? +###Found an issue or have a question? Please create an [Issue](https://github.com/loiane/javascript-datastructures-algorithms/issues) or [Pull Request](https://github.com/loiane/javascript-datastructures-algorithms/pulls) From d12ebc24e373f246666cc9fe409e45de0adf2e1b Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 27 Feb 2016 15:57:46 -0300 Subject: [PATCH 52/54] Update 03-AVLTree.js --- chapter08/03-AVLTree.js | 149 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 149 insertions(+) diff --git a/chapter08/03-AVLTree.js b/chapter08/03-AVLTree.js index e69de29b..277a22b6 100644 --- a/chapter08/03-AVLTree.js +++ b/chapter08/03-AVLTree.js @@ -0,0 +1,149 @@ +function AVLTree() { + + var Node = function(key){ + this.key = key; + this.left = null; + this.right = null; + }; + + var root = null; + + this.getRoot = function(){ + return root; + }; + + var heightNode = function(node) { + if (node === null) { + return -1; + } else { + return Math.max(heightNode(node.left), heightNode(node.right)) + 1; + } + }; + + var rotationLL = function(node) { + var tmp = node.left; + node.left = tmp.right; + tmp.right = node; + + return tmp; + }; + + var rotationRR = function(node) { + var tmp = node.right; + node.right = tmp.left; + tmp.left = node; + + return tmp; + }; + + var rotationLR = function(node) { + node.left = rotationRR(node.left); + return rotationLL(node); + }; + + var rotationRL = function(node) { + node.right = rotationLL(node.right); + return rotationRR(node); + }; + + var insertNode = function(node, element) { + + if (node === null) { + node = new Node(element); + + } else if (element < node.key) { + + node.left = insertNode(node.left, element); + + if (node.left !== null) { + + if ((heightNode(node.left) - heightNode(node.right)) > 1){ + if (element < node.left.key){ + node = rotationLL(node); + } else { + node = rotationLR(node); + } + } + } + } else if (element > node.key) { + + node.right = insertNode(node.right, element); + + if (node.right !== null) { + + if ((heightNode(node.right) - heightNode(node.left)) > 1){ + + if (element > node.right.key){ + node = rotationRR(node); + } else { + node = rotationRL(node); + } + } + } + } + + return node; + }; + + this.insert = function(element) { + root = insertNode(root, element); + }; + + var parentNode; + var nodeToBeDeleted; + + var removeNode = function(node, element) { + if (node === null) { + return null; + } + parentNode = node; + + if (element < node.key) { + node.left = removeNode(node.left, element); + } else { + nodeToBeDeleted = node; + node.right = removeNode(node.right, element); + } + + if (node === parentNode) { //remove node + if (nodeToBeDeleted !== null && element === nodeToBeDeleted.key) { + if (nodeToBeDeleted === parentNode) { + node = node.left; + } else { + var tmp = nodeToBeDeleted.key; + nodeToBeDeleted.key = parentNode.key; + parentNode.key = tmp; + node = node.right; + } + } + } else { //do balancing + + if (node.left === undefined) node.left = null; + if (node.right === undefined) node.right = null; + + if ((heightNode(node.left) - heightNode(node.right)) === 2) { + if (element < node.left.key) { + node = rotationLR(node); + } else { + node = rotationLL(node); + } + } + + if ((heightNode(node.right) - heightNode(node.left)) === 2) { + if (element > node.right.key) { + node = rotationRL(node); + } else { + node = rotationRR(node); + } + } + } + + return node; + }; + + this.remove = function(element) { + parentNode = null; + nodeToBeDeleted = null; + root = removeNode(root, element); + }; +} From 2ac724e0b4017458738e808b772fcb49ea7e7949 Mon Sep 17 00:00:00 2001 From: Loiane Groner Date: Sat, 27 Feb 2016 15:58:06 -0300 Subject: [PATCH 53/54] Update 04-UsingAVLTree.js --- chapter08/04-UsingAVLTree.js | 61 ++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/chapter08/04-UsingAVLTree.js b/chapter08/04-UsingAVLTree.js index e69de29b..1f70c66c 100644 --- a/chapter08/04-UsingAVLTree.js +++ b/chapter08/04-UsingAVLTree.js @@ -0,0 +1,61 @@ +var avlTree = new AVLTree(); + +avlTree.insert(1); +avlTree.insert(2); +avlTree.insert(3); +avlTree.insert(4); +avlTree.insert(5); +avlTree.insert(6); +avlTree.insert(7); +avlTree.insert(14); +avlTree.insert(15); +avlTree.insert(13); +avlTree.insert(12); +avlTree.insert(11); + +//RR rotation +/*avlTree.insert(50); +avlTree.insert(30); +avlTree.insert(70); +avlTree.insert(60); +avlTree.insert(80); +avlTree.insert(90);*/ + +//LL rotation +/*avlTree.insert(50); +avlTree.insert(30); +avlTree.insert(70); +avlTree.insert(10); +avlTree.insert(40); +avlTree.insert(5);*/ + +//LR rotation +/*avlTree.insert(50); +avlTree.insert(30); +avlTree.insert(70); +avlTree.insert(40); +avlTree.insert(10); +avlTree.insert(35);*/ + +//RL rotation +/*avlTree.insert(70); +avlTree.insert(50); +avlTree.insert(80); +avlTree.insert(72); +avlTree.insert(90); +avlTree.insert(75);*/ + +console.log('********* raw data structure ***********'); +console.log(avlTree.getRoot()); + +/*avlTree.remove(12); +avlTree.remove(15); +avlTree.remove(11); +avlTree.remove(14); +avlTree.remove(13); +avlTree.remove(7); +avlTree.remove(6); +avlTree.remove(2); +avlTree.remove(4); + +console.log(avlTree.getRoot());*/ From 9945233c4fd172a28a26aa8d1a8b555cd19991af Mon Sep 17 00:00:00 2001 From: loiane Date: Thu, 7 Sep 2017 09:16:04 -0300 Subject: [PATCH 54/54] gitignore --- .gitignore | 4 +- npm-debug.log | 180 -------------------------------------------------- 2 files changed, 3 insertions(+), 181 deletions(-) delete mode 100644 npm-debug.log diff --git a/.gitignore b/.gitignore index 6fee6d3a..2458e8b0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ .idea/* -*.log \ No newline at end of file +*.log +node_modules +coverage diff --git a/npm-debug.log b/npm-debug.log deleted file mode 100644 index 324f5d2d..00000000 --- a/npm-debug.log +++ /dev/null @@ -1,180 +0,0 @@ -0 info it worked if it ends with ok -1 verbose cli [ 'node', '/usr/local/bin/npm', 'install', 'http-server', '-g' ] -2 info using npm@1.4.23 -3 info using node@v0.10.31 -4 verbose cache add [ 'http-server', null ] -5 verbose cache add name=undefined spec="http-server" args=["http-server",null] -6 verbose parsed url { protocol: null, -6 verbose parsed url slashes: null, -6 verbose parsed url auth: null, -6 verbose parsed url host: null, -6 verbose parsed url port: null, -6 verbose parsed url hostname: null, -6 verbose parsed url hash: null, -6 verbose parsed url search: null, -6 verbose parsed url query: null, -6 verbose parsed url pathname: 'http-server', -6 verbose parsed url path: 'http-server', -6 verbose parsed url href: 'http-server' } -7 silly lockFile ed608307-http-server http-server -8 verbose lock http-server /Users/loiane/.npm/ed608307-http-server.lock -9 silly lockFile ed608307-http-server http-server -10 silly lockFile ed608307-http-server http-server -11 verbose addNamed [ 'http-server', '' ] -12 verbose addNamed [ null, '*' ] -13 silly lockFile 550353c6-http-server http-server@ -14 verbose lock http-server@ /Users/loiane/.npm/550353c6-http-server.lock -15 silly addNameRange { name: 'http-server', range: '*', hasData: false } -16 verbose request where is /http-server -17 verbose request registry https://registry.npmjs.org/ -18 verbose request id 5de596c601e747df -19 verbose url raw /http-server -20 verbose url resolving [ 'https://registry.npmjs.org/', './http-server' ] -21 verbose url resolved https://registry.npmjs.org/http-server -22 verbose request where is https://registry.npmjs.org/http-server -23 info trying registry request attempt 1 at 16:26:40 -24 http GET https://registry.npmjs.org/http-server -25 http 200 https://registry.npmjs.org/http-server -26 silly registry.get cb [ 200, -26 silly registry.get { date: 'Mon, 01 Sep 2014 19:26:41 GMT', -26 silly registry.get server: 'CouchDB/1.5.0 (Erlang OTP/R16B03)', -26 silly registry.get etag: '"GRUZZAK9N6WU29IC3EFS78GW"', -26 silly registry.get 'content-type': 'application/json', -26 silly registry.get 'cache-control': 'max-age=60', -26 silly registry.get 'content-length': '42618', -26 silly registry.get 'accept-ranges': 'bytes', -26 silly registry.get via: '1.1 varnish', -26 silly registry.get age: '942', -26 silly registry.get 'x-served-by': 'cache-iad2134-IAD', -26 silly registry.get 'x-cache': 'HIT', -26 silly registry.get 'x-cache-hits': '1', -26 silly registry.get 'x-timer': 'S1409599601.088721,VS0,VE16', -26 silly registry.get vary: 'Accept', -26 silly registry.get 'keep-alive': 'timeout=10, max=50', -26 silly registry.get connection: 'Keep-Alive' } ] -27 silly addNameRange number 2 { name: 'http-server', range: '*', hasData: true } -28 silly addNameRange versions [ 'http-server', -28 silly addNameRange [ '0.1.0', -28 silly addNameRange '0.1.1', -28 silly addNameRange '0.1.3', -28 silly addNameRange '0.2.1', -28 silly addNameRange '0.2.2', -28 silly addNameRange '0.2.3', -28 silly addNameRange '0.2.4', -28 silly addNameRange '0.2.5', -28 silly addNameRange '0.2.6', -28 silly addNameRange '0.2.9', -28 silly addNameRange '0.3.0', -28 silly addNameRange '0.4.0', -28 silly addNameRange '0.4.1', -28 silly addNameRange '0.5.0', -28 silly addNameRange '0.5.1', -28 silly addNameRange '0.5.2', -28 silly addNameRange '0.5.3', -28 silly addNameRange '0.5.5', -28 silly addNameRange '0.6.0', -28 silly addNameRange '0.6.1' ] ] -29 verbose addNamed [ 'http-server', '0.6.1' ] -30 verbose addNamed [ '0.6.1', '0.6.1' ] -31 silly lockFile 1e2b2518-http-server-0-6-1 http-server@0.6.1 -32 verbose lock http-server@0.6.1 /Users/loiane/.npm/1e2b2518-http-server-0-6-1.lock -33 silly lockFile c3f4b4b6-ttp-server-http-server-0-6-1-tgz https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz -34 verbose lock https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz /Users/loiane/.npm/c3f4b4b6-ttp-server-http-server-0-6-1-tgz.lock -35 verbose addRemoteTarball [ 'https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz', -35 verbose addRemoteTarball '06fce65cf2bd4132a578bdac62ffacb97d613981' ] -36 info retry fetch attempt 1 at 16:26:42 -37 verbose fetch to= /var/folders/p6/h5zxx5c5153gfhgsvg1_s6n80000gn/T/npm-4783-wjg257Iq/registry.npmjs.org/http-server/-/http-server-0.6.1.tgz -38 http GET https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz -39 http 200 https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz -40 silly lockFile c3f4b4b6-ttp-server-http-server-0-6-1-tgz https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz -41 silly lockFile c3f4b4b6-ttp-server-http-server-0-6-1-tgz https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz -42 silly lockFile 1e2b2518-http-server-0-6-1 http-server@0.6.1 -43 silly lockFile 1e2b2518-http-server-0-6-1 http-server@0.6.1 -44 silly lockFile 550353c6-http-server http-server@ -45 silly lockFile 550353c6-http-server http-server@ -46 silly resolved [ { name: 'http-server', -46 silly resolved version: '0.6.1', -46 silly resolved author: { name: 'Nodejitsu', email: 'support@nodejitsu.com' }, -46 silly resolved description: 'a simple zero-configuration command-line http server', -46 silly resolved main: './lib/http-server', -46 silly resolved repository: -46 silly resolved { type: 'git', -46 silly resolved url: 'git://github.com/nodeapps/http-server.git' }, -46 silly resolved keywords: [ 'cli', 'command' ], -46 silly resolved scripts: -46 silly resolved { start: 'node ./bin/http-server', -46 silly resolved test: 'vows --spec --isolate' }, -46 silly resolved contributors: -46 silly resolved [ [Object], -46 silly resolved [Object], -46 silly resolved [Object], -46 silly resolved [Object], -46 silly resolved [Object], -46 silly resolved [Object], -46 silly resolved [Object], -46 silly resolved [Object] ], -46 silly resolved dependencies: -46 silly resolved { colors: '0.6.x', -46 silly resolved optimist: '0.5.x', -46 silly resolved union: '0.3.x', -46 silly resolved ecstatic: '0.4.x', -46 silly resolved portfinder: '0.2.x', -46 silly resolved opener: '~1.3.0' }, -46 silly resolved devDependencies: { vows: '0.7.x', request: '2.21.x' }, -46 silly resolved bugs: { url: 'https://github.com/nodeapps/http-server/issues' }, -46 silly resolved licenses: [ [Object] ], -46 silly resolved analyze: false, -46 silly resolved preferGlobal: 'true', -46 silly resolved bin: { 'http-server': './bin/http-server' }, -46 silly resolved readme: '# http-server: a command-line http server\n\n`http-server` is a simple, zero-configuration command-line http server. It is powerful enough for production usage, but it\'s simple and hackable enough to be used for testing, local development, and learning.\n\n![](https://github.com/nodeapps/http-server/raw/master/screenshots/public.png)\n\n# Installing globally:\n\nInstallation via `npm`. If you don\'t have `npm` yet:\n\n curl https://npmjs.org/install.sh | sh\n \nOnce you have `npm`:\n\n npm install http-server -g\n \nThis will install `http-server` globally so that it may be run from the command line.\n\n## Usage:\n\n http-server [path] [options]\n\n`[path]` defaults to `./public` if the folder exists, and `./` otherwise.\n\n# Installing as a node app\n\n mkdir myapp\n cd myapp/\n jitsu install http-server\n\n*If you do not have `jitsu` installed you can install it via `npm install jitsu -g`*\n\n## Usage\n\n### Starting http-server locally\n\n node bin/http-server\n\n*Now you can visit http://localhost:8080 to view your server*\n\n### Deploy http-server to nodejitsu\n\n jitsu deploy\n\n*You will now be prompted for a `subdomain` to deploy your application on*\n\n## Available Options:\n\n`-p` Port to listen for connections on (defaults to 8080)\n\n`-a` Address to bind to (defaults to \'0.0.0.0\')\n\n`-d` Show directory listings (defaults to \'True\')\n\n`-i` Display autoIndex (defaults to \'True\')\n\n`-e` or `--ext` Default file extension (defaults to \'html\')\n\n`-s` or `--silent` In silent mode, log messages aren\'t logged to the console.\n\n`-h` or `--help` Displays a list of commands and exits.\n\n`-c` Set cache time (in seconds) for cache-control max-age header, e.g. -c10 for 10 seconds. To disable caching, use -c-1.\n', -46 silly resolved readmeFilename: 'README.md', -46 silly resolved homepage: 'https://github.com/nodeapps/http-server', -46 silly resolved _id: 'http-server@0.6.1', -46 silly resolved dist: -46 silly resolved { shasum: '06fce65cf2bd4132a578bdac62ffacb97d613981', -46 silly resolved tarball: 'http://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz' }, -46 silly resolved _from: 'http-server@', -46 silly resolved _npmVersion: '1.3.14', -46 silly resolved _npmUser: { name: 'indexzero', email: 'charlie.robbins@gmail.com' }, -46 silly resolved maintainers: [ [Object], [Object], [Object] ], -46 silly resolved directories: {}, -46 silly resolved _shasum: '06fce65cf2bd4132a578bdac62ffacb97d613981', -46 silly resolved _resolved: 'https://registry.npmjs.org/http-server/-/http-server-0.6.1.tgz' } ] -47 info install http-server@0.6.1 into /usr/local/lib -48 info installOne http-server@0.6.1 -49 verbose lib/node_modules/http-server unbuild -50 verbose tar unpack /Users/loiane/.npm/http-server/0.6.1/package.tgz -51 silly lockFile c2cc12bc-cal-lib-node-modules-http-server tar:///usr/local/lib/node_modules/http-server -52 verbose lock tar:///usr/local/lib/node_modules/http-server /Users/loiane/.npm/c2cc12bc-cal-lib-node-modules-http-server.lock -53 silly lockFile 57f8618f-pm-http-server-0-6-1-package-tgz tar:///Users/loiane/.npm/http-server/0.6.1/package.tgz -54 verbose lock tar:///Users/loiane/.npm/http-server/0.6.1/package.tgz /Users/loiane/.npm/57f8618f-pm-http-server-0-6-1-package-tgz.lock -55 silly gunzTarPerm modes [ '755', '644' ] -56 error Error: EACCES, mkdir '/usr/local/lib/node_modules/http-server' -56 error { [Error: EACCES, mkdir '/usr/local/lib/node_modules/http-server'] -56 error errno: 3, -56 error code: 'EACCES', -56 error path: '/usr/local/lib/node_modules/http-server', -56 error fstream_type: 'Directory', -56 error fstream_path: '/usr/local/lib/node_modules/http-server', -56 error fstream_class: 'DirWriter', -56 error fstream_stack: -56 error [ '/usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23', -56 error '/usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:46:53', -56 error 'Object.oncomplete (fs.js:107:15)' ] } -57 error Please try running this command again as root/Administrator. -58 error System Darwin 13.3.0 -59 error command "node" "/usr/local/bin/npm" "install" "http-server" "-g" -60 error cwd /Applications/XAMPP/xamppfiles/htdocs/javascript-datastructures-algorithms -61 error node -v v0.10.31 -62 error npm -v 1.4.23 -63 error path /usr/local/lib/node_modules/http-server -64 error fstream_path /usr/local/lib/node_modules/http-server -65 error fstream_type Directory -66 error fstream_class DirWriter -67 error code EACCES -68 error errno 3 -69 error stack Error: EACCES, mkdir '/usr/local/lib/node_modules/http-server' -70 error fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23 -70 error fstream_stack /usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:46:53 -70 error fstream_stack Object.oncomplete (fs.js:107:15) -71 verbose exit [ 3, true ]