chore(i18n,curriculum): update translations (#43881)

This commit is contained in:
camperbot
2021-10-18 08:17:43 -07:00
committed by GitHub
parent e8e64318b3
commit 0654bd92b0
67 changed files with 513 additions and 402 deletions

View File

@ -13,7 +13,7 @@ dashedName: use-the-strong-tag-to-make-text-bold
# --instructions--
`p` 標籤裏的 `Stanford University` 內容文本添加 `strong` 標籤。
`p` 標籤裏的 `Stanford University` 內容文本外面添加 `strong` 標籤(不包括句號)
# --hints--

View File

@ -35,6 +35,18 @@ assert($('input[type="radio"]').prop('checked'));
assert($('input[type="checkbox"]').prop('checked'));
```
不應該更改 `Indoor` 標籤的內部文本。
```js
assert.equal(document.querySelector('label[for="indoor"]')?.innerText?.trim(), 'Indoor');
```
不應該更改 `Loving` 標籤的內部文本。
```js
assert.equal(document.querySelector('label[for="loving"]')?.innerText?.trim(), 'Loving');
```
# --seed--
## --seed-contents--

View File

@ -60,7 +60,7 @@ assert(
);
```
`footer` 元素的 `id` 屬性值應爲 `footer`
`a` 元素的文本應該是 “Jump to Bottom”
```js
assert(

View File

@ -13,9 +13,9 @@ dashedName: record-collection
`updateRecords` 函數開始,這個函數需要一個對象 `records`,包含一個音樂專輯集合,一個 `id`,一個 `prop`(如 `artist``tracks`),和一個 `value`。 使用下面的規則完成函數來修改傳遞給函數的對象。
- 函數必須始終返回整個音樂專輯集合對象。
- 如果 `prop` 不是 `tracks` 並且 `value` 不是一個空字符串, 將相冊`prop` 更新或設置爲 `value`
- 如果 `prop` 不是 `tracks` 並且 `value` 不是一個空字符串, 將專輯`prop` 更新或設置爲 `value`
- 如果 `prop``tracks` 但專輯沒有 `tracks` 屬性,則應創建空數組併爲其添加 `value`
- 如果 `prop``tracks` 並且 `value` 不是一個空字符串,將 `value` 添加到相冊現有 `tracks` 數組的末尾。
- 如果 `prop``tracks` 並且 `value` 不是一個空字符串,將 `value` 添加到專輯現有 `tracks` 數組的末尾。
- 如果 `value` 是空字符串,從專輯裏刪除指定的 `prop`
**注意:**`recordCollection` 對象做爲測試參數對象。

View File

@ -23,10 +23,19 @@ setFullName(firstAndLast)
# --hints--
`Object.keys(bob).length` 應返回 6。
不應添加屬性。 `Object.keys(bob).length` 應返回 6。
```js
assert.deepEqual(Object.keys(bob).length, 6);
assert.strictEqual(
Object.keys((function () {
let bob = new Person('Bob Ross');
bob.setFirstName('Haskell');
bob.setLastName('Curry');
bob.setFullName('John Smith');
return bob;
})()).length,
6
);
```
`bob instanceof Person` 應返回 `true`

View File

@ -36,6 +36,12 @@ assert(!code.match(/\.?[\s\S]*?trim/));
assert(!code.match(/result\s*=\s*["'`].*?["'`]/));
```
`hello` 變量的值不應更改。
```js
assert(hello === ' Hello, World! ');
```
# --seed--
## --seed-contents--

View File

@ -8,7 +8,7 @@ dashedName: set-state-with-this-setstate
# --description--
前面的挑戰涵蓋了組件的 `state` 以及如何在 `constructor` 中初始化 state。 還有一種方法可以更改組件的 `state` React 提供了 `setState` 方法來更新組件的 `state`。 在組件類中調用 `setState` 方法如下所示:`this.setState()`,傳入鍵值對的對象, 其中鍵是 state 屬性,值是更新後的 state 數據。 例如,如果我們在 state 中存儲 `username`,並想要更新它,代碼如下所示:
前面的挑戰涵蓋了組件的 `state` 以及如何在 `constructor` 中初始化 state。 還有一種方法可以更改組件的 `state` React 提供了 `setState` 方法來更新組件的 `state`。 在組件類中調用 `setState` 方法如下所示:`this.setState()`,傳入鍵值對的對象, 其中鍵是 state 屬性,值是更新後的 state 數據。 例如,如果我們在 state 中存儲 `username`,並想要更新它,代碼如下所示:
```jsx
this.setState({
@ -16,11 +16,11 @@ this.setState({
});
```
React 要求永遠不要直接修改 `state`,而是在 state 發生改變時始終使用 `this.setState()`。 此外應該注意React 可以批量處理多個 state 更新以提高性能。 這意味着通過 `setState` 方法進行的 state 更新可以是異步的。 `setState` 方法有一種替代語法可以解決異步問題, 雖然這很少用到,但是最好還是記住它! 有關詳細信息,請參閱[React 文檔](https://facebook.github.io/react/docs/state-and-lifecycle.html)。
React 要求永遠不要直接修改 `state`,而是在 state 發生改變時始終使用 `this.setState()`。 此外應該注意React 可以批量處理多個 state 更新以提高性能。 這意味着通過 `setState` 方法進行的 state 更新可以是異步的。 `setState` 方法有一種替代語法可以解決異步問題, 雖然這很少用到,但是最好還是記住它! 有關詳細信息,請參閱[React 文檔](https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous)。
# --instructions--
代碼編輯器中有一個 `button` 元素,它有一個 `onClick()` 處理程序。 當 `button` 在瀏覽器中接收到單擊事件時觸發此處理程序,並運行 `MyComponent` 中定義的 `handleClick` 方法。 在 `handleClick` 方法中,使用 `this.setState()` 更新組件的 `state`。 設置 `state` 中的 `name` 屬性爲字符串 `React Rocks!`
代碼編輯器中有一個 `button` 元素,它有一個 `onClick()` handler。 當 `button` 在瀏覽器中接收到單擊事件時觸發此 handler,並運行 `MyComponent` 中定義的 `handleClick` 方法。 在 `handleClick` 方法中,使用 `this.setState()` 更新組件的 `state`。 設置 `state` 中的 `name` 屬性爲字符串 `React Rocks!`
單擊按鈕查看渲染的 state 的更新。 如果不完全理解單擊處理程序代碼在此時的工作方式,請不要擔心。 在接下來的挑戰中會有講述。

View File

@ -16,7 +16,7 @@ React 提供了有用的類型檢查特性,以驗證組件是否接收了正
MyComponent.propTypes = { handleClick: PropTypes.func.isRequired }
```
在上面的示例中,`PropTypes.func` 部分檢查 `handleClick` 是否爲函數。 添加 `isRequired`,告訴 React `handleClick` 是該組件的必需屬性。 如果沒有那個屬性,將出現警告。 還要注意 `func` 代表 `function` 。 在 7 種 JavaScript 原語類型中, `function``boolean` (寫爲 `bool` )是唯一使用異常拼寫的兩種類型。 除了原始類型,還有其他類型可用。 例如,你可以檢查 prop 是否爲 React 元素。 請參閱[文檔](https://reactjs.org/docs/jsx-in-depth.html#specifying-the-react-element-type)以獲取所有選項。
在上面的示例中,`PropTypes.func` 部分檢查 `handleClick` 是否爲函數。 添加 `isRequired`,告訴 React `handleClick` 是該組件的必需屬性。 如果沒有那個屬性,將出現警告。 還要注意 `func` 代表 `function` 。 在 7 種 JavaScript 原語類型中, `function``boolean` (寫爲 `bool` )是唯一使用異常拼寫的兩種類型。 除了原始類型,還有其他類型可用。 例如,你可以檢查 prop 是否爲 React 元素。 請參閱[文檔](https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes)以獲取所有選項。
**注意:**在 React v15.5.0 中, `PropTypes` 可以從 React 中單獨引入,例如:`import PropTypes from 'prop-types';`

View File

@ -27,7 +27,9 @@ dashedName: stock-price-checker
3. 添加安全功能到 `server.js`
4.`tests/2_functional-tests.js` 中創建所有的功能測試
`tests/2_functional-tests.js` 中編寫下以下測試:
**注意** 隱私考慮:由於每個 IP 只能接受一個贊like你必須保存 IP 地址。 必須遵守數據隱私法規,例如《通用數據保護條例》。 一個選項是獲得保存用戶數據的權限,但是匿名化則要簡單得多。 對於此挑戰,請記住在將 IP 地址保存到數據庫之前對其進行匿名化。 如果你想知道如何做到這一點,你可以選擇散列數據、截斷它、或將 IP 地址的一部分設置爲 0。
`tests/2_functional-tests.js` 中編寫以下測試:
- 查看股價:發送 GET 請求到 `/api/stock-prices/`
- 查看一個股票並關注它:發送 GET 請求到 `/api/stock-prices/`
@ -37,7 +39,7 @@ dashedName: stock-price-checker
# --hints--
提交自己的項目,而不是示例的 URL。
提交自己的項目,而不是示例的 URL。
```js
(getUserInput) => {
@ -74,7 +76,7 @@ async (getUserInput) => {
};
```
`stockData` 屬性包括字符串 `stock` 代碼、數字 `price`,以及數字 `likes`
`stockData` 屬性包括字符串 `stock`、數字 `price`,以及數字 `likes`
```js
async (getUserInput) => {
@ -89,7 +91,7 @@ async (getUserInput) => {
};
```
你也可以作爲 `true`(布爾值)傳遞 `like` 字段,讓你的偏好添加到股票中。 每個 IP 應該只接受 1 個贊。
你也可以`like` 字段作爲 `true`(布爾值)傳遞,讓你的偏好添加到股票中。 每個 IP 應該只接受 1 個贊like
```js

View File

@ -1,6 +1,6 @@
---
id: 8d5123c8c441eddfaeb5bdef
title: Implement Bubble Sort
title: 實現冒泡排序
challengeType: 1
forumTopicId: 301612
dashedName: implement-bubble-sort
@ -8,23 +8,23 @@ dashedName: implement-bubble-sort
# --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.
這種方法需要對數組進行多次循環,對於平均和最壞的情況來說,其時間複雜性爲二次方。 雖然簡單,但在大多數情況下通常不切實際。
**Instructions:** Write a function `bubbleSort` which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest.
**說明:**寫一個 `bubbleSort` 函數,它將一個整數數組作爲輸入,並返回一個數組,其中的整數元素以從小到大的順序排列。
# --hints--
`bubbleSort` should be a function.
`bubbleSort` 應該是一個函數。
```js
assert(typeof bubbleSort == 'function');
```
`bubbleSort` should return a sorted array (least to greatest).
`bubbleSort` 應該返回一個已排序的數組(從小到大)。
```js
assert(
@ -52,7 +52,7 @@ assert(
);
```
`bubbleSort` should return an array that is unchanged except for order.
`bubbleSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])` 應返回一個除順序外沒有變化的數組。
```js
assert.sameMembers(
@ -79,7 +79,7 @@ assert.sameMembers(
);
```
`bubbleSort` should not use the built-in `.sort()` method.
`bubbleSort` 不應使用內置的 `.sort()` 方法。
```js
assert(isBuiltInSortUsed());
@ -113,8 +113,6 @@ function bubbleSort(array) {
return array;
// Only change code above this line
}
bubbleSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: 587d8259367417b2b2512c86
title: Implement Insertion Sort
title: 實現插入排序
challengeType: 1
forumTopicId: 301613
dashedName: implement-insertion-sort
@ -8,19 +8,19 @@ dashedName: implement-insertion-sort
# --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.
我們將要研究的下一個排序方法是插入排序。 此方法的工作原理是通過在數組的開頭構建排序數組。 它從第一個元素開始排序數組。 然後,它檢查下一個元素並將其向後交換到已排序的數組中,直到它處於已排序的位置爲止。 它繼續遍歷列表,並將新項目向後交換到已排序的部分中,直到到達末尾爲止。 這種算法在平均和最壞的情況下都有二次方的時間複雜性。
**Instructions:** Write a function `insertionSort` which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest.
**說明:** 編寫一個函數`insertionSort` ,它將一個整數數組作爲輸入,並按照從最小到最大的排序順序返回這些整數的數組。
# --hints--
`insertionSort` should be a function.
`insertionSort` 應該是一個函數。
```js
assert(typeof insertionSort == 'function');
```
`insertionSort` should return a sorted array (least to greatest).
`insertionSort` 應該返回一個排序的數組(從最小到最大)。
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
`insertionSort` should return an array that is unchanged except for order.
`insertionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])` 應返回一個除順序外沒有變化的數組。
```js
assert.sameMembers(
@ -75,7 +75,13 @@ assert.sameMembers(
);
```
`insertionSort` should not use the built-in `.sort()` method.
`insertionSort([5, 4, 33, 2, 8])` 應返回 `[2, 4, 5, 8, 33]`
```js
assert.deepEqual(insertionSort([5, 4, 33, 2, 8]), [2, 4, 5, 8, 33])
```
`insertionSort` 不應使用內置的 `.sort()` 方法。
```js
assert(isBuiltInSortUsed());
@ -109,8 +115,6 @@ function insertionSort(array) {
return array;
// Only change code above this line
}
insertionSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: 587d825c367417b2b2512c8f
title: Implement Merge Sort
title: 實現歸併排序
challengeType: 1
forumTopicId: 301614
dashedName: implement-merge-sort
@ -8,27 +8,27 @@ dashedName: implement-merge-sort
# --description--
Another common intermediate sorting algorithm 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:
另一種常見的中間排序算法是歸併排序。 像快速排序一樣,合併排序也使用分而治之的遞歸方法對數組進行排序。 它基於這樣一個事實:要將兩個已經排好序的數組排在一起,是相對容易的。 但是我們只從一個數組作爲輸入開始,那麼我們如何從中獲得兩個已排序的數組呢? 好吧,我們可以遞歸地將原始輸入分成兩部分,直到我們到達每個數組只有一個元素的基本情況。 單項數組是自然排序的,因此我們可以開始組合。 這個組合將展開拆分原始數組的遞歸調用,最終生成所有元素的最終排序數組。 合併排序的步驟如下:
**1)** Recursively split the input array in half until a sub-array with only one element is produced.
**1)** 將輸入數組遞歸地分成兩部分,直到生成僅包含一個元素的子數組。
**2)** Merge each sorted sub-array together to produce the final sorted array.
**2)** 將每個已排序的子數組合並在一起以生成最終的排序的數組。
Merge sort is an efficient sorting method, with time complexity of *O(nlog(n))*. This algorithm is popular because it is performant and relatively easy to implement.
合併排序是一種有效的排序方法,時間複雜度爲 *O(nlog(n))* 。 該算法很受歡迎,因爲它性能高且易於實現。
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.
順便說一句,這將是我們在此處介紹的最後一種排序算法。 但是,稍後在關於樹型數據結構的部分中,我們將描述堆排序,這是另一種在其實現中需要二進制堆的有效排序方法。
**Instructions:** Write a function `mergeSort` 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 `merge`, which is responsible for merging two sorted arrays, and another function, for instance `mergeSort`, which is responsible for the recursion that produces single-item arrays to feed into merge. Good luck!
**說明:** 編寫一個函數 `mergeSort`,它以整數數組作爲輸入,並按從最小到最大的排序順序返回這些整數的數組。 實現這一點的一個好方法是編寫一個函數,例如 `merge`,它負責合併兩個已排序的數組;以及另一個函數,例如 `mergeSort`,它負責遞歸,生成單項數組以提供給 merge。 祝你好運!
# --hints--
`mergeSort` should be a function.
`mergeSort` 應該是一個函數。
```js
assert(typeof mergeSort == 'function');
```
`mergeSort` should return a sorted array (least to greatest).
`mergeSort` 應該返回一個已排序的數組(從小到大)。
```js
assert(
@ -56,7 +56,7 @@ assert(
);
```
`mergeSort` should return an array that is unchanged except for order.
`mergeSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])` 應返回一個除順序外沒有變化的數組。
```js
assert.sameMembers(
@ -83,7 +83,7 @@ assert.sameMembers(
);
```
`mergeSort` should not use the built-in `.sort()` method.
`mergeSort` 不應使用內置的 `.sort()` 方法。
```js
assert(isBuiltInSortUsed());
@ -117,8 +117,6 @@ function mergeSort(array) {
return array;
// Only change code above this line
}
mergeSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: 587d8259367417b2b2512c85
title: Implement Selection Sort
title: 實現選擇排序
challengeType: 1
forumTopicId: 301616
dashedName: implement-selection-sort
@ -8,19 +8,19 @@ dashedName: implement-selection-sort
# --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.
這裏我們將實現選擇排序。 選擇排序的工作原理是選擇列表中的最小值並與列表中的第一個值進行交換。 然後它從第二個位置開始,選擇剩餘列表中的最小值,並將其與第二個元素交換。 它繼續遍歷列表並交換元素,直到它到達列表的末尾。 現在列表已排序。 在所有情況下,選擇排序都具有二次方的時間複雜度。
**Instructions**: Write a function `selectionSort` which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest.
**說明**:編寫一個 `selectionSort` 函數,它將一個整數數組作爲輸入,並按照從最小到最大的排序順序返回這些整數的數組。
# --hints--
`selectionSort` should be a function.
`selectionSort` 應該是一個函數。
```js
assert(typeof selectionSort == 'function');
```
`selectionSort` should return a sorted array (least to greatest).
`selectionSort` 應該返回一個排序的數組(從最小到最大)。
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
`selectionSort` should return an array that is unchanged except for order.
`selectionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])` 應返回一個除順序外沒有變化的數組。
```js
assert.sameMembers(
@ -75,7 +75,7 @@ assert.sameMembers(
);
```
`selectionSort` should not use the built-in `.sort()` method.
`selectionSort` 不應使用內置的 `.sort()` 方法。
```js
assert(isBuiltInSortUsed());
@ -109,9 +109,6 @@ function selectionSort(array) {
return array;
// Only change code above this line
}
selectionSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: a7bf700cd123b9a54eef01d5
title: No Repeats Please
title: 請不要重複
challengeType: 5
forumTopicId: 16037
dashedName: no-repeats-please
@ -8,67 +8,67 @@ dashedName: no-repeats-please
# --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, `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.
例如,`aab` 應該返回 2因爲它有 6 個排列(`aab``aab``aba``aba``baa` `baa`),但其中只有 2 個(`aba` `aba`)沒有重複相同字符(即 `a`)。
# --hints--
`permAlone("aab")` should return a number.
`permAlone("aab")` 應返回 2。
```js
assert.isNumber(permAlone('aab'));
```
`permAlone("aab")` should return 2.
`permAlone("aab")` 應該返回 2
```js
assert.strictEqual(permAlone('aab'), 2);
```
`permAlone("aaa")` should return 0.
`permAlone("aaa")` 應該返回 0
```js
assert.strictEqual(permAlone('aaa'), 0);
```
`permAlone("aabb")` should return 8.
`permAlone("aabb")`應返回 8
```js
assert.strictEqual(permAlone('aabb'), 8);
```
`permAlone("abcdefa")` should return 3600.
`permAlone("abcdefa")`應返回 3600
```js
assert.strictEqual(permAlone('abcdefa'), 3600);
```
`permAlone("abfdefa")` should return 2640.
`permAlone("abfdefa")`應該返回 2640
```js
assert.strictEqual(permAlone('abfdefa'), 2640);
```
`permAlone("zzzzzzzz")` should return 0.
`permAlone("zzzzzzzz")` 應返回 0
```js
assert.strictEqual(permAlone('zzzzzzzz'), 0);
```
`permAlone("a")` should return 1.
`permAlone("a")` 應該返回 1
```js
assert.strictEqual(permAlone('a'), 1);
```
`permAlone("aaab")` should return 0.
`permAlone("aaab")` 應該返回 0
```js
assert.strictEqual(permAlone('aaab'), 0);
```
`permAlone("aaabb")` should return 12.
`permAlone("aaabb")` 應返回 12.
```js
assert.strictEqual(permAlone('aaabb'), 12);

View File

@ -1,6 +1,6 @@
---
id: a3f503de51cfab748ff001aa
title: Pairwise
title: 成對
challengeType: 5
forumTopicId: 301617
dashedName: pairwise
@ -8,57 +8,57 @@ dashedName: pairwise
# --description--
Given an array `arr`, find element pairs whose sum equal the second argument `arg` and return the sum of their indices.
給定一個數組 `arr` ,找到其中總和等於第二個參數 `arg` 的元素對,並返回它們的索引之和。
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, `pairwise([1, 1, 2], 3)` creates a pair `[2, 1]` using the 1 at index 0 rather than the 1 at index 1, because 0+2 < 1+2.
你可以使用具有相同數字元素但索引不同的多個對。 每對應使用盡可能低的索引。 一旦元素被使用,它就不能被重用來與另一個元素配對。 例如, `pairwise([1, 1, 2], 3)` 使用索引爲 0 的 1而不是索引爲 1 的 1 來創建一對 `[2, 1]`,因爲 0 + 2 < 1 + 2。
For example `pairwise([7, 9, 11, 13, 15], 20)` returns `6`. The pairs that sum to 20 are `[7, 13]` and `[9, 11]`. We can then write out the array with their indices and values.
例如, `pairwise([7, 9, 11, 13, 15], 20)` 返回 `6`。 總和爲 20 的對是 `[7, 13]` `[9, 11]`。 然後我們可以用它們的索引和值寫出數組。
<div style='margin-left: 2em;'>
| Index | 0 | 1 | 2 | 3 | 4 |
| 索引 | 0 | 1 | 2 | 3 | 4 |
| ----- | - | - | -- | -- | -- |
| Value | 7 | 9 | 11 | 13 | 15 |
| | 7 | 9 | 11 | 13 | 15 |
</div>
Below we'll take their corresponding indices and add them.
接下來,我們將獲取它們的相應索引並添加它們。
<div style='margin-left: 2em;'>
7 + 13 = 20 → Indices 0 + 3 = 3
9 + 11 = 20 → Indices 1 + 2 = 3
3 + 3 = 6 → Return `6`
7 + 13 = 20 → 索引 0 + 3 = 3
9 + 11 = 20 → 索引 1 + 2 = 3
3 + 3 = 6 →返回 `6`
</div>
# --hints--
`pairwise([1, 4, 2, 3, 0, 5], 7)` should return 11.
`pairwise([1, 4, 2, 3, 0, 5], 7)` 應該返回 11
```js
assert.deepEqual(pairwise([1, 4, 2, 3, 0, 5], 7), 11);
```
`pairwise([1, 3, 2, 4], 4)` should return 1.
`pairwise([1, 3, 2, 4], 4)` 應返回 1
```js
assert.deepEqual(pairwise([1, 3, 2, 4], 4), 1);
```
`pairwise([1, 1, 1], 2)` should return 1.
`pairwise([1, 1, 1], 2)` 應該返回 1
```js
assert.deepEqual(pairwise([1, 1, 1], 2), 1);
```
`pairwise([0, 0, 0, 0, 1, 1], 1)` should return 10.
`pairwise([0, 0, 0, 0, 1, 1], 1)` 應該返回10
```js
assert.deepEqual(pairwise([0, 0, 0, 0, 1, 1], 1), 10);
```
`pairwise([], 100)` should return 0.
`pairwise([], 100)` 應該返回 0
```js
assert.deepEqual(pairwise([], 100), 0);

View File

@ -1,6 +1,6 @@
---
id: 587d8257367417b2b2512c7b
title: Add a New Element to a Binary Search Tree
title: 將新元素添加到二叉搜索樹
challengeType: 1
forumTopicId: 301618
dashedName: add-a-new-element-to-a-binary-search-tree
@ -8,27 +8,27 @@ dashedName: add-a-new-element-to-a-binary-search-tree
# --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.
首先,讓我們描述一下我們將遇到的關於樹的一些常見術語。 根節點root是樹的頂部。 樹中的數據點稱爲節點node。 分支通向其他節點的節點稱爲分支通向的節點(即子節點)的父節點。 如你所料,其他更復雜的家庭術語也適用。 子樹指的是某一特定節點的所有後代,分支可稱爲邊,而葉子節點是位於樹的末端的且沒有子節點的節點。 最後,請注意,樹本質上是遞歸的數據結構。 也就是說,一個節點的任何子節點都是其自己的子樹的父節點,依此類推。 在爲常見的樹操作設計算法時,樹的遞歸性質很重要。
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; background-color: var(--gray-05);' 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 — 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.
現在,這種有序的關係是非常容易看到的。 注意,根節點 8 左邊的每個值都小於 8右邊的每個值都大於 8。 還要注意的是,這種關係也適用於每個子樹。 例如,第一個左孩子節點是一個子樹。 3 是父節點,它正好有兩個子節點——根據二進制搜索樹的規則,我們甚至不用看就知道這個節點的左子節點(以及它的任何子節點)都將小於 3右子節點以及它的任何子節點都將大於 3但也小於根結點的值依此類推。
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, you will create a method to add new values to our binary search tree. The method should be called `add` 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 `null`. Otherwise, if the addition is successful, `undefined` should be returned.
我們將從簡單的內容開始。 我們在這裏定義了一個二叉搜索樹結構的骨架,此外還有一個爲我們的樹創建節點的函數。 注意觀察每個節點可能有一個左值和右值。 如果子樹存在,它們將被分配給對應的子樹。 在我們的二叉搜索樹中,你將創建一個方法來向我們的二叉搜索樹添加新的值。 該方法應該被稱爲`add` ,它應該接受一個整數值來添加到樹中。 注意保持二叉搜索樹的不變量:每個左子項中的值應小於或等於父值,並且每個右子項中的值應大於或等於父值。 在這裏,讓我們確保我們的樹不會含有重複的值。 如果我們嘗試添加已存在的值,則該方法應返回`null` 。 否則,如果添加成功,則應返回`undefined`
**Hint:** trees are naturally recursive data structures!
**提示:** 樹是自然的遞歸數據結構!
# --hints--
The `BinarySearchTree` data structure should exist.
存在 `BinarySearchTree` 的數據結構。
```js
assert(
@ -42,7 +42,7 @@ assert(
);
```
The binary search tree should have a method called `add`.
二叉搜索樹應該有一個名爲 `add` 的方法。
```js
assert(
@ -58,7 +58,7 @@ assert(
);
```
The add method should add elements according to the binary search tree rules.
添加的方法應該根據二叉搜索樹的規則來添加元素。
```js
assert(
@ -87,7 +87,7 @@ assert(
);
```
Adding an element that already exists should return `null`.
添加一個已經存在的元素應該返回 `null`
```js
assert(

View File

@ -13,7 +13,7 @@ dashedName: use-the-strong-tag-to-make-text-bold
# --instructions--
`p` 标签里的 `Stanford University` 内容文本添加 `strong` 标签。
`p` 标签里的 `Stanford University` 内容文本外面添加 `strong` 标签(不包括句号)
# --hints--

View File

@ -35,6 +35,18 @@ assert($('input[type="radio"]').prop('checked'));
assert($('input[type="checkbox"]').prop('checked'));
```
不应该更改 `Indoor` 标签的内部文本。
```js
assert.equal(document.querySelector('label[for="indoor"]')?.innerText?.trim(), 'Indoor');
```
不应该更改 `Loving` 标签的内部文本。
```js
assert.equal(document.querySelector('label[for="loving"]')?.innerText?.trim(), 'Loving');
```
# --seed--
## --seed-contents--

View File

@ -60,7 +60,7 @@ assert(
);
```
`footer` 元素的 `id` 属性值应为 `footer`
`a` 元素的文本应该是 “Jump to Bottom”
```js
assert(

View File

@ -13,9 +13,9 @@ dashedName: record-collection
`updateRecords` 函数开始,这个函数需要一个对象 `records`,包含一个音乐专辑集合,一个 `id`,一个 `prop`(如 `artist``tracks`),和一个 `value`。 使用下面的规则完成函数来修改传递给函数的对象。
- 函数必须始终返回整个音乐专辑集合对象。
- 如果 `prop` 不是 `tracks` 并且 `value` 不是一个空字符串, 将相册`prop` 更新或设置为 `value`
- 如果 `prop` 不是 `tracks` 并且 `value` 不是一个空字符串, 将专辑`prop` 更新或设置为 `value`
- 如果 `prop``tracks` 但专辑没有 `tracks` 属性,则应创建空数组并为其添加 `value`
- 如果 `prop``tracks` 并且 `value` 不是一个空字符串,将 `value` 添加到相册现有 `tracks` 数组的末尾。
- 如果 `prop``tracks` 并且 `value` 不是一个空字符串,将 `value` 添加到专辑现有 `tracks` 数组的末尾。
- 如果 `value` 是空字符串,从专辑里删除指定的 `prop`
**注意:**`recordCollection` 对象做为测试参数对象。

View File

@ -23,10 +23,19 @@ setFullName(firstAndLast)
# --hints--
`Object.keys(bob).length` 应返回 6。
不应添加属性。 `Object.keys(bob).length` 应返回 6。
```js
assert.deepEqual(Object.keys(bob).length, 6);
assert.strictEqual(
Object.keys((function () {
let bob = new Person('Bob Ross');
bob.setFirstName('Haskell');
bob.setLastName('Curry');
bob.setFullName('John Smith');
return bob;
})()).length,
6
);
```
`bob instanceof Person` 应返回 `true`

View File

@ -36,6 +36,12 @@ assert(!code.match(/\.?[\s\S]*?trim/));
assert(!code.match(/result\s*=\s*["'`].*?["'`]/));
```
`hello` 变量的值不应更改。
```js
assert(hello === ' Hello, World! ');
```
# --seed--
## --seed-contents--

View File

@ -8,7 +8,7 @@ dashedName: set-state-with-this-setstate
# --description--
前面的挑战涵盖了组件的 `state` 以及如何在 `constructor` 中初始化 state。 还有一种方法可以更改组件的 `state` React 提供了 `setState` 方法来更新组件的 `state`。 在组件类中调用 `setState` 方法如下所示:`this.setState()`,传入键值对的对象, 其中键是 state 属性,值是更新后的 state 数据。 例如,如果我们在 state 中存储 `username`,并想要更新它,代码如下所示:
前面的挑战涵盖了组件的 `state` 以及如何在 `constructor` 中初始化 state。 还有一种方法可以更改组件的 `state` React 提供了 `setState` 方法来更新组件的 `state`。 在组件类中调用 `setState` 方法如下所示:`this.setState()`,传入键值对的对象, 其中键是 state 属性,值是更新后的 state 数据。 例如,如果我们在 state 中存储 `username`,并想要更新它,代码如下所示:
```jsx
this.setState({
@ -16,11 +16,11 @@ this.setState({
});
```
React 要求永远不要直接修改 `state`,而是在 state 发生改变时始终使用 `this.setState()`。 此外应该注意React 可以批量处理多个 state 更新以提高性能。 这意味着通过 `setState` 方法进行的 state 更新可以是异步的。 `setState` 方法有一种替代语法可以解决异步问题, 虽然这很少用到,但是最好还是记住它! 有关详细信息,请参阅[React 文档](https://facebook.github.io/react/docs/state-and-lifecycle.html)。
React 要求永远不要直接修改 `state`,而是在 state 发生改变时始终使用 `this.setState()`。 此外应该注意React 可以批量处理多个 state 更新以提高性能。 这意味着通过 `setState` 方法进行的 state 更新可以是异步的。 `setState` 方法有一种替代语法可以解决异步问题, 虽然这很少用到,但是最好还是记住它! 有关详细信息,请参阅[React 文档](https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous)。
# --instructions--
代码编辑器中有一个 `button` 元素,它有一个 `onClick()` 处理程序。 当 `button` 在浏览器中接收到单击事件时触发此处理程序,并运行 `MyComponent` 中定义的 `handleClick` 方法。 在 `handleClick` 方法中,使用 `this.setState()` 更新组件的 `state`。 设置 `state` 中的 `name` 属性为字符串 `React Rocks!`
代码编辑器中有一个 `button` 元素,它有一个 `onClick()` handler。 当 `button` 在浏览器中接收到单击事件时触发此 handler,并运行 `MyComponent` 中定义的 `handleClick` 方法。 在 `handleClick` 方法中,使用 `this.setState()` 更新组件的 `state`。 设置 `state` 中的 `name` 属性为字符串 `React Rocks!`
单击按钮查看渲染的 state 的更新。 如果不完全理解单击处理程序代码在此时的工作方式,请不要担心。 在接下来的挑战中会有讲述。

View File

@ -16,7 +16,7 @@ React 提供了有用的类型检查特性,以验证组件是否接收了正
MyComponent.propTypes = { handleClick: PropTypes.func.isRequired }
```
在上面的示例中,`PropTypes.func` 部分检查 `handleClick` 是否为函数。 添加 `isRequired`,告诉 React `handleClick` 是该组件的必需属性。 如果没有那个属性,将出现警告。 还要注意 `func` 代表 `function` 。 在 7 种 JavaScript 原语类型中, `function``boolean` (写为 `bool` )是唯一使用异常拼写的两种类型。 除了原始类型,还有其他类型可用。 例如,你可以检查 prop 是否为 React 元素。 请参阅[文档](https://reactjs.org/docs/jsx-in-depth.html#specifying-the-react-element-type)以获取所有选项。
在上面的示例中,`PropTypes.func` 部分检查 `handleClick` 是否为函数。 添加 `isRequired`,告诉 React `handleClick` 是该组件的必需属性。 如果没有那个属性,将出现警告。 还要注意 `func` 代表 `function` 。 在 7 种 JavaScript 原语类型中, `function``boolean` (写为 `bool` )是唯一使用异常拼写的两种类型。 除了原始类型,还有其他类型可用。 例如,你可以检查 prop 是否为 React 元素。 请参阅[文档](https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes)以获取所有选项。
**注意:**在 React v15.5.0 中, `PropTypes` 可以从 React 中单独引入,例如:`import PropTypes from 'prop-types';`

View File

@ -27,7 +27,9 @@ dashedName: stock-price-checker
3. 添加安全功能到 `server.js`
4.`tests/2_functional-tests.js` 中创建所有的功能测试
`tests/2_functional-tests.js` 中编写下以下测试:
**注意** 隐私考虑:由于每个 IP 只能接受一个赞like你必须保存 IP 地址。 必须遵守数据隐私法规,例如《通用数据保护条例》。 一个选项是获得保存用户数据的权限,但是匿名化则要简单得多。 对于此挑战,请记住在将 IP 地址保存到数据库之前对其进行匿名化。 如果你想知道如何做到这一点,你可以选择散列数据、截断它、或将 IP 地址的一部分设置为 0。
`tests/2_functional-tests.js` 中编写以下测试:
- 查看股价:发送 GET 请求到 `/api/stock-prices/`
- 查看一个股票并关注它:发送 GET 请求到 `/api/stock-prices/`
@ -37,7 +39,7 @@ dashedName: stock-price-checker
# --hints--
提交自己的项目,而不是示例的 URL。
提交自己的项目,而不是示例的 URL。
```js
(getUserInput) => {
@ -74,7 +76,7 @@ async (getUserInput) => {
};
```
`stockData` 属性包括字符串 `stock` 代码、数字 `price`,以及数字 `likes`
`stockData` 属性包括字符串 `stock`、数字 `price`,以及数字 `likes`
```js
async (getUserInput) => {
@ -89,7 +91,7 @@ async (getUserInput) => {
};
```
你也可以作为 `true`(布尔值)传递 `like` 字段,让你的偏好添加到股票中。 每个 IP 应该只接受 1 个赞。
你也可以`like` 字段作为 `true`(布尔值)传递,让你的偏好添加到股票中。 每个 IP 应该只接受 1 个赞like
```js

View File

@ -1,6 +1,6 @@
---
id: 8d5123c8c441eddfaeb5bdef
title: Implement Bubble Sort
title: 实现冒泡排序
challengeType: 1
forumTopicId: 301612
dashedName: implement-bubble-sort
@ -8,23 +8,23 @@ dashedName: implement-bubble-sort
# --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.
这种方法需要对数组进行多次循环,对于平均和最坏的情况来说,其时间复杂性为二次方。 虽然简单,但在大多数情况下通常不切实际。
**Instructions:** Write a function `bubbleSort` which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest.
**说明:**写一个 `bubbleSort` 函数,它将一个整数数组作为输入,并返回一个数组,其中的整数元素以从小到大的顺序排列。
# --hints--
`bubbleSort` should be a function.
`bubbleSort` 应该是一个函数。
```js
assert(typeof bubbleSort == 'function');
```
`bubbleSort` should return a sorted array (least to greatest).
`bubbleSort` 应该返回一个已排序的数组(从小到大)。
```js
assert(
@ -52,7 +52,7 @@ assert(
);
```
`bubbleSort` should return an array that is unchanged except for order.
`bubbleSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])` 应返回一个除顺序外没有变化的数组。
```js
assert.sameMembers(
@ -79,7 +79,7 @@ assert.sameMembers(
);
```
`bubbleSort` should not use the built-in `.sort()` method.
`bubbleSort` 不应使用内置的 `.sort()` 方法。
```js
assert(isBuiltInSortUsed());
@ -113,8 +113,6 @@ function bubbleSort(array) {
return array;
// Only change code above this line
}
bubbleSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: 587d8259367417b2b2512c86
title: Implement Insertion Sort
title: 实现插入排序
challengeType: 1
forumTopicId: 301613
dashedName: implement-insertion-sort
@ -8,19 +8,19 @@ dashedName: implement-insertion-sort
# --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.
我们将要研究的下一个排序方法是插入排序。 此方法的工作原理是通过在数组的开头构建排序数组。 它从第一个元素开始排序数组。 然后,它检查下一个元素并将其向后交换到已排序的数组中,直到它处于已排序的位置为止。 它继续遍历列表,并将新项目向后交换到已排序的部分中,直到到达末尾为止。 这种算法在平均和最坏的情况下都有二次方的时间复杂性。
**Instructions:** Write a function `insertionSort` which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest.
**说明:** 编写一个函数`insertionSort` ,它将一个整数数组作为输入,并按照从最小到最大的排序顺序返回这些整数的数组。
# --hints--
`insertionSort` should be a function.
`insertionSort` 应该是一个函数。
```js
assert(typeof insertionSort == 'function');
```
`insertionSort` should return a sorted array (least to greatest).
`insertionSort` 应该返回一个排序的数组(从最小到最大)。
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
`insertionSort` should return an array that is unchanged except for order.
`insertionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])` 应返回一个除顺序外没有变化的数组。
```js
assert.sameMembers(
@ -75,7 +75,13 @@ assert.sameMembers(
);
```
`insertionSort` should not use the built-in `.sort()` method.
`insertionSort([5, 4, 33, 2, 8])` 应返回 `[2, 4, 5, 8, 33]`
```js
assert.deepEqual(insertionSort([5, 4, 33, 2, 8]), [2, 4, 5, 8, 33])
```
`insertionSort` 不应使用内置的 `.sort()` 方法。
```js
assert(isBuiltInSortUsed());
@ -109,8 +115,6 @@ function insertionSort(array) {
return array;
// Only change code above this line
}
insertionSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: 587d825c367417b2b2512c8f
title: Implement Merge Sort
title: 实现归并排序
challengeType: 1
forumTopicId: 301614
dashedName: implement-merge-sort
@ -8,27 +8,27 @@ dashedName: implement-merge-sort
# --description--
Another common intermediate sorting algorithm 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:
另一种常见的中间排序算法是归并排序。 像快速排序一样,合并排序也使用分而治之的递归方法对数组进行排序。 它基于这样一个事实:要将两个已经排好序的数组排在一起,是相对容易的。 但是我们只从一个数组作为输入开始,那么我们如何从中获得两个已排序的数组呢? 好吧,我们可以递归地将原始输入分成两部分,直到我们到达每个数组只有一个元素的基本情况。 单项数组是自然排序的,因此我们可以开始组合。 这个组合将展开拆分原始数组的递归调用,最终生成所有元素的最终排序数组。 合并排序的步骤如下:
**1)** Recursively split the input array in half until a sub-array with only one element is produced.
**1)** 将输入数组递归地分成两部分,直到生成仅包含一个元素的子数组。
**2)** Merge each sorted sub-array together to produce the final sorted array.
**2)** 将每个已排序的子数组合并在一起以生成最终的排序的数组。
Merge sort is an efficient sorting method, with time complexity of *O(nlog(n))*. This algorithm is popular because it is performant and relatively easy to implement.
合并排序是一种有效的排序方法,时间复杂度为 *O(nlog(n))* 。 该算法很受欢迎,因为它性能高且易于实现。
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.
顺便说一句,这将是我们在此处介绍的最后一种排序算法。 但是,稍后在关于树型数据结构的部分中,我们将描述堆排序,这是另一种在其实现中需要二进制堆的有效排序方法。
**Instructions:** Write a function `mergeSort` 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 `merge`, which is responsible for merging two sorted arrays, and another function, for instance `mergeSort`, which is responsible for the recursion that produces single-item arrays to feed into merge. Good luck!
**说明:** 编写一个函数 `mergeSort`,它以整数数组作为输入,并按从最小到最大的排序顺序返回这些整数的数组。 实现这一点的一个好方法是编写一个函数,例如 `merge`,它负责合并两个已排序的数组;以及另一个函数,例如 `mergeSort`,它负责递归,生成单项数组以提供给 merge。 祝你好运!
# --hints--
`mergeSort` should be a function.
`mergeSort` 应该是一个函数。
```js
assert(typeof mergeSort == 'function');
```
`mergeSort` should return a sorted array (least to greatest).
`mergeSort` 应该返回一个已排序的数组(从小到大)。
```js
assert(
@ -56,7 +56,7 @@ assert(
);
```
`mergeSort` should return an array that is unchanged except for order.
`mergeSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])` 应返回一个除顺序外没有变化的数组。
```js
assert.sameMembers(
@ -83,7 +83,7 @@ assert.sameMembers(
);
```
`mergeSort` should not use the built-in `.sort()` method.
`mergeSort` 不应使用内置的 `.sort()` 方法。
```js
assert(isBuiltInSortUsed());
@ -117,8 +117,6 @@ function mergeSort(array) {
return array;
// Only change code above this line
}
mergeSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: 587d8259367417b2b2512c85
title: Implement Selection Sort
title: 实现选择排序
challengeType: 1
forumTopicId: 301616
dashedName: implement-selection-sort
@ -8,19 +8,19 @@ dashedName: implement-selection-sort
# --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.
这里我们将实现选择排序。 选择排序的工作原理是选择列表中的最小值并与列表中的第一个值进行交换。 然后它从第二个位置开始,选择剩余列表中的最小值,并将其与第二个元素交换。 它继续遍历列表并交换元素,直到它到达列表的末尾。 现在列表已排序。 在所有情况下,选择排序都具有二次方的时间复杂度。
**Instructions**: Write a function `selectionSort` which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest.
**说明**:编写一个 `selectionSort` 函数,它将一个整数数组作为输入,并按照从最小到最大的排序顺序返回这些整数的数组。
# --hints--
`selectionSort` should be a function.
`selectionSort` 应该是一个函数。
```js
assert(typeof selectionSort == 'function');
```
`selectionSort` should return a sorted array (least to greatest).
`selectionSort` 应该返回一个排序的数组(从最小到最大)。
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
`selectionSort` should return an array that is unchanged except for order.
`selectionSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])` 应返回一个除顺序外没有变化的数组。
```js
assert.sameMembers(
@ -75,7 +75,7 @@ assert.sameMembers(
);
```
`selectionSort` should not use the built-in `.sort()` method.
`selectionSort` 不应使用内置的 `.sort()` 方法。
```js
assert(isBuiltInSortUsed());
@ -109,9 +109,6 @@ function selectionSort(array) {
return array;
// Only change code above this line
}
selectionSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: a7bf700cd123b9a54eef01d5
title: No Repeats Please
title: 请不要重复
challengeType: 5
forumTopicId: 16037
dashedName: no-repeats-please
@ -8,67 +8,67 @@ dashedName: no-repeats-please
# --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, `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.
例如,`aab` 应该返回 2因为它有 6 个排列(`aab``aab``aba``aba``baa` `baa`),但其中只有 2 个(`aba` `aba`)没有重复相同字符(即 `a`)。
# --hints--
`permAlone("aab")` should return a number.
`permAlone("aab")` 应返回 2。
```js
assert.isNumber(permAlone('aab'));
```
`permAlone("aab")` should return 2.
`permAlone("aab")` 应该返回 2
```js
assert.strictEqual(permAlone('aab'), 2);
```
`permAlone("aaa")` should return 0.
`permAlone("aaa")` 应该返回 0
```js
assert.strictEqual(permAlone('aaa'), 0);
```
`permAlone("aabb")` should return 8.
`permAlone("aabb")`应返回 8
```js
assert.strictEqual(permAlone('aabb'), 8);
```
`permAlone("abcdefa")` should return 3600.
`permAlone("abcdefa")`应返回 3600
```js
assert.strictEqual(permAlone('abcdefa'), 3600);
```
`permAlone("abfdefa")` should return 2640.
`permAlone("abfdefa")`应该返回 2640
```js
assert.strictEqual(permAlone('abfdefa'), 2640);
```
`permAlone("zzzzzzzz")` should return 0.
`permAlone("zzzzzzzz")` 应返回 0
```js
assert.strictEqual(permAlone('zzzzzzzz'), 0);
```
`permAlone("a")` should return 1.
`permAlone("a")` 应该返回 1
```js
assert.strictEqual(permAlone('a'), 1);
```
`permAlone("aaab")` should return 0.
`permAlone("aaab")` 应该返回 0
```js
assert.strictEqual(permAlone('aaab'), 0);
```
`permAlone("aaabb")` should return 12.
`permAlone("aaabb")` 应返回 12.
```js
assert.strictEqual(permAlone('aaabb'), 12);

View File

@ -1,6 +1,6 @@
---
id: a3f503de51cfab748ff001aa
title: Pairwise
title: 成对
challengeType: 5
forumTopicId: 301617
dashedName: pairwise
@ -8,57 +8,57 @@ dashedName: pairwise
# --description--
Given an array `arr`, find element pairs whose sum equal the second argument `arg` and return the sum of their indices.
给定一个数组 `arr` ,找到其中总和等于第二个参数 `arg` 的元素对,并返回它们的索引之和。
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, `pairwise([1, 1, 2], 3)` creates a pair `[2, 1]` using the 1 at index 0 rather than the 1 at index 1, because 0+2 &lt; 1+2.
你可以使用具有相同数字元素但索引不同的多个对。 每对应使用尽可能低的索引。 一旦元素被使用,它就不能被重用来与另一个元素配对。 例如, `pairwise([1, 1, 2], 3)` 使用索引为 0 的 1而不是索引为 1 的 1 来创建一对 `[2, 1]`,因为 0 + 2 &lt; 1 + 2。
For example `pairwise([7, 9, 11, 13, 15], 20)` returns `6`. The pairs that sum to 20 are `[7, 13]` and `[9, 11]`. We can then write out the array with their indices and values.
例如, `pairwise([7, 9, 11, 13, 15], 20)` 返回 `6`。 总和为 20 的对是 `[7, 13]` `[9, 11]`。 然后我们可以用它们的索引和值写出数组。
<div style='margin-left: 2em;'>
| Index | 0 | 1 | 2 | 3 | 4 |
| 索引 | 0 | 1 | 2 | 3 | 4 |
| ----- | - | - | -- | -- | -- |
| Value | 7 | 9 | 11 | 13 | 15 |
| | 7 | 9 | 11 | 13 | 15 |
</div>
Below we'll take their corresponding indices and add them.
接下来,我们将获取它们的相应索引并添加它们。
<div style='margin-left: 2em;'>
7 + 13 = 20 → Indices 0 + 3 = 3
9 + 11 = 20 → Indices 1 + 2 = 3
3 + 3 = 6 → Return `6`
7 + 13 = 20 → 索引 0 + 3 = 3
9 + 11 = 20 → 索引 1 + 2 = 3
3 + 3 = 6 →返回 `6`
</div>
# --hints--
`pairwise([1, 4, 2, 3, 0, 5], 7)` should return 11.
`pairwise([1, 4, 2, 3, 0, 5], 7)` 应该返回 11
```js
assert.deepEqual(pairwise([1, 4, 2, 3, 0, 5], 7), 11);
```
`pairwise([1, 3, 2, 4], 4)` should return 1.
`pairwise([1, 3, 2, 4], 4)` 应返回 1
```js
assert.deepEqual(pairwise([1, 3, 2, 4], 4), 1);
```
`pairwise([1, 1, 1], 2)` should return 1.
`pairwise([1, 1, 1], 2)` 应该返回 1
```js
assert.deepEqual(pairwise([1, 1, 1], 2), 1);
```
`pairwise([0, 0, 0, 0, 1, 1], 1)` should return 10.
`pairwise([0, 0, 0, 0, 1, 1], 1)` 应该返回10
```js
assert.deepEqual(pairwise([0, 0, 0, 0, 1, 1], 1), 10);
```
`pairwise([], 100)` should return 0.
`pairwise([], 100)` 应该返回 0
```js
assert.deepEqual(pairwise([], 100), 0);

View File

@ -1,6 +1,6 @@
---
id: 587d8257367417b2b2512c7b
title: Add a New Element to a Binary Search Tree
title: 将新元素添加到二叉搜索树
challengeType: 1
forumTopicId: 301618
dashedName: add-a-new-element-to-a-binary-search-tree
@ -8,27 +8,27 @@ dashedName: add-a-new-element-to-a-binary-search-tree
# --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.
首先,让我们描述一下我们将遇到的关于树的一些常见术语。 根节点root是树的顶部。 树中的数据点称为节点node。 分支通向其他节点的节点称为分支通向的节点(即子节点)的父节点。 如你所料,其他更复杂的家庭术语也适用。 子树指的是某一特定节点的所有后代,分支可称为边,而叶子节点是位于树的末端的且没有子节点的节点。 最后,请注意,树本质上是递归的数据结构。 也就是说,一个节点的任何子节点都是其自己的子树的父节点,依此类推。 在为常见的树操作设计算法时,树的递归性质很重要。
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; background-color: var(--gray-05);' 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 — 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.
现在,这种有序的关系是非常容易看到的。 注意,根节点 8 左边的每个值都小于 8右边的每个值都大于 8。 还要注意的是,这种关系也适用于每个子树。 例如,第一个左孩子节点是一个子树。 3 是父节点,它正好有两个子节点——根据二进制搜索树的规则,我们甚至不用看就知道这个节点的左子节点(以及它的任何子节点)都将小于 3右子节点以及它的任何子节点都将大于 3但也小于根结点的值依此类推。
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, you will create a method to add new values to our binary search tree. The method should be called `add` 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 `null`. Otherwise, if the addition is successful, `undefined` should be returned.
我们将从简单的内容开始。 我们在这里定义了一个二叉搜索树结构的骨架,此外还有一个为我们的树创建节点的函数。 注意观察每个节点可能有一个左值和右值。 如果子树存在,它们将被分配给对应的子树。 在我们的二叉搜索树中,你将创建一个方法来向我们的二叉搜索树添加新的值。 该方法应该被称为`add` ,它应该接受一个整数值来添加到树中。 注意保持二叉搜索树的不变量:每个左子项中的值应小于或等于父值,并且每个右子项中的值应大于或等于父值。 在这里,让我们确保我们的树不会含有重复的值。 如果我们尝试添加已存在的值,则该方法应返回`null` 。 否则,如果添加成功,则应返回`undefined`
**Hint:** trees are naturally recursive data structures!
**提示:** 树是自然的递归数据结构!
# --hints--
The `BinarySearchTree` data structure should exist.
存在 `BinarySearchTree` 的数据结构。
```js
assert(
@ -42,7 +42,7 @@ assert(
);
```
The binary search tree should have a method called `add`.
二叉搜索树应该有一个名为 `add` 的方法。
```js
assert(
@ -58,7 +58,7 @@ assert(
);
```
The add method should add elements according to the binary search tree rules.
添加的方法应该根据二叉搜索树的规则来添加元素。
```js
assert(
@ -87,7 +87,7 @@ assert(
);
```
Adding an element that already exists should return `null`.
添加一个已经存在的元素应该返回 `null`
```js
assert(

View File

@ -23,10 +23,19 @@ Ejecuta las pruebas para ver el resultado esperado para cada método. Los métod
# --hints--
`Object.keys(bob).length` debe devolver 6.
No se deben agregar propiedades. `Object.keys(bob).length` siempre debe devolver 6.
```js
assert.deepEqual(Object.keys(bob).length, 6);
assert.strictEqual(
Object.keys((function () {
let bob = new Person('Bob Ross');
bob.setFirstName('Haskell');
bob.setLastName('Curry');
bob.setFullName('John Smith');
return bob;
})()).length,
6
);
```
`bob instanceof Person` debe devolver `true`.

View File

@ -48,7 +48,7 @@ El cuarto elemento `title` debe tener un cuadro emergente de texto de `17`.
assert($('title').eq(3).text() == '17');
```
El quinto elemento `title` debe tener uncuadro emergente de texto de `25`.
El quinto elemento `title` debe tener un cuadro emergente de texto de `25`.
```js
assert($('title').eq(4).text() == '25');

View File

@ -10,7 +10,7 @@ dashedName: add-attributes-to-the-circle-elements
El último desafío creó los elementos `circle` para cada punto en el `dataset` y los agregó al lienzo SVG. Pero D3 necesita más información sobre la posición y el tamaño de cada `circle` para mostrarlos correctamente.
Un `circle` en SVG tiene tres atributos principales. Los atributos `cx` y `cy` son las coordenadas. Le dicen a D3 donde colocar el *center* de la forma en el lienzo SVG. El radio (`r` atributo) da el tamaño del `circle`.
Un `circle` en SVG tiene tres atributos principales. Los atributos `cx` y `cy` son las coordenadas. Le dicen a D3 donde colocar el *center* de la forma en el lienzo SVG. El radio (atributo `r`) da el tamaño del `circle`.
Al igual que la coordenada `rect` `y`, el atributo `cy` para un `circle` se mide desde la parte superior del lienzo SVG, no desde abajo.

View File

@ -30,7 +30,7 @@ El código anterior coloca el eje "x" en la parte inferior del lienzo SVG. Luego
# --instructions--
El diagrama de dispersión ahora tiene un eje x. Crea un eje y en una variable denominada `yAxis` utilizando el método `axisLeft()`. Luego renderiza el eje usando un elemento `g`. Asegúrete de utilizar un atributo `transform` para trasladar el eje por la cantidad de unidades de relleno a la derecha y `0` unidades hacia abajo. Recuerda de `call()` al eje.
El diagrama de dispersión ahora tiene un eje x. Crea un eje y en una variable denominada `yAxis` utilizando el método `axisLeft()`. Luego renderiza el eje usando un elemento `g`. Asegúrete de utilizar un atributo `transform` para trasladar el eje por la cantidad de unidades de relleno a la derecha y `0` unidades hacia abajo. Recuerda de llamar (`call()`) al eje.
# --hints--

View File

@ -16,7 +16,7 @@ El método `attr()` funciona de la misma manera que `style()`. Toma valores sepa
selection.attr("class", "container");
```
Tenga en cuenta que el parámetro `class` seguirá siendo el mismo siempre que necesite agregar una clase y solo cambiará el parámetro `container`.
Ten en cuenta que el parámetro `class` seguirá siendo el mismo siempre que necesites agregar una clase y solo cambiará el parámetro `container`.
# --instructions--

View File

@ -18,7 +18,7 @@ Agrega un método `attr()` para establecer el `fill` (relleno) de todas las barr
# --hints--
Todas las barras deberían tener un color de `fill` azul marino.
Todas las barras deben tener un color de `fill` azul marino.
```js
assert($('rect').css('fill') == 'rgb(0, 0, 128)');

View File

@ -1,6 +1,6 @@
---
id: 587d7fa8367417b2b2512bcd
title: Crea una barra para cada punto de dato en el set
title: Crea una barra para cada punto de dato en el conjunto
challengeType: 6
forumTopicId: 301482
dashedName: create-a-bar-for-each-data-point-in-the-set

View File

@ -12,7 +12,7 @@ La barra y los diagramas de dispersión dibujan los datos directamente en el lie
En D3, hay escalas para ayudar a trazar datos. `scales` son funciones que le dicen al programa cómo asignar un conjunto de puntos de datos en bruto, a los píxeles del lienzo SVG.
Por ejemplo, digamos que tienes un lienzo SVG de 100x500 y quieres trazar el Producto Bruto Interno(PBI) para una cantidad de países. El conjunto de números estaría en el rango de miles de millones o billones de dólares. Tú le provees a D3 un tipo de escala para decirle como colocar los grandes valores de PBI en esa área de tamaño 100x500.
Por ejemplo, digamos que tienes un lienzo SVG de 100x500 y quieres trazar el Producto Bruto Interno(PBI) para una cantidad de países. El conjunto de números estaría en el rango de miles de millones o billones de dólares. Tú le provees a D3 un tipo de escala para decirle cómo colocar los grandes valores de PBI en esa área de tamaño 100x500.
Es muy poco probable que traces los datos en bruto tal como son. Antes de trazarlo, estableces la escala para todo tu conjunto de datos(data set), para que los valores de `x` e `y` vayan dentro del alto y ancho de tu lienzo.

View File

@ -1,6 +1,6 @@
---
id: 587d7fa8367417b2b2512bcc
title: Mostrar formas con SVG
title: Muestra formas con SVG
challengeType: 6
forumTopicId: 301485
dashedName: display-shapes-with-svg

View File

@ -1,6 +1,6 @@
---
id: 587d7fa9367417b2b2512bce
title: Dynamically Set the Coordinates for Each Bar
title: Establece dinámicamente las coordenadas para cada barra
challengeType: 6
forumTopicId: 301487
dashedName: dynamically-set-the-coordinates-for-each-bar
@ -8,13 +8,13 @@ dashedName: dynamically-set-the-coordinates-for-each-bar
# --description--
The last challenge created and appended a rectangle to the `svg` element for each point in `dataset` to represent a bar. Unfortunately, they were all stacked on top of each other.
El último desafío crea un rectángulo adjunto al elemento `svg` por cada punto en `dataset` para representar una barra. Desafortunadamente, todas estaban apiladas una arriba de la otra.
The placement of a rectangle is handled by the `x` and `y` attributes. They tell D3 where to start drawing the shape in the `svg` area. The last challenge set them each to 0, so every bar was placed in the upper-left corner.
La posición de un rectángulo es manejada por los atributos `x` e `y`. Le dicen a D3 dónde empezar a dibujar la figura en el área de `svg`. El último desafío los puso cada uno a 0, por lo que cada barra se colocó en la esquina superior izquierda.
For a bar chart, all of the bars should sit on the same vertical level, which means the `y` value stays the same (at 0) for all bars. The `x` value, however, needs to change as you add new bars. Remember that larger `x` values push items farther to the right. As you go through the array elements in `dataset`, the `x` value should increase.
Para un gráfico de barras, todas las barras deben asentarse en el mismo nivel vertical, lo que significa que el valor `y` permanece igual (en 0) para todas las barras. Sin embargo, el valor `x` necesita cambiar a medida que se añaden nuevas barras. Recuerda que los valores de `x` más grandes empujan los elementos más a la derecha. A medida que recorres los elementos del arreglo en `dataset`, el valor `x` debería aumentar.
The `attr()` method in D3 accepts a callback function to dynamically set that attribute. The callback function takes two arguments, one for the data point itself (usually `d`) and one for the index of the data point in the array. The second argument for the index is optional. Here's the format:
El método `attr()` en D3 acepta una función callback para establecer dinámicamente ese atributo. La función callback toma dos argumentos, uno para el punto de datos en sí (generalmente `d`) y otro para el índice del punto de datos en el arreglo. El segundo argumento para el índice es opcional. Este es el formato:
```js
selection.attr("property", (d, i) => {
@ -22,65 +22,65 @@ selection.attr("property", (d, i) => {
})
```
It's important to note that you do NOT need to write a `for` loop or use `forEach()` to iterate over the items in the data set. Recall that the `data()` method parses the data set, and any method that's chained after `data()` is run once for each item in the data set.
Es importante tener en cuenta que NO necesitas escribir un bucle `for` o usar `forEach()` para iterar sobre los elementos en el conjunto de datos. Recuerda que el método `data()` analiza el conjunto de datos, y cualquier método que vaya después de `data()` se ejecuta una vez por cada elemento del conjunto de datos.
# --instructions--
Change the `x` attribute callback function so it returns the index times 30.
Cambia la función callback de atributo `x` para que devuelva el índice multiplicado por 30.
**Note:** Each bar has a width of 25, so increasing each `x` value by 30 adds some space between the bars. Any value greater than 25 would work in this example.
**Nota:** Cada barra tiene un ancho de 25, por lo que cada valor `x` añade algo de espacio entre las barras. Cualquier valor mayor a 25 funcionaría en este ejemplo.
# --hints--
The first `rect` should have an `x` value of `0`.
El primer `rect` debe tener un valor `x` de `0`.
```js
assert($('rect').eq(0).attr('x') == '0');
```
The second `rect` should have an `x` value of `30`.
El segundo `rect` debe tener un valor `x` de `30`.
```js
assert($('rect').eq(1).attr('x') == '30');
```
The third `rect` should have an `x` value of `60`.
El tercer `rect` debe tener un valor `x` de `60`.
```js
assert($('rect').eq(2).attr('x') == '60');
```
The fourth `rect` should have an `x` value of `90`.
El cuarto `rect` debe tener un valor `x` de `90`.
```js
assert($('rect').eq(3).attr('x') == '90');
```
The fifth `rect` should have an `x` value of `120`.
El quinto `rect` debe tener un valor `x` de `120`.
```js
assert($('rect').eq(4).attr('x') == '120');
```
The sixth `rect` should have an `x` value of `150`.
El sexto `rect` debe un valor `x` de `150`.
```js
assert($('rect').eq(5).attr('x') == '150');
```
The seventh `rect` should have an `x` value of `180`.
El séptimo `rect` debe tener un valor `x` de `180`.
```js
assert($('rect').eq(6).attr('x') == '180');
```
The eighth `rect` should have an `x` value of `210`.
El octavo `rect` debe tener un valor `x` de `210`.
```js
assert($('rect').eq(7).attr('x') == '210');
```
The ninth `rect` should have an `x` value of `240`.
El noveno `rect` debe tener un valor `x` de `240`.
```js
assert($('rect').eq(8).attr('x') == '240');

View File

@ -1,6 +1,6 @@
---
id: 587d7fa9367417b2b2512bd0
title: Invert SVG Elements
title: Invierte elementos SVG
challengeType: 6
forumTopicId: 301488
dashedName: invert-svg-elements
@ -8,73 +8,73 @@ dashedName: invert-svg-elements
# --description--
You may have noticed the bar chart looked like it's upside-down, or inverted. This is because of how SVG uses (x, y) coordinates.
Habrás notado que el gráfico de barras parecía estar al revés, o invertido. Esto se debe a cómo SVG utiliza las coordenadas (x, y).
In SVG, the origin point for the coordinates is in the upper-left corner. An `x` coordinate of 0 places a shape on the left edge of the SVG area. A `y` coordinate of 0 places a shape on the top edge of the SVG area. Higher `x` values push the rectangle to the right. Higher `y` values push the rectangle down.
En SVG, el punto de origen de coordenadas está en la esquina superior izquierda. Una coordenada `x` de 0 coloca la forma en el borde izquierdo del área SVG. Una coordenada `y` de 0 coloca la forma en el borde superior del área SVG. Valores más altos de `x` empujan el rectángulo a la derecha. Valores más altos de `y` empujan el rectángulo hacia abajo.
To make the bars right-side-up, you need to change the way the `y` coordinate is calculated. It needs to account for both the height of the bar and the total height of the SVG area.
Para poner las barras hacia arriba, necesitas cambiar la forma en la que la coordenada `y` es calculada. Necesita tener en cuenta tanto la altura de la barra como el alto total del área SVG.
The height of the SVG area is 100. If you have a data point of 0 in the set, you would want the bar to start at the bottom of the SVG area (not the top). To do this, the `y` coordinate needs a value of 100. If the data point value were 1, you would start with a `y` coordinate of 100 to set the bar at the bottom. Then you need to account for the height of the bar of 1, so the final `y` coordinate would be 99.
La altura del área SVG es 100. Si tienes un punto de dato de 0 en el conjunto, querrías que la barra comience en la parte inferior del área SVG (no en la superior). Para hacer esto, la coordenada `y` necesita un valor de 100. Si el punto de dato fuese 1, comenzarías con una coordenada `y` de 100 para colocar la barra en la parte inferior. Aparte, debes tener en consideración la altura de la barra de 1, así que la coordenada final de `y` sería 99.
The `y` coordinate that is `y = heightOfSVG - heightOfBar` would place the bars right-side-up.
La coordenada `y` que es `y = heightOfSVG - heightOfBar` (y = alturaDeSVG - alturaDeBarra) colocaría las barras hacia arriba.
# --instructions--
Change the callback function for the `y` attribute to set the bars right-side-up. Remember that the `height` of the bar is 3 times the data value `d`.
Cambia la función callback para el atributo `y` para colocar las barras hacia arriba. Recuerda que la `height` (altura) de la barra es 3 veces el valor del dato `d`.
**Note:** In general, the relationship is `y = h - m * d`, where `m` is the constant that scales the data points.
**Nota:** En general, la relación es `y = h - m * d`, donde `m` es la constante que escala los puntos de datos.
# --hints--
The first `rect` should have a `y` value of `64`.
El primer `rect` debe tener un valor `y` de `64`.
```js
assert($('rect').eq(0).attr('y') == h - dataset[0] * 3);
```
The second `rect` should have a `y` value of `7`.
El segundo `rect` debe tener un valor `y` de `7`.
```js
assert($('rect').eq(1).attr('y') == h - dataset[1] * 3);
```
The third `rect` should have a `y` value of `34`.
El tercer `rect` debe tener un valor `y` de `34`.
```js
assert($('rect').eq(2).attr('y') == h - dataset[2] * 3);
```
The fourth `rect` should have a `y` value of `49`.
El cuarto `rect` debe tener un valor `y` de `49`.
```js
assert($('rect').eq(3).attr('y') == h - dataset[3] * 3);
```
The fifth `rect` should have a `y` value of `25`.
El quinto `rect` debe tener un valor `y` de `25`.
```js
assert($('rect').eq(4).attr('y') == h - dataset[4] * 3);
```
The sixth `rect` should have a `y` value of `46`.
El sexto `rect` debe tener un valor `y` de `46`.
```js
assert($('rect').eq(5).attr('y') == h - dataset[5] * 3);
```
The seventh `rect` should have a `y` value of `13`.
El séptimo `rect` debe tener un valor `y` de `13`.
```js
assert($('rect').eq(6).attr('y') == h - dataset[6] * 3);
```
The eighth `rect` should have a `y` value of `58`.
El octavo `rect` debe tener un valor `y` de `58`.
```js
assert($('rect').eq(7).attr('y') == h - dataset[7] * 3);
```
The ninth `rect` should have a `y` value of `73`.
El noveno `rect` debe tener un valor `y` de `73`.
```js
assert($('rect').eq(8).attr('y') == h - dataset[8] * 3);

View File

@ -1,6 +1,6 @@
---
id: 587d7fa8367417b2b2512bcb
title: Learn About SVG in D3
title: Aprende sobre SVG en D3
challengeType: 6
forumTopicId: 301489
dashedName: learn-about-svg-in-d3
@ -8,35 +8,35 @@ dashedName: learn-about-svg-in-d3
# --description--
<dfn>SVG</dfn> stands for <dfn>Scalable Vector Graphics</dfn>.
<dfn>SVG</dfn> significa <dfn>Scalable Vector Graphics</dfn> (Gráficos vectoriales escalables).
Here "scalable" means that, if you zoom in or out on an object, it would not appear pixelated. It scales with the display system, whether it's on a small mobile screen or a large TV monitor.
Aquí "escalable" significa que, si te acercas o alejas a un objeto, no se vería pixelado. El objeto escala con la pantalla, ya sea en una pequeña pantalla de teléfono o en un gran monitor de TV.
SVG is used to make common geometric shapes. Since D3 maps data into a visual representation, it uses SVG to create the shapes for the visualization. SVG shapes for a web page must go within an HTML `svg` tag.
SVG se utiliza para crear formas geométricas comunes. Ya que D3 traza datos en una representación visual, utiliza SVG para crear las formas para la visualización. Las formas SVG para una página web deben ir dentro de una etiqueta HTML llamada `svg`.
CSS can be scalable when styles use relative units (such as `vh`, `vw`, or percentages), but using SVG is more flexible to build data visualizations.
CSS puede ser escalable cuando los estilos usan medidas relativas (como por ejemplo `vh`, `vw` o porcentajes), pero usar SVG es más flexible para construir visualizaciones de datos.
# --instructions--
Add an `svg` node to the `body` using `append()`. Give it a `width` attribute set to the provided `w` constant and a `height` attribute set to the provided `h` constant using the `attr()` or `style()` methods for each. You'll see it in the output because there's a `background-color` of pink applied to it in the `style` tag.
Agrega un nodo `svg` al `body` utilizando `append()`. Dale un atributo `width` con el valor de la constante `w` proporcionada, y un atributo `height` con el valor de la constante `h` proporcionado, utilizando los métodos `attr()` o `style()` para cada uno de ellos. Lo verás en la salida porque hay un `background-color` (color de fondo) rosa aplicado en la etiqueta `style`.
**Note:** When using `attr()` width and height attributes do not have units. This is the building block of scaling - the element will always have a 5:1 width to height ratio, no matter what the zoom level is.
**Nota:** Al utilizar `attr()` los atributos width (ancho) y height (alto) no llevan unidades. Este es el bloque de construcción de la escala: el elemento siempre tendrá una relación ancho a alto de 5:1, sin importar el nivel de zoom.
# --hints--
Your document should have 1 `svg` element.
Tu documento debe tener 1 elemento `svg`.
```js
assert($('svg').length == 1);
```
The `svg` element should have a `width` attribute set to `500` or styled to have a width of `500px`.
El elemento `svg` debe tener un atributo `width` establecido en `500` o estilizado para tener un ancho de `500px`.
```js
assert($('svg').attr('width') == '500' || $('svg').css('width') == '500px');
```
The `svg` element should have a `height` attribute set to `100` or styled to have a height of `100px`.
El elemento `svg` debe tener un atributo `height` establecido en `100` o estilizado para tener una altura de `100px`.
```js
assert($('svg').attr('height') == '100' || $('svg').css('height') == '100px');

View File

@ -1,6 +1,6 @@
---
id: 587d7fa6367417b2b2512bc3
title: Select a Group of Elements with D3
title: Selecciona un grupo de elementos con D3
challengeType: 6
forumTopicId: 301490
dashedName: select-a-group-of-elements-with-d3
@ -8,21 +8,21 @@ dashedName: select-a-group-of-elements-with-d3
# --description--
D3 also has the `selectAll()` method to select a group of elements. It returns an array of HTML nodes for all the items in the document that match the input string. Here's an example to select all the anchor tags in a document:
D3 también tiene el método `selectAll()` para seleccionar un grupo de elementos. Devuelve un arreglo de nodos HTML con todos los elementos en el documento que coinciden con el texto ingresado. Aquí hay un ejemplo para seleccionar todas las etiquetas de anclaje en un documento:
```js
const anchors = d3.selectAll("a");
```
Like the `select()` method, `selectAll()` supports method chaining, and you can use it with other methods.
Al igual que el método `select()`, `selectAll()` soporta el encadenamiento de métodos, y puedes usarlo con otros métodos.
# --instructions--
Select all of the `li` tags in the document, and change their text to the string `list item` by chaining the `.text()` method.
Selecciona todas las etiquetas `li` en el documento, y cambia su texto a la cadena `list item` concatenando el método `.text()`.
# --hints--
There should be 3 `li` elements on the page, and the text in each one should say `list item`. Capitalization and spacing should match exactly.
Debe haber 3 elementos `li` en la pagina, y el texto en cada uno debe ser `list item`. Las mayúsculas y los espacios deben coincidir exactamente.
```js
assert(
@ -32,13 +32,13 @@ assert(
);
```
Your code should access the `d3` object.
Tu código debe acceder al objeto `d3`.
```js
assert(code.match(/d3/g));
```
Your code should use the `selectAll` method.
Tu código debe utilizar el método `selectAll`.
```js
assert(code.match(/\.selectAll/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7fac367417b2b2512bdb
title: Set a Domain and a Range on a Scale
title: Establece un dominio y un rango en una escala
challengeType: 6
forumTopicId: 301491
dashedName: set-a-domain-and-a-range-on-a-scale
@ -8,13 +8,13 @@ dashedName: set-a-domain-and-a-range-on-a-scale
# --description--
By default, scales use the identity relationship. This means the input value maps to the output value. However, scales can be much more flexible and interesting.
Por defecto, las escalas usan la relación de identidad. Esto significa que el valor de entrada se asigna al valor de salida. Sin embargo, las escalas pueden ser mucho más flexibles e interesantes.
Say a dataset has values ranging from 50 to 480. This is the input information for a scale, also known as the <dfn>domain</dfn>.
Digamos que un conjunto de datos tiene valores entre 50 y 480. Esta es la información de entrada para una escala, también conocido como el <dfn>dominio</dfn>.
You want to map those points along the `x` axis on the SVG canvas, between 10 units and 500 units. This is the output information, also known as the <dfn>range</dfn>.
Quieres trazar esos puntos a lo largo del eje `x` en el lienzo SVG, entre 10 unidades y 500 unidades. Esta es la información de salida, también conocida como el <dfn>rango</dfn>.
The `domain()` and `range()` methods set these values for the scale. Both methods take an array of at least two elements as an argument. Here's an example:
Los métodos `domain()` y `range()` establecen estos valores para la escala. Ambos métodos toman un arreglo de al menos dos elementos como argumento. Aquí un ejemplo:
```js
scale.domain([50, 480]);
@ -26,43 +26,43 @@ scale(750)
d3.scaleLinear()
```
In order, the following values would be displayed in the console: `10`, `500`, `323.37`, and `807.67`.
En orden, los siguientes valores se mostrarían en la consola: `10`, `500`, `323.37`, y `807.67`.
Notice that the scale uses the linear relationship between the domain and range values to figure out what the output should be for a given number. The minimum value in the domain (50) maps to the minimum value (10) in the range.
Observa que la escala usa la relación lineal entre los valores del dominio y del rango para averiguar cuál debe ser la salida para un número dado. El valor mínimo en el dominio (50) se asigna al valor mínimo (10) en el rango.
# --instructions--
Create a scale and set its domain to `[250, 500]` and range to `[10, 150]`.
Crea una escala y establece su dominio a `[250, 500]` y su rango a `[10, 150]`.
**Note:** You can chain the `domain()` and `range()` methods onto the `scale` variable.
**Nota:** Puedes encadenar los métodos `domain()` y `range()` a la variable `scale`.
# --hints--
Your code should use the `domain()` method.
Tu código debe usar el método `domain()`.
```js
assert(code.match(/\.domain/g));
```
The `domain()` of the `scale` should be set to `[250, 500]`.
El `domain()` de `scale` (escala) debe ser establecido a `[250, 500]`.
```js
assert(JSON.stringify(scale.domain()) == JSON.stringify([250, 500]));
```
Your code should use the `range()` method.
Tu código debe usar el método `range()`.
```js
assert(code.match(/\.range/g));
```
The `range()` of the `scale` should be set to `[10, 150]`.
El `range()` de `scale` (escala) debe ser establecido a `[10, 150]`.
```js
assert(JSON.stringify(scale.range()) == JSON.stringify([10, 150]));
```
The text in the `h2` should be `-102`.
El texto en el `h2` debe ser `-102`.
```js
assert($('h2').text() == '-102');

View File

@ -1,6 +1,6 @@
---
id: 587d7faa367417b2b2512bd3
title: Style D3 Labels
title: Estiliza etiquetas D3
challengeType: 6
forumTopicId: 301492
dashedName: style-d3-labels
@ -8,21 +8,21 @@ dashedName: style-d3-labels
# --description--
D3 methods can add styles to the bar labels. The `fill` attribute sets the color of the text for a `text` node. The `style()` method sets CSS rules for other styles, such as `font-family` or `font-size`.
Los métodos D3 pueden agregar estilos a las etiquetas de barras. El atributo `fill` establece el color del texto para un nodo de texto `text`. El método `style()` establece reglas CSS para otros estilos, como por ejemplo `font-family` o `font-size`.
# --instructions--
Set the `font-size` of the `text` elements to `25px`, and the color of the text to red.
Establece el `font-size` de los elementos `text` a `25px`, y el color del texto a rojo (red).
# --hints--
The labels should all have a `fill` color of red.
Todas las etiquetas deben tener un `fill` de color rojo.
```js
assert($('text').css('fill') == 'rgb(255, 0, 0)');
```
The labels should all have a `font-size` of `25` pixels.
Todas las etiquetas deben tener un `font-size` de `25` píxeles.
```js
assert($('text').css('font-size') == '25px');

View File

@ -1,6 +1,6 @@
---
id: 587d7fa8367417b2b2512bc9
title: Update the Height of an Element Dynamically
title: Actualiza la altura de un elemento dinámicamente
challengeType: 6
forumTopicId: 301493
dashedName: update-the-height-of-an-element-dynamically
@ -8,13 +8,13 @@ dashedName: update-the-height-of-an-element-dynamically
# --description--
The previous challenges covered how to display data from an array and how to add CSS classes. You can combine these lessons to create a simple bar chart. There are two steps to this:
Los desafíos anteriores cubrieron cómo mostrar los datos de un arreglo y cómo agregar clases CSS. Puedes combinar estas lecciones para crear un simple gráfico de barras. Hay dos pasos para conseguirlo:
1) Create a `div` for each data point in the array
1) Crea un `div` por cada punto de datos en el arreglo
2) Give each `div` a dynamic height, using a callback function in the `style()` method that sets height equal to the data value
2) Dale a cada `div` una altura dinámica, usa la función callback en el método `style()` que establece una altura igual al valor de los datos
Recall the format to set a style using a callback function:
Recuerda el formato para establecer un estilo usando una función callback:
```js
selection.style("cssProperty", (d) => d)
@ -22,59 +22,59 @@ selection.style("cssProperty", (d) => d)
# --instructions--
Add the `style()` method to the code in the editor to set the `height` property for each element. Use a callback function to return the value of the data point with the string `px` added to it.
Añade el método `style()` al código en el editor para establecer la propiedad `height` a cada elemento. Usa una función callback para devolver el valor de los datos con la cadena `px` añadida a él.
# --hints--
The first `div` should have a `height` of `12` pixels.
El primer `div` debe tener un valor `height` de `12` píxeles.
```js
assert($('div').eq(0)[0].style.height === '12px');
```
The second `div` should have a `height` of `31` pixels.
El segundo `div` debe tener un valor `height` de `31` píxeles.
```js
assert($('div').eq(1)[0].style.height === '31px');
```
The third `div` should have a `height` of `22` pixels.
El tercer `div` debe tener un valor `height` de `22` píxeles.
```js
assert($('div').eq(2)[0].style.height === '22px');
```
The fourth `div` should have a `height` of `17` pixels.
El cuarto `div` debe tener un valor `height` de `17` píxeles.
```js
assert($('div').eq(3)[0].style.height === '17px');
```
The fifth `div` should have a `height` of `25` pixels.
El quinto `div` debe tener un valor `height` de `25` píxeles.
```js
assert($('div').eq(4)[0].style.height === '25px');
```
The sixth `div` should have a `height` of `18` pixels.
El sexto `div` debe tener un valor `height` de `18` píxeles.
```js
assert($('div').eq(5)[0].style.height === '18px');
```
The seventh `div` should have a `height` of `29` pixels.
El séptimo `div` debe tener un valor `height` de `29` píxeles.
```js
assert($('div').eq(6)[0].style.height === '29px');
```
The eighth `div` should have a `height` of `14` pixels.
El octavo `div` debe tener un valor `height` de `14` píxeles.
```js
assert($('div').eq(7)[0].style.height === '14px');
```
The ninth `div` should have a `height` of `9` pixels.
El noveno `div` debe tener un valor `height` de `9` píxeles.
```js
assert($('div').eq(8)[0].style.height === '9px');

View File

@ -1,6 +1,6 @@
---
id: 587d7fac367417b2b2512bde
title: Use a Pre-Defined Scale to Place Elements
title: Usa una escala predefinida para colocar elementos
challengeType: 6
forumTopicId: 301494
dashedName: use-a-pre-defined-scale-to-place-elements
@ -8,32 +8,32 @@ dashedName: use-a-pre-defined-scale-to-place-elements
# --description--
With the scales set up, it's time to map the scatter plot again. The scales are like processing functions that turn the `x` and `y` raw data into values that fit and render correctly on the SVG canvas. They keep the data within the screen's plotting area.
Con las escalas configuradas, es tiempo de trazar el diagrama de dispersión nuevamente. Las escalas son como funciones procesadoras que transforman los datos iniciales de `x` e `y` a valores que encajan y se renderizan correctamente en el lienzo SVG. Mantienen los datos dentro del área de trazado de la pantalla.
You set the coordinate attribute values for an SVG shape with the scaling function. This includes `x` and `y` attributes for `rect` or `text` elements, or `cx` and `cy` for `circles`. Here's an example:
Establece los valores de los atributos de coordenada para una forma SVG con la función escaladora. Esto incluye los atributos `x` e `y` para `rect` o elementos `text`, o `cx` y `cy` para `circles`. He aquí un ejemplo:
```js
shape
.attr("x", (d) => xScale(d[0]))
```
Scales set shape coordinate attributes to place the data points onto the SVG canvas. You don't need to apply scales when you display the actual data value, for example, in the `text()` method for a tooltip or label.
Las escalas establecen atributos de coordenada de las formas para colocar los puntos de datos en el lienzo SVG. No necesitas aplicar escalas cuando muestras el valor del dato real, por ejemplo, en el método `text()` para una descripción o una etiqueta.
# --instructions--
Use `xScale` and `yScale` to position both the `circle` and `text` shapes onto the SVG canvas. For the `circles`, apply the scales to set the `cx` and `cy` attributes. Give them a radius of `5` units, too.
Usa `xScale` e `yScale` para posicionar ambas formas `circle` y `text` en el lienzo SVG. Para los `circles`, aplica las escalas para establecer los atributos `cx` y `cy`. También, dales un radio de `5` unidades.
For the `text` elements, apply the scales to set the `x` and `y` attributes. The labels should be offset to the right of the dots. To do this, add `10` units to the `x` data value before passing it to the `xScale`.
Para los elementos `text`, aplica las escalas para establecer los atributos `x` e `y`. Las etiquetas deben ser desplazadas a la derecha de los puntos. Para ello, agrega `10` unidades al valor de datos `x` antes de pasarlo a `xScale`.
# --hints--
Your code should have 10 `circle` elements.
Tu código debe tener 10 elementos `circle`.
```js
assert($('circle').length == 10);
```
The first `circle` element should have a `cx` value of approximately `91` and a `cy` value of approximately `368` after applying the scales. It should also have an `r` value of `5`.
El primer elemento `circle` debe tener un valor `cx` de aproximadamente `91` y un valor `cy` de aproximadamente `368` luego de aplicar las escalas. También debe tener un valor `r` de `5`.
```js
assert(
@ -43,7 +43,7 @@ assert(
);
```
The second `circle` element should have a `cx` value of approximately `159` and a `cy` value of approximately `181` after applying the scales. It should also have an `r` value of `5`.
El segundo elemento `circle` debe tener un valor `cx` de aproximadamente `159` y un valor `cy` de aproximadamente `181` luego de aplicar las escalas. También debe tener un valor `r` de `5`.
```js
assert(
@ -53,7 +53,7 @@ assert(
);
```
The third `circle` element should have a `cx` value of approximately `340` and a `cy` value of approximately `329` after applying the scales. It should also have an `r` value of `5`.
El tercer elemento `circle` debe tener un valor `cx` de aproximadamente `340` y un valor `cy` de aproximadamente `329` luego de aplicar las escalas. También debe tener un valor `r` de `5`.
```js
assert(
@ -63,7 +63,7 @@ assert(
);
```
The fourth `circle` element should have a `cx` value of approximately `131` and a `cy` value of approximately `60` after applying the scales. It should also have an `r` value of `5`.
El cuarto elemento `circle` debe tener un valor `cx` de aproximadamente `131` y un valor `cy` de aproximadamente `60` luego de aplicar las escalas. También debe tener un valor `r` de `5`.
```js
assert(
@ -73,7 +73,7 @@ assert(
);
```
The fifth `circle` element should have a `cx` value of approximately `440` and a `cy` value of approximately `237` after applying the scales. It should also have an `r` value of `5`.
El quinto elemento `circle` debe tener un valor `cx` de aproximadamente `440` y un valor `cy` de aproximadamente `237` luego de aplicar las escalas. También debe tener un valor `r` de `5`.
```js
assert(
@ -83,7 +83,7 @@ assert(
);
```
The sixth `circle` element should have a `cx` value of approximately `271` and a `cy` value of approximately `306` after applying the scales. It should also have an `r` value of `5`.
El sexto elemento `circle` debe tener un valor `cx` de aproximadamente `271` y un valor `cy` de aproximadamente `306` luego de aplicar las escalas. También debe tener un valor `r` de `5`.
```js
assert(
@ -93,7 +93,7 @@ assert(
);
```
The seventh `circle` element should have a `cx` value of approximately `361` and a `cy` value of approximately `351` after applying the scales. It should also have an `r` value of `5`.
El séptimo elemento `circle` debe tener un valor `cx` de aproximadamente `361` y un valor `cy` de aproximadamente `351` luego de aplicar las escalas. También debe tener un valor `r` de `5`.
```js
assert(
@ -103,7 +103,7 @@ assert(
);
```
The eighth `circle` element should have a `cx` value of approximately `261` and a `cy` value of approximately `132` after applying the scales. It should also have an `r` value of `5`.
El octavo elemento `circle` debe tener un valor `cx` de aproximadamente `261` y un valor `cy` de aproximadamente `132` luego de aplicar las escalas. También debe tener un valor `r` de `5`.
```js
assert(
@ -113,7 +113,7 @@ assert(
);
```
The ninth `circle` element should have a `cx` value of approximately `131` and a `cy` value of approximately `144` after applying the scales. It should also have an `r` value of `5`.
El noveno elemento `circle` debe tener un valor `cx` de aproximadamente `131` y un valor `cy` de aproximadamente `144` luego de aplicar las escalas. También debe tener un valor `r` de `5`.
```js
assert(
@ -123,7 +123,7 @@ assert(
);
```
The tenth `circle` element should have a `cx` value of approximately `79` and a `cy` value of approximately `326` after applying the scales. It should also have an `r` value of `5`.
El décimo elemento `circle` debe tener un valor `cx` de aproximadamente `79` y un valor `cy` de aproximadamente `326` luego de aplicar las escalas. También debe tener un valor `r` de `5`.
```js
assert(
@ -133,13 +133,13 @@ assert(
);
```
Your code should have 10 `text` elements.
Tu código debe tener 10 elementos `text`.
```js
assert($('text').length == 10);
```
The first label should have an `x` value of approximately `100` and a `y` value of approximately `368` after applying the scales.
La primer etiqueta debe tener un valor `x` de aproximadamente `100` y un valor `y` de aproximadamente `368` luego de aplicar las escalas.
```js
assert(
@ -148,7 +148,7 @@ assert(
);
```
The second label should have an `x` value of approximately `168` and a `y` value of approximately `181` after applying the scales.
La segunda etiqueta debe tener un valor `x` de aproximadamente `168` y un valor `y` de aproximadamente `181` luego de aplicar las escalas.
```js
assert(
@ -157,7 +157,7 @@ assert(
);
```
The third label should have an `x` value of approximately `350` and a `y` value of approximately `329` after applying the scales.
La tercer etiqueta debe tener un valor `x` de aproximadamente `350` y un valor `y` de aproximadamente `329` luego de aplicar las escalas.
```js
assert(
@ -166,7 +166,7 @@ assert(
);
```
The fourth label should have an `x` value of approximately `141` and a `y` value of approximately `60` after applying the scales.
La cuarta etiqueta debe tener un valor `x` de aproximadamente `141` y un valor `y` de aproximadamente `60` luego de aplicar las escalas.
```js
assert(
@ -175,7 +175,7 @@ assert(
);
```
The fifth label should have an `x` value of approximately `449` and a `y` value of approximately `237` after applying the scales.
La quinta etiqueta debe tener un valor `x` de aproximadamente `449` y un valor `y` de aproximadamente `237` luego de aplicar las escalas.
```js
assert(
@ -184,7 +184,7 @@ assert(
);
```
The sixth label should have an `x` value of approximately `280` and a `y` value of approximately `306` after applying the scales.
La sexta etiqueta debe tener un valor `x` de aproximadamente `280` y un valor `y` de aproximadamente `306` luego de aplicar las escalas.
```js
assert(
@ -193,7 +193,7 @@ assert(
);
```
The seventh label should have an `x` value of approximately `370` and a `y` value of approximately `351` after applying the scales.
La séptima etiqueta debe tener un valor `x` de aproximadamente `370` y un valor `y` de aproximadamente `351` luego de aplicar las escalas.
```js
assert(
@ -202,7 +202,7 @@ assert(
);
```
The eighth label should have an `x` value of approximately `270` and a `y` value of approximately `132` after applying the scales.
La octava etiqueta debe tener un valor `x` de aproximadamente `270` y un valor `y` de aproximadamente `132` luego de aplicar las escalas.
```js
assert(
@ -211,7 +211,7 @@ assert(
);
```
The ninth label should have an `x` value of approximately `140` and a `y` value of approximately `144` after applying the scales.
La novena etiqueta debe tener un valor `x` de aproximadamente `140` y un valor `y` de aproximadamente `144` luego de aplicar las escalas.
```js
assert(
@ -220,7 +220,7 @@ assert(
);
```
The tenth label should have an `x` value of approximately `88` and a `y` value of approximately `326` after applying the scales.
La décima etiqueta debe tener un valor `x` de aproximadamente `88` y un valor `y` de aproximadamente `326` luego de aplicar las escalas.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7fac367417b2b2512bdd
title: Use Dynamic Scales
title: Utiliza escalas dinámicas
challengeType: 6
forumTopicId: 301495
dashedName: use-dynamic-scales
@ -8,13 +8,13 @@ dashedName: use-dynamic-scales
# --description--
The D3 `min()` and `max()` methods are useful to help set the scale.
Los métodos `min()` y `max()` de D3 son útiles para ayudar a establecer la escala.
Given a complex data set, one priority is to set the scale so the visualization fits the SVG container's width and height. You want all the data plotted inside the SVG canvas so it's visible on the web page.
Dado un conjunto de datos complejo, una de las prioridades es establecer la escala para que la visualización encaje la anchura y altura del contenedor SVG. Deseas que todos los datos estén trazados dentro del lienzo SVG para que sea visible en la página web.
The example below sets the x-axis scale for scatter plot data. The `domain()` method passes information to the scale about the raw data values for the plot. The `range()` method gives it information about the actual space on the web page for the visualization.
El siguiente ejemplo establece la escala del eje x para datos de un diagrama de dispersión. El método `domain()` envía información a la escala sobre los valores originales de los datos para el trazado. El método `range()` le proporciona información sobre el espacio actual en la página web para la visualización.
In the example, the domain goes from 0 to the maximum in the set. It uses the `max()` method with a callback function based on the x values in the arrays. The range uses the SVG canvas' width (`w`), but it includes some padding, too. This puts space between the scatter plot dots and the edge of the SVG canvas.
En el ejemplo, el dominio va de 0 al máximo en el conjunto. Utiliza el método `max()` con una función callback basada en los valores de x en los arreglos. El rango usa la anchura del lienzo SVG (`w`), pero incluye algo de padding (relleno), también. Esto pone espacio entre los puntos del diagrama de dispersión y el borde del lienzo SVG.
```js
const dataset = [
@ -38,29 +38,29 @@ const xScale = d3.scaleLinear()
.range([padding, w - padding]);
```
The padding may be confusing at first. Picture the x-axis as a horizontal line from 0 to 500 (the width value for the SVG canvas). Including the padding in the `range()` method forces the plot to start at 30 along that line (instead of 0), and end at 470 (instead of 500).
El padding (relleno) podría ser confuso en un principio. Imagínate el eje x como una línea horizontal de 0 a 500 (el valor del ancho del lienzo SVG). Incluir el padding en el método `range()` obliga al trazado a empezar en 30 a lo largo de esa línea (en lugar de 0), y terminar en 470 (en lugar de 500).
# --instructions--
Use the `yScale` variable to create a linear y-axis scale. The domain should start at zero and go to the maximum `y` value in the set. The range should use the SVG height (`h`) and include padding.
Utiliza la variable `yScale` para crear una escala lineal para el eje y. El dominio debe comenzar en cero e ir hasta el máximo valor de `y` en el conjunto. El rango debe usar la altura de SVG (`h`) e incluir padding (relleno).
**Note:** Remember to keep the plot right-side-up. When you set the range for the y coordinates, the higher value (height minus padding) is the first argument, and the lower value is the second argument.
**Nota:** Recuerda mantener el trazado hacia arriba. Cuando estableces el rango para las coordenadas y, el valor más alto (altura menos el relleno) es el primer argumento, y el valor más bajo es el segundo argumento.
# --hints--
The text in the `h2` should be `30`.
El texto en el `h2` debe ser `30`.
```js
assert(output == 30 && $('h2').text() == '30');
```
The `domain()` of yScale should be equivalent to `[0, 411]`.
El `domain()` de yScale debe ser equivalente a `[0, 411]`.
```js
assert(JSON.stringify(yScale.domain()) == JSON.stringify([0, 411]));
```
The `range()` of yScale should be equivalent to `[470, 30]`.
El `range()` de yScale debe ser equivalente a `[470, 30]`.
```js
assert(JSON.stringify(yScale.range()) == JSON.stringify([470, 30]));

View File

@ -1,7 +1,7 @@
---
id: 587d7fac367417b2b2512bdc
title: >-
Use the d3.max and d3.min Functions to Find Minimum and Maximum Values in a Dataset
Utiliza las funciones d3.max y d3.min para encontrar valores mínimos y máximos en un conjunto de datos
challengeType: 6
forumTopicId: 301496
dashedName: >-
@ -10,11 +10,11 @@ dashedName: >-
# --description--
The D3 methods `domain()` and `range()` set that information for your scale based on the data. There are a couple methods to make that easier.
Los métodos D3 `domain()` y `range()` establecen esa información para tu escala basada en los datos. Hay algunos métodos para hacerlo más fácil.
Often when you set the domain, you'll want to use the minimum and maximum values within the data set. Trying to find these values manually, especially in a large data set, may cause errors.
A menudo cuando estableces el dominio, querrás utilizar los valores mínimo y máximo dentro del conjunto de datos. Intentar buscar estos valores manualmente, especialmente en un conjunto de datos grande, puede causar errores.
D3 has two methods - `min()` and `max()` to return this information. Here's an example:
D3 tiene dos métodos: `min()` y `max()` para devolver esta información. He aquí un ejemplo:
```js
const exampleData = [34, 234, 73, 90, 6, 52];
@ -22,28 +22,28 @@ d3.min(exampleData)
d3.max(exampleData)
```
A dataset may have nested arrays, like the `[x, y]` coordinate pairs that were in the scatter plot example. In that case, you need to tell D3 how to calculate the maximum and minimum. Fortunately, both the `min()` and `max()` methods take a callback function. In this example, the callback function's argument `d` is for the current inner array. The callback needs to return the element from the inner array (the `x` or `y` value) over which you want to compute the maximum or minimum. Here's an example for how to find the min and max values with an array of arrays:
Un conjunto de datos podría tener arreglos anidados, como lo estaban el par de coordenada `[x, y]` en el ejemplo del diagrama de dispersión. En ese caso, necesitas decirle a D3 cómo calcular el máximo y el mínimo. Afortunadamente, ambos métodos `min()` y `max()` toman una función callback. En este ejemplo, el argumento de la función callback `d` es para el arreglo interno actual. El callback necesita retornar el elemento desde el arreglo interno (el valor de `x` o de `y`) sobre el cual quieres computar el máximo o el mínimo. Aquí hay un ejemplo de cómo encontrar los valores mínimo y máximo con un arreglo de arreglos:
```js
const locationData = [[1, 7],[6, 3],[8, 3]];
const minX = d3.min(locationData, (d) => d[0]);
```
`minX` would have the value `1`.
`minX` tendría el valor `1`.
# --instructions--
The `positionData` array holds sub arrays of x, y, and z coordinates. Use a D3 method to find the maximum value of the z coordinate (the third value) from the arrays and save it in the `output` variable.
El arreglo `positionData` contiene sub-arreglos de las coordenadas x, y, y z. Utiliza un método D3 para hallar el valor máximo de la coordenada z (el tercer valor) de los arreglos y guárdalo en la variable `output`.
# --hints--
The text in the `h2` should be `8`.
El texto en el `h2` debe ser `8`.
```js
assert(output == 8 && $('h2').text() == '8');
```
Your code should use the `max()` method.
Tu código debe usar el método `max()`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d7fa7367417b2b2512bc4
title: Work with Data in D3
title: Trabaja con datos en D3
challengeType: 6
forumTopicId: 301497
dashedName: work-with-data-in-d3
@ -8,15 +8,15 @@ dashedName: work-with-data-in-d3
# --description--
The D3 library focuses on a data-driven approach. When you have a set of data, you can apply D3 methods to display it on the page. Data comes in many formats, but this challenge uses a simple array of numbers.
La biblioteca de D3 se centra en un acercamiento enfocado a los datos. Cuando tienes un conjunto de datos, puedes aplicar métodos D3 para mostrarlo en la página. Los datos vienen en muchos formatos, pero este desafío utiliza un simple arreglo de números.
The first step is to make D3 aware of the data. The `data()` method is used on a selection of DOM elements to attach the data to those elements. The data set is passed as an argument to the method.
El primer paso es hacer que D3 sea consciente de los datos. El método `data()` es usado en una selección de elementos DOM para adjuntar los datos a esos elementos. El conjunto de datos es pasado como argumento al método.
A common workflow pattern is to create a new element in the document for each piece of data in the set. D3 has the `enter()` method for this purpose.
Un patrón de flujo de trabajo común es crear un nuevo elemento en el documento para cada pieza de datos del conjunto. D3 tiene el método `enter()` para este propósito.
When `enter()` is combined with the `data()` method, it looks at the selected elements from the page and compares them to the number of data items in the set. If there are fewer elements than data items, it creates the missing elements.
Cuando `enter()` es combinado con el método `data()`, observa los elementos seleccionados de la página y los compara con la cantidad de artículos de datos en el conjunto. Si hay menos elementos que artículos de datos, crea los elementos restantes.
Here is an example that selects a `ul` element and creates a new list item based on the number of entries in the array:
Aquí hay un ejemplo que selecciona un elemento `ul` y crea un nuevo elemento de lista basado en la cantidad de entradas en el arreglo:
```html
<body>
@ -32,21 +32,21 @@ Here is an example that selects a `ul` element and creates a new list item based
</body>
```
It may seem confusing to select elements that don't exist yet. This code is telling D3 to first select the `ul` on the page. Next, select all list items, which returns an empty selection. Then the `data()` method reviews the dataset and runs the following code three times, once for each item in the array. The `enter()` method sees there are no `li` elements on the page, but it needs 3 (one for each piece of data in `dataset`). New `li` elements are appended to the `ul` and have the text `New item`.
Puede parecer confuso seleccionar elementos que aún no existen. Este código le está diciendo a D3 que primero seleccione el `ul` en la página. A continuación, selecciona todos los artículos de la lista, lo cual devuelve una selección vacía. Entonces el método `data()` revisa el conjunto de datos y ejecuta el siguiente código tres veces, una vez por cada artículo en el arreglo. El método `enter()` observa que no hay elementos `li` en la página, pero necesita 3 (uno para cada pieza de datos en `dataset`). Se añaden nuevos elementos `li` al `ul` y tienen el texto `New item`.
# --instructions--
Select the `body` node, then select all `h2` elements. Have D3 create and append an `h2` tag for each item in the `dataset` array. The text in the `h2` should say `New Title`. Your code should use the `data()` and `enter()` methods.
Selecciona el nodo `body`, luego selecciona todos los elementos `h2`. Haz que D3 cree y añada una etiqueta `h2` para cada artículo en el arreglo `dataset`. El texto en el `h2` debe decir `New Title`. Tu código debe usar los métodos `data()` y `enter()`.
# --hints--
Your document should have 9 `h2` elements.
Tu documento debe tener 9 elementos `h2`.
```js
assert($('h2').length == 9);
```
The text in the `h2` elements should say `New Title`. The capitalization and spacing should match exactly.
El texto en los elementos `h2` debe decir `New Title`. Las mayúsculas y los espacios deben coincidir exactamente.
```js
assert(
@ -56,13 +56,13 @@ assert(
);
```
Your code should use the `data()` method.
Tu código debe usar el método `data()`.
```js
assert(code.match(/\.data/g));
```
Your code should use the `enter()` method.
Tu código debe usar el método `enter()`.
```js
assert(code.match(/\.enter/g));

View File

@ -1,6 +1,6 @@
---
id: 587d7fa7367417b2b2512bc5
title: Work with Dynamic Data in D3
title: Trabaja con datos dinámicos en D3
challengeType: 6
forumTopicId: 301498
dashedName: work-with-dynamic-data-in-d3
@ -8,75 +8,75 @@ dashedName: work-with-dynamic-data-in-d3
# --description--
The last two challenges cover the basics of displaying data dynamically with D3 using the `data()` and `enter()` methods. These methods take a data set and, together with the `append()` method, create a new DOM element for each entry in the data set.
Los dos últimos desafíos cubren las básicas de mostrar datos dinámicamente con D3 utilizando los métodos `data()` y `enter()`. Estos métodos toman un conjunto de datos y, junto con el método `append()`, crean un nuevo elemento DOM para cada entrada en el conjunto de datos.
In the previous challenge, you created a new `h2` element for each item in the `dataset` array, but they all contained the same text, `New Title`. This is because you have not made use of the data that is bound to each of the `h2` elements.
En el desafío anterior, haz creado un nuevo elemento `h2` para cada artículo en el arreglo `dataset`, pero todos contenían el mismo texto, `New Title`. Esto es porque no has usado los datos que están vinculados a cada uno de los elementos `h2`.
The D3 `text()` method can take a string or a callback function as an argument:
El método `text()` de D3 puede tomar una cadena o una función callback como argumento:
```js
selection.text((d) => d)
```
In the example above, the parameter `d` refers to a single entry in the dataset that a selection is bound to.
En el ejemplo superior, el parámetro `d` hace referencia a una sola entrada en el conjunto de datos a la cual la selección está vinculada.
Using the current example as context, the first `h2` element is bound to 12, the second `h2` element is bound to 31, the third `h2` element is bound to 22, and so on.
Utilizando el ejemplo actual como contexto, el primer elemento `h2` está vinculado a 12, el segundo elemento `h2` está vinculado a 31, el tercer elemento `h2` está vinculado a 22, y así sucesivamente.
# --instructions--
Change the `text()` method so that each `h2` element displays the corresponding value from the `dataset` array with a single space and the string `USD`. For example, the first heading should be `12 USD`.
Cambia el método `text()` para que cada elemento `h2` muestre el valor correspondiente del arreglo `dataset` con un solo espacio y la cadena `USD`. Por ejemplo, el primer título debe ser `12 USD`.
# --hints--
The first `h2` should have the text `12 USD`.
El primer `h2` debe tener el texto `12 USD`.
```js
assert($('h2').eq(0).text() == '12 USD');
```
The second `h2` should have the text `31 USD`.
El segundo `h2` debe tener el texto `31 USD`.
```js
assert($('h2').eq(1).text() == '31 USD');
```
The third `h2` should have the text `22 USD`.
El tercer `h2` debe tener el texto `22 USD`.
```js
assert($('h2').eq(2).text() == '22 USD');
```
The fourth `h2` should have the text `17 USD`.
El cuarto `h2` debe tener el texto `17 USD`.
```js
assert($('h2').eq(3).text() == '17 USD');
```
The fifth `h2` should have the text `25 USD`.
El quinto `h2` debe tener el texto `25 USD`.
```js
assert($('h2').eq(4).text() == '25 USD');
```
The sixth `h2` should have the text `18 USD`.
El sexto `h2` debe tener el texto `18 USD`.
```js
assert($('h2').eq(5).text() == '18 USD');
```
The seventh `h2` should have the text `29 USD`.
El séptimo `h2` debe tener el texto `29 USD`.
```js
assert($('h2').eq(6).text() == '29 USD');
```
The eighth `h2` should have the text `14 USD`.
El octavo `h2` debe tener el texto `14 USD`.
```js
assert($('h2').eq(7).text() == '14 USD');
```
The ninth `h2` should have the text `9 USD`.
El noveno `h2` debe tener el texto `9 USD`.
```js
assert($('h2').eq(8).text() == '9 USD');

View File

@ -36,6 +36,12 @@ La variabile `result` non dovrebbe essere impostata direttamente con una stringa
assert(!code.match(/result\s*=\s*["'`].*?["'`]/));
```
Il valore della variabile `hello` non dovrebbe cambiare.
```js
assert(hello === ' Hello, World! ');
```
# --seed--
## --seed-contents--

View File

@ -16,7 +16,7 @@ this.setState({
});
```
React si aspetta che tu non modifichi mai lo `state` direttamente: usa sempre `this.setState()` quando si verificano cambiamenti di stato. Inoltre, dovresti notare che React può raggruppare più aggiornamenti di stato al fine di migliorare le prestazioni. Ciò significa che gli aggiornamenti di stato attraverso il metodo `setState` possono essere asincroni. C'è una sintassi alternativa per il metodo `setState` che fornisce un modo per aggirare questo problema. Questo raramente è necessario, ma è bene tenerlo in mente! Consulta la [Documentazione di React](https://facebook.github.io/react/docs/state-and-lifecycle.html) per ulteriori dettagli.
React si aspetta che tu non modifichi mai lo `state` direttamente: usa sempre `this.setState()` quando si verificano cambiamenti di stato. Inoltre, dovresti notare che React può raggruppare più aggiornamenti di stato al fine di migliorare le prestazioni. Ciò significa che gli aggiornamenti di stato attraverso il metodo `setState` possono essere asincroni. C'è una sintassi alternativa per il metodo `setState` che fornisce un modo per aggirare questo problema. Questo raramente è necessario, ma è bene tenerlo in mente! Consulta la [Documentazione di React](https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous) per ulteriori dettagli.
# --instructions--

View File

@ -16,7 +16,7 @@ React fornisce utili funzioni di verifica del tipo per verificare che i componen
MyComponent.propTypes = { handleClick: PropTypes.func.isRequired }
```
Nell'esempio sopra, la parte `PropTypes.func` controlla che `handleClick` sia una funzione. Aggiungendo `isRequired` si dice a React che `handleClick` è una proprietà richiesta per quel componente. Se quella prop non è fornita vedrai un avviso. Nota anche che `func` rappresenta `function`. Tra i sette tipi primitivi JavaScript, `function` e `boolean` (scritto come `bool`) sono gli unici che usano un'ortografia insolita. Oltre ai tipi primitivi, ci sono altri tipi disponibili. Ad esempio, puoi controllare che una prop sia un elemento React. Fai riferimento alla [documentazione](https://reactjs.org/docs/jsx-in-depth.html#specifying-the-react-element-type) per tutte le opzioni.
Nell'esempio sopra, la parte `PropTypes.func` controlla che `handleClick` sia una funzione. Aggiungendo `isRequired` si dice a React che `handleClick` è una proprietà richiesta per quel componente. Se quella prop non è fornita vedrai un avviso. Nota anche che `func` rappresenta `function`. Tra i sette tipi primitivi JavaScript, `function` e `boolean` (scritto come `bool`) sono gli unici che usano un'ortografia insolita. Oltre ai tipi primitivi, ci sono altri tipi disponibili. Ad esempio, puoi controllare che una prop sia un elemento React. Fai riferimento alla [documentazione](https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes) per tutte le opzioni.
**Nota:** A partire da React v15.5.0, `PropTypes` viene importato indipendentemente da React, in questo modo: `import PropTypes from 'prop-types';`

View File

@ -3,6 +3,10 @@ id: 5e9a093a74c4063ca6f7c164
title: Analisi HTML e salvataggio dei dati
challengeType: 11
videoId: bJaqnTWQmb0
bilibiliIds:
aid: 335522976
bvid: BV1RA411F7vi
cid: 409023170
dashedName: parsing-html-and-saving-data
---
@ -12,14 +16,14 @@ dashedName: parsing-html-and-saving-data
Altre risorse:
- [Notebook su GitHub](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-17-reading-html-tables/files)
- [Notebook su GitHub](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas)
- [Come aprire Notebooks da GitHub usando Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
# --question--
## --text--
Quale libreria di Python ha un metodo `.read_html()` che possiamo usare per analizzare documenti HTML ed estrarre tabelle?
Quale libreria Python ha un metodo `.read_html()` che possiamo usare per analizzare documenti HTML ed estrarre tabelle?
## --answers--

View File

@ -3,6 +3,10 @@ id: 5e9a093a74c4063ca6f7c162
title: Lettura di dati CSV e TXT
challengeType: 11
videoId: ViGEv0zOzUk
bilibiliIds:
aid: 505575354
bvid: BV1tg411c7GH
cid: 409020451
dashedName: reading-data-csv-and-txt
---
@ -12,7 +16,7 @@ dashedName: reading-data-csv-and-txt
Altre risorse:
- [Notebook su GitHub](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-1-reading-csv-and-txt-files/files)
- [Notebook su GitHub](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas)
- [Come aprire Notebooks da GitHub usando Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
# --question--

View File

@ -3,6 +3,10 @@ id: 5e9a093a74c4063ca6f7c163
title: Leggere i dati dal database
challengeType: 11
videoId: MtgXS1MofRw
bilibiliIds:
aid: 890546354
bvid: BV1JP4y1h7gk
cid: 409020851
dashedName: reading-data-from-databases
---
@ -12,7 +16,7 @@ dashedName: reading-data-from-databases
Altre risorse:
- [Notebook su GitHub](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-11-reading-data-from-relational-databases/files)
- [Notebook su GitHub](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas)
- [Come aprire Notebooks da GitHub usando Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
# --question--

View File

@ -3,6 +3,10 @@ id: 5e9a093a74c4063ca6f7c161
title: Introduzione alla lettura dei dati
challengeType: 11
videoId: cDnt02BcHng
bilibiliIds:
aid: 548023524
bvid: BV1Nq4y1K7iV
cid: 409020187
dashedName: reading-data-introduction
---
@ -12,7 +16,7 @@ dashedName: reading-data-introduction
Altre risorse:
- [Notebook su GitHub](https://github.com/ine-rmotr-curriculum/RDP-Reading-Data-with-Python-and-Pandas/tree/master/unit-1-reading-data-with-python-and-pandas/lesson-1-reading-csv-and-txt-files/files)
- [Notebook su GitHub](https://github.com/krishnatray/RDP-Reading-Data-with-Python-and-Pandas)
- [Come aprire Notebooks da GitHub usando Google Colab.](https://colab.research.google.com/github/googlecolab/colabtools/blob/master/notebooks/colab-github-demo.ipynb)
# --question--

View File

@ -35,6 +35,18 @@ A primeira checkbox de seu formulário deve estar selecionada por padrão.
assert($('input[type="checkbox"]').prop('checked'));
```
Você não deve alterar o texto interno da etiqueta `Indoor`.
```js
assert.equal(document.querySelector('label[for="indoor"]')?.innerText?.trim(), 'Indoor');
```
Você não deve alterar o texto interno da etiqueta `Loving`.
```js
assert.equal(document.querySelector('label[for="loving"]')?.innerText?.trim(), 'Loving');
```
# --seed--
## --seed-contents--

View File

@ -36,6 +36,12 @@ Você não deve atribuir uma string diretamente à variável `result`
assert(!code.match(/result\s*=\s*["'`].*?["'`]/));
```
O valor da variável `hello` não deve ser alterado.
```js
assert(hello === ' Hello, World! ');
```
# --seed--
## --seed-contents--

View File

@ -16,7 +16,7 @@ this.setState({
});
```
React espera que você nunca modifique o `state` diretamente, em vez disso sempre use `this.setState()` quando as mudanças de estado ocorrerem. Além disso, você deve notar que React pode agrupar várias atualizações de estado para melhorar o desempenho. Isso significa que atualizações de estado através do método `setState` podem ser assíncronas. Existe uma sintaxe alternativa para o método `setState` que fornece uma forma de contornar esse problema. Isso raramente é necessário, mas é bom ter isso em mente! Consulte a [documentação do React](https://facebook.github.io/react/docs/state-and-lifecycle.html) para saber mais detalhes.
React espera que você nunca modifique o `state` diretamente, em vez disso sempre use `this.setState()` quando as mudanças de estado ocorrerem. Além disso, você deve notar que React pode agrupar várias atualizações de estado para melhorar o desempenho. Isso significa que atualizações de estado através do método `setState` podem ser assíncronas. Existe uma sintaxe alternativa para o método `setState` que fornece uma forma de contornar esse problema. Isso raramente é necessário, mas é bom ter isso em mente! Consulte a [documentação do React](https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous) para saber mais detalhes.
# --instructions--

View File

@ -16,7 +16,7 @@ React fornece recursos úteis de checagem de tipos para verificar se os componen
MyComponent.propTypes = { handleClick: PropTypes.func.isRequired }
```
No exemplo acima, a parte `PropTypes.func` verifica se `handleClick` é uma função. Adicionar `isRequired` diz ao React que `handleClick` é uma propriedade necessária para esse componente. Você verá um aviso se essa propriedade não for fornecida. Também observe que `func` representa `function`. Entre os sete tipos primitivos de JavaScript, `function` e `boolean` (escrito como `bool`) são os únicos dois que usam ortografia incomum. Além dos tipos primitivos, existem outros tipos disponíveis. Por exemplo, você pode verificar que uma prop é um elemento React. Por favor, consulte a [documentação](https://reactjs.org/docs/jsx-in-depth.html#specifying-the-react-element-type) para todas as opções.
No exemplo acima, a parte `PropTypes.func` verifica se `handleClick` é uma função. Adicionar `isRequired` diz ao React que `handleClick` é uma propriedade necessária para esse componente. Você verá um aviso se essa propriedade não for fornecida. Também observe que `func` representa `function`. Entre os sete tipos primitivos de JavaScript, `function` e `boolean` (escrito como `bool`) são os únicos dois que usam ortografia incomum. Além dos tipos primitivos, existem outros tipos disponíveis. Por exemplo, você pode verificar que uma prop é um elemento React. Consulte a [documentação](https://reactjs.org/docs/typechecking-with-proptypes.html#proptypes) para ver todas as opções.
**Observação:** a partir do React v15.5.0, `PropTypes` é importado independentemente do React, como: `import PropTypes from 'prop-types';`

View File

@ -1,6 +1,6 @@
---
id: 5900f3e61000cf542c50fef9
title: 'Problem 122: Efficient exponentiation'
title: 'Problema 122: Exponenciação eficiente'
challengeType: 5
forumTopicId: 301749
dashedName: problem-122-efficient-exponentiation
@ -8,28 +8,28 @@ dashedName: problem-122-efficient-exponentiation
# --description--
The most naive way of computing n15 requires fourteen multiplications:
A maneira mais ingênua de calcular $n^{15}$ requer 14 multiplicações:
n × n × ... × n = n15
$$n × n × \ldots × n = n^{15}$$
But using a "binary" method you can compute it in six multiplications:
Mas usando um método "binário" você pode calculá-lo em seis multiplicações:
n × n = n2n2 × n2 = n4n4 × n4 = n8n8 × n4 = n12n12 × n2 = n14n14 × n = n15
$$\begin{align} & n × n = n^2\\\\ & n^2 × n^2 = n^4\\\\ & n^4 × n^4 = n^8\\\\ & n^8 × n^4 = n^{12}\\\\ & n^{12} × n^2 = n^{14}\\\\ & n^{14} × n = n^{15} \end{align}$$
However it is yet possible to compute it in only five multiplications:
No entanto, ainda é possível calculá-lo em apenas cinco multiplicações:
n × n = n2n2 × n = n3n3 × n3 = n6n6 × n6 = n12n12 × n3 = n15
$$\begin{align} & n × n = n^2\\\\ & n^2 × n = n^3\\\\ & n^3 × n^3 = n^6\\\\ & n^6 × n^6 = n^{12}\\\\ & n^{12} × n^3 = n^{15} \end{align}$$
We shall define m(k) to be the minimum number of multiplications to compute nk; for example m(15) = 5.
Definiremos $m(k)$ como o número mínimo de multiplicações para calcular $n^k$; por exemplo, $m(15) = 5$.
For 1 ≤ k ≤ 200, find ∑ m(k).
Para $1 ≤ k ≤ 200$, encontre $\sum{m(k)}$.
# --hints--
`euler122()` should return 1582.
`efficientExponentation()` deve retornar `1582`.
```js
assert.strictEqual(euler122(), 1582);
assert.strictEqual(efficientExponentation(), 1582);
```
# --seed--
@ -37,12 +37,12 @@ assert.strictEqual(euler122(), 1582);
## --seed-contents--
```js
function euler122() {
function efficientExponentation() {
return true;
}
euler122();
efficientExponentation();
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: 5900f3e91000cf542c50fefc
title: 'Problem 125: Palindromic sums'
title: 'Problema 125: Somas de palíndromo'
challengeType: 5
forumTopicId: 301752
dashedName: problem-125-palindromic-sums
@ -8,18 +8,18 @@ dashedName: problem-125-palindromic-sums
# --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.
O número palíndromo 595 é interessante, porque ele pode ser escrito como a soma dos quadrados consecutivos: $6^2 + 7^2 + 8^2 + 9^2 + 9^2 + 10^2 + 11^2 + 12^2$.
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.
Existem exatamente onze palíndromos abaixo de mil que podem ser escritos como somas quadradas consecutivas. A soma destes palíndromos é 4164. Observe que $1 = 0^2 + 1^2$ não foi incluído pois este problema está interessado nos quadrados de inteiros positivos.
Find the sum of all the numbers less than 108 that are both palindromic and can be written as the sum of consecutive squares.
Calcule a soma de todos os números menores que $10^8$ que são palíndromos e podem ser escritos como a soma de quadrados consecutivos.
# --hints--
`euler125()` should return 2906969179.
`palindromicSums()` deve retornar `2906969179`.
```js
assert.strictEqual(euler125(), 2906969179);
assert.strictEqual(palindromicSums(), 2906969179);
```
# --seed--
@ -27,12 +27,12 @@ assert.strictEqual(euler125(), 2906969179);
## --seed-contents--
```js
function euler125() {
function palindromicSums() {
return true;
}
euler125();
palindromicSums();
```
# --solutions--

View File

@ -1,6 +1,6 @@
---
id: 5900f3ea1000cf542c50fefd
title: 'Problem 126: Cuboid layers'
title: 'Problema 126: Camadas de cuboides'
challengeType: 5
forumTopicId: 301753
dashedName: problem-126-cuboid-layers
@ -8,16 +8,26 @@ dashedName: problem-126-cuboid-layers
# --description--
The minimum number of cubes to cover every visible face on a cuboid measuring 3 x 2 x 1 is twenty-two.
A número mínimo de cubos para cobrir todas as faces visíveis de um cuboide medindo 3 x 2 x 1 é 22.
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.
<img class="img-responsive center-block" alt="Cuboide 3 x 2 x 1 coberto por 22 cubos 1 x 1 x 1" src="https://cdn.freecodecamp.org/curriculum/project-euler/cuboid-layers.png" style="background-color: white; padding: 10px;" />
Se adicionarmos uma segunda camada a este sólido, precisaremos de 46 cubos para cobrir todas as faces visíveis, a terceira camada precisará de 78 cubos e a quarta camada precisará de 118 cubos para cobrir todas as faces visíveis.
No entanto, a primeira camada de um cuboide que mede 5 x 1 x 1 também precisa de 22 cubos; analogamente, a primeira camada de cuboides que medem 5 x 3 x 1, 7 x 2 x 1 e 11 x 1 x 1 contém 46 cubos.
Definiremos $C(n)$ como a representação do número de cubos que contêm $n$ cubos em uma de suas camadas. Portanto, $C(22) = 2$, $C(46) = 4$, $C(78) = 5$ e $C(118) = 8$.
Acontece que 154 é o menor valor de $n$ no qual $C(n) = 10$.
Calcule o menor valor de $n$ no qual $C(n) = 1000$.
# --hints--
`euler126()` should return 18522.
`cuboidLayers()` deve retornar `18522`.
```js
assert.strictEqual(euler126(), 18522);
assert.strictEqual(cuboidLayers(), 18522);
```
# --seed--
@ -25,12 +35,12 @@ assert.strictEqual(euler126(), 18522);
## --seed-contents--
```js
function euler126() {
function cuboidLayers() {
return true;
}
euler126();
cuboidLayers();
```
# --solutions--