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,200 @@
---
title: Find the Symmetric Difference
localeTitle: 找到对称差异
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 "triangular_flag_on_post")如果卡住,请记得使用[**`Read-Search-Ask`**](https://forum.freecodecamp.org/t/how-to-get-help-when-you-are-stuck/) 。尝试配对程序![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 "busts_in_silhouette")并编写自己的代码![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":铅笔:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 "checkered_flag")问题说明:
两组的对称差异(通常用Δ表示)是在两组中的任一组中的元素集,但在两者中都不是。
例如, `sym([1, 2, 3], [5, 2, 1, 4])`应该产生`[3, 4, 5]`
根据上述定义三组_A_ _B_和_C的_对称差异可表示为`(A Δ B) Δ C`
#### 相关链接
* [对称差异 - 维基百科](https://en.wikipedia.org/wiki/Symmetric_difference)
* [对称差异 - YouTube](https://www.youtube.com/watch?v=PxffSUQRkG4)
[](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
[## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 "speech_balloon")提示1
_arguments_对象是类似_Array_的对象只继承`Array.length`属性。因此请考虑将其转换为实际的_数组_ 。
> _现在尝试解决问题_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 "speech_balloon")提示2
Deem编写一个辅助函数在每次调用时返回两个数组的对称差异而不是试图同时区分所有集合。
> _现在尝试解决问题_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 "speech_balloon")提示3
对创建的arguments数组应用辅助函数递归地逐对减少元素以形成预期的输出。
**注意** 在_奇数个集合_的情况下对称差异将包括在所有给定集合中存在的相同元素。例如;
```
A = {1, 2, 3}
B = {2, 3, 4}
C = {3, 4, 5}
(A ⋂ B) ⋂ C = {1, 4} &Intersection {3, 4, 5}
A ⋂ B = {1, 3, 5}
```
> _现在尝试解决问题_
## 扰流警报!
![:warning:](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif ":警告:")
**提前解决!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":初学者:")基本代码解决方案
```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);
}
```](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
[![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":火箭:")](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) [运行代码](https://repl.it/C4II/0)
### 代码说明:
* `push()`用于将_arguments_对象分解为数组_args_ 。
* `symDiff`函数查找两个集合之间的对称差异。它用作_args上_调用的`reduce()`方法的回调函数。
* `arrayOne.forEach()`将元素推送到_结果_ 这些元素仅存在于_arrayOne中_ 并且还不是_结果_的一部分。
* `arrayTwo.forEach()`将元素推送到_结果中_ 这些元素仅存在于_arrayTwo中_ 并且还不是_结果_的一部分。
* 返回_结果_ ,即对称差异。此解决方案适用于任意数量的集合。
#### 相关链接
* [JavaScript for](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/statements/for)
* [JavaScript Array.length](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/length)
* [JavaScript Array.prototype.push](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push)
* [JavaScript Array.prototype.forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
* [JavaScript Array.prototype.indexOf](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":向日葵:")中级代码解决方案:
```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 ":火箭:") [运行代码](https://repl.it/CLoc/0)
### 代码说明:
* `slice()`方法用于将_arguments_对象分解为数组_args_ 。
* `getDiff`函数查找两个集合_arr1_和_arr2_之间的对称差异。它用作_args上_调用的`reduce()`方法的回调函数。
* 第一个`filterFunction()`返回_arr1_中_arr2中_不存在的元素。
* 下一个`filterFunction()`在每个数组`filterFunction()`对于另一个运行,以检查第一次检查唯一性的反转并连接它。
* _摘要_包含减少的参数。
* `filter()`用在_总结_只保留唯一值并返回_唯一的_ 。
#### 相关链接
* [JavaScript Array.prototype.slice](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)
* [JavaScript Array.prototype.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
* [JavaScript Array.prototype.concat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat)
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 "rotating_light")高级代码解决方案
```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 ":火箭:") [运行代码](https://repl.it/@ashenm/Symmetric-Difference)
### 代码说明:
* 主函数_sym_从_参数_创建一个数组并使用辅助函数_diffArray_将其元素_简化_为单个数组。
* 函数_diffArray_通过挑选参数化数组中的唯一元素来返回两个数组的对称差异; _arr1_和_arr2_ 。
#### 相关链接
* [JavaScript Array.from](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)
* [JavaScript Array.prototype.filter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":剪贴板:")捐款说明:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":警告:") **请勿**添加与任何现有解决方案类似的解决方案。如果您认为它**_相似但更好_** ,那么尝试合并(或替换)现有的类似解决方案。
* 添加解决方案的说明。
* 将解决方案分为以下类别之一 - **基本** **中级**和**高级** 。 ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":红绿灯:")
* 如果您添加了任何**相关的主要内容,**请仅添加您的用户名。 ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":警告:") **_不要_** _删除任何现有的用户名_
> 看到![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 "point_right") [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272)供参考。

View File

@@ -0,0 +1,49 @@
---
title: Implement Bubble Sort
localeTitle: 实施冒泡排序
---
## 实施冒泡排序
### 方法:
* 冒泡排序是一种排序算法它将每个过程结束时最大数字排序或_冒泡_作为最后一个元素。
* 我们将每个元素与前面的元素进行比较,如果之前的元素较小,我们交换它们的位置。
* 冒泡排序的时间复杂度为**On 2 ** 。
* 这是一个**稳定的**算法。
* ![泡泡排序在行动](https://upload.wikimedia.org/wikipedia/commons/c/c8/Bubble-sort-example-300px.gif)
### 解:
#### 解决方案1基本
```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;
}
```
#### 解决方案2高级
`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; }`
* [运行代码](https://repl.it/@ezioda004/Bubble-Sort)
### 参考文献:
* [GeeksForGeeks](https://www.geeksforgeeks.org/bubble-sort/)
* [维基百科](https://en.wikipedia.org/wiki/Bubble_sort)
* 视频来自[HackerRank](https://www.youtube.com/watch?v=6Gv8vg0kcHc)

View File

@@ -0,0 +1,40 @@
---
title: Implement Insertion Sort
localeTitle: 实现插入排序
---
## 实现插入排序
### 方法:
* 插入排序假定数组分为两部分:
1. 排序(最初是第一个元素)
2. 未分类
* 每次传递,我们选择一个元素,并根据排序的数组进行检查。
* 如果所选元素小于已排序数组的最后一个元素那么我们将排序数组移1直到找到要_插入_所选元素的点。
* ![插入排序在行动中](https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif) - [来源](https://en.wikipedia.org/wiki/Insertion_sort)
* 插入排序的时间复杂度为**On 2 ** 。
* 这是一个**稳定的**算法。
### 解:
```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;
}
```
* [运行代码](https://repl.it/@ezioda004/Insertion-Sort)
### 参考文献:
* [维基百科](https://en.wikipedia.org/wiki/Insertion_sort)
* [可汗学院](https://www.youtube.com/watch?v=lCzQvQr8Utw)

View File

@@ -0,0 +1,56 @@
---
title: Implement Merge Sort
localeTitle: 实现合并排序
---
## 实现合并排序
### 方法:
* 合并排序是一个经典的分而治之的问题。
* 涉及以下步骤:
* 除以我们使用recusion从中间打破数组直到我们留下1个元素。
* 征服:然后我们对这些小数组进行排序。
* 组合:最后,我们将这些小数组合并为一个排序数组并继续执行直到我们组合所有数组。
* Merge Sort的时间复杂度为**Onlogn** 。
* Merge Sort的空间复杂度为**On** 。
* 这是一个**稳定的**算法。
* ![合并排序操作](https://upload.wikimedia.org/wikipedia/commons/c/cc/Merge-sort-example-300px.gif)
### 解:
```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);
}
```
* [运行代码](https://repl.it/@ezioda004/Merge-Sort)
### 参考文献:
* [维基百科](https://en.wikipedia.org/wiki/Merge_sort)
* [Hackerrank的](https://www.youtube.com/watch?v=KF2j-9iSf4Q)视频

View File

@@ -0,0 +1,56 @@
---
title: Implement Quick Sort
localeTitle: 实施快速排序
---
## 实施快速排序
### 方法:
* 快速排序是一种有效的排序算法。它是一种就地算法,因此它不需要任何辅助空间。
* 首先选择一个随机的枢轴点,将所有较小的元素移动到它的左边,将更大的元素移动到它的右边。
* 在获得该实际上是该元素的固定位置的pivotIndex之后我们通过重新调用此函数找到其他pivotIndex。
* 快速排序的最坏情况是**On 2 **但是如果我们选择随机枢轴点就可以避免这种情况因此它的大O是**Onlogn** 。
* 它的空间复杂度是**Ologn** 。
* 这是一个**不稳定的**算法。
* ![快速排序行动](https://upload.wikimedia.org/wikipedia/commons/6/6a/Sorting_quicksort_anim.gif)
### 解:
```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;
}
```
* [运行代码](https://repl.it/@ezioda004/Quick-Sort)
### 参考:
* [维基百科](https://en.wikipedia.org/wiki/Quicksort)
* [可汗学院](https://www.khanacademy.org/computing/computer-science/algorithms/quick-sort/a/overview-of-quicksort)

View File

@@ -0,0 +1,41 @@
---
title: Implement Selection Sort
localeTitle: 实施选择排序
---
## 实施选择排序
### 方法:
* Selection Sort是理解和实现的更简单的排序算法之一。
* 该算法将数组分为两部分:
1. 排序
2. 未分类
* Sorted部分位于数组的开头之后是Unsorted部分。
* 每次传递最初我们假设第一个元素是最小的然后我们遍历整个数组并_选择_最小的元素。在传递结束时我们将最小元素交换到排序数组。
* 它具有**On 2 **时间复杂度。
### 解:
```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;
}
```
### 参考文献:
* 阅读[维基百科的](https://en.wikipedia.org/wiki/Selection_sort)选择排序

View File

@@ -0,0 +1,11 @@
---
title: Algorithms
localeTitle: 算法
---
## 算法
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/mathematics/quadratic-equations/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。
#### 更多信息:

View File

@@ -0,0 +1,294 @@
---
title: Inventory Update
localeTitle: 库存更新
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 "triangular_flag_on_post")如果卡住,请记得使用**`Read-Search-Ask`** 。尝试配对程序![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 "busts_in_silhouette")并编写自己的代码![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":铅笔:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 "checkered_flag")问题说明:
在这个问题中您需要将存储在2D阵列中的库存与新交付的第二个2D阵列进行比较和更新。更新当前现有库存物料数量`arr1` )。如果找不到商品,请将新商品和数量添加到库存数组中。返回的库存数组应按项目的字母顺序排列。
当前和新的库存将采用以下格式: `[[2, "item-0"], [3, "item-1"], [67, "item-2"], [7, "item-3"]]`
#### 相关链接
* [JS阵列](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 "speech_balloon")提示1
您需要处理新库存的每个项目,以查看它是否存在于当前库存中。请记住,产品名称存储为每个子数组的第二个元素: `array[0][1] = "item-name"`
> _现在尝试解决问题_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 "speech_balloon")提示2
如果该项目存在,则需要添加新库存中的数量。如果该项目不存在,则需要添加整个项目。
> _现在尝试解决问题_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 "speech_balloon")提示3
按字母顺序返回已完成的库存。
> _现在尝试解决问题_
## 扰流警报!
![警告牌](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**提前解决!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":初学者:")基本代码解决方案
```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 ":火箭:") [运行代码](https://repl.it/CLok/0)
### 代码说明:
* 变量**索引**存储产品的位置(索引)。
* 辅助函数`getProductIndex()`返回指定产品的索引。它遍历调用它的数组的每个元素直到它可以找到name参数。如果在清单中找不到产品则返回`undefined`
* 然后,新库存(交货)中的每个项目都通过以下方式完成:
* **index**设置为调用辅助函数的结果,即在新库存中搜索该产品名称并返回其索引。
* 如果找到该项目,则将产品数量添加到当前库存中相同产品的数量。
* 如果未找到该项目,则会将整个产品(名称和数量)添加到当前库存中。
* 然后,更新的库存**arr1**按产品名称排序(保存在`arr1[x][1]` )。
* 然后返回最终更新和排序的数组。
#### 相关链接
* [JS这个](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/this)
* [JS Array.length](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/length)
* [JS Array.prototype.push](http://forum.freecodecamp.com/t/javascript-array-prototype-push/14298)
* [JS Array.prototype.sort](http://forum.freecodecamp.com/t/javascript-array-prototype-sort/14306)
## ![:sunflower:](https://forum.freecodecamp.com/images/emoji/emoji_one/sunflower.png?v=3 ":向日葵:")中级代码解决方案:
```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 ":火箭:") [运行代码](https://repl.it/CLol/0)
### 代码说明:
* 变量**索引**存储产品的位置(索引)。
* **arrCurInvName**具有**arr1**项的名称。
* **arrNeInvName**具有**arr2**项的名称。
* `arr1.map(function(item1))`负责处理库存中已存在的项目,即增加库存中的数量。
* 接下来, `arr2.map(function(item))``arr1.map(function(item))`获取新库存和当前库存的商品名称。
* `arrNeInvName.map(function(item))`处理库存中尚不存在的项目,即它将新项目添加到库存中。
* 然后,按产品名称(保存在`arr1[x][1]` )按字母顺序对已更新的数组**arr1**进行排序并返回。
#### 相关链接
* [JS Array.prototype.map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
* [JS Array.prototype.indexOf](http://forum.freecodecamp.com/t/javascript-array-prototype-indexof/14291)
* [JS三元运营商](http://forum.freecodecamp.com/t/javascript-ternary-operator/15973)
## ![:rotating_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/rotating_light.png?v=3 "rotating_light")高级代码解决方案
```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 ":火箭:") [运行代码](https://repl.it/MQvv/latest)
### 代码说明:
* 将当前库存数组**arr1**转换为一维数组,以便`indexOf()`方法可用于检查当前库存中新交货项目的存在。
* 使用`indexOf()`检查当前库存中是否已存在项目。
* 如果项目存在更新数量并继续循环执行。
* 否则将项目附加到库存。
* 最后,按字母顺序对数组进行排序并返回更新的库存。
#### 相关链接
* [JS Function.prototype.apply](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply)
* [JS继续](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue)
* [JS Array.prototype.sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":剪贴板:")捐款说明:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":警告:") **请勿**添加与任何现有解决方案类似的解决方案。如果您认为它**_相似但更好_** ,那么尝试合并(或替换)现有的类似解决方案。
* 添加解决方案的说明。
* 将解决方案分为以下类别之一 - **基本** **中级**和**高级** 。 ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":红绿灯:")
* 如果您添加了任何**相关的主要内容,**请仅添加您的用户名。 ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":警告:") **_不要_** _删除任何现有的用户名_
> 看到![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 "point_right") [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272)供参考。

View File

@@ -0,0 +1,177 @@
---
title: No Repeats Please
localeTitle: 请不要重复
---
![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 "triangular_flag_on_post")如果卡住,请记得使用**`Read-Search-Ask`** 。尝试配对程序![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 "busts_in_silhouette")并编写自己的代码![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":铅笔:")
### ![:checkered_flag:](https://forum.freecodecamp.com/images/emoji/emoji_one/checkered_flag.png?v=3 "checkered_flag")问题说明:
此任务要求我们返回没有重复连续字母的提供字符串的总排列数。假设所提供的字符串中的所有字符都是唯一的。例如, `aab`应该返回2因为它总共有6个排列 `aab` `aab` `aba` `aba` `baa` `baa` 但只有2个 `aba``aba` )没有相同的字母(在这种情况下为`a` )重复。
为此,我们必须查看字符串的每个可能的排列。有几种方法可以做到这一点。一个常见的面试问题是构建一个收集字符串所有排列的函数。互联网上有几个关于如何做到这一点的教程。
#### 用作解决方案的潜在方法
##### 递归方法
即使在观看教程之后,这项任务也令人望而生畏。要编写递归解决方案,您需要发送函数的每个新用法三个输入:
1. 正在构建的新字符串(或字符数组)。
2. 新字符串中的一个位置将在下一个填充。
3. 还没有使用原始字符串中的字符(更具体地说是位置)的想法。
伪代码看起来像这样:
```
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));
```
考虑这个问题的另一种方法是从一个空的空间开始。介绍该空间的第一个字母。此空间现在将包含第一个子排列。这是一个说明这个想法的图表:
![](//discourse-user-assets.s3.amazonaws.com/original/2X/6/69896bacc8bd3b2e347beb4b304a7f97caa6d9ab.png)
##### 非递归方法
```
// 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
}
```
然后,通过将上述内容包括在采用源阵列并返回目标阵列的函数中,可以非递归地完成每个置换。对于输入字符串的每个字母,传递该字符,以及从上一次调用函数返回的数组。
可视化这种方法的方法是考虑以字符串的第一个字符开头的树:
![排列树](//discourse-user-assets.s3.amazonaws.com/original/2X/8/8187f2b06cdc02cf62286c18ce15bfcdc99bc68c.png)
#### 相关链接
* [排列](https://www.mathsisfun.com/combinatorics/combinations-permutations.html)
* [Heap的算法](https://en.wikipedia.org/wiki/Heap%27s_algorithm)
* JS Regex资源
* [JS String对象](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 "speech_balloon")提示1
* 最简单的方法是使用Heap算法递归获取所有排列的列表。
> _现在尝试解决问题_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 "speech_balloon")提示2
* 获得列表后,只需创建一个正则表达式来捕获重复的字符。
> _现在尝试解决问题_
## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 "speech_balloon")提示3
* 您将希望将排列作为连接字符串的数组而不是分隔的字符。
> _现在尝试解决问题_
## 扰流警报!
![警告牌](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif)
**提前解决!**
## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":初学者:")基本代码解决方案
```
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 ":火箭:") [运行代码](https://repl.it/CLop/0)
### 代码说明:
* **正则表达式**包含匹配重复连续字符的正则表达式。
* 字符串**str**被分成一个字符数组**arr** 。
* 如果**str**包含相同的字符则返回0。
* 函数`swap()`用于交换两个变量内容的内容。
* 下一个代码块使用堆的算法来产生在**排列**的排列的阵列。
* **过滤的**变量过滤**排列**以仅包括非重复的排列。
* `filtered.length`返回没有重复连续字母的提供字符串的总排列数。
#### 相关链接
* [JS String Prototype Split](http://forum.freecodecamp.com/t/javascript-string-prototype-split/15944)
* [JS String Prototype Match](http://forum.freecodecamp.com/t/javascript-string-prototype-match/15941)
* [JS阵列原型推送](http://forum.freecodecamp.com/t/javascript-array-prototype-push/14298)
* [JS Array Prototype Join](http://forum.freecodecamp.com/t/javascript-array-prototype-join/14292)
* [JS for Loops解释](http://forum.freecodecamp.com/t/javascript-for-loop/14666s-Explained)
* [array.length](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/length)
* [JS数组原型过滤器](http://forum.freecodecamp.com/t/javascript-array-prototype-filter/14289)
## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":剪贴板:")捐款说明:
* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":警告:") **请勿**添加与任何现有解决方案类似的解决方案。如果您认为它**_相似但更好_** ,那么尝试合并(或替换)现有的类似解决方案。
* 添加解决方案的说明。
* 将解决方案分为以下类别之一 - **基本** **中级**和**高级** 。 ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":红绿灯:")
* 如果您添加了任何**相关的主要内容,**请仅添加您的用户名。 ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":警告:") **_不要_** _删除任何现有的用户名_
> 看到![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 "point_right") [**`Wiki Challenge Solution Template`**](http://forum.freecodecamp.com/t/algorithm-article-template/14272)供参考。

View File

@@ -0,0 +1,9 @@
---
title: Pairwise
localeTitle: 成对
---
## 成对
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/coding-interview-prep/algorithms/pairwise/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。