fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@ -0,0 +1,198 @@
---
title: Find the Symmetric Difference
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a href="https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/" rel="help">**`Read-Search-Ask`**</a> if you get stuck. Try to pair program![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation: ###
Symmetric difference (commonly denoted by &Delta;) of two sets is the set of elements which are in either of the two sets, but not in both.
For example, `sym([1, 2, 3], [5, 2, 1, 4])` should yield `[3, 4, 5]`.
Following above definition, symmetric difference of three sets *A*, *B*, and *C* can be expressed as `(A &Delta; B) &Delta; C`.
#### Relevant Links ####
* <a href="https://en.wikipedia.org/wiki/Symmetric_difference" target="_blank" rel="nofollow">Symmetric difference - Wikipedia</a>
* <a href="https://www.youtube.com/watch?v=PxffSUQRkG4" target="_blank" rel="nofollow">Symmetric difference - YouTube</a>
* <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce" target="_blank"
rel="nofollow">JavaScript Array.prototype.reduce()</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1 ##
The *arguments* object is *Array*-like object that only inherits `Array.length` property. Hence consider converting it to an actual *Array*.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2 ##
Deem writing a helper function that returns the symmetric difference of two arrays on each call instead of attempting to difference all sets simultaneously.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3 ##
Apply helper function against the created arguments array reducing its elements pairwise recursively to form the expected output.
**Note**
In the event of *odd number of sets* the symmetric difference will include identical elements present in all given sets. For instance;
A = {1, 2, 3}
B = {2, 3, 4}
C = {3, 4, 5}
(A &Intersection; B) &Intersection; C = {1, 4} &Intersection {3, 4, 5}
A &Intersection; B = {1, 3, 5}
> _try to solve the problem now_
## Spoiler Alert! ##
![:warning:](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif ":warning:")
**Solution Ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution: ##
```javascript
function sym() {
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(arguments[i]);
}
function symDiff(arrayOne, arrayTwo) {
var result = [];
arrayOne.forEach(function(item) {
if (arrayTwo.indexOf(item) < 0 && result.indexOf(item) < 0) {
result.push(item);
}
});
arrayTwo.forEach(function(item) {
if (arrayOne.indexOf(item) < 0 && result.indexOf(item) < 0) {
result.push(item);
}
});
return result;
}
// Apply reduce method to args array, using the symDiff function
return args.reduce(symDiff);
}
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href="https://repl.it/C4II/0" target="_blank" rel="nofollow">Run Code</a>
### Code Explanation: ###
* `push()` is used to break down the *arguments* object to an array, *args*.
* The `symDiff` function finds the symmetric difference between two sets. It is used as a callback function for the `reduce()` method called on *args*.
* `arrayOne.forEach()` pushes the elements to *result* which are present only in *arrayOne* as well as not already a part of *result*.
* `arrayTwo.forEach()` pushes the elements to *result* which are present only in *arrayTwo* as well as not already a part of *result*.
* The *result*, which is the symmetric difference is returned. This solution works for any number of sets.
#### Relevant Links ####
* <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/statements/for" target="_blank" rel="nofollow">JavaScript for</a>
* <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/length" target="_blank" rel="nofollow">JavaScript Array.length</a>
* <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push" target="_blank" rel="nofollow">JavaScript Array.prototype.push()</a>
* <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach" target="_blank" rel="nofollow">JavaScript Array.prototype.forEach()</a>
* <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf" target="_blank" rel="nofollow">JavaScript Array.prototype.indexOf()</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution: ##
```javascript
function sym() {
// Convert the argument object into a proper array
var args = Array.prototype.slice.call(arguments);
// Return the symmetric difference of 2 arrays
var getDiff = function(arr1, arr2) {
// Returns items in arr1 that don't exist in arr2
function filterFunction(arr1, arr2) {
return arr1.filter(function(item) {
return arr2.indexOf(item) === -1;
});
}
// Run filter function on each array against the other
return filterFunction(arr1, arr2)
.concat(filterFunction(arr2, arr1));
};
// Reduce all arguments getting the difference of them
var summary = args.reduce(getDiff, []);
// Run filter function to get the unique values
var unique = summary.filter(function(elem, index, self) {
return index === self.indexOf(elem);
});
return unique;
}
// test here
sym([1, 2, 3], [5, 2, 1, 4]);
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href="https://repl.it/CLoc/0" target="_blank" rel="nofollow">Run Code</a>
### Code Explanation: ###
* The `slice()` method is used to break down the *arguments* object to an array, *args*.
* The `getDiff` function finds the symmetric difference between two sets, *arr1* and *arr2*. It is used as a callback function for the `reduce()` method called on *args*.
* The first `filterFunction()` returns elements in *arr1* that don't exist in *arr2*.
* The next `filterFunction()` is run on each array against the other to check the inverse of the first check for uniqueness and concatenate it.
* *summary* consists of the reduced arguments.
* `filter()` is used on *summary* to keep only the unique values and *unique* is returned.
#### Relevant Links ####
* <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice" target="_blank" rel="nofollow">JavaScript Array.prototype.slice()</a>
* <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" target="_blank" rel="nofollow">JavaScript Array.prototype.filter()</a>
* <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat" target="_blank" rel="nofollow">JavaScript Array.prototype.concat()</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution: ##
```javascript
function sym() {
let argv = Array.from(arguments).reduce(diffArray);
return argv.filter((element, index, array) => index === array.indexOf(element));//remove duplicates
}
function diffArray(arr1, arr2) {
return arr1
.filter(element => !arr2.includes(element))
.concat(arr2.filter(element => !arr1.includes(element)));
}
// test here
sym([1, 2, 3], [5, 2, 1, 4]);
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href="https://repl.it/@ashenm/Symmetric-Difference" target="_blank" rel="nofollow">Run Code</a>
### Code Explanation: ###
* The main function *sym()* creates an array from *arguments* and reduces its elements utilising helper function *diffArray()* to a single array.
* The function *diffArray()* returns the symmetric difference of two arrays by picking out unique elements in parameterised arrays; *arr1* and *arr2*.
#### Relevant Links ####
* <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from" target="_blank" rel="nofollow">JavaScript Array.from()</a>
* <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" target="_blank" rel="nofollow">JavaScript Array.prototype.filter()</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS: ##
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href="http://forum.freecodecamp.com/t/algorithm-article-template/14272" target="_blank" rel="nofollow">**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,49 @@
---
title: Implement Bubble Sort
---
## Implement Bubble Sort
### Method:
- Bubble Sort is a sorting algorithm which sorts or *bubbles* the largest number as last element at the end of each pass.
- We compare each element to the one ahead of it, if the element before is smaller, we swap their places.
- Bubble Sort's time complexity is **O(n<sup>2</sup>)**.
- It's a **stable** algorithm.
- ![Bubble sort in action](https://upload.wikimedia.org/wikipedia/commons/c/c8/Bubble-sort-example-300px.gif)
### Solution:
#### Solution 1: Basic
```js
function swap(a, b, arr){
let tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
function bubbleSort(array) {
for (let i = 0; i < array.length; i++){
for (let j = 0; j < array.length-1-i; j++){ // -i because the largest element will be bubbled at the end so we don't have to compare.
if (array[j] > array[j+1]){
swap(j, j+1, array);
}
}
}
return array;
}
```
#### Solution 2: Advanced
```js
function bubbleSort(array) {
for (let i = 0; i < array.length; i++){
for (let j = 0; j < array.length-1-i; j++){
if (array[j] > array[j+1]) [array[j], array[j+1]] = [array[j+1], array[j]]; // Using ES6 array destructuring to swap
}
}
return array;
}
```
- [Run Code](https://repl.it/@ezioda004/Bubble-Sort)
### References:
- [GeeksForGeeks](https://www.geeksforgeeks.org/bubble-sort/)
- [Wikipedia](https://en.wikipedia.org/wiki/Bubble_sort)
- Video by [HackerRank](https://www.youtube.com/watch?v=6Gv8vg0kcHc)

View File

@ -0,0 +1,34 @@
---
title: Implement Insertion Sort
---
## Implement Insertion Sort
### Method:
- Insertion Sort assumes that array is divided in two parts:
1. Sorted (Initially the first element)
2. Unsorted
- Each pass, we select an element, and check it against the sorted array.
- If the selected element is smaller than the last element of the sorted array then we shift the sorted array by 1 until we find the spot to *insert* the selected element.
- ![Insertion sort in action](https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif) - [source](https://en.wikipedia.org/wiki/Insertion_sort)
- Time comlexity of Insertion sort is of **O(n<sup>2</sup>)**.
- It's a **stable** algorithm.
### Solution:
```js
function insertionSort(array) {
for (let i = 1; i < array.length; i++){
let curr = array[i];
for (var j = i-1; j >= 0 && array[j] > curr; j--){
array[j+1] = array[j];
}
array[j+1] = curr;
}
return array;
}
```
- [Run Code](https://repl.it/@ezioda004/Insertion-Sort)
### References:
- [Wikipedia](https://en.wikipedia.org/wiki/Insertion_sort)
- [Khan Academy](https://www.youtube.com/watch?v=lCzQvQr8Utw)

View File

@ -0,0 +1,50 @@
---
title: Implement Merge Sort
---
## Implement Merge Sort
### Method:
- Merge Sort is a classic divide and conquer problem.
- The following steps are involved:
- Divide: We break the array from the middle using recusion until we're left with 1 element.
- Conquer: Then we sort these small arrays.
- Combine: Finally, we merge these small arrays into one sorted array and keep doing it until we combine all the arrays.
- Time complexity of Merge Sort is **O(nlogn)**.
- Space complexity of Merge Sort is **O(n)**.
- It's a **stable** algorithm.
- ![Merge Sort in action](https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif)
### Solution:
```js
//Merger function, which merges 2 sorted array into 1 sorted array
function merger(arr1, arr2){
let i = 0, j = 0, mergedArr = [];
while (i < arr1.length && j < arr2.length){
if (arr1[i] > arr2[j]) mergedArr.push(arr2[j++]);
else mergedArr.push(arr1[i++]);
}
while (i < arr1.length){
mergedArr.push(arr1[i++]);
}
while (j < arr2.length){
mergedArr.push(arr2[j++]);
}
return mergedArr;
}
function mergeSort(array) {
//Array of length 1 is sorted so we return the same array back
if (array.length == 1) return array;
//Break down the array to half from middle into left and right
let middle = Math.floor(array.length/2);
let left = mergeSort(array.slice(0, middle));
let right = mergeSort(array.slice(middle));
//Return the merged sorted array
return merger(left, right);
}
```
- [Run Code](https://repl.it/@ezioda004/Merge-Sort)
### References:
- [Wikipedia](https://en.wikipedia.org/wiki/Merge_sort)
- Video by [Hackerrank](https://www.youtube.com/watch?v=KF2j-9iSf4Q)

View File

@ -0,0 +1,51 @@
---
title: Implement Quick Sort
---
## Implement Quick Sort
### Method:
- Quick sort is an efficient sorting algorithm. It's an in-place algorithm so it doesn't take any auxilary space.
- First pick a random pivot point around which move all the smaller elements to it to the left of it and the bigger elements to the right of it.
- After getting the pivotIndex which is essentially the fixed position of that element, we find other pivotIndex by recusirvely calling this function.
- Quick sort's worst case is **O(n<sup>2</sup>)** but that can be avoided if we pick random pivot point, so that way it's big O is **O(nlogn)**.
- It's space complexity is **O(logn)**.
- It's an **unstable** algorithm.
- ![Quick sort in action](https://upload.wikimedia.org/wikipedia/commons/6/6a/Sorting_quicksort_anim.gif)
### Solution:
```js
//Swapping array elements via ES6 array destructuring
function swap(arr, x, y){
[arr[x], arr[y]] = [arr[y], arr[x]];
}
//Pivot function returns the fixed pivot point
function pivot(arr, left = 0, right = arr.length-1){
let shift = left;
for (let i = left+1; i <= right; i++){
//Move all the small elements on the left side
if (arr[i] < arr[left]) swap(arr, i, ++shift);
}
//Finally swapping the last element with the left
swap(arr, left, shift);
return shift;
}
function quickSort(array, left = 0, right = array.length-1) {
if (left < right){
let pivotIndex = pivot(array, left, right);
//Recusrively calling the function to the left of the pivot and to the right of the pivot
quickSort(array, left, pivotIndex-1);
quickSort(array, pivotIndex+1, right);
}
return array;
}
```
- [Run Code](https://repl.it/@ezioda004/Quick-Sort)
### Reference:
- [Wikipedia](https://en.wikipedia.org/wiki/Quicksort)
- [Khan Academy](https://www.khanacademy.org/computing/computer-science/algorithms/quick-sort/a/overview-of-quicksort)

View File

@ -0,0 +1,36 @@
---
title: Implement Selection Sort
---
## Implement Selection Sort
### Method:
- Selection Sort is one of the easier sorting algorithm to understand and implement.
- This algorithm splits the array in two parts:
1. Sorted
2. Unsorted
- The Sorted part is at the beginning of the array and Unsorted part afterwards.
- Each pass, initially we assume the first element to be the smallest then we loop through the whole array and *select* the smallest element. At the end of the pass we swap smallest element to the sorted array.
- It has **O(n<sup>2</sup>)** time complexity.
### Solution:
```js
function swap(a, b, arr){
let tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
function selectionSort(array) {
for (let i = 0; i < array.length-1; i++){
let min = i;
for (let j = i+1; j < array.length; j++){
if (array[min] > array[j]) min = j;
}
swap(i, min, array);
}
return array;
}
```
### References:
- Read about Selection Sort at [Wikipedia](https://en.wikipedia.org/wiki/Selection_sort)

View File

@ -0,0 +1,13 @@
---
title: Algorithms
---
## Algorithms
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
#### More Information:
<!-- Please add any articles you think might be helpful to read before writing the article -->

View File

@ -0,0 +1,293 @@
---
title: Inventory Update
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
In this problem, you've to 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 `arr1`). 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.
The current as well as new inventory will be in this format: `[[2, "item-0"], [3, "item-1"], [67, "item-2"], [7, "item-3"]]`.
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array' target='_blank' rel='nofollow'>JS Array</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
You need to work through each item of the new inventory to see if it exists in the current inventory or not. Remember that the product name is stored as the second element of each sub-array: `array[0][1] = "item-name"`.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
If the item exists, you need to add the quantity from the new inventory. If the item doesn't exist, you need to add the entire item.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
Return the completed inventory in alphabetical order.
> _try to solve the problem now_
## Spoiler Alert!
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
```javascript
function updateInventory(arr1, arr2) {
// Variable for location of product
var index;
// A helper method to return the index of a specified product (undefined if not found)
var getProductIndex = function (name) {
for (var i = 0; i < this.length; i++) {
if (this<a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>i][1] === name) {
return i;
}
}
return undefined;
}
// For each item of the new Inventory
for (var i = 0; i < arr2.length; i++) {
// Invoke our helper function using arr1 as this
index = getProductIndex.call(arr1, arr2[i][1]);
// If the item doesn't exist
if (index === undefined) {
// Push the entire item
arr1.push(arr2[i]);
} else {
// Add the new quantity of the current item
arr1[index][0] += arr2[i][0];
}
}
// Sort alphabetically, by the product name of each item
arr1.sort(function (a, b) {
if (a[1] > b[1]) {
return 1;
}
if (a[1] < b[1]) {
return -1;
}
return 0;
});
return arr1;
}
// test here
// 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);
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLok/0' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
* The variable **index** stores the location (index) of a product.
* The helper function `getProductIndex()` returns the index of a specified product. It iterates through each element of the array that it is called on until it can find the name parameter. If the product is not found in the inventory, `undefined` is returned.
* Then, each item in the new inventory (delivery) is worked through:
* **index** is set to the result of invoking the helper function i.e., search the new inventory for that product name and return it's index.
* If the item is found, quantity of the product is added to the quantity of the same product in current inventory.
* If the item is not found, the entire product (name and quantity) is added to the current inventory.
* The updated inventory, **arr1**, is then sorted by product name (held in `arr1[x][1]`).
* The final - updated as well as sorted array is then returned.
#### Relevant Links
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this' target='_blank' rel='nofollow'>JS this</a>
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/length' target='_blank' rel='nofollow'>JS Array.length</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-push/14298' target='_blank' rel='nofollow'>JS Array.prototype.push()</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-sort/14306' target='_blank' rel='nofollow'>JS Array.prototype.sort()</a>
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":sunflower:") Intermediate Code Solution:
```javascript
function updateInventory(arr1, arr2) {
// All inventory must be accounted for or you're fired!
var index;
var arrCurInvName = <a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>]; // Names of arr1's items
var arrNeInvName = []; // Names of arr2's items
// Same as using two for loops, this takes care of increasing the number of stock quantity.
arr1.map(function(item1) {
return arr2.map(function(item2) {
if (item1[1] === item2[1]) {
item1[0] = item1[0] + item2[0]; //Increase number of stock
}
});
});
// Get item's name for new Inventory
arr2.map(function(item) {
arrNeInvName.push(item[1]);
});
// Get item's name for Current Inventory
arr1.map(function(item) {
arrCurInvName.push(item[1]);
});
// Add new inventory items to current inventory.
arrNeInvName.map(function(item) {
if (arrCurInvName.indexOf(item) === -1) {
index = arrNeInvName.indexOf(item);
arr1.push(arr2[index]);
}
});
// Sort the array alphabetically using the second element of the array as base.
arr1.sort(function(currItem, nextItem) {
//Ternary function to avoid using if else
return currItem[1] > nextItem[1] ? 1 : -1;
});
return arr1;
}
// test here
// 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);
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLol/0' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
* The variable **index** stores the location (index) of a product.
* **arrCurInvName** has the names of **arr1**'s items.
* **arrNeInvName** has the names of **arr2**'s items.
* `arr1.map(function(item1))` takes care of items already existing in inventory i.e., it increases the quantity in the inventory.
* Next, `arr2.map(function(item))` and `arr1.map(function(item))` get the names of items for the new and current inventory respectively.
* `arrNeInvName.map(function(item))` handles items which don't already exist in inventory i.e., it adds new items to the inventory.
* The updated array **arr1** is then sorted alphabetically by product name (held in `arr1[x][1]`) and returned.
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map' target='_blank' rel='nofollow'>JS Array.prototype.map()</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-indexof/14291' target='_blank' rel='nofollow'>JS Array.prototype.indexOf()</a>
* <a href='http://forum.freecodecamp.com/t/javascript-ternary-operator/15973' target='_blank' rel='nofollow'>JS Ternary Operator</a>
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 ":rotating_light:") Advanced Code Solution:
```javascript
function updateInventory(arr1, arr2) {
// All inventory must be accounted for or you're fired!
// convert current inventory (arr1) to an one-dimensional array
const inventory = Array.prototype.concat.apply([], arr1);
// loop through new delivery (arr2)
for (let i = 0; i < arr2.length; i++) {
// extract item properties for easy reference
const item = arr2[i][1];
const quantity = arr2[i][0];
// check if item already exists in inventory
const position = inventory.indexOf(item);
// exsisting item: update quantity
if (position !== -1) {
const row = Math.floor(position / 2);
arr1[row][0] += quantity;
continue;
}
// alien item: add to inventory
arr1.push([quantity, item]);
}
// sort inventory in alphabetical order
arr1.sort((previous, next) => (previous[1] > [next[1]]) ? 1 : -1);
return arr1;
}
// test here
// 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);
```
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/MQvv/latest' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
* Convert current inventory array **arr1** to an one-dimensional array in order that `indexOf()` method could be used to check existance of new delivery items in current inventory.
* Check if item already exists in current inventory using `indexOf()`.
* If item exists update quantity and continue loop execution.
* Else append item to inventory.
* Finally, sort the array alphabetically and return the updated inventory.
#### Relevant Links
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply'>JS Function.prototype.apply()</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue' target='_blank' rel='nofollow'>JS continue</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort' target='_blank' rel='nofollow'>JS Array.prototype.sort()</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,173 @@
---
title: No Repeats Please
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 ":checkered_flag:") Problem Explanation:
This task requires us to return the number of total permutations of the provided string that don't have repeated consecutive letters. It is to be assumed that all characters in the provided string are each unique. For example, `aab` should return 2 because it has 6 total permutations (`aab`, `aab`, `aba`, `aba`, `baa`, `baa`), but only 2 of them (`aba` and `aba`) don't have the same letter (in this case `a`) repeating.
To achieve that, we'll have to look at each possible permutation of a string. There are several ways to do that. A common interview question is building a function that collects all permutations of a string. There are several tutorials available on the internet on how to do that.
#### Potential Methods Used As Solution
##### Recursive Method
This task can be daunting even after watching a tutorial. To write a recursive solution, you will want to send each new use of the function three inputs:
1. A new string (or character array) that is being built.
2. A position in your new string that's going to be filled next.
3. An idea of what characters (more specifically positions) from the original string have yet to be used.
The pseudo code will look something like this:
var str = ???;
permAlone(current position in original string, characters used already in original string, created string) {
if (current string is finished) {
print current string;
} else {
for (var i = 0; i < str.length; i++) {
if (str[i] has not been used) {
put str[i] into the current position of new string;
mark str[i] as used;
permAlone(current position in original string, characters used already in original string, created string);
remove str[i] as used because another branch in the tree for i + 1 will likely use it;
}
}
}
}
permAlone(0, nothing used yet, empty new string (or array the same size as str));
Another way to think about this problem is to start from an empty space. Introduce the first letter to the space. This space will now contain the first sub-permutation. Here's a diagram illustrating the idea:
![diagram](//discourse-user-assets.s3.amazonaws.com/original/2X/6/69896bacc8bd3b2e347beb4b304a7f97caa6d9ab.png)
##### Non-Recursive Method
// An approach to introduce a new character to a permutation
var ch = '?';
var source = ['?', '?', '?']; // Current sub-permutation
var temp, dest = [];
for (var i = 0; i <= source.length; ++i) {
temp = source.slice(0); // Copy the array
temp.splice(i, 0, ch); // Insert the new character
dest.push(temp); // Store the new sub-permutation
}
Finding each permutation could then be done non-recursively by including the above in a function taking a source array and returning a destination array. For each letter of the input string, pass that character, as well as the array returned from the previous call of the function.
A way to visualize this is by considering a tree that starts with the first character of your string:
![Permutation Tree](//discourse-user-assets.s3.amazonaws.com/original/2X/8/8187f2b06cdc02cf62286c18ce15bfcdc99bc68c.png)
#### Relevant Links
* <a href='https://www.mathsisfun.com/combinatorics/combinations-permutations.html' target='_blank' rel='nofollow'>Permutations</a>
* <a href='https://en.wikipedia.org/wiki/Heap%27s_algorithm' target='_blank' rel='nofollow'>Heap's algorithm</a>
* <a>JS Regex Resources</a>
* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String' target='_blank' rel='nofollow'>JS String object</a>
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1
* The easiest way is to use Heap's algorithm to recursively get a list of all the permutations.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 2
* Once you have the list then just create a regular expression to catch the repeating characters.
> _try to solve the problem now_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 3
* You will want to have the permutations as an array of joined strings instead of separated characters.
> _try to solve the problem now_
## Spoiler Alert!
![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**Solution ahead!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution:
function permAlone(str) {
// Create a regex to match repeated consecutive characters.
var regex = /(.)\1+/g;
// Split the string into an array of characters.
var arr = str.split('');
var permutations = <a href='https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:"' target='_blank' rel='nofollow'>];
var tmp;
// Return 0 if str contains same character.
if (str.match(regex) !== null && str.match(regex)[0] === str) return 0;
// Function to swap variables' content.
function swap(index1, index2) {
tmp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = tmp;
}
// Generate arrays of permutations using the algorithm.
function generate(int) {
if (int === 1) {
// Make sure to join the characters as we create the permutation arrays
permutations.push(arr.join(''));
} else {
for (var i = 0; i != int; ++i) {
generate(int - 1);
swap(int % 2 ? 0 : i, int - 1);
}
}
}
generate(arr.length);
// Filter the array of repeated permutations.
var filtered = permutations.filter(function(string) {
return !string.match(regex);
});
// Return how many have no repetitions.
return filtered.length;
}
// Test here.
permAlone('aab');
![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://repl.it/CLop/0' target='_blank' rel='nofollow'>Run Code</a>
### Code Explanation:
* **regex** contains the regular expression to match repeated consecutive characters.
* The string **str** is split into an array of characters, **arr**.
* 0 is returned if **str** contains same characters.
* The function `swap()` is used for the purpose of swapping the contents of two variable's contents.
* The next block of code uses Heap's algorithm to generate arrays of permutations in **permutations**.
* The **filtered** variable filters **permutations** to include only non-repeated permutations.
* `filtered.length` returns the number of total permutations of the provided string that don't have repeated consecutive letters.
#### Relevant Links
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-split/15944' target='_blank' rel='nofollow'>JS String Prototype Split</a>
* <a href='http://forum.freecodecamp.com/t/javascript-string-prototype-match/15941' target='_blank' rel='nofollow'>JS String Prototype Match</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-push/14298' target='_blank' rel='nofollow'>JS Array Prototype Push</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-join/14292' target='_blank' rel='nofollow'>JS Array Prototype Join</a>
* <a href='http://forum.freecodecamp.com/t/javascript-for-loop/14666s-Explained' target='_blank' rel='nofollow'>JS For Loops Explained</a>
* <a href='https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/length' target='_blank' rel='nofollow'>array.length</a>
* <a href='http://forum.freecodecamp.com/t/javascript-array-prototype-filter/14289' target='_blank' rel='nofollow'>JS Array Prototype Filter</a>
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution.
* Add an explanation of your solution.
* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:")
* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_)
> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference.

View File

@ -0,0 +1,10 @@
---
title: Pairwise
---
## Pairwise
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/algorithms/pairwise/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->