diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/2-1.js b/js/hanbit-data-structures-and-algorithms-with-js/02/2-1.js new file mode 100644 index 0000000000..3797c3a009 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/2-1.js @@ -0,0 +1,24 @@ +// 02 배열 - 2 배열 사용하기 - 1 배열 만들기 + +var numbers1 = []; +console.log(numbers1.length); // 0 + +var numbers2 = [1,2,3,4,5]; +console.log(numbers2.length); // 5 + +var numbers3 = new Array(); +console.log(numbers3.length); // 0 + +var numbers4 = new Array(1,2,3,4,5); +console.log(numbers4.length); // 5 + +var numbers5 = new Array(10); +console.log(numbers5.length); // 10 + +var objects = [1, 'Joe', true, null]; + + +var numbers = 3; +var arr = [7,4,1776]; +console.log(Array.isArray(numbers)); // false +console.log(Array.isArray(arr)); // true \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/2-2.js b/js/hanbit-data-structures-and-algorithms-with-js/02/2-2.js new file mode 100644 index 0000000000..62f3cf601a --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/2-2.js @@ -0,0 +1,17 @@ +// 02 배열 - 2 배열 사용하기 - 2 배열 요소 접근하고 값 고치기 + +var nums = []; +for (var i = 0; i < 100; ++i) { + nums[i] = i+1; +} + +var numbers = [1,2,3,4,5]; +var sum = numbers[0] + numbers[1] + numbers[2] + numbers[3] + numbers[4]; +console.log(sum); // 15 + +var result = 0; +for (var i = 0; i < numbers.length; ++i) { + result += numbers[i]; +} + +console.log(result); // 15 \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/2-3.js b/js/hanbit-data-structures-and-algorithms-with-js/02/2-3.js new file mode 100644 index 0000000000..fdfb9cbead --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/2-3.js @@ -0,0 +1,7 @@ +// 02 배열 - 2 배열 사용하기 - 3 문자열로 배열 만들기 + +var sentence = 'the quick brown for jumped over the lazy dog'; +var words = sentence.split(' '); +for (var i = 0; i < words.length; ++i) { + console.log('word ' + i + ': ' + words[i]); +} \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/2-4.js b/js/hanbit-data-structures-and-algorithms-with-js/02/2-4.js new file mode 100644 index 0000000000..21f9e5a2f2 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/2-4.js @@ -0,0 +1,26 @@ +// 02 배열 - 2 배열 사용하기 - 4 배열 전체에 적용되는 기능 + +var nums = []; +for (var i = 0; i < 100; ++i) { + nums[i] = i+1; +} +var samenums = nums; +nums[0] = 400; +console.log(samenums[0]); // 400 + +///////// + +function copy(arr1, arr2) { + for (var i = 0; i < arr1.length; ++i) { + arr2[i] = arr1[i]; + } +} + +var nums2 = []; +for (var i = 0; i < 100; ++i) { + nums2[i] = i+1; +} +var samenums2 = []; +copy(nums2, samenums2); +nums2[0] = 400; +console.log(samenums2[0]); // 1 \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/3-1.js b/js/hanbit-data-structures-and-algorithms-with-js/02/3-1.js new file mode 100644 index 0000000000..4f02c2757f --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/3-1.js @@ -0,0 +1,18 @@ +// 02 배열 - 3 접근자 함수 - 1 값 검색하기 + +var names = ['David', 'Cynthia', 'Raymond', 'Clayton', 'Jennifer']; + +var name = 'David' +var position = names.indexOf(name); +if (position >= 0) { + console.log('Found ' + name + ' at the position ' + position); +} else { + console.log(name + ' not found in array.'); +} + +// +var name2 = 'Mike'; +var firstPos = names.indexOf(name); +console.log('First found ' + name + ' at position ' + firstPos); +var lastPos = names.lastIndexOf(name); +console.log('Last found ' + name + ' at position ' + lastPos); \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/3-2.js b/js/hanbit-data-structures-and-algorithms-with-js/02/3-2.js new file mode 100644 index 0000000000..627cc65646 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/3-2.js @@ -0,0 +1,7 @@ +// 02 배열 - 3 접근자 함수 - 2 배열을 문자열로 표현하기 + +var names = ['David', 'Cynthia', 'Raymond', 'Clayton', 'Jennifer']; +var nameStr = names.join(); +console.log(nameStr); // David,Cynthia,Raymond,Clayton,Jennifer +nameStr = names.toString(); +console.log(nameStr); // David,Cynthia,Raymond,Clayton,Jennifer \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/3-3.js b/js/hanbit-data-structures-and-algorithms-with-js/02/3-3.js new file mode 100644 index 0000000000..6dacc05b77 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/3-3.js @@ -0,0 +1,14 @@ +// 02 배열 - 3 접근자 함수 - 3 기존 배열을 이용해 새 배열 만들기 + +var cisDept = ['Mike', 'Clayton', 'Terrill', 'Danny', 'Jennifer']; +var dmpDept = ['Raymond', 'Cynthia', 'Bryan']; +var itDiv = cisDept.concat(dmpDept); +console.log(itDiv); // [ 'Mike','Clayton','Terrill','Danny','Jennifer','Raymond','Cynthia','Bryan' ] +itDiv = dmpDept.concat(cisDept); +console.log(itDiv); // [ 'Raymond','Cynthia','Bryan','Mike','Clayton','Terrill','Danny','Jennifer' ] + +var itDiv2 = ['Mike', 'Clayton', 'Terril', 'Raymond', 'Cynthia', 'Danny', 'Jennifer']; +var dmpDept2 = itDiv2.splice(3,3); +var cisDept2 = itDiv2; +console.log(dmpDept2); // [ 'Raymond', 'Cynthia', 'Danny' ] +console.log(cisDept2); // [ 'Mike', 'Clayton', 'Terril', 'Jennifer' ] \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/4-1.js b/js/hanbit-data-structures-and-algorithms-with-js/02/4-1.js new file mode 100644 index 0000000000..a7ecd1661b --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/4-1.js @@ -0,0 +1,29 @@ +// 02 배열 - 4 변형자 함수 - 1 배열에 요소 추가하기 + +var nums = [1,2,3,4,5]; +console.log(nums); // [ 1, 2, 3, 4, 5 ] +nums.push(6); +console.log(nums); // [ 1, 2, 3, 4, 5, 6 ] + +var nums2 = [1,2,3,4,5]; +console.log(nums2); // [ 1, 2, 3, 4, 5 ] +nums2[nums2.length] = 6; +console.log(nums2); // [ 1, 2, 3, 4, 5, 6 ] + +var nums3 = [2,3,4,5]; +var newnum = 1; +var N = nums3.length; +for (var i = N; i >= 0; --i) { + nums3[i] = nums3[i-1]; +} +nums3[0] = newnum; +console.log(nums3); // [1, 2, 3, 4, 5] + +var nums4 = [2,3,4,5]; +console.log(nums4); // [2, 3, 4, 5] +var newnum2 = 1; +nums4.unshift(newnum); +console.log(nums); // [1, 2, 3, 4, 5] +nums4 = [3, 4, 5]; +nums.unshift(newnum2, 2); +console.log(nums4); // [1, 2, 3, 4, 5] \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/4-2.js b/js/hanbit-data-structures-and-algorithms-with-js/02/4-2.js new file mode 100644 index 0000000000..c409dcf9e5 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/4-2.js @@ -0,0 +1,16 @@ +// 02 배열 - 4 변형자 함수 - 2 배열의 요소 삭제하기 + +var nums = [1,2,3,4,5,9]; +nums.pop(); +console.log(nums); // [1,2,3,4,5] + +var nums2 = [9,1,2,3,4,5]; +console.log(nums2); // [9,1,2,3,4,5] +for (var i = 0; i < nums2.length; ++i) { + nums2[i] = nums2[i+1]; +} +console.log(nums2); // [1,2,3,4,5,undefined] + +var nums3 = [9,1,2,3,4,5]; +nums3.shift(); +console.log(nums3); // [1,2,3,4,5] \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/4-3.js b/js/hanbit-data-structures-and-algorithms-with-js/02/4-3.js new file mode 100644 index 0000000000..1a5e5b9771 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/4-3.js @@ -0,0 +1,10 @@ +// 02 배열 - 4 변형자 함수 - 3 배열 중간에 요소를 추가하거나 배열의 중간에 있는 요소 삭제하기 + +var nums = [1,2,3,7,8,9]; +var newElements = [4,5,6]; +nums.splice(3,0,4,5,6); +console.log(nums); // [1,2,3,4,5,6,7,8,9] + +var nums2 = [1,2,3,100,200,300,400,4,5]; +nums2.splice(3,4); +console.log(nums2); // [1,2,3,4,5]; \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/4-4.js b/js/hanbit-data-structures-and-algorithms-with-js/02/4-4.js new file mode 100644 index 0000000000..8052948e0a --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/4-4.js @@ -0,0 +1,21 @@ +// 02 배열 - 4 변형자 함수 - 4 배열 요소 정렬하기 + +var nums = [1,2,3,4,5]; +nums.reverse(); +console.log(nums); // [5,4,3,2,1] + +var names = ['David', 'Mike', 'Cynthia', 'Clayton', 'Bryan', 'Raymond']; +names.sort(); +console.log(names); // [ 'Bryan', 'Clayton', 'Cynthia', 'David', 'Mike', 'Raymond' ] + +var nums2 = [3,1,2,100,4,200]; +nums2.sort(); +console.log(nums2); // [ 1, 100, 2, 200, 3, 4 ] + +function compare(num1, num2) { + return num1 - num2; +} + +var nums3 = [3,1,2,100,4,200]; +nums3.sort(compare); +console.log(nums3); // [ 1, 2, 3, 4, 100, 200 ] \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/5-1.js b/js/hanbit-data-structures-and-algorithms-with-js/02/5-1.js new file mode 100644 index 0000000000..ab45897a92 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/5-1.js @@ -0,0 +1,69 @@ +// 02 배열 - 5 반복자 함수 - 1 배열을 만들지 않는 반복자 함수 + +function square(num) { + console.log(num, num*num); +} + +var nums = [1,2,3,4,5,6,7,8,9,10]; +nums.forEach(square); +/* +1 1 +2 4 +3 9 +4 16 +5 25 +6 36 +7 49 +8 64 +9 81 +10 100 +*/ + +function isEven(num) { + return num % 2 == 0; +} + +var nums2 = [2,4,6,8,10]; +var even = nums2.every(isEven); +if (even) { + console.log('all numbers are even'); // printed +} else { + console.log('not all numbers are even'); +} + +var nums3 = [1,2,3,4,5,6,7,8,9,10]; +var someEven = nums3.some(isEven); +if (someEven) { + console.log('some numbers are even'); // printed +} else { + console.log('no numbers are even'); +} + +nums3 = [1,3,5,7,9]; +someEven = nums3.some(isEven); +if (someEven) { + console.log('some numbers are even'); +} else { + console.log('no numbers are even'); // printed +} + +///////// + +function add(runningTotal, currentValue) { + return runningTotal + currentValue; +} + +var nums4 = [1,2,3,4,5,6,7,8,9,10]; +var sum = nums4.reduce(add); +console.log(sum); // 55 + +function concat(accumulatedString, item) { + return accumulatedString + item; +} + +var words = ['the ', 'quick ', 'brown ', 'fox ']; +var sentence = words.reduce(concat); +console.log(sentence); // the quick brown fox + +var sencente2 = words.reduceRight(concat); +console.log(sencente2); // fox brown quick the diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/5-2.js b/js/hanbit-data-structures-and-algorithms-with-js/02/5-2.js new file mode 100644 index 0000000000..3a3a875adf --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/5-2.js @@ -0,0 +1,57 @@ +// 02 배열 - 5 반복자 함수 - 2 새 배열을 반환하는 반복자 함수 + +function curve(grade) { + return grade += 5; +} + +var grades = [77, 65, 81, 92, 83]; +var newgrades = grades.map(curve); +console.log(newgrades); // [82, 70, 86, 97, 88] + +function first(word) { + return word[0]; +} + +var words = ['for', 'your', 'information']; +var acronym = words.map(first); +console.log(acronym.join('')); // fyi + +function isEven(num) { + return num % 2 == 0; +} + +function isOdd(num) { + return num % 2 != 0; +} + +var nums = []; +for (var i = 0; i < 20; i++) { + nums[i] = i+1; +} +var evens = nums.filter(isEven); +console.log('Even numbers: ' + evens); // Even numbers: 2,4,6,8,10,12,14,16,18,20 +var odds = nums.filter(isOdd); +console.log('Odd numbers: ' + odds); // Odd numbers: 1,3,5,7,9,11,13,15,17,19 + +function passing(num) { + return num >= 60; +} + +var grades2 = []; +for (var i = 0; i < 20; ++i) { + grades2[i] = Math.floor(Math.random() * 101); +} +var passGrades = grades2.filter(passing); +console.log('All grades: ' + grades2); +console.log('Passing grades: ' + passGrades); + +function afterc(str) { + if (str.indexOf('cie') > -1) { + return true; + } + return false; +} + +var words = ['recieve', 'deceive', 'percieve', 'deceit', 'conciet']; +var misspelled = words.filter(afterc); +console.log(misspelled); // [ 'recieve', 'percieve', 'conciet' ] \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/6-1.js b/js/hanbit-data-structures-and-algorithms-with-js/02/6-1.js new file mode 100644 index 0000000000..6be0db2a07 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/6-1.js @@ -0,0 +1,28 @@ +// 02 배열 - 6 이차원 배열과 다차원 배열 - 1 이차원 배열 만들기 + +var twod = []; +var rows = 5; +for (var i = 0; i < rows; ++i) { + twod[i] = []; +} + +Array.matrix = function(numrows, numcols, initial) { + var arr = []; + for (var i = 0; i < numrows; ++i) { + var columns = []; + for (var j = 0; j < numcols; ++j) { + columns[j] = initial; + } + arr[i] = columns; + } + return arr; +} + +var nums = Array.matrix(5,5,0); +console.log(nums[1][1]); // 0 +var names = Array.matrix(3,3,''); +names[1][2] = 'Joe'; +console.log(names[1][2]); + +var grades = [[89,77,78],[76,82,81],[91,94,89]]; +console.log(grades[2][2]); // 89 \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/6-2.js b/js/hanbit-data-structures-and-algorithms-with-js/02/6-2.js new file mode 100644 index 0000000000..8959859939 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/6-2.js @@ -0,0 +1,34 @@ +// 02 배열 - 6 이차원 배열과 다차원 배열 - 2 이차원 배열 요소 처리하기 + +var grades = [[89,77,78],[76,82,81],[91,94,89]]; +var total = 0; +var average = 0.0; +for (var row = 0; row < grades.length; ++row) { + for (var col = 0; col < grades[row].length; ++col) { + total += grades[row][col]; + } + average = total / grades[row].length; + console.log('Student ' + parseInt(row+1) + 'average: ' + average.toFixed(2)); + total = 0; + average = 0.0; +} +/* +Student 1average: 81.33 +Student 2average: 79.67 +Student 3average: 91.33 +*/ + +for (var col = 0; col < grades.length; ++col) { + for (var row = 0; row < grades[col].length; ++row) { + total += grades[row][col]; + } + average = total / grades[col].length; + console.log('Test ' + parseInt(col + 1) + ' average: ' + average.toFixed(2)); + total = 0; + average = 0.0; +} +/* +Test 1 average: 85.33 +Test 2 average: 84.33 +Test 3 average: 82.67 +*/ \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/6-3.js b/js/hanbit-data-structures-and-algorithms-with-js/02/6-3.js new file mode 100644 index 0000000000..bf07f6e0af --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/6-3.js @@ -0,0 +1,19 @@ +// 02 배열 - 6 이차원 배열과 다차원 배열 - 3 들쭉날쭉한 배열 + +var grades = [[89,77],[76,82,81],[91,94,89,99]]; +var total = 0; +var average = 0.0; +for (var row = 0; row < grades.length; ++row) { + for (var col = 0; col < grades[row].length; ++col) { + total += grades[row][col]; + } + average = total / grades[row].length; + console.log('Student ' + parseInt(row+1) + ' average: ' + average.toFixed(2)); + total = 0; + average = 0.0; +} +/* +Student 1 average: 83.00 +Student 2 average: 79.67 +Student 3 average: 93.25 +*/ \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/7.js b/js/hanbit-data-structures-and-algorithms-with-js/02/7.js new file mode 100644 index 0000000000..ef94ee48af --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/7.js @@ -0,0 +1,47 @@ +// 02 배열 - 7 객체를 요소로 포함하는 배열 + +function Point(x, y) { + this.x = x; + this.y = y; +} + +function displayPts(arr) { + for (var i = 0; i < arr.length; ++i) { + console.log(arr[i].x + ', ' + arr[i].y); + } +} + +var p1 = new Point(1,2); +var p2 = new Point(3,5); +var p3 = new Point(2,8); +var p4 = new Point(4,4); +var points = [p1,p2,p3,p4]; +for (var i = 0; i < points.length; ++i) { + console.log('Point ' + parseInt(i+1) + ': ' + points[i].x + ', ' + points[i].y); +} +/* +Point 1: 1, 2 +Point 2: 3, 5 +Point 3: 2, 8 +Point 4: 4, 4 +*/ +var p5 = new Point(12,-3); +points.push(p5); +console.log('After push: '); +displayPts(points) +/* +1, 2 +3, 5 +2, 8 +4, 4 +12, -3 +*/ +points.shift(); +console.log('After push: '); +displayPts(points) +/* +3, 5 +2, 8 +4, 4 +12, -3 +*/ \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/8.js b/js/hanbit-data-structures-and-algorithms-with-js/02/8.js new file mode 100644 index 0000000000..993777c958 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/8.js @@ -0,0 +1,30 @@ +// 02 배열 - 8 객체에 포함된 배열 + +function weekTemps() { + this.dataStore = []; + this.add = add; + this.average = average; +} + +function add(temp) { + this.dataStore.push(temp); +} + +function average() { + var total = 0; + for (var i = 0; i < this.dataStore.length; ++i) { + total += this.dataStore[i]; + } + return total / this.dataStore.length; +} + +var thisWeek = new weekTemps(); +thisWeek.add(52); +thisWeek.add(55); +thisWeek.add(61); +thisWeek.add(65); +thisWeek.add(55); +thisWeek.add(50); +thisWeek.add(52); +thisWeek.add(49); +console.log(thisWeek.average()); // 54.875 \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/quiz/1.js b/js/hanbit-data-structures-and-algorithms-with-js/02/quiz/1.js new file mode 100644 index 0000000000..a452df386a --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/quiz/1.js @@ -0,0 +1,19 @@ +// 1. 객체에 학생들의 점수 집합을 저장하는 grades 객체를 만드시오. 점수를 추가하는 함수, 학생의 평균 점수를 출력하는 기능을 객체에 추가하시오. + +function grades() { + this.scores = []; + this.add = add; + this.average = average; +} + +function add(score) { + this.scores.push(score); +} + +function average() { + var total = 0; + for (var i = 0; i < this.scores.length; ++i) { + total += this.scores[i]; + } + return total / this.scores.length; +} diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/quiz/2.js b/js/hanbit-data-structures-and-algorithms-with-js/02/quiz/2.js new file mode 100644 index 0000000000..62fadcc63e --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/quiz/2.js @@ -0,0 +1,24 @@ +// 2. 배열의 단어 집합을 저장한 다음 배열의 내용을 정방향 또는 역방향으로 출력하는 기능을 구현하시오. + +function words() { + this.wordsList = []; + this.add = add; + this.printAsc = printAsc; + this.printDesc = printDesc; +} + +function add(word) { + this.wordsList.push(word); +} + +function printAsc() { + for (var i = 0; i < this.wordsList.length; ++i) { + console.log(this.wordsList[i]); + } +} + +function printDesc() { + for (var i = this.wordsList.length - 1; i >= 0; --i) { + console.log(this.wordsList[i]); + } +} diff --git a/js/hanbit-data-structures-and-algorithms-with-js/02/quiz/3.js b/js/hanbit-data-structures-and-algorithms-with-js/02/quiz/3.js new file mode 100644 index 0000000000..a0c6b08f4e --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/02/quiz/3.js @@ -0,0 +1,65 @@ +// 3. 이차원 배열을 이용해 월간 온도 자료를 저장하도록 weeklyTemps 객체를 고치시오. 월간 평균, 지정한 주의 평균, 모든 주의 평균을 출력하는 함수를 만드시오. + +function weekTemps() { + this.dataStore = []; + this.add = add; + this.monthAverage = monthAverage; + this.weekAverage = weekAverage; + this.weekAverages = weekAverages; +} + +function add(temp) { + this.dataStore.push(temp); +} + +function monthAverage() { + var total = 0; + for (var i = 0; i < this.dataStore.length; ++i) { + total += this.dataStore[i][0]; + } + return total / this.dataStore.length; +} + +function weekAverage(week) { + var total = 0, weekDataCount = 0; + for (var i = 0; i < this.dataStore.length; ++i) { + var data = this.dataStore[i]; + if (data[1] === week) { + total += data[0]; + weekDataCount++; + } + } + return total / weekDataCount; +} + +function weekAverages() { + var totals = {}, weekDataCounts = {}; + for (var i = 0; i < this.dataStore.length; ++i) { + var data = this.dataStore[i]; + if (totals[data[1]]) { + totals[data[1]] += data[0]; + weekDataCounts[data[1]]++; + } else { + totals[data[1]] = data[0]; + weekDataCounts[data[1]] = 1; + } + } + var result = []; + for (var total in totals) { + result.push(totals[total] / weekDataCounts[total]); + } + return result; +} + +var thisMonth = new weekTemps(); +thisMonth.add([52, 1]); +thisMonth.add([55, 2]); +thisMonth.add([61, 3]); +thisMonth.add([65, 4]); +thisMonth.add([55, 3]); +thisMonth.add([50, 4]); +thisMonth.add([52, 2]); +thisMonth.add([49, 1]); +console.log(thisMonth.monthAverage()); // 54.875 +console.log(thisMonth.weekAverage(1)); // 50.5 +console.log(thisMonth.weekAverages()); // [ 50.5, 53.5, 58, 57.5 ] diff --git a/js/hanbit-data-structures-and-algorithms-with-js/03/Customer.js b/js/hanbit-data-structures-and-algorithms-with-js/03/Customer.js new file mode 100644 index 0000000000..d9c5ad76c3 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/03/Customer.js @@ -0,0 +1,17 @@ +function Customer(name, movie) { + this.name = name, + this.movie = movie; +} + +function checkOut(name, movie, filmList, customerList) { + if (filmList.contains(movie)) { + var c = new Customer(name, movie); + customerList.append(c); + filmList.remove(movie); + } else { + console.log(movie + ' is not available.'); + } +} + +module.exports.Customer = Customer; +module.exports.checkOut = checkOut; \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/03/List.js b/js/hanbit-data-structures-and-algorithms-with-js/03/List.js new file mode 100644 index 0000000000..28b2fde227 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/03/List.js @@ -0,0 +1,110 @@ +function List() { + this.listSize = 0; + this.pos = 0; + this.dataStore = []; // 리스트 요소를 저장할 빈 배열 초기화 + this.clear = clear; + this.find = find; + this.toString = toString; + this.insert = insert; + this.append = append; + this.remove = remove; + this.front = front; + this.end = end; + this.prev = prev; + this.next = next; + this.length = length; + this.currPos = currPos; + this.moveTo = moveTo; + this.getElement = getElement; + this.contains = contains; +} + +function append(element) { + this.dataStore[this.listSize++] = element; +} + +function find(element) { + for (var i = 0; i < this.dataStore.length; ++i) { + if (this.dataStore[i] == element) { + return i; + } + } + return -1; +} + +function remove(element) { + var foundAt = this.find(element); + if (foundAt > -1) { + this.dataStore.splice(foundAt, 1); + --this.listSize; + return true; + } + return false; +} + +function length() { + return this.listSize; +} + +function toString() { + return this.dataStore; +} + +function insert(element, after) { + var insertPos = this.find(after); + if (insertPos > -1) { + this.dataStore.splice(inserPos+1, 0, element); + ++this.listSize; + return true; + } + return false; +} + +function clear() { + delete this.dataStore; + this.dataStore.length = 0; + this.listSize = this.pos = 0; +} + +function contains(element) { + for (var i = 0; i < this.dataStore.length; ++i) { + if (this.dataStore[i] == element) { + return true; + } + } + return false; +} + +function front() { + this.pos = 0; +} + +function end() { + this.pos = this.listSize - 1; +} + +function prev() { + if (this.pos >= 0) { + --this.pos; + } +} + +function next() { + if (this.pos < this.listSize) { + ++this.pos; + } +} + +function currPos() { + return this.pos; +} + +function moveTo(position) { + this.pos = position; +} + +function getElement() { + return this.dataStore[this.pos]; +} + +module.exports.List = List; \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/03/films.txt b/js/hanbit-data-structures-and-algorithms-with-js/03/films.txt new file mode 100644 index 0000000000..ebc06a2005 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/03/films.txt @@ -0,0 +1,20 @@ +The Shawshank Redemption +The Godfather +The Godfather : Part II +Pulp Fiction +The Goods, the bad and the Ugly +12 Angry Man +Schidler's List +The Dark Knight +The Lord of the Rings: The Return of the King +Fight Club +Star Wars: Episode V - The Empire Strikes Back +One Flew Over the Cuckoo's Nest +The Lord of the Rings: The Fellowship of the Ring +Inception +Goodfellas +Star Wars +Seven Samurai +The Matrix +Forrest Gump +City of God \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/03/index.js b/js/hanbit-data-structures-and-algorithms-with-js/03/index.js new file mode 100644 index 0000000000..026dd53689 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/03/index.js @@ -0,0 +1,50 @@ +var fs = require('fs'); + +var movies = fs.readFileSync('./films.txt').toString('utf8').split('\n'); + +function createArr(file) { + var arr = fs.readFileSync(file).toString('utf8').split('\n'); + for (var i = 0; i < arr.length; ++i) { + arr[i] = arr[i].trim(); + } + return arr; +} + +///////////////// + +var {List} = require('./List'); + +var movieList = new List(); +for (var i = 0; i < movies.length; ++i) { + movieList.append(movies[i]); +} + +function displayList(list) { + for (list.front(); list.currPos() < list.length(); list.next()) { + console.log(list.getElement()); + } +} +displayList(movieList); + +////////////////// + +function displayList2(list) { + for (list.front(); list.currPos() < list.length(); list.next()) { + if (list.getElement() instanceof Customer) { + console.log(list.getElement()['name'] + ', ' + list.getElement()['movie']); + } else { + console.log(list.getElement()); + } + } +} + +var {Customer, checkOut} = require('./Customer'); +var customers = new List(); + +console.log('Available movies: \n'); +displayList2(movieList); +checkOut('Jane Doe', 'The Godfather', movieList, customers); +console.log('\nCustomer Rentals: \n'); +displayList2(customers); // Jane Doe, The Godfather +console.log('\nMovies Now Available\n'); +displayList2(movieList); diff --git a/js/hanbit-data-structures-and-algorithms-with-js/03/quiz/1.js b/js/hanbit-data-structures-and-algorithms-with-js/03/quiz/1.js new file mode 100644 index 0000000000..7d139681d7 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/03/quiz/1.js @@ -0,0 +1,18 @@ +// 1. 현재 리스트의 모든 요소보다 클 때만 요소를 삽입하는 함수를 구현하시오. 여기서 크다는 의미는 숫자일 때는 크기를 비교하고, 텍스트일 때는 알파벳순으로 나중을 의미한다. + +function List() { + this.dataStore = []; + this.add = add; +} + +function add(value) { + var limit = true; + for (var i = 0; i < this.dataStore.length; i++) { + if (this.dataStore[i] >= value) { + limit = false; + } + } + if (limit) { + this.dataStore.push(value); + } +} diff --git a/js/hanbit-data-structures-and-algorithms-with-js/03/quiz/2.js b/js/hanbit-data-structures-and-algorithms-with-js/03/quiz/2.js new file mode 100644 index 0000000000..6709091974 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/03/quiz/2.js @@ -0,0 +1,18 @@ +// 2. 현재 리스트의 모든 요소보다 작을 때만 요소를 삽입하는 함수를 구현하시오. + +function List() { + this.dataStore = []; + this.add = add; +} + +function add(value) { + var limit = true; + for (var i = 0; i < this.dataStore.length; i++) { + if (this.dataStore[i] <= value) { + limit = false; + } + } + if (limit) { + this.dataStore.push(value); + } +} diff --git a/js/hanbit-data-structures-and-algorithms-with-js/03/quiz/3.js b/js/hanbit-data-structures-and-algorithms-with-js/03/quiz/3.js new file mode 100644 index 0000000000..955a0980f5 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/03/quiz/3.js @@ -0,0 +1,31 @@ +// 3. 사람의 이름과 성별을 저장하는 Person 클래스를 구현하시오. 최소한 10개의 Person 객체를 포함하는 리스트를 만드시오. 리스트에서 같은 성별을 가진 사람을 모두 출력하는 함수를 구현하시오. + +function Person(name, gender) { + this.name = name; + this.gender = gender; +} + +function People() { + this.people = []; + this.add = add; + this.printByGender = printByGender; +} + +function add(person) { + this.people.push(person); +} + +function printByGender(gender) { + for (var i = 0; i < this.people.length; i++) { + var person = this.people[i]; + if (person.gender === gender) { + console.log(person); + } + } +} + +var people = new People(); +people.add(new Person('Jinho', 'M')); +people.add(new Person('Youngmi', 'F')); + +people.printByGender('M'); diff --git a/js/hanbit-data-structures-and-algorithms-with-js/03/quiz/4.js b/js/hanbit-data-structures-and-algorithms-with-js/03/quiz/4.js new file mode 100644 index 0000000000..5aab3704f6 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/03/quiz/4.js @@ -0,0 +1,11 @@ +// 4. 비디오 대여 상점 프로그램에서 고객이 대여한 영화를 대여한 영화 리스트로 추가하시오. 그리고 고객이 영화를 대여할 때마다 대여된 영화 리스트를 출력하시오. + +function movieList() { + this.rentedMovieList = []; + this.rent = rent; +} + +function rent(video) { + this.rentedMovieList.push(video); + console.log(this.rentedMovieList); +} diff --git a/js/hanbit-data-structures-and-algorithms-with-js/03/quiz/5.js b/js/hanbit-data-structures-and-algorithms-with-js/03/quiz/5.js new file mode 100644 index 0000000000..c6bb6562c6 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/03/quiz/5.js @@ -0,0 +1,19 @@ +// 5. 비디오 대여 상점 프로그램에 반납 함수를 추가하시오. 고객이 영화를 반납하면 대여된 영화 리스트에서 영화를 삭제한 다음 이용할 수 있는 영화 리스트로 추가하시오. + +function movieList() { + this.rentedMovieList = []; + this.returnedMovieList = []; + this.rentMovie = rentMovie; + this.returnMovie = returnMovie; +} + +function rentMovie(movie) { + this.rentedMovieList.push(movie); + console.log(this.rentedMovieList); +} + +function returnMovie(movie) { + var indexOfMovie = this.rentedMovieList.indexOf(movie); + this.rentedMovieList = this.rentedMovieList.slice(0, indexOfMovie).concat(this.rentedMovieList(indexOfMovie+1, this.rentedMovieList.length)); + this.returnedMovieList.push(movie); +} diff --git a/js/hanbit-data-structures-and-algorithms-with-js/03/use_list.js b/js/hanbit-data-structures-and-algorithms-with-js/03/use_list.js new file mode 100644 index 0000000000..41bb95265c --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/03/use_list.js @@ -0,0 +1,29 @@ +var {List} = require('./List'); + +var list = new List(); +list.append('Cynthia'); +list.append('Raymond'); +list.append('Barbara'); +console.log(list.toString()); // [ 'Cynthia', 'Raymond', 'Barbara' ] +list.remove('Raymond'); +console.log(list.toString()); // [ 'Cynthia', 'Raymond' ] + + +var names = new List(); +names.append('Clayton'); +names.append('Raymond'); +names.append('Cynthia'); +names.append('Jennifer'); +names.append('Bryan'); +names.append('Danny'); + +// names.front(); +// console.log(names.getElement()); // clayton + +// for (names.front(); names.currPos() < names.length(); names.next()) { +// console.log(names.getElement()); +// } + +for (names.end(); names.currPos() >= 0; names.prev()) { + console.log(names.getElement()); +} \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/04/Stack.js b/js/hanbit-data-structures-and-algorithms-with-js/04/Stack.js new file mode 100644 index 0000000000..60f89f820f --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/04/Stack.js @@ -0,0 +1,31 @@ +function Stack() { + this.dataStore = []; + this.top = 0; + this.push = push; + this.pop = pop; + this.peek = peek; + this.length = length; + this.clear = clear; +} + +function push(element) { + this.dataStore[this.top++] = element; +} + +function pop() { + return this.dataStore[--this.top]; +} + +function peek() { + return this.dataStore[this.top-1]; +} + +function length() { + return this.top; +} + +function clear() { + this.top = 0; +} + +module.exports.Stack = Stack; \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/04/index.js b/js/hanbit-data-structures-and-algorithms-with-js/04/index.js new file mode 100644 index 0000000000..3ed1e150dd --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/04/index.js @@ -0,0 +1,81 @@ +var {Stack} = require('./Stack'); + +function mulBase(num, base) { + var s = new Stack(); + do { + s.push(num % base); + num = Math.floor(num /= base); + } while (num > 0); + var converted = ''; + while (s.length() > 0) { + converted += s.pop(); + } + return converted; +} + +var num = 32; +var base = 2; +var newNum = mulBase(num, base); +console.log(num + ' converted to base ' + base + ' is ' + newNum); // 32 converted to base 2 is 100000 + +var num2 = 125; +var base2 = 8; +var newNum2 = mulBase(num2, base2); +console.log(num2 + ' converted to base ' + base2 + ' is ' + newNum2); // 125 converted to base 8 is 175 + +///////////// + +function isPalindrome(word) { + var s = new Stack(); + for (var i = 0; i < word.length; ++i) { + s.push(word[i]); + } + var rword = ''; + while (s.length() > 0) { + rword += s.pop(); + } + if (word == rword) { + return true; + } else { + return false; + } +} + +var word = 'hello'; +if (isPalindrome(word)) { + console.log(word + ' is a palindrome'); +} else { + console.log(word + ' is not a palindrome'); // hello is not a palindrome +} + +var word2 = 'racecar'; +if (isPalindrome(word2)) { + console.log(word2 + ' is a palindrome'); // racecar is a palindrome +} else { + console.log(word2 + ' is not a palindrome'); +} + +///////////////// + +function factorial(n) { + if (n === 0) { + return 1; + } else { + return n * factorial(n-1); + } +} + +function fact(n) { + var s = new Stack() + while (n > 1) { + s.push(n--); + } + var product = 1; + while (s.length() > 0) { + product *= s.pop(); + } + return product; +} + +console.log(factorial(5)); // 120 +console.log(fact(5)); // 120 \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/04/quiz/1.js b/js/hanbit-data-structures-and-algorithms-with-js/04/quiz/1.js new file mode 100644 index 0000000000..9a14b19d30 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/04/quiz/1.js @@ -0,0 +1,5 @@ +/* +1. 수식에 열고 닫는 괄호 쌍이 제대로 갖춰졌는지 확인할 때도 스택을 이용할 수 있다. +수식을 인자로 받아 수식에 열거나 닫는 괄호가 없을 떼 그 위치를 반환하는 함수를 구현하시오. +예를 들어 '2.3 + 23 / 12 + (3.14159 * .24)'에는 닫는 괄호가 없다. +*/ diff --git a/js/hanbit-data-structures-and-algorithms-with-js/04/quiz/2.js b/js/hanbit-data-structures-and-algorithms-with-js/04/quiz/2.js new file mode 100644 index 0000000000..e7240ea322 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/04/quiz/2.js @@ -0,0 +1,4 @@ +/* +2. 다음과 같은 형식을 갖는 후위 연산 표기를 처리하는 후위 연산 평가자를 구현하시오 +op1 op2 operator +*/ diff --git a/js/hanbit-data-structures-and-algorithms-with-js/04/quiz/3.js b/js/hanbit-data-structures-and-algorithms-with-js/04/quiz/3.js new file mode 100644 index 0000000000..1d12adcb3a --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/04/quiz/3.js @@ -0,0 +1,5 @@ +/* +3. 우리 주변의 페즈 디스펜서Pez dispenser는 스택과 같은 방식으로 동작한다. +페즈 디스펜서에 빨간색, 노란색, 흰색 사탕이 섞여있는데 노란색 사탕은 우리가 싫어하는 맛이다. +스택(한 개 이상의 스택을 사용할 수 있다)을 이용해 디스펜서의 다른 사탕 순서는 바꾸지 말고 노란색 사탕만 제거하는 프로그램을 구현하시오. +*/ diff --git a/js/hanbit-data-structures-and-algorithms-with-js/04/use_stack.js b/js/hanbit-data-structures-and-algorithms-with-js/04/use_stack.js new file mode 100644 index 0000000000..a46ebada53 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/04/use_stack.js @@ -0,0 +1,22 @@ +var {Stack} = require('./Stack'); + +var s = new Stack(); +s.push('David'); +s.push('Raymond'); +s.push('Bryan'); +console.log('length: ' + s.length()); // 3 +console.log(s.peek()); // Bryan + +var popped = s.pop(); +console.log('The popped element is: ' + popped); // Bryan +console.log(s.peek()); // Raymond + +s.push('Cynthia'); +console.log(s.peek()); // Cynthia + +s.clear(); +console.log('length: ' + s.length()); // 0 +console.log(s.peek()); // undefined + +s.push('Clayton'); +console.log(s.peek()); // Clayton \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/05/PriorityQueue.js b/js/hanbit-data-structures-and-algorithms-with-js/05/PriorityQueue.js new file mode 100644 index 0000000000..876f72dec3 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/05/PriorityQueue.js @@ -0,0 +1,56 @@ +var {Queue} = require('./Queue'); + +function Patient(name, code) { + this.name = name; + this.code = code; +} + +var p = new Patient('Smith', 5); +var ed = new Queue(); +ed.enqueue(p); +p = new Patient('Jones', 4); +ed.enqueue(p); +p = new Patient('Fehrenbach', 6); +ed.enqueue(p); +p = new Patient('Brown', 1); +ed.enqueue(p); +p = new Patient('Ingram', 1); +ed.enqueue(p); +console.log(ed.toString2()); +/* +Smith code: 5 +Jones code: 4 +Fehrenbach code: 6 +Brown code: 1 +Ingram code: 1 +*/ + +var seen = ed.dequeue2(); +console.log('Patient being treated: ' + seen[0].name); // Brown +console.log('Patients waiting to be seen: ') +console.log(ed.toString2()); +/* +Smith code: 5 +Fehrenbach code: +Brown code: 1 +Ingram code: 1 +*/ + +var seen = ed.dequeue2(); +console.log('Patient being treated: ' + seen[0].name); +console.log('Patients waiting to be seen: ') +console.log(ed.toString2()); +/* +Smith code: 5 +Fehrenbach code: 6 +Ingram code: 1 +*/ + +var seen = ed.dequeue2(); +console.log('Patient being treated: ' + seen[0].name); +console.log('Patients waiting to be seen: ') +console.log(ed.toString2()); +/* +Smith code: 5 +Fehrenbach code: 6 +*/ \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/05/Queue.js b/js/hanbit-data-structures-and-algorithms-with-js/05/Queue.js new file mode 100644 index 0000000000..b7c14fb662 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/05/Queue.js @@ -0,0 +1,70 @@ +function Queue() { + this.dataStore = []; + this.enqueue = enqueue; + this.dequeue = dequeue; + this.front = front; + this.back = back; + this.toString = toString; + this.empty = empty; + this.count = count; + this.dequeue2 = dequeue2; + this.toString2 = toString2; +} + +function enqueue(element) { + this.dataStore.push(element); +} + +function dequeue(element) { + return this.dataStore.shift(); +} + +function front() { + return this.dataStore[0]; +} + +function back() { + return this.dataStore[this.dataStore.length - 1]; +} + +function toString() { + var retStr = ''; + for (var i = 0; i < this.dataStore.length; i++) { + retStr += this.dataStore[i] + '\n'; + } + return retStr; +} + +function empty() { + if (this.dataStore.length == 0) { + return true; + } else { + return false; + } +} + +function count() { + return this.dataStore.length; +} + + + +function dequeue2() { + var entry = 0; + for (var i = 0; i < this.dataStore.length; ++i) { + if (this.dataStore[i].code < this.dataStore[entry].code) { + entry = i; + return this.dataStore.splice(entry, 1); + } + } +} + +function toString2() { + var retStr = ''; + for (var i = 0; i < this.dataStore.length; ++i) { + retStr += this.dataStore[i].name + ' code: ' + this.dataStore[i].code + '\n'; + } + return retStr; +} + +module.exports.Queue = Queue; \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/05/dancers.js b/js/hanbit-data-structures-and-algorithms-with-js/05/dancers.js new file mode 100644 index 0000000000..4183044d59 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/05/dancers.js @@ -0,0 +1,60 @@ +var {Queue} = require('./Queue'); +var fs = require('fs'); + +function Dancer(name, sex) { + this.name = name; + this.sex = sex; +} + +function getDancers(males, females) { + var names = fs.readFileSync('./dancers.txt').toString('utf8').split('\n'); + + for (var i = 0; i < names.length; ++i) { + var dancer = names[i].split(' '); + var sex = dancer[0]; + var name = dancer[1]; + if (sex == 'F') { + females.enqueue(new Dancer(name, sex)); + } else { + males.enqueue(new Dancer(name, sex)); + } + } +} + +function dance(males, females) { + console.log('The dance partners are: \n'); + while (!females.empty() && !males.empty()) { + male = females.dequeue(); + female = males.dequeue() + console.log('Female dancer is: ' + male.name + ' and the Male dancer is: ' + female.name); + } + console.log(); +} + +var maleDancers = new Queue(); +var femaleDancers = new Queue(); +getDancers(maleDancers, femaleDancers); +dance(maleDancers, femaleDancers); +/* +The dance partners are: + +Female dancer is: Allison and the Male dancer is: Frank +Female dancer is: Cheryl and the Male dancer is: Mason +Female dancer is: Jennifer and the Male dancer is: Clayton +Female dancer is: Aurora and the Male dancer is: Raymond +*/ + +if (!femaleDancers.empty()) { + console.log(femaleDancers.front().name + ' is waiting to dance.'); +} +if (!maleDancers.empty()) { + console.log(maleDancers.front().name + ' is waiting to dance.'); // Bryan is waiting to dance. +} + +if (maleDancers.count() > 0) { + console.log('There are ' + maleDancers.count() + ' male dancers waiting to dance.'); // There are 3 male dancers waiting to dance. +} + +if (femaleDancers.count() > 0) { + console.log('There are ' + femaleDancers.count() + ' female dancers waiting to dance.'); +} \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/05/dancers.txt b/js/hanbit-data-structures-and-algorithms-with-js/05/dancers.txt new file mode 100644 index 0000000000..a3102b3521 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/05/dancers.txt @@ -0,0 +1,11 @@ +F Allison McMillan +M Frank Optiz +M Mason McMillan +M Clayton Ruff +F Cheryl Ferenback +M Raymond Williams +F Jennifer Ingram +M Bryan Frazer +M David Durr +M Danny Martin +F Aurora Adney \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/05/quiz.js b/js/hanbit-data-structures-and-algorithms-with-js/05/quiz.js new file mode 100644 index 0000000000..63b217f668 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/05/quiz.js @@ -0,0 +1,9 @@ +/* +1. Queue 클래스를 고쳐 Deque 클래스를 만드시오. Deque는 큐와 비슷한 자료구조로 리스트의 앞부분과 끝부분 모두에서 요소의 삽입과 삭제가 일어난다. 프로그램을 이용해 구현한 Deque 클래스를 테스트하시오. +2. 연습문제 1번에서 구현한 Deque 클래스를 이용해 주어진 단어가 회문인지 검사하는 프로그램을 만드시오. +3. 예제 [5-5]의 우서순위 큐 예제에서 낮은 수가 아니라 높은 숫자가 높은 우선순위를 갖도록 프로그램을 고치시오. 테스트 프로그램으로 [예제 5-5]를 테스트해 본 것처럼 고친 프로그램이 제대로 동작하는지 테스트 프로그램으로 확인하시오. +4. 사용자가 응급실의 활동을 제어할 수 있도록 응급실 예제(예제 5-5)를 고치시오. 사용자가 다음과 같은 활동을 선택할 수 있도록 시스템 메뉴를 만들어 제공하시오. +a. 환자가 응급실에 들어옴 +b. 의사가 환자를 검사함. +c. 대기 환자 목록을 출력함. +*/ \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/05/sort.js b/js/hanbit-data-structures-and-algorithms-with-js/05/sort.js new file mode 100644 index 0000000000..c37d62e885 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/05/sort.js @@ -0,0 +1,48 @@ +var {Queue} = require('./Queue'); + +function distribute(nums, queues, n, digit) { // digit는 1의 자리 숫자인지, 10의 자리 숫자인지를 구분하는 인자 + for (var i = 0; i < n; ++i) { + if (digit == 1) { + queues[nums[i] % 10].enqueue(nums[i]); + } else { + queues[Math.floor(nums[i] / 10)].enqueue(nums[i]); + } + } +} + +function collect(queues, nums) { + var i = 0; + for (var digit = 0; digit < 10; ++digit) { + while (!queues[digit].empty()) { + nums[i++] = queues[digit].dequeue(); + } + } +} + +function dispArray(arr) { + var result = ''; + for (var i = 0; i < arr.length; ++i) { + result += arr[i] + ' '; + } + console.log(result); +} + +var queues = []; +for (var i = 0; i < 10; ++i) { + queues[i] = new Queue(); +} + +var nums = []; +for (var i = 0; i < 10; ++i) { + nums[i] = Math.floor(Math.floor(Math.random() * 101)); +} + +console.log('Before radix sort: '); +dispArray(nums); +distribute(nums, queues, 10, 1); +collect(queues, nums); +distribute(nums, queues, 10, 10); +collect(queues, nums); + +console.log('\n\nAfter radix sort: '); +dispArray(nums); \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/05/use_queue.js b/js/hanbit-data-structures-and-algorithms-with-js/05/use_queue.js new file mode 100644 index 0000000000..4554383ac9 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/05/use_queue.js @@ -0,0 +1,15 @@ +var {Queue} = require('./Queue'); + +var q = new Queue(); +q.enqueue('Meredith'); +q.enqueue('Cynthia'); +q.enqueue('Jennifer'); + +console.log(q.toString()); + +q.dequeue(); + +console.log(q.toString()); + +console.log('Front of queue: ' + q.front()); // Cynthia +console.log('Back of queue: ' + q.back()); // Jennifer \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/06/Node.js b/js/hanbit-data-structures-and-algorithms-with-js/06/Node.js new file mode 100644 index 0000000000..5435780655 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/06/Node.js @@ -0,0 +1,53 @@ +function Node(element) { + this.element = element; + this.next = null; +} + +function LList() { + this.head = new Node('head'); + this.find = find; + this.insert = insert; + this.display = display; + this.findPrevious = findPrevious; + this.remove = remove; +} + +function find(item) { + var currNode = this.head; + while (currNode.element != item) { + currNode = currNode.next; + } + return currNode; +} + +function insert(newElement, item) { + var newNode = new Node(newElement); + var current = this.find(item); + newNode.next = current.next; + current.next = newNode; +} + +function display() { + var currNode = this.head; + while (!(currNode.next == null)) { + console.log(currNode.next.element); + currNode = currNode.next; + } +} + +function findPrevious(item) { + var currNode = this.head; + while (!(currNode.next == null) && (currNode.next.element != item)) { + currNode = currNode.next; + } + return currNode; +} + +function remove(item) { + var prevNode = this.findPrevious(item); + if (!(prevNode.next == null)) { + prevNode.next = prevNode.next.next; + } +} + +module.exports.LList = LList; \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/06/Node2.js b/js/hanbit-data-structures-and-algorithms-with-js/06/Node2.js new file mode 100644 index 0000000000..2162550448 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/06/Node2.js @@ -0,0 +1,68 @@ +function Node(element) { + this.element = element; + this.next = null; + this.previous = null; +} + +function LList() { + this.head = new Node('head'); + this.find = find; + this.insert = insert; + this.display = display; + this.remove = remove; + this.findLast = findLast; + this.dispReverse = dispReverse; +} + +function find(item) { + var currNode = this.head; + while (currNode.element != item) { + currNode = currNode.next; + } + return currNode; +} + +function insert(newElement, item) { + var newNode = new Node(newElement); + var current = this.find(item); + newNode.next = current.next; + newNode.previous = current; + current.next = newNode; +} + +function display() { + var currNode = this.head; + while (!(currNode.next == null)) { + console.log(currNode.next.element); + currNode = currNode.next; + } +} + +function remove(item) { + var currNode = this.find(item); + if (!(currNode.next == null)) { + currNode.previous.next = currNode.next; + currNode.next.previous = currNode.previous; + currNode.next = null; + currNode.previous = null; + } +} + +function findLast() { + var currNode = this.head; + while (!(currNode.next == null)) { + currNode = currNode.next; + } + return currNode; +} + +function dispReverse() { + var currNode = this.head; + currNode = this.findLast(); + while (!(currNode.previous == null)) { + console.log(currNode.element); + currNode = currNode.previous; + } +} + +module.exports.LList = LList; \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/06/Node3.js b/js/hanbit-data-structures-and-algorithms-with-js/06/Node3.js new file mode 100644 index 0000000000..a4aef39f72 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/06/Node3.js @@ -0,0 +1,54 @@ +function Node(element) { + this.element = element; + this.next = null; +} + +function LList() { + this.head = new Node('head'); + this.head.next = this.head; + this.find = find; + this.insert = insert; + this.display = display; + this.findPrevious = findPrevious; + this.remove = remove; +} + +function find(item) { + var currNode = this.head; + while (currNode.element != item) { + currNode = currNode.next; + } + return currNode; +} + +function insert(newElement, item) { + var newNode = new Node(newElement); + var current = this.find(item); + newNode.next = current.next; + current.next = newNode; +} + +function display() { + var currNode = this.head; + while (!(currNode.next == null) && !(currNode.next.element == 'head')) { + console.log(currNode.next.element); + currNode = currNode.next; + } +} + +function findPrevious(item) { + var currNode = this.head; + while (!(currNode.next == null) && (currNode.next.element != item)) { + currNode = currNode.next; + } + return currNode; +} + +function remove(item) { + var prevNode = this.findPrevious(item); + if (!(prevNode.next == null)) { + prevNode.next = prevNode.next.next; + } +} + +module.exports.LList = LList; \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/06/quiz.js b/js/hanbit-data-structures-and-algorithms-with-js/06/quiz.js new file mode 100644 index 0000000000..05c229d7b9 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/06/quiz.js @@ -0,0 +1,8 @@ +/* +1. advance(n) 함수를 구현하시오. advance(n) 함수를 호출하면 현재 노드가 n 노드 만큼 전진한다. +2. back(n) 함수를 구현하시오. back(n) 함수를 호출하면 현재 노드가 n 노드 만큼 후진한다. +3. 현재 노드의 데이터를 출력하는 show() 함수를 구현하시오. +4. 대화형으로 입력된 테스트 점수를 단방향 연결 리스트로 저장하는 프로그램을 구현하시오. +5. 양방향 연결 리스트를 이용해 [예제 6-4]를 다시 구현하시오. +6. 전설에 의하면 1세기에 유대인 로마 전쟁 당시 역사가 플라비우스 요세푸스와 40명의 유대인이 로마 군인에게 붙잡힐 위기에 처했다. 유대인 병사들은 포로로 잡히느니 죽음을 택하기로 했다. 사람으로 원을 만든 다음 사람이 남지 않을 때까지 매 세 번째 병사를 죽여 나가기로 작전을 세웠다. 요세푸스와 다른 한 명은 일찍 죽임을 당하는 위치에 서고 싶지 않아 어디에 서야 최후까지 생존할 수 있을지 빨리 계산해야 했다. n명의 사람이 원을 만들고 매 m번째 사람을 죽이는 프로그램을 구현하시오. 그리고 마지막으로 남을 두 사람을 계산하시오. 순환형 연결 리스트를 이용해 이 문제를 해결한다. +*/ \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/06/use_node.js b/js/hanbit-data-structures-and-algorithms-with-js/06/use_node.js new file mode 100644 index 0000000000..1557bb3382 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/06/use_node.js @@ -0,0 +1,21 @@ +var {LList} = require('./Node'); + +var cities = new LList(); +cities.insert('Conway', 'head'); +cities.insert('Russellville', 'Conway'); +cities.insert('Carlisle', 'Russellville'); +cities.insert('Alma', 'Carlisle'); +cities.display(); +/* +Conway +Russellville +Carlisle +Alma +*/ +cities.remove('Carlisle'); +cities.display(); +/* +Conway +Russellville +Alma +*/ \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/06/use_node2.js b/js/hanbit-data-structures-and-algorithms-with-js/06/use_node2.js new file mode 100644 index 0000000000..77a5ba1bcf --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/06/use_node2.js @@ -0,0 +1,27 @@ +var {LList} = require('./Node2'); + +var cities = new LList(); +cities.insert('Conway', 'head'); +cities.insert('Russellville', 'Conway'); +cities.insert('Carlisle', 'Russellville'); +cities.insert('Alma', 'Carlisle'); +cities.display(); +/* +Conway +Russellville +Carlisle +Alma +*/ +cities.remove('Carlisle'); +cities.display(); +/* +Conway +Russellville +Alma +*/ +cities.dispReverse(); +/* +Alma +Russellville +Conway +*/ \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/07/Dictionary.js b/js/hanbit-data-structures-and-algorithms-with-js/07/Dictionary.js new file mode 100644 index 0000000000..7833a415d2 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/07/Dictionary.js @@ -0,0 +1,45 @@ +function Dictionary() { + this.datastore = new Array(); + this.add = add; + this.find = find; + this.remove = remove; + this.showAll = showAll; + this.count = count; + this.clear = clear; +} + +function add(key, value) { + this.datastore[key] = value; +} + +function find(key) { + return this.datastore[key]; +} + +function remove(key) { + delete this.datastore[key]; +} + +function showAll() { + var keys = Object.keys(this.datastore).sort(); + for (var i = 0; i < keys.length; i++) { + console.log(keys[i] + ' -> ' + this.datastore[keys[i]]); + } +} + +function count() { + var n = 0; + for (var i = 0; i < Object.keys(this.datastore); i++) { + ++n; + } + return n; +} + +function clear() { + var keys = Object.keys(this.datastore); + for (var i = 0; i < keys.length; i++) { + delete this.datastore[keys[i]]; + } +} + +module.exports.Dictionary = Dictionary \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/07/quiz.js b/js/hanbit-data-structures-and-algorithms-with-js/07/quiz.js new file mode 100644 index 0000000000..d77b3e6225 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/07/quiz.js @@ -0,0 +1,11 @@ +/* +1. 텍스트 파일에서 이름과 전화번호를 읽어 Dictionary 객체에 저장하는 프로그램을 구현하시오. 또한 특정 전화번호 출력 기능, 모든 전화번호 출력 기능, 새로운 전화번호 추가 기능, 기존 전화번호 삭제 기능, 모든 전화번호 삭제 기능을 추가하시오. +2. Dictionay 클래스를 이용해 어떤 텍스트에서 단어가 몇 번 나오는지를 저장하는 프로그램을 구현하시오. 프로그램은 텍스트에서 각 단어가 몇 회 나오는지 표시해야 한다. 예를 들어 'the brown fox jumped over the blue fox,'를 입력했을 때 다음과 같은 결과가 출력돼야 한다. +the: 2 +brown: 1 +fox: 2 +jumped: 1 +over: 1 +blue: 1 +3. 2번 예제의 결과를 정렬해서 출력하도록 프로그램을 고치시오. +*/ \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/07/use_dictionary.js b/js/hanbit-data-structures-and-algorithms-with-js/07/use_dictionary.js new file mode 100644 index 0000000000..874841d539 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/07/use_dictionary.js @@ -0,0 +1,34 @@ +var {Dictionary} = require('./Dictionary'); + +var pbook = new Dictionary(); +pbook.add('Mike', '123'); +pbook.add('David', '345'); +pbook.add('Cynthia', '456'); +console.log("David's extension: " + pbook.find('David')); // 345 +pbook.remove('David'); +pbook.showAll(); +/* +Mike -> 123 +Cynthia -> 456 +*/ +pbook.clear(); +console.log('Number of entries: ' + pbook.count()); // 0 + +var pbook2 = new Dictionary(); +pbook.add('Raymond','123'); +pbook.add('David','345'); +pbook.add('Cynthia','456'); +pbook.add('Mike','723'); +pbook.add('Jennifer','987'); +pbook.add('Danny','012'); +pbook.add('Jonathan','666'); +pbook.showAll(); +/* +Cynthia -> 456 +Danny -> 012 +David -> 345 +Jennifer -> 987 +Jonathan -> 666 +Mike -> 723 +Raymond -> 123 +*/ \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/08/HashTable.js b/js/hanbit-data-structures-and-algorithms-with-js/08/HashTable.js new file mode 100644 index 0000000000..df344e4fd7 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/08/HashTable.js @@ -0,0 +1,49 @@ +function HashTable() { + this.table = new Array(137); + this.simpleHash = simpleHash; + this.betterHash = betterHash; + this.showDistro = showDistro; + this.put = put; + this.get = get; +} + +function simpleHash(data) { + var total = 0; + for (var i = 0; i < data.length; ++i) { + total += data.charCodeAt(i); + } + return total % this.table.length; +} + +function put(data) { + var pos = this.betterHash(data); + this.table[pos] = data; +} + +function get(key) { + return this.table[this.betterHash(key)]; +} + +function showDistro() { + var n = 0; + for (var i = 0; i < this.table.length; ++i) { + if (this.table[i] != undefined) { + console.log(i + ': ' + this.table[i]); + } + } +} + +function betterHash(string) { + var H = 37; + var total = 0; + for (var i = 0; i < string.length-1; i++) { + total += H * total + string.charCodeAt(i); + } + total = total % this.table.length; + if (total < 0) { + total += this.table.length-1; + } + return parseInt(total); +} + +module.exports.HashTable = HashTable; diff --git a/js/hanbit-data-structures-and-algorithms-with-js/08/HashTable_SeperateChaining.js b/js/hanbit-data-structures-and-algorithms-with-js/08/HashTable_SeperateChaining.js new file mode 100644 index 0000000000..ee9f3f8e08 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/08/HashTable_SeperateChaining.js @@ -0,0 +1,56 @@ +function HashTable() { + this.table = new Array(137); + this.simpleHash = simpleHash; + this.betterHash = betterHash; + this.showDistro = showDistro; + this.put = put; + this.get = get; + this.buildChains = buildChains; +} + +function simpleHash(data) { + var total = 0; + for (var i = 0; i < data.length; ++i) { + total += data.charCodeAt(i); + } + return total % this.table.length; +} + +function put(data) { + var pos = this.betterHash(data); + this.table[pos] = data; +} + +function get(key) { + return this.table[this.betterHash(key)]; +} + +function showDistro() { + var n = 0; + for (var i = 0; i < this.table.length; ++i) { + if (this.table[i][0] != undefined) { + console.log(i + ': ' + this.table[i]); + } + } +} + +function betterHash(string) { + var H = 37; + var total = 0; + for (var i = 0; i < string.length-1; i++) { + total += H * total + string.charCodeAt(i); + } + total = total % this.table.length; + if (total < 0) { + total += this.table.length-1; + } + return parseInt(total); +} + +function buildChains() { + for (var i = 0; i < this.table.length; ++i) { + this.table[i] = new Array(); + } +} + +module.exports.HashTable = HashTable; diff --git a/js/hanbit-data-structures-and-algorithms-with-js/08/build_chains.js b/js/hanbit-data-structures-and-algorithms-with-js/08/build_chains.js new file mode 100644 index 0000000000..6e7a27ee2b --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/08/build_chains.js @@ -0,0 +1,22 @@ +var {HashTable} = require('./HashTable_SeperateChaining'); + +var hTable = new HashTable(); +hTable.buildChains(); + +var someNames = ['David', 'Jennifer', 'Donnie', 'Raymond', 'Cynthia', 'Mike', 'Clayton', 'Danny', 'Jonathan']; + +for (var i = 0; i < someNames.length; ++i) { + hTable.put(someNames[i]); +} +hTable.showDistro(); +/* +6: Donnie +29: Cynthia +34: Raymond +55: Jennifer +61: Danny +68: Mike +86: David +114: Clayton +129: Jonathan +*/ diff --git a/js/hanbit-data-structures-and-algorithms-with-js/08/quiz.js b/js/hanbit-data-structures-and-algorithms-with-js/08/quiz.js new file mode 100644 index 0000000000..7e5d85fd45 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/08/quiz.js @@ -0,0 +1,5 @@ +/* +1. 선형 조사 기법을 이용해 단어의 정의를 저장하는 간단한 딕셔너리를 만드시오. 프로그램은 두 가지 기능을 제공해야 한다. 우선 단어와 정의를 포함하는 파일을 읽어 해시 테이블에 저장하는 기능이 필요하다. 사용자가 입력한 단어의 정의를 보여주는 기능도 필요하다. +2. 분리된 체인을 이용해 1번 문제를 해결하시오. +3. 텍스트 파일을 읽은 다음 파일에 포함된 단어를 인식해 파일에서 각 단어가 몇 번 등장했는지를 계산하는 프로그램을 구현하시오. +*/ diff --git a/js/hanbit-data-structures-and-algorithms-with-js/08/use_hashtable_1.js b/js/hanbit-data-structures-and-algorithms-with-js/08/use_hashtable_1.js new file mode 100644 index 0000000000..372655a776 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/08/use_hashtable_1.js @@ -0,0 +1,31 @@ +var {HashTable} = require('./HashTable'); + +var someNames = ['David', 'Jennifer', 'Donnie', 'Raymond', 'Cynthia', 'Mike', 'Clayton', 'Danny', 'Jonathan']; + +var hTable = new HashTable(); +for (var i = 0; i < someNames.length; ++i) { + hTable.put(someNames[i]); +} +hTable.showDistro(); +/* +simple hash +35: Cynthia +45: Clayton +57: Donnie +77: David +95: Danny +116: Mike +132: Jennifer +134: Jonathan + +better hash +6: Donnie +29: Cynthia +34: Raymond +55: Jennifer +61: Danny +68: Mike +86: David +114: Clayton +129: Jonathan +*/ diff --git a/js/hanbit-data-structures-and-algorithms-with-js/08/use_hashtable_2.js b/js/hanbit-data-structures-and-algorithms-with-js/08/use_hashtable_2.js new file mode 100644 index 0000000000..f8a2891659 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/08/use_hashtable_2.js @@ -0,0 +1,60 @@ +var {HashTable} = require('./HashTable'); + +function getRandomInt(min, max) { + return Math.floor(Math.random() * (max - min + 1) + min); +} + +function genStuData(arr) { + for (var i = 0; i < arr.length; ++i) { + var num = ''; + for (var j = 1; j <= 9; ++j) { + num += Math.floor(Math.random() * 10); + } + num += getRandomInt(50, 100); + arr[i] = num; + } +} + +var numStudents = 10; +var arrSize = 97; +var idLen = 9; +var students = new Array(numStudents); +genStuData(students); +/* +(example) +04699389 94 +26704238 89 +87502846 82 +32877112 59 +61488320 99 +30327969 56 +24043492 56 +53433385 89 +44532181 79 +83041600 87 +*/ + +console.log('Student Data: \n'); +for (var i = 0; i < students.length; ++i) { + console.log(students[i].substring(0,8) + ' ' + students[i].substring(9)); +} + +console.log('\n\nData distribution: \n'); +var hTable = new HashTable(); +for (var i = 0; i < students.length; ++i) { + hTable.put(students[i]); +} +hTable.showDistro(); +/* +(example) +21: 87502846882 +46: 44532181579 +65: 04699389394 +66: 61488320499 +78: 32877112759 +89: 53433385189 +91: 24043492556 +98: 30327969356 +113: 83041600687 +136: 26704238989 +*/ diff --git a/js/hanbit-data-structures-and-algorithms-with-js/09/Set.js b/js/hanbit-data-structures-and-algorithms-with-js/09/Set.js new file mode 100644 index 0000000000..90c73c52ce --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/09/Set.js @@ -0,0 +1,96 @@ +function Set() { + this.dataStore = []; + this.add = add; + this.remove = remove; + this.size = size; + this.contains = contains + this.union = union; + this.intersect = intersect; + this.subset = subset; + this.difference = difference; + this.show = show; +} + +function add(data) { + if (this.dataStore.indexOf(data) < 0) { + this.dataStore.push(data); + return true; + } else { + return false; + } +} + +function remove(data) { + var pos = this.dataStore.indexOf(data); + if (pos > -1) { + this.dataStore.splice(pos, 1); + return true; + } else { + return false; + } +} + +function show() { + return this.dataStore; +} + +function contains(data) { + if (this.dataStore.indexOf(data) > -1) { + return true; + } else { + return false; + } +} + +function union(set) { + var tempSet = new Set(); + for (var i = 0; i < this.dataStore.length; ++i) { + tempSet.add(this.dataStore[i]); + } + for (var i = 0; i < set.dataStore.length; ++i) { + if (!tempSet.contains(set.dataStore[i])) { + tempSet.dataStore.push(set.dataStore[i]); + } + } + + return tempSet; +} + +function intersect(set) { + var tempSet = new Set(); + for (var i = 0; i < this.dataStore.length; ++i) { + if (set.contains(this.dataStore[i])) { + tempSet.add(this.dataStore[i]); + } + } + return tempSet; +} + +function subset(set) { + if (this.size() > set.size()) { + return false; + } else { + for (var i = 0; i < this.dataStore.length; i++) { + if (!set.contains(this.dataStore[i])) { + return false; + } + } + } + return true; +} + +function size() { + return this.dataStore.length; +} + +function difference(set) { + var tempSet = new Set(); + for (var i = 0; i < this.dataStore.length; ++i) { + if (!set.contains(this.dataStore[i])) { + tempSet.add(this.dataStore[i]); + } + } + return tempSet; +} + +module.exports.Set = Set; diff --git a/js/hanbit-data-structures-and-algorithms-with-js/09/quiz.js b/js/hanbit-data-structures-and-algorithms-with-js/09/quiz.js new file mode 100644 index 0000000000..ce9e858302 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/09/quiz.js @@ -0,0 +1,6 @@ +/* +1. Set 클래스에 저장하는 요소를 정렬하도록 Set 클래스를 고치시오. 그리고 요소가 정렬되었는지 확인할 수 있는 프로그램을 구현하시오. +2. 배열 대신 연결 리스트에 요소를 저장하도록 Set 클래스를 고치시오. 그리고 고친 SEt 클래스가 제대로 동작하는지 확인하는 프로그램을 구현하시오. +3. Set 클래스에 higher(요소) 함수를 추가하시오. higher() 함수는 인자로 제공된 인자보다 큰 요소 중 가장 작은 요소를 반환한다. higher() 함수가 제대로 동작하는지 확인할 수 있는 프로그램을 구현하시오. +4. Set 클래스에 lower(요소) 함수를 추가하시오. lower() 함수는 인자로 제공된 인자보다 작은 요소 중 가장 큰 요소를 반환한다. lower() 함수가 제대로 동작하는지 확인할 수 있는 프로그램을 구현하시오. +*/ diff --git a/js/hanbit-data-structures-and-algorithms-with-js/09/use_set.js b/js/hanbit-data-structures-and-algorithms-with-js/09/use_set.js new file mode 100644 index 0000000000..26383f9852 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/09/use_set.js @@ -0,0 +1,35 @@ +var {Set} = require('./Set'); + +var names = new Set(); +names.add('David'); +names.add('Jennifer'); +names.add('Cynthia'); +names.add('Mike'); +names.add('Raymond'); + +if (names.add('Mike')) { + console.log('Mike added'); +} else { + console.log("Can't add Mike, must already be in set"); // Can't add Mike, must already be in set +} + +console.log(names.show()); // [ 'David', 'Jennifer', 'Cynthia', 'Mike', 'Raymond' ] + +var removed = 'Mike'; + +if (names.remove(removed)) { + console.log(removed + ' removed'); // Mike removed +} else { + console.log(removed + ' not removed'); +} + +names.add('Clayton'); + +console.log(names.show()); // [ 'David', 'Jennifer', 'Cynthia', 'Raymond', 'Clayton' ] + +removed = 'Alisa'; +if (names.remove(removed)) { + console.log(removed + ' removed'); +} else { + console.log(removed + ' not removed'); // Alisa not removed +} diff --git a/js/hanbit-data-structures-and-algorithms-with-js/09/use_set2.js b/js/hanbit-data-structures-and-algorithms-with-js/09/use_set2.js new file mode 100644 index 0000000000..255eb5e8ac --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/09/use_set2.js @@ -0,0 +1,63 @@ +var {Set} = require('./Set'); + +var cis = new Set(); + +cis.add('Mike'); +cis.add('Clayton'); +cis.add('Jennifer'); +cis.add('Raymond'); + +var dmp = new Set(); +dmp.add('Raymond'); +dmp.add('Cynthia'); +dmp.add('Jonathan'); + +var it = new Set(); +it = cis.union(dmp); + +console.log(it.show()); // [ 'Mike', 'Clayton', 'Jennifer', 'Raymond', 'Cynthia', 'Jonathan' ] + +var inter = cis.intersect(dmp); +console.log(inter.show()); // [ 'Raymond' ] + + +////////// + +var it2 = new Set(); +it2.add('Cynthia'); +it2.add('Clayton'); +it2.add('Jennifer'); +it2.add('Danny'); +it2.add('Jonathan'); +it2.add('Terrill'); +it2.add('Raymond'); +it2.add('Mike'); + +var dmp2 = new Set(); +dmp.add('Cynthia'); +dmp.add('Raymond'); +dmp.add('Jonathan'); + +if (dmp2.subset(it2)) { + console.log('dmp2 is a subset of it2'); // dmp2 is a subset of it2 +} else { + console.log('dmp2 is not a subset of it2'); +} + +//////////// + +var cis3 = new Set(); +var it3 = new Set(); +cis3.add('Clayton'); +cis3.add('Jennifer'); +cis3.add('Danny'); +it3.add('Bryan'); +it3.add('Clayton'); +it3.add('Jennifer'); + +var diff = new Set(); +diff = cis3.difference(it3); + +console.log('[' + cis3.show() + '] difference [' + it3.show() + '] -> [' + diff.show() + ']'); // [Clayton,Jennifer,Danny] difference [Bryan,Clayton,Jennifer] -> [Danny] + + diff --git a/js/hanbit-data-structures-and-algorithms-with-js/10/BST.js b/js/hanbit-data-structures-and-algorithms-with-js/10/BST.js new file mode 100644 index 0000000000..d68f1eaf2c --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/10/BST.js @@ -0,0 +1,113 @@ +var {Node} = require('./Node'); + +function BST() { + this.root = null; + this.insert = insert; + this.getMin = getMin; + this.getMax = getMax; + this.find = find; + this.remove = remove; + this.removeNode = removeNode; + this.update = update; +} + +function insert(data) { + var n = new Node(data, null, null); + + if (this.root == null) { + this.root = n; + } else { + var current = this.root; + var parent; + while (true) { + parent = current; + if (data < current.data) { + current = current.left; + if (current == null) { + parent.left = n; + break; + } + } else { + current = current.right; + if (current == null) { + parent.right = n; + break; + } + } + } + } +} + +function getMin() { + var current = this.root; + while (!(current.left == null)) { + current = current.left; + } + return current.data; +} + +function getMax() { + var current = this.root; + while (!(current.right == null)) { + current = current.right; + } + return current.data; +} + +function find(data) { + var current = this.root; + while (current && current.data != data) { + if (data < current.data) { + current = current.left; + } else { + current = current.right; + } + if (current == null) { + return null; + } + } + return current; +} + +function remove(data) { + root = removeNode(this.root, data); +} + +function removeNode(node, data) { + if (node == null) { + return null; + } + if (data == node.data) { + // 자식이 없는 노드 + if (node.left == null && node.right == null) { + return null; + } + // 왼쪽 자식이 없는 노드 + if (node.left == null) { + return node.right; + } + // 오른쪽 자식이 없는 노드 + if (node.right == null) { + return node.left; + } + // 두 자식이 있는 노드 + // var tempNode = getSmallest(node.right); + // node.data = tempNode.data; + // node.right = removeNode(node.right, tempNode.data); + return node; + } else if (data < node.data) { + node.left = removeNode(node.left, data); + return node; + } else { + node.right = removeNode(node.right, data); + return node; + } +} + +function update(data) { + var grade = this.find(data); + grade.count++; + return grade; +} + +module.exports.BST = BST; diff --git a/js/hanbit-data-structures-and-algorithms-with-js/10/Node.js b/js/hanbit-data-structures-and-algorithms-with-js/10/Node.js new file mode 100644 index 0000000000..838db5963a --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/10/Node.js @@ -0,0 +1,13 @@ +function Node(data, left, right) { + this.data = data; + this.count = 1; + this.left = left; + this.right = right; + this.show = show; +} + +function show() { + return this.data; +} + +module.exports.Node = Node; diff --git a/js/hanbit-data-structures-and-algorithms-with-js/10/quiz.js b/js/hanbit-data-structures-and-algorithms-with-js/10/quiz.js new file mode 100644 index 0000000000..56bb5ab85b --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/10/quiz.js @@ -0,0 +1,7 @@ +/* +1. BST의 노드 개수를 계산하는 함수를 BST 클래스에 추가하시오. +2. BST의 에지 개수를 계산하는 함수를 BST 클래스에 추가하시오. +3. BST에서 최댓값을 검색하는 max() 함수를 BST 클래스에 추가하시오. +4. BST에서 최솟값을 검색하는 min() 함수를 BST 클래스에 추가하시오. +5. 큰 텍스트 파일에 저장된 단어를 BST로 저장한 다음 각 단어가 등장하는 횟수를 출력하는 프로그램을 구현하시오. +*/ diff --git a/js/hanbit-data-structures-and-algorithms-with-js/10/use_bst.js b/js/hanbit-data-structures-and-algorithms-with-js/10/use_bst.js new file mode 100644 index 0000000000..eecc2a836b --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/10/use_bst.js @@ -0,0 +1,43 @@ +var {BST} = require('./BST'); + +function inOrder(node) { + if (!(node == null)) { + inOrder(node.left); + console.log(node.show()); + inOrder(node.right); + } +} + +var nums = new BST(); +nums.insert(23); +nums.insert(45); +nums.insert(16); +nums.insert(37); +nums.insert(3); +nums.insert(99); +nums.insert(22); + +console.log('Inorder traversal: '); +inOrder(nums.root); // 3 16 22 23 37 45 99 + +function preOrder(node) { + if (!(node == null)) { + console.log(node.show()); + preOrder(node.left); + preOrder(node.right); + } +} + +console.log('Preorder traversal: '); +preOrder(nums.root); // 23 16 3 22 45 37 99 + +function postOrder(node) { + if (!(node == null)) { + postOrder(node.left); + postOrder(node.right); + console.log(node.show()); + } +} + +console.log('Postorder traversal: '); +postOrder(nums.root); // 3 22 16 37 99 45 23 diff --git a/js/hanbit-data-structures-and-algorithms-with-js/10/use_bst2.js b/js/hanbit-data-structures-and-algorithms-with-js/10/use_bst2.js new file mode 100644 index 0000000000..2b04d90a10 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/10/use_bst2.js @@ -0,0 +1,35 @@ +var {BST} = require('./BST'); + +var nums = new BST(); +nums.insert(23); +nums.insert(45); +nums.insert(16); +nums.insert(37); +nums.insert(3); +nums.insert(99); +nums.insert(22); + +var min = nums.getMin(); +console.log('The minimum value of the BST is: ' + min); // 3 + +var max = nums.getMax(); +console.log('The maximum value of the BST is: ' + max); // 99 + +function inOrder(node) { + if (!(node == null)) { + inOrder(node.left); + console.log(node.show()); + inOrder(node.right); + } +} + +inOrder(nums.root); + +var value = 3; +var found = nums.find(value); + +if (found != null) { + console.log('Found ' + value + ' in the BST.'); // Found 3 in the BST. +} else { + console.log(value + ' was not found in the BST.'); +} diff --git a/js/hanbit-data-structures-and-algorithms-with-js/10/use_bst3.js b/js/hanbit-data-structures-and-algorithms-with-js/10/use_bst3.js new file mode 100644 index 0000000000..57b5bfdffb --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/10/use_bst3.js @@ -0,0 +1,46 @@ +var {BST} = require('./BST'); + +function prArray(arr) { + console.log(arr[0].toString()); + + for (var i = 0; i < arr.length; ++i) { + console.log(arr[i].toString()); + if (i % 10 == 0) { + console.log('\n'); + } + } +} + +function genArray(length) { + var arr = []; + for (var i = 0; i < length; ++i) { + arr[i] = Math.floor(Math.random() * 101); + } + return arr; +} + +var grades = genArray(100); + +prArray(grades); + +var gradedistro = new BST(); + +for (var i = 0; i < grades.length; ++i) { + var g = grades[i]; + var grade = gradedistro.find(g); + if (grade == null) { + gradedistro.insert(g); + } else { + gradedistro.update(g); + } +} + +var cont = 'y'; + +var g = 100; +var aGrade = gradedistro.find(g); +if (aGrade == null) { + console.log('No occurences of ' + g); +} else { + console.log('Occurences of ' + g + ': ' + aGrade.count); +} diff --git a/js/hanbit-data-structures-and-algorithms-with-js/11/Graph.js b/js/hanbit-data-structures-and-algorithms-with-js/11/Graph.js new file mode 100644 index 0000000000..ee7f759ada --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/11/Graph.js @@ -0,0 +1,122 @@ +function Graph(v) { + this.vertices = v; + this.vertexList = []; + this.edges = 0; + this.adj = []; + for (var i = 0; i < this.vertices; ++i) { + this.adj[i] = []; + } + this.addEdge = addEdge; + this.showGraph = showGraph; + this.dfs = dfs; + this.marked = []; + for (var i = 0; i < this.vertices; ++i) { + this.marked[i] = false; + } + this.edgeTo = []; + this.bfs = bfs; + this.pathTo = pathTo; + this.hasPathTo = hasPathTo; + this.topSort = topSort; + this.topSortHelper = topSortHelper; +} + +function addEdge(v, w) { + this.adj[v].push(w); + this.adj[w].push(v); + this.edges++; +} + +function showGraph() { + for (var i = 0; i < this.vertices; ++i) { + var result = i + ' -> '; + for (var j = 0; j < this.vertices; ++j) { + if (this.adj[i][j] != undefined) { + result += this.adj[i][j] + ' '; + } + } + console.log(result); + } +} + +// 깊이 우선 검색 +function dfs(v) { + this.marked[v] = true; + if (this.adj[v] != undefined) { + console.log('Visited vertex: ' + v); + } + for (var i = 0; i < this.adj[v].length; ++i) { + if (!this.marked[this.adj[v][i]]) { + this.dfs(this.adj[v][i]); + } + } +} + +// 너비 우선 검색 +function bfs(s) { + var queue = []; + this.marked[s] = true; + queue.push(s); // 큐로 삽입 + while (queue.length > 0) { + var v = queue.shift(); // 큐에서 가져옴 + if (v != undefined) { + console.log('Visited vertex: ' + v); + } + for (var i = 0; i < this.adj[v].length; ++i) { + if (!this.marked[this.adj[v][i]]) { + this.edgeTo[this.adj[v][i]] = v; + this.marked[this.adj[v][i]] = true; + queue.push(this.adj[v][i]); + } + } + } +} + +function pathTo(v) { + var source = 0; + if (!this.hasPathTo(v)) { + return undefined; + } + + var path = []; + for (var i = v; i != source; i = this.edgeTo[i]) { + path.push(i); + } + path.push(source); + return path; +} + +function hasPathTo(v) { + return this.marked[v]; +} + +function topSort() { + var stack = []; + var visited = []; + for (var i = 0; i < this.vertices; i++) { + visited[i] = false; + } + for (var i = 0 ; i < this.vertices; i++) { + if (visited[i] == false) { + this.topSortHelper(i, visited, stack); + } + } + for (var i = 0; i < stack.length; i++) { + if (stack[i] != undefined && stack[i] != false) { + console.log(this.vertexList[stack[i]]); + } + } +} + +function topSortHelper(v, visited, stack) { + visited[v] = true; + for (var i = 0; i < this.adj[v].length; ++i) { + if (!visited[this.adj[v][i]]) { + this.topSortHelper(this.adj[v][i], visited, stack); + } + } + console.log(v) + stack.push(v); +} + +module.exports.Graph = Graph; \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/11/quiz.js b/js/hanbit-data-structures-and-algorithms-with-js/11/quiz.js new file mode 100644 index 0000000000..7134bf361f --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/11/quiz.js @@ -0,0 +1,7 @@ +/* +1. 너비 우선 검색과 깊이 우선 검색 중 어떤 그래프 검색 방법이 더 빠른지 검증하는 프로그램을 구현하시오. +2. 그래프를 파일로 저장하는 프로그램을 구현하시오. +3. 파일로부터 그래프를 읽는 프로그램을 구현하시오. +4. 자신이 사는 동네의 지도를 표현하는 그래프를 만드시오. 첫 번째 정점에서 마지막 정점으로 도달하는 최단 경로를 찾으시오. +5. 4번 예제에서 만든 그래프에 깊이 우선 검색과 너비 우선 검색을 수행하시오. +*/ diff --git a/js/hanbit-data-structures-and-algorithms-with-js/11/use_graph.js b/js/hanbit-data-structures-and-algorithms-with-js/11/use_graph.js new file mode 100644 index 0000000000..7aa715af91 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/11/use_graph.js @@ -0,0 +1,45 @@ +var {Graph} = require('./Graph'); + +var g = new Graph(5); +g.addEdge(0,1); +g.addEdge(0,2); +g.addEdge(1,3); +g.addEdge(2,4); +g.showGraph(); +/* +0 -> 1 2 +1 -> 0 3 +2 -> 0 4 +3 -> 1 +4 -> 2 +*/ + +// g.dfs(0); +/* +Visited vertex: 0 +Visited vertex: 1 +Visited vertex: 3 +Visited vertex: 2 +Visited vertex: 4 +*/ + +g.bfs(0); +/* +Visited vertex: 0 +Visited vertex: 1 +Visited vertex: 2 +Visited vertex: 3 +Visited vertex: 4 +*/ + +var vertex = 4; +var paths = g.pathTo(vertex); +var result = ''; +while (paths.length > 0) { + if (paths.length > 1) { + result += paths.pop() + '-'; + } else { + result += paths.pop(); + } +} +console.log(result); // 0-2-4 \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/11/use_graph2.js b/js/hanbit-data-structures-and-algorithms-with-js/11/use_graph2.js new file mode 100644 index 0000000000..049db19a65 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/11/use_graph2.js @@ -0,0 +1,19 @@ +var {Graph} = require('./Graph'); + +var g = new Graph(6); +g.addEdge(1,2); +g.addEdge(2,5); +g.addEdge(1,3); +g.addEdge(1,4); +g.addEdge(0,1); + +g.vertexList = ['CS1', 'CS2', 'Data Structures', 'Assembly Language', 'Operating Systems', 'Algorithms']; + +g.topSort() +/* +Algorithms +Data Structures +Assembly Language +Operating Systems +CS2 +*/ \ No newline at end of file diff --git a/js/hanbit-data-structures-and-algorithms-with-js/12/CArray.js b/js/hanbit-data-structures-and-algorithms-with-js/12/CArray.js new file mode 100644 index 0000000000..629926c3cb --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/12/CArray.js @@ -0,0 +1,182 @@ +function CArray(numElements) { + this.dataStore = []; + this.pos = 0; + this.numElements = numElements; + this.insert = insert; + this.toString = toString; + this.clear = clear; + this.setData = setData; + this.swap = swap; + this.bubbleSort = bubbleSort; + this.selectionSort = selectionSort; + this.insertionSort = insertionSort; + this.gaps = [5,3,1]; + this.shellSort = shellSort; + this.setGaps = setGaps; + this.shellSort2 = shellSort2; + this.mergeSort = mergeSort; + this.mergeArrays = mergeArrays; + for (var i = 0; i < numElements; ++i) { + this.dataStore[i] = 0; + } +} + +function setData() { + for (var i = 0; i < this.numElements; ++i) { + this.dataStore[i] = Math.floor(Math.random() * (this.numElements + 1)); + } +} + +function clear() { + for(var i = 0; i < this.dataStore.length; ++i) { + this.dataStore[i] = 0; + } +} + +function insert(element) { + this.dataStore[this.pos++] = element; +} + +function toString() { + var retstr = ''; + for (var i = 0; i < this.dataStore.length; ++i) { + retstr += this.dataStore[i] + ' '; + if (i > 0 && i % 10 == 0) { + retstr += '\n'; + } + } + return retstr; +} + +function swap(arr, index1, index2) { + var temp = arr[index1]; + arr[index1] = arr[index2]; + arr[index2] = temp; +} + +function bubbleSort() { + var numElements = this.dataStore.length; + var temp; + for (var outer = numElements; outer >= 2; --outer) { + for (var inner = 0; inner <= outer-1; ++inner) { + if (this.dataStore[inner] > this.dataStore[inner+1]) { + swap(this.dataStore, inner, inner+1); + } + } + console.log(this.toString()); + } +} + +function selectionSort() { + var min, temp; + for (var outer = 0; outer <= this.dataStore.length-2; ++outer) { + min = outer; + for (var inner = outer + 1; inner <= this.dataStore.length-1; ++inner) { + if (this.dataStore[inner] < this.dataStore[min]) { + min = inner; + } + } + swap(this.dataStore, outer, min); + } +} + +function insertionSort() { + var temp, inner; + for (var outer = 1; outer <= this.dataStore.length - 1; ++outer) { + temp = this.dataStore[outer]; + inner = outer; + while (inner > 0 && (this.dataStore[inner - 1] >= temp)) { + this.dataStore[inner] = this.dataStore[inner - 1]; + --inner; + } + this.dataStore[inner] = temp; + } +} + +function shellSort() { + for (var g = 0; g < this.gaps.length; ++g) { + for (var i = this.gaps[g]; i < this.dataStore.length; ++i) { + var temp = this.dataStore[i]; + for (var j = i; j >= this.gaps[g] && this.dataStore[j - this.gaps[g]] > temp; j -= this.gaps[g]) { + this.dataStore[j] = this.dataStore[j - this.gaps[g]]; + } + this.dataStore[j] = temp; + } + } +} + +function setGaps(arr) { + this.gaps = arr; +} + +function shellSort2() { + var N = this.dataStore.length; + var h = 1; + while (h < N/3) { + h = 3 * h + 1; + } + while (h >= 1) { + for (var i = h; i < N; i++) { + for (var j = i; j >= h && this.dataStore[j] < this.dataStore[j-h]; j -= h) { + swap(this.dataStore, j, j-h); + } + } + h = (h-1)/3; + } +} + +function mergeSort() { + if (this.dataStore.length < 2) { + return; + } + var step = 1; + var left, right; + while (step < this.dataStore.length) { + left = 0; + right = step; + while (right + step <= this.dataStore.length) { + mergeArrays(this.dataStore, left, left+step, right, right+step); + left = right + step; + right = left + step; + } + if (right < this.dataStore.length) { + mergeArrays(this.dataStore, left, left+step, right, this.dataStore.length); + } + step *= 2; + } +} + +function mergeArrays(arr, startLeft, stopLeft, startRight, stopRight) { + var rightArr = new Array(stopRight - startRight + 1); + var leftArr = new Array(stopLeft - startLeft + 1); + k = startRight; + for (var i = 0; i < (rightArr.length-1); ++i) { + rightArr[i] = arr[k]; + ++k; + } + k = startLeft; + for (var i = 0; i < (leftArr.length-1); ++i) { + leftArr[i] = arr[k]; + ++k; + } + + rightArr[rightArr.length-1] = Infinity; // 특수값 + leftArr[leftArr.length-1] = Infinity; // 특수값 + + var m = 0; + var n = 0; + + for (var k = startLeft; k < stopRight; ++k) { + if (leftArr[m] <= rightArr[n]) { + arr[k] = leftArr[m]; + m++; + } else { + arr[k] = rightArr[n]; + n++; + } + } + console.log('left array - ', leftArr); + console.log('right array - ', rightArr); +} + +module.exports.CArray = CArray; diff --git a/js/hanbit-data-structures-and-algorithms-with-js/12/example_mergesort.js b/js/hanbit-data-structures-and-algorithms-with-js/12/example_mergesort.js new file mode 100644 index 0000000000..c6bb381cc7 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/12/example_mergesort.js @@ -0,0 +1,78 @@ +function mergeSort(arr) { + if (arr.length < 2) { + return; + } + var step = 1; + var left, right; + while (step < arr.length) { + left = 0; + right = step; + while (right + step <= arr.length) { + mergeArrays(arr, left, left+step, right, right+step); + left = right + step; + right = left + step; + } + if (right < arr.length) { + mergeArrays(arr, left, left+step, right, arr.length); + } + step *= 2; + } +} + +function mergeArrays(arr, startLeft, stopLeft, startRight, stopRight) { + var rightArr = new Array(stopRight - startRight + 1); + var leftArr = new Array(stopLeft - startLeft + 1); + k = startRight; + for (var i = 0; i < (rightArr.length-1); ++i) { + rightArr[i] = arr[k]; + ++k; + } + k = startLeft; + for (var i = 0; i < (leftArr.length-1); ++i) { + leftArr[i] = arr[k]; + ++k; + } + + rightArr[rightArr.length-1] = Infinity; // 특수값 + leftArr[leftArr.length-1] = Infinity; // 특수값 + + var m = 0; + var n = 0; + + for (var k = startLeft; k < stopRight; ++k) { + if (leftArr[m] <= rightArr[n]) { + arr[k] = leftArr[m]; + m++; + } else { + arr[k] = rightArr[n]; + n++; + } + } + console.log('left array - ', leftArr); + console.log('right array - ', rightArr); +} + +var nums = [6,10,1,9,4,8,2,7,3,5]; +mergeSort(nums); +/* +left array - [ 6, Infinity ] +right array - [ 10, Infinity ] +left array - [ 1, Infinity ] +right array - [ 9, Infinity ] +left array - [ 4, Infinity ] +right array - [ 8, Infinity ] +left array - [ 2, Infinity ] +right array - [ 7, Infinity ] +left array - [ 3, Infinity ] +right array - [ 5, Infinity ] +left array - [ 6, 10, Infinity ] +right array - [ 1, 9, Infinity ] +left array - [ 4, 8, Infinity ] +right array - [ 2, 7, Infinity ] +left array - [ 1, 6, 9, 10, Infinity ] +right array - [ 2, 4, 7, 8, Infinity ] +left array - [ 1, 2, 4, 6, 7, 8, 9, 10, Infinity ] +right array - [ 3, 5, Infinity ] +*/ + +console.log(nums); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] diff --git a/js/hanbit-data-structures-and-algorithms-with-js/12/example_qsort.js b/js/hanbit-data-structures-and-algorithms-with-js/12/example_qsort.js new file mode 100644 index 0000000000..6c0442b1b0 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/12/example_qsort.js @@ -0,0 +1,24 @@ +function qSort(arr) { + if (arr.length == 0) { + return []; + } + var left = []; + var right = []; + var pivot = arr[0]; + for (var i = 1; i < arr.length; i++) { + if (arr[i] < pivot) { + left.push(arr[i]); + } else { + right.push(arr[i]); + } + } + return qSort(left).concat(pivot, qSort(right)); +} + +var a = []; +for (var i = 0; i < 10; ++i) { + a[i] = Math.floor((Math.random() * 100) + 1); +} + +console.log(a); // [ 8, 9, 84, 12, 88, 29, 47, 33, 54, 73 ] +console.log(qSort(a)); // [ 8, 9, 12, 29, 33, 47, 54, 73, 84, 88 ] diff --git a/js/hanbit-data-structures-and-algorithms-with-js/12/quiz.js b/js/hanbit-data-structures-and-algorithms-with-js/12/quiz.js new file mode 100644 index 0000000000..6afd22a147 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/12/quiz.js @@ -0,0 +1,6 @@ +/* +1. 12장에서 설명한 세 가지 알고리즘에 숫자 대신 문자열 데이터를 적용해보고 성능을 비교하시오. 숫자 데이터를 이용했을 때와 같은 성능 결과가 나오는가? +2. 크기순으로 정렬된 1,000개의 정수를 포함하는 배열을 만드시오. 그리고 각 알고리즘으로 이 배열을 정렬하면서 소요되는 시간을 측정하시오. 임의의 순서로 되어 있는 배열을 정렬할 때와 비교했을 때 얼마나 빨리 정렬을 수행하는가? +3. 역순으로 정렬된 1,000개의 정수를 포함하는 배열을 만드시오. 그리고 각 알고리즘을 이 배열을 정리하면서 시간을 측정하고 성능을 비교하시오. +4. 임의의 숫자 10,000개의 정수를 포함하는 배열을 만든 다음 퀵 정렬과 자바 내장 정렬 함수를 이용해 배열을 정렬하면서 시간을 측정하시오. 두 함수의 성능이 같은지 비교하시오. +*/ diff --git a/js/hanbit-data-structures-and-algorithms-with-js/12/use_carray.js b/js/hanbit-data-structures-and-algorithms-with-js/12/use_carray.js new file mode 100644 index 0000000000..100efad98e --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/12/use_carray.js @@ -0,0 +1,24 @@ +var {CArray} = require('./CArray'); + +var numElements = 1000; +var myNums = new CArray(numElements); +myNums.setData(); +console.log(myNums.toString()); + +var start = new Date().getTime(); +myNums.bubbleSort(); +var stop = new Date().getTime(); +var elapsed = stop - start; +console.log('Elapsed time for the bubble sort on ' + numElements + ' elements is: ' + elapsed + ' miliseconds.'); + +start = new Date().getTime(); +myNums.selectionSort(); +stop = new Date().getTime(); +elapsed = stop - start; +console.log('Elapsed time for the selection sort on ' + numElements + ' elements is: ' + elapsed + ' miliseconds.'); + +start = new Date().getTime(); +myNums.insertionSort(); +stop = new Date().getTime(); +elapsed = stop - start; +console.log('Elapsed time for the insertion sort on ' + numElements + ' elements is: ' + elapsed + ' miliseconds.'); diff --git a/js/hanbit-data-structures-and-algorithms-with-js/12/use_mergesort.js b/js/hanbit-data-structures-and-algorithms-with-js/12/use_mergesort.js new file mode 100644 index 0000000000..51f0a8136d --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/12/use_mergesort.js @@ -0,0 +1,30 @@ +var {CArray} = require('./CArray'); + +var nums = new CArray(10); + +nums.setData(); +console.log(nums.toString()); // 2 9 5 7 8 2 0 0 6 1 + +nums.mergeSort(); +/* +left array - [ 2, Infinity ] +right array - [ 9, Infinity ] +left array - [ 5, Infinity ] +right array - [ 7, Infinity ] +left array - [ 8, Infinity ] +right array - [ 2, Infinity ] +left array - [ 0, Infinity ] +right array - [ 0, Infinity ] +left array - [ 6, Infinity ] +right array - [ 1, Infinity ] +left array - [ 2, 9, Infinity ] +right array - [ 5, 7, Infinity ] +left array - [ 2, 8, Infinity ] +right array - [ 0, 0, Infinity ] +left array - [ 2, 5, 7, 9, Infinity ] +right array - [ 0, 0, 2, 8, Infinity ] +left array - [ 0, 0, 2, 2, 5, 7, 8, 9, Infinity ] +right array - [ 1, 6, Infinity ] +*/ + +console.log(nums.toString()); // 0 0 1 2 2 5 6 7 8 9 diff --git a/js/hanbit-data-structures-and-algorithms-with-js/12/use_shellsort.js b/js/hanbit-data-structures-and-algorithms-with-js/12/use_shellsort.js new file mode 100644 index 0000000000..68651b6a9b --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/12/use_shellsort.js @@ -0,0 +1,30 @@ +var {CArray} = require('./CArray'); + +var nums = new CArray(10); +nums.setData(); + +console.log('Before Shellsort: \n'); +console.log(nums.toString()); + +console.log('\nDuring Shellsort: \n'); +nums.shellSort(); + +console.log('\nAfter Shellsort: \n'); +console.log(nums.toString()); + +/* +var start = new Date().getTime(); +nums.shellSort(); +var stop = new Date().getTime(); +var elapsed = stop - start; +console.log('Shellsort with hard-coded gap sequence: ' + elapsed + ' ms.'); + +nums.clear(); +nums.setData(); + +start = new Date().getTime(); +nums.shellSort2(); +stop = new Date().getTime(); +elapsed = stop - start; +console.log('Shellsort with dynamic gap sequence: ' + elapsed + ' ms.'); +*/ diff --git a/js/hanbit-data-structures-and-algorithms-with-js/13/1-0.js b/js/hanbit-data-structures-and-algorithms-with-js/13/1-0.js new file mode 100644 index 0000000000..dce5ddf15f --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/13/1-0.js @@ -0,0 +1,29 @@ +// 13 검색 알고리즘 - 1 순차 검색 + +var {dispArr} = require('./dispArr'); + +function seqSearch(arr, data) { + for (var i = 0; i < arr.length; ++i) { + if (arr[i] == data) { + return i; + } + } + return -1; +} + +var nums = []; +for (var i = 0; i < 100; ++i) { + nums[i] = Math.floor(Math.random() * 101); +} + +dispArr(nums); + +var num = Math.floor(Math.random() * 101); +var position = seqSearch(nums, num); + +if (position > -1) { + console.log(num + ' is in the array at the position ' + position); +} else { + console.log(num + ' is not in the array.'); +} + diff --git a/js/hanbit-data-structures-and-algorithms-with-js/13/1-1.js b/js/hanbit-data-structures-and-algorithms-with-js/13/1-1.js new file mode 100644 index 0000000000..a61454ad4d --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/13/1-1.js @@ -0,0 +1,38 @@ +// 13 검색 알고리즘 - 1 순차 검색 - 1 최솟값과 최댓값 검색 + +var {dispArr} = require('./dispArr'); + +function findMin(arr) { + var min = arr[0]; + for (var i = 0; i < arr.length; ++i) { + if (arr[i] < min) { + min = arr[i]; + } + } + return min; +} + +var nums = []; +for (var i = 0; i < 100; ++i) { + nums[i] = Math.floor(Math.random() * 101); +} + +var minValue = findMin(nums); +dispArr(nums); + +console.log('The minimum value is: ' + minValue); + +//////////// + +function findMax(arr) { + var max = arr[0]; + for (var i = 0; i < arr.length; ++i) { + if (arr[i] > max) { + max = arr[i]; + } + } + return max; +} + +var maxValue = findMax(nums); +console.log('The maxmium value is: ' + maxValue); diff --git a/js/hanbit-data-structures-and-algorithms-with-js/13/1-2.js b/js/hanbit-data-structures-and-algorithms-with-js/13/1-2.js new file mode 100644 index 0000000000..8092e99242 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/13/1-2.js @@ -0,0 +1,61 @@ +// 13 검색 알고리즘 - 1 순차 검색 - 2 자체 정렬 데이터 + +var {dispArr} = require('./dispArr'); + +function seqSearch(arr, data) { + for (var i = 0; i < arr.length; ++i) { + if (arr[i] == data) { + if (i > 0) { + swap(arr, i, i-1); + } + return true; + } + } + return false; +} + +function swap(arr, index, index1) { + var temp = arr[index]; + arr[index] = arr[index1]; + arr[index1] = temp; +} + +var numbers = [5,1,7,4,2,10,9,3,6,8]; + +for (var i = 1; i <= 3; i++) { + seqSearch(numbers, 4); + console.log(numbers); +} +/* +[ 5, 1, 4, 7, 2, 10, 9, 3, 6, 8 ] +[ 5, 4, 1, 7, 2, 10, 9, 3, 6, 8 ] +[ 4, 5, 1, 7, 2, 10, 9, 3, 6, 8 ] +*/ + +//////////////// + +function seqSearch2(arr, data) { + for (var i = 0; i < arr.length; ++i) { + if(arr[i] == data && i > (arr.length * 0.2)) { + swap(arr, i, 0); + return true; + } else if (arr[i] == data) { + return true; + } + } + return false; +} + +var numbers2 = []; +for (var i = 0; i < 10; ++i) { + numbers2[i] = Math.floor(Math.random() * 11); +} +dispArr(numbers2); + +var val = 10; +if (seqSearch2(numbers2, val)) { + console.log('Found element: ') + dispArr(numbers); +} else { + console.log(val + ' is not in array.'); +} diff --git a/js/hanbit-data-structures-and-algorithms-with-js/13/2-0.js b/js/hanbit-data-structures-and-algorithms-with-js/13/2-0.js new file mode 100644 index 0000000000..6772c71f76 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/13/2-0.js @@ -0,0 +1,53 @@ +// 13 - 2 이진 검색 + +var {dispArr} = require('./dispArr'); + +function binSearch(arr, data) { + var upperBound = arr.length - 1; + var lowerBound = 0; + while (lowerBound <= upperBound) { + var mid = Math.floor((upperBound + lowerBound) / 2); + console.log('Current midpoint: ' + mid); + if (arr[mid] < data) { + lowerBound = mid + 1; + } else if (arr[mid] > data) { + upperBound = mid - 1; + } else { + return mid; + } + } + return -1; +} + +var nums = []; +for (var i = 0; i < 100; ++i) { + nums[i] = Math.floor(Math.random() * 101); +} + +function insertionSort(arr) { + var temp, inner; + for (var outer = 1; outer <= arr.length - 1; ++outer) { + temp = arr[outer]; + inner = outer; + while (inner > 0 && (arr[inner - 1] >= temp)) { + arr[inner] = arr[inner - 1]; + --inner; + } + arr[inner] = temp; + } +} + +insertionSort(nums); +dispArr(nums); + +var val = 10; +var retVal = binSearch(nums, val); + +if (retVal >= 0) { + console.log('Found ' + val + ' at the position ' + retVal); +} else { + console.log(val + ' is not in array.'); +} + +module.exports.binSearch = binSearch; +module.exports.insertionSort = insertionSort; diff --git a/js/hanbit-data-structures-and-algorithms-with-js/13/2-1.js b/js/hanbit-data-structures-and-algorithms-with-js/13/2-1.js new file mode 100644 index 0000000000..e57bb57f9e --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/13/2-1.js @@ -0,0 +1,40 @@ +// 13 - 2 이진 검색 - 1 발견 횟수 계산 + +var {binSearch, insertionSort} = require('./2-0'); +var {dispArr} = require('./dispArr'); + +function count(arr, data) { + var count = 0; + var position = binSearch(arr, data); + + if (position > -1) { + ++count; + for (var i = position-1; i > 0; --i) { + if (arr[i] == data) { + ++count; + } else { + break; + } + } + for (var i = position+1; i < arr.length; ++i) { + if (arr[i] == data) { + ++count; + } else { + break; + } + } + } + return count; +} + +var nums = []; +for (var i = 0; i < 100; ++i) { + nums[i] = Math.floor(Math.random() * 101); +} + +insertionSort(nums); +dispArr(nums); + +var val = 10; +var retVal = count(nums, val); +console.log('Found ' + retVal + ' occurences of ' + val + '.'); diff --git a/js/hanbit-data-structures-and-algorithms-with-js/13/3.js b/js/hanbit-data-structures-and-algorithms-with-js/13/3.js new file mode 100644 index 0000000000..8a1552f7e1 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/13/3.js @@ -0,0 +1,26 @@ +// 13 - 3 텍스트 데이터 검색 + +var fs = require('fs'); +var words = fs.readFileSync('./words.txt').toString('utf8').split(' '); + +function seqSearch(arr, data) { + for (var i = 0; i < arr.length; ++i) { + if (arr[i] == data) { + return i; + } + } + return -1; +} + +var word = 'rhetoric'; +var start = new Date().getTime(); +var position = seqSearch(words, word); +var stop = new Date().getTime(); +var elapsed = stop - start; + +if (position >= 0) { + console.log('Found ' + word + ' at position ' + position + '.'); + console.log('Sequential searck took ' + elapsed + ' miliseconds.'); +} else { + console.log(word + ' is not in the file.'); +} diff --git a/js/hanbit-data-structures-and-algorithms-with-js/13/dispArr.js b/js/hanbit-data-structures-and-algorithms-with-js/13/dispArr.js new file mode 100644 index 0000000000..4f497687da --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/13/dispArr.js @@ -0,0 +1,15 @@ +function dispArr(arr) { + var result = ''; + for (var i = 0; i < arr.length; ++i) { + result += arr[i] + ' '; + if (i % 10 == 9) { + result += '\n'; + } + } + if (i *10 != 0) { + result += '\n'; + } + console.log(result); +} + +module.exports.dispArr = dispArr; diff --git a/js/hanbit-data-structures-and-algorithms-with-js/13/quiz.js b/js/hanbit-data-structures-and-algorithms-with-js/13/quiz.js new file mode 100644 index 0000000000..882995afdc --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/13/quiz.js @@ -0,0 +1,5 @@ +/* +1. 순차 검색 알고리즘은 항상 데이터 집합에서 검색한 첫 번째 요소를 반환한다. 데이터 집합에서 검색된 마지막 요소를 반환하돌고 순차 검색 알고리즘을 고치시오. +2. 순차 검색으로 데이터를 검색하는 데 걸린 시간과 삽입 정렬을 이용한 데이터 집합 정렬에 걸린 시간을 포함한 전체 이진 검색을 수행하는 데 걸린 시간을 서로 비교하시오. 누가 더 빠른가? +3. 데이터 집합에서 두 번째로 작은 요소를 검색하는 함수를 구현하시오. 데이터 집합에서 세 번째, 네 번째, 다섯 번째 등으로 작은 요소를 검색하도록 함수 정의를 일반화할 수 있는가? 적어도 1,000개의 요소를 가진 데이터 집합을 이용해 함수를 테스트하이소. 또한 숫자와 텍스트 두 가지 데이터로 함수를 테스트하시오. +*/ diff --git a/js/hanbit-data-structures-and-algorithms-with-js/13/words.txt b/js/hanbit-data-structures-and-algorithms-with-js/13/words.txt new file mode 100644 index 0000000000..be29ecab57 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/13/words.txt @@ -0,0 +1 @@ +The nationalism of Hamilton was undemocratic. The democracy of Jefferson was, in the beginning, provincial. The historic mission of uniting nationalism and democracy was in the course of time given to new leaders from a region beyond the mountains, peopled by men and women from all sections and free from those state traditions which ran back to the early days of colonization. The voice of the democratic nationalism nourished in the West was heard when Clay of Kentucky advocated his American system of protection for industries; when Jackson of Tennessee condemned nullification in a ringing proclamation that has taken its place among the great American state papers; and when Lincoln of Illinois, in a fateful hour, called upon a bewildered people to meet the supreme test whether this was a nation destined to survive or to perish. And it will be remembered that Lincoln's party chose for its banner that earlier device--Republican--which Jefferson had made a sign of power. The "rail splitter" from Illinois united the nationalism of Hamilton with the democracy of Jefferson, and his appeal was clothed in the simple language of the people, not in the sonorous rhetoric which Webster learned in the schools diff --git a/js/hanbit-data-structures-and-algorithms-with-js/14/1-1.js b/js/hanbit-data-structures-and-algorithms-with-js/14/1-1.js new file mode 100644 index 0000000000..4413d745fa --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/14/1-1.js @@ -0,0 +1,48 @@ +// 14 고급 알고리즘 - 1 동적 프로그래밍 - 1 동적 프로그래밍 예제: 피보나치 숫자 계산 + +function recurFib(n) { + if (n<2) { + return n; + } else { + return recurFib(n-1) + recurFib(n-2); + } +} + +function dynFib(n) { + var val = []; + for (var i = 0; i <= n; ++i) { + val[i] = 0; + } + if (n == 1 || n == 2) { + return 1; + } else { + val[1] = 1; + val[2] = 2; + for (var i = 3; i <= n; ++i) { + val[i] = val[i-1] + val[i-2]; + } + return val[n-1]; + } +} + +var start = new Date().getTime(); +console.log(recurFib(10)); +var stop = new Date().getTime(); +console.log('recursive time - ' + (stop-start) + 'miliseconds'); + +start = new Date().getTime(); +console.log(dynFib(10)); +stop = new Date().getTime(); +console.log('dynamic programming time - ' + (stop-start) + 'miliseconds'); + +function iterFib(n) { + var last = 1; + var nextLast = 1; + var result = 1; + for (var i = 2; i < n; ++i) { + result = last + nextLast; + nextLast = last; + last = result; + } + return result; +} diff --git a/js/hanbit-data-structures-and-algorithms-with-js/14/1-2.js b/js/hanbit-data-structures-and-algorithms-with-js/14/1-2.js new file mode 100644 index 0000000000..d9a4c6a46a --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/14/1-2.js @@ -0,0 +1,41 @@ +// 14 고급 알고리즘 - 1 동적 프로그래밍 - 2 가장 긴 공통 문자열 찾기 + +function lcs(word1, word2) { + var max = 0; + var index = 0; + var lcsarr = new Array(word1.length + 1); + for (var i = 0; i < word1.length; ++i) { + lcsarr[i] = new Array(word2.length+1); + for (var j = 0; j <= word2.length+1; ++j) { + lcsarr[i][j] = 0; + } + } + + for (var i = 0; i <= word1.length; ++i) { + for (var j = 0; j <= word2.length; ++j) { + if (i == 0 || j == 0) { + lcsarr[i][j] = 0; + } else { + if (word1[i-1] == word2[j-1]) { + lcsarr[i][j] = lcsarr[i-1][j-1] + 1; + } else { + lcsarr[i][j] = 0; + } + } + + if (max < lcsarr[i][j]) { + max = lcsarr[i][j]; + index = i; + } + } + } + var str = ''; + if (max == 0) { + return ''; + } else { + for (var i = index-max; i <= max; ++i) { + str += word2[i]; + } + return str; + } +} diff --git a/js/hanbit-data-structures-and-algorithms-with-js/14/1-3.js b/js/hanbit-data-structures-and-algorithms-with-js/14/1-3.js new file mode 100644 index 0000000000..12cfb15b69 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/14/1-3.js @@ -0,0 +1,26 @@ +// 14 고급 알고리즘 - 1 동적 프로그래밍 - 3 배낭 문제: 재귀 해법 + +function max(a, b) { + return (a > b) ? a : b; +} + +function knapsack(capacity, size, value, n) { + if (n == 0 || capacity == 0) { + return 0; + } + if (size[n-1] > capacity) { + return knapsack(capacity, size, value, n-1); + } else { + return max( + value[n-1] + knapsack(capacity-size[n-1], size, value, n-1), + knapsack(capacity, size, value, n-1) + ); + } +} + +var value = [4,5,10,11,13]; +var size = [3,4,7,8,9]; +var capacity = 16; +var n = 5; + +console.log(knapsack(capacity, size, value, n)); // 23 diff --git a/js/hanbit-data-structures-and-algorithms-with-js/14/1-4.js b/js/hanbit-data-structures-and-algorithms-with-js/14/1-4.js new file mode 100644 index 0000000000..43de512fcb --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/14/1-4.js @@ -0,0 +1,44 @@ +// 14 고급 알고리즘 - 1 동적 프로그래밍 - 4 배낭 문제: 동적 프로그래밍 해법 + +function max(a,b) { + return (a>b) ? a : b; +} + +function dKnapsack(capacity, size, value, n) { + var K = []; + for (var i = 0; i <= capacity+1; i++) { + K[i] = []; + } + for (var i = 0; i <= n; i++) { + var result = ''; + for (var w = 0; w <= capacity; w++) { + if (i == 0 || w == 0) { + K[i][w] = 0; + } else if (size[i-1] <= w) { + K[i][w] = max(value[i-1] + K[i-1][w-size[i-1]], K[i-1][w]); + } else { + + K[i][w] = K[i-1][w]; + } + result += K[i][w] + ' '; + } + console.log(result); + } + return K[n][capacity]; +} + +var value = [4,5,10,11,13]; +var size = [3,4,7,8,9]; +var capacity = 16; +var n = 5; + +console.log(dKnapsack(capacity, size, value, n)); +/* +0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 +0 0 0 4 4 4 4 4 4 4 4 4 4 4 4 4 4 +0 0 0 4 5 5 5 9 9 9 9 9 9 9 9 9 9 +0 0 0 4 5 5 5 10 10 10 14 15 15 15 19 19 19 +0 0 0 4 5 5 5 10 11 11 14 15 16 16 19 21 21 +0 0 0 4 5 5 5 10 11 13 14 15 17 18 19 21 23 +23 +*/ diff --git a/js/hanbit-data-structures-and-algorithms-with-js/14/2-1.js b/js/hanbit-data-structures-and-algorithms-with-js/14/2-1.js new file mode 100644 index 0000000000..493b03eb7d --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/14/2-1.js @@ -0,0 +1,46 @@ +// 14 고급 알고리즘 - 2 탐욕 알고리즘 - 1 첫 번째 탐욕 알고리즘 예제: 동전 거스름돈 문제 + +function makeChange(origAmt, coins) { + var remainAmt = 0; + if (origAmt % .25 < origAmt) { + coins[3] = parseInt(origAmt / .25); + remainAmt = origAmt % .25; + origAmt = remainAmt; + } + if (origAmt & .1 < origAmt) { + coins[2] = parseInt(origAmt / .05); + remainAmt = origAmt % .05; + origAmt = remainAmt; + } + if (origAmt % .05 < origAmt) { + coins[1] = parseInt(origAmt / .05); + remainAmt = origAmt % .05; + origAmt = remainAmt; + } + coins[0] = parseInt(origAmt / .01); +} + +function showChange(coins) { + if (coins[3] > 0) { + console.log('Number of quarters - ' + coins[3] + ' - ' + coins[3] * .25); + } + if (coins[2] > 0) { + console.log('Number of dimes - ' + coins[2] + ' - ' + coins[2] * .10); + } + if (coins[1] > 0) { + console.log('Number of nickels - ' + coins[1] + ' - ' + coins[1] * .05); + } + if (coins[0] > 0) { + console.log('Number of penny - ' + coins[0] + ' - ' + coins[0] * .01); + } +} + +var origAmt = .63; +var coins = []; +makeChange(origAmt, coins); +showChange(coins); +/* +Number of quarters - 2 - 0.5 +Number of nickels - 2 - 0.1 +Number of penny - 3 - 0.03 +*/ diff --git a/js/hanbit-data-structures-and-algorithms-with-js/14/2-2.js b/js/hanbit-data-structures-and-algorithms-with-js/14/2-2.js new file mode 100644 index 0000000000..d219829c96 --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/14/2-2.js @@ -0,0 +1,25 @@ +// 14 고급 알고리즘 - 2 탐욕 알고리즘 - 2 탐욕 알고리즘으로 배낭 문제 해결하기 + +function ksack(values, weights, capacity) { + var load = 0; + var i = 0; + var w = 0; + while (load < capacity && i < 4) { + if (weights[i] <= (capacity-load)) { + w += values[i]; + load += weights[i]; + } else { + var r = (capacity-load)/weights[i]; + w += r * values[i]; + load += weights[i]; + } + ++i; + } + return w; +} + +var items = ['A', 'B', 'C', 'D']; +var values = [50, 140, 60, 60]; +var weights = [5, 20, 10, 12]; +var capacity = 30; +console.log(ksack(values, weights, capacity)); // 220 diff --git a/js/hanbit-data-structures-and-algorithms-with-js/14/quiz.js b/js/hanbit-data-structures-and-algorithms-with-js/14/quiz.js new file mode 100644 index 0000000000..a2c5df8c2c --- /dev/null +++ b/js/hanbit-data-structures-and-algorithms-with-js/14/quiz.js @@ -0,0 +1,5 @@ +/* +1. 무작위적인 방식으로 가장 긴 공통 문자열을 찾는 프로그램을 구현하시오. +2. 제약 조건을 바꾸면 결과가 어떻게 달라지는지 확인할 수 있게 사용자가 제약 조건을 바꿀 수 있는 가방 문제를 구현하시오. 예를 들어 사용자는 가방 용량, 물건 값, 물건 무게를 조절할 수 있다. 세 가지 조건 중 한 번에 한 가지만 바꿀 수 있도록 허용하는 것이 바람직하다. +3. 동전 거스름돈 기법을 탐욕 알고리즘으로 구현하시오. 단, 30센트의 거스름돈을 계산해야 하며 다임은 사용할 수 없다. 탐욕 알고리즘으로 구현한 프로그램 결과가 최상의 결과인가? +*/