chore(curriculum): Remove files in wrong format

This commit is contained in:
Bouncey
2018-10-04 14:37:37 +01:00
committed by Stuart Taylor
parent 61222b1fb6
commit 8f39bc1288
2947 changed files with 118541 additions and 212907 deletions

View File

@ -0,0 +1,94 @@
---
id: a3f503de51cf954ede28891d
title: Find the Symmetric Difference
challengeType: 5
---
## Description
<section id='description'>
Create a function that takes two or more arrays and returns an array of the <dfn>symmetric difference</dfn> (<code>&xutri;</code> or <code>&oplus;</code>) of the provided arrays.
Given two sets (for example set <code>A = {1, 2, 3}</code> and set <code>B = {2, 3, 4}</code>), the mathematical term "symmetric difference" of two sets is the set of elements which are in either of the two sets, but not in both (<code>A &xutri; B = C = {1, 4}</code>). For every additional symmetric difference you take (say on a set <code>D = {2, 3}</code>), you should get the set with elements which are in either of the two the sets but not both (<code>C &xutri; D = {1, 4} &xutri; {2, 3} = {1, 2, 3, 4}</code>). The resulting array must contain only unique values (<em>no duplicates</em>).
Remember to use <a href='http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514' target='_blank'>Read-Search-Ask</a> if you get stuck. Try to pair program. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>sym([1, 2, 3], [5, 2, 1, 4])</code> should return <code>[3, 4, 5]</code>.'
testString: 'assert.sameMembers(sym([1, 2, 3], [5, 2, 1, 4]), [3, 4, 5], ''<code>sym([1, 2, 3], [5, 2, 1, 4])</code> should return <code>[3, 4, 5]</code>.'');'
- text: '<code>sym([1, 2, 3], [5, 2, 1, 4])</code> should contain only three elements.'
testString: 'assert.equal(sym([1, 2, 3], [5, 2, 1, 4]).length, 3, ''<code>sym([1, 2, 3], [5, 2, 1, 4])</code> should contain only three elements.'');'
- text: '<code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> should return <code>[3, 4, 5]</code>.'
testString: 'assert.sameMembers(sym([1, 2, 3, 3], [5, 2, 1, 4]), [3, 4, 5], ''<code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> should return <code>[3, 4, 5]</code>.'');'
- text: '<code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> should contain only three elements.'
testString: 'assert.equal(sym([1, 2, 3, 3], [5, 2, 1, 4]).length, 3, ''<code>sym([1, 2, 3, 3], [5, 2, 1, 4])</code> should contain only three elements.'');'
- text: '<code>sym([1, 2, 3], [5, 2, 1, 4, 5])</code> should return <code>[3, 4, 5]</code>.'
testString: 'assert.sameMembers(sym([1, 2, 3], [5, 2, 1, 4, 5]), [3, 4, 5], ''<code>sym([1, 2, 3], [5, 2, 1, 4, 5])</code> should return <code>[3, 4, 5]</code>.'');'
- text: '<code>sym([1, 2, 3], [5, 2, 1, 4, 5])</code> should contain only three elements.'
testString: 'assert.equal(sym([1, 2, 3], [5, 2, 1, 4, 5]).length, 3, ''<code>sym([1, 2, 3], [5, 2, 1, 4, 5])</code> should contain only three elements.'');'
- text: '<code>sym([1, 2, 5], [2, 3, 5], [3, 4, 5])</code> should return <code>[1, 4, 5]</code>'
testString: 'assert.sameMembers(sym([1, 2, 5], [2, 3, 5], [3, 4, 5]), [1, 4, 5], ''<code>sym([1, 2, 5], [2, 3, 5], [3, 4, 5])</code> should return <code>[1, 4, 5]</code>'');'
- text: '<code>sym([1, 2, 5], [2, 3, 5], [3, 4, 5])</code> should contain only three elements.'
testString: 'assert.equal(sym([1, 2, 5], [2, 3, 5], [3, 4, 5]).length, 3, ''<code>sym([1, 2, 5], [2, 3, 5], [3, 4, 5])</code> should contain only three elements.'');'
- text: '<code>sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])</code> should return <code>[1, 4, 5]</code>.'
testString: 'assert.sameMembers(sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]), [1, 4, 5], ''<code>sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])</code> should return <code>[1, 4, 5]</code>.'');'
- text: '<code>sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])</code> should contain only three elements.'
testString: 'assert.equal(sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]).length, 3, ''<code>sym([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5])</code> should contain only three elements.'');'
- text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> should return <code>[2, 3, 4, 6, 7]</code>.'
testString: 'assert.sameMembers(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]), [2, 3, 4, 6, 7], ''<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> should return <code>[2, 3, 4, 6, 7]</code>.'');'
- text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> should contain only five elements.'
testString: 'assert.equal(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]).length, 5, ''<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3])</code> should contain only five elements.'');'
- text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> should return <code>[1, 2, 4, 5, 6, 7, 8, 9]</code>.'
testString: 'assert.sameMembers(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1]), [1, 2, 4, 5, 6, 7, 8, 9], ''<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> should return <code>[1, 2, 4, 5, 6, 7, 8, 9]</code>.'');'
- text: '<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> should contain only eight elements.'
testString: 'assert.equal(sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1]).length, 8, ''<code>sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3], [5, 3, 9, 8], [1])</code> should contain only eight elements.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function sym(args) {
return args;
}
sym([1, 2, 3], [5, 2, 1, 4]);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function sym() {
var arrays = [].slice.call(arguments);
return arrays.reduce(function (symDiff, arr) {
return symDiff.concat(arr).filter(function (val, idx, theArr) {
return theArr.indexOf(val) === idx
&& (symDiff.indexOf(val) === -1 || arr.indexOf(val) === -1);
});
});
}
sym([1, 2, 3], [5, 2, 1, 4]);
```
</section>

View File

@ -0,0 +1,76 @@
---
id: 8d5123c8c441eddfaeb5bdef
title: Implement Bubble Sort
challengeType: 1
---
## Description
<section id='description'>
This is the first of several challenges on sorting algorithms. Given an array of unsorted items, we want to be able to return a sorted array. We will see several different methods to do this and learn some tradeoffs between these different approaches. While most modern languages have built-in sorting methods for operations like this, it is still important to understand some of the common basic approaches and learn how they can be implemented.
Here we will see bubble sort. The bubble sort method starts at the beginning of an unsorted array and 'bubbles up' unsorted values towards the end, iterating through the array until it is completely sorted. It does this by comparing adjacent items and swapping them if they are out of order. The method continues looping through the array until no swaps occur at which point the array is sorted.
This method requires multiple iterations through the array and for average and worst cases has quadratic time complexity. While simple, it is usually impractical in most situations.
<strong>Instructions:</strong> Write a function <code>bubbleSort</code> which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest.
<strong>Note:</strong><br>We are calling this function from behind the scenes; the test array we are using is commented out in the editor. Try logging <code>array</code> to see your sorting algorithm in action!
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>bubbleSort</code> is a function.
testString: 'assert(typeof bubbleSort == ''function'', ''<code>bubbleSort</code> is a function.'');'
- text: <code>bubbleSort</code> returns a sorted array (least to greatest).
testString: 'assert(isSorted(bubbleSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])), ''<code>bubbleSort</code> returns a sorted array (least to greatest).'');'
- text: <code>bubbleSort</code> returns an array that is unchanged except for order.
testString: 'assert.sameMembers(bubbleSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]), [1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92], ''<code>bubbleSort</code> returns an array that is unchanged except for order.'');'
- text: <code>bubbleSort</code> should not use the built-in <code>.sort()</code> method.
testString: 'assert.strictEqual(code.search(/\.sort\(/), -1, ''<code>bubbleSort</code> should not use the built-in <code>.sort()</code> method.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function bubbleSort(array) {
// change code below this line
// change code above this line
return array;
}
// test array:
// [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,74 @@
---
id: 587d8259367417b2b2512c86
title: Implement Insertion Sort
challengeType: 1
---
## Description
<section id='description'>
The next sorting method we'll look at is insertion sort. This method works by building up a sorted array at the beginning of the list. It begins the sorted array with the first element. Then it inspects the next element and swaps it backwards into the sorted array until it is in sorted position. It continues iterating through the list and swapping new items backwards into the sorted portion until it reaches the end. This algorithm has quadratic time complexity in the average and worst cases.
<strong>Instructions:</strong> Write a function <code>insertionSort</code> which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest.
<strong>Note:</strong><br>We are calling this function from behind the scenes; the test array we are using is commented out in the editor. Try logging <code>array</code> to see your sorting algorithm in action!
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>insertionSort</code> is a function.
testString: 'assert(typeof insertionSort == ''function'', ''<code>insertionSort</code> is a function.'');'
- text: <code>insertionSort</code> returns a sorted array (least to greatest).
testString: 'assert(isSorted(insertionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])), ''<code>insertionSort</code> returns a sorted array (least to greatest).'');'
- text: <code>insertionSort</code> returns an array that is unchanged except for order.
testString: 'assert.sameMembers(insertionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]), [1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92], ''<code>insertionSort</code> returns an array that is unchanged except for order.'');'
- text: <code>insertionSort</code> should not use the built-in <code>.sort()</code> method.
testString: 'assert.strictEqual(code.search(/\.sort\(/), -1, ''<code>insertionSort</code> should not use the built-in <code>.sort()</code> method.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function insertionSort(array) {
// change code below this line
// change code above this line
return array;
}
// test array:
// [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,78 @@
---
id: 587d825c367417b2b2512c8f
title: Implement Merge Sort
challengeType: 1
---
## Description
<section id='description'>
Another intermediate sorting algorithm that is very common is merge sort. Like quick sort, merge sort also uses a divide-and-conquer, recursive methodology to sort an array. It takes advantage of the fact that it is relatively easy to sort two arrays as long as each is sorted in the first place. But we'll start with only one array as input, so how do we get to two sorted arrays from that? Well, we can recursively divide the original input in two until we reach the base case of an array with one item. A single-item array is naturally sorted, so then we can start combining. This combination will unwind the recursive calls that split the original array, eventually producing a final sorted array of all the elements. The steps of merge sort, then, are:
<strong>1)</strong> Recursively split the input array in half until a sub-array with only one element is produced.
<strong>2)</strong> Merge each sorted sub-array together to produce the final sorted array.
Merge sort is an efficient sorting method, with time complexity of <i>O(nlog(n))</i>. This algorithm is popular because it is performant and relatively easy to implement.
As an aside, this will be the last sorting algorithm we cover here. However, later in the section on tree data structures we will describe heap sort, another efficient sorting method that requires a binary heap in its implementation.
<strong>Instructions:</strong> Write a function <code>mergeSort</code> which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest. A good way to implement this is to write one function, for instance <code>merge</code>, which is responsible for merging two sorted arrays, and another function, for instance <code>mergeSort</code>, which is responsible for the recursion that produces single-item arrays to feed into merge. Good luck!
<strong>Note:</strong><br>We are calling this function from behind the scenes; the test array we are using is commented out in the editor. Try logging <code>array</code> to see your sorting algorithm in action!
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>mergeSort</code> is a function.
testString: 'assert(typeof mergeSort == ''function'', ''<code>mergeSort</code> is a function.'');'
- text: <code>mergeSort</code> returns a sorted array (least to greatest).
testString: 'assert(isSorted(mergeSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])), ''<code>mergeSort</code> returns a sorted array (least to greatest).'');'
- text: <code>mergeSort</code> returns an array that is unchanged except for order.
testString: 'assert.sameMembers(mergeSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]), [1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92], ''<code>mergeSort</code> returns an array that is unchanged except for order.'');'
- text: <code>mergeSort</code> should not use the built-in <code>.sort()</code> method.
testString: 'assert.strictEqual(code.search(/\.sort\(/), -1, ''<code>mergeSort</code> should not use the built-in <code>.sort()</code> method.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function mergeSort(array) {
// change code below this line
// change code above this line
return array;
}
// test array:
// [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,75 @@
---
id: 587d825a367417b2b2512c89
title: Implement Quick Sort
challengeType: 1
---
## Description
<section id='description'>
Here we will move on to an intermediate sorting algorithm: quick sort. Quick sort is an efficient, recursive divide-and-conquer approach to sorting an array. In this method, a pivot value is chosen in the original array. The array is then partitioned into two subarrays of values less than and greater than the pivot value. We then combine the result of recursively calling the quick sort algorithm on both sub-arrays. This continues until the base case of an empty or single-item array is reached, which we return. The unwinding of the recursive calls return us the sorted array.
Quick sort is a very efficient sorting method, providing <i>O(nlog(n))</i> performance on average. It is also relatively easy to implement. These attributes make it a popular and useful sorting method.
<strong>Instructions:</strong> Write a function <code>quickSort</code> which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest. While the choice of the pivot value is important, any pivot will do for our purposes here. For simplicity, the first or last element could be used.
<strong>Note:</strong><br>We are calling this function from behind the scenes; the test array we are using is commented out in the editor. Try logging <code>array</code> to see your sorting algorithm in action!
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>quickSort</code> is a function.
testString: 'assert(typeof quickSort == ''function'', ''<code>quickSort</code> is a function.'');'
- text: <code>quickSort</code> returns a sorted array (least to greatest).
testString: 'assert(isSorted(quickSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])), ''<code>quickSort</code> returns a sorted array (least to greatest).'');'
- text: <code>quickSort</code> returns an array that is unchanged except for order.
testString: 'assert.sameMembers(quickSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]), [1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92], ''<code>quickSort</code> returns an array that is unchanged except for order.'');'
- text: <code>quickSort</code> should not use the built-in <code>.sort()</code> method.
testString: 'assert.strictEqual(code.search(/\.sort\(/), -1, ''<code>quickSort</code> should not use the built-in <code>.sort()</code> method.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function quickSort(array) {
// change code below this line
// change code above this line
return array;
}
// test array:
// [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,74 @@
---
id: 587d8259367417b2b2512c85
title: Implement Selection Sort
challengeType: 1
---
## Description
<section id='description'>
Here we will implement selection sort. Selection sort works by selecting the minimum value in a list and swapping it with the first value in the list. It then starts at the second position, selects the smallest value in the remaining list, and swaps it with the second element. It continues iterating through the list and swapping elements until it reaches the end of the list. Now the list is sorted. Selection sort has quadratic time complexity in all cases.
<strong>Instructions</strong>: Write a function <code>selectionSort</code> which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest.
<strong>Note:</strong><br>We are calling this function from behind the scenes; the test array we are using is commented out in the editor. Try logging <code>array</code> to see your sorting algorithm in action!
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>selectionSort</code> is a function.
testString: 'assert(typeof selectionSort == ''function'', ''<code>selectionSort</code> is a function.'');'
- text: <code>selectionSort</code> returns a sorted array (least to greatest).
testString: 'assert(isSorted(selectionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])), ''<code>selectionSort</code> returns a sorted array (least to greatest).'');'
- text: <code>selectionSort</code> returns an array that is unchanged except for order.
testString: 'assert.sameMembers(selectionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]), [1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92], ''<code>selectionSort</code> returns an array that is unchanged except for order.'');'
- text: <code>selectionSort</code> should not use the built-in <code>.sort()</code> method.
testString: 'assert.strictEqual(code.search(/\.sort\(/), -1, ''<code>selectionSort</code> should not use the built-in <code>.sort()</code> method.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function selectionSort(array) {
// change code below this line
// change code above this line
return array;
}
// test array:
// [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,121 @@
---
id: a56138aff60341a09ed6c480
title: Inventory Update
challengeType: 5
---
## Description
<section id='description'>
Compare and update the inventory stored in a 2D array against a second 2D array of a fresh delivery. Update the current existing inventory item quantities (in <code>arr1</code>). If an item cannot be found, add the new item and quantity into the inventory array. The returned inventory array should be in alphabetical order by item.
Remember to use <a href='http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514' target='_blank'>Read-Search-Ask</a> if you get stuck. Try to pair program. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The function <code>updateInventory</code> should return an array.
testString: 'assert.isArray(updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]), ''The function <code>updateInventory</code> should return an array.'');'
- text: '<code>updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])</code> should return an array with a length of 6.'
testString: 'assert.equal(updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]).length, 6, ''<code>updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])</code> should return an array with a length of 6.'');'
- text: '<code>updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])</code> should return <code>[[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]</code>.'
testString: 'assert.deepEqual(updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]), [[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]], ''<code>updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])</code> should return <code>[[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]</code>.'');'
- text: '<code>updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [])</code> should return <code>[[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]]</code>.'
testString: 'assert.deepEqual(updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], []), [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], ''<code>updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [])</code> should return <code>[[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]]</code>.'');'
- text: '<code>updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])</code> should return <code>[[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]]</code>.'
testString: 'assert.deepEqual(updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]), [[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]], ''<code>updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])</code> should return <code>[[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]]</code>.'');'
- text: '<code>updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]])</code> should return <code>[[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]]</code>.'
testString: 'assert.deepEqual(updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]]), [[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]], ''<code>updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]])</code> should return <code>[[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]]</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function updateInventory(arr1, arr2) {
// All inventory must be accounted for or you're fired!
return arr1;
}
// Example inventory lists
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"]
];
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
updateInventory(curInv, newInv);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function updateInventory(arr1, arr2) {
arr2.forEach(function(item) {
createOrUpdate(arr1, item);
});
// All inventory must be accounted for or you're fired!
return arr1;
}
function createOrUpdate(arr1, item) {
var index = -1;
while (++index < arr1.length) {
if (arr1[index][1] === item[1]) {
arr1[index][0] += item[0];
return;
}
if (arr1[index][1] > item[1]) {
break;
}
}
arr1.splice(index, 0, item);
}
// Example inventory lists
var curInv = [
[21, 'Bowling Ball'],
[2, 'Dirty Sock'],
[1, 'Hair Pin'],
[5, 'Microphone']
];
var newInv = [
[2, 'Hair Pin'],
[3, 'Half-Eaten Apple'],
[67, 'Bowling Ball'],
[7, 'Toothpaste']
];
updateInventory(curInv, newInv);
```
</section>

View File

@ -0,0 +1,50 @@
{
"name": "Algorithms",
"dashedName": "algorithms",
"order": 1,
"time": "",
"template": "",
"required": [],
"superBlock": "coding-interview-prep",
"superOrder": 8,
"challengeOrder": [
[
"a3f503de51cf954ede28891d",
"Find the Symmetric Difference"
],
[
"a56138aff60341a09ed6c480",
"Inventory Update"
],
[
"a7bf700cd123b9a54eef01d5",
"No Repeats Please"
],
[
"a3f503de51cfab748ff001aa",
"Pairwise"
],
[
"8d5123c8c441eddfaeb5bdef",
"Implement Bubble Sort"
],
[
"587d8259367417b2b2512c85",
"Implement Selection Sort"
],
[
"587d8259367417b2b2512c86",
"Implement Insertion Sort"
],
[
"587d825a367417b2b2512c89",
"Implement Quick Sort"
],
[
"587d825c367417b2b2512c8f",
"Implement Merge Sort"
]
],
"helpRoom": "HelpJavaScript",
"fileName": "08-coding-interview-prep/algorithms.json"
}

View File

@ -0,0 +1,110 @@
---
id: a7bf700cd123b9a54eef01d5
title: No Repeats Please
challengeType: 5
---
## Description
<section id='description'>
Return the number of total permutations of the provided string that don't have repeated consecutive letters. Assume that all characters in the provided string are each unique.
For example, <code>aab</code> should return 2 because it has 6 total permutations (<code>aab</code>, <code>aab</code>, <code>aba</code>, <code>aba</code>, <code>baa</code>, <code>baa</code>), but only 2 of them (<code>aba</code> and <code>aba</code>) don't have the same letter (in this case <code>a</code>) repeating.
Remember to use <a href='http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514' target='_blank'>Read-Search-Ask</a> if you get stuck. Try to pair program. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>permAlone("aab")</code> should return a number.
testString: 'assert.isNumber(permAlone(''aab''), ''<code>permAlone("aab")</code> should return a number.'');'
- text: <code>permAlone("aab")</code> should return 2.
testString: 'assert.strictEqual(permAlone(''aab''), 2, ''<code>permAlone("aab")</code> should return 2.'');'
- text: <code>permAlone("aaa")</code> should return 0.
testString: 'assert.strictEqual(permAlone(''aaa''), 0, ''<code>permAlone("aaa")</code> should return 0.'');'
- text: <code>permAlone("aabb")</code> should return 8.
testString: 'assert.strictEqual(permAlone(''aabb''), 8, ''<code>permAlone("aabb")</code> should return 8.'');'
- text: <code>permAlone("abcdefa")</code> should return 3600.
testString: 'assert.strictEqual(permAlone(''abcdefa''), 3600, ''<code>permAlone("abcdefa")</code> should return 3600.'');'
- text: <code>permAlone("abfdefa")</code> should return 2640.
testString: 'assert.strictEqual(permAlone(''abfdefa''), 2640, ''<code>permAlone("abfdefa")</code> should return 2640.'');'
- text: <code>permAlone("zzzzzzzz")</code> should return 0.
testString: 'assert.strictEqual(permAlone(''zzzzzzzz''), 0, ''<code>permAlone("zzzzzzzz")</code> should return 0.'');'
- text: <code>permAlone("a")</code> should return 1.
testString: 'assert.strictEqual(permAlone(''a''), 1, ''<code>permAlone("a")</code> should return 1.'');'
- text: <code>permAlone("aaab")</code> should return 0.
testString: 'assert.strictEqual(permAlone(''aaab''), 0, ''<code>permAlone("aaab")</code> should return 0.'');'
- text: <code>permAlone("aaabb")</code> should return 12.
testString: 'assert.strictEqual(permAlone(''aaabb''), 12, ''<code>permAlone("aaabb")</code> should return 12.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function permAlone(str) {
return str;
}
permAlone('aab');
```
</div>
</section>
## Solution
<section id='solution'>
```js
function permAlone(str) {
return permutor(str).filter(function(perm) {
return !perm.match(/(.)\1/g);
}).length;
}
function permutor(str) {
// http://staff.roguecc.edu/JMiller/JavaScript/permute.html
//permArr: Global array which holds the list of permutations
//usedChars: Global utility array which holds a list of "currently-in-use" characters
var permArr = [], usedChars = [];
function permute(input) {
//convert input into a char array (one element for each character)
var i, ch, chars = input.split("");
for (i = 0; i < chars.length; i++) {
//get and remove character at index "i" from char array
ch = chars.splice(i, 1);
//add removed character to the end of used characters
usedChars.push(ch);
//when there are no more characters left in char array to add, add used chars to list of permutations
if (chars.length === 0) permArr[permArr.length] = usedChars.join("");
//send characters (minus the removed one from above) from char array to be permuted
permute(chars.join(""));
//add removed character back into char array in original position
chars.splice(i, 0, ch);
//remove the last character used off the end of used characters array
usedChars.pop();
}
}
permute(str);
return permArr;
}
permAlone('aab');
```
</section>

View File

@ -0,0 +1,88 @@
---
id: a3f503de51cfab748ff001aa
title: Pairwise
challengeType: 5
---
## Description
<section id='description'>
Given an array <code>arr</code>, find element pairs whose sum equal the second argument <code>arg</code> and return the sum of their indices.
You may use multiple pairs that have the same numeric elements but different indices. Each pair should use the lowest possible available indices. Once an element has been used it cannot be reused to pair with another element. For instance, <code>pairwise([1, 1, 2], 3)</code> creates a pair <code>[2, 1]</code> using the 1 at indice 0 rather than the 1 at indice 1, because 0+2 < 1+2.
For example <code>pairwise([7, 9, 11, 13, 15], 20)</code> returns <code>6</code>. The pairs that sum to 20 are <code>[7, 13]</code> and <code>[9, 11]</code>. We can then write out the array with their indices and values.
<table class="table"><tr><th><strong>Index</strong></th><th>0</th><th>1</th><th>2</th><th>3</th><th>4</th></tr><tr><td>Value</td><td>7</td><td>9</td><td>11</td><td>13</td><td>15</td></tr></table>
Below we'll take their corresponding indices and add them.
7 + 13 = 20 &#8594; Indices 0 + 3 = 3<br>9 + 11 = 20 &#8594; Indices 1 + 2 = 3<br>3 + 3 = 6 &#8594 Return <code>6</code>
Remember to use <a href='http://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/19514' target='_blank'>Read-Search-Ask</a> if you get stuck. Try to pair program. Write your own code.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>pairwise([1, 4, 2, 3, 0, 5], 7)</code> should return 11.'
testString: 'assert.deepEqual(pairwise([1, 4, 2, 3, 0, 5], 7), 11, ''<code>pairwise([1, 4, 2, 3, 0, 5], 7)</code> should return 11.'');'
- text: '<code>pairwise([1, 3, 2, 4], 4)</code> should return 1.'
testString: 'assert.deepEqual(pairwise([1, 3, 2, 4], 4), 1, ''<code>pairwise([1, 3, 2, 4], 4)</code> should return 1.'');'
- text: '<code>pairwise([1, 1, 1], 2)</code> should return 1.'
testString: 'assert.deepEqual(pairwise([1, 1, 1], 2), 1, ''<code>pairwise([1, 1, 1], 2)</code> should return 1.'');'
- text: '<code>pairwise([0, 0, 0, 0, 1, 1], 1)</code> should return 10.'
testString: 'assert.deepEqual(pairwise([0, 0, 0, 0, 1, 1], 1), 10, ''<code>pairwise([0, 0, 0, 0, 1, 1], 1)</code> should return 10.'');'
- text: '<code>pairwise([], 100)</code> should return 0.'
testString: 'assert.deepEqual(pairwise([], 100), 0, ''<code>pairwise([], 100)</code> should return 0.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function pairwise(arr, arg) {
return arg;
}
pairwise([1,4,2,3,0,5], 7);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function pairwise(arr, arg) {
var sum = 0;
arr.forEach(function(e, i, a) {
if (e != null) {
var diff = arg-e;
a[i] = null;
var dix = a.indexOf(diff);
if (dix !== -1) {
sum += dix;
sum += i;
a[dix] = null;
}
}
});
return sum;
}
pairwise([1,4,2,3,0,5], 7);
```
</section>

View File

@ -0,0 +1,113 @@
---
id: 587d8257367417b2b2512c7b
title: Add a New Element to a Binary Search Tree
challengeType: 1
---
## Description
<section id='description'>
Now that we have an idea of the basics lets write a more complex method.
In this challenge, we will create a method to add new values to our binary search tree. The method should be called <code>add</code> and it should accept an integer value to add to the tree. Take care to maintain the invariant of a binary search tree: the value in each left child should be less than or equal to the parent value, and the value in each right child should be greater than or equal to the parent value. Here, let's make it so our tree cannot hold duplicate values. If we try to add a value that already exists, the method should return <code>null</code>. Otherwise, if the addition is successful, <code>undefined</code> should be returned.
Hint: trees are naturally recursive data structures!
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The <code>BinarySearchTree</code> data structure exists.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() }; return (typeof test == ''object'')})(), ''The <code>BinarySearchTree</code> data structure exists.'');'
- text: The binary search tree has a method called <code>add</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.add == ''function'')})(), ''The binary search tree has a method called <code>add</code>.'');'
- text: The add method adds elements according to the binary search tree rules.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.add !== ''function'') { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); const expectedResult = [ 1, 4, 7, 8, 34, 45, 73, 87 ]; const result = test.inOrder(); return (expectedResult.toString() === result.toString()); })(), ''The add method adds elements according to the binary search tree rules.'');'
- text: Adding an element that already exists returns <code>null</code>
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.add !== ''function'') { return false; }; test.add(4); return test.add(4) == null; })(), ''Adding an element that already exists returns <code>null</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
this.add = function (element) {
let current = this.root;
if (!current) {
this.root = new Node(element)
return;
} else {
const searchTree = function (current) {
if (current.value > element) {
if (current.left) { //si existe
return searchTree(current.left)
} else {
current.left = new Node(element);
return;
}
} else if (current.value < element) {
if (current.right) {
return searchTree(current.right)
} else {
current.right = new Node(element)
return;
}
} else {
return null;
}
}
return searchTree(current);
}
}
}
```
</section>

View File

@ -0,0 +1,98 @@
---
id: 587d8252367417b2b2512c67
title: Add Elements at a Specific Index in a Linked List
challengeType: 1
---
## Description
<section id='description'>
Let's create a addAt(index,element) method that adds an element at a given index.
Just like how we remove elements at a given index, we need to keep track of the currentIndex as we traverse the linked list. When the currentIndex matches the given index, we would need to reassign the previous node's next property to reference the new added node. And the new node should reference the next node in the currentIndex.
Returning to the conga line example, a new person wants to join the line, but he wants to join in the middle. You are in the middle of the line, so you take your hands off of the person ahead of you. The new person walks over and puts his hands on the person you once had hands on, and you now have your hands on the new person.
Instructions
Create an addAt(index,element) method that adds an element at a given index. Return false if an element was unable to be added.
Note
Remember to check if the given index is a negative or is longer than the length of the linked list.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>addAt</code> method should reassign <code>head</code> to the new node when the given index is 0.
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); test.add(''dog''); test.addAt(0,''cat''); return test.head().element === ''cat''}()), ''Your <code>addAt</code> method should reassign <code>head</code> to the new node when the given index is 0.'');'
- text: Your <code>addAt</code> method should increase the length of the linked list by one for each new node added to the linked list.
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); test.add(''dog''); test.addAt(0,''cat''); return test.size() === 3}()), ''Your <code>addAt</code> method should increase the length of the linked list by one for each new node added to the linked list.'');'
- text: Your <code>addAt</code> method should return <code>false</code> if a node was unable to be added.
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); test.add(''dog''); return (test.addAt(4,''cat'') === false); }()), ''Your <code>addAt</code> method should return <code>false</code> if a node was unable to be added.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element){
this.element = element;
this.next = null;
};
this.size = function(){
return length;
};
this.head = function(){
return head;
};
this.add = function(element){
var node = new Node(element);
if(head === null){
head = node;
} else {
currentNode = head;
while(currentNode.next){
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
// Only change code below this line
// Only change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,69 @@
---
id: 587d8256367417b2b2512c77
title: Adjacency List
challengeType: 1
---
## Description
<section id='description'>
Graphs can be represented in different ways. Here we describe one way, which is called an <dfn>adjacency list</dfn>.
An adjacency list is essentially a bulleted list where the left side is the node and the right side lists all the other nodes it's connected to. Below is a representation of an adjacency list.
<blockquote>Node1: Node2, Node3<br>Node2: Node1<br>Node3: Node1</blockquote>
Above is an undirected graph because <code>Node1</code> is connected to <code>Node2</code> and <code>Node3</code>, and that information is consistent with the connections <code>Node2</code> and <code>Node3</code> show. An adjacency list for a directed graph would mean each row of the list shows direction. If the above was directed, then <code>Node2: Node1</code> would mean there the directed edge is pointing from <code>Node2</code> towards <code>Node1</code>.
We can represent the undirected graph above as an adjacency list by putting it within a JavaScript object.
<blockquote>var undirectedG = {<br> Node1: ["Node2", "Node3"],<br> Node2: ["Node1"],<br> Node3: ["Node1"]<br>};</blockquote>
This can also be more simply represented as an array where the nodes just have numbers rather than string labels.
<blockquote>var undirectedGArr = [<br> [1, 2], # Node1<br> [0], # Node2<br> [0] # Node3<br>];</blockquote>
</section>
## Instructions
<section id='instructions'>
Create a social network as an undirected graph with 4 nodes/people named <code>James</code>, <code>Jill</code>, <code>Jenny</code>, and <code>Jeff</code>. There are edges/relationships between James and Jeff, Jill and Jenny, and Jeff and Jenny.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>undirectedAdjList</code> should only contain four nodes.
testString: 'assert(Object.keys(undirectedAdjList).length === 4, ''<code>undirectedAdjList</code> should only contain four nodes.'');'
- text: There should be an edge between <code>Jeff</code> and <code>James</code>.
testString: 'assert(undirectedAdjList.James.indexOf("Jeff") !== -1 && undirectedAdjList.Jeff.indexOf("James") !== -1, ''There should be an edge between <code>Jeff</code> and <code>James</code>.'');'
- text: There should be an edge between <code>Jill</code> and <code>Jenny</code>.
testString: 'assert(undirectedAdjList.Jill.indexOf("Jenny") !== -1 && undirectedAdjList.Jill.indexOf("Jenny") !== -1, ''There should be an edge between <code>Jill</code> and <code>Jenny</code>.'');'
- text: There should be an edge between <code>Jeff</code> and <code>Jenny</code>.
testString: 'assert(undirectedAdjList.Jeff.indexOf("Jenny") !== -1 && undirectedAdjList.Jenny.indexOf("Jeff") !== -1, ''There should be an edge between <code>Jeff</code> and <code>Jenny</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var undirectedAdjList = {
};
```
</div>
</section>
## Solution
<section id='solution'>
```js
var undirectedAdjList = {
"James": ["Jeff"],"Jill": ["Jenny"],"Jenny": ["Jill", "Jeff"],
"Jeff": ["James", "Jenny"]
};
```
</section>

View File

@ -0,0 +1,70 @@
---
id: 587d8256367417b2b2512c78
title: Adjacency Matrix
challengeType: 1
---
## Description
<section id='description'>
Another way to represent a graph is to put it in an <dfn>adjacency matrix</dfn>.
An <dfn>adjacency matrix</dfn> is a two-dimensional (2D) array where each nested array has the same number of elements as the outer array. In other words, it is a matrix or grid of numbers, where the numbers represent the edges. Zeros mean there is no edge or relationship.
<blockquote> 1 2 3<br> ------<br>1 | 0 1 1<br>2 | 1 0 0<br>3 | 1 0 0</blockquote>
Above is a very simple, undirected graph where you have three nodes, where the first node is connected to the second and third node. <strong>Note</strong>: The numbers to the top and left of the matrix are just labels for the nodes.
Below is a JavaScript implementation of the same thing.
<blockquote>var adjMat = [<br> [0, 1, 1],<br> [1, 0, 0],<br> [1, 0, 0]<br>];</blockquote>
Unlike an adjacency list, each "row" of the matrix has to have the same number of elements as nodes in the graph. Here we have a three by three matrix, which means we have three nodes in our graph.
A directed graph would look similar. Below is a graph where the first node has an edge pointing toward the second node, and then the second node has an edge pointing to the third node.
<blockquote>var adjMatDirected = [<br> [0, 1, 0],<br> [0, 0, 1],<br> [0, 0, 0]<br>];</blockquote>
Graphs can also have <dfn>weights</dfn> on their edges. So far, we have <dfn>unweighted</dfn> edges where just the presence and lack of edge is binary (<code>0</code> or <code>1</code>). You can have different weights depending on your application.
</section>
## Instructions
<section id='instructions'>
Create an adjacency matrix of an undirected graph with five nodes. This matrix should be in a multi-dimensional array. These five nodes have relationships between the first and fourth node, the first and third node, the third and fifth node, and the fourth and fifth node. All edge weights are one.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>undirectedAdjList</code> should only contain five nodes.
testString: 'assert((adjMatUndirected.length === 5) && adjMatUndirected.map(function(x) { return x.length === 5 }).reduce(function(a, b) { return a && b }) , ''<code>undirectedAdjList</code> should only contain five nodes.'');'
- text: There should be an edge between the first and fourth node.
testString: 'assert((adjMatUndirected[0][3] === 1) && (adjMatUndirected[3][0] === 1), ''There should be an edge between the first and fourth node.'');'
- text: There should be an edge between the first and third node.
testString: 'assert((adjMatUndirected[0][2] === 1) && (adjMatUndirected[2][0] === 1), ''There should be an edge between the first and third node.'');'
- text: There should be an edge between the third and fifth node.
testString: 'assert((adjMatUndirected[2][4] === 1) && (adjMatUndirected[4][2] === 1), ''There should be an edge between the third and fifth node.'');'
- text: There should be an edge between the fourth and fifth node.
testString: 'assert((adjMatUndirected[3][4] === 1) && (adjMatUndirected[4][3] === 1), ''There should be an edge between the fourth and fifth node.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var adjMatUndirected = [
];
```
</div>
</section>
## Solution
<section id='solution'>
```js
var adjMatUndirected = [[0, 0, 1, 1, 0],[0, 0, 0, 0, 0],[1, 0, 0, 0, 1],[1, 0, 0, 0, 1],[0, 0, 1, 1, 0]];
```
</section>

View File

@ -0,0 +1,118 @@
---
id: 587d825c367417b2b2512c90
title: Breadth-First Search
challengeType: 1
---
## Description
<section id='description'>
So far, we've learned different ways of creating representations of graphs. What now? One natural question to have is what are the distances between any two nodes in the graph? Enter <dfn>graph traversal algorithms</dfn>.
<dfn>Traversal algorithms</dfn> are algorithms to traverse or visit nodes in a graph. One type of traversal algorithm is the breadth-first search algorithm.
This algorithm starts at one node, first visits all its neighbors that are one edge away, then goes on to visiting each of their neighbors.
Visually, this is what the algorithm is doing.
<img class='img-responsive' src='https://camo.githubusercontent.com/2f57e6239884a1a03402912f13c49555dec76d06/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f342f34362f416e696d617465645f4246532e676966'>
To implement this algorithm, you'll need to input a graph structure and a node you want to start at.
First, you'll want to be aware of the distances from the start node. This you'll want to start all your distances initially some large number, like <code>Infinity</code>. This gives a reference for the case where a node may not be reachable from your start node.
Next, you'll want to go from the start node to its neighbors. These neighbors are one edge away and at this point you should add one unit of distance to the distances you're keeping track of.
Last, an important data structure that will help implement the breadth-first search algorithm is the queue. This is an array where you can add elements to one end and remove elements from the other end. This is also known as a <dfn>FIFO</dfn> or <dfn>First-In-First-Out</dfn> data structure.
</section>
## Instructions
<section id='instructions'>
Write a function <code>bfs()</code> that takes an adjacency matrix graph (a two-dimensional array) and a node label root as parameters. The node label will just be the integer value of the node between <code>0</code> and <code>n - 1</code>, where <code>n</code> is the total number of nodes in the graph.
Your function will output a JavaScript object key-value pairs with the node and its distance from the root. If the node could not be reached, it should have a distance of <code>Infinity</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>1</code> should return <code>{0: 1, 1: 0, 2: 1, 3: 2}</code>'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]; var results = bfs(graph, 1); return isEquivalent(results, {0: 1, 1: 0, 2: 1, 3: 2})})(), ''The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>1</code> should return <code>{0: 1, 1: 0, 2: 1, 3: 2}</code>'');'
- text: 'The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> with a start node of <code>1</code> should return <code>{0: 1, 1: 0, 2: 1, 3: Infinity}</code>'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]; var results = bfs(graph, 1); return isEquivalent(results, {0: 1, 1: 0, 2: 1, 3: Infinity})})(), ''The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> with a start node of <code>1</code> should return <code>{0: 1, 1: 0, 2: 1, 3: Infinity}</code>'');'
- text: 'The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>0</code> should return <code>{0: 0, 1: 1, 2: 2, 3: 3}</code>'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]; var results = bfs(graph, 0); return isEquivalent(results, {0: 0, 1: 1, 2: 2, 3: 3})})(), ''The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>0</code> should return <code>{0: 0, 1: 1, 2: 2, 3: 3}</code>'');'
- text: 'The input graph <code>[[0, 1], [1, 0]]</code> with a start node of <code>0</code> should return <code>{0: 0, 1: 1}</code>'
testString: 'assert((function() { var graph = [[0, 1], [1, 0]]; var results = bfs(graph, 0); return isEquivalent(results, {0: 0, 1: 1})})(), ''The input graph <code>[[0, 1], [1, 0]]</code> with a start node of <code>0</code> should return <code>{0: 0, 1: 1}</code>'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function bfs(graph, root) {
// Distance object returned
var nodesLen = {};
return nodesLen;
};
var exBFSGraph = [
[0, 1, 0, 0],
[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0]
];
console.log(bfs(exBFSGraph, 3));
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
function bfs(graph, root) {
// Distance object returned
var nodesLen = {};
// Set all distances to infinity
for (var i = 0; i < graph.length; i++) {
nodesLen[i] = Infinity;
}
nodesLen[root] = 0; // ...except root node
var queue = [root]; // Keep track of nodes to visit
var current; // Current node traversing
// Keep on going until no more nodes to traverse
while (queue.length !== 0) {
current = queue.shift();
// Get adjacent nodes from current node
var curConnected = graph[current]; // Get layer of edges from current
var neighborIdx = []; // List of nodes with edges
var idx = curConnected.indexOf(1); // Get first edge connection
while (idx !== -1) {
neighborIdx.push(idx); // Add to list of neighbors
idx = curConnected.indexOf(1, idx + 1); // Keep on searching
}
// Loop through neighbors and get lengths
for (var j = 0; j < neighborIdx.length; j++) {
// Increment distance for nodes traversed
if (nodesLen[neighborIdx[j]] === Infinity) {
nodesLen[neighborIdx[j]] = nodesLen[current] + 1;
queue.push(neighborIdx[j]); // Add new neighbors to queue
}
}
}
return nodesLen;}
```
</section>

View File

@ -0,0 +1,76 @@
---
id: 587d8257367417b2b2512c7c
title: Check if an Element is Present in a Binary Search Tree
challengeType: 1
---
## Description
<section id='description'>
Now that we have a general sense of what a binary search tree is let's talk about it in a little more detail. Binary search trees provide logarithmic time for the common operations of lookup, insertion, and deletion in the average case, and linear time in the worst case. Why is this? Each of those basic operations requires us to find an item in the tree (or in the case of insertion to find where it should go) and because of the tree structure at each parent node we are branching left or right and effectively excluding half the size of the remaining tree. This makes the search proportional to the logarithm of the number of nodes in the tree, which creates logarithmic time for these operations in the average case.
Ok, but what about the worst case? Well, consider constructing a tree from the following values, adding them left to right: <code>10</code>, <code>12</code>, <code>17</code>, <code>25</code>. Following our rules for a binary search tree, we will add <code>12</code> to the right of <code>10</code>, <code>17</code> to the right of this, and <code>25</code> to the right of this. Now our tree resembles a linked list and traversing it to find <code>25</code> would require us to traverse all the items in linear fashion. Hence, linear time in the worst case. The problem here is that the tree is unbalanced. We'll look a little more into what this means in the following challenges.
Instructions: In this challenge, we will create a utility for our tree. Write a method <code>isPresent</code> which takes an integer value as input and returns a boolean value for the presence or absence of that value in the binary search tree.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The <code>BinarySearchTree</code> data structure exists.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() }; return (typeof test == ''object'')})(), ''The <code>BinarySearchTree</code> data structure exists.'');'
- text: The binary search tree has a method called <code>isPresent</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.isPresent == ''function'')})(), ''The binary search tree has a method called <code>isPresent</code>.'');'
- text: The <code>isPresent</code> method correctly checks for the presence or absence of elements added to the tree.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.isPresent !== ''function'') { return false; }; test.add(4); test.add(7); test.add(411); test.add(452); return ( test.isPresent(452) && test.isPresent(411) && test.isPresent(7) && !test.isPresent(100) ); })(), ''The <code>isPresent</code> method correctly checks for the presence or absence of elements added to the tree.'');'
- text: <code>isPresent</code> handles cases where the tree is empty.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.isPresent !== ''function'') { return false; }; return test.isPresent(5) == false; })(), ''<code>isPresent</code> handles cases where the tree is empty.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,143 @@
---
id: 587d8255367417b2b2512c75
title: Create a Circular Queue
challengeType: 1
---
## Description
<section id='description'>
In this challenge you will be creating a Circular Queue. A circular queue is basically a queue that writes to the end of a collection then begins over writing itself at the beginning of the collection. This is type of data structure has some useful applications in certain situations. For example, a circular queue can be used for streaming media. Once the queue is full, new media data simply begins to overwrite old data.
A good way to illustrate this concept is with an array:
<blockquote>[1, 2, 3, 4, 5]<br> ^Read @ 0<br> ^Write @ 0</blockquote>
Here the read and write are both at position <code>0</code>. Now the queue gets 3 new records <code>a</code>, <code>b</code>, and <code>c</code>. Our queue now looks like:
<blockquote>[a, b, c, 4, 5]<br> ^Read @ 0<br> ^Write @ 3</blockquote>
As the read head reads, it can remove values or keep them:
<blockquote>[null, null, null, 4, 5]<br> ^Read @ 3<br> ^Write @ 3</blockquote>
Once the write reaches the end of the array it loops back to the beginning:
<blockquote>[f, null, null, d, e]<br> ^Read @ 3<br> ^Write @ 1</blockquote>
This approach requires a constant amount of memory but allows files of a much larger size to be processed.
Instructions:
In this challenge we will implement a circular queue. The circular queue should provide <code>enqueue</code> and <code>dequeue</code> methods which allow you to read from and write to the queue. The class itself should also accept an integer which you can use to specify the size of the queue when you create it. We've written the starting version of this class for you in the code editor. When you enqueue items to the queue, the write pointer should advance forward and loop back to the beginning once it reaches the end of the queue. Likewise, the read pointer should advance forward as you dequeue items. The write pointer should not be allowed to move past the read pointer (our class won't let you overwrite data you haven't read yet) and the read pointer should not be able to advance past data you have written.
In addition, the <code>enqueue</code> method should return the item you enqueued if it is successfully and otherwise return <code>null</code>. Similarly, when you dequeue an item it should be returned and if you cannot dequeue you should return <code>null</code>.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The <code>enqueue</code> method adds items to the circular queue.
testString: 'assert((function(){ var test = new CircularQueue(3); test.enqueue(17); test.enqueue(32); test.enqueue(591); var print = test.print(); return print[0] === 17 && print[1] === 32 && print[2] === 591; })(), ''The <code>enqueue</code> method adds items to the circular queue.'');'
- text: You cannot enqueue items past the read pointer.
testString: 'assert((function(){ var test = new CircularQueue(3); test.enqueue(17); test.enqueue(32); test.enqueue(591); test.enqueue(13); test.enqueue(25); test.enqueue(59); var print = test.print(); return print[0] === 17 && print[1] === 32 && print[2] === 591; })(), ''You cannot enqueue items past the read pointer.'');'
- text: The <code>dequeue</code> method dequeues items from the queue.
testString: 'assert((function(){ var test = new CircularQueue(3); test.enqueue(17); test.enqueue(32); test.enqueue(591); return test.dequeue() === 17 && test.dequeue() === 32 && test.dequeue() === 591; })(), ''The <code>dequeue</code> method dequeues items from the queue.'');'
- text: After an item is dequeued its position in the queue should be reset to <code>null</code>.
testString: 'assert((function(){ var test = new CircularQueue(3); test.enqueue(17); test.enqueue(32); test.enqueue(672); test.dequeue(); test.dequeue(); var print = test.print(); return print[0] === null && print[1] === null && print[2] === 672; })(), ''After an item is dequeued its position in the queue should be reset to <code>null</code>.'');'
- text: Trying to dequeue past the write pointer returns <code>null</code> and does not advance the write pointer.
testString: 'assert((function(){ var test = new CircularQueue(3); test.enqueue(17); test.enqueue(32); test.enqueue(591); return test.dequeue() === 17 && test.dequeue() === 32 && test.dequeue() === 591 && test.dequeue() === null && test.dequeue() === null && test.dequeue() === null && test.dequeue() === null && test.enqueue(100) === 100 && test.dequeue() === 100; })(), ''Trying to dequeue past the write pointer returns <code>null</code> and does not advance the write pointer.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
class CircularQueue {
constructor(size) {
this.queue = [];
this.read = 0;
this.write = 0;
this.max = size - 1;
while (size > 0) {
this.queue.push(null);
size--;
}
}
print() {
return this.queue;
}
enqueue(item) {
// Only change code below this line
// Only change code above this line
}
dequeue() {
// Only change code below this line
// Only change code above this line
}
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
class CircularQueue {
constructor(size) {
this.queue = [];
this.read = 0;
this.write = 0;
this.max = size - 1;
while (size > 0) {
this.queue.push(null);
size--;
}
}
print() {
return this.queue;
}
enqueue(item) {
if (this.queue[this.write] === null) {
this.queue[this.write] = item;
if (this.write === this.max) {
this.write = 0;
} else {
this.write++;
}
return item;
}
return null;
}
dequeue() {
if (this.queue[this.read] !== null) {
var item = this.queue[this.read];
this.queue[this.read] = null;
if (this.read === this.max) {
this.read = 0;
} else {
this.read++;
}
return item;
} else {
return null;
}
}
}
```
</section>

View File

@ -0,0 +1,84 @@
---
id: 587d825a367417b2b2512c87
title: Create a Doubly Linked List
challengeType: 1
---
## Description
<section id='description'>
All of the linked lists we've created so far are singly linked lists. Here, we'll create a <dfn>doubly linked list</dfn>. As the name implies, nodes in a doubly linked list have references to the next and previous node in the list.
This allows us to traverse the list in both directions but it also requires more memory to be used because every node must contain an additional reference to the previous node in the list.
</section>
## Instructions
<section id='instructions'>
We've provided a <code>Node</code> object and started our <code>DoublyLinkedList</code>. Let's add two methods to our doubly linked list called <code>add</code> and <code>remove</code>. The <code>add</code> method should add the given element to the list while the <code>remove</code> method should remove all occurrences of a given element in the list.
Be careful to handle any possible edge cases when writing these methods, such as deletions for the first or last element. Also, removing any item on an empty list should return <code>null</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The DoublyLinkedList data structure exists.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== ''undefined'') { test = new DoublyLinkedList() }; return (typeof test == ''object'')})(), ''The DoublyLinkedList data structure exists.'');'
- text: The DoublyLinkedList has a method called add.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== ''undefined'') { test = new DoublyLinkedList() }; if (test.add == undefined) { return false; }; return (typeof test.add == ''function'')})(), ''The DoublyLinkedList has a method called add.'');'
- text: The DoublyLinkedList has a method called remove.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== ''undefined'') { test = new DoublyLinkedList() }; if (test.remove == undefined) { return false; }; return (typeof test.remove == ''function'')})(), ''The DoublyLinkedList has a method called remove.'');'
- text: Removing an item from an empty list returns null.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== ''undefined'') { test = new DoublyLinkedList() }; return (test.remove(100) == null); })(), ''Removing an item from an empty list returns null.'');'
- text: The add method adds items to the list.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== ''undefined'') { test = new DoublyLinkedList() }; test.add(5); test.add(6); test.add(723); return (test.print().join('''') == ''56723''); })(), ''The add method adds items to the list.'');'
- text: Each node keeps track of the previous node.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== ''undefined'') { test = new DoublyLinkedList() }; test.add(50); test.add(68); test.add(73); return (test.printReverse().join('''') == ''736850''); })(), ''Each node keeps track of the previous node.'');'
- text: The first item can be removed from the list.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== ''undefined'') { test = new DoublyLinkedList() }; test.add(25); test.add(35); test.add(60); test.remove(25); return ( test.print().join('''') == ''3560'' ) })(), ''The first item can be removed from the list.'');'
- text: The last item can be removed from the list.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== ''undefined'') { test = new DoublyLinkedList() }; test.add(25); test.add(35); test.add(60); test.remove(60); return ( test.print().join('''') == ''2535'' ) })(), ''The last item can be removed from the list.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var Node = function(data, prev) {
this.data = data;
this.prev = prev;
this.next = null;
};
var DoublyLinkedList = function() {
this.head = null;
this.tail = null;
// change code below this line
// change code above this line
};
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,93 @@
---
id: 587d825b367417b2b2512c8e
title: Create a Hash Table
challengeType: 1
---
## Description
<section id='description'>
In this challenge we will learn about hash tables. A Hash table is used to implement associative arrays, or mappings of key-value pairs, like the objects and Maps we have just been studying. A JavaScript object could be implemented as a hash table, for instance (its actual implementation will depend on the environment it's running in). The way a hash table works is that it takes a key input and hashes this key in a deterministic way to some numerical value. This numerical value is then used as the actual key the associated value is stored by. Then, if you try to access the same key again, the hashing function will process the key, return the same numerical result, which will then be used to look up the associated value. This provides very efficient O(n) lookup time on average.
Hash tables can be implemented as arrays with hash functions producing array indices within a specified range. In this method, the choice of the array size is important, as is the hashing function. For instance, what if the hashing function produces the same value for two different keys? This is called a collision. One way to handle collisions is to just store both key-value pairs at that index. Then, upon lookup of either, you would have to iterate through the bucket of items to find the key you are looking for. A good hashing function will minimize collisions to maintain efficient search time.
Here, we won't be concerned with the details of hashing or hash table implementation, we will just try to get a general sense of how they work.
Instructions: Let's create the basic functionality of a hash table. We've created a naive hashing function for you to use. You can pass a string value to the function hash and it will return a hashed value you can use as a key for storage. Store items based on this hashed value in the this.collection object. Create these three methods: add, remove, and lookup. The first should accept a key value pair to add to the hash table. The second should remove a key-value pair when passed a key. The third should accept a key and return the associated value or null if the key is not present.
Be sure to write your code to account for collisions!
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The HashTable data structure exists.
testString: 'assert((function() { var test = false; if (typeof HashTable !== ''undefined'') { test = new HashTable() }; return (typeof test === ''object'')})(), ''The HashTable data structure exists.'');'
- text: The HashTable has an add method.
testString: 'assert((function() { var test = false; if (typeof HashTable !== ''undefined'') { test = new HashTable() }; return ((typeof test.add) === ''function'')})(), ''The HashTable has an add method.'');'
- text: The HashTable has an remove method.
testString: 'assert((function() { var test = false; if (typeof HashTable !== ''undefined'') { test = new HashTable() }; return ((typeof test.remove) === ''function'')})(), ''The HashTable has an remove method.'');'
- text: The HashTable has an lookup method.
testString: 'assert((function() { var test = false; if (typeof HashTable !== ''undefined'') { test = new HashTable() }; return ((typeof test.lookup) === ''function'')})(), ''The HashTable has an lookup method.'');'
- text: The add method adds key value pairs and the lookup method returns the values associated with a given key.
testString: 'assert((function() { var test = false; if (typeof HashTable !== ''undefined'') { test = new HashTable() }; test.add(''key'', ''value''); return (test.lookup(''key'') === ''value'')})(), ''The add method adds key value pairs and the lookup method returns the values associated with a given key.'');'
- text: The remove method accepts a key as input and removes the associated key value pair.
testString: 'assert((function() { var test = false; if (typeof HashTable !== ''undefined'') { test = new HashTable() }; test.add(''key'', ''value''); test.remove(''key''); return (test.lookup(''key'') === null)})(), ''The remove method accepts a key as input and removes the associated key value pair.'');'
- text: Items are added using the hash function.
testString: 'assert((function() { var test = false; if (typeof HashTable !== ''undefined'') { test = new HashTable() }; called = 0; test.add(''key1'',''value1''); test.add(''key2'',''value2''); test.add(''key3'',''value3''); return (called === 3)})(), ''Items are added using the hash function.'');'
- text: The hash table handles collisions.
testString: 'assert((function() { var test = false; if (typeof HashTable !== ''undefined'') { test = new HashTable() }; called = 0; test.add(''key1'',''value1''); test.add(''1key'',''value2''); test.add(''ke1y'',''value3''); return (test.lookup(''key1'') === ''value1'' && test.lookup(''1key'') == ''value2'' && test.lookup(''ke1y'') == ''value3'')})(), ''The hash table handles collisions.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var called = 0;
var hash = (string) => {
called++;
var hash = 0;
for (var i = 0; i < string.length; i++) { hash += string.charCodeAt(i); }
return hash;
};
var HashTable = function() {
this.collection = {};
// change code below this line
// change code above this line
};
```
</div>
### Before Test
<div id='js-setup'>
```js
var called = 0;
var hash = (string) => {
called++;
var hash = 0;
for (var i = 0; i < string.length; i++) { hash += string.charCodeAt(i); };
return hash;
};
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,83 @@
---
id: 587d8251367417b2b2512c62
title: Create a Linked List Class
challengeType: 1
---
## Description
<section id='description'>
Let's create a <code>linked list</code> class. Every linked list should start out with a few basic properties: a <code>head</code> (the first item in your list) and a <code>length</code> (number of items in your list). Sometimes you'll see implementations of linked lists that incorporate a <code>tail</code> for the last element of the list, but for now we'll just stick with these two. Whenever we add an element to the linked list, our <code>length</code> property should be incremented by one.
We'll want to have a way to add items to our linked list, so the first method we'll want to create is the <code>add</code> method.
If our list is empty, adding an element to our linked list is straightforward enough: we just wrap that element in a <code>Node</code> class, and we assign that node to the <code>head</code> of our linked list.
But what if our list already has one or more members? How do we add an element to the list? Recall that each node in a linked list has a <code>next</code> property. To add a node to the list, find the last node in the list, and point that last node's <code>next</code> property at our new node. (Hint: you know you've reached the end of a linked list when a node's <code>next</code> property is <code>null</code>.)
</section>
## Instructions
<section id='instructions'>
Write an add method that assigns the first node you push to the linked list to the <code>head</code>; after that, whenever adding a node, every node should be referenced by the previous node's <code>next</code> property.
Note
Your list's <code>length</code> should increase by one every time an element is added to the linked list.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>LinkedList</code> class should have a <code>add</code> method.
testString: 'assert((function(){var test = new LinkedList(); return (typeof test.add === ''function'')}()), ''Your <code>LinkedList</code> class should have a <code>add</code> method.'');'
- text: Your <code>LinkedList</code> class should assign <code>head</code> to the first node added.
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); return test.head().element === ''cat''}()), ''Your <code>LinkedList</code> class should assign <code>head</code> to the first node added.'');'
- text: The previous <code>node</code> in your <code>LinkedList</code> class should have reference to the newest node created.
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); test.add(''dog''); return test.head().next.element === ''dog''}()), ''The previous <code>node</code> in your <code>LinkedList</code> class should have reference to the newest node created.'');'
- text: The <code>size</code> of your <code>LinkedList</code> class should equal the amount of nodes in the linked list.
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); test.add(''dog''); return test.size() === 2}()), ''The <code>size</code> of your <code>LinkedList</code> class should equal the amount of nodes in the linked list.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element){
this.element = element;
this.next = null;
};
this.head = function(){
return head;
};
this.size = function(){
return length;
};
this.add = function(element){
// Only change code below this line
// Only change code above this line
};
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,77 @@
---
id: 8d5823c8c441eddfaeb5bdef
title: Create a Map Data Structure
challengeType: 1
---
## Description
<section id='description'>
The next few challenges will cover maps and hash tables. Maps are data structures that store key-value pairs. In JavaScript, these are available to us as objects. Maps provide rapid lookup of stored items based on key values and are very common and useful data structures.
Instructions: Let's get some practice creating our own map. Because JavaScript objects provide a much more efficient map structure than anything we could write here, this is intended primarily as a learning exercise. However, JavaScript objects only provide us with certain operations. What if we wanted to define custom operations?
Use the <code>Map</code> object provided here as a wrapper around a JavaScript <code>object</code>. Create the following methods and operations on the Map object:
<ul>
<li><code>add</code> accepts a <code>key, value</code> pair to add to the map.</li>
<li><code>remove</code> accepts a key and removes the associated <code>key, value</code> pair</li>
<li><code>get</code> accepts a <code>key</code> and returns the stored <code>value</code></li>
<li><code>has</code> accepts a <code>key</code> and returns <dfn>true</dfn> if the key exists or <dfn>false</dfn> if it doesn't.</li>
<li><code>values</code> returns an array of all the values in the map</li>
<li><code>size</code> returns the number of items in the map</li>
<li><code>clear</code> empties the map</li>
</ul>
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The Map data structure exists.
testString: 'assert((function() { var test = false; if (typeof Map !== ''undefined'') { test = new Map() }; return (typeof test == ''object'')})(), ''The Map data structure exists.'');'
- text: 'The Map object has the following methods: add, remove, get, has, values, clear, and size.'
testString: 'assert((function() { var test = false; if (typeof Map !== ''undefined'') { test = new Map() }; return (typeof test.add == ''function'' && typeof test.remove == ''function'' && typeof test.get == ''function'' && typeof test.has == ''function'' && typeof test.values == ''function'' && typeof test.clear == ''function'' && typeof test.size == ''function'')})(), ''The Map object has the following methods: add, remove, get, has, values, clear, and size.'');'
- text: The add method adds items to the map.
testString: 'assert((function() { var test = false; if (typeof Map !== ''undefined'') { test = new Map() }; test.add(5,6); test.add(2,3); test.add(2,5); return (test.size() == 2)})(), ''The add method adds items to the map.'');'
- text: The has method returns true for added items and false for absent items.
testString: 'assert((function() { var test = false; if (typeof Map !== ''undefined'') { test = new Map() }; test.add(''test'',''value''); return (test.has(''test'') && !test.has(''false''))})(), ''The has method returns true for added items and false for absent items.'');'
- text: The get method accepts keys as input and returns the associated values.
testString: 'assert((function() { var test = false; if (typeof Map !== ''undefined'') { test = new Map() }; test.add(''abc'',''def''); return (test.get(''abc'') == ''def'')})(), ''The get method accepts keys as input and returns the associated values.'');'
- text: The values method returns all the values stored in the map as strings in an array.
testString: 'assert((function() { var test = false; if (typeof Map !== ''undefined'') { test = new Map() }; test.add(''a'',''b''); test.add(''c'',''d''); test.add(''e'',''f''); var vals = test.values(); return (vals.indexOf(''b'') != -1 && vals.indexOf(''d'') != -1 && vals.indexOf(''f'') != -1)})(), ''The values method returns all the values stored in the map as strings in an array.'');'
- text: The clear method empties the map and the size method returns the number of items present in the map.
testString: 'assert((function() { var test = false; if (typeof Map !== ''undefined'') { test = new Map() }; test.add(''b'',''b''); test.add(''c'',''d''); test.remove(''asdfas''); var init = test.size(); test.clear(); return (init == 2 && test.size() == 0)})(), ''The clear method empties the map and the size method returns the number of items present in the map.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var Map = function() {
this.collection = {};
// change code below this line
// change code above this line
};
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,112 @@
---
id: 587d8255367417b2b2512c74
title: Create a Priority Queue Class
challengeType: 1
---
## Description
<section id='description'>
In this challenge you will be creating a Priority Queue. A Priority Queue is a special type of Queue in which items may have additional information which specifies their priority. This could be simply represented with an integer. Item priority will override placement order in determining the sequence items are dequeued. If an item with a higher priority is enqueued after items with lower priority, the higher priority item will be dequeued before all the others.
For instance, lets imagine we have a priority queue with three items:
<code>[[kitten, 2], [dog, 2], [rabbit, 2]]</code>
Here the second value (an integer) represents item priority. If we enqueue <code>[human, 1]</code> with a priority of <code>1</code> (assuming lower priorities are given precedence) it would then be the first item to be dequeued. The collection would like this:
<code>[[human, 1], [kitten, 2], [dog, 2], [rabbit, 2]]</code>.
Weve started writing a <code>PriorityQueue</code> in the code editor. You will need to add an <code>enqueue</code> method for adding items with a priority, a <code>dequeue</code> method for removing items, a <code>size</code> method to return the number of items in the queue, a <code>front</code> method to return the element at the front of the queue, and finally an <code>isEmpty</code> method that will return <code>true</code> if the queue is empty or <code>false</code> if it is not.
The <code>enqueue</code> should accept items with the format shown above (<code>['human', 1]</code>) where <code>1</code> represents the priority. The <code>dequeue</code> should return only the current item, not its priority.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>Queue</code> class should have a <code>enqueue</code> method.
testString: 'assert((function(){var test = new PriorityQueue(); return (typeof test.enqueue === ''function'')}()), ''Your <code>Queue</code> class should have a <code>enqueue</code> method.'');'
- text: Your <code>Queue</code> class should have a <code>dequeue</code> method.
testString: 'assert((function(){var test = new PriorityQueue(); return (typeof test.dequeue === ''function'')}()), ''Your <code>Queue</code> class should have a <code>dequeue</code> method.'');'
- text: Your <code>Queue</code> class should have a <code>size</code> method.
testString: 'assert((function(){var test = new PriorityQueue(); return (typeof test.size === ''function'')}()), ''Your <code>Queue</code> class should have a <code>size</code> method.'');'
- text: Your <code>Queue</code> class should have an <code>isEmpty</code> method.
testString: 'assert((function(){var test = new PriorityQueue(); return (typeof test.isEmpty === ''function'')}()), ''Your <code>Queue</code> class should have an <code>isEmpty</code> method.'');'
- text: Your PriorityQueue should correctly keep track of the current number of items using the <code>size</code> method as items are enqueued and dequeued.
testString: 'assert((function(){var test = new PriorityQueue(); test.enqueue([''David Brown'', 2]); test.enqueue([''Jon Snow'', 1]); var size1 = test.size(); test.dequeue(); var size2 = test.size(); test.enqueue([''A'', 3]); test.enqueue([''B'', 3]); test.enqueue([''C'', 3]); return (size1 === 2 && size2 === 1 && test.size() === 4)}()), ''Your PriorityQueue should correctly keep track of the current number of items using the <code>size</code> method as items are enqueued and dequeued.'');'
- text: The <code>isEmpty</code> method should return <code>true</code> when the queue is empty.
testString: 'assert((function(){var test = new PriorityQueue(); test.enqueue([''A'', 1]); test.enqueue([''B'', 1]); test.dequeue(); var first = test.isEmpty(); test.dequeue(); return (!first && test.isEmpty()); }()), ''The <code>isEmpty</code> method should return <code>true</code> when the queue is empty.'');'
- text: The priority queue should return items with a higher priority before items with a lower priority and return items in first-in-first-out order otherwise.
testString: 'assert((function(){var test = new PriorityQueue(); test.enqueue([''A'', 5]); test.enqueue([''B'', 5]); test.enqueue([''C'', 5]); test.enqueue([''D'', 3]); test.enqueue([''E'', 1]); test.enqueue([''F'', 7]); var result = []; result.push(test.dequeue()); result.push(test.dequeue()); result.push(test.dequeue()); result.push(test.dequeue()); result.push(test.dequeue()); result.push(test.dequeue()); return result.join('''') === ''EDABCF'';}()), ''The priority queue should return items with a higher priority before items with a lower priority and return items in first-in-first-out order otherwise.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function PriorityQueue () {
this.collection = [];
this.printCollection = function() {
console.log(this.collection);
};
// Only change code below this line
// Only change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function PriorityQueue () {
this.collection = [];
this.printCollection = function(){
console.log(this.collection);
};
this.size = function() {
return this.collection.length;
};
this.isEmpty = function() {
return this.size() > 0 ? false : true;
};
this.enqueue = function (newitem) {
if (this.isEmpty()) {
return this.collection.push(newitem);
}
this.collection = this.collection.reverse();
var found_index = this.collection.findIndex(function (item) {
return newitem[1] >= item[1];
});
if (found_index === -1) {
this.collection.push(newitem);
} else {
this.collection.splice(found_index, 0, newitem);
}
this.collection = this.collection.reverse();
};
this.dequeue = function() {
if (!this.isEmpty()) {
return this.collection.shift()[0];
} else {
return 'The queue is empty.'
}
};
}
```
</section>

View File

@ -0,0 +1,78 @@
---
id: 587d8250367417b2b2512c60
title: Create a Queue Class
challengeType: 1
---
## Description
<section id='description'>
Like stacks, queues are a collection of elements. But unlike stacks, queues follow the FIFO (First-In First-Out) principle. Elements added to a queue are pushed to the tail, or the end, of the queue, and only the element at the front of the queue is allowed to be removed.
We could use an array to represent a queue, but just like stacks, we want to limit the amount of control we have over our queues.
The two main methods of a queue class is the enqueue and the dequeue method. The enqueue method pushes an element to the tail of the queue, and the dequeue method removes and returns the element at the front of the queue. Other useful methods are the front, size, and isEmpty methods.
Instructions
Write an enqueue method that pushes an element to the tail of the queue, a dequeue method that removes and returns the front element, a front method that lets us see the front element, a size method that shows the length, and an isEmpty method to check if the queue is empty.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>Queue</code> class should have a <code>enqueue</code> method.
testString: 'assert((function(){var test = new Queue(); return (typeof test.enqueue === ''function'')}()), ''Your <code>Queue</code> class should have a <code>enqueue</code> method.'');'
- text: Your <code>Queue</code> class should have a <code>dequeue</code> method.
testString: 'assert((function(){var test = new Queue(); return (typeof test.dequeue === ''function'')}()), ''Your <code>Queue</code> class should have a <code>dequeue</code> method.'');'
- text: Your <code>Queue</code> class should have a <code>front</code> method.
testString: 'assert((function(){var test = new Queue(); return (typeof test.front === ''function'')}()), ''Your <code>Queue</code> class should have a <code>front</code> method.'');'
- text: Your <code>Queue</code> class should have a <code>size</code> method.
testString: 'assert((function(){var test = new Queue(); return (typeof test.size === ''function'')}()), ''Your <code>Queue</code> class should have a <code>size</code> method.'');'
- text: Your <code>Queue</code> class should have an <code>isEmpty</code> method.
testString: 'assert((function(){var test = new Queue(); return (typeof test.isEmpty === ''function'')}()), ''Your <code>Queue</code> class should have an <code>isEmpty</code> method.'');'
- text: The <code>dequeue</code> method should remove and return the front element of the queue
testString: 'assert((function(){var test = new Queue(); test.enqueue(''Smith''); return (test.dequeue() === ''Smith'')}()), ''The <code>dequeue</code> method should remove and return the front element of the queue'');'
- text: The <code>front</code> method should return value of the front element of the queue
testString: 'assert((function(){var test = new Queue(); test.enqueue(''Smith''); test.enqueue(''John''); return (test.front() === ''Smith'')}()), ''The <code>front</code> method should return value of the front element of the queue'');'
- text: The <code>size</code> method should return the length of the queue
testString: 'assert((function(){var test = new Queue(); test.enqueue(''Smith''); return (test.size() === 1)}()), ''The <code>size</code> method should return the length of the queue'');'
- text: The <code>isEmpty</code> method should return <code>false</code> if there are elements in the queue
testString: 'assert((function(){var test = new Queue(); test.enqueue(''Smith''); return !(test.isEmpty())}()), ''The <code>isEmpty</code> method should return <code>false</code> if there are elements in the queue'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Queue () {
var collection = [];
this.print = function() {
console.log(collection);
};
// Only change code below this line
// Only change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,76 @@
---
id: 8d1323c8c441eddfaeb5bdef
title: Create a Set Class
challengeType: 1
---
## Description
<section id='description'>
In the next few exercises we are going to create a function to emulate a data structure called a "Set". A Set is like an array, but it cannot contain duplicate values. The typical use for a Set is to simply check for the presence of an item. This can be implemented with an object, for instance:
<blockquote>var set = new Object();<br>set.foo = true;<br>// See if foo exists in our set:<br>console.log(set.foo) // true</blockquote>
In the next few exercises, we will build a full featured Set from scratch.
For this exercise, create a function that will add a value to our set collection as long as the value does not already exist in the set. For example:
<blockquote>this.add = function(element) {<br> //some code to add value to the set<br>}</blockquote>
The function should return <code>true</code> if the value is successfully added and <code>false</code> otherwise.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>Set</code> class should have an <code>add</code> method.
testString: 'assert((function(){var test = new Set(); return (typeof test.add === ''function'')}()), ''Your <code>Set</code> class should have an <code>add</code> method.'');'
- text: Your <code>add</code> method should not add duplicate values.
testString: 'assert((function(){var test = new Set(); test.add(''a''); test.add(''b''); test.add(''a''); var vals = test.values(); return (vals[0] === ''a'' && vals[1] === ''b'' && vals.length === 2)}()), ''Your <code>add</code> method should not add duplicate values.'');'
- text: Your <code>add</code> method should return <code>true</code> when a value has been successfully added.
testString: 'assert((function(){var test = new Set(); var result = test.add(''a''); return (result != undefined) && (result === true);}()), ''Your <code>add</code> method should return <code>true</code> when a value has been successfully added.'');'
- text: Your <code>add</code> method should return <code>false</code> when a duplicate value is added.
testString: 'assert((function(){var test = new Set(); test.add(''a''); var result = test.add(''a''); return (result != undefined) && (result === false);}()), ''Your <code>add</code> method should return <code>false</code> when a duplicate value is added.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Set() {
// the var collection will hold our set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function Set() {var collection = []; this.has = function(e){return(collection.indexOf(e) !== -1);};this.values = function() {return collection;};this.add = function(element) {if (!this.has(element)) {collection.push(element);return true;} else {return false;}};}
```
</section>

View File

@ -0,0 +1,79 @@
---
id: 587d8250367417b2b2512c5f
title: Create a Stack Class
challengeType: 1
---
## Description
<section id='description'>
In the last section, we talked about what a stack is and how we can use an array to represent a stack. In this section, we will be creating our own stack class.
Although you can use arrays to create stacks, sometimes it is best to limit the amount of control we have with our stacks.
Apart from the <code>push</code> and <code>pop</code> method, stacks have other useful methods. Let's add a <code>peek</code>, <code>isEmpty</code>, and <code>clear</code> method to our stack class.
Instructions
Write a <code>push</code> method that pushes an element to the top of the stack, a <code>pop</code> method that removes the element on the top of the stack, a <code>peek</code> method that looks at the first element in the stack, an <code>isEmpty</code> method that checks if the stack is empty, and a <code>clear</code> method that removes all elements from the stack.
Normally stacks don't have this, but we've added a <code>print</code> helper method that console logs the collection.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>Stack</code> class should have a <code>push</code> method.
testString: 'assert((function(){var test = new Stack(); return (typeof test.push === ''function'')}()), ''Your <code>Stack</code> class should have a <code>push</code> method.'');'
- text: Your <code>Stack</code> class should have a <code>pop</code> method.
testString: 'assert((function(){var test = new Stack(); return (typeof test.pop === ''function'')}()), ''Your <code>Stack</code> class should have a <code>pop</code> method.'');'
- text: Your <code>Stack</code> class should have a <code>peek</code> method.
testString: 'assert((function(){var test = new Stack(); return (typeof test.peek === ''function'')}()), ''Your <code>Stack</code> class should have a <code>peek</code> method.'');'
- text: Your <code>Stack</code> class should have a <code>isEmpty</code> method.
testString: 'assert((function(){var test = new Stack(); return (typeof test.isEmpty === ''function'')}()), ''Your <code>Stack</code> class should have a <code>isEmpty</code> method.'');'
- text: Your <code>Stack</code> class should have a <code>clear</code> method.
testString: 'assert((function(){var test = new Stack(); return (typeof test.clear === ''function'')}()), ''Your <code>Stack</code> class should have a <code>clear</code> method.'');'
- text: The <code>peek</code> method should return the top element of the stack
testString: 'assert((function(){var test = new Stack(); test.push(''CS50''); return (test.peek() === ''CS50'')}()), ''The <code>peek</code> method should return the top element of the stack'');'
- text: The <code>pop</code> method should remove and return the top element of the stack
testString: 'assert((function(){var test = new Stack(); test.push(''CS50''); return (test.pop() === ''CS50'');}()), ''The <code>pop</code> method should remove and return the top element of the stack'');'
- text: The <code>isEmpty</code> method should return true if a stack does not contain any elements
testString: 'assert((function(){var test = new Stack(); return test.isEmpty()}()), ''The <code>isEmpty</code> method should return true if a stack does not contain any elements'');'
- text: The <code>clear</code> method should remove all element from the stack
testString: 'assert((function(){var test = new Stack(); test.push(''CS50''); test.clear(); return (test.isEmpty())}()), ''The <code>clear</code> method should remove all element from the stack'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Stack() {
var collection = [];
this.print = function() {
console.log(collection);
};
// Only change code below this line
// Only change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,76 @@
---
id: 587d8259367417b2b2512c84
title: Create a Trie Search Tree
challengeType: 1
---
## Description
<section id='description'>
Here we will move on from binary search trees and take a look at another type of tree structure called a trie. A trie is an ordered search tree commonly used to hold strings, or more generically associative arrays or dynamic datasets in which the keys are strings. They are very good at storing sets of data when many keys will have overlapping prefixes, for example, all the words in a dictionary.
Unlike a binary tree, nodes are not associated with actual values. Instead, the path to a node represents a specific key. For instance, if we wanted to store the string code in a trie, we would have four nodes, one for each letter: c — o — d — e. Following that path through all these nodes will then create code as a string — that path is the key we stored. Then, if we wanted to add the string coding, it would share the first three nodes of code before branching away after the d. In this way, large datasets can be stored very compactly. In addition, search can be very quick because it is effectively limited to the length of the string you are storing. Furthermore, unlike binary trees a node can store any number of child nodes.
As you might have guessed from the above example, some metadata is commonly stored at nodes that hold the end of a key so that on later traversals that key can still be retrieved. For instance, if we added codes in our example above we would need some way to know that the e in code represents the end of a key that was previously entered. Otherwise, this information would effectively be lost when we add codes.
Instructions: Let's create a trie to store words. It will accept words through an add method and store these in a trie data structure. It will also allow us to query if a given string is a word with an isWord method, and retrieve all the words entered into the trie with a print method. isWord should return a boolean value and print should return an array of all these words as string values.
In order for us to verify that this data structure is implemented correctly, we've provided a Node structure for each node in the tree. Each node will be an object with a keys property which is a JavaScript Map object. This will hold the individual letters that are valid keys of each node. We've also created an end property on the nodes that can be set to true if the node represents the termination of a word.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The Trie has an add method.
testString: 'assert((function testTrie() { var test = false; if (typeof Trie !== ''undefined'') { test = new Trie() } else { return false; }; return (typeof test.add == ''function'') }()), ''The Trie has an add method.'');'
- text: The Trie has a print method.
testString: 'assert((function testTrie() { var test = false; if (typeof Trie !== ''undefined'') { test = new Trie() } else { return false; }; return (typeof test.print == ''function'') }()), ''The Trie has a print method.'');'
- text: The Trie has an isWord method.
testString: 'assert((function testTrie() { var test = false; if (typeof Trie !== ''undefined'') { test = new Trie() } else { return false; }; return (typeof test.isWord == ''function'') }()), ''The Trie has an isWord method.'');'
- text: The print method returns all items added to the trie as strings in an array.
testString: 'assert((function testTrie() { var test = false; if (typeof Trie !== ''undefined'') { test = new Trie() } else { return false; }; test.add(''jump''); test.add(''jumps''); test.add(''jumped''); test.add(''house''); test.add(''mouse''); var added = test.print(); return (added.indexOf(''jump'') != -1 && added.indexOf(''jumps'') != -1 && added.indexOf(''jumped'') != -1 && added.indexOf(''house'') != -1 && added.indexOf(''mouse'') != -1 && added.length == 5); }()), ''The print method returns all items added to the trie as strings in an array.'');'
- text: The isWord method returns true only for words added to the trie and false for all other words.
testString: 'assert((function testTrie() { var test = false; if (typeof Trie !== ''undefined'') { test = new Trie() } else { return false; }; test.add(''hop''); test.add(''hops''); test.add(''hopped''); test.add(''hoppy''); test.add(''hope''); return (test.isWord(''hop'') && !test.isWord(''ho'') && test.isWord(''hopped'') && !test.isWord(''hopp'') && test.isWord(''hoppy'') && !test.isWord(''hoping'')); }()), ''The isWord method returns true only for words added to the trie and false for all other words.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
var Node = function() {
this.keys = new Map();
this.end = false;
this.setEnd = function() {
this.end = true;
};
this.isEnd = function() {
return this.end;
};
};
var Trie = function() {
// change code below this line
// change code above this line
};
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,60 @@
---
id: 587d825b367417b2b2512c8d
title: Create an ES6 JavaScript Map
challengeType: 1
---
## Description
<section id='description'>
The new version of JavaScript provides us with a built-in Map object which provides much of the functionality we wrote by hand in the last challenge. This Map object, although similar to regular JavaScript objects, provides some useful functionality that normal objects lack. For example, an ES6 Map tracks the insertion order of items that are added to it. Here is a more complete overview of its methods:
<code>.has(key)</code> returns true or false based on the presence of a key
<code>.get(key)</code> returns the value associated with a key
<code>.set(key, value)</code> sets a new key, value pair
<code>.delete(key)</code> removes a key, value pair
<code>.clear()</code> removes all key, value pairs
<code>.entries()</code> returns an array of all the keys in insertion order
<code>.values()</code> returns an array of all the values in insertion order
Instructions: Define a JavaScript Map object and assign to it a variable called myMap. Add the key, value pair <code>freeCodeCamp</code>, <code>Awesome!</code> to it.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The myMap object exists.
testString: 'assert(typeof myMap === ''object'', ''The myMap object exists.'');'
- text: 'myMap contains the key value pair <code>freeCodeCamp</code>, <code>Awesome!</code>.'
testString: 'assert(myMap.get(''freeCodeCamp'') === ''Awesome!'', ''myMap contains the key value pair <code>freeCodeCamp</code>, <code>Awesome!</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// change code below this line
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,72 @@
---
id: 587d8254367417b2b2512c70
title: Create and Add to Sets in ES6
challengeType: 1
---
## Description
<section id='description'>
Now that you have worked through ES5, you are going to perform something similar in ES6. This will be considerably easier. ES6 contains a built-in data structure <code>Set</code> so many of the operations you wrote by hand are now included for you. Let's take a look:
To create a new empty set:
<code>var set = new Set();</code>
You can create a set with a value:
<code>var set = new Set(1);</code>
You can create a set with an array:
<code>var set = new Set([1, 2, 3]);</code>
Once you have created a set, you can add the values you wish using the <code>add</code> method:
<blockquote>var set = new Set([1, 2, 3]);<br>set.add([4, 5, 6]);</blockquote>
As a reminder, a set is a data structure that cannot contain duplicate values:
<blockquote>var set = new Set([1, 2, 3, 1, 2, 3]);<br>// set contains [1, 2, 3] only</blockquote>
</section>
## Instructions
<section id='instructions'>
For this exercise, return a set with the following values: <code>1, 2, 3, 'Taco', 'Cat', 'Awesome'</code>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'Your <code>Set</code> should only contain the values <code>1, 2, 3, Taco, Cat, Awesome</code>.'
testString: 'assert(function(){var test = checkSet(); return (test.size == 6) && test.has(1) && test.has(2) && test.has(3) && test.has(''Taco'') && test.has(''Cat'') && test.has(''Awesome'');}, ''Your <code>Set</code> should only contain the values <code>1, 2, 3, Taco, Cat, Awesome</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function checkSet() {
var set = new Set([1, 2, 3, 3, 2, 1, 2, 3, 1]);
// change code below this line
// change code above this line
console.log(set);
return set;
}
checkSet();
```
</div>
</section>
## Solution
<section id='solution'>
```js
function checkSet(){var set = new Set([1,2,3,'Taco','Cat','Awesome']);
return set;}
```
</section>

View File

@ -0,0 +1,82 @@
---
id: 587d8258367417b2b2512c80
title: Delete a Leaf Node in a Binary Search Tree
challengeType: 1
---
## Description
<section id='description'>
This is the first of three challenges where we will implement a more difficult operation in binary search trees: deletion. Deletion is difficult because removing nodes breaks links in the tree. These links must be carefully reestablished to ensure the binary tree structure is maintained. For some deletions, this means the tree must be rearranged. In general, you will encounter one of three cases when trying to delete a node:
Leaf Node: The target to delete has zero children.
One Child: The target to delete only has one child.
Two Children: The target to delete has two child nodes.
Removing a leaf node is easy, we simply remove it. Deleting a node with one child is also relatively easy, we simply remove it and link its parent to child of the node we deleted. Removing a node with two children is more difficult, however, because this creates two child nodes that need to be reconnected to the parent tree. We'll see how to deal with this case in the third challenge. Additionally, you need to be mindful of some edge cases when handling deletion. What if the tree is empty? What if the node to delete is the root node? What if there are only two elements in the tree? For now, let's handle the first case where we delete a leaf node.
Instructions: Create a method on our binary tree called <code>remove</code>. We'll build the logic for our deletion operation in here. First, you'll want to create a function within remove that finds the node we are trying to delete in the current tree. If the node is not present in the tree, <code>remove</code> should return <code>null</code>. Now, if the target node is a leaf node with no children, then the parent reference to it should be set to <code>null</code>. This effectively deletes the node from the tree. To do this, you will have to keep track of the parent of the node we are trying to delete as well. It will also be useful to create a way to track the number of children the target node has, as this will determine which case our deletion falls under.
We will handle the second and third cases in the next challenges. Good luck!
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The <code>BinarySearchTree</code> data structure exists.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() }; return (typeof test == ''object'')})(), ''The <code>BinarySearchTree</code> data structure exists.'');'
- text: The binary search tree has a method called <code>remove</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.remove == ''function'')})(), ''The binary search tree has a method called <code>remove</code>.'');'
- text: Trying to remove an element that does not exist returns <code>null</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== ''function'') { return false; }; return (test.remove(100) == null); })(), ''Trying to remove an element that does not exist returns <code>null</code>.'');'
- text: 'If the root node has no children, deleting it sets the root to <code>null</code>.'
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== ''function'') { return false; }; test.add(500); test.remove(500); return (test.inorder() == null); })(), ''If the root node has no children, deleting it sets the root to <code>null</code>.'');'
- text: The <code>remove</code> method removes leaf nodes from the tree
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== ''function'') { return false; }; test.add(5); test.add(3); test.add(7); test.add(6); test.add(10); test.add(12); test.remove(3); test.remove(12); test.remove(10); return (test.inorder().join('''') == ''567''); })(), ''The <code>remove</code> method removes leaf nodes from the tree'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// case 1: target has no children, change code below this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,122 @@
---
id: 587d8258367417b2b2512c81
title: Delete a Node with One Child in a Binary Search Tree
challengeType: 1
---
## Description
<section id='description'>
Now that we can delete leaf nodes let's move on to the second case: deleting a node with one child. For this case, say we have a tree with the following nodes 1 — 2 — 3 where 1 is the root. To delete 2, we simply need to make the right reference in 1 point to 3. More generally to delete a node with only one child, we make that node's parent reference the next node in the tree.
Instructions: We've provided some code in our <code>remove</code> method that accomplishes the tasks from the last challenge. We find the target to delete and its parent and define the number of children the target node has. Let's add the next case here for target nodes with only one child. Here, we'll have to determine if the single child is a left or right branch in the tree and then set the correct reference in the parent to point to this node. In addition, let's account for the case where the target is the root node (this means the parent node will be <code>null</code>). Feel free to replace all the starter code with your own as long as it passes the tests.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The <code>BinarySearchTree</code> data structure exists.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() }; return (typeof test == ''object'')})(), ''The <code>BinarySearchTree</code> data structure exists.'');'
- text: The binary search tree has a method called <code>remove</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.remove == ''function'')})(), ''The binary search tree has a method called <code>remove</code>.'');'
- text: Trying to remove an element that does not exist returns <code>null</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== ''function'') { return false; }; return (test.remove(100) == null); })(), ''Trying to remove an element that does not exist returns <code>null</code>.'');'
- text: 'If the root node has no children, deleting it sets the root to <code>null</code>.'
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== ''function'') { return false; }; test.add(500); test.remove(500); return (test.inorder() == null); })(), ''If the root node has no children, deleting it sets the root to <code>null</code>.'');'
- text: The <code>remove</code> method removes leaf nodes from the tree
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== ''function'') { return false; }; test.add(5); test.add(3); test.add(7); test.add(6); test.add(10); test.add(12); test.remove(3); test.remove(12); test.remove(10); return (test.inorder().join('''') == ''567''); })(), ''The <code>remove</code> method removes leaf nodes from the tree'');'
- text: The <code>remove</code> method removes nodes with one child.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== ''function'') { return false; }; test.add(-1); test.add(3); test.add(7); test.add(16); test.remove(16); test.remove(7); test.remove(3); return (test.inorder().join('''') == ''-1''); })(), ''The <code>remove</code> method removes nodes with one child.'');'
- text: Removing the root in a tree with two nodes sets the second to be the root.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== ''function'') { return false; }; test.add(15); test.add(27); test.remove(15); return (test.inorder().join('''') == ''27''); })(), ''Removing the root in a tree with two nodes sets the second to be the root.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
this.remove = function(value) {
if (this.root === null) {
return null;
}
var target;
var parent = null;
// find the target value and its parent
(function findValue(node = this.root) {
if (value == node.value) {
target = node;
} else if (value < node.value && node.left !== null) {
parent = node;
return findValue(node.left);
} else if (value < node.value && node.left === null) {
return null;
} else if (value > node.value && node.right !== null) {
parent = node;
return findValue(node.right);
} else {
return null;
}
}).bind(this)();
if (target === null) {
return null;
}
// count the children of the target to delete
var children = (target.left !== null ? 1 : 0) + (target.right !== null ? 1 : 0);
// case 1: target has no children
if (children === 0) {
if (target == this.root) {
this.root = null;
}
else {
if (parent.left == target) {
parent.left = null;
} else {
parent.right = null;
}
}
}
// case 2: target has one child, change code below this line
};
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,141 @@
---
id: 587d8258367417b2b2512c82
title: Delete a Node with Two Children in a Binary Search Tree
challengeType: 1
---
## Description
<section id='description'>
Removing nodes that have two children is the hardest case to implement. Removing a node like this produces two subtrees that are no longer connected to the original tree structure. How can we reconnect them? One method is to find the smallest value in the right subtree of the target node and replace the target node with this value. Selecting the replacement in this way ensures that it is greater than every node in the left subtree it becomes the new parent of but also less than every node in the right subtree it becomes the new parent of.
Once this replacement is made the replacement node must be removed from the right subtree. Even this operation is tricky because the replacement may be a leaf or it may itself be the parent of a right subtree. If it is a leaf we must remove its parent's reference to it. Otherwise, it must be the right child of the target. In this case, we must replace the target value with the replacement value and make the target reference the replacement's right child.
Instructions: Let's finish our <code>remove</code> method by handling the third case. We've provided some code again for the first two cases. Add some code now to handle target nodes with two children. Any edge cases to be aware of? What if the tree has only three nodes? Once you are finished this will complete our deletion operation for binary search trees. Nice job, this is a pretty hard problem!
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The <code>BinarySearchTree</code> data structure exists.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() }; return (typeof test == ''object'')})(), ''The <code>BinarySearchTree</code> data structure exists.'');'
- text: The binary search tree has a method called <code>remove</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.remove == ''function'')})(), ''The binary search tree has a method called <code>remove</code>.'');'
- text: Trying to remove an element that does not exist returns <code>null</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.remove == ''function'') ? (test.remove(100) == null) : false})(), ''Trying to remove an element that does not exist returns <code>null</code>.'');'
- text: 'If the root node has no children, deleting it sets the root to <code>null</code>.'
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; test.add(500); test.remove(500); return (typeof test.remove == ''function'') ? (test.inorder() == null) : false})(), ''If the root node has no children, deleting it sets the root to <code>null</code>.'');'
- text: The <code>remove</code> method removes leaf nodes from the tree
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; test.add(5); test.add(3); test.add(7); test.add(6); test.add(10); test.add(12); test.remove(3); test.remove(12); test.remove(10); return (typeof test.remove == ''function'') ? (test.inorder().join('''') == ''567'') : false})(), ''The <code>remove</code> method removes leaf nodes from the tree'');'
- text: The <code>remove</code> method removes nodes with one child.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== ''function'') { return false; }; test.add(-1); test.add(3); test.add(7); test.add(16); test.remove(16); test.remove(7); test.remove(3); return (test.inorder().join('''') == ''-1''); })(), ''The <code>remove</code> method removes nodes with one child.'');'
- text: Removing the root in a tree with two nodes sets the second to be the root.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== ''function'') { return false; }; test.add(15); test.add(27); test.remove(15); return (test.inorder().join('''') == ''27''); })(), ''Removing the root in a tree with two nodes sets the second to be the root.'');'
- text: The <code>remove</code> method removes nodes with two children while maintaining the binary search tree structure.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== ''function'') { return false; }; test.add(1); test.add(4); test.add(3); test.add(7); test.add(9); test.add(11); test.add(14); test.add(15); test.add(19); test.add(50); test.remove(9); if (!test.isBinarySearchTree()) { return false; }; test.remove(11); if (!test.isBinarySearchTree()) { return false; }; test.remove(14); if (!test.isBinarySearchTree()) { return false; }; test.remove(19); if (!test.isBinarySearchTree()) { return false; }; test.remove(3); if (!test.isBinarySearchTree()) { return false; }; test.remove(50); if (!test.isBinarySearchTree()) { return false; }; test.remove(15); if (!test.isBinarySearchTree()) { return false; }; return (test.inorder().join('''') == ''147''); })(), ''The <code>remove</code> method removes nodes with two children while maintaining the binary search tree structure.'');'
- text: The root can be removed on a tree of three nodes.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.remove !== ''function'') { return false; }; test.add(100); test.add(50); test.add(300); test.remove(100); return (test.inorder().join('''') == 50300); })(), ''The root can be removed on a tree of three nodes.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
this.remove = function(value) {
if (this.root === null) {
return null;
}
var target;
var parent = null;
// find the target value and its parent
(function findValue(node = this.root) {
if (value == node.value) {
target = node;
} else if (value < node.value && node.left !== null) {
parent = node;
return findValue(node.left);
} else if (value < node.value && node.left === null) {
return null;
} else if (value > node.value && node.right !== null) {
parent = node;
return findValue(node.right);
} else {
return null;
}
}).bind(this)();
if (target === null) {
return null;
}
// count the children of the target to delete
var children = (target.left !== null ? 1 : 0) + (target.right !== null ? 1 : 0);
// case 1: target has no children
if (children === 0) {
if (target == this.root) {
this.root = null;
}
else {
if (parent.left == target) {
parent.left = null;
} else {
parent.right = null;
}
}
}
// case 2: target has one child
else if (children == 1) {
var newChild = (target.left !== null) ? target.left : target.right;
if (parent === null) {
target.value = newChild.value;
target.left = null;
target.right = null;
} else if (newChild.value < parent.value) {
parent.left = newChild;
} else {
parent.right = newChild;
}
target = null;
}
// case 3: target has two children, change code below this line
};
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,82 @@
---
id: 587d825d367417b2b2512c96
title: Depth-First Search
challengeType: 1
---
## Description
<section id='description'>
Similar to <dfn>breadth-first search</dfn>, here we will learn about another graph traversal algorithm called <dfn>depth-first search</dfn>.
Whereas the breadth-first search searches incremental edge lengths away from the source node, <dfn>depth-first search</dfn> first goes down a path of edges as far as it can.
Once it reaches one end of a path, the search will backtrack to the last node with an un-visited edge path and continue searching.
Visually, this is what the algorithm is doing where the top node is the starting point of the search.
<img class='img-responsive' src='https://camo.githubusercontent.com/aaad9e39961daf34d967c616edeb50abf3bf1235/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f372f37662f44657074682d46697273742d5365617263682e676966'>
A simple output of this algorithm is a list of nodes which are reachable from a given node. So when implementing this algorithm, you'll need to keep track of the nodes you visit.
</section>
## Instructions
<section id='instructions'>
Write a function <code>dfs()</code> that takes an undirected, adjacency matrix <code>graph</code> and a node label <code>root</code> as parameters. The node label will just be the numeric value of the node between <code>0</code> and <code>n - 1</code>, where <code>n</code> is the total number of nodes in the graph.
Your function should output an array of all nodes reachable from <code>root</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>1</code> should return an array with <code>0</code>, <code>1</code>, <code>2</code>, and <code>3</code>.'
testString: 'assert.sameMembers((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]; return dfs(graph, 1);})(), [0, 1, 2, 3], ''The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>1</code> should return an array with <code>0</code>, <code>1</code>, <code>2</code>, and <code>3</code>.'');'
- text: 'The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>1</code> should return an array with four elements.'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]; return dfs(graph, 1);})().length === 4, ''The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>1</code> should return an array with four elements.'');'
- text: 'The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> with a start node of <code>3</code> should return an array with <code>3</code>.'
testString: 'assert.sameMembers((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]; return dfs(graph, 3);})(), [3], ''The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> with a start node of <code>3</code> should return an array with <code>3</code>.'');'
- text: 'The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> with a start node of <code>3</code> should return an array with one element.'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]; return dfs(graph, 3);})().length === 1, ''The input graph <code>[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]</code> with a start node of <code>3</code> should return an array with one element.'');'
- text: 'The input graph <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>3</code> should return an array with <code>2</code> and <code>3</code>.'
testString: 'assert.sameMembers((function() { var graph = [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]; return dfs(graph, 3);})(), [2, 3], ''The input graph <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>3</code> should return an array with <code>2</code> and <code>3</code>.'');'
- text: 'The input graph <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>3</code> should return an array with two elements.'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]; return dfs(graph, 3);})().length === 2, ''The input graph <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>3</code> should return an array with two elements.'');'
- text: 'The input graph <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>0</code> should return an array with <code>0</code> and <code>1</code>.'
testString: 'assert.sameMembers((function() { var graph = [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]; return dfs(graph, 0);})(), [0, 1], ''The input graph <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>0</code> should return an array with <code>0</code> and <code>1</code>.'');'
- text: 'The input graph <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>0</code> should return an array with two elements.'
testString: 'assert((function() { var graph = [[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]; return dfs(graph, 0);})().length === 2, ''The input graph <code>[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]</code> with a start node of <code>0</code> should return an array with two elements.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function dfs(graph, root) {
}
var exDFSGraph = [
[0, 1, 0, 0],
[1, 0, 1, 0],
[0, 1, 0, 1],
[0, 0, 1, 0]
];
console.log(dfs(exDFSGraph, 3));
```
</div>
</section>
## Solution
<section id='solution'>
```js
function dfs(graph, root) { var stack = []; var tempV; var visited = []; var tempVNeighbors = []; stack.push(root); while (stack.length > 0) { tempV = stack.pop(); if (visited.indexOf(tempV) == -1) { visited.push(tempV); tempVNeighbors = graph[tempV]; for (var i = 0; i < tempVNeighbors.length; i++) { if (tempVNeighbors[i] == 1) { stack.push(i); }}}} return visited;}
```
</section>

View File

@ -0,0 +1,85 @@
---
id: 587d8257367417b2b2512c7d
title: Find the Minimum and Maximum Height of a Binary Search Tree
challengeType: 1
---
## Description
<section id='description'>
In the last challenge we described a scenario in which a tree could become unbalanced. To understand the concept of balance, let's take a look at another tree property: height. Height in a tree represents the distance from the root node to any given leaf node. Different paths in a highly branched tree structure may have different heights, but for a given tree there will be a minimum and maximum height. If the tree is balanced, these values will differ at most by one. This means that in a balanced tree, all the leaf nodes exist within the same level, or if they are not within the same level they are at most one level apart.
The property of balance is important for trees because it is what determines the efficiency of tree operations. As we explained in the last challenge, we face worst case time complexity for heavily unbalanced trees. Self-balancing trees are commonly used to account for this issue in trees with dynamic data sets. Common examples of these include AVL trees, red-black trees, and B-trees. These trees all contain additional internal logic which re-balance the tree when insertions or deletions create a state of imbalance.
Note: A similar property to height is depth, which refers to how far a given node is from the root node.
Instructions: Write two methods for our binary tree: <code>findMinHeight</code> and <code>findMaxHeight</code>. These methods should return an integer value for the minimum and maximum height within a given binary tree, respectively. If the node is empty let's assign it a height of <code>-1</code> (that's the base case). Finally, add a third method <code>isBalanced</code> which returns <code>true</code> or <code>false</code> depending on whether the tree is balanced or not. You can use the first two methods you just wrote to determine this.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The <code>BinarySearchTree</code> data structure exists.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() }; return (typeof test == ''object'')})(), ''The <code>BinarySearchTree</code> data structure exists.'');'
- text: The binary search tree has a method called <code>findMinHeight</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.findMinHeight == ''function'')})(), ''The binary search tree has a method called <code>findMinHeight</code>.'');'
- text: The binary search tree has a method called <code>findMaxHeight</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.findMaxHeight == ''function'')})(), ''The binary search tree has a method called <code>findMaxHeight</code>.'');'
- text: The binary search tree has a method called <code>isBalanced</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.isBalanced == ''function'')})(), ''The binary search tree has a method called <code>isBalanced</code>.'');'
- text: The <code>findMinHeight</code> method returns the minimum height of the tree.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.findMinHeight !== ''function'') { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); return (test.findMinHeight() == 1); })(), ''The <code>findMinHeight</code> method returns the minimum height of the tree.'');'
- text: The <code>findMaxHeight</code> method returns the maximum height of the tree.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.findMaxHeight !== ''function'') { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); return (test.findMaxHeight() == 5); })(), ''The <code>findMaxHeight</code> method returns the maximum height of the tree.'');'
- text: An empty tree returns a height of <code>-1</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.findMaxHeight !== ''function'') { return false; }; return (test.findMaxHeight() == -1); })(), ''An empty tree returns a height of <code>-1</code>.'');'
- text: The <code>isBalanced</code> method returns true if the tree is a balanced binary search tree.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.isBalanced !== ''function'') { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); return test.isBalanced(); })(), ''The <code>isBalanced</code> method returns true if the tree is a balanced binary search tree.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,84 @@
---
id: 587d8256367417b2b2512c7a
title: Find the Minimum and Maximum Value in a Binary Search Tree
challengeType: 1
---
## Description
<section id='description'>
This series of challenges will introduce the tree data structure. Trees are an important and versatile data structure in computer science. Of course, their name comes from the fact that when visualized they look much like the trees we are familiar with in the natural world. A tree data structure begins with one node, typically referred to as the root, and from here branches out to additional nodes, each of which may have more child nodes, and so on and so forth. The data structure is usually visualized with the root node at the top; you can think of it as a natural tree flipped upside down.
First, let's describe some common terminology we will encounter with trees. The root node is the top of the tree. Data points in the tree are called nodes. Nodes with branches leading to other nodes are referred to as the parent of the node the branch leads to (the child). Other more complicated familial terms apply as you might expect. A subtree refers to all the descendants of a particular node, branches may be referred to as edges, and leaf nodes are nodes at the end of the tree that have no children. Finally, note that trees are inherently recursive data structures. That is, any children of a node are parents of their own subtree, and so on. The recursive nature of trees is important to understand when designing algorithms for common tree operations.
To begin, we will discuss a particular type of a tree, the binary tree. In fact, we will actually discuss a particular binary tree, a binary search tree. Let's describe what this means. While the tree data structure can have any number of branches at a single node, a binary tree can only have two branches for every node. Furthermore, a binary search tree is ordered with respect to the child subtrees, such that the value of each node in the left subtree is less than or equal to the value of the parent node, and the value of each node in the right subtree is greater than or equal to the value of the parent node. It's very helpful to visualize this relationship in order to understand it better:
<div style='width: 100%; display: flex; justify-content: center; align-items: center;'><img style='width: 100%; max-width: 350px;' src='https://user-images.githubusercontent.com/18563015/32136009-1e665d98-bbd6-11e7-9133-63184f9f9182.png'></div>
Now this ordered relationship is very easy to see. Note that every value to the left of 8, the root node, is less than 8, and every value to the right is greater than 8. Also notice that this relationship applies to each of the subtrees as well. For example, the first left child is a subtree. 3 is the parent node, and it has exactly two child nodes &mdash; by the rules governing binary search trees, we know without even looking that the left child of this node (and any of its children) will be less than 3, and the right child (and any of its children) will be greater than 3 (but also less than the structure's root value), and so on.
Binary search trees are very common and useful data structures because they provide logarithmic time in the average case for several common operations such as lookup, insertion, and deletion.
Instructions: We'll start simple. We've defined the skeleton of a binary search tree structure here in addition to a function to create nodes for our tree. Observe that each node may have a left and right value. These will be assigned child subtrees if they exist. In our binary search tree, define two methods, <code>findMin</code> and <code>findMax</code>. These methods should return the minimum and maximum value held in the binary search tree (don't worry about adding values to the tree for now, we have added some in the background). If you get stuck, reflect on the invariant that must be true for binary search trees: each left subtree is less than or equal to its parent and each right subtree is greater than or equal to its parent. Let's also say that our tree can only store integer values. If the tree is empty, either method should return <code>null</code>.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The <code>BinarySearchTree</code> data structure exists.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() }; return (typeof test == ''object'')})(), ''The <code>BinarySearchTree</code> data structure exists.'');'
- text: The binary search tree has a method called <code>findMin</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.findMin == ''function'')})(), ''The binary search tree has a method called <code>findMin</code>.'');'
- text: The binary search tree has a method called <code>findMax</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.findMax == ''function'')})(), ''The binary search tree has a method called <code>findMax</code>.'');'
- text: The <code>findMin</code> method returns the minimum value in the binary search tree.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.findMin !== ''function'') { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); return test.findMin() == 1; })(), ''The <code>findMin</code> method returns the minimum value in the binary search tree.'');'
- text: The <code>findMax</code> method returns the maximum value in the binary search tree.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.findMax !== ''function'') { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); return test.findMax() == 87; })(), ''The <code>findMax</code> method returns the maximum value in the binary search tree.'');'
- text: The <code>findMin</code> and <code>findMax</code> methods return <code>null</code> for an empty tree.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.findMin !== ''function'') { return false; }; if (typeof test.findMax !== ''function'') { return false; }; return (test.findMin() == null && test.findMax() == null) })(), ''The <code>findMin</code> and <code>findMax</code> methods return <code>null</code> for an empty tree.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,74 @@
---
id: 587d825b367417b2b2512c8c
title: Implement Heap Sort with a Min Heap
challengeType: 1
---
## Description
<section id='description'>
Now that we can add and remove elements let's see some of the applications heaps can be used for. Heaps are commonly used to implement priority queues because they always store an item of greatest or least value in first position. In addition, they are used to implement a sorting algorithm called heap sort. We'll see how to do this here. Heap sort uses a min heap, the reverse of a max heap. A min heap always stores the element of least value in the root position.
Heap sort works by taking an unsorted array, adding each item in the array into a min heap, and then extracting every item out of the min heap into a new array. The min heap structure ensures that the new array will contain the original items in least to greatest order. This is one of the most efficient sorting algorithms with average and worst case performance of O(nlog(n)).
Instructions: Let's implement heap sort with a min heap. Feel free to adapt your max heap code here. Create an object MinHeap with insert, remove, and sort methods. The sort method should return an array of all the elements in the min heap sorted from smallest to largest.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The MinHeap data structure exists.
testString: 'assert((function() { var test = false; if (typeof MinHeap !== ''undefined'') { test = new MinHeap() }; return (typeof test == ''object'')})(), ''The MinHeap data structure exists.'');'
- text: MinHeap has a method called insert.
testString: 'assert((function() { var test = false; if (typeof MinHeap !== ''undefined'') { test = new MinHeap() } else { return false; }; return (typeof test.insert == ''function'')})(), ''MinHeap has a method called insert.'');'
- text: MinHeap has a method called remove.
testString: 'assert((function() { var test = false; if (typeof MinHeap !== ''undefined'') { test = new MinHeap() } else { return false; }; return (typeof test.remove == ''function'')})(), ''MinHeap has a method called remove.'');'
- text: MinHeap has a method called sort.
testString: 'assert((function() { var test = false; if (typeof MinHeap !== ''undefined'') { test = new MinHeap() } else { return false; }; return (typeof test.sort == ''function'')})(), ''MinHeap has a method called sort.'');'
- text: The sort method returns an array containing all items added to the min heap in sorted order.
testString: 'assert((function() { var test = false; if (typeof MinHeap !== ''undefined'') { test = new MinHeap() } else { return false; }; test.insert(3); test.insert(12); test.insert(5); test.insert(10); test.insert(1); test.insert(27); test.insert(42); test.insert(57); test.insert(5); var result = test.sort(); return (isSorted(result)); })(), ''The sort method returns an array containing all items added to the min heap in sorted order.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
// check if array is sorted
function isSorted(arr) {
var check = (i) => (i == arr.length - 1) ? true : (arr[i] > arr[i + 1]) ? false : check(i + 1);
return check(0);
}
// generate a randomly filled array
var array = new Array();
(function createArray(size = 5) {
array.push(+(Math.random() * 100).toFixed(0));
return (size > 1) ? createArray(size - 1) : undefined;
})(25);
var MinHeap = function() {
// change code below this line
// change code above this line
};
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,74 @@
---
id: 587d8256367417b2b2512c79
title: Incidence Matrix
challengeType: 1
---
## Description
<section id='description'>
Yet another way to represent a graph is to put it in an <dfn>incidence matrix.</dfn>
An <dfn>incidence matrix</dfn> is a two-dimensional (2D) array. Generally speaking, an incidence matrix relates two different classes of objects between its two dimensions. This kind of matrix is similar to an adjacency matrix. However, the rows and columns mean something else here.
In graphs, we have edges and nodes. These will be our "two different classes of objects". This matrix will have the rows be the nodes and columns be the edges. This means that we can have an uneven number of rows and columns.
Each column will represent a unique edge. Also, each edge connects two nodes. To show that there is an edge between two nodes, you will put a 1 in the two rows of a particular column. Below is a 3 node graph with one edge between node 1 and node 3.
<blockquote> 1<br> ---<br>1 | 1<br>2 | 0<br>3 | 1</blockquote>
Here is an example of an <code>incidence matrix</code> with 4 edges and 4 nodes. Remember, the columns are the edges and rows are the nodes themselves.
<blockquote> 1 2 3 4<br> --------<br>1 | 0 1 1 1<br>2 | 1 1 0 0<br>3 | 1 0 0 1<br>4 | 0 0 1 0</blockquote>
Below is a JavaScript implementation of the same thing.
<blockquote>var incMat = [<br> [0, 1, 1, 1],<br> [1, 1, 0, 0],<br> [1, 0, 0, 1],<br> [0, 0, 1, 0]<br>];</blockquote>
To make a directed graph, use <code>-1</code> for an edge leaving a particular node and <code>1</code> for an edge entering a node.
<blockquote>var incMatDirected = [<br> [ 0, -1, 1, -1],<br> [-1, 1, 0, 0],<br> [ 1, 0, 0, 1],<br> [ 0, 0, -1, 0]<br>];</blockquote>
Graphs can also have <dfn>weights</dfn> on their edges. So far, we have <dfn>unweighted</dfn> edges where just the presence and lack of edge is binary (<code>0</code> or <code>1</code>). You can have different weights depending on your application. A different weight is represented as numbers greater than 1.
</section>
## Instructions
<section id='instructions'>
Create an incidence matrix of an undirected graph with five nodes and four edges. This matrix should be in a multi-dimensional array.
These five nodes have relationships following relationships. The first edge is between the first and second node. The second edge is between the second and third node. The third edge is between the third and fifth node. And four edge is between the fourth and second node. All edge weights are one and the edge order matters.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>incMatUndirected</code> should only contain five nodes.
testString: 'assert((incMatUndirected.length === 5) && incMatUndirected.map(function(x) { return x.length === 4 }).reduce(function(a, b) { return a && b }) , ''<code>incMatUndirected</code> should only contain five nodes.'');'
- text: There should be a first edge between the first and second node.
testString: 'assert((incMatUndirected[0][0] === 1) && (incMatUndirected[1][0] === 1), ''There should be a first edge between the first and second node.'');'
- text: There should be a second edge between the second and third node.
testString: 'assert((incMatUndirected[1][1] === 1) && (incMatUndirected[2][1] === 1), ''There should be a second edge between the second and third node.'');'
- text: There should be a third edge between the third and fifth node.
testString: 'assert((incMatUndirected[2][2] === 1) && (incMatUndirected[4][2] === 1), ''There should be a third edge between the third and fifth node.'');'
- text: There should be a fourth edge between the second and fourth node.
testString: 'assert((incMatUndirected[1][3] === 1) && (incMatUndirected[3][3] === 1), ''There should be a fourth edge between the second and fourth node.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var incMatUndirected = [
];
```
</div>
</section>
## Solution
<section id='solution'>
```js
var incMatUndirected = [[1, 0, 0, 0],[1, 1, 0, 1],[0, 1, 1, 0],[0, 0, 0, 1],[0, 0, 1, 0]];
```
</section>

View File

@ -0,0 +1,74 @@
---
id: 587d825a367417b2b2512c8a
title: Insert an Element into a Max Heap
challengeType: 1
---
## Description
<section id='description'>
Now we will move on to another tree data structure, the binary heap. A binary heap is a partially ordered binary tree which satisfies the heap property. The heap property specifies a relationship between parent and child nodes. You may have a max heap, in which all parent nodes are greater than or equal to their child nodes, or a min heap, in which the reverse is true. Binary heaps are also complete binary trees. This means that all levels of the tree are fully filled and if the last level is partially filled it is filled from left to right.
While binary heaps may be implemented as tree structures with nodes that contain left and right references, the partial ordering according to the heap property allows us to represent the heap with an array. The parent-children relationship is what we're interested in and with simple arithmetic we can compute the children of any parent and the parent of any child node.
For instance, consider this array representation of a binary min heap:
<code>[ 6, 22, 30, 37, 63, 48, 42, 76 ]</code>
The root node is the first element, 6. Its children are 22 and 30. If we look at the relationship between the array indices of these values, for index i the children are 2 * i + 1 and 2 * i + 2. Similarly, the element at index 0 is the parent of these two children at indices 1 and 2. More generally, we can find the parent of a node at any index with the following: (i - 1) / 2. These patterns will hold true as the binary tree grows to any size. Finally, we can make a slight adjustment to make this arithmetic even easier by skipping the first element in the array. Doing this creates the following relationship for any element at a given index i:
Example Array representation:
<code>[ null, 6, 22, 30, 37, 63, 48, 42, 76 ]</code>
An element's left child: i * 2
An element's right child: i * 2 + 1
An element's parent: i / 2
Once you wrap your head around the math, using an array representation is very useful because node locations can be quickly determined with this arithmetic and memory usage is diminished because you don't need to maintain references to child nodes.
Instructions: Here we will create a max heap. Start by just creating an insert method which adds elements to our heap. During insertion, it is important to always maintain the heap property. For a max heap this means the root element should always have the greatest value in the tree and all parent nodes should be greater than their children. For an array implementation of a heap, this is typically accomplished in three steps:
Add the new element to the end of the array.
If the element is larger than its parents, switch them.
Continue switching until the new element is either smaller than its parent or you reach the root of the tree.
Finally, add a print method which returns an array of all the items that have been added to the heap.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The MaxHeap data structure exists.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== ''undefined'') { test = new MaxHeap() }; return (typeof test == ''object'')})(), ''The MaxHeap data structure exists.'');'
- text: MaxHeap has a method called insert.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== ''undefined'') { test = new MaxHeap() } else { return false; }; return (typeof test.insert == ''function'')})(), ''MaxHeap has a method called insert.'');'
- text: MaxHeap has a method called print.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== ''undefined'') { test = new MaxHeap() } else { return false; }; return (typeof test.print == ''function'')})(), ''MaxHeap has a method called print.'');'
- text: The insert method adds elements according to the max heap property.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== ''undefined'') { test = new MaxHeap() } else { return false; }; test.insert(50); test.insert(100); test.insert(700); test.insert(32); test.insert(51); let result = test.print(); return ((result.length == 5) ? result[0] == 700 : result[1] == 700) })(), ''The insert method adds elements according to the max heap property.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var MaxHeap = function() {
// change code below this line
// change code above this line
};
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,74 @@
---
id: 587d8259367417b2b2512c83
title: Invert a Binary Tree
challengeType: 1
---
## Description
<section id='description'>
Here will we create a function to invert a binary tree. Given a binary tree, we want to produce a new tree that is equivalently the mirror image of this tree. Running an inorder traversal on an inverted tree will explore the nodes in reverse order when compared to the inorder traversal of the original tree. Write a method to do this called <code>invert</code> on our binary tree. Calling this method should invert the current tree structure. Ideally, we would like to do this in-place in linear time. That is, we only visit each node once and we modify the existing tree structure as we go, without using any additional memory. Good luck!
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The <code>BinarySearchTree</code> data structure exists.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() }; return (typeof test == ''object'')})(), ''The <code>BinarySearchTree</code> data structure exists.'');'
- text: The binary search tree has a method called <code>invert</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.invert == ''function'')})(), ''The binary search tree has a method called <code>invert</code>.'');'
- text: The <code>invert</code> method correctly inverts the tree structure.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.invert !== ''function'') { return false; }; test.add(4); test.add(1); test.add(7); test.add(87); test.add(34); test.add(45); test.add(73); test.add(8); test.invert(); return test.inorder().join('''') == ''877345348741''; })(), ''The <code>invert</code> method correctly inverts the tree structure.'');'
- text: Inverting an empty tree returns <code>null</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.invert !== ''function'') { return false; }; return (test.invert() == null); })(), ''Inverting an empty tree returns <code>null</code>.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,63 @@
---
id: 587d8250367417b2b2512c5e
title: Learn how a Stack Works
challengeType: 1
---
## Description
<section id='description'>
You are probably familiar with stack of books on your table. You have likely used the undo feature of a text editor. You are also probably used to hitting the back button on your phone to go back to the previous view in your app.
You know what they all have in common? They all store the data in a way so that you can traverse backwards.
The topmost book in the stack was the one that was put there last. If you remove that book from your stack's top, you would expose the book that was put there before the last book and so on.
If you think about it, in all the above examples, you are getting <dfn>Last-In-First-Out</dfn> type of service. We will try to mimic this with our code.
This data storage scheme is called a <dfn>Stack</dfn>. In particular, we would have to implement the <code>push()</code> method that pushes JavaScript objects at the top of the stack; and <code>pop()</code> method, that removes the JavaScript object that's at the top of the stack at the current moment.
</section>
## Instructions
<section id='instructions'>
Here we have a stack of homework assignments represented as an array: <code>"BIO12"</code> is at the base, and <code>"PSY44"</code> is at the top of the stack.
Modify the given array and treat it like a <code>stack</code> using the JavaScript methods mentioned above. Remove the top element <code>"PSY44"</code> from the stack. Then add <code>"CS50"</code> to be the new top element of the stack.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>homeworkStack</code> should only contain 4 elements.
testString: 'assert(homeworkStack.length === 4, ''<code>homeworkStack</code> should only contain 4 elements.'');'
- text: The last element in <code>homeworkStack</code> should be <code>"CS50"</code>.
testString: 'assert(homeworkStack[3] === ''CS50'', ''The last element in <code>homeworkStack</code> should be <code>"CS50"</code>.'');'
- text: <code>homeworkStack</code> should not contain <code>"PSY44"</code>.
testString: 'assert(homeworkStack.indexOf(''PSY44'') === -1, ''<code>homeworkStack</code> should not contain <code>"PSY44"</code>.'');'
- text: The initial declaration of the <code>homeworkStack</code> should not be changed.
testString: 'assert(code.match(/=/g).length === 1 && /homeworkStack\s*=\s*\["BIO12"\s*,\s*"HIS80"\s*,\s*"MAT122"\s*,\s*"PSY44"\]/.test(code), ''The initial declaration of the <code>homeworkStack</code> should not be changed.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var homeworkStack = ["BIO12","HIS80","MAT122","PSY44"];
// Only change code below this line
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,202 @@
{
"name": "Data Structures",
"dashedName": "data-structures",
"order": 2,
"time": "",
"template": "",
"required": [],
"superBlock": "coding-interview-prep",
"superOrder": 8,
"challengeOrder": [
[
"587d8253367417b2b2512c6a",
"Typed Arrays"
],
[
"587d8250367417b2b2512c5e",
"Learn how a Stack Works"
],
[
"587d8250367417b2b2512c5f",
"Create a Stack Class"
],
[
"587d8250367417b2b2512c60",
"Create a Queue Class"
],
[
"587d8255367417b2b2512c74",
"Create a Priority Queue Class"
],
[
"587d8255367417b2b2512c75",
"Create a Circular Queue"
],
[
"8d1323c8c441eddfaeb5bdef",
"Create a Set Class"
],
[
"587d8253367417b2b2512c6b",
"Remove from a Set"
],
[
"8d1923c8c441eddfaeb5bdef",
"Size of the Set"
],
[
"587d8253367417b2b2512c6c",
"Perform a Union on Two Sets"
],
[
"587d8253367417b2b2512c6d",
"Perform an Intersection on Two Sets of Data"
],
[
"587d8254367417b2b2512c6e",
"Perform a Difference on Two Sets of Data"
],
[
"587d8254367417b2b2512c6f",
"Perform a Subset Check on Two Sets of Data"
],
[
"587d8254367417b2b2512c70",
"Create and Add to Sets in ES6"
],
[
"587d8254367417b2b2512c71",
"Remove items from a set in ES6"
],
[
"587d8255367417b2b2512c72",
"Use .has and .size on an ES6 Set"
],
[
"587d8255367417b2b2512c73",
"Use Spread and Notes for ES5 Set() Integration"
],
[
"8d5823c8c441eddfaeb5bdef",
"Create a Map Data Structure"
],
[
"587d825b367417b2b2512c8d",
"Create an ES6 JavaScript Map"
],
[
"587d825b367417b2b2512c8e",
"Create a Hash Table"
],
[
"587d8251367417b2b2512c61",
"Work with Nodes in a Linked List"
],
[
"587d8251367417b2b2512c62",
"Create a Linked List Class"
],
[
"587d8251367417b2b2512c63",
"Remove Elements from a Linked List"
],
[
"587d8251367417b2b2512c64",
"Search within a Linked List"
],
[
"587d8251367417b2b2512c65",
"Remove Elements from a Linked List by Index"
],
[
"587d8252367417b2b2512c67",
"Add Elements at a Specific Index in a Linked List"
],
[
"587d825a367417b2b2512c87",
"Create a Doubly Linked List"
],
[
"587d825a367417b2b2512c88",
"Reverse a Doubly Linked List"
],
[
"587d8256367417b2b2512c7a",
"Find the Minimum and Maximum Value in a Binary Search Tree"
],
[
"587d8257367417b2b2512c7b",
"Add a New Element to a Binary Search Tree"
],
[
"587d8257367417b2b2512c7c",
"Check if an Element is Present in a Binary Search Tree"
],
[
"587d8257367417b2b2512c7d",
"Find the Minimum and Maximum Height of a Binary Search Tree"
],
[
"587d8257367417b2b2512c7e",
"Use Depth First Search in a Binary Search Tree"
],
[
"587d8258367417b2b2512c7f",
"Use Breadth First Search in a Binary Search Tree"
],
[
"587d8258367417b2b2512c80",
"Delete a Leaf Node in a Binary Search Tree"
],
[
"587d8258367417b2b2512c81",
"Delete a Node with One Child in a Binary Search Tree"
],
[
"587d8258367417b2b2512c82",
"Delete a Node with Two Children in a Binary Search Tree"
],
[
"587d8259367417b2b2512c83",
"Invert a Binary Tree"
],
[
"587d8259367417b2b2512c84",
"Create a Trie Search Tree"
],
[
"587d825a367417b2b2512c8a",
"Insert an Element into a Max Heap"
],
[
"587d825b367417b2b2512c8b",
"Remove an Element from a Max Heap"
],
[
"587d825b367417b2b2512c8c",
"Implement Heap Sort with a Min Heap"
],
[
"587d8256367417b2b2512c77",
"Adjacency List"
],
[
"587d8256367417b2b2512c78",
"Adjacency Matrix"
],
[
"587d8256367417b2b2512c79",
"Incidence Matrix"
],
[
"587d825c367417b2b2512c90",
"Breadth-First Search"
],
[
"587d825d367417b2b2512c96",
"Depth-First Search"
]
],
"helpRoom": "HelpJavaScript",
"fileName": "08-coding-interview-prep/data-structures.json"
}

View File

@ -0,0 +1,113 @@
---
id: 587d8254367417b2b2512c6e
title: Perform a Difference on Two Sets of Data
challengeType: 1
---
## Description
<section id='description'>
In this exercise we are going to perform a difference on 2 sets of data. We will create a method on our <code>Set</code> data structure called <code>difference</code>. A difference of sets should compare two sets and return the items present in the first set that are absent in the second. This method should take another <code>Set</code> as an argument and return the <code>difference</code> of the two sets.
For example, if <code>setA = ['a','b','c']</code> and <code>setB = ['a','b','d','e']</code>, then the difference of setA and setB is: <code>setA.difference(setB) = ['c']</code>.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>Set</code> class should have a <code>difference</code> method.
testString: 'assert(function(){var test = new Set(); return (typeof test.difference === ''function'')}, ''Your <code>Set</code> class should have a <code>difference</code> method.'');'
- text: The proper collection was returned
testString: 'assert(function(){var setA = new Set(); var setB = new Set(); setA.add(''a''); setA.add(''b''); setA.add(''c''); setB.add(''c''); setB.add(''d''); var differenceSetAB = setA.difference(setB); return (differenceSetAB.size() === 2) && (differenceSetAB.values() === [ ''a'', ''b'' ])}, ''The proper collection was returned'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Set() {
// the var collection will hold the set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
// this method will add an element to the set
this.add = function(element) {
if(!this.has(element)){
collection.push(element);
return true;
}
return false;
};
// this method will remove an element from a set
this.remove = function(element) {
if(this.has(element)){
var index = collection.indexOf(element);
collection.splice(index,1);
return true;
}
return false;
};
// this method will return the size of the collection
this.size = function() {
return collection.length;
};
// this method will return the union of two sets
this.union = function(otherSet) {
var unionSet = new Set();
var firstSet = this.values();
var secondSet = otherSet.values();
firstSet.forEach(function(e){
unionSet.add(e);
});
secondSet.forEach(function(e){
unionSet.add(e);
});
return unionSet;
};
// this method will return the intersection of two sets as a new set
this.intersection = function(otherSet) {
var intersectionSet = new Set();
var firstSet = this.values();
firstSet.forEach(function(e){
if(otherSet.has(e)){
intersectionSet.add(e);
}
});
return intersectionSet;
};
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function Set() {var collection = []; this.has = function(e){return(collection.indexOf(e) !== -1);};this.values = function() {return collection;};this.add = function(element) {if (!this.has(element)) {collection.push(element);return true;} else {return false;}};this.remove = function(element) {if(this.has(element)) {var i = collection.indexOf(element);collection.splice(i, 1);return true;}return false;};this.size = function() {return collection.length;};this.union = function(set) {var u = new Set();var c = this.values();var s = set.values();c.forEach(function(element){u.add(element);});s.forEach(function(element){u.add(element);});return u;};this.intersection = function(set) {var i = new Set();var c = this.values();c.forEach(function(element){if(s.has(element)) i.add(element);});};this.difference = function(set) {var d = new Set();var c = this.values();c.forEach(function(e){if(!set.has(e)) d.add(e);});};}
```
</section>

View File

@ -0,0 +1,132 @@
---
id: 587d8254367417b2b2512c6f
title: Perform a Subset Check on Two Sets of Data
challengeType: 1
---
## Description
<section id='description'>
In this exercise we are going to perform a subset test on 2 sets of data. We will create a method on our <code>Set</code> data structure called <code>subset</code>. This will compare the first set, against the second and if the first set is fully contained within the Second then it will return true.
For example, if <code>setA = ['a','b']</code> and <code>setB = ['a','b','c','d']</code>, then the subset of setA and setB is: <code>setA.subset(setB)</code> should be <code>true</code>.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>Set</code> class should have a <code>union</code> method.
testString: 'assert(function(){var test = new Set(); return (typeof test.subset === ''function'')}, ''Your <code>Set</code> class should have a <code>union</code> method.'');'
- text: The first Set() was contained in the second Set
testString: 'assert(function(){var setA = new Set(); var setB = new Set(); setA.add(''a''); setB.add(''b''); setB.add(''c''); setB.add(''a''); setB.add(''d''); var subsetSetAB = setA.subset(setB);return (subsetSetAB === true)}, ''The first Set() was contained in the second Set'');'
- text: '<code>[''a'', ''b''].subset([''a'', ''b'', ''c'', ''d''])</code> should return <code>true</code>")'
testString: 'assert(function(){var setA = new Set(); var setB = new Set(); setA.add(''a''); setA.add(''b''); setB.add(''a''); setB.add(''b''); setB.add(''c''); setB.add(''d''); var subsetSetAB = setA.subset(setB); return (subsetSetAB === true)}, "<code>[''a'', ''b''].subset([''a'', ''b'', ''c'', ''d''])</code> should return <code>true</code>");'
- text: '<code>[''a'', ''b'', ''c''].subset([''a'', ''b''])</code> should return <code>false</code>")'
testString: 'assert(function(){var setA = new Set(); var setB = new Set(); setA.add(''a''); setA.add(''b''); setA.add(''c''); setB.add(''a''); setB.add(''b''); var subsetSetAB = setA.subset(setB); return (subsetSetAB === false)}, "<code>[''a'', ''b'', ''c''].subset([''a'', ''b''])</code> should return <code>false</code>");'
- text: '<code>[].subset([])</code> should return <code>true</code>'
testString: 'assert(function(){var setA = new Set(); var setB = new Set(); var subsetSetAB = setA.subset(setB); return (subsetSetAB === true)}, ''<code>[].subset([])</code> should return <code>true</code>'');'
- text: '<code>[''a'', ''b''].subset([''c'', ''d''])</code> should return <code>false</code>")'
testString: 'assert(function(){var setA = new Set(); var setB = new Set(); setA.add(''a''); setA.add(''b''); setB.add(''c''); setB.add(''d''); var subsetSetAB = setA.subset(setB); return (subsetSetAB === false)}, "<code>[''a'', ''b''].subset([''c'', ''d''])</code> should return <code>false</code>");'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Set() {
// the var collection will hold the set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
// this method will add an element to the set
this.add = function(element) {
if(!this.has(element)){
collection.push(element);
return true;
}
return false;
};
// this method will remove an element from a set
this.remove = function(element) {
if(this.has(element)){
var index = collection.indexOf(element);
collection.splice(index,1);
return true;
}
return false;
};
// this method will return the size of the collection
this.size = function() {
return collection.length;
};
// this method will return the union of two sets
this.union = function(otherSet) {
var unionSet = new Set();
var firstSet = this.values();
var secondSet = otherSet.values();
firstSet.forEach(function(e){
unionSet.add(e);
});
secondSet.forEach(function(e){
unionSet.add(e);
});
return unionSet;
};
// this method will return the intersection of two sets as a new set
this.intersection = function(otherSet) {
var intersectionSet = new Set();
var firstSet = this.values();
firstSet.forEach(function(e){
if(otherSet.has(e)){
intersectionSet.add(e);
}
});
return intersectionSet;
};
// this method will return the difference of two sets as a new set
this.difference = function(otherSet) {
var differenceSet = new Set();
var firstSet = this.values();
firstSet.forEach(function(e){
if(!otherSet.has(e)){
differenceSet.add(e);
}
});
return differenceSet;
};
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function Set() {var collection = []; this.has = function(e){return(collection.indexOf(e) !== -1);};this.values = function() {return collection;};this.add = function(element) {if (!this.has(element)) {collection.push(element);return true;} else {return false;}};this.remove = function(element) {if(this.has(element)) {var i = collection.indexOf(element);collection.splice(i, 1);return true;}return false;};this.size = function() {return collection.length;};this.union = function(set) {var u = new Set();var c = this.values();var s = set.values();c.forEach(function(element){u.add(element);});s.forEach(function(element){u.add(element);});return u;};this.intersection = function(set) {var i = new Set();var c = this.values();c.forEach(function(element){if(s.has(element)) i.add(element);});};this.difference = function(set) {var d = new Set();var c = this.values();c.forEach(function(e){if(!set.has(e)) d.add(e);});};this.subset = function(set) {var isSubset = true;var c = this.values();c.forEach(function(e){if(!set.has(e)) isSubset = false;});return isSubset;};}
```
</section>

View File

@ -0,0 +1,90 @@
---
id: 587d8253367417b2b2512c6c
title: Perform a Union on Two Sets
challengeType: 1
---
## Description
<section id='description'>
In this exercise we are going to perform a union on two sets of data. We will create a method on our <code>Set</code> data structure called <code>union</code>. This method should take another <code>Set</code> as an argument and return the <code>union</code> of the two sets, excluding any duplicate values.
For example, if <code>setA = ['a','b','c']</code> and <code>setB = ['a','b','d','e']</code>, then the union of setA and setB is: <code>setA.union(setB) = ['a', 'b', 'c', 'd', 'e']</code>.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>Set</code> class should have a <code>union</code> method.
testString: 'assert((function(){var test = new Set(); return (typeof test.union === ''function'')})(), ''Your <code>Set</code> class should have a <code>union</code> method.'');'
- text: The proper collection was returned
testString: 'assert((function(){var setA = new Set(); var setB = new Set(); setA.add(''a''); setA.add(''b''); setA.add(''c''); setB.add(''c''); setB.add(''d''); var unionSetAB = setA.union(setB); var final = unionSetAB.values(); return (final.indexOf(''a'') !== -1 && final.indexOf(''b'') !== -1 && final.indexOf(''c'') !== -1 && final.indexOf(''d'') !== -1 && final.length === 4)})(), ''The proper collection was returned'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Set() {
// the var collection will hold the set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
// this method will add an element to the set
this.add = function(element) {
if(!this.has(element)){
collection.push(element);
return true;
}
return false;
};
// this method will remove an element from a set
this.remove = function(element) {
if(this.has(element)){
var index = collection.indexOf(element);
collection.splice(index,1);
return true;
}
return false;
};
// this method will return the size of the set
this.size = function() {
return collection.length;
};
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function Set() {var collection = []; this.has = function(e){return(collection.indexOf(e) !== -1);};this.values = function() {return collection;};this.add = function(element) {if (!this.has(element)) {collection.push(element);return true;} else {return false;}};this.remove = function(element) {if(this.has(element)) {var i = collection.indexOf(element);collection.splice(i, 1);return true;}return false;};this.size = function() {return collection.length;};this.union = function(set) {var u = new Set();var c = this.values();var s = set.values();c.forEach(function(element){u.add(element);});s.forEach(function(element){u.add(element);});return u;};}
```
</section>

View File

@ -0,0 +1,102 @@
---
id: 587d8253367417b2b2512c6d
title: Perform an Intersection on Two Sets of Data
challengeType: 1
---
## Description
<section id='description'>
In this exercise we are going to perform an intersection on 2 sets of data. We will create a method on our <code>Set</code> data structure called <code>intersection</code>. An intersection of sets represents all values that are common to two or more sets. This method should take another <code>Set</code> as an argument and return the <code>intersection</code> of the two sets.
For example, if <code>setA = ['a','b','c']</code> and <code>setB = ['a','b','d','e']</code>, then the intersection of setA and setB is: <code>setA.intersection(setB) = ['a', 'b']</code>.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>Set</code> class should have a <code>intersection</code> method.
testString: 'assert(function(){var test = new Set(); return (typeof test.intersection === ''function'')}, ''Your <code>Set</code> class should have a <code>intersection</code> method.'');'
- text: The proper collection was returned
testString: 'assert(function(){ var setA = new Set(); var setB = new Set(); setA.add(''a''); setA.add(''b''); setA.add(''c''); setB.add(''c''); setB.add(''d''); var intersectionSetAB = setA.intersection(setB); return (intersectionSetAB.size() === 1 && intersectionSetAB.values()[0] === ''c'')}, ''The proper collection was returned'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Set() {
// the var collection will hold the set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
// this method will add an element to the set
this.add = function(element) {
if(!this.has(element)){
collection.push(element);
return true;
}
return false;
};
// this method will remove an element from a set
this.remove = function(element) {
if(this.has(element)){
var index = collection.indexOf(element);
collection.splice(index,1);
return true;
}
return false;
};
// this method will return the size of the collection
this.size = function() {
return collection.length;
};
// this method will return the union of two sets
this.union = function(otherSet) {
var unionSet = new Set();
var firstSet = this.values();
var secondSet = otherSet.values();
firstSet.forEach(function(e){
unionSet.add(e);
});
secondSet.forEach(function(e){
unionSet.add(e);
});
return unionSet;
};
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function Set() {var collection = []; this.has = function(e){return(collection.indexOf(e) !== -1);};this.values = function() {return collection;};this.add = function(element) {if (!this.has(element)) {collection.push(element);return true;} else {return false;}};this.remove = function(element) {if(this.has(element)) {var i = collection.indexOf(element);collection.splice(i, 1);return true;}return false;};this.size = function() {return collection.length;};this.union = function(set) {var u = new Set();var c = this.values();var s = set.values();c.forEach(function(element){u.add(element);});s.forEach(function(element){u.add(element);});return u;};this.intersection = function(set) {var i = new Set();var c = this.values();c.forEach(function(element){if(s.has(element)) i.add(element);});};}
```
</section>

View File

@ -0,0 +1,65 @@
---
id: 587d825b367417b2b2512c8b
title: Remove an Element from a Max Heap
challengeType: 1
---
## Description
<section id='description'>
Now that we can add elements to our heap let's see how we can remove elements. Removing and inserting elements both require similar logic. In a max heap you will usually want to remove the greatest value, so this involves simply extracting it from the root of our tree. This will break the heap property of our tree, so we must reestablish it in some way. Typically, for a max heap this is done in the following way:
Move the last element in the heap into the root position.
If either child of the root is greater than it, swap the root with the child of greater value.
Continue swapping until the parent is greater than both children, or you reach the last level in the tree.
Instructions: Add a method to our max heap called remove. This method should return the greatest value that has been added to our max heap and remove it from the heap. It should also reorder the heap so the heap property is maintained. After removing an element, the next greatest element remaining in the heap should become the root. Add your insert method again here as well.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The MaxHeap data structure exists.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== ''undefined'') { test = new MaxHeap() }; return (typeof test == ''object'')})(), ''The MaxHeap data structure exists.'');'
- text: MaxHeap has a method called print.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== ''undefined'') { test = new MaxHeap() } else { return false; }; return (typeof test.print == ''function'')})(), ''MaxHeap has a method called print.'');'
- text: MaxHeap has a method called insert.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== ''undefined'') { test = new MaxHeap() } else { return false; }; return (typeof test.insert == ''function'')})(), ''MaxHeap has a method called insert.'');'
- text: MaxHeap has a method called remove.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== ''undefined'') { test = new MaxHeap() } else { return false; }; return (typeof test.remove == ''function'')})(), ''MaxHeap has a method called remove.'');'
- text: The remove method removes the greatest element from the max heap while maintaining the max heap property.
testString: 'assert((function() { var test = false; if (typeof MaxHeap !== ''undefined'') { test = new MaxHeap() } else { return false; }; test.insert(30); test.insert(300); test.insert(500); test.insert(10); let result = []; result.push(test.remove()); result.push(test.remove()); result.push(test.remove()); result.push(test.remove()); return (result.join('''') == ''5003003010'') })(), ''The remove method removes the greatest element from the max heap while maintaining the max heap property.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var MaxHeap = function() {
// change code below this line
// change code above this line
};
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,117 @@
---
id: 587d8251367417b2b2512c65
title: Remove Elements from a Linked List by Index
challengeType: 1
---
## Description
<section id='description'>
Before we move on to another data structure, let's get a couple of last bits of practice with linked lists.
Let's write a <code>removeAt</code> method that removes the <code>element</code> at a given <code>index</code>. The method should be called <code>removeAt(index)</code>. To remove an <code>element</code> at a certain <code>index</code>, we'll need to keep a running count of each node as we move along the linked list.
A common technique used to iterate through the elements of a linked list involves a <dfn>'runner'</dfn>, or sentinel, that 'points' at the nodes that your code is comparing. In our case, starting at the <code>head</code> of our list, we start with a <code>currentIndex</code> variable that starts at <code>0</code>. The <code>currentIndex</code> should increment by one for each node we pass.
Just like our <code>remove(element)</code> method, we need to be careful not to orphan the rest of our list when we remove the node in our removeAt(index) method. We keep our nodes contiguous by making sure that the node that has reference to the removed node has a reference to the next node.
</section>
## Instructions
<section id='instructions'>
Write a <code>removeAt(index)</code> method that removes and returns a node at a given <code>index</code>. The method should return <code>null</code> if the given <code>index</code> is either negative, or greater than or equal to the <code>length</code> of the linked list.
Note
Remember to keep count of the <code>currentIndex</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>LinkedList</code> class should have a <code>removeAt</code> method.
testString: 'assert((function(){var test = new LinkedList(); return (typeof test.removeAt === ''function'')}()), ''Your <code>LinkedList</code> class should have a <code>removeAt</code> method.'');'
- text: Your <code>removeAt</code> method should reduce the <code>length</code> of the linked list
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); test.add(''dog''); test.add(''kitten''); test.removeAt(1); return test.size() === 2}()), ''Your <code>removeAt</code> method should reduce the <code>length</code> of the linked list'');'
- text: Your <code>removeAt</code> method should also return the element of the removed node.
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); test.add(''dog''); test.add(''kitten''); return test.removeAt(1) === ''dog''}()), ''Your <code>removeAt</code> method should also return the element of the removed node.'');'
- text: Your <code>removeAt</code> method should also return <code>null</code> if the given index is less than <code>0</code>
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); test.add(''dog''); test.add(''kitten''); return (test.removeAt(-1) === null)}()), ''Your <code>removeAt</code> method should also return <code>null</code> if the given index is less than <code>0</code>'');'
- text: Your <code>removeAt</code> method should also return <code>null</code> if the given index is equal or more than the <code>length</code> of the linked list.
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); test.add(''dog''); test.add(''kitten''); return (test.removeAt(3) === null)}()), ''Your <code>removeAt</code> method should also return <code>null</code> if the given index is equal or more than the <code>length</code> of the linked list.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element){ // {1}
this.element = element;
this.next = null;
};
this.size = function(){
return length;
};
this.head = function(){
return head;
};
this.add = function(element){
var node = new Node(element);
if(head === null){
head = node;
} else {
currentNode = head;
while(currentNode.next){
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
this.remove = function(element){
var currentNode = head;
var previousNode;
if(currentNode.element === element){
head = currentNode.next;
} else {
while(currentNode.element !== element) {
previousNode = currentNode;
currentNode = currentNode.next;
}
previousNode.next = currentNode.next;
}
length --;
};
// Only change code below this line
// Only change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,160 @@
---
id: 587d8251367417b2b2512c63
title: Remove Elements from a Linked List
challengeType: 1
---
## Description
<section id='description'>
The next important method that any implementation of a linked list will need is a <code>remove</code> method. This method should take the element we want to remove as an argument, and then search the list to find and remove the node that contains that element.
Whenever we remove a node from a linked list, it's important that we don't accidentally orphan the rest of the list in doing so. Recall that every node's <code>next</code> property points to the node that follows it in the list. If we're removing the middle element, say, we'll want to make sure that we have a connection from that element's previous node's <code>next</code> property to the middle element's <code>next</code> property (which is the next node in the list!)
This might sound really confusing, so let's return to the conga line example so we have a good conceptual model. Picture yourself in a conga line, and the person directly in front of you leaves the line. The person who just left the line no longer has her hands on anyone in line--and you no longer have your hands on the person that left. You step forward and put your hands on next person you see.
If the element we wish to remove is the <code>head</code> element, we reassign the <code>head</code> to the second node of the linked list.
</section>
## Instructions
<section id='instructions'>
Write a <code>remove</code> method that takes an element and removes it from the linked list.
Note
The <code>length</code> of the list should decrease by one every time an element is removed from the linked list.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>LinkedList</code> class should have a <code>remove</code> method.
testString: 'assert((function(){var test = new LinkedList(); return (typeof test.remove === ''function'')}()), ''Your <code>LinkedList</code> class should have a <code>remove</code> method.'');'
- text: Your <code>remove</code> method should reassign <code>head</code> to the second node when the first node is removed.
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); test.add(''dog''); test.remove(''cat''); return test.head().element === ''dog''}()), ''Your <code>remove</code> method should reassign <code>head</code> to the second node when the first node is removed.'');'
- text: Your <code>remove</code> method should decrease the <code>length</code> of the linked list by one for every node removed.
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); test.add(''dog''); test.remove(''cat''); return test.size() === 1})(), ''Your <code>remove</code> method should decrease the <code>length</code> of the linked list by one for every node removed.'');'
- text: Your <code>remove</code> method should reassign the reference of the previous node of the removed node to the removed node&apos;s <code>next</code> reference.
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); test.add(''dog'');test.add(''kitten''); test.remove(''dog''); return test.head().next.element === ''kitten''})(), ''Your <code>remove</code> method should reassign the reference of the previous node of the removed node to the removed node&apos;s <code>next</code> reference.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element){
this.element = element;
this.next = null;
};
this.size = function(){
return length;
};
this.head = function(){
return head;
};
this.add = function(element){
var node = new Node(element);
if(head === null){
head = node;
} else {
currentNode = head;
while(currentNode.next){
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
this.remove = function(element){
// Only change code below this line
// Only change code above this line
};
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
class Node {
constructor (element) {
this.element = element;
this.next = null;
}
}
class LinkedList {
constructor () {
this._length = 0;
this._head = null;
}
head () {
return this._head;
}
size () {
return this._length;
}
add (element) {
const node = new Node(element);
if (this._head === null) {
this._head = node;
} else {
let current = this._head;
while (current.next !== null) {
current = current.next;
}
current.next = node;
}
++this._length;
}
remove (element) {
if (this._head === null) return;
let previous;
let current = this._head;
while (current.next !== null && current.element !== element) {
previous = current;
current = current.next;
}
if (previous) {
previous.next = current.next;
} else {
this._head = current.next;
}
--this._length;
}
}
```
</section>

View File

@ -0,0 +1,77 @@
---
id: 587d8253367417b2b2512c6b
title: Remove from a Set
challengeType: 1
---
## Description
<section id='description'>
In this exercises we are going to create a delete function for our set. The function should be named <code>this.remove</code>. This function should accept a value and check if it exists in the set. If it does, remove that value from the set, and return true. Otherwise, return false.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>Set</code> class should have a <code>remove</code> method.
testString: 'assert((function(){var test = new Set(); return (typeof test.remove === ''function'')}()), ''Your <code>Set</code> class should have a <code>remove</code> method.'');'
- text: Your <code>remove</code> method should only remove items that are present in the set.
testString: 'assert.deepEqual((function(){var test = new Set(); test.add(''a'');test.add(''b'');test.remove(''c''); return test.values(); })(), [''a'', ''b''], ''Your <code>remove</code> method should only remove items that are present in the set.'');'
- text: Your <code>remove</code> method should remove the given item from the set.
testString: 'assert((function(){var test = new Set(); test.add(''a'');test.add(''b'');test.remove(''a''); var vals = test.values(); return (vals[0] === ''b'' && vals.length === 1)}()), ''Your <code>remove</code> method should remove the given item from the set.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Set() {
// the var collection will hold the set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
// this method will add an element to the set
this.add = function(element) {
if(!this.has(element)){
collection.push(element);
return true;
}
return false;
};
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function Set() {var collection = []; this.has = function(e){return(collection.indexOf(e) !== -1);};this.values = function() {return collection;};this.add = function(element) {if (!this.has(element)) {collection.push(element);return true;} else {return false;}};this.remove = function(element) {if(this.has(element)) {var i = collection.indexOf(element);collection.splice(i, 1);return true;}return false;};}
```
</section>

View File

@ -0,0 +1,67 @@
---
id: 587d8254367417b2b2512c71
title: Remove items from a set in ES6
challengeType: 1
---
## Description
<section id='description'>
Let's practice removimg items from an ES6 Set using the <code>delete</code> method.
First, create an ES6 Set
<code>var set = new Set([1,2,3]);</code>
Now remove an item from your Set with the <code>delete</code> method.
<blockquote>set.delete(1);<br>console.log([...set]) // should return [ 2, 3 ]<blockquote>
</section>
## Instructions
<section id='instructions'>
Now, create a set with the integers 1, 2, 3, 4, & 5.
Remove the values 2 and 5, and then return the set.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: 'Your Set should contain the values 1, 3, & 4'
testString: 'assert(function(){var test = checkSet(); return test.has(1) && test.has(3) && test.has(4) && test.size === 3}, ''Your Set should contain the values 1, 3, & 4'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function checkSet(){
var set = //Create a set with values 1, 2, 3, 4, & 5
//Remove the value 2
//Remove the value 5
//Return the set
return set;
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function checkSet(){
var set = new Set([1,2,3,4,5]);
set.delete(2);
set.delete(5);
return set;}
```
</section>

View File

@ -0,0 +1,78 @@
---
id: 587d825a367417b2b2512c88
title: Reverse a Doubly Linked List
challengeType: 1
---
## Description
<section id='description'>
Let's create one more method for our doubly linked list called reverse which reverses the list in place. Once the method is executed the head should point to the previous tail and the tail should point to the previous head. Now, if we traverse the list from head to tail we should meet the nodes in a reverse order compared to the original list. Trying to reverse an empty list should return null.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The DoublyLinkedList data structure exists.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== ''undefined'') { test = new DoublyLinkedList() }; return (typeof test == ''object'')})(), ''The DoublyLinkedList data structure exists.'');'
- text: The DoublyLinkedList has a method called add.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== ''undefined'') { test = new DoublyLinkedList() }; if (test.add == undefined) { return false; }; return (typeof test.add == ''function'')})(), ''The DoublyLinkedList has a method called add.'');'
- text: The DoublyLinkedList has a method called reverse.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== ''undefined'') { test = new DoublyLinkedList() }; if (test.reverse == undefined) { return false; }; return (typeof test.reverse == ''function'')})(), ''The DoublyLinkedList has a method called reverse.'');'
- text: Reversing an empty list returns null.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== ''undefined'') { test = new DoublyLinkedList() }; return (test.reverse() == null); })(), ''Reversing an empty list returns null.'');'
- text: The reverse method reverses the list.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== ''undefined'') { test = new DoublyLinkedList() }; test.add(58); test.add(61); test.add(32); test.reverse(); return (test.print().join('''') == ''326158''); })(), ''The reverse method reverses the list.'');'
- text: The next and previous references are correctly maintained when a list is reversed.
testString: 'assert((function() { var test = false; if (typeof DoublyLinkedList !== ''undefined'') { test = new DoublyLinkedList() }; test.add(11); test.add(22); test.add(33); test.reverse(); return (test.printReverse().join('''') == ''112233''); })(), ''The next and previous references are correctly maintained when a list is reversed.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var Node = function(data, prev) {
this.data = data;
this.prev = prev;
this.next = null;
};
var DoublyLinkedList = function() {
this.head = null;
this.tail = null;
// change code below this line
// change code above this line
};
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,114 @@
---
id: 587d8251367417b2b2512c64
title: Search within a Linked List
challengeType: 1
---
## Description
<section id='description'>
Let's add a few more useful methods to our linked list class. Wouldn't it be useful if we could tell if our list was empty or not, as with our <code>Stack</code> and <code>Queue</code> classes?
We should also be able to find specific elements in our linked list. Traversing through data structures is something you'll want to get a lot of practice with! Let's create an <code>indexOf</code> method that takes an <code>element</code> as an argument, and returns that element's <code>index</code> in the linked list. If the element is not found in the linked list, return <code>-1</code>.
Let's also implement a method that does the opposite: an <code>elementAt</code> method that takes an <code>index</code> as an argument and returns the <code>element</code> at the given <code>index</code>. If no <code>element</code> is found, return <code>undefined</code>.
</section>
## Instructions
<section id='instructions'>
Write an <code>isEmpty</code> method that checks if the linked list is empty, an <code>indexOf</code> method that returns the <code>index</code> of a given element, and an <code>elementAt</code> that returns an <code>element</code> at a given <code>index.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>LinkedList</code> class should have a <code>indexOf</code> method.
testString: 'assert((function(){var test = new LinkedList(); return (typeof test.indexOf === ''function'')}()), ''Your <code>LinkedList</code> class should have a <code>indexOf</code> method.'');'
- text: Your <code>LinkedList</code> class should have a <code>elementAt</code> method.
testString: 'assert((function(){var test = new LinkedList(); return (typeof test.elementAt === ''function'')}()), ''Your <code>LinkedList</code> class should have a <code>elementAt</code> method.'');'
- text: Your <code>size</code> method should return the length of the linked list
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); test.add(''dog''); test.add(''kitten''); return test.size() === 3}()), ''Your <code>size</code> method should return the length of the linked list'');'
- text: Your <code>indexOf</code> method should return the index of the given element.
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); test.add(''dog''); test.add(''kitten''); return test.indexOf(''kitten'') === 2}()), ''Your <code>indexOf</code> method should return the index of the given element.'');'
- text: Your <code>elementAt</code> method should return at element at a given index.
testString: 'assert((function(){var test = new LinkedList(); test.add(''cat''); test.add(''dog''); test.add(''kitten''); return test.elementAt(1) === ''dog''}()), ''Your <code>elementAt</code> method should return at element at a given index.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function LinkedList() {
var length = 0;
var head = null;
var Node = function(element){ // {1}
this.element = element;
this.next = null;
};
this.size = function() {
return length;
};
this.head = function(){
return head;
};
this.add = function(element){
var node = new Node(element);
if(head === null){
head = node;
} else {
currentNode = head;
while(currentNode.next){
currentNode = currentNode.next;
}
currentNode.next = node;
}
length++;
};
this.remove = function(element){
var currentNode = head;
var previousNode;
if(currentNode.element === element){
head = currentNode.next;
} else {
while(currentNode.element !== element) {
previousNode = currentNode;
currentNode = currentNode.next;
}
previousNode.next = currentNode.next;
}
length --;
};
// Only change code below this line
// Only change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,84 @@
---
id: 8d1923c8c441eddfaeb5bdef
title: Size of the Set
challengeType: 1
---
## Description
<section id='description'>
In this exercise we are going to create a size function for our Set. This function should be named <code>this.size</code> and it should return the size of the collection.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>Set</code> class should have a <code>size</code> method.
testString: 'assert((function(){var test = new Set(); return (typeof test.size === ''function'')}()), ''Your <code>Set</code> class should have a <code>size</code> method.'');'
- text: The <code>size</code> method should return the number of elements in the collection.
testString: 'assert((function(){var test = new Set(); test.add(''a'');test.add(''b'');test.remove(''a'');return (test.size() === 1)}()), ''The <code>size</code> method should return the number of elements in the collection.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function Set() {
// the var collection will hold the set
var collection = [];
// this method will check for the presence of an element and return true or false
this.has = function(element) {
return (collection.indexOf(element) !== -1);
};
// this method will return all the values in the set
this.values = function() {
return collection;
};
// this method will add an element to the set
this.add = function(element) {
if(!this.has(element)){
collection.push(element);
return true;
}
return false;
};
// this method will remove an element from a set
this.remove = function(element) {
if(this.has(element)){
var index = collection.indexOf(element);
collection.splice(index,1);
return true;
}
return false;
};
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function Set() {var collection = []; this.has = function(e){return(collection.indexOf(e) !== -1);};this.values = function() {return collection;};this.add = function(element) {if (!this.has(element)) {collection.push(element);return true;} else {return false;}};this.remove = function(element) {if(this.has(element)) {var i = collection.indexOf(element);collection.splice(i, 1);return true;}return false;};this.size = function() {return collection.length;};}
```
</section>

View File

@ -0,0 +1,71 @@
---
id: 587d8253367417b2b2512c6a
title: Typed Arrays
challengeType: 1
---
## Description
<section id='description'>
Arrays are JavaScript objects that can hold a lot of different elements.
<code>var complexArr = [1, 5, "2", "Word", {"name": "James"}];</code>
Basically what happens in the background is that your browser will automatically give the right amount of memory space for that array. It will also change as needed if you add or remove data.
However, in the world of high performance and different element types, sometimes you need to be more specific on how much memory is given to an array.
<dfn>Typed arrays</dfn> are the answer to this problem. You are now able to say how much memory you want to give an array. Below is a basic overview of the different types of arrays available and the size in bytes for each element in that array.
<table class='table table-striped'><tr><th>Type</th><th>Each element size in bytes</th></tr><tr><td><code>Int8Array</code></td><td>1</td></tr><tr><td><code>Uint8Array</code></td><td>1</td></tr><tr><td><code>Uint8ClampedArray</code></td><td>1</td></tr><tr><td><code>Int16Array</code></td><td>2</td></tr><tr><td><code>Uint16Array</code></td><td>2</td></tr><tr><td><code>Int32Array</code></td><td>4</td></tr><tr><td><code>Uint32Array</code></td><td>4</td></tr><tr><td><code>Float32Array</code></td><td>4</td></tr><tr><td><code>Float64Array</code></td><td>8</td></tr></table>
There are two ways in creating these kind of arrays. One way is to create it directly. Below is how to create a 3 length <code>Int16Array</code>.
<blockquote>var i8 = new Int16Array(3);<br>console.log(i8);<br>// Returns [0, 0, 0]</blockquote>
You can also create a <dfn>buffer</dfn> to assign how much data (in bytes) you want the array to take up.
<strong>Note</strong><br>To create typed arrays using buffers, you need to assign the number of bytes to be a multiple of the bytes listed above.
<blockquote>// Create same Int16Array array differently<br>var byteSize = 6; // Needs to be multiple of 2<br>var buffer = new ArrayBuffer(byteSize);<br>var i8View = new Int16Array(buffer);<br>buffer.byteLength; // Returns 6<br>i8View.byteLength; // Returns 6<br>console.log(i8View); // Returns [0, 0, 0]</blockquote>
<dfn>Buffers</dfn> are general purpose objects that just carry data. You cannot access them normally. To access them, you need to first create a <dfn>view</dfn>.
<blockquote>i8View[0] = 42;<br>console.log(i8View); // Returns [42, 0, 0]</blockquote>
<strong>Note</strong><br>Typed arrays do not have some of the methods traditional arrays have such as <code>.pop()</code> or <code>.push()</code>. Typed arrays also fail <code>Array.isArray()</code> that checks if something is an array. Although simpler, this can be an advantage for less-sophisticated JavaScript engines to implement them.
</section>
## Instructions
<section id='instructions'>
First create a <code>buffer</code> that is 64-bytes. Then create a <code>Int32Array</code> typed array with a view of it called <code>i32View</code>.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>buffer</code> should be 64 bytes large.
testString: 'assert(buffer.byteLength === 64, ''Your <code>buffer</code> should be 64 bytes large.'');'
- text: Your <code>i32View</code> view of your buffer should be 64 bytes large.
testString: 'assert(i32View.byteLength === 64, ''Your <code>i32View</code> view of your buffer should be 64 bytes large.'');'
- text: Your <code>i32View</code> view of your buffer should be 16 elements long.
testString: 'assert(i32View.length === 16, ''Your <code>i32View</code> view of your buffer should be 16 elements long.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var buffer;
var i32View;
```
</div>
</section>
## Solution
<section id='solution'>
```js
var buffer = new ArrayBuffer(64);
var i32View = new Int32Array(buffer);
```
</section>

View File

@ -0,0 +1,73 @@
---
id: 587d8255367417b2b2512c72
title: Use .has and .size on an ES6 Set
challengeType: 1
---
## Description
<section id='description'>
Let's look at the .has and .size methods available on the ES6 Set object.
First, create an ES6 Set
<code>var set = new Set([1,2,3]);</code>
The .has method will check if the value is contained within the set.
<code>var hasTwo = set.has(2);</code>
The .size method will return an integer representing the size of the Set
<code>var howBig = set.size;</code>
</section>
## Instructions
<section id='instructions'>
In this exercise we will pass an array and a value to the checkSet() function. Your function should create an ES6 set from the array argument. Find if the set contains the value argument. Find the size of the set. And return those two values in an array.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: '<code>checkSet([4, 5, 6], 3)</code> should return [ false, 3 ]'
testString: 'assert(function(){var test = checkSet([4,5,6], 3); test === [ false, 3 ]}, ''<code>checkSet([4, 5, 6], 3)</code> should return [ false, 3 ]'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function checkSet(arrToBeSet, checkValue){
// change code below this line
// change code above this line
}
checkSet([ 1, 2, 3], 2); // Should return [ true, 3 ]
```
</div>
</section>
## Solution
<section id='solution'>
```js
function checkSet(arrToBeSet, checkValue){
var set = new Set(arrToBeSet);
var result = [
set.has(checkValue),
set.size
];
return result;
}
```
</section>

View File

@ -0,0 +1,82 @@
---
id: 587d8258367417b2b2512c7f
title: Use Breadth First Search in a Binary Search Tree
challengeType: 1
---
## Description
<section id='description'>
Here we will introduce another tree traversal method: breadth-first search. In contrast to the depth-first search methods from the last challenge, breadth-first search explores all the nodes in a given level within a tree before continuing on to the next level. Typically, queues are utilized as helper data structures in the design of breadth-first search algorithms.
In this method, we start by adding the root node to a queue. Then we begin a loop where we dequeue the first item in the queue, add it to a new array, and then inspect both its child subtrees. If its children are not null, they are each enqueued. This process continues until the queue is empty.
Instructions: Let's create a breadth-first search method in our tree called <code>levelOrder</code>. This method should return an array containing the values of all the tree nodes, explored in a breadth-first manner. Be sure to return the values in the array, not the nodes themselves. A level should be traversed from left to right. Next, let's write a similar method called <code>reverseLevelOrder</code> which performs the same search but in the reverse direction (right to left) at each level.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The <code>BinarySearchTree</code> data structure exists.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() }; return (typeof test == ''object'')})(), ''The <code>BinarySearchTree</code> data structure exists.'');'
- text: The binary search tree has a method called <code>levelOrder</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.levelOrder == ''function'')})(), ''The binary search tree has a method called <code>levelOrder</code>.'');'
- text: The binary search tree has a method called <code>reverseLevelOrder</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.reverseLevelOrder == ''function'')})(), ''The binary search tree has a method called <code>reverseLevelOrder</code>.'');'
- text: The <code>levelOrder</code> method returns an array of the tree node values explored in level order.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.levelOrder !== ''function'') { return false; }; test.add(7); test.add(1); test.add(9); test.add(0); test.add(3); test.add(8); test.add(10); test.add(2); test.add(5); test.add(4); test.add(6); return (test.levelOrder().join('''') == ''719038102546''); })(), ''The <code>levelOrder</code> method returns an array of the tree node values explored in level order.'');'
- text: The <code>reverseLevelOrder</code> method returns an array of the tree node values explored in reverse level order.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.reverseLevelOrder !== ''function'') { return false; }; test.add(7); test.add(1); test.add(9); test.add(0); test.add(3); test.add(8); test.add(10); test.add(2); test.add(5); test.add(4); test.add(6); return (test.reverseLevelOrder().join('''') == ''791108305264''); })(), ''The <code>reverseLevelOrder</code> method returns an array of the tree node values explored in reverse level order.'');'
- text: The <code>levelOrder</code> method returns <code>null</code> for an empty tree.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.levelOrder !== ''function'') { return false; }; return (test.levelOrder() == null); })(), ''The <code>levelOrder</code> method returns <code>null</code> for an empty tree.'');'
- text: The <code>reverseLevelOrder</code> method returns <code>null</code> for an empty tree.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.reverseLevelOrder !== ''function'') { return false; }; return (test.reverseLevelOrder() == null); })(), ''The <code>reverseLevelOrder</code> method returns <code>null</code> for an empty tree.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,92 @@
---
id: 587d8257367417b2b2512c7e
title: Use Depth First Search in a Binary Search Tree
challengeType: 1
---
## Description
<section id='description'>
We know how to search a binary search tree for a specific value. But what if we just want to explore the entire tree? Or what if we don't have an ordered tree and we need to just search for a value? Here we will introduce some tree traversal methods which can be used to explore tree data structures. First up is depth-first search. In depth-first search, a given subtree is explored as deeply as possible before the search continues on to another subtree. There are three ways this can be done:
In-order: Begin the search at the left-most node and end at the right-most node.
Pre-order: Explore all the roots before the leaves.
Post-order: Explore all the leaves before the roots.
As you may guess, you may choose different search methods depending on what type of data your tree is storing and what you are looking for. For a binary search tree, an inorder traversal returns the nodes in sorted order.
Instructions: Here we will create these three search methods on our binary search tree. Depth-first search is an inherently recursive operation which continues to explore further subtrees so long as child nodes are present. Once you understand this basic concept, you can simply rearrange the order in which you explore the nodes and subtrees to produce any of the three searches above. For example, in post-order search we would want to recurse all the way to a leaf node before we begin to return any of the nodes themselves, whereas in pre-order search we would want to return the nodes first, and then continue recursing down the tree.
Define <code>inorder</code>, <code>preorder</code>, and <code>postorder</code> methods on our tree. Each of these methods should return an array of items which represent the tree traversal. Be sure to return the integer values at each node in the array, not the nodes themselves. Finally, return <code>null</code> if the tree is empty.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: The <code>BinarySearchTree</code> data structure exists.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() }; return (typeof test == ''object'')})(), ''The <code>BinarySearchTree</code> data structure exists.'');'
- text: The binary search tree has a method called <code>inorder</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.inorder == ''function'')})(), ''The binary search tree has a method called <code>inorder</code>.'');'
- text: The binary search tree has a method called <code>preorder</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.preorder == ''function'')})(), ''The binary search tree has a method called <code>preorder</code>.'');'
- text: The binary search tree has a method called <code>postorder</code>.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; return (typeof test.postorder == ''function'')})(), ''The binary search tree has a method called <code>postorder</code>.'');'
- text: The <code>inorder</code> method returns an array of the node values that result from an inorder traversal.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.inorder !== ''function'') { return false; }; test.add(7); test.add(1); test.add(9); test.add(0); test.add(3); test.add(8); test.add(10); test.add(2); test.add(5); test.add(4); test.add(6); return (test.inorder().join('''') == ''012345678910''); })(), ''The <code>inorder</code> method returns an array of the node values that result from an inorder traversal.'');'
- text: The <code>preorder</code> method returns an array of the node values that result from a preorder traversal.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.preorder !== ''function'') { return false; }; test.add(7); test.add(1); test.add(9); test.add(0); test.add(3); test.add(8); test.add(10); test.add(2); test.add(5); test.add(4); test.add(6); return (test.preorder().join('''') == ''710325469810''); })(), ''The <code>preorder</code> method returns an array of the node values that result from a preorder traversal.'');'
- text: The <code>postorder</code> method returns an array of the node values that result from a postorder traversal.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.postorder !== ''function'') { return false; }; test.add(7); test.add(1); test.add(9); test.add(0); test.add(3); test.add(8); test.add(10); test.add(2); test.add(5); test.add(4); test.add(6); return (test.postorder().join('''') == ''024653181097''); })(), ''The <code>postorder</code> method returns an array of the node values that result from a postorder traversal.'');'
- text: The <code>inorder</code> method returns <code>null</code> for an empty tree.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.inorder !== ''function'') { return false; }; return (test.inorder() == null); })(), ''The <code>inorder</code> method returns <code>null</code> for an empty tree.'');'
- text: The <code>preorder</code> method returns <code>null</code> for an empty tree.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.preorder !== ''function'') { return false; }; return (test.preorder() == null); })(), ''The <code>preorder</code> method returns <code>null</code> for an empty tree.'');'
- text: The <code>postorder</code> method returns <code>null</code> for an empty tree.
testString: 'assert((function() { var test = false; if (typeof BinarySearchTree !== ''undefined'') { test = new BinarySearchTree() } else { return false; }; if (typeof test.postorder !== ''function'') { return false; }; return (test.postorder() == null); })(), ''The <code>postorder</code> method returns <code>null</code> for an empty tree.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
// change code below this line
// change code above this line
}
```
</div>
### After Test
<div id='js-teardown'>
```js
console.info('after the test');
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,61 @@
---
id: 587d8255367417b2b2512c73
title: Use Spread and Notes for ES5 Set() Integration
challengeType: 1
---
## Description
<section id='description'>
Do you remember the ES6 spread operator <code>...</code>?
<code>...</code> can take iterable objects in ES6 and turn them into arrays.
Let's create a Set, and check out the spread function.
<blockquote>var set = new Set([1,2,3]);<br>var setToArr = [...set]<br>console.log(setToArr) // returns [ 1, 2, 3 ]</blockquote>
</section>
## Instructions
<section id='instructions'>
In this exercise we will pass a set object to the <code>checkSet</code> function. It should return an array containing the values of the Set.
Now you've successfully learned how to use the ES6 <code>Set()</code> object, good job!
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your Set was returned correctly!
testString: 'assert(function(){var test = checkSet(new Set([1,2,3,4,5,6,7])); test === [ 1, 2, 3, 4, 5, 6, 7 ]}, ''Your Set was returned correctly!'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function checkSet(set){
// change code below this line
// change code above this line
}
```
</div>
</section>
## Solution
<section id='solution'>
```js
function checkSet(set){
return [...set];}
```
</section>

View File

@ -0,0 +1,65 @@
---
id: 587d8251367417b2b2512c61
title: Work with Nodes in a Linked List
challengeType: 1
---
## Description
<section id='description'>
Another common data structure you'll run into in computer science is the <dfn>linked list</dfn>. A linked list is a linear collection of data elements, called 'nodes', each of which points to the next. Each <dfn>node</dfn> in a linked list contains two key pieces of information: the <code>element</code> itself, and a reference to the next <code>node</code>.
Imagine that you are in a conga line. You have your hands on the next person in the line, and the person behind you has their hands on you. You can see the person straight ahead of you, but they are blocking the view of the other people ahead in line. A node is just like a person in a conga line: they know who they are and they can only see the next person in line, but they are not aware of the other people ahead or behind them.
</section>
## Instructions
<section id='instructions'>
In our code editor, we've created two nodes, <code>Kitten</code> and <code>Puppy</code>, and we've manually connected the <code>Kitten</code> node to the <code>Puppy</code> node.
Create a <code>Cat</code> and <code>Dog</code> node and manually add them to the line.
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: Your <code>Puppy</code> node should have a reference to a <code>Cat</code> node.
testString: 'assert(Puppy.next.element === "Cat", ''Your <code>Puppy</code> node should have a reference to a <code>Cat</code> node.'');'
- text: Your <code>Cat</code> node should have a reference to a <code>Dog</code> node.
testString: 'assert(Cat.next.element === "Dog", ''Your <code>Cat</code> node should have a reference to a <code>Dog</code> node.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
var Node = function(element){
this.element = element;
this.next = null;
};
var Kitten = new Node("Kitten");
var Puppy = new Node("Puppy");
Kitten.next = Puppy;
// only add code below this line
// test your code
console.log(Kitten.next);
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,73 @@
---
id: 5900f36e1000cf542c50fe80
challengeType: 5
title: 'Problem 1: Multiples of 3 and 5'
---
## Description
<section id='description'>
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below the provided parameter value <code>number</code>.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>multiplesOf3and5(1000)</code> should return 233168.
testString: 'assert.strictEqual(multiplesOf3and5(1000), 233168, ''<code>multiplesOf3and5(1000)</code> should return 233168.'');'
- text: <code>multiplesOf3and5(49)</code> should return 543.
testString: 'assert.strictEqual(multiplesOf3and5(49), 543, ''<code>multiplesOf3and5(49)</code> should return 543.'');'
- text: <code>multiplesOf3and5(19564)</code> should return 89301183.
testString: 'assert.strictEqual(multiplesOf3and5(19564), 89301183, ''<code>multiplesOf3and5(19564)</code> should return 89301183.'');'
- text: Your function is not returning the correct result using our tests values.
testString: 'assert.strictEqual(multiplesOf3and5(8456), 16687353, ''Your function is not returning the correct result using our tests values.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function multiplesOf3and5(number) {
// Good luck!
return true;
}
multiplesOf3and5(1000);
```
</div>
</section>
## Solution
<section id='solution'>
```js
const multiplesOf3and5 = (number) => {
var total = 0;
for(var i = 0; i < number; i++) {
if(i % 3 == 0 || i % 5 == 0) {
total += i;
}
}
return total;
};
```
</section>

View File

@ -0,0 +1,98 @@
---
id: 5900f3761000cf542c50fe89
challengeType: 5
title: 'Problem 10: Summation of primes'
---
## Description
<section id='description'>
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below n.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>primeSummation(17)</code> should return 41.
testString: 'assert.strictEqual(primeSummation(17), 41, ''<code>primeSummation(17)</code> should return 41.'');'
- text: <code>primeSummation(2001)</code> should return 277050.
testString: 'assert.strictEqual(primeSummation(2001), 277050, ''<code>primeSummation(2001)</code> should return 277050.'');'
- text: <code>primeSummation(140759)</code> should return 873608362.
testString: 'assert.strictEqual(primeSummation(140759), 873608362, ''<code>primeSummation(140759)</code> should return 873608362.'');'
- text: <code>primeSummation(2000000)</code> should return 142913828922.
testString: 'assert.strictEqual(primeSummation(2000000), 142913828922, ''<code>primeSummation(2000000)</code> should return 142913828922.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function primeSummation(n) {
// Good luck!
return true;
}
primeSummation(2000000);
```
</div>
</section>
## Solution
<section id='solution'>
```js
//noprotect
function primeSummation(n) {
// Initialise an array containing only prime numbers
let primes = [2];
let result = 2;
function isPrime(y, primes) {
// Find sqrt(y)
const sqrt = Math.floor(Math.sqrt(y));
// Divide y by each applicable prime, return false if any of them divide y
for (let i = 0; i < primes.length && primes[i] <= sqrt; i++) {
if (y % primes[i] === 0) {
return false;
}
}
// At this point x must be prime
return true;
}
// For every odd integer, add it to the array if it is prime
for (let x = 3; x < n; x += 2) {
if (isPrime(x, primes)) {
if (x > n) {
return result;
} else {
result += x;
primes.push(x);
}
}
}
return result;
}
```
</section>

View File

@ -0,0 +1,57 @@
---
id: 5900f3d01000cf542c50fee3
challengeType: 5
title: 'Problem 100: Arranged probability'
---
## Description
<section id='description'>
If a box contains twenty-one coloured discs, composed of fifteen blue discs and six red discs, and two discs were taken at random, it can be seen that the probability of taking two blue discs, P(BB) = (15/21)×(14/20) = 1/2.
The next such arrangement, for which there is exactly 50% chance of taking two blue discs at random, is a box containing eighty-five blue discs and thirty-five red discs.
By finding the first arrangement to contain over 1012 = 1,000,000,000,000 discs in total, determine the number of blue discs that the box would contain.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler100()</code> should return 756872327473.
testString: 'assert.strictEqual(euler100(), 756872327473, ''<code>euler100()</code> should return 756872327473.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler100() {
// Good luck!
return true;
}
euler100();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,75 @@
---
id: 5900f3d21000cf542c50fee4
challengeType: 5
title: 'Problem 101: Optimum polynomial'
---
## Description
<section id='description'>
If we are presented with the first k terms of a sequence it is impossible to say with certainty the value of the next term, as there are infinitely many polynomial functions that can model the sequence.
As an example, let us consider the sequence of cube numbers. This is defined by the generating function, un = n3: 1, 8, 27, 64, 125, 216, ...
Suppose we were only given the first two terms of this sequence. Working on the principle that "simple is best" we should assume a linear relationship and predict the next term to be 15 (common difference 7). Even if we were presented with the first three terms, by the same principle of simplicity, a quadratic relationship should be assumed.
We shall define OP(k, n) to be the nth term of the optimum polynomial generating function for the first k terms of a sequence. It should be clear that OP(k, n) will accurately generate the terms of the sequence for n ≤ k, and potentially the first incorrect term (FIT) will be OP(k, k+1); in which case we shall call it a bad OP (BOP).
As a basis, if we were only given the first term of sequence, it would be most sensible to assume constancy; that is, for n ≥ 2, OP(1, n) = u1.
Hence we obtain the following OPs for the cubic sequence:
OP(1, n) = 1
1, 1, 1, 1, ...
OP(2, n) = 7n6
1, 8, 15, ...
OP(3, n) = 6n211n+6     
1, 8, 27, 58, ...
OP(4, n) = n3
1, 8, 27, 64, 125, ...
Clearly no BOPs exist for k ≥ 4.
By considering the sum of FITs generated by the BOPs (indicated in red above), we obtain 1 + 15 + 58 = 74.
Consider the following tenth degree polynomial generating function:
un = 1 n + n2 n3 + n4 n5 + n6 n7 + n8 n9 + n10
Find the sum of FITs for the BOPs.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler101()</code> should return 37076114526.
testString: 'assert.strictEqual(euler101(), 37076114526, ''<code>euler101()</code> should return 37076114526.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler101() {
// Good luck!
return true;
}
euler101();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,61 @@
---
id: 5900f3d21000cf542c50fee5
challengeType: 5
title: 'Problem 102: Triangle containment'
---
## Description
<section id='description'>
Three distinct points are plotted at random on a Cartesian plane, for which -1000 ≤ x, y ≤ 1000, such that a triangle is formed.
Consider the following two triangles:
A(-340,495), B(-153,-910), C(835,-947)
X(-175,41), Y(-421,-714), Z(574,-645)
It can be verified that triangle ABC contains the origin, whereas triangle XYZ does not.
Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file containing the co-ordinates of one thousand "random" triangles, find the number of triangles for which the interior contains the origin.
NOTE: The first two examples in the file represent the triangles in the example given above.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler102()</code> should return 228.
testString: 'assert.strictEqual(euler102(), 228, ''<code>euler102()</code> should return 228.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler102() {
// Good luck!
return true;
}
euler102();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,63 @@
---
id: 5900f3d61000cf542c50fee7
challengeType: 5
title: 'Problem 103: Special subset sums: optimum'
---
## Description
<section id='description'>
Let S(A) represent the sum of elements in set A of size n. We shall call it a special sum set if for any two non-empty disjoint subsets, B and C, the following properties are true:
S(B) ≠ S(C); that is, sums of subsets cannot be equal.
If B contains more elements than C then S(B) > S(C).
If S(A) is minimised for a given n, we shall call it an optimum special sum set. The first five optimum special sum sets are given below.
n = 1: {1}n = 2: {1, 2}n = 3: {2, 3, 4}n = 4: {3, 5, 6, 7}n = 5: {6, 9, 11, 12, 13}
It seems that for a given optimum set, A = {a1, a2, ... , an}, the next optimum set is of the form B = {b, a1+b, a2+b, ... ,an+b}, where b is the "middle" element on the previous row.
By applying this "rule" we would expect the optimum set for n = 6 to be A = {11, 17, 20, 22, 23, 24}, with S(A) = 117. However, this is not the optimum set, as we have merely applied an algorithm to provide a near optimum set. The optimum set for n = 6 is A = {11, 18, 19, 20, 22, 25}, with S(A) = 115 and corresponding set string: 111819202225.
Given that A is an optimum special sum set for n = 7, find its set string.
NOTE: This problem is related to Problem 105 and Problem 106.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler103()</code> should return 20313839404245.
testString: 'assert.strictEqual(euler103(), 20313839404245, ''<code>euler103()</code> should return 20313839404245.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler103() {
// Good luck!
return true;
}
euler103();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,58 @@
---
id: 5900f3d51000cf542c50fee6
challengeType: 5
title: 'Problem 104: Pandigital Fibonacci ends'
---
## Description
<section id='description'>
The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn1 + Fn2, where F1 = 1 and F2 = 1.
It turns out that F541, which contains 113 digits, is the first Fibonacci number for which the last nine digits are 1-9 pandigital (contain all the digits 1 to 9, but not necessarily in order). And F2749, which contains 575 digits, is the first Fibonacci number for which the first nine digits are 1-9 pandigital.
Given that Fk is the first Fibonacci number for which the first nine digits AND the last nine digits are 1-9 pandigital, find k.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler104()</code> should return 329468.
testString: 'assert.strictEqual(euler104(), 329468, ''<code>euler104()</code> should return 329468.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler104() {
// Good luck!
return true;
}
euler104();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,60 @@
---
id: 5900f3d61000cf542c50fee8
challengeType: 5
title: 'Problem 105: Special subset sums: testing'
---
## Description
<section id='description'>
Let S(A) represent the sum of elements in set A of size n. We shall call it a special sum set if for any two non-empty disjoint subsets, B and C, the following properties are true:
S(B) ≠ S(C); that is, sums of subsets cannot be equal.
If B contains more elements than C then S(B) > S(C).
For example, {81, 88, 75, 42, 87, 84, 86, 65} is not a special sum set because 65 + 87 + 88 = 75 + 81 + 84, whereas {157, 150, 164, 119, 79, 159, 161, 139, 158} satisfies both rules for all possible subset pair combinations and S(A) = 1286.
Using sets.txt (right click and "Save Link/Target As..."), a 4K text file with one-hundred sets containing seven to twelve elements (the two examples given above are the first two sets in the file), identify all the special sum sets, A1, A2, ..., Ak, and find the value of S(A1) + S(A2) + ... + S(Ak).
NOTE: This problem is related to Problem 103 and Problem 106.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler105()</code> should return 73702.
testString: 'assert.strictEqual(euler105(), 73702, ''<code>euler105()</code> should return 73702.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler105() {
// Good luck!
return true;
}
euler105();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,61 @@
---
id: 5900f3d71000cf542c50fee9
challengeType: 5
title: 'Problem 106: Special subset sums: meta-testing'
---
## Description
<section id='description'>
Let S(A) represent the sum of elements in set A of size n. We shall call it a special sum set if for any two non-empty disjoint subsets, B and C, the following properties are true:
S(B) ≠ S(C); that is, sums of subsets cannot be equal.
If B contains more elements than C then S(B) > S(C).
For this problem we shall assume that a given set contains n strictly increasing elements and it already satisfies the second rule.
Surprisingly, out of the 25 possible subset pairs that can be obtained from a set for which n = 4, only 1 of these pairs need to be tested for equality (first rule). Similarly, when n = 7, only 70 out of the 966 subset pairs need to be tested.
For n = 12, how many of the 261625 subset pairs that can be obtained need to be tested for equality?
NOTE: This problem is related to Problem 103 and Problem 105.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler106()</code> should return 21384.
testString: 'assert.strictEqual(euler106(), 21384, ''<code>euler106()</code> should return 21384.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler106() {
// Good luck!
return true;
}
euler106();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,70 @@
---
id: 5900f3d91000cf542c50feea
challengeType: 5
title: 'Problem 107: Minimal network'
---
## Description
<section id='description'>
The following undirected network consists of seven vertices and twelve edges with a total weight of 243.
The same network can be represented by the matrix below.
    ABCDEFG
A-161221---
B16--1720--
C12--28-31-
D211728-181923
E-20-18--11
F--3119--27
G---231127-
However, it is possible to optimise the network by removing some edges and still ensure that all points on the network remain connected. The network which achieves the maximum saving is shown below. It has a weight of 93, representing a saving of 243 93 = 150 from the original network.
Using network.txt (right click and 'Save Link/Target As...'), a 6K text file containing a network with forty vertices, and given in matrix form, find the maximum saving which can be achieved by removing redundant edges whilst ensuring that the network remains connected.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler107()</code> should return 259679.
testString: 'assert.strictEqual(euler107(), 259679, ''<code>euler107()</code> should return 259679.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler107() {
// Good luck!
return true;
}
euler107();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,59 @@
---
id: 5900f3d91000cf542c50feeb
challengeType: 5
title: 'Problem 108: Diophantine Reciprocals I'
---
## Description
<section id='description'>
In the following equation x, y, and n are positive integers.
1/<var>x</var> + 1/<var>y</var> = 1/<var>n</var>
For <var>n</var> = 4 there are exactly three distinct solutions:
1/5 + 1/20 = 1/4<br />1/6 + 1/12 = 1/4<br />1/8 + 1/8 = 1/4
What is the least value of <var>n</var> for which the number of distinct solutions exceeds one-thousand?
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>diophantineOne()</code> should return 180180.
testString: 'assert.strictEqual(diophantineOne(), 180180, ''<code>diophantineOne()</code> should return 180180.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function diophantineOne() {
// Good luck!
return true;
}
diophantineOne();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,101 @@
---
id: 5900f3db1000cf542c50feec
challengeType: 5
title: 'Problem 109: Darts'
---
## Description
<section id='description'>
In the game of darts a player throws three darts at a target board which is split into twenty equal sized sections numbered one to twenty.
The score of a dart is determined by the number of the region that the dart lands in. A dart landing outside the red/green outer ring scores zero. The black and cream regions inside this ring represent single scores. However, the red/green outer ring and middle ring score double and treble scores respectively.
At the centre of the board are two concentric circles called the bull region, or bulls-eye. The outer bull is worth 25 points and the inner bull is a double, worth 50 points.
There are many variations of rules but in the most popular game the players will begin with a score 301 or 501 and the first player to reduce their running total to zero is a winner. However, it is normal to play a "doubles out" system, which means that the player must land a double (including the double bulls-eye at the centre of the board) on their final dart to win; any other dart that would reduce their running total to one or lower means the score for that set of three darts is "bust".
When a player is able to finish on their current score it is called a "checkout" and the highest checkout is 170: T20 T20 D25 (two treble 20s and double bull).
There are exactly eleven distinct ways to checkout on a score of 6:
D3
D1
D2
S2
D2
D2
D1
S4
D1
S1
S1
D2
S1
T1
D1
S1
S3
D1
D1
D1
D1
D1
S2
D1
S2
S2
D1
Note that D1 D2 is considered different to D2 D1 as they finish on different doubles. However, the combination S1 T1 D1 is considered the same as T1 S1 D1.
In addition we shall not include misses in considering combinations; for example, D3 is the same as 0 D3 and 0 0 D3.
Incredibly there are 42336 distinct ways of checking out in total.
How many distinct ways can a player checkout with a score less than 100?
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler109()</code> should return 38182.
testString: 'assert.strictEqual(euler109(), 38182, ''<code>euler109()</code> should return 38182.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler109() {
// Good luck!
return true;
}
euler109();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,188 @@
---
id: 5900f3781000cf542c50fe8a
challengeType: 5
title: 'Problem 11: Largest product in a grid'
---
## Description
<section id='description'>
In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
<div style='text-align: center;'>08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08</div>
<div style='text-align: center;'>49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00</div>
<div style='text-align: center;'>81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65</div>
<div style='text-align: center;'>52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91</div>
<div style='text-align: center;'>22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80</div>
<div style='text-align: center;'>24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50</div>
<div style='text-align: center;'>32 98 81 28 64 23 67 10 <span style='color: red'><b>26</b></span> 38 40 67 59 54 70 66 18 38 64 70</div>
<div style='text-align: center;'>67 26 20 68 02 62 12 20 95 <span style='color: red'><b>63</b></span> 94 39 63 08 40 91 66 49 94 21</div>
<div style='text-align: center;'>24 55 58 05 66 73 99 26 97 17 <span style='color: red'><b>78</b></span> 78 96 83 14 88 34 89 63 72</div>
<div style='text-align: center;'>21 36 23 09 75 00 76 44 20 45 35 <span style='color: red'><b>14</b></span> 00 61 33 97 34 31 33 95</div>
<div style='text-align: center;'>78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92</div>
<div style='text-align: center;'>16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57</div>
<div style='text-align: center;'>86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58</div>
<div style='text-align: center;'>19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40</div>
<div style='text-align: center;'>04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66</div>
<div style='text-align: center;'>88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69</div>
<div style='text-align: center;'>04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36</div>
<div style='text-align: center;'>20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16</div>
<div style='text-align: center;'>20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54</div>
<div style='text-align: center;'>01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48</div>
The product of these numbers is 26 × 63 × 78 × 14 = 1788696.
What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in a given <code>arr</code> grid?
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>largestGridProduct(grid)</code> should return 70600674.
testString: 'assert.strictEqual(largestGridProduct(grid), 70600674, ''<code>largestGridProduct(grid)</code> should return 70600674.'');'
- text: <code>largestGridProduct(testGrid)</code> should return 14169081.
testString: 'assert.strictEqual(largestGridProduct(testGrid), 14169081, ''<code>largestGridProduct(testGrid)</code> should return 14169081.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function largestGridProduct(arr) {
// Good luck!
return arr;
}
// Only change code above this line
const grid = [
[8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8],
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65],
[52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91],
[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
[24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
[32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
[67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21],
[24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
[21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95],
[78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92],
[16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57],
[86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
[19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40],
[4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
[88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
[4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36],
[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16],
[20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54],
[1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48]
];
const testGrid = [
[40, 17, 81, 18, 57],
[74, 4, 36, 16, 29],
[36, 42, 69, 73, 45],
[51, 54, 69, 16, 92],
[7, 97, 57, 32, 16]
];
largestGridProduct(testGrid);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function largestGridProduct(arr) {
let maxProduct = 0;
let currProduct = 0;
function maxProductChecker(n) {
if (n > maxProduct) {
return maxProduct = n;
}
}
// loop rows
for (let r = 0; r < arr.length; r++) {
// loop columns
for (let c = 0; c < arr[r].length; c++) {
const limit = arr[r].length - 3;
// check horizontal
if (c < limit) {
currProduct = arr[r][c] * arr[r][c + 1] * arr[r][c + 2] * arr[r][c + 3];
maxProductChecker(currProduct);
}
// check vertical
if (r < limit) {
currProduct = arr[r][c] * arr[r + 1][c] * arr[r + 2][c] * arr[r + 3][c];
maxProductChecker(currProduct);
}
// check diagonal [\]
if (c < limit && r < limit) {
currProduct = arr[r][c] * arr[r + 1][c + 1] * arr[r + 2][c + 2] * arr[r + 3][c + 3];
maxProductChecker(currProduct);
}
// check diagonal [/]
if (c > 3 && r < limit) {
currProduct = arr[r][c] * arr[r + 1][c - 1] * arr[r + 2][c - 2] * arr[r + 3][c - 3];
maxProductChecker(currProduct);
}
}
}
return maxProduct;
}
const grid = [ [8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8],
[49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0],
[81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65],
[52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91],
[22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80],
[24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50],
[32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70],
[67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21],
[24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72],
[21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95],
[78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92],
[16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57],
[86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58],
[19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40],
[4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66],
[88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69],
[4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36],
[20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16],
[20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54],
[1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48]
];
const testGrid = [
[40, 17, 81, 18, 57],
[74, 4, 36, 16, 29],
[36, 42, 69, 73, 45],
[51, 54, 69, 16, 92],
[7, 97, 57, 32, 16]
];
```
</section>

View File

@ -0,0 +1,58 @@
---
id: 5900f3db1000cf542c50feed
challengeType: 5
title: 'Problem 110: Diophantine Reciprocals II'
---
## Description
<section id='description'>
In the following equation x, y, and n are positive integers.
1/<var>x</var> + 1/<var>y</var> = 1/<var>n</var>
It can be verified that when <var>n</var> = 1260 there are 113 distinct solutions and this is the least value of <var>n</var> for which the total number of distinct solutions exceeds one hundred.
What is the least value of <var>n</var> for which the number of distinct solutions exceeds four million?
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>diophantineTwo</code> should return 9350130049860600.
testString: 'assert.strictEqual(diophantineTwo(), 9350130049860600, ''<code>diophantineTwo()</code> should return 9350130049860600.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function diophantineTwo() {
// Good luck!
return true;
}
diophantineTwo();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,107 @@
---
id: 5900f3db1000cf542c50feee
challengeType: 5
title: 'Problem 111: Primes with runs'
---
## Description
<section id='description'>
Considering 4-digit primes containing repeated digits it is clear that they cannot all be the same: 1111 is divisible by 11, 2222 is divisible by 22, and so on. But there are nine 4-digit primes containing three ones:
1117, 1151, 1171, 1181, 1511, 1811, 2111, 4111, 8111
We shall say that M(n, d) represents the maximum number of repeated digits for an n-digit prime where d is the repeated digit, N(n, d) represents the number of such primes, and S(n, d) represents the sum of these primes.
So M(4, 1) = 3 is the maximum number of repeated digits for a 4-digit prime where one is the repeated digit, there are N(4, 1) = 9 such primes, and the sum of these primes is S(4, 1) = 22275. It turns out that for d = 0, it is only possible to have M(4, 0) = 2 repeated digits, but there are N(4, 0) = 13 such cases.
In the same way we obtain the following results for 4-digit primes.
Digit, d
M(4, d)
N(4, d)
S(4, d)
0
2
13
67061
1
3
9
22275
2
3
1
2221
3
3
12
46214
4
3
2
8888
5
3
1
5557
6
3
1
6661
7
3
9
57863
8
3
1
8887
9
3
7
48073
For d = 0 to 9, the sum of all S(4, d) is 273700.
Find the sum of all S(10, d).
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler111()</code> should return 612407567715.
testString: 'assert.strictEqual(euler111(), 612407567715, ''<code>euler111()</code> should return 612407567715.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler111() {
// Good luck!
return true;
}
euler111();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,60 @@
---
id: 5900f3dd1000cf542c50feef
challengeType: 5
title: 'Problem 112: Bouncy numbers'
---
## Description
<section id='description'>
Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468.
Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420.
We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349.
Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538.
Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%.
Find the least number for which the proportion of bouncy numbers is exactly 99%.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler112()</code> should return 1587000.
testString: 'assert.strictEqual(euler112(), 1587000, ''<code>euler112()</code> should return 1587000.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler112() {
// Good luck!
return true;
}
euler112();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,59 @@
---
id: 5900f3dd1000cf542c50fef0
challengeType: 5
title: 'Problem 113: Non-bouncy numbers'
---
## Description
<section id='description'>
Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468.
Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420.
We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349.
As n increases, the proportion of bouncy numbers below n increases such that there are only 12951 numbers below one-million that are not bouncy and only 277032 non-bouncy numbers below 1010.
How many numbers below a googol (10100) are not bouncy?
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler113()</code> should return 51161058134250.
testString: 'assert.strictEqual(euler113(), 51161058134250, ''<code>euler113()</code> should return 51161058134250.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler113() {
// Good luck!
return true;
}
euler113();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,158 @@
---
id: 5900f3e01000cf542c50fef2
challengeType: 5
title: 'Problem 114: Counting block combinations I'
---
## Description
<section id='description'>
A row measuring seven units in length has red blocks with a minimum length of three units placed on it, such that any two red blocks (which are allowed to be different lengths) are separated by at least one black square. There are exactly seventeen ways of doing this.
How many ways can a row measuring fifty units in length be filled?
NOTE: Although the example above does not lend itself to the possibility, in general it is permitted to mix block sizes. For example, on a row measuring eight units in length you could use red (3), black (1), and red (4).
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler114()</code> should return 16475640049.
testString: 'assert.strictEqual(euler114(), 16475640049, ''<code>euler114()</code> should return 16475640049.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler114() {
// Good luck!
return true;
}
euler114();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,61 @@
---
id: 5900f3df1000cf542c50fef1
challengeType: 5
title: 'Problem 115: Counting block combinations II'
---
## Description
<section id='description'>
NOTE: This is a more difficult version of Problem 114.
A row measuring n units in length has red blocks with a minimum length of m units placed on it, such that any two red blocks (which are allowed to be different lengths) are separated by at least one black square.
Let the fill-count function, F(m, n), represent the number of ways that a row can be filled.
For example, F(3, 29) = 673135 and F(3, 30) = 1089155.
That is, for m = 3, it can be seen that n = 30 is the smallest value for which the fill-count function first exceeds one million.
In the same way, for m = 10, it can be verified that F(10, 56) = 880711 and F(10, 57) = 1148904, so n = 57 is the least value for which the fill-count function first exceeds one million.
For m = 50, find the least value of n for which the fill-count function first exceeds one million.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler115()</code> should return 168.
testString: 'assert.strictEqual(euler115(), 168, ''<code>euler115()</code> should return 168.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler115() {
// Good luck!
return true;
}
euler115();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,128 @@
---
id: 5900f3e01000cf542c50fef3
challengeType: 5
title: 'Problem 116: Red, green or blue tiles'
---
## Description
<section id='description'>
A row of five black square tiles is to have a number of its tiles replaced with coloured oblong tiles chosen from red (length two), green (length three), or blue (length four).
If red tiles are chosen there are exactly seven ways this can be done.
If green tiles are chosen there are three ways.
And if blue tiles are chosen there are two ways.
Assuming that colours cannot be mixed there are 7 + 3 + 2 = 12 ways of replacing the black tiles in a row measuring five units in length.
How many different ways can the black tiles in a row measuring fifty units in length be replaced if colours cannot be mixed and at least one coloured tile must be used?
NOTE: This is related to Problem 117.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler116()</code> should return 20492570929.
testString: 'assert.strictEqual(euler116(), 20492570929, ''<code>euler116()</code> should return 20492570929.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler116() {
// Good luck!
return true;
}
euler116();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,136 @@
---
id: 5900f3e21000cf542c50fef4
challengeType: 5
title: 'Problem 117: Red, green, and blue tiles'
---
## Description
<section id='description'>
Using a combination of black square tiles and oblong tiles chosen from: red tiles measuring two units, green tiles measuring three units, and blue tiles measuring four units, it is possible to tile a row measuring five units in length in exactly fifteen different ways.
How many ways can a row measuring fifty units in length be tiled?
NOTE: This is related to Problem 116.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler117()</code> should return 100808458960497.
testString: 'assert.strictEqual(euler117(), 100808458960497, ''<code>euler117()</code> should return 100808458960497.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler117() {
// Good luck!
return true;
}
euler117();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,56 @@
---
id: 5900f3e21000cf542c50fef5
challengeType: 5
title: 'Problem 118: Pandigital prime sets'
---
## Description
<section id='description'>
Using all of the digits 1 through 9 and concatenating them freely to form decimal integers, different sets can be formed. Interestingly with the set {2,5,47,89,631}, all of the elements belonging to it are prime.
How many distinct sets containing each of the digits one through nine exactly once contain only prime elements?
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler118()</code> should return 44680.
testString: 'assert.strictEqual(euler118(), 44680, ''<code>euler118()</code> should return 44680.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler118() {
// Good luck!
return true;
}
euler118();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,58 @@
---
id: 5900f3e41000cf542c50fef6
challengeType: 5
title: 'Problem 119: Digit power sum'
---
## Description
<section id='description'>
The number 512 is interesting because it is equal to the sum of its digits raised to some power: 5 + 1 + 2 = 8, and 83 = 512. Another example of a number with this property is 614656 = 284.
We shall define an to be the nth term of this sequence and insist that a number must contain at least two digits to have a sum.
You are given that a2 = 512 and a10 = 614656.
Find a30.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler119()</code> should return 248155780267521.
testString: 'assert.strictEqual(euler119(), 248155780267521, ''<code>euler119()</code> should return 248155780267521.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler119() {
// Good luck!
return true;
}
euler119();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,105 @@
---
id: 5900f3781000cf542c50fe8b
challengeType: 5
title: 'Problem 12: Highly divisible triangular number'
---
## Description
<section id='description'>
The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
<div style='text-align: center;'>1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...</div>
Let us list the factors of the first seven triangle numbers:
<div style='padding-left: 4em;'><b>1:</b> 1</div>
<div style='padding-left: 4em;'><b>3:</b> 1, 3</div>
<div style='padding-left: 4em;'><b>6:</b> 1, 2, 3, 6</div>
<div style='padding-left: 4em;'><b>10:</b> 1, 2, 5, 10</div>
<div style='padding-left: 4em;'><b>15:</b> 1, 3, 5, 15</div>
<div style='padding-left: 4em;'><b>21:</b> 1, 3, 7, 21</div>
<div style='padding-left: 4em;'><b>28:</b> 1, 2, 4, 7, 14, 28</div>
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over <code>n</code> divisors?
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>divisibleTriangleNumber(5)</code> should return 28.
testString: 'assert.strictEqual(divisibleTriangleNumber(5), 28, ''<code>divisibleTriangleNumber(5)</code> should return 28.'');'
- text: <code>divisibleTriangleNumber(23)</code> should return 630.
testString: 'assert.strictEqual(divisibleTriangleNumber(23), 630, ''<code>divisibleTriangleNumber(23)</code> should return 630.'');'
- text: <code>divisibleTriangleNumber(167)</code> should return 1385280.
testString: 'assert.strictEqual(divisibleTriangleNumber(167), 1385280, ''<code>divisibleTriangleNumber(167)</code> should return 1385280.'');'
- text: <code>divisibleTriangleNumber(374)</code> should return 17907120.
testString: 'assert.strictEqual(divisibleTriangleNumber(374), 17907120, ''<code>divisibleTriangleNumber(374)</code> should return 17907120.'');'
- text: <code>divisibleTriangleNumber(500)</code> should return 76576500.
testString: 'assert.strictEqual(divisibleTriangleNumber(500), 76576500, ''<code>divisibleTriangleNumber(500)</code> should return 76576500.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function divisibleTriangleNumber(n) {
// Good luck!
return true;
}
divisibleTriangleNumber(500);
```
</div>
</section>
## Solution
<section id='solution'>
```js
function divisibleTriangleNumber(n) {
let counter = 1;
let triangleNumber = counter++;
function getFactors(num) {
let factors = [];
let possibleFactor = 1;
let sqrt = Math.sqrt(num);
while (possibleFactor <= sqrt) {
if (num % possibleFactor == 0) {
factors.push(possibleFactor);
var otherPossibleFactor = num / possibleFactor;
if (otherPossibleFactor > possibleFactor) {
factors.push(otherPossibleFactor);
}
}
possibleFactor++;
}
return factors;
}
while (getFactors(triangleNumber).length < n) {
triangleNumber += counter++;
}
console.log(triangleNumber)
return triangleNumber;
}
```
</section>

View File

@ -0,0 +1,57 @@
---
id: 5900f3e41000cf542c50fef7
challengeType: 5
title: 'Problem 120: Square remainders'
---
## Description
<section id='description'>
Let r be the remainder when (a1)n + (a+1)n is divided by a2.
For example, if a = 7 and n = 3, then r = 42: 63 + 83 = 728 ≡ 42 mod 49. And as n varies, so too will r, but for a = 7 it turns out that rmax = 42.
For 3 ≤ a ≤ 1000, find ∑ rmax.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler120()</code> should return 333082500.
testString: 'assert.strictEqual(euler120(), 333082500, ''<code>euler120()</code> should return 333082500.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler120() {
// Good luck!
return true;
}
euler120();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,58 @@
---
id: 5900f3e51000cf542c50fef8
challengeType: 5
title: 'Problem 121: Disc game prize fund'
---
## Description
<section id='description'>
A bag contains one red disc and one blue disc. In a game of chance a player takes a disc at random and its colour is noted. After each turn the disc is returned to the bag, an extra red disc is added, and another disc is taken at random.
The player pays £1 to play and wins if they have taken more blue discs than red discs at the end of the game.
If the game is played for four turns, the probability of a player winning is exactly 11/120, and so the maximum prize fund the banker should allocate for winning in this game would be £10 before they would expect to incur a loss. Note that any payout will be a whole number of pounds and also includes the original £1 paid to play the game, so in the example given the player actually wins £9.
Find the maximum prize fund that should be allocated to a single game in which fifteen turns are played.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler121()</code> should return 2269.
testString: 'assert.strictEqual(euler121(), 2269, ''<code>euler121()</code> should return 2269.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler121() {
// Good luck!
return true;
}
euler121();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,62 @@
---
id: 5900f3e61000cf542c50fef9
challengeType: 5
title: 'Problem 122: Efficient exponentiation'
---
## Description
<section id='description'>
The most naive way of computing n15 requires fourteen multiplications:
n × n × ... × n = n15
But using a "binary" method you can compute it in six multiplications:
n × n = n2n2 × n2 = n4n4 × n4 = n8n8 × n4 = n12n12 × n2 = n14n14 × n = n15
However it is yet possible to compute it in only five multiplications:
n × n = n2n2 × n = n3n3 × n3 = n6n6 × n6 = n12n12 × n3 = n15
We shall define m(k) to be the minimum number of multiplications to compute nk; for example m(15) = 5.
For 1 ≤ k ≤ 200, find ∑ m(k).
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler122()</code> should return 1582.
testString: 'assert.strictEqual(euler122(), 1582, ''<code>euler122()</code> should return 1582.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler122() {
// Good luck!
return true;
}
euler122();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,58 @@
---
id: 5900f3e71000cf542c50fefa
challengeType: 5
title: 'Problem 123: Prime square remainders'
---
## Description
<section id='description'>
Let pn be the nth prime: 2, 3, 5, 7, 11, ..., and let r be the remainder when (pn1)n + (pn+1)n is divided by pn2.
For example, when n = 3, p3 = 5, and 43 + 63 = 280 ≡ 5 mod 25.
The least value of n for which the remainder first exceeds 109 is 7037.
Find the least value of n for which the remainder first exceeds 1010.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler123()</code> should return 21035.
testString: 'assert.strictEqual(euler123(), 21035, ''<code>euler123()</code> should return 21035.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler123() {
// Good luck!
return true;
}
euler123();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,97 @@
---
id: 5900f3e81000cf542c50fefb
challengeType: 5
title: 'Problem 124: Ordered radicals'
---
## Description
<section id='description'>
The radical of n, rad(n), is the product of the distinct prime factors of n. For example, 504 = 23 × 32 × 7, so rad(504) = 2 × 3 × 7 = 42.
If we calculate rad(n) for 1 ≤ n ≤ 10, then sort them on rad(n), and sorting on n if the radical values are equal, we get:
Unsorted
Sorted
n
rad(n)
n
rad(n)
k
11
111
22
222
33
423
42
824
55
335
66
936
77
557
82
668
93
779
1010
101010
Let E(k) be the kth element in the sorted n column; for example, E(4) = 8 and E(6) = 9.
If rad(n) is sorted for 1 ≤ n ≤ 100000, find E(10000).
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler124()</code> should return 21417.
testString: 'assert.strictEqual(euler124(), 21417, ''<code>euler124()</code> should return 21417.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler124() {
// Good luck!
return true;
}
euler124();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,57 @@
---
id: 5900f3e91000cf542c50fefc
challengeType: 5
title: 'Problem 125: Palindromic sums'
---
## Description
<section id='description'>
The palindromic number 595 is interesting because it can be written as the sum of consecutive squares: 62 + 72 + 82 + 92 + 102 + 112 + 122.
There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums, and the sum of these palindromes is 4164. Note that 1 = 02 + 12 has not been included as this problem is concerned with the squares of positive integers.
Find the sum of all the numbers less than 108 that are both palindromic and can be written as the sum of consecutive squares.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler125()</code> should return 2906969179.
testString: 'assert.strictEqual(euler125(), 2906969179, ''<code>euler125()</code> should return 2906969179.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler125() {
// Good luck!
return true;
}
euler125();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,62 @@
---
id: 5900f3ea1000cf542c50fefd
challengeType: 5
title: 'Problem 126: Cuboid layers'
---
## Description
<section id='description'>
The minimum number of cubes to cover every visible face on a cuboid measuring 3 x 2 x 1 is twenty-two.
If we then add a second layer to this solid it would require forty-six cubes to cover every visible face, the third layer would require seventy-eight cubes, and the fourth layer would require one-hundred and eighteen cubes to cover every visible face.
However, the first layer on a cuboid measuring 5 x 1 x 1 also requires twenty-two cubes; similarly the first layer on cuboids measuring 5 x 3 x 1, 7 x 2 x 1, and 11 x 1 x 1 all contain forty-six cubes.
We shall define C(n) to represent the number of cuboids that contain n cubes in one of its layers. So C(22) = 2, C(46) = 4, C(78) = 5, and C(118) = 8.
It turns out that 154 is the least value of n for which C(n) = 10.
Find the least value of n for which C(n) = 1000.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler126()</code> should return 18522.
testString: 'assert.strictEqual(euler126(), 18522, ''<code>euler126()</code> should return 18522.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler126() {
// Good luck!
return true;
}
euler126();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,67 @@
---
id: 5900f3ec1000cf542c50fefe
challengeType: 5
title: 'Problem 127: abc-hits'
---
## Description
<section id='description'>
The radical of n, rad(n), is the product of distinct prime factors of n. For example, 504 = 23 × 32 × 7, so rad(504) = 2 × 3 × 7 = 42.
We shall define the triplet of positive integers (a, b, c) to be an abc-hit if:
GCD(a, b) = GCD(a, c) = GCD(b, c) = 1
a < b
a + b = c
rad(abc) < c
For example, (5, 27, 32) is an abc-hit, because:
GCD(5, 27) = GCD(5, 32) = GCD(27, 32) = 1
5 < 27
5 + 27 = 32
rad(4320) = 30 < 32
It turns out that abc-hits are quite rare and there are only thirty-one abc-hits for c < 1000, with c = 12523.
Find c for c < 120000.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler127()</code> should return 18407904.
testString: 'assert.strictEqual(euler127(), 18407904, ''<code>euler127()</code> should return 18407904.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler127() {
// Good luck!
return true;
}
euler127();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,64 @@
---
id: 5900f3ec1000cf542c50feff
challengeType: 5
title: 'Problem 128: Hexagonal tile differences'
---
## Description
<section id='description'>
A hexagonal tile with number 1 is surrounded by a ring of six hexagonal tiles, starting at "12 o'clock" and numbering the tiles 2 to 7 in an anti-clockwise direction.
New rings are added in the same fashion, with the next rings being numbered 8 to 19, 20 to 37, 38 to 61, and so on. The diagram below shows the first three rings.
By finding the difference between tile n and each of its six neighbours we shall define PD(n) to be the number of those differences which are prime.
For example, working clockwise around tile 8 the differences are 12, 29, 11, 6, 1, and 13. So PD(8) = 3.
In the same way, the differences around tile 17 are 1, 17, 16, 1, 11, and 10, hence PD(17) = 2.
It can be shown that the maximum value of PD(n) is 3.
If all of the tiles for which PD(n) = 3 are listed in ascending order to form a sequence, the 10th tile would be 271.
Find the 2000th tile in this sequence.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler128()</code> should return 14516824220.
testString: 'assert.strictEqual(euler128(), 14516824220, ''<code>euler128()</code> should return 14516824220.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler128() {
// Good luck!
return true;
}
euler128();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,58 @@
---
id: 5900f3ef1000cf542c50ff01
challengeType: 5
title: 'Problem 129: Repunit divisibility'
---
## Description
<section id='description'>
A number consisting entirely of ones is called a repunit. We shall define R(k) to be a repunit of length k; for example, R(6) = 111111.
Given that n is a positive integer and GCD(n, 10) = 1, it can be shown that there always exists a value, k, for which R(k) is divisible by n, and let A(n) be the least such value of k; for example, A(7) = 6 and A(41) = 5.
The least value of n for which A(n) first exceeds ten is 17.
Find the least value of n for which A(n) first exceeds one-million.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler129()</code> should return 1000023.
testString: 'assert.strictEqual(euler129(), 1000023, ''<code>euler129()</code> should return 1000023.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler129() {
// Good luck!
return true;
}
euler129();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,295 @@
---
id: 5900f37a1000cf542c50fe8c
challengeType: 5
title: 'Problem 13: Large sum'
---
## Description
<section id='description'>
Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>largeSum(testNums)</code> should return 8348422521.
testString: 'assert.strictEqual(largeSum(testNums), 8348422521, ''<code>largeSum(testNums)</code> should return 8348422521.'');'
- text: <code>largeSum(fiftyDigitNums)</code> should return 5537376230.
testString: 'assert.strictEqual(largeSum(fiftyDigitNums), 5537376230, ''<code>largeSum(fiftyDigitNums)</code> should return 5537376230.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function largeSum(arr) {
// Good luck!
return true;
}
// only change code above this line
const testNums = [
'37107287533902102798797998220837590246510135740250',
'46376937677490009712648124896970078050417018260538'
];
largeSum(testNums);
```
</div>
### Before Test
<div id='js-setup'>
```js
const fiftyDigitNums = [
'37107287533902102798797998220837590246510135740250',
'46376937677490009712648124896970078050417018260538',
'74324986199524741059474233309513058123726617309629',
'91942213363574161572522430563301811072406154908250',
'23067588207539346171171980310421047513778063246676',
'89261670696623633820136378418383684178734361726757',
'28112879812849979408065481931592621691275889832738',
'44274228917432520321923589422876796487670272189318',
'47451445736001306439091167216856844588711603153276',
'70386486105843025439939619828917593665686757934951',
'62176457141856560629502157223196586755079324193331',
'64906352462741904929101432445813822663347944758178',
'92575867718337217661963751590579239728245598838407',
'58203565325359399008402633568948830189458628227828',
'80181199384826282014278194139940567587151170094390',
'35398664372827112653829987240784473053190104293586',
'86515506006295864861532075273371959191420517255829',
'71693888707715466499115593487603532921714970056938',
'54370070576826684624621495650076471787294438377604',
'53282654108756828443191190634694037855217779295145',
'36123272525000296071075082563815656710885258350721',
'45876576172410976447339110607218265236877223636045',
'17423706905851860660448207621209813287860733969412',
'81142660418086830619328460811191061556940512689692',
'51934325451728388641918047049293215058642563049483',
'62467221648435076201727918039944693004732956340691',
'15732444386908125794514089057706229429197107928209',
'55037687525678773091862540744969844508330393682126',
'18336384825330154686196124348767681297534375946515',
'80386287592878490201521685554828717201219257766954',
'78182833757993103614740356856449095527097864797581',
'16726320100436897842553539920931837441497806860984',
'48403098129077791799088218795327364475675590848030',
'87086987551392711854517078544161852424320693150332',
'59959406895756536782107074926966537676326235447210',
'69793950679652694742597709739166693763042633987085',
'41052684708299085211399427365734116182760315001271',
'65378607361501080857009149939512557028198746004375',
'35829035317434717326932123578154982629742552737307',
'94953759765105305946966067683156574377167401875275',
'88902802571733229619176668713819931811048770190271',
'25267680276078003013678680992525463401061632866526',
'36270218540497705585629946580636237993140746255962',
'24074486908231174977792365466257246923322810917141',
'91430288197103288597806669760892938638285025333403',
'34413065578016127815921815005561868836468420090470',
'23053081172816430487623791969842487255036638784583',
'11487696932154902810424020138335124462181441773470',
'63783299490636259666498587618221225225512486764533',
'67720186971698544312419572409913959008952310058822',
'95548255300263520781532296796249481641953868218774',
'76085327132285723110424803456124867697064507995236',
'37774242535411291684276865538926205024910326572967',
'23701913275725675285653248258265463092207058596522',
'29798860272258331913126375147341994889534765745501',
'18495701454879288984856827726077713721403798879715',
'38298203783031473527721580348144513491373226651381',
'34829543829199918180278916522431027392251122869539',
'40957953066405232632538044100059654939159879593635',
'29746152185502371307642255121183693803580388584903',
'41698116222072977186158236678424689157993532961922',
'62467957194401269043877107275048102390895523597457',
'23189706772547915061505504953922979530901129967519',
'86188088225875314529584099251203829009407770775672',
'11306739708304724483816533873502340845647058077308',
'82959174767140363198008187129011875491310547126581',
'97623331044818386269515456334926366572897563400500',
'42846280183517070527831839425882145521227251250327',
'55121603546981200581762165212827652751691296897789',
'32238195734329339946437501907836945765883352399886',
'75506164965184775180738168837861091527357929701337',
'62177842752192623401942399639168044983993173312731',
'32924185707147349566916674687634660915035914677504',
'99518671430235219628894890102423325116913619626622',
'73267460800591547471830798392868535206946944540724',
'76841822524674417161514036427982273348055556214818',
'97142617910342598647204516893989422179826088076852',
'87783646182799346313767754307809363333018982642090',
'10848802521674670883215120185883543223812876952786',
'71329612474782464538636993009049310363619763878039',
'62184073572399794223406235393808339651327408011116',
'66627891981488087797941876876144230030984490851411',
'60661826293682836764744779239180335110989069790714',
'85786944089552990653640447425576083659976645795096',
'66024396409905389607120198219976047599490197230297',
'64913982680032973156037120041377903785566085089252',
'16730939319872750275468906903707539413042652315011',
'94809377245048795150954100921645863754710598436791',
'78639167021187492431995700641917969777599028300699',
'15368713711936614952811305876380278410754449733078',
'40789923115535562561142322423255033685442488917353',
'44889911501440648020369068063960672322193204149535',
'41503128880339536053299340368006977710650566631954',
'81234880673210146739058568557934581403627822703280',
'82616570773948327592232845941706525094512325230608',
'22918802058777319719839450180888072429661980811197',
'77158542502016545090413245809786882778948721859617',
'72107838435069186155435662884062257473692284509516',
'20849603980134001723930671666823555245252804609722',
'53503534226472524250874054075591789781264330331690'
];
const testNums = [
'37107287533902102798797998220837590246510135740250',
'46376937677490009712648124896970078050417018260538'
];
```
</div>
</section>
## Solution
<section id='solution'>
```js
function largeSum(arr) {
let sum = 0;
arr.forEach(function(num) {
sum += parseInt(num, 10);
});
sum = sum.toString(10);
sum = sum.substr(0, 1) + sum.substr(2);
let firstTen = sum.slice(0, 10);
return parseInt(firstTen, 10);
}
```
</section>

View File

@ -0,0 +1,59 @@
---
id: 5900f3ee1000cf542c50ff00
challengeType: 5
title: 'Problem 130: Composites with prime repunit property'
---
## Description
<section id='description'>
A number consisting entirely of ones is called a repunit. We shall define R(k) to be a repunit of length k; for example, R(6) = 111111.
Given that n is a positive integer and GCD(n, 10) = 1, it can be shown that there always exists a value, k, for which R(k) is divisible by n, and let A(n) be the least such value of k; for example, A(7) = 6 and A(41) = 5.
You are given that for all primes, p > 5, that p 1 is divisible by A(p). For example, when p = 41, A(41) = 5, and 40 is divisible by 5.
However, there are rare composite values for which this is also true; the first five examples being 91, 259, 451, 481, and 703.
Find the sum of the first twenty-five composite values of n for whichGCD(n, 10) = 1 and n 1 is divisible by A(n).
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler130()</code> should return 149253.
testString: 'assert.strictEqual(euler130(), 149253, ''<code>euler130()</code> should return 149253.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler130() {
// Good luck!
return true;
}
euler130();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,58 @@
---
id: 5900f3ef1000cf542c50ff02
challengeType: 5
title: 'Problem 131: Prime cube partnership'
---
## Description
<section id='description'>
There are some prime values, p, for which there exists a positive integer, n, such that the expression n3 + n2p is a perfect cube.
For example, when p = 19, 83 + 82×19 = 123.
What is perhaps most surprising is that for each prime with this property the value of n is unique, and there are only four such primes below one-hundred.
How many primes below one million have this remarkable property?
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler131()</code> should return 173.
testString: 'assert.strictEqual(euler131(), 173, ''<code>euler131()</code> should return 173.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler131() {
// Good luck!
return true;
}
euler131();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,57 @@
---
id: 5900f3f11000cf542c50ff03
challengeType: 5
title: 'Problem 132: Large repunit factors'
---
## Description
<section id='description'>
A number consisting entirely of ones is called a repunit. We shall define R(k) to be a repunit of length k.
For example, R(10) = 1111111111 = 11×41×271×9091, and the sum of these prime factors is 9414.
Find the sum of the first forty prime factors of R(109).
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler132()</code> should return 843296.
testString: 'assert.strictEqual(euler132(), 843296, ''<code>euler132()</code> should return 843296.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler132() {
// Good luck!
return true;
}
euler132();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,58 @@
---
id: 5900f3f21000cf542c50ff04
challengeType: 5
title: 'Problem 133: Repunit nonfactors'
---
## Description
<section id='description'>
A number consisting entirely of ones is called a repunit. We shall define R(k) to be a repunit of length k; for example, R(6) = 111111.
Let us consider repunits of the form R(10n).
Although R(10), R(100), or R(1000) are not divisible by 17, R(10000) is divisible by 17. Yet there is no value of n for which R(10n) will divide by 19. In fact, it is remarkable that 11, 17, 41, and 73 are the only four primes below one-hundred that can be a factor of R(10n).
Find the sum of all the primes below one-hundred thousand that will never be a factor of R(10n).
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler133()</code> should return 453647705.
testString: 'assert.strictEqual(euler133(), 453647705, ''<code>euler133()</code> should return 453647705.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler133() {
// Good luck!
return true;
}
euler133();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,57 @@
---
id: 5900f3f21000cf542c50ff05
challengeType: 5
title: 'Problem 134: Prime pair connection'
---
## Description
<section id='description'>
Consider the consecutive primes p1 = 19 and p2 = 23. It can be verified that 1219 is the smallest number such that the last digits are formed by p1 whilst also being divisible by p2.
In fact, with the exception of p1 = 3 and p2 = 5, for every pair of consecutive primes, p2 > p1, there exist values of n for which the last digits are formed by p1 and n is divisible by p2. Let S be the smallest of these values of n.
Find ∑ S for every pair of consecutive primes with 5 ≤ p1 ≤ 1000000.
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler134()</code> should return 18613426663617120.
testString: 'assert.strictEqual(euler134(), 18613426663617120, ''<code>euler134()</code> should return 18613426663617120.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler134() {
// Good luck!
return true;
}
euler134();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

View File

@ -0,0 +1,58 @@
---
id: 5900f3f31000cf542c50ff06
challengeType: 5
title: 'Problem 135: Same differences'
---
## Description
<section id='description'>
Given the positive integers, x, y, and z, are consecutive terms of an arithmetic progression, the least value of the positive integer, n, for which the equation, x2 y2 z2 = n, has exactly two solutions is n = 27:
342 272 202 = 122 92 62 = 27
It turns out that n = 1155 is the least value which has exactly ten solutions.
How many values of n less than one million have exactly ten distinct solutions?
</section>
## Instructions
<section id='instructions'>
</section>
## Tests
<section id='tests'>
```yml
tests:
- text: <code>euler135()</code> should return 4989.
testString: 'assert.strictEqual(euler135(), 4989, ''<code>euler135()</code> should return 4989.'');'
```
</section>
## Challenge Seed
<section id='challengeSeed'>
<div id='js-seed'>
```js
function euler135() {
// Good luck!
return true;
}
euler135();
```
</div>
</section>
## Solution
<section id='solution'>
```js
// solution required
```
</section>

Some files were not shown because too many files have changed in this diff Show More