chore(i18n,curriculum): update translations (#43140)
This commit is contained in:
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 59694356a6e7011f7f1c5f4e
|
||||
title: Deal cards for FreeCell
|
||||
title: Distribuir as cartas no Freecell
|
||||
challengeType: 5
|
||||
forumTopicId: 302246
|
||||
dashedName: deal-cards-for-freecell
|
||||
@ -8,36 +8,36 @@ dashedName: deal-cards-for-freecell
|
||||
|
||||
# --description--
|
||||
|
||||
*FreeCell* is the solitaire card game that Paul Alfille introduced to the PLATO system in 1978. Jim Horne, at Microsoft, changed the name to FreeCell and reimplemented the game for [DOS](https://rosettacode.org/wiki/DOS "DOS"), then [Windows](https://rosettacode.org/wiki/Windows "Windows"). This version introduced 32000 numbered deals.
|
||||
O *FreeCell* é o jogo de cartas de paciência que Paul Alfille introduziu no sistema PLATO, em 1978. Jim Horne, na Microsoft, mudou o nome para FreeCell e reimplementou o jogo para o [DOS](https://rosettacode.org/wiki/DOS "DOS") e, posteriormente, para o [Windows](https://rosettacode.org/wiki/Windows "Windows"). A versão do Windows apresentava 32 mil distribuições numeradas.
|
||||
|
||||
As the game became popular, Jim Horne disclosed the algorithm, and other implementations of FreeCell began to reproduce the Microsoft deals. These deals are numbered from 1 to 32000. Newer versions from Microsoft have 1 million deals, numbered from 1 to 1000000; some implementations allow numbers outside that range.
|
||||
À medida que o jogo se tornou popular, Jim Horne revelou o algoritmo, e outras implementações do FreeCell começaram a reproduzir as distribuições de cartas da versão da Microsoft. Estas distribuições eram numeradas de 1 a 32000. As versões mais recentes da Microsoft têm 1 milhão de distribuições, numeradas de 1 a 1000000. Algumas implementações permitem números fora desse intervalo.
|
||||
|
||||
The algorithm uses this [linear congruential generator](https://rosettacode.org/wiki/linear congruential generator "linear congruential generator") from Microsoft C:
|
||||
O algoritmo usa este [gerador de congruência linear](https://rosettacode.org/wiki/linear congruential generator "linear congruential generator") de Microsoft C:
|
||||
|
||||
<ul>
|
||||
<li>$state_{n + 1} \equiv 214013 \times state_n + 2531011 \pmod{2^{31}}$</li>
|
||||
<li>$rand_n = state_n \div 2^{16}$</li>
|
||||
<li>$rand_n$ is in range 0 to 32767.</li>
|
||||
<li>$rand_n$ está no intervalo de 0 a 32767.</li>
|
||||
</ul>
|
||||
|
||||
The algorithm follows:
|
||||
Segue o algoritmo:
|
||||
|
||||
<ol>
|
||||
<li>Seed the RNG with the number of the deal.
|
||||
</li><li>Create an <a href='https://rosettacode.org/wiki/array' title='array' target='_blank'>array</a> of 52 cards: Ace of Clubs, Ace of Diamonds, Ace of Hearts, Ace of Spades, 2 of Clubs, 2 of Diamonds, and so on through the ranks: Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King. The array indexes are 0 to 51, with Ace of Clubs at 0, and King of Spades at 51.</li>
|
||||
<li>Until the array is empty:</li>
|
||||
<li>Choose a random card at index ≡ next random number (mod array length).</li>
|
||||
<li>Faça o seed do RNG (intervalo) com o número da distribuição.
|
||||
</li><li>Crie um <a href='https://rosettacode.org/wiki/array' title='array' target='_blank'>array</a> de 52 cartas: Ás de Paus, Ás de Ouro, Ás de Copas, Ás de Espadas, 2 de Paus, 2 de Ouro, e assim por diante: Ás, 2, 3, 4, 5, 6, 7, 8, 9, 10, Valete, Rainha, Rei. Os índices do array vão de 0 a 51, estando o Ás de Paus no índice 0 e o Rei de Espadas no índice 51.</li>
|
||||
<li>Até que o array esteja vazio:</li>
|
||||
<li>Escolha uma carta aleatória no índice ≡ próximo número aleatório (tamanho do array mod).</li>
|
||||
<ul>
|
||||
<li>Swap this random card with the last card of the array.</li>
|
||||
<li>Remove this random card from the array. (Array length goes down by 1.)</li>
|
||||
<li>Deal this random card.</li>
|
||||
<li>Troque esta carta aleatória pela última carta do array.</li>
|
||||
<li>Remova esta carta aleatória do array. (O comprimento do array diminui em 1.)</li>
|
||||
<li>Distribua esta carta aleatória.</li>
|
||||
</ul>
|
||||
<li>Deal all 52 cards, face up, across 8 columns. The first 8 cards go in 8 columns, the next 8 cards go on the first 8 cards, and so on.</li>
|
||||
<li>Distribua todas as 52 cartas, com a face voltada para cima, em 8 colunas. As primeiras 8 cartas aparecem em 8 colunas, as próximas 8 cartas vão sobre as primeiras 8 cartas e assim por diante.</li>
|
||||
</ol>
|
||||
|
||||
**Example:**
|
||||
**Exemplo:**
|
||||
|
||||
**Order to deal cards**
|
||||
**Ordenar de distribuição das cartas**
|
||||
|
||||
<pre> 1 2 3 4 5 6 7 8
|
||||
9 10 11 12 13 14 15 16
|
||||
@ -47,7 +47,7 @@ The algorithm follows:
|
||||
41 42 43 44 45 46 47 48
|
||||
49 50 51 52</pre>
|
||||
|
||||
**Game #1**
|
||||
**Jogo nº 1**
|
||||
|
||||
```js
|
||||
[
|
||||
@ -61,7 +61,7 @@ The algorithm follows:
|
||||
]
|
||||
```
|
||||
|
||||
**Game #617**
|
||||
**Jogo nº 617**
|
||||
|
||||
```js
|
||||
[
|
||||
@ -77,37 +77,37 @@ The algorithm follows:
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function to take a deal number and deal cards in the same order as this algorithm. The function must return a two dimensional array representing the FreeCell board.
|
||||
Escreva uma função para receber um número de distribuição e distribuir as cartas na mesma ordem que se encontram neste algoritmo. A função deve retornar um array bidimensional representando a mesa de Freecell.
|
||||
|
||||
Deals can also be checked against [FreeCell solutions to 1000000 games](https://freecellgamesolutions.com/). (Summon a video solution, and it displays the initial deal.)
|
||||
As distribuições também podem ser verificadas comparando-as às [soluções do FreeCell para 1.000.000 de jogos](https://freecellgamesolutions.com/). (Chame uma das solução por vídeo e ela mostra a distribuição inicial.)
|
||||
|
||||
# --hints--
|
||||
|
||||
`dealFreeCell` should be a function.
|
||||
`dealFreeCell` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof dealFreeCell === 'function');
|
||||
```
|
||||
|
||||
`dealFreeCell(seed)` should return an object.
|
||||
`dealFreeCell(seed)` deve retornar um objeto.
|
||||
|
||||
```js
|
||||
assert(typeof dealFreeCell(1) === 'object');
|
||||
```
|
||||
|
||||
`dealFreeCell(seed)` should return an array of length 7.
|
||||
`dealFreeCell(seed)` deve retornar um array de tamanho 7.
|
||||
|
||||
```js
|
||||
assert(dealFreeCell(1).length === 7);
|
||||
```
|
||||
|
||||
`dealFreeCell(1)` should return an array identical to example "Game #1"
|
||||
`dealFreeCell(1)` deve retornar um array idêntico ao exemple "Jogo nº 1"
|
||||
|
||||
```js
|
||||
assert.deepEqual(dealFreeCell(1), game1);
|
||||
```
|
||||
|
||||
`dealFreeCell(617)` should return an array identical to example "Game #617"
|
||||
`dealFreeCell(617)` deve retornar um array idêntico ao exemplo "Jogo nº 617"
|
||||
|
||||
```js
|
||||
assert.deepEqual(dealFreeCell(617), game617);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 596a8888ab7c01048de257d5
|
||||
title: Deepcopy
|
||||
title: Cópia profunda
|
||||
challengeType: 5
|
||||
forumTopicId: 302247
|
||||
dashedName: deepcopy
|
||||
@ -8,44 +8,44 @@ dashedName: deepcopy
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function that returns a deep copy of a given object. The copy must not be the same object that was given.
|
||||
Escreva uma função que retorne uma cópia profunda de um objeto dado. A cópia não deve ser o mesmo objeto que foi dado.
|
||||
|
||||
This task will not test for:
|
||||
Esta tarefa não testará:
|
||||
|
||||
<ul>
|
||||
<li>Objects with properties that are functions</li>
|
||||
<li>Date objects or object with properties that are Date objects</li>
|
||||
<li>RegEx or object with properties that are RegEx objects</li>
|
||||
<li>Prototype copying</li>
|
||||
<li>Objetos com propriedades que são funções</li>
|
||||
<li>Objetos de data ou objetos com propriedades que são objetos de data</li>
|
||||
<li>RegEx ou objetos com propriedades que são objetos RegEx</li>
|
||||
<li>Cópias de protótipos</li>
|
||||
</ul>
|
||||
|
||||
# --hints--
|
||||
|
||||
`deepcopy` should be a function.
|
||||
`deepcopy` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof deepcopy === 'function');
|
||||
```
|
||||
|
||||
`deepcopy({test: "test"})` should return an object.
|
||||
`deepcopy({test: "test"})` deve retornar um objeto.
|
||||
|
||||
```js
|
||||
assert(typeof deepcopy(obj1) === 'object');
|
||||
```
|
||||
|
||||
`deepcopy` should not return the same object that was provided.
|
||||
`deepcopy` não deve retornar o mesmo objeto que foi fornecido.
|
||||
|
||||
```js
|
||||
assert(deepcopy(obj2) != obj2);
|
||||
```
|
||||
|
||||
When passed an object containing an array, `deepcopy` should return a deep copy of the object.
|
||||
Quando for passado um objeto contendo um array, `deepcopy` deve retornar uma cópia profunda do objeto.
|
||||
|
||||
```js
|
||||
assert.deepEqual(deepcopy(obj2), obj2);
|
||||
```
|
||||
|
||||
When passed an object containing another object, `deepcopy` should return a deep copy of the object.
|
||||
Quando for passado um objeto contendo outro objeto, `deepcopy` deve retornar uma cópia profunda do objeto.
|
||||
|
||||
```js
|
||||
assert.deepEqual(deepcopy(obj3), obj3);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 597089c87eec450c68aa1643
|
||||
title: Define a primitive data type
|
||||
title: Definir um tipo de dado primitivo
|
||||
challengeType: 5
|
||||
forumTopicId: 302248
|
||||
dashedName: define-a-primitive-data-type
|
||||
@ -8,42 +8,42 @@ dashedName: define-a-primitive-data-type
|
||||
|
||||
# --description--
|
||||
|
||||
Define a type that behaves like an integer but has a lowest valid value of 1 and a highest valid value of 10.
|
||||
Defina um tipo que se comporte como um número inteiro, mas que tenha seu valor menor válido de 1 e seu maior valor válido de 10.
|
||||
|
||||
Error handling:
|
||||
Tratamento de erro:
|
||||
|
||||
<ul>
|
||||
<li>If you try to instantiate a <code>Num</code> with a value outside of 1 - 10, it should throw a <code>TypeError</code> with an error message of <code>'Out of range'</code>.</li>
|
||||
<li>If you try to instantiate a <code>Num</code> with a value that is not a number, it should throw a <code>TypeError</code> with an error message of <code>'Not a Number'</code>.</li>
|
||||
<li>Se você tentar instanciar um <code>Num</code> com um valor fora do intervalo de 1 - 10, deve lançar um <code>TypeError</code> com uma mensagem de erro de <code>'Out of range'</code>.</li>
|
||||
<li>Se você tentar instanciar um <code>Num</code> com um valor que não seja um número, deve lançar um <code>TypeError</code> com uma mensagem de erro de <code>'Not a Number'</code>.</li>
|
||||
</ul>
|
||||
|
||||
# --hints--
|
||||
|
||||
`Num` should be a function.
|
||||
`Num` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof Num === 'function');
|
||||
```
|
||||
|
||||
`new Num(4)` should return an object.
|
||||
`new Num(4)` deve retornar um objeto.
|
||||
|
||||
```js
|
||||
assert(typeof new Num(4) === 'object');
|
||||
```
|
||||
|
||||
`new Num('test')` should throw a TypeError with message 'Not a Number'.
|
||||
`new Num('test')` deve lançar um TypeError com a mensagem 'Not a Number'.
|
||||
|
||||
```js
|
||||
assert.throws(() => new Num('test'), TypeError);
|
||||
```
|
||||
|
||||
`new Num(0)` should throw a TypeError with message 'Out of range'.
|
||||
`new Num(0)` deve lançar um TypeError com a mensagem 'Out of range'.
|
||||
|
||||
```js
|
||||
assert.throws(() => new Num(0), TypeError);
|
||||
```
|
||||
|
||||
`new Num(-5)` should throw a TypeError with message 'Out of range'.
|
||||
`new Num(-5)` deve lançar um TypeError com a mensagem 'Out of range'.
|
||||
|
||||
```js
|
||||
assert.throws(() => new Num(-5), TypeError);
|
||||
@ -61,43 +61,43 @@ assert.throws(() => new Num(11), TypeError);
|
||||
assert.throws(() => new Num(20), TypeError);
|
||||
```
|
||||
|
||||
`new Num(3) + new Num(4)` should equal 7.
|
||||
`new Num(3) + new Num(4)` deve ser igual a 7.
|
||||
|
||||
```js
|
||||
assert.equal(new Num(3) + new Num(4), 7);
|
||||
```
|
||||
|
||||
`new Num(3) - new Num(4)` should equal -1.
|
||||
`new Num(3) - new Num(4)` deve ser igual a -1.
|
||||
|
||||
```js
|
||||
assert.equal(new Num(3) - new Num(4), -1);
|
||||
```
|
||||
|
||||
`new Num(3) * new Num(4)` should equal 12.
|
||||
`new Num(3) * new Num(4)` deve ser igual a 12.
|
||||
|
||||
```js
|
||||
assert.equal(new Num(3) * new Num(4), 12);
|
||||
```
|
||||
|
||||
`new Num(3) / new Num(4)` should equal 0.75.
|
||||
`new Num(3) / new Num(4)` deve ser igual a 0.75.
|
||||
|
||||
```js
|
||||
assert.equal(new Num(3) / new Num(4), 0.75);
|
||||
```
|
||||
|
||||
`new Num(3) < new Num(4)` should be true.
|
||||
`new Num(3) < new Num(4)` deve ser true.
|
||||
|
||||
```js
|
||||
assert(new Num(3) < new Num(4));
|
||||
```
|
||||
|
||||
`new Num(3) > new Num(4)` should be false.
|
||||
`new Num(3) > new Num(4)` deve ser false.
|
||||
|
||||
```js
|
||||
assert(!(new Num(3) > new Num(4)));
|
||||
```
|
||||
|
||||
`(new Num(5)).toString()` should return '5'
|
||||
`(new Num(5)).toString()` deve retornar '5'
|
||||
|
||||
```js
|
||||
assert.equal(new Num(5).toString(), '5');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 59f40b17e79dbf1ab720ed7a
|
||||
title: Department Numbers
|
||||
title: Números dos departamentos
|
||||
challengeType: 5
|
||||
forumTopicId: 302249
|
||||
dashedName: department-numbers
|
||||
@ -8,23 +8,23 @@ dashedName: department-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
There is a highly organized city that has decided to assign a number to each of their departments:
|
||||
Existe uma cidade altamente organizada que decidiu atribuir um número a cada um de seus departamentos:
|
||||
|
||||
<ul>
|
||||
<li>Police department</li>
|
||||
<li>Sanitation department</li>
|
||||
<li>Fire department</li>
|
||||
<li>Departamento de polícia</li>
|
||||
<li>Departamento de limpeza sanitária</li>
|
||||
<li>Departamento dos bombeiros</li>
|
||||
</ul>
|
||||
|
||||
Each department can have a number between 1 and 7 (inclusive).
|
||||
Cada departamento pode ter um número de 1 a 7 (inclusive).
|
||||
|
||||
The three department numbers are to be unique (different from each other) and must add up to the number 12.
|
||||
Os três números de departamento devem ser exclusivos (diferentes um do outro) e devem somar, no total, 12.
|
||||
|
||||
The Chief of the Police doesn't like odd numbers and wants to have an even number for his department.
|
||||
O chefe de polícia não gosta de números ímpares e quer que o número de seu departamento seja par.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a program which outputs all valid combinations as an array.
|
||||
Escreva um programa que retorne todas as combinações válidas na forma de um array.
|
||||
|
||||
```js
|
||||
[2, 3, 7] [2, 4, 6] [2, 6, 4]
|
||||
@ -36,25 +36,25 @@ Write a program which outputs all valid combinations as an array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`combinations` should be a function.
|
||||
`combinations` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof combinations === 'function');
|
||||
```
|
||||
|
||||
`combinations([1, 2, 3], 6)` should return an Array.
|
||||
`combinations([1, 2, 3], 6)` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(combinations([1, 2, 3], 6)));
|
||||
```
|
||||
|
||||
`combinations([1, 2, 3, 4, 5, 6, 7], 12)` should return an array of length 14.
|
||||
`combinations([1, 2, 3, 4, 5, 6, 7], 12)` deve retornar um array de tamanho 14.
|
||||
|
||||
```js
|
||||
assert(combinations(nums, total).length === len);
|
||||
```
|
||||
|
||||
`combinations([1, 2, 3, 4, 5, 6, 7], 12)` should return all valid combinations.
|
||||
`combinations([1, 2, 3, 4, 5, 6, 7], 12)` deve retornar todas as combinações válidas.
|
||||
|
||||
```js
|
||||
assert.deepEqual(combinations(nums, total), result);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 59f4eafba0343628bb682785
|
||||
title: Discordian date
|
||||
title: Data discordiana
|
||||
challengeType: 5
|
||||
forumTopicId: 302250
|
||||
dashedName: discordian-date
|
||||
@ -8,17 +8,17 @@ dashedName: discordian-date
|
||||
|
||||
# --description--
|
||||
|
||||
Convert a given date from the [Gregorian calendar](https://en.wikipedia.org/wiki/Gregorian calendar "wp: Gregorian calendar") to the [Discordian calendar](https://en.wikipedia.org/wiki/Discordian calendar "wp: Discordian calendar").
|
||||
Converta uma data fornecida do [Calendário Gregoriano](https://en.wikipedia.org/wiki/Gregorian calendar "wp: Gregorian calendar") para o [Calendário Discordiano](https://en.wikipedia.org/wiki/Discordian calendar "wp: Discordian calendar").
|
||||
|
||||
# --hints--
|
||||
|
||||
`discordianDate` should be a function.
|
||||
`discordianDate` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof discordianDate === 'function');
|
||||
```
|
||||
|
||||
`discordianDate(new Date(2010, 6, 22))` should return `"Pungenday, the 57th day of Confusion in the YOLD 3176"`.
|
||||
`discordianDate(new Date(2010, 6, 22))` deve retornar `"Pungenday, the 57th day of Confusion in the YOLD 3176"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -27,7 +27,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`discordianDate(new Date(2012, 1, 28))` should return `"Prickle-Prickle, the 59th day of Chaos in the YOLD 3178"`.
|
||||
`discordianDate(new Date(2012, 1, 28))` deve retornar `"Prickle-Prickle, the 59th day of Chaos in the YOLD 3178"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -36,7 +36,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`discordianDate(new Date(2012, 1, 29))` should return `"Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib\'s Day!"`.
|
||||
`discordianDate(new Date(2012, 1, 29))` deve retornar `"Setting Orange, the 60th day of Chaos in the YOLD 3178. Celebrate St. Tib\'s Day!"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -45,7 +45,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`discordianDate(new Date(2012, 2, 1))` should return `"Setting Orange, the 60th day of Chaos in the YOLD 3178"`.
|
||||
`discordianDate(new Date(2012, 2, 1))` deve retornar `"Setting Orange, the 60th day of Chaos in the YOLD 3178"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -54,7 +54,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`discordianDate(new Date(2010, 0, 5))` should return `"Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!"`.
|
||||
`discordianDate(new Date(2010, 0, 5))` deve retornar `"Setting Orange, the 5th day of Chaos in the YOLD 3176. Celebrate Mungday!"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -63,7 +63,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`discordianDate(new Date(2011, 4, 3))` should return `"Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!"`.
|
||||
`discordianDate(new Date(2011, 4, 3))` deve retornar `"Pungenday, the 50th day of Discord in the YOLD 3177. Celebrate Discoflux!"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -72,7 +72,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`discordianDate(new Date(2015, 9, 19))` should return `"Boomtime, the 73rd day of Bureaucracy in the YOLD 3181"`.
|
||||
`discordianDate(new Date(2015, 9, 19))` deve retornar `"Boomtime, the 73rd day of Bureaucracy in the YOLD 3181"`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7e1e
|
||||
title: Dot product
|
||||
title: Produto escalar
|
||||
challengeType: 5
|
||||
forumTopicId: 302251
|
||||
dashedName: dot-product
|
||||
@ -8,47 +8,47 @@ dashedName: dot-product
|
||||
|
||||
# --description--
|
||||
|
||||
Create a function, to compute the **[dot product](https://en.wikipedia.org/wiki/Dot product)**, also known as the **scalar product** of two vectors.
|
||||
Crie uma função, para calcular o **[Produto escalar](https://en.wikipedia.org/wiki/Dot product)**, também conhecido como **produto interno** entre dois vetores.
|
||||
|
||||
# --hints--
|
||||
|
||||
`dotProduct` should be a function.
|
||||
`dotProduct` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof dotProduct == 'function');
|
||||
```
|
||||
|
||||
`dotProduct([1, 3, -5], [4, -2, -1])` should return a number.
|
||||
`dotProduct([1, 3, -5], [4, -2, -1])` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof dotProduct([1, 3, -5], [4, -2, -1]) == 'number');
|
||||
```
|
||||
|
||||
`dotProduct([1, 3, -5], [4, -2, -1])` should return `3`.
|
||||
`dotProduct([1, 3, -5], [4, -2, -1])` deve retornar `3`.
|
||||
|
||||
```js
|
||||
assert.equal(dotProduct([1, 3, -5], [4, -2, -1]), 3);
|
||||
```
|
||||
|
||||
`dotProduct([1, 2, 3, 4, 5], [6, 7, 8, 9, 10])` should return `130`.
|
||||
`dotProduct([1, 2, 3, 4, 5], [6, 7, 8, 9, 10])` deve retornar `130`.
|
||||
|
||||
```js
|
||||
assert.equal(dotProduct([1, 2, 3, 4, 5], [6, 7, 8, 9, 10]), 130);
|
||||
```
|
||||
|
||||
`dotProduct([5, 4, 3, 2], [7, 8, 9, 6])` should return `106`.
|
||||
`dotProduct([5, 4, 3, 2], [7, 8, 9, 6])` deve retornar `106`.
|
||||
|
||||
```js
|
||||
assert.equal(dotProduct([5, 4, 3, 2], [7, 8, 9, 6]), 106);
|
||||
```
|
||||
|
||||
`dotProduct([-5, 4, -3, 2], [-7, -8, 9, -6])` should return `-36`.
|
||||
`dotProduct([-5, 4, -3, 2], [-7, -8, 9, -6])` deve retornar `-36`.
|
||||
|
||||
```js
|
||||
assert.equal(dotProduct([-5, 4, -3, 2], [-7, -8, 9, -6]), -36);
|
||||
```
|
||||
|
||||
`dotProduct([17, 27, 34, 43, 15], [62, 73, 48, 95, 110])` should return `10392`.
|
||||
`dotProduct([17, 27, 34, 43, 15], [62, 73, 48, 95, 110])` deve retornar `10392`.
|
||||
|
||||
```js
|
||||
assert.equal(dotProduct([17, 27, 34, 43, 15], [62, 73, 48, 95, 110]), 10392);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 599c333915e0ea32d04d4bec
|
||||
title: Element-wise operations
|
||||
title: Operações de elementos
|
||||
challengeType: 5
|
||||
forumTopicId: 302252
|
||||
dashedName: element-wise-operations
|
||||
@ -8,29 +8,29 @@ dashedName: element-wise-operations
|
||||
|
||||
# --description--
|
||||
|
||||
Implement basic element-wise matrix-matrix and scalar-matrix operations.
|
||||
Implemente operações básicas matriz-matriz e escalar-matriz de elementos.
|
||||
|
||||
**Implement:**
|
||||
**Implemente:**
|
||||
|
||||
<ul>
|
||||
<li>addition</li>
|
||||
<li>subtraction</li>
|
||||
<li>multiplication</li>
|
||||
<li>division</li>
|
||||
<li>exponentiation</li>
|
||||
<li>adição</li>
|
||||
<li>subtração</li>
|
||||
<li>multiplicação</li>
|
||||
<li>divisão</li>
|
||||
<li>exponenciação</li>
|
||||
</ul>
|
||||
|
||||
The first parameter will be the operation to be performed, for example, "m_add" for matrix addition and "s_add" for scalar addition. The second and third parameters will be the matrices on which the operations are to be performed.
|
||||
O primeiro parâmetro será a operação a ser executada, por exemplo, "m_add" para adição de matrizes e "s_add" para a adição escalar. O segundo e o terceiro parâmetros serão as matrizes sobre as quais as operações serão realizadas.
|
||||
|
||||
# --hints--
|
||||
|
||||
`operation` should be a function.
|
||||
`operation` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof operation === 'function');
|
||||
```
|
||||
|
||||
`operation("m_add",[[1,2],[3,4]],[[1,2],[3,4]])` should return `[[2,4],[6,8]]`.
|
||||
`operation("m_add",[[1,2],[3,4]],[[1,2],[3,4]])` deve retornar `[[2,4],[6,8]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -52,7 +52,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`operation("s_add",[[1,2],[3,4]],2)` should return `[[3,4],[5,6]]`.
|
||||
`operation("s_add",[[1,2],[3,4]],2)` deve retornar `[[3,4],[5,6]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -71,7 +71,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`operation("m_sub",[[1,2],[3,4]],[[1,2],[3,4]])` should return `[[0,0],[0,0]]`.
|
||||
`operation("m_sub",[[1,2],[3,4]],[[1,2],[3,4]])` deve retornar `[[0,0],[0,0]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -93,7 +93,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`operation("m_mult",[[1,2],[3,4]],[[1,2],[3,4]])` should return `[[1,4],[9,16]]`.
|
||||
`operation("m_mult",[[1,2],[3,4]],[[1,2],[3,4]])` deve retornar `[[1,4],[9,16]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -115,7 +115,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`operation("m_div",[[1,2],[3,4]],[[1,2],[3,4]])` should return `[[1,1],[1,1]]`.
|
||||
`operation("m_div",[[1,2],[3,4]],[[1,2],[3,4]])` deve retornar `[[1,1],[1,1]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -137,7 +137,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`operation("m_exp",[[1,2],[3,4]],[[1,2],[3,4]])` should return `[[1,4],[27,256]]`.
|
||||
`operation("m_exp",[[1,2],[3,4]],[[1,2],[3,4]])` deve retornar `[[1,4],[27,256]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -159,7 +159,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`operation("m_add",[[1,2,3,4],[5,6,7,8]],[[9,10,11,12],[13,14,15,16]])` should return `[[10,12,14,16],[18,20,22,24]]`.
|
||||
`operation("m_add",[[1,2,3,4],[5,6,7,8]],[[9,10,11,12],[13,14,15,16]])` deve retornar `[[10,12,14,16],[18,20,22,24]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 599d0ba974141b0f508b37d5
|
||||
title: Emirp primes
|
||||
title: Primos omirp
|
||||
challengeType: 5
|
||||
forumTopicId: 302253
|
||||
dashedName: emirp-primes
|
||||
@ -8,30 +8,30 @@ dashedName: emirp-primes
|
||||
|
||||
# --description--
|
||||
|
||||
An emirp (**prime** spelled backwards) are primes that when reversed (in their decimal representation) are a different prime.
|
||||
Um omirp (**primo** escrito ao contrário) é um número primo que, quando invertido (em sua representação decimal) é um número primo diferente.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that:
|
||||
Escreva uma função que:
|
||||
|
||||
<ul>
|
||||
<li>Shows the first <code>n</code> emirp numbers.</li>
|
||||
<li>Shows the emirp numbers in a range.</li>
|
||||
<li>Shows the number of emirps in a range.</li>
|
||||
<li>Shows the <code>n<sup>th</sup></code> emirp number.</li>
|
||||
<li>Mostra os <code>n</code> primeiros números omirp.</li>
|
||||
<li>Mostra os números omirp em um intervalo.</li>
|
||||
<li>Mostra o número de omirps em um intervalo.</li>
|
||||
<li>Mostre o <code>n<sup>th</sup></code> (enésimo) número omirp.</li>
|
||||
</ul>
|
||||
|
||||
The function should accept two parameters. The first will receive `n` or the range as an array. The second will receive a boolean, that specifies if the function returns the emirps as an array or a single number (the number of primes in the range or the <code>n<sup>th</sup></code> prime). According to the parameters the function should return an array or a number.
|
||||
A função deve receber dois parâmetros. O primeiro receberá `n` ou o intervalo como um array. O segundo receberá um booleano, que especifica se a função retorna os omirps como um array ou um único número - o número de primos no intervalo ou o <code>n<sup>th</sup></code> (enésimo) primo. De acordo com os parâmetros, a função deve retornar um array ou um número.
|
||||
|
||||
# --hints--
|
||||
|
||||
`emirps` should be a function.
|
||||
`emirps` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof emirps === 'function');
|
||||
```
|
||||
|
||||
`emirps(20,true)` should return `[13,17,31,37,71,73,79,97,107,113,149,157,167,179,199,311,337,347,359,389]`
|
||||
`emirps(20,true)` deve retornar `[13,17,31,37,71,73,79,97,107,113,149,157,167,179,199,311,337,347,359,389]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(emirps(20, true), [
|
||||
@ -58,13 +58,13 @@ assert.deepEqual(emirps(20, true), [
|
||||
]);
|
||||
```
|
||||
|
||||
`emirps(1000)` should return `70529`
|
||||
`emirps(1000)` deve retornar `70529`
|
||||
|
||||
```js
|
||||
assert.deepEqual(emirps(1000), 70529);
|
||||
```
|
||||
|
||||
`emirps([7700,8000],true)` should return `[7717,7757,7817,7841,7867,7879,7901,7927,7949,7951,7963]`
|
||||
`emirps([7700,8000],true)` deve retornar `[7717,7757,7817,7841,7867,7879,7901,7927,7949,7951,7963]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(emirps([7700, 8000], true), [
|
||||
@ -82,7 +82,7 @@ assert.deepEqual(emirps([7700, 8000], true), [
|
||||
]);
|
||||
```
|
||||
|
||||
`emirps([7700,8000],false)` should return `11`
|
||||
`emirps([7700,8000],false)` deve retornar `11`
|
||||
|
||||
```js
|
||||
assert.deepEqual(emirps([7700, 8000], false), 11);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 599d15309e88c813a40baf58
|
||||
title: Entropy
|
||||
title: Entropia
|
||||
challengeType: 5
|
||||
forumTopicId: 302254
|
||||
dashedName: entropy
|
||||
@ -8,53 +8,53 @@ dashedName: entropy
|
||||
|
||||
# --description--
|
||||
|
||||
Calculate the Shannon entropy H of a given input string.
|
||||
Calcule a entropia H de de uma string de entrada fornecida.
|
||||
|
||||
Given the discreet random variable $X$ that is a string of $N$ "symbols" (total characters) consisting of $n$ different characters (n=2 for binary), the Shannon entropy of X in bits/symbol is:
|
||||
Dada a variável aleatória discreta $X$, que é uma string de "símbolos" $N$ (total de caracteres) que consiste em $n$ caracteres diferentes (n=2 para binário), a entropia de Shannon de X em bits/símbolo é:
|
||||
|
||||
$H_2(X) = -\\sum\_{i=1}^n \\frac{count_i}{N} \\log_2 \\left(\\frac{count_i}{N}\\right)$
|
||||
|
||||
where $count_i$ is the count of character $n_i$.
|
||||
onde $count_i$ é a contagem de caracteres $n_i$.
|
||||
|
||||
# --hints--
|
||||
|
||||
`entropy` should be a function.
|
||||
`entropy` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof entropy === 'function');
|
||||
```
|
||||
|
||||
`entropy("0")` should return `0`
|
||||
`entropy("0")` deve retornar `0`
|
||||
|
||||
```js
|
||||
assert.equal(entropy('0'), 0);
|
||||
```
|
||||
|
||||
`entropy("01")` should return `1`
|
||||
`entropy("01")` deve retornar `1`
|
||||
|
||||
```js
|
||||
assert.equal(entropy('01'), 1);
|
||||
```
|
||||
|
||||
`entropy("0123")` should return `2`
|
||||
`entropy("0123")` deve retornar `2`
|
||||
|
||||
```js
|
||||
assert.equal(entropy('0123'), 2);
|
||||
```
|
||||
|
||||
`entropy("01234567")` should return `3`
|
||||
`entropy("01234567")` deve retornar `3`
|
||||
|
||||
```js
|
||||
assert.equal(entropy('01234567'), 3);
|
||||
```
|
||||
|
||||
`entropy("0123456789abcdef")` should return `4`
|
||||
`entropy("0123456789abcdef")` deve retornar `4`
|
||||
|
||||
```js
|
||||
assert.equal(entropy('0123456789abcdef'), 4);
|
||||
```
|
||||
|
||||
`entropy("1223334444")` should return `1.8464393446710154`
|
||||
`entropy("1223334444")` deve retornar `1.8464393446710154`
|
||||
|
||||
```js
|
||||
assert.equal(entropy('1223334444'), 1.8464393446710154);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5987fd532b954e0f21b5d3f6
|
||||
title: Equilibrium index
|
||||
title: Índice de equilíbrio
|
||||
challengeType: 5
|
||||
forumTopicId: 302255
|
||||
dashedName: equilibrium-index
|
||||
@ -8,9 +8,9 @@ dashedName: equilibrium-index
|
||||
|
||||
# --description--
|
||||
|
||||
An equilibrium index of a sequence is an index into the sequence such that the sum of elements at lower indices is equal to the sum of elements at higher indices.
|
||||
Um índice de equilíbrio de uma sequência é um índice na sequência, tal que a soma dos elementos nos índices mais baixos é igual à soma dos elementos nos índices mais altos.
|
||||
|
||||
For example, in a sequence $A$:
|
||||
Por exemplo, em uma sequência $A$:
|
||||
|
||||
<ul style='list-style: none;'>
|
||||
<li><big>$A_0 = -7$</big></li>
|
||||
@ -22,67 +22,67 @@ For example, in a sequence $A$:
|
||||
<li><big>$A_6 = 0$</big></li>
|
||||
</ul>
|
||||
|
||||
`3` is an equilibrium index, because:
|
||||
`3` é um índice de equilíbrio, porque:
|
||||
|
||||
<ul style='list-style: none;'>
|
||||
<li><big>$A_0 + A_1 + A_2 = A_4 + A_5 + A_6$</big></li>
|
||||
</ul>
|
||||
|
||||
`6` is also an equilibrium index, because:
|
||||
`6` também é um índice de equilíbrio, porque:
|
||||
|
||||
<ul style='list-style: none;'>
|
||||
<li><big>$A_0 + A_1 + A_2 + A_3 + A_4 + A_5 = 0$</big></li>
|
||||
</ul>
|
||||
|
||||
(sum of zero elements is zero)
|
||||
(a soma de zero elementos é zero)
|
||||
|
||||
`7` is not an equilibrium index, because it is not a valid index of sequence $A$.
|
||||
`7` não é um índice de equilíbrio porque não é um índice válido da sequência $A$.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that, given a sequence, returns its equilibrium indices (if any).
|
||||
Escreva uma função que, dada uma sequência, retorne seus índices de equilíbrio (se houver).
|
||||
|
||||
Assume that the sequence may be very long.
|
||||
Suponha que a sequência seja muito longa.
|
||||
|
||||
# --hints--
|
||||
|
||||
`equilibrium` should be a function.
|
||||
`equilibrium` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof equilibrium === 'function');
|
||||
```
|
||||
|
||||
`equilibrium([-7, 1, 5, 2, -4, 3, 0])` should return `[3,6]`.
|
||||
`equilibrium([-7, 1, 5, 2, -4, 3, 0])` deve retornar `[3,6]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(equilibrium(equilibriumTests[0]), ans[0]);
|
||||
```
|
||||
|
||||
`equilibrium([2, 4, 6])` should return `[]`.
|
||||
`equilibrium([2, 4, 6])` deve retornar `[]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(equilibrium(equilibriumTests[1]), ans[1]);
|
||||
```
|
||||
|
||||
`equilibrium([2, 9, 2])` should return `[1]`.
|
||||
`equilibrium([2, 9, 2])` deve retornar `[1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(equilibrium(equilibriumTests[2]), ans[2]);
|
||||
```
|
||||
|
||||
`equilibrium([1, -1, 1, -1, 1, -1, 1])` should return `[0,1,2,3,4,5,6]`.
|
||||
`equilibrium([1, -1, 1, -1, 1, -1, 1])` deve retornar `[0,1,2,3,4,5,6]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(equilibrium(equilibriumTests[3]), ans[3]);
|
||||
```
|
||||
|
||||
`equilibrium([1])` should return `[0]`.
|
||||
`equilibrium([1])` deve retornar `[0]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(equilibrium(equilibriumTests[4]), ans[4]);
|
||||
```
|
||||
|
||||
`equilibrium([])` should return `[]`.
|
||||
`equilibrium([])` deve retornar `[]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(equilibrium(equilibriumTests[5]), ans[5]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 599d1566a02b571412643b84
|
||||
title: Ethiopian multiplication
|
||||
title: Multiplicação etíope
|
||||
challengeType: 5
|
||||
forumTopicId: 302257
|
||||
dashedName: ethiopian-multiplication
|
||||
@ -8,24 +8,24 @@ dashedName: ethiopian-multiplication
|
||||
|
||||
# --description--
|
||||
|
||||
Ethiopian multiplication is a method of multiplying integers using only addition, doubling, and halving.
|
||||
A multiplicação etíope é um método de multiplicação de inteiros usando apenas adição, duplicação e divisão pela metade.
|
||||
|
||||
**Method:**
|
||||
**Método:**
|
||||
|
||||
<ol>
|
||||
<li>Take two numbers to be multiplied and write them down at the top of two columns</li>
|
||||
<li>In the left-hand column repeatedly halve the last number, discarding any remainders, and write the result below the last in the same column, until you write a value of <code>1</code></li>
|
||||
<li>In the right-hand column repeatedly double the last number and write the result below. stop when you add a result in the same row as where the left hand column shows <code>1</code></li>
|
||||
<li>Examine the table produced and discard any row where the value in the left column is even</li>
|
||||
<li>Sum the values in the right-hand column that remain to produce the result of multiplying the original two numbers together</li>
|
||||
<li>Pegue dois números para serem multiplicados e anote-os no topo de duas colunas</li>
|
||||
<li>Na coluna da esquerda, reduza repetidamente pela metade o último número, descartando quaisquer restos, e escreva o resultado abaixo do último na mesma coluna, até você escrever o valor de <code>1</code></li>
|
||||
<li>Na coluna da direita, duplique repetidamente o último número e escreva o resultado abaixo. Pare quando adicionar um resultado na mesma linha onde a coluna da esquerda mostre <code>1</code></li>
|
||||
<li>Examinar a tabela produzida e descarte qualquer linha onde o valor na coluna da esquerda seja par</li>
|
||||
<li>Soma os valores na coluna da direita que permanecem para produzir o resultado da multiplicação dos dois números originais juntos</li>
|
||||
</ol>
|
||||
|
||||
**For example:** `17 × 34`
|
||||
**Por exemplo:** `17 × 34`
|
||||
|
||||
<pre>17 34
|
||||
</pre>
|
||||
|
||||
Halving the first column:
|
||||
Dividindo o valor da primeira coluna pela metade:
|
||||
|
||||
<pre>17 34
|
||||
8
|
||||
@ -34,7 +34,7 @@ Halving the first column:
|
||||
1
|
||||
</pre>
|
||||
|
||||
Doubling the second column:
|
||||
Duplicando o valor da segunda coluna:
|
||||
|
||||
<pre>17 34
|
||||
8 68
|
||||
@ -43,7 +43,7 @@ Doubling the second column:
|
||||
1 544
|
||||
</pre>
|
||||
|
||||
Strike-out rows whose first cell is even:
|
||||
Removendo as linhas em que a primeira célula é par:
|
||||
|
||||
<pre>17 34
|
||||
8 <strike>68</strike>
|
||||
@ -52,7 +52,7 @@ Strike-out rows whose first cell is even:
|
||||
1 544
|
||||
</pre>
|
||||
|
||||
Sum the remaining numbers in the right-hand column:
|
||||
Somando os números restantes na coluna da direita:
|
||||
|
||||
<!-- markdownlint-disable MD003 -->
|
||||
|
||||
@ -67,55 +67,55 @@ Sum the remaining numbers in the right-hand column:
|
||||
|
||||
<!-- markdownlint-enable MD003 -->
|
||||
|
||||
So `17` multiplied by `34`, by the Ethiopian method is `578`.
|
||||
Temos, então, que `17` multiplicado por `34`, pelo método etíope, é `578`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
The task is to define three named functions/methods/procedures/subroutines:
|
||||
A tarefa é definir três funções/métodos/procedimentos/sub-rotinas nomeadas:
|
||||
|
||||
<ol>
|
||||
<li>one to halve an integer,</li>
|
||||
<li>one to double an integer, and</li>
|
||||
<li>one to state if an integer is even</li>
|
||||
<li>um para dividir pela metade um número inteiro,</li>
|
||||
<li>um para dobrar um número inteiro, e</li>
|
||||
<li>uma para declarar se um inteiro é par</li>
|
||||
</ol>
|
||||
|
||||
Use these functions to create a function that does Ethiopian multiplication.
|
||||
Use essas funções para criar uma função que faça uma multiplicação etíope.
|
||||
|
||||
<!-- markdownlint-disable MD046-->
|
||||
|
||||
# --hints--
|
||||
|
||||
`eth_mult` should be a function.
|
||||
`eth_mult` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof eth_mult === 'function');
|
||||
```
|
||||
|
||||
`eth_mult(17,34)` should return `578`.
|
||||
`eth_mult(17,34)` deve retornar `578`.
|
||||
|
||||
```js
|
||||
assert.equal(eth_mult(17, 34), 578);
|
||||
```
|
||||
|
||||
`eth_mult(23,46)` should return `1058`.
|
||||
`eth_mult(23,46)` deve retornar `1058`.
|
||||
|
||||
```js
|
||||
assert.equal(eth_mult(23, 46), 1058);
|
||||
```
|
||||
|
||||
`eth_mult(12,27)` should return `324`.
|
||||
`eth_mult(12,27)` deve retornar `324`.
|
||||
|
||||
```js
|
||||
assert.equal(eth_mult(12, 27), 324);
|
||||
```
|
||||
|
||||
`eth_mult(56,98)` should return `5488`.
|
||||
`eth_mult(56,98)` deve retornar `5488`.
|
||||
|
||||
```js
|
||||
assert.equal(eth_mult(56, 98), 5488);
|
||||
```
|
||||
|
||||
`eth_mult(63,74)` should return `4662`.
|
||||
`eth_mult(63,74)` deve retornar `4662`.
|
||||
|
||||
```js
|
||||
assert.equal(eth_mult(63, 74), 4662);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 59880443fb36441083c6c20e
|
||||
title: Euler method
|
||||
title: Método de Euler
|
||||
challengeType: 5
|
||||
forumTopicId: 302258
|
||||
dashedName: euler-method
|
||||
@ -8,63 +8,63 @@ dashedName: euler-method
|
||||
|
||||
# --description--
|
||||
|
||||
Euler's method numerically approximates solutions of first-order ordinary differential equations (ODEs) with a given initial value. It is an explicit method for solving initial value problems (IVPs), as described in [the wikipedia page](https://en.wikipedia.org/wiki/Euler method "wp: Euler method").
|
||||
O método de Euler aproxima numericamente as soluções de equações diferenciais normais de primeira ordem (ODEs) com um dado valor inicial. É um método explícito para resolver problemas de valor inicial (IVPs), conforme descrito na [página da Wikipédia](https://en.wikipedia.org/wiki/Euler method "wp: Euler method").
|
||||
|
||||
The ODE has to be provided in the following form:
|
||||
O ODE deve ser fornecido da seguinte forma:
|
||||
|
||||
<ul style='list-style: none;'>
|
||||
<li><big>$\frac{dy(t)}{dt} = f(t,y(t))$</big></li>
|
||||
</ul>
|
||||
|
||||
with an initial value
|
||||
com um valor inicial
|
||||
|
||||
<ul style='list-style: none;'>
|
||||
<li><big>$y(t_0) = y_0$</big></li>
|
||||
</ul>
|
||||
|
||||
To get a numeric solution, we replace the derivative on the LHS with a finite difference approximation:
|
||||
Para obter uma solução numérica, substituímos a derivada do lado esquerdo por uma aproximação da diferença finita:
|
||||
|
||||
<ul style='list-style: none;'>
|
||||
<li><big>$\frac{dy(t)}{dt} \approx \frac{y(t+h)-y(t)}{h}$</big></li>
|
||||
</ul>
|
||||
|
||||
then solve for $y(t+h)$:
|
||||
então resolva para $y(t+h)$:
|
||||
|
||||
<ul style='list-style: none;'>
|
||||
<li><big>$y(t+h) \approx y(t) + h \, \frac{dy(t)}{dt}$</big></li>
|
||||
</ul>
|
||||
|
||||
which is the same as
|
||||
que é o mesmo que
|
||||
|
||||
<ul style='list-style: none;'>
|
||||
<li><big>$y(t+h) \approx y(t) + h \, f(t,y(t))$</big></li>
|
||||
</ul>
|
||||
|
||||
The iterative solution rule is then:
|
||||
A regra de solução iterativa é, então:
|
||||
|
||||
<ul style='list-style: none;'>
|
||||
<li><big>$y_{n+1} = y_n + h \, f(t_n, y_n)$</big></li>
|
||||
</ul>
|
||||
|
||||
where $h$ is the step size, the most relevant parameter for accuracy of the solution. A smaller step size increases accuracy but also the computation cost, so it has always has to be hand-picked according to the problem at hand.
|
||||
onde $h$ é o tamanho da etapa, o parâmetro mais relevante para a precisão da solução. Um tamanho de etapa menor aumenta a precisão, mas também o custo de cálculo. Então, ele tem que ser sempre escolhido com cuidado e de acordo com o problema em questão.
|
||||
|
||||
**Example: Newton's Cooling Law**
|
||||
**Exemplo: Lei de resfriamento de Newton**
|
||||
|
||||
Newton's cooling law describes how an object of initial temperature $T(t_0) = T_0$ cools down in an environment of temperature $T_R$:
|
||||
A lei de resfriamento de Newton descreve como um objeto de temperatura inicial $T(t_0) = T_0$ resfria em um ambiente de temperatura $T_R$:
|
||||
|
||||
<ul style='list-style: none;'>
|
||||
<li><big>$\frac{dT(t)}{dt} = -k \, \Delta T$</big></li>
|
||||
</ul>
|
||||
|
||||
or
|
||||
ou
|
||||
|
||||
<ul style='list-style: none;'>
|
||||
<li><big>$\frac{dT(t)}{dt} = -k \, (T(t) - T_R)$</big></li>
|
||||
</ul>
|
||||
|
||||
It says that the cooling rate $\\frac{dT(t)}{dt}$ of the object is proportional to the current temperature difference $\\Delta T = (T(t) - T_R)$ to the surrounding environment.
|
||||
Ela diz que a taxa de resfriamento $\\frac{dT(t)}{dt}$ do objeto é proporcional à diferença de temperatura atual $\\Delta = (T(t) - T_R)$ com relação ao ambiente ao redor.
|
||||
|
||||
The analytical solution, which we will compare to the numerical approximation, is
|
||||
A solução analítica, que compararemos à aproximação numérica, é
|
||||
|
||||
<ul style='list-style: none;'>
|
||||
<li><big>$T(t) = T_R + (T_0 - T_R) \; e^{-k t}$</big></li>
|
||||
@ -72,54 +72,54 @@ The analytical solution, which we will compare to the numerical approximation, i
|
||||
|
||||
# --instructions--
|
||||
|
||||
Implement a routine of Euler's method and then use it to solve the given example of Newton's cooling law for three different step sizes of:
|
||||
Implemente uma rotina do método de Euler e, em seguida, use-a para resolver o exemplo da lei de resfriamento de Newton para três tamanhos de etapa diferentes de:
|
||||
|
||||
<ul>
|
||||
<li><code>2 s</code></li>
|
||||
<li><code>5 s</code> and</li>
|
||||
<li><code>5 s</code> e</li>
|
||||
<li><code>10 s</code></li>
|
||||
</ul>
|
||||
|
||||
and compare with the analytical solution.
|
||||
e compare com a solução analítica.
|
||||
|
||||
**Initial values:**
|
||||
**Valores iniciais:**
|
||||
|
||||
<ul>
|
||||
<li>initial temperature <big>$T_0$</big> shall be <code>100 °C</code></li>
|
||||
<li>room temperature <big>$T_R$</big> shall be <code>20 °C</code></li>
|
||||
<li>cooling constant <big>$k$</big> shall be <code>0.07</code></li>
|
||||
<li>time interval to calculate shall be from <code>0 s</code> to <code>100 s</code></li>
|
||||
<li>a temperatura inicial <big>$T_0$</big> deve ser <code>100 °C</code></li>
|
||||
<li>a temperatura ambiente <big>$T_R$</big> deve ser <code>20 °C</code></li>
|
||||
<li>a constante de resfriamento <big>$k$</big> será <code>0.07</code></li>
|
||||
<li>o intervalo de tempo para calcular deve ser de <code>0 s</code> a <code>100 s</code></li>
|
||||
</ul>
|
||||
|
||||
First parameter to the function is initial time, second parameter is initial temperature, third parameter is elapsed time and fourth parameter is step size.
|
||||
O primeiro parâmetro para a função é o tempo inicial, o segundo parâmetro é a temperatura inicial, o terceiro parâmetro é o tempo passado e o quarto parâmetro é o tamanho do passo.
|
||||
|
||||
# --hints--
|
||||
|
||||
`eulersMethod` should be a function.
|
||||
`eulersMethod` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof eulersMethod === 'function');
|
||||
```
|
||||
|
||||
`eulersMethod(0, 100, 100, 2)` should return a number.
|
||||
`eulersMethod(0, 100, 100, 2)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof eulersMethod(0, 100, 100, 2) === 'number');
|
||||
```
|
||||
|
||||
`eulersMethod(0, 100, 100, 2)` should return 20.0424631833732.
|
||||
`eulersMethod(0, 100, 100, 2)` deve retornar 20.0424631833732.
|
||||
|
||||
```js
|
||||
assert.equal(eulersMethod(0, 100, 100, 2), 20.0424631833732);
|
||||
```
|
||||
|
||||
`eulersMethod(0, 100, 100, 5)` should return 20.01449963666907.
|
||||
`eulersMethod(0, 100, 100, 5)` deve retornar 20.01449963666907.
|
||||
|
||||
```js
|
||||
assert.equal(eulersMethod(0, 100, 100, 5), 20.01449963666907);
|
||||
```
|
||||
|
||||
`eulersMethod(0, 100, 100, 10)` should return 20.000472392.
|
||||
`eulersMethod(0, 100, 100, 10)` deve retornar 20.000472392.
|
||||
|
||||
```js
|
||||
assert.equal(eulersMethod(0, 100, 100, 10), 20.000472392);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 598de241872ef8353c58a7a2
|
||||
title: Evaluate binomial coefficients
|
||||
title: Avaliar coeficientes binomiais
|
||||
challengeType: 5
|
||||
forumTopicId: 302259
|
||||
dashedName: evaluate-binomial-coefficients
|
||||
@ -8,45 +8,45 @@ dashedName: evaluate-binomial-coefficients
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function to calculate the binomial coefficient for the given value of n and k.
|
||||
Escreva uma função para calcular o coeficiente binomial para o valor dado de n e k.
|
||||
|
||||
This formula is recommended:
|
||||
Esta fórmula é recomendada:
|
||||
|
||||
$\\binom{n}{k} = \\frac{n!}{(n-k)!k!} = \\frac{n(n-1)(n-2)\\ldots(n-k+1)}{k(k-1)(k-2)\\ldots 1}$
|
||||
|
||||
# --hints--
|
||||
|
||||
`binom` should be a function.
|
||||
`binom` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof binom === 'function');
|
||||
```
|
||||
|
||||
`binom(5,3)` should return 10.
|
||||
`binom(5,3)` deve retornar 10.
|
||||
|
||||
```js
|
||||
assert.equal(binom(5, 3), 10);
|
||||
```
|
||||
|
||||
`binom(7,2)` should return 21.
|
||||
`binom(7,2)` deve retornar 21.
|
||||
|
||||
```js
|
||||
assert.equal(binom(7, 2), 21);
|
||||
```
|
||||
|
||||
`binom(10,4)` should return 210.
|
||||
`binom(10,4)` deve retornar 210.
|
||||
|
||||
```js
|
||||
assert.equal(binom(10, 4), 210);
|
||||
```
|
||||
|
||||
`binom(6,1)` should return 6.
|
||||
`binom(6,1)` deve retornar 6.
|
||||
|
||||
```js
|
||||
assert.equal(binom(6, 1), 6);
|
||||
```
|
||||
|
||||
`binom(12,8)` should return 495.
|
||||
`binom(12,8)` deve retornar 495.
|
||||
|
||||
```js
|
||||
assert.equal(binom(12, 8), 495);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 59e09e6d412c5939baa02d16
|
||||
title: Execute a Markov algorithm
|
||||
title: Executar um algoritmo de Markov
|
||||
challengeType: 5
|
||||
forumTopicId: 302260
|
||||
dashedName: execute-a-markov-algorithm
|
||||
@ -8,9 +8,9 @@ dashedName: execute-a-markov-algorithm
|
||||
|
||||
# --description--
|
||||
|
||||
Create an interpreter for a [Markov Algorithm](https://en.wikipedia.org/wiki/Markov algorithm "wp: Markov algorithm").
|
||||
Crie um interpretador para um [Algoritmo de Markov](https://en.wikipedia.org/wiki/Markov algorithm "wp: Markov algorithm").
|
||||
|
||||
Rules have the syntax:
|
||||
As regras têm a seguinte sintaxe:
|
||||
|
||||
<pre>[ruleset] ::= (([comment] | [rule]) [newline]+)*
|
||||
[comment] ::= # {[any character]}
|
||||
@ -18,79 +18,79 @@ Rules have the syntax:
|
||||
[whitespace] ::= ([tab] | [space]) [[whitespace]]
|
||||
</pre>
|
||||
|
||||
There is one rule per line.
|
||||
Há uma regra por linha.
|
||||
|
||||
If there is a `.` (period) present before the \[replacement], then this is a terminating rule in which case the interpreter must halt execution.
|
||||
Se houver um `.` (ponto) presente antes de \[replacement], esta é uma regra de encerramento. Neste caso, o interpretador deve parar a execução.
|
||||
|
||||
A ruleset consists of a sequence of rules, with optional comments.
|
||||
Um conjunto de regras consiste em uma sequência de regras, com comentários opcionais.
|
||||
|
||||
Rulesets
|
||||
Regras
|
||||
|
||||
Use the following tests on entries:
|
||||
Use os seguintes testes em entradas:
|
||||
|
||||
**Ruleset 1:**
|
||||
**Regra 1:**
|
||||
|
||||
<pre># This rules file is extracted from Wikipedia:
|
||||
<pre># Este arquivo de regras foi extraído da Wikipédia:
|
||||
# <code>http://en.wikipedia.org/wiki/Markov_Algorithm</code>
|
||||
A -> apple
|
||||
B -> bag
|
||||
S -> shop
|
||||
T -> the
|
||||
the shop -> my brother
|
||||
a never used -> .terminating rule
|
||||
A -> apple (maçã)
|
||||
B -> bag (sacola)
|
||||
S -> shop (loja)
|
||||
T -> the (o/a)
|
||||
the shop -> my brother (a loja -> meu irmão)
|
||||
a nunca usado -> .regra de encerramento
|
||||
</pre>
|
||||
|
||||
Sample text of `I bought a B of As from T S.` should generate the output `I bought a bag of apples from my brother.`
|
||||
O texto de exemplo `I bought a B of As from T S.` deve gerar a saída `I bought a bag of apples from my brother.`
|
||||
|
||||
**Ruleset 2:**
|
||||
**Regra 2:**
|
||||
|
||||
A test of the terminating rule
|
||||
Um teste da regra de encerramento
|
||||
|
||||
<pre># Slightly modified from the rules on Wikipedia
|
||||
<pre># Levemente modificado a partir das regras da Wikipédia
|
||||
A -> apple
|
||||
B -> bag
|
||||
S -> .shop
|
||||
T -> the
|
||||
the shop -> my brother
|
||||
a never used -> .terminating rule
|
||||
a nunca usado -> .regra de encerramento
|
||||
</pre>
|
||||
|
||||
Sample text of `I bought a B of As from T S.` should generate `I bought a bag of apples from T shop.`
|
||||
O texto de exemplo `I bought a B of As from T S.` deve gerar a saída `I bought a bag of apples from T shop.`
|
||||
|
||||
**Ruleset 3:**
|
||||
**Regra 3:**
|
||||
|
||||
This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped.
|
||||
Isto testa a ordem de substituição correta e pode capturar rotinas de substituição simples baseadas em regexp se caracteres especiais não forem escapados.
|
||||
|
||||
<pre># BNF Syntax testing rules
|
||||
A -> apple
|
||||
WWWW -> with
|
||||
<pre># Regras de teste de sintaxe do formalismo de Backus-Naur
|
||||
A -> apple (maçã)
|
||||
WWWW -> with (com)
|
||||
Bgage -> ->.*
|
||||
B -> bag
|
||||
->.* -> money
|
||||
B -> bag (sacola)
|
||||
->.* -> money (dinheiro)
|
||||
W -> WW
|
||||
S -> .shop
|
||||
T -> the
|
||||
the shop -> my brother
|
||||
a never used -> .terminating rule
|
||||
S -> .shop (.loja)
|
||||
T -> the (o/a)
|
||||
the shop -> my brother (a loja -> meu irmão)
|
||||
a nunca usado -> .regra de encerramento
|
||||
</pre>
|
||||
|
||||
Sample text of `I bought a B of As W my Bgage from T S.` should generate `I bought a bag of apples with my money from T shop.`
|
||||
O texto de exemplo `I bought a B of As W my Bgage from T S.` deve gerar `I bought a bag of apples with my money from T shop.`
|
||||
|
||||
**Ruleset 4:**
|
||||
**Regra 4:**
|
||||
|
||||
This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order. It implements a general unary multiplication engine. (Note that the input expression must be placed within underscores in this implementation.)
|
||||
Esta regra testa a ordem correta de varredura das regras e pode capturar rotinas de substituição que fazem a varredura na ordem errada. Ela implementa um mecanismo de multiplicação unária geral. (Observe que a expressão de entrada deve ser colocada dentro dos sublinhados nesta implementação.)
|
||||
|
||||
<pre>### Unary Multiplication Engine, for testing Markov Algorithm implementations
|
||||
### By Donal Fellows.
|
||||
# Unary addition engine
|
||||
<pre>### Mecanismo de multiplicação unária, para testar implementações do algoritmo de Markov
|
||||
### Por Donal Fellows.
|
||||
# Mecanismo de adição unária
|
||||
_+1 -> _1+
|
||||
1+1 -> 11+
|
||||
# Pass for converting from the splitting of multiplication into ordinary
|
||||
# addition
|
||||
# Passada para converter da divisão de multiplicação em simples
|
||||
# adição
|
||||
1! -> !1
|
||||
,! -> !+
|
||||
_! -> _
|
||||
# Unary multiplication by duplicating left side, right side times
|
||||
# Multiplicação unária pela duplicação do lado esquerdo, o lado direito de vezes
|
||||
1*1 -> x,@y
|
||||
1x -> xX
|
||||
X, -> 1,1
|
||||
@ -99,82 +99,82 @@ _x -> _X
|
||||
,x -> ,X
|
||||
y1 -> 1y
|
||||
y_ -> _
|
||||
# Next phase of applying
|
||||
# Próxima fase de aplicação
|
||||
1@1 -> x,@y
|
||||
1@_ -> @_
|
||||
,@_ -> !_
|
||||
++ -> +
|
||||
# Termination cleanup for addition
|
||||
# Limpeza de encerramento para a adição
|
||||
_1 -> 1
|
||||
1+_ -> 1
|
||||
_+_ ->
|
||||
</pre>
|
||||
|
||||
Sample text of `_1111*11111_` should generate the output `11111111111111111111`
|
||||
O texto de exemplo `_1111*11111_` deve gerar o resultado `11111111111111111111`
|
||||
|
||||
**Ruleset 5:**
|
||||
**Regra 5:**
|
||||
|
||||
A simple [Turing machine](http://en.wikipedia.org/wiki/Turing_machine "link: http://en.wikipedia.org/wiki/Turing_machine"), implementing a three-state [busy beaver](http://en.wikipedia.org/wiki/Busy_beaver "link: http://en.wikipedia.org/wiki/Busy_beaver").
|
||||
Uma [Máquina de Turing](http://en.wikipedia.org/wiki/Turing_machine "link: http://en.wikipedia.org/wiki/Turing_machine") simples, implementando um [algoritmo do castor](http://en.wikipedia.org/wiki/Busy_beaver "link: http://en.wikipedia.org/wiki/Busy_beaver") de três estados.
|
||||
|
||||
The tape consists of `0`s and `1`s, the states are `A`, `B`, `C` and `H` (for `H`alt), and the head position is indicated by writing the state letter before the character where the head is. All parts of the initial tape the machine operates on have to be given in the input.
|
||||
A fita consiste em `0`s e `1`s, os estados são `A`, `B`, `C` e `H` (para `H`alt - parada), e a posição do cabeçote é indicada pela escrita da letra de estado antes do caractere onde o cabeçote está. Todas as partes da fita inicial que a máquina opera têm de ser fornecidas na entrada.
|
||||
|
||||
Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets.
|
||||
Além de demonstrar que o algoritmo de Markov está completo para Turing, essa regra também me fez pegar um bug na implementação de C ++, que não foi capturado pelas primeiras quatro regras.
|
||||
|
||||
<pre># Turing machine: three-state busy beaver
|
||||
<pre># Máquina de Turing: algoritmo do castor de três estados
|
||||
#
|
||||
# state A, symbol 0 => write 1, move right, new state B
|
||||
# estado A, símbolo 0 => escreve 1, move para a direita, novo estado B
|
||||
A0 -> 1B
|
||||
# state A, symbol 1 => write 1, move left, new state C
|
||||
# estado A, símbolo 1 => escreve 1, move para a esquerda, novo estado C
|
||||
0A1 -> C01
|
||||
1A1 -> C11
|
||||
# state B, symbol 0 => write 1, move left, new state A
|
||||
# estado B, símbolo 0 => escreve 1, move para a esquerda, novo estado A
|
||||
0B0 -> A01
|
||||
1B0 -> A11
|
||||
# state B, symbol 1 => write 1, move right, new state B
|
||||
# estado B, símbolo 1 => escreve 1, move para a direita, novo estado B
|
||||
B1 -> 1B
|
||||
# state C, symbol 0 => write 1, move left, new state B
|
||||
# estado C, símbolo 0 => escreve 1, move para a esquerda, novo estado B
|
||||
0C0 -> B01
|
||||
1C0 -> B11
|
||||
# state C, symbol 1 => write 1, move left, halt
|
||||
# estado C, símbolo 1 => escreve 1, move para a esquerda, para
|
||||
0C1 -> H01
|
||||
1C1 -> H11
|
||||
</pre>
|
||||
|
||||
This ruleset should turn `000000A000000` into `00011H1111000`
|
||||
Este conjunto de regras deve transformar `000000A000000` em `00011H1111000`
|
||||
|
||||
# --hints--
|
||||
|
||||
`markov` should be a function.
|
||||
`markov` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof markov === 'function');
|
||||
```
|
||||
|
||||
`markov(["A -> apple","B -> bag","S -> shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As from T S.")` should return "I bought a bag of apples from my brother.".
|
||||
`markov(["A -> apple","B -> bag","S -> shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As from T S.")` deve retornar "I bought a bag of apples from my brother.".
|
||||
|
||||
```js
|
||||
assert.deepEqual(markov(rules[0], tests[0]), outputs[0]);
|
||||
```
|
||||
|
||||
`markov(["A -> apple","B -> bag","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As from T S.")` should return "I bought a bag of apples from T shop.".
|
||||
`markov(["A -> apple","B -> bag","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As from T S.")` deve retornar "I bought a bag of apples from T shop.".
|
||||
|
||||
```js
|
||||
assert.deepEqual(markov(rules[1], tests[1]), outputs[1]);
|
||||
```
|
||||
|
||||
`markov(["A -> apple","WWWW -> with","Bgage -> ->.*","B -> bag","->.* -> money","W -> WW","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As W my Bgage from T S.")` should return "I bought a bag of apples with my money from T shop.".
|
||||
`markov(["A -> apple","WWWW -> with","Bgage -> ->.*","B -> bag","->.* -> money","W -> WW","S -> .shop","T -> the","the shop -> my brother","a never used -> .terminating rule"],"I bought a B of As W my Bgage from T S.")` deve retornar "I bought a bag of apples with my money from T shop.".
|
||||
|
||||
```js
|
||||
assert.deepEqual(markov(rules[2], tests[2]), outputs[2]);
|
||||
```
|
||||
|
||||
`markov(["_+1 -> _1+","1+1 -> 11+","1! -> !1",",! -> !+","_! -> _","1*1 -> x,@y","1x -> xX","X, -> 1,1","X1 -> 1X","_x -> _X",",x -> ,X","y1 -> 1y","y_ -> _","1@1 -> x,@y","1@_ -> @_",",@_ -> !_","++ -> +","_1 -> 1","1+_ -> 1","_+_ -> "],"_1111*11111_")` should return "11111111111111111111".
|
||||
`markov(["_+1 -> _1+","1+1 -> 11+","1! -> !1",",! -> !+","_! -> _","1*1 -> x,@y","1x -> xX","X, -> 1,1","X1 -> 1X","_x -> _X",",x -> ,X","y1 -> 1y","y_ -> _","1@1 -> x,@y","1@_ -> @_",",@_ -> !_","++ -> +","_1 -> 1","1+_ -> 1","_+_ -> "],"_1111*11111_")` deve retornar "11111111111111111111".
|
||||
|
||||
```js
|
||||
assert.deepEqual(markov(rules[3], tests[3]), outputs[3]);
|
||||
```
|
||||
|
||||
`markov(["A0 -> 1B","0A1 -> C01","1A1 -> C11","0B0 -> A01","1B0 -> A11","B1 -> 1B","0C0 -> B01","1C0 -> B11","0C1 -> H01","1C1 -> H11"],"")` should return "00011H1111000".
|
||||
`markov(["A0 -> 1B","0A1 -> C01","1A1 -> C11","0B0 -> A01","1B0 -> A11","B1 -> 1B","0C0 -> B01","1C0 -> B11","0C1 -> H01","1C1 -> H11"],"")` deve retornar "00011H1111000".
|
||||
|
||||
```js
|
||||
assert.deepEqual(markov(rules[4], tests[4]), outputs[4]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 59e0a8df964e4540d5abe599
|
||||
title: Execute Brain****
|
||||
title: Executar Brain****
|
||||
challengeType: 5
|
||||
forumTopicId: 302261
|
||||
dashedName: execute-brain
|
||||
@ -8,54 +8,54 @@ dashedName: execute-brain
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function to implement a Brain\*\*\*\* interpreter. The function will take a string as a parameter and should return a string as the output. More details are given below:
|
||||
Escreva uma função para implementar um interpretador de Brain\*\*\*\*. A função receberá uma string como um parâmetro e deve retornar uma string como saída. Mais detalhes são fornecidos abaixo:
|
||||
|
||||
RCBF is a set of [Brainf\*\*\*](https://rosettacode.org/wiki/Brainf*** "Brainf\*\*\*") compilers and interpreters written for Rosetta Code in a variety of languages.
|
||||
RCBF é um conjunto de interpretadores e compiladores [Brainf\*\*\*](https://rosettacode.org/wiki/Brainf*** "Brainf\*\*\*") escritos pelo Rosetta Code em diversas linguagens.
|
||||
|
||||
Below are links to each of the versions of RCBF.
|
||||
Abaixo, encontramos os links para cada uma das versões do RCBF.
|
||||
|
||||
An implementation need only properly implement the following instructions:
|
||||
Uma implementação só precisa implementar corretamente as seguintes instruções:
|
||||
|
||||
| Command | Description |
|
||||
| ------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| <code>></code> | Move the pointer to the right |
|
||||
| <code><</code> | Move the pointer to the left |
|
||||
| <code>+</code> | Increment the memory cell under the pointer |
|
||||
| <code>-</code> | Decrement the memory cell under the pointer |
|
||||
| <code>.</code> | Output the character signified by the cell at the pointer |
|
||||
| <code>,</code> | Input a character and store it in the cell at the pointer |
|
||||
| <code>\[</code> | Jump past the matching <code>]</code> if the cell under the pointer is 0 |
|
||||
| <code>]</code> | Jump back to the matching <code>\[</code> if the cell under the pointer is nonzero |
|
||||
| Comando | Descrição |
|
||||
| ------------------------- | ---------------------------------------------------------------------------------------------- |
|
||||
| <code>></code> | Mova o ponteiro para a direita |
|
||||
| <code><</code> | Mova o ponteiro para a esquerda |
|
||||
| <code>+</code> | Incremente a célula de memória sob o ponteiro |
|
||||
| <code>-</code> | Decremente a célula de memória sob o ponteiro |
|
||||
| <code>.</code> | Produza o caractere representado pela célula no ponteiro |
|
||||
| <code>,</code> | Insira um caractere e armazene-o na célula do ponteiro |
|
||||
| <code>\[</code> | Salte para além da correspondência de <code>]</code> se a célula sob o ponteiro for 0 |
|
||||
| <code>]</code> | Volte à célula correspondente <code>\[</code> se a célula sob o ponteiro não for zero |
|
||||
|
||||
Any cell size is allowed, EOF (*E*nd-*O*-*F*ile) support is optional, as is whether you have bounded or unbounded memory.
|
||||
Qualquer tamanho de célula é permitido, suporte a EOF (*E*nd-*O*f-*F*ile) é opcional, bem como ter memória limitada ou não limitada.
|
||||
|
||||
# --hints--
|
||||
|
||||
`brain(bye)` should return a string
|
||||
`brain(bye)` deve retornar uma string
|
||||
|
||||
```js
|
||||
assert(typeof brain(bye) === 'string');
|
||||
```
|
||||
|
||||
`brain("++++++[>++++++++++<-]>+++++.")` should return "A"
|
||||
`brain("++++++[>++++++++++<-]>+++++.")` deve retornar "A"
|
||||
|
||||
```js
|
||||
assert.equal(brain('++++++[>++++++++++<-]>+++++.'), 'A');
|
||||
```
|
||||
|
||||
`brain(bye)` should return `Goodbye, World!\r\n`
|
||||
`brain(bye)` deve retornar `Goodbye, World!\r\n`
|
||||
|
||||
```js
|
||||
assert.equal(brain(bye), 'Goodbye, World!\r\n');
|
||||
```
|
||||
|
||||
`brain(hello)` should return `Hello World!\n`
|
||||
`brain(hello)` deve retornar `Hello World!\n`
|
||||
|
||||
```js
|
||||
assert.equal(brain(hello), 'Hello World!\n');
|
||||
```
|
||||
|
||||
`brain(fib)` should return `1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89`
|
||||
`brain(fib)` deve retornar `1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89`
|
||||
|
||||
```js
|
||||
assert.equal(brain(fib), '1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 598ee8b91b410510ae82efef
|
||||
title: Extensible prime generator
|
||||
title: Gerador de números primos extensível
|
||||
challengeType: 5
|
||||
forumTopicId: 302262
|
||||
dashedName: extensible-prime-generator
|
||||
@ -8,28 +8,28 @@ dashedName: extensible-prime-generator
|
||||
|
||||
# --description--
|
||||
|
||||
Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime.
|
||||
Escreva um gerador de números primos, em ordem, que se ajuste automaticamente para acomodar a geração de qualquer número primo razoavelmente alto.
|
||||
|
||||
The generator should be able to:
|
||||
O gerador deve poder:
|
||||
|
||||
<ul>
|
||||
<li>Show the first <code>n</code> prime numbers</li>
|
||||
<li>Show the prime numbers in a range</li>
|
||||
<li>Show the number of primes in a range</li>
|
||||
<li>Show the <code>n<sup>th</sup></code> prime number</li>
|
||||
<li>Mostrar os <code>n</code> primeiros números primos</li>
|
||||
<li>Mostrar os números primos em um intervalo</li>
|
||||
<li>Mostrar a quantidade de números primos em um intervalo</li>
|
||||
<li>Mostrar o <code>n<sup>th</sup></code> (enésimo) número primo</li>
|
||||
</ul>
|
||||
|
||||
The function should have two parameters. The first will receive `n` or the range as an array. The second will receive a boolean, that specifies if the function returns the prime numbers as an array or a single number(the number of primes in the range or the <code>n<sup>th</sup></code> prime). According to the parameters the function should return an array.
|
||||
A função deve receber dois parâmetros. O primeiro receberá `n` ou o intervalo como um array. O segundo receberá um booleano, que especifica se a função retorna os números primos como um array ou um único número - o número de primos no intervalo ou o <code>n<sup>th</sup></code> (enésimo) primo. De acordo com os parâmetros, a função deve retornar um array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`primeGenerator` should be a function.
|
||||
`primeGenerator` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof primeGenerator === 'function');
|
||||
```
|
||||
|
||||
`primeGenerator(20, true)` should return `[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]`.
|
||||
`primeGenerator(20, true)` deve retornar `[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(primeGenerator(20, true), [
|
||||
@ -56,7 +56,7 @@ assert.deepEqual(primeGenerator(20, true), [
|
||||
]);
|
||||
```
|
||||
|
||||
`primeGenerator([100, 150], true)` should return `[101, 103, 107, 109, 113, 127, 131, 137, 139, 149]`.
|
||||
`primeGenerator([100, 150], true)` deve retornar `[101, 103, 107, 109, 113, 127, 131, 137, 139, 149]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(primeGenerator([100, 150], true), [
|
||||
@ -73,13 +73,13 @@ assert.deepEqual(primeGenerator([100, 150], true), [
|
||||
]);
|
||||
```
|
||||
|
||||
`primeGenerator([7700, 8000], false)` should return `30`.
|
||||
`primeGenerator([7700, 8000], false)` deve retornar `30`.
|
||||
|
||||
```js
|
||||
assert.equal(primeGenerator([7700, 8000], false), 30);
|
||||
```
|
||||
|
||||
`primeGenerator(10000, false)` should return `104729`.
|
||||
`primeGenerator(10000, false)` deve retornar `104729`.
|
||||
|
||||
```js
|
||||
assert.equal(primeGenerator(10000, false), 104729);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 597b2b2a2702b44414742771
|
||||
title: Factorial
|
||||
title: Fatorial
|
||||
challengeType: 5
|
||||
forumTopicId: 302263
|
||||
dashedName: factorial
|
||||
@ -8,49 +8,49 @@ dashedName: factorial
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function to return the factorial of a number.
|
||||
Escreva uma função que retorne o fatorial de um número.
|
||||
|
||||
Factorial of a number is given by:
|
||||
O fatorial de um número é dado por:
|
||||
|
||||
<pre><big>n! = n * (n-1) * (n-2) * ..... * 1</big>
|
||||
</pre>
|
||||
|
||||
For example:
|
||||
Por exemplo:
|
||||
|
||||
<ul>
|
||||
<li><code>3! = 3 * 2 * 1 = 6</code></li>
|
||||
<li><code>4! = 4 * 3 * 2 * 1 = 24</code></li>
|
||||
</ul>
|
||||
|
||||
**Note:** `0! = 1`
|
||||
**Observação:** `0! = 1`
|
||||
|
||||
# --hints--
|
||||
|
||||
`factorial` should be a function.
|
||||
`factorial` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof factorial === 'function');
|
||||
```
|
||||
|
||||
`factorial(2)` should return a number.
|
||||
`factorial(2)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof factorial(2) === 'number');
|
||||
```
|
||||
|
||||
`factorial(3)` should return 6.
|
||||
`factorial(3)` deve retornar 6.
|
||||
|
||||
```js
|
||||
assert.equal(factorial(3), 6);
|
||||
```
|
||||
|
||||
`factorial(5)` should return 120.
|
||||
`factorial(5)` deve retornar 120.
|
||||
|
||||
```js
|
||||
assert.equal(factorial(5), 120);
|
||||
```
|
||||
|
||||
`factorial(10)` should return 3,628,800.
|
||||
`factorial(10)` deve retornar 3,628,800.
|
||||
|
||||
```js
|
||||
assert.equal(factorial(10), 3628800);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 598eea87e5cf4b116c3ff81a
|
||||
title: Factors of a Mersenne number
|
||||
title: Fatores de um número de Mersenne
|
||||
challengeType: 5
|
||||
forumTopicId: 302264
|
||||
dashedName: factors-of-a-mersenne-number
|
||||
@ -8,28 +8,28 @@ dashedName: factors-of-a-mersenne-number
|
||||
|
||||
# --description--
|
||||
|
||||
A Mersenne number is a number in the form of <code>2<sup>P</sup>-1</code>.
|
||||
Um número de Mersenne é um número na forma de <code>2<sup>P</sup>-1</code>.
|
||||
|
||||
If `P` is prime, the Mersenne number may be a Mersenne prime. (If `P` is not prime, the Mersenne number is also not prime.)
|
||||
Se `P` for primo, o número de Mersenne pode ser primo de Mersenne. (Se `P` não for primo, o número de Mersenne também não será primo.)
|
||||
|
||||
In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, [Lucas-Lehmer test](https://rosettacode.org/wiki/Lucas-Lehmer test "Lucas-Lehmer test").
|
||||
Na busca por números primos de Mersenne, é vantajoso eliminar expoentes, encontrando um pequeno fator antes de iniciar um [teste de Lucas-Lehmer](https://rosettacode.org/wiki/Lucas-Lehmer test "Lucas-Lehmer test"), potencialmente extenso.
|
||||
|
||||
There are very efficient algorithms for determining if a number divides <code>2<sup>P</sup>-1</code> (or equivalently, if <code>2<sup>P</sup> mod (the number) = 1</code>).
|
||||
Existem algoritmos muito eficientes para determinar se um número divide <code>2<sup>P</sup>-1</code> (ou, de modo equivalente, se <code>2<sup>P</sup> mod (o número) = 1</code>).
|
||||
|
||||
Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar).
|
||||
Algumas linguagens já possuem implementações integradas desta operação exponente-e-mod (chamada modPow ou algo similar).
|
||||
|
||||
The following is how to implement this modPow yourself:
|
||||
A seguir, vemos como você mesmo pode implementar este modPow:
|
||||
|
||||
For example, let's compute <code>2<sup>23</sup> mod 47</code>.
|
||||
Por exemplo, vamos calcular <code>2<sup>23</sup> mod 47</code>.
|
||||
|
||||
Convert the exponent 23 to binary, you get 10111. Starting with <code><tt>square</tt> = 1</code>, repeatedly square it.
|
||||
Converta o expoente 23 em binário, você obtém 10111. Começando com <code><tt>square</tt> = 1</code>, eleve-o repetidamente ao quadrado.
|
||||
|
||||
Remove the top bit of the exponent, and if it's 1 multiply `square` by the base of the exponentiation (2), then compute <code><tt>square</tt> modulo 47</code>.
|
||||
Remova a parte superior do expoente e, se for 1, multiplique `square` pela base da exponenciação (2). Então, calcule <code><tt>square</tt> modulo 47</code>.
|
||||
|
||||
Use the result of the modulo from the last step as the initial value of `square` in the next step:
|
||||
Use o resultado do módulo da última etapa como o valor inicial de `square` na próxima etapa:
|
||||
|
||||
<pre>Remove Optional
|
||||
square top bit multiply by 2 mod 47
|
||||
<pre>Remova Opcional
|
||||
square pte sup multiplique 2 mod 47
|
||||
------------ ------- ------------- ------
|
||||
1*1 = 1 1 0111 1*2 = 2 2
|
||||
2*2 = 4 0 111 no 4
|
||||
@ -38,51 +38,51 @@ square top bit multiply by 2 mod 47
|
||||
27*27 = 729 1 729*2 = 1458 1
|
||||
</pre>
|
||||
|
||||
Since <code>2<sup>23</sup> mod 47 = 1</code>, 47 is a factor of <code>2<sup>P</sup>-1</code>.
|
||||
Como <code>2<sup>23</sup> mod 47 = 1</code>, 47 é um fator de <code>2<sup>P</sup>-1</code>.
|
||||
|
||||
(To see this, subtract 1 from both sides: <code>2<sup>23</sup>-1 = 0 mod 47</code>.)
|
||||
(Para ver isso, subtraia 1 de ambos os lados: <code>2<sup>23</sup>-1 = 0 mod 47</code>.)
|
||||
|
||||
Since we've shown that 47 is a factor, <code>2<sup>23</sup>-1</code> is not prime.
|
||||
Como mostramos que 47 é um fator, <code>2<sup>23</sup>-1</code> não é primo.
|
||||
|
||||
Further properties of Mersenne numbers allow us to refine the process even more.
|
||||
Outras propriedades dos números de Mersenne nos permitem refinar ainda mais o processo.
|
||||
|
||||
Any factor `q` of <code>2<sup>P</sup>-1</code> must be of the form `2kP+1`, `k` being a positive integer or zero. Furthermore, `q` must be `1` or `7 mod 8`.
|
||||
Qualquer fator `q` de <code>2<sup>P</sup>-1</code> deve ser no formato `2kP+1`, `k`, sendo um inteiro positivo ou zero. Além disso, `q` deve ser `1` ou `7 mod 8`.
|
||||
|
||||
Finally any potential factor `q` must be [prime](https://rosettacode.org/wiki/Primality by Trial Division "Primality by Trial Division").
|
||||
Por fim, qualquer fator potencial `q` deve ser [primo](https://rosettacode.org/wiki/Primality by Trial Division "Primality by Trial Division").
|
||||
|
||||
As in other trial division algorithms, the algorithm stops when `2kP+1 > sqrt(N)`.These primarily tests only work on Mersenne numbers where `P` is prime. For example, <code>M<sub>4</sub>=15</code> yields no factors using these techniques, but factors into 3 and 5, neither of which fit `2kP+1`.
|
||||
Como em outros algoritmos de divisão de teste, o algoritmo termina quando `2kP+1 > sqrt(N)`. Estes testes só funcionam em números de Mersenne, onde o `P` é primo. Por exemplo, <code>M<sub>4</sub>=15</code> não gera fatores usando essas técnicas, mas fator em 3 e 5, nenhum dos quais se ajusta a `2kP+1`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Using the above method find a factor of <code>2<sup>p</sup>-1</code>.
|
||||
Usando o método acima, encontre um fator de <code>2<sup>p</sup>-1</code>.
|
||||
|
||||
# --hints--
|
||||
|
||||
`check_mersenne` should be a function.
|
||||
`check_mersenne` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof check_mersenne === 'function');
|
||||
```
|
||||
|
||||
`check_mersenne(3)` should return a string.
|
||||
`check_mersenne(3)` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(typeof check_mersenne(3) == 'string');
|
||||
```
|
||||
|
||||
`check_mersenne(3)` should return the string `M3 = 2^3-1 is prime`.
|
||||
`check_mersenne(3)` deve retornar a string `M3 = 2^3-1 is prime`.
|
||||
|
||||
```js
|
||||
assert.equal(check_mersenne(3), 'M3 = 2^3-1 is prime');
|
||||
```
|
||||
|
||||
`check_mersenne(23)` should return the string `M23 = 2^23-1 is composite with factor 47`.
|
||||
`check_mersenne(23)` deve retornar a string `M23 = 2^23-1 is composite with factor 47`.
|
||||
|
||||
```js
|
||||
assert.equal(check_mersenne(23), 'M23 = 2^23-1 is composite with factor 47');
|
||||
```
|
||||
|
||||
`check_mersenne(929)` should return the string `M929 = 2^929-1 is composite with factor 13007`.
|
||||
`check_mersenne(929)` deve retornar a string `M929 = 2^929-1 is composite with factor 13007`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 597f1e7fbc206f0e9ba95dc4
|
||||
title: Factors of an integer
|
||||
title: Fatores de um inteiro
|
||||
challengeType: 5
|
||||
forumTopicId: 302265
|
||||
dashedName: factors-of-an-integer
|
||||
@ -8,31 +8,31 @@ dashedName: factors-of-an-integer
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function that returns the factors of a positive integer as an array.
|
||||
Escreva uma função que retorne os fatores de um inteiro positivo como um array.
|
||||
|
||||
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
|
||||
Estes fatores são os inteiros positivos através dos quais o número que está sendo fatorado pode ser dividido para produzir um resultado inteiro e positivo.
|
||||
|
||||
# --hints--
|
||||
|
||||
`factors` should be a function.
|
||||
`factors` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof factors === 'function');
|
||||
```
|
||||
|
||||
`factors(45)` should return `[1,3,5,9,15,45]`.
|
||||
`factors(45)` deve retornar `[1,3,5,9,15,45]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(factors(45), ans[0]);
|
||||
```
|
||||
|
||||
`factors(53)` should return `[1,53]`.
|
||||
`factors(53)` deve retornar `[1,53]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(factors(53), ans[1]);
|
||||
```
|
||||
|
||||
`factors(64)` should return `[1,2,4,8,16,32,64]`.
|
||||
`factors(64)` deve retornar `[1,2,4,8,16,32,64]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(factors(64), ans[2]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 59c3ec9f15068017c96eb8a3
|
||||
title: Farey sequence
|
||||
title: Sequência de Farey
|
||||
challengeType: 5
|
||||
forumTopicId: 302266
|
||||
dashedName: farey-sequence
|
||||
@ -8,18 +8,18 @@ dashedName: farey-sequence
|
||||
|
||||
# --description--
|
||||
|
||||
The [Farey sequence](https://en.wikipedia.org/wiki/Farey sequence "wp: Farey sequence") <code>F<sub>n</sub></code> of order `n` is the sequence of completely reduced fractions between `0` and `1` which, when in lowest terms, have denominators less than or equal to `n`, arranged in order of increasing size.
|
||||
A [sequência de Farey](https://en.wikipedia.org/wiki/Farey sequence "wp: Farey sequence") <code>F<sub>n</sub></code> de ordem `n` é a sequência de frações completamente reduzida entre `0` e `1` que, quando em seus termos menores, tem denominadores menores que ou iguais a `n`, organizadas em ordem de tamanho crescente.
|
||||
|
||||
The *Farey sequence* is sometimes incorrectly called a *Farey series*.
|
||||
A *sequência de Farey*, algumas vezes, é incorretamente chamada de *série de Farey*.
|
||||
|
||||
Each Farey sequence:
|
||||
Cada sequência de Farey:
|
||||
|
||||
<ul>
|
||||
<li>starts with the value 0, denoted by the fraction $ \frac{0}{1} $</li>
|
||||
<li>ends with the value 1, denoted by the fraction $ \frac{1}{1}$.</li>
|
||||
<li>começa com o valor 0, denotado pela fração $ \frac{0}{1} $</li>
|
||||
<li>termina com o valor 1, denotado pela fração $ \frac{1}{1}$.</li>
|
||||
</ul>
|
||||
|
||||
The Farey sequences of orders `1` to `5` are:
|
||||
As sequências de Farey de ordens `1` a `5` são:
|
||||
|
||||
<ul>
|
||||
<li style='list-style: none;'>${\bf\it{F}}_1 = \frac{0}{1}, \frac{1}{1}$</li>
|
||||
@ -31,35 +31,35 @@ The Farey sequences of orders `1` to `5` are:
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that returns the Farey sequence of order `n`. The function should have one parameter that is `n`. It should return the sequence as an array.
|
||||
Escreva uma função que retorne a sequência de Farey de ordem `n`. A função deve ter um parâmetro que é `n`. Ela deve retornar a sequência como um array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`farey` should be a function.
|
||||
`farey` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof farey === 'function');
|
||||
```
|
||||
|
||||
`farey(3)` should return an array
|
||||
`farey(3)` deve retornar um array
|
||||
|
||||
```js
|
||||
assert(Array.isArray(farey(3)));
|
||||
```
|
||||
|
||||
`farey(3)` should return `["1/3","1/2","2/3"]`
|
||||
`farey(3)` deve retornar `["1/3","1/2","2/3"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(farey(3), ['1/3', '1/2', '2/3']);
|
||||
```
|
||||
|
||||
`farey(4)` should return `["1/4","1/3","1/2","2/4","2/3","3/4"]`
|
||||
`farey(4)` deve retornar `["1/4","1/3","1/2","2/4","2/3","3/4"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(farey(4), ['1/4', '1/3', '1/2', '2/4', '2/3', '3/4']);
|
||||
```
|
||||
|
||||
`farey(5)` should return `["1/5","1/4","1/3","2/5","1/2","2/4","3/5","2/3","3/4","4/5"]`
|
||||
`farey(5)` deve retornar `["1/5","1/4","1/3","2/5","1/2","2/4","3/5","2/3","3/4","4/5"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(farey(5), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 598eef80ba501f1268170e1e
|
||||
title: Fibonacci n-step number sequences
|
||||
title: Sequências de números de n passos de Fibonacci
|
||||
challengeType: 5
|
||||
forumTopicId: 302267
|
||||
dashedName: fibonacci-n-step-number-sequences
|
||||
@ -8,82 +8,82 @@ dashedName: fibonacci-n-step-number-sequences
|
||||
|
||||
# --description--
|
||||
|
||||
These number series are an expansion of the ordinary [Fibonacci sequence](https://rosettacode.org/wiki/Fibonacci sequence "Fibonacci sequence") where:
|
||||
Essas séries numéricas são uma expansão da [Sequência de Fibonacci](https://rosettacode.org/wiki/Fibonacci sequence "Fibonacci sequence") comum, onde:
|
||||
|
||||
<ol>
|
||||
<li>For $n = 2$ we have the Fibonacci sequence; with initial values $[1, 1]$ and $F_k^2 = F_{k-1}^2 + F_{k-2}^2$</li>
|
||||
<li>For $n = 3$ we have the tribonacci sequence; with initial values $[1, 1, 2]$ and $F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3$</li>
|
||||
<li>For $n = 4$ we have the tetranacci sequence; with initial values $[1, 1, 2, 4]$ and $F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4$...</li>
|
||||
<li>For general $n>2$ we have the Fibonacci $n$-step sequence - $F_k^n$; with initial values of the first $n$ values of the $(n-1)$'th Fibonacci $n$-step sequence $F_k^{n-1}$; and $k$'th value of this $n$'th sequence being $F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}}$</li>
|
||||
<li>Para $n = 2$, temos a sequência de Fibonacci, com os valores iniciais $[1, 1]$ e $F_k^2 = F_{k-1}^2 + F_{k-2}^2$</li>
|
||||
<li>Para $n = 3$, temos a sequência de tribonacci, com os valores iniciais $[1, 1, 2]$ e $F_k^3 = F_{k-1}^3 + F_{k-2}^3 + F_{k-3}^3$</li>
|
||||
<li>Para $n = 4$, temos a sequência de tetranacci, com os valores iniciais $[1, 1, 2, 4]$ e $F_k^4 = F_{k-1}^4 + F_{k-2}^4 + F_{k-3}^4 + F_{k-4}^4$...</li>
|
||||
<li>Para a $n>2$ mais geral, temos a sequência de Fibonacci de $n$ passos - $F_k^n$, com os valores iniciais dos primeiros $n$ valores da $(n-1)$-ésima sequência de Fibonacci da $n$-ésima etapa $F_k^{n-1}$, e o $k$-ésimo valor dessa $n$-ésima sequência sendo $F_k^n = \sum_{i=1}^{(n)} {F_{k-i}^{(n)}}$</li>
|
||||
</ol>
|
||||
|
||||
For small values of $n$, [Greek numeric prefixes](https://en.wikipedia.org/wiki/Number prefix#Greek_series "wp: Number prefix#Greek_series") are sometimes used to individually name each series.
|
||||
Para valores pequenos de $n$, [prefixos numéricos gregos](https://en.wikipedia.org/wiki/Number prefix#Greek_series "wp: Number prefix#Greek_series") são algumas vezes usados para nomear cada série individualmente.
|
||||
|
||||
Fibonacci $n$-step sequences:
|
||||
Sequências de $n$-ésimos passos de Fibonacci:
|
||||
|
||||
| $n$ | Series name | Values |
|
||||
| --- | ----------- | ------------------------------------------------------ |
|
||||
| 2 | fibonacci | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... |
|
||||
| 3 | tribonacci | 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... |
|
||||
| 4 | tetranacci | 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... |
|
||||
| 5 | pentanacci | 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... |
|
||||
| 6 | hexanacci | 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... |
|
||||
| 7 | heptanacci | 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... |
|
||||
| 8 | octonacci | 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... |
|
||||
| 9 | nonanacci | 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... |
|
||||
| 10 | decanacci | 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... |
|
||||
| $n$ | Nome da série | Valores |
|
||||
| --- | ------------- | ------------------------------------------------------ |
|
||||
| 2 | fibonacci | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ... |
|
||||
| 3 | tribonacci | 1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ... |
|
||||
| 4 | tetranacci | 1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ... |
|
||||
| 5 | pentanacci | 1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ... |
|
||||
| 6 | hexanacci | 1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ... |
|
||||
| 7 | heptanacci | 1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ... |
|
||||
| 8 | octonacci | 1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ... |
|
||||
| 9 | nonanacci | 1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ... |
|
||||
| 10 | decanacci | 1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ... |
|
||||
|
||||
Allied sequences can be generated where the initial values are changed: The [Lucas series](https://en.wikipedia.org/wiki/Lucas number "wp: Lucas number") sums the two preceding values like the fibonacci series for $n=2$ but uses $\[2, 1]$ as its initial values.
|
||||
As sequências aliadas podem ser geradas onde os valores iniciais são alterados: A [série de Lucas](https://en.wikipedia.org/wiki/Lucas number "wp: Lucas number") soma os dois valores anteriores, como a série de fibonacci para $n=2$, mas usa $\[2, 1]$ como seus valores iniciais.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function to generate Fibonacci $n$-step number sequences and Lucas sequences. The first parameter will be $n$. The second parameter will be the number of elements to be returned. The third parameter will specify whether to output the Fibonacci sequence or the Lucas sequence. If the parameter is `"f"` then return the Fibonacci sequence and if it is `"l"`, then return the Lucas sequence. The sequences must be returned as an array.
|
||||
Escreva uma função para gerar sequências numéricas de $n$ passos de Fibonacci e sequências de Lucas. O primeiro parâmetro será $n$. O segundo parâmetro será o número de elementos a serem retornados. O terceiro parâmetro especificará se será exibida a sequência de Fibonacci ou a sequência de Lucas. Se o parâmetro for `"f"`, retorne a sequência de Fibonacci. Se for `"l"`, retorne a sequência de Lucas. As sequências devem ser retornadas como um array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`fib_luc` should be a function.
|
||||
`fib_luc` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof fib_luc === 'function');
|
||||
```
|
||||
|
||||
`fib_luc(2,10,"f")` should return `[1,1,2,3,5,8,13,21,34,55]`.
|
||||
`fib_luc(2,10,"f")` deve retornar `[1,1,2,3,5,8,13,21,34,55]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fib_luc(2, 10, 'f'), ans[0]);
|
||||
```
|
||||
|
||||
`fib_luc(3,15,"f")` should return `[1,1,2,4,7,13,24,44,81,149,274,504,927,1705,3136]`.
|
||||
`fib_luc(3,15,"f")` deve retornar `[1,1,2,4,7,13,24,44,81,149,274,504,927,1705,3136]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fib_luc(3, 15, 'f'), ans[1]);
|
||||
```
|
||||
|
||||
`fib_luc(4,15,"f")` should return `[1,1,2,4,8,15,29,56,108,208,401,773,1490,2872,5536]`.
|
||||
`fib_luc(4,15,"f")` deve retornar `[1,1,2,4,8,15,29,56,108,208,401,773,1490,2872,5536]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fib_luc(4, 15, 'f'), ans[2]);
|
||||
```
|
||||
|
||||
`fib_luc(2,10,"l")` should return `[ 2, 1, 3, 4, 7, 11, 18, 29, 47, 76]`.
|
||||
`fib_luc(2,10,"l")` deve retornar `[ 2, 1, 3, 4, 7, 11, 18, 29, 47, 76]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fib_luc(2, 10, 'l'), ans[3]);
|
||||
```
|
||||
|
||||
`fib_luc(3,15,"l")` should return `[ 2, 1, 3, 6, 10, 19, 35, 64, 118, 217, 399, 734, 1350, 2483, 4567 ]`.
|
||||
`fib_luc(3,15,"l")` deve retornar `[ 2, 1, 3, 6, 10, 19, 35, 64, 118, 217, 399, 734, 1350, 2483, 4567 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fib_luc(3, 15, 'l'), ans[4]);
|
||||
```
|
||||
|
||||
`fib_luc(4,15,"l")` should return `[ 2, 1, 3, 6, 12, 22, 43, 83, 160, 308, 594, 1145, 2207, 4254, 8200 ]`.
|
||||
`fib_luc(4,15,"l")` deve retornar `[ 2, 1, 3, 6, 12, 22, 43, 83, 160, 308, 594, 1145, 2207, 4254, 8200 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fib_luc(4, 15, 'l'), ans[5]);
|
||||
```
|
||||
|
||||
`fib_luc(5,15,"l")` should return `[ 2, 1, 3, 6, 12, 24, 46, 91, 179, 352, 692, 1360, 2674, 5257, 10335 ]`.
|
||||
`fib_luc(5,15,"l")` deve retornar `[ 2, 1, 3, 6, 12, 24, 46, 91, 179, 352, 692, 1360, 2674, 5257, 10335 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fib_luc(5, 15, 'l'), ans[6]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 597f24c1dda4e70f53c79c81
|
||||
title: Fibonacci sequence
|
||||
title: Sequência de Fibonacci
|
||||
challengeType: 5
|
||||
forumTopicId: 302268
|
||||
dashedName: fibonacci-sequence
|
||||
@ -8,43 +8,43 @@ dashedName: fibonacci-sequence
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function to generate the <code>n<sup>th</sup></code> Fibonacci number.
|
||||
Escreva uma função para gerar o <code>n<sup>th</sup></code> (enésimo) número de Fibonacci.
|
||||
|
||||
The <code>n<sup>th</sup></code> Fibonacci number is given by:
|
||||
O <code>n<sup>th</sup></code> (enésimo) número de Fibonacci é dado por:
|
||||
|
||||
<code>F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub></code>
|
||||
|
||||
The first two terms of the series are 0 and 1.
|
||||
Os dois primeiros termos da série são 0 e 1.
|
||||
|
||||
Hence, the series is: 0, 1, 1, 2, 3, 5, 8, 13...
|
||||
Portanto, a série é: 0, 1, 1, 2, 3, 5, 8, 13...
|
||||
|
||||
# --hints--
|
||||
|
||||
`fibonacci` should be a function.
|
||||
`fibonacci` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof fibonacci === 'function');
|
||||
```
|
||||
|
||||
`fibonacci(2)` should return a number.
|
||||
`fibonacci(2)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof fibonacci(2) == 'number');
|
||||
```
|
||||
|
||||
`fibonacci(3)` should return 2.
|
||||
`fibonacci(3)` deve retornar 2.
|
||||
|
||||
```js
|
||||
assert.equal(fibonacci(3), 2);
|
||||
```
|
||||
|
||||
`fibonacci(5)` should return 5.
|
||||
`fibonacci(5)` deve retornar 5.
|
||||
|
||||
```js
|
||||
assert.equal(fibonacci(5), 5);
|
||||
```
|
||||
|
||||
`fibonacci(10)` should return 55.
|
||||
`fibonacci(10)` deve retornar 55.
|
||||
|
||||
```js
|
||||
assert.equal(fibonacci(10), 55);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5992e222d397f00d21122931
|
||||
title: Fibonacci word
|
||||
title: Palavra de Fibonacci
|
||||
challengeType: 5
|
||||
forumTopicId: 302269
|
||||
dashedName: fibonacci-word
|
||||
@ -8,33 +8,33 @@ dashedName: fibonacci-word
|
||||
|
||||
# --description--
|
||||
|
||||
The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence [as described here](https://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf):
|
||||
A palavra de Fibonacci pode ser criada de forma análoga à Sequência de Fibonacci, [conforme descrito aqui](https://hal.archives-ouvertes.fr/docs/00/36/79/72/PDF/The_Fibonacci_word_fractal.pdf):
|
||||
|
||||
<pre>Define F_Word<sub>1</sub> as <strong>1</strong>
|
||||
Define F_Word<sub>2</sub> as <strong>0</strong>
|
||||
Form F_Word<sub>3</sub> as F_Word<sub>2</sub> concatenated with F_Word<sub>1</sub> i.e.: <strong>01</strong>
|
||||
Form F_Word<sub>n</sub> as F_Word<sub>n-1</sub> concatenated with F_word<sub>n-2</sub>
|
||||
<pre>Defina a F_Word<sub>1</sub> como <strong>1</strong>
|
||||
Defina a F_Word<sub>2</sub> como <strong>0</strong>
|
||||
Forme a F_Word<sub>3</sub> como F_Word<sub>2</sub> concatenada com a F_Word <sub>1</sub>, ou seja: <strong>01</strong>
|
||||
Forme a F_Word<sub>n</sub> como F_Word<sub>n-1</sub> concatenada com a F_word <sub>n-2</sub>
|
||||
</pre>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function to return the Fibonacci Words up to `n`. `n` will be provided as a parameter to the function. The function should return an array of objects. The objects should be of the form: `{ N: 1, Length: 1, Entropy: 0, Word: '1' }`.
|
||||
Escreva uma função para retornar as palavras de Fibonacci até `n`. `n` será fornecido como um parâmetro para a função. A função deve retornar um array de objetos. Os objetos devem estar na forma: `{ N: 1, Length: 1, Entropy: 0, Word: '1' }` (tamanho, entropia e palavra).
|
||||
|
||||
# --hints--
|
||||
|
||||
`fibWord` should be a function.
|
||||
`fibWord` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof fibWord === 'function');
|
||||
```
|
||||
|
||||
`fibWord(5)` should return an array.
|
||||
`fibWord(5)` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(fibWord(5)));
|
||||
```
|
||||
|
||||
`fibWord(5)` should return `[{ N:1, Length:1, Entropy:0, Word:"1" },{ N:2, Length:1, Entropy:0, Word:"0" },{ N:3, Length:2, Entropy:1, Word:"01" },{ N:4, Length:3, Entropy:0.9182958340544896, Word:"010" },{ N:5, Length:5, Entropy:0.9709505944546688, Word:"01001" }]`.
|
||||
`fibWord(5)` deve retornar `[{ N:1, Length:1, Entropy:0, Word:"1" },{ N:2, Length:1, Entropy:0, Word:"0" },{ N:3, Length:2, Entropy:1, Word:"01" },{ N:4, Length:3, Entropy:0.9182958340544896, Word:"010" },{ N:5, Length:5, Entropy:0.9709505944546688, Word:"01001" }]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fibWord(5), ans);
|
||||
|
@ -8,51 +8,51 @@ dashedName: fizzbuzz
|
||||
|
||||
# --description--
|
||||
|
||||
Write a program that generates an array of integers from 1 to 100 (inclusive). But:
|
||||
Escreva um programa que gere um array de números inteiros de 1 a 100 (inclusive). Mas:
|
||||
|
||||
<ul>
|
||||
<li>for multiples of 3, add <code>"Fizz"</code> to the array instead of the number</li>
|
||||
<li>for multiples of 5, add <code>"Buzz"</code> to the array instead of the number</li>
|
||||
<li>for multiples of 3 and 5, add <code>"FizzBuzz"</code> to the array instead of the number</li>
|
||||
<li>para múltiplos de 3, adicione <code>"Fizz"</code> no array no lugar do número</li>
|
||||
<li>para múltiplos de 5, adicione <code>"Buzz"</code> no array no lugar do número</li>
|
||||
<li>para múltiplos de 3 e 5, adicione <code>"FizzBuzz"</code> no array no lugar do número</li>
|
||||
</ul>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Your program should return an array containing the results based on the rules above.
|
||||
O programa deve retornar um array contendo os resultados com base nas regras acima.
|
||||
|
||||
# --hints--
|
||||
|
||||
`fizzBuzz` should be a function.
|
||||
`fizzBuzz` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof fizzBuzz == 'function');
|
||||
```
|
||||
|
||||
`fizzBuzz()` should return an Array.
|
||||
`fizzBuzz()` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(fizzBuzz()) == true);
|
||||
```
|
||||
|
||||
Numbers divisible by only 3 should return `"Fizz"`.
|
||||
Números divisíveis apenas por 3 devem retornar `"Fizz"`.
|
||||
|
||||
```js
|
||||
assert.equal(fizzBuzz()[2], 'Fizz');
|
||||
```
|
||||
|
||||
Numbers divisible by only 5 should return `"Buzz"`.
|
||||
Números divisíveis apenas por 5 devem retornar `"Buzz"`.
|
||||
|
||||
```js
|
||||
assert.equal(fizzBuzz()[99], 'Buzz');
|
||||
```
|
||||
|
||||
Numbers divisible by both 3 and 5 should return `"FizzBuzz"`.
|
||||
Números divisíveis por 3 e por 5 devem retornar `"FizzBuzz"`.
|
||||
|
||||
```js
|
||||
assert.equal(fizzBuzz()[89], 'FizzBuzz');
|
||||
```
|
||||
|
||||
Numbers not divisible by either 3 or 5 should return the number itself.
|
||||
Números não divisíveis por 3 nem 5 devem retornar o próprio número.
|
||||
|
||||
```js
|
||||
assert.equal(fizzBuzz()[12], 13);
|
||||
|
@ -8,74 +8,74 @@ dashedName: fractran
|
||||
|
||||
# --description--
|
||||
|
||||
[FRACTRAN](https://en.wikipedia.org/wiki/FRACTRAN "wp: FRACTRAN") is a Turing-complete esoteric programming language invented by the mathematician [John Horton Conway](https://en.wikipedia.org/wiki/John Horton Conway "wp: John Horton Conway").
|
||||
[FRACTRAN](https://en.wikipedia.org/wiki/FRACTRAN "wp: FRACTRAN") é uma linguagem de programação esotérica completa de Turing inventada pelo matemático [John Horton Conway](https://en.wikipedia.org/wiki/John Horton Conway "wp: John Horton Conway").
|
||||
|
||||
A FRACTRAN program is an ordered list of positive fractions $P = (f_1, f_2, \\ldots, f_m)$, together with an initial positive integer input $n$.
|
||||
Um programa em FRACTRAN é uma lista ordenada de frações positivas $P = (f_1, f_2, \\ldots, f_m)$, juntamente com uma primeira entrada positiva inteira $n$.
|
||||
|
||||
The program is run by updating the integer $n$ as follows:
|
||||
O programa é executado atualizando o inteiro $n$ da seguinte forma:
|
||||
|
||||
<ul>
|
||||
<li>for the first fraction, $f_i$, in the list for which $nf_i$ is an integer, replace $n$ with $nf_i$ ;</li>
|
||||
<li>repeat this rule until no fraction in the list produces an integer when multiplied by $n$, then halt.</li>
|
||||
<li>para a primeira fração, $f_i$, na lista para a qual $nf_i$ é um número inteiro, substitua $n$ por $nf_i$;</li>
|
||||
<li>repita essa regra até que nenhuma fração na lista produza um inteiro quando multiplicado por $n$, e então pare.</li>
|
||||
</ul>
|
||||
|
||||
Conway gave a program for primes in FRACTRAN:
|
||||
Conway forneceu um programa para números primos em FRACTRAN:
|
||||
|
||||
$\\dfrac{17}{91}$, $\\dfrac{78}{85}$, $\\dfrac{19}{51}$, $\\dfrac{23}{38}$, $\\dfrac{29}{33}$, $\\dfrac{77}{29}$, $\\dfrac{95}{23}$, $\\dfrac{77}{19}$, $\\dfrac{1}{17}$, $\\dfrac{11}{13}$, $\\dfrac{13}{11}$, $\\dfrac{15}{14}$, $\\dfrac{15}{2}$, $\\dfrac{55}{1}$
|
||||
|
||||
Starting with $n=2$, this FRACTRAN program will change $n$ to $15=2\\times (\\frac{15}{2})$, then $825=15\\times (\\frac{55}{1})$, generating the following sequence of integers:
|
||||
Começando com $n=2$, este programa em FRACTRAN mudará $n$ para $15=2\\vezes (\\frac{15}{2})$, então $825=15\\vezes (\\frac{55}{1})$, gerando a seguinte sequência de inteiros:
|
||||
|
||||
$2$, $15$, $825$, $725$, $1925$, $2275$, $425$, $390$, $330$, $290$, $770$, $\\ldots$
|
||||
|
||||
After 2, this sequence contains the following powers of 2:
|
||||
Depois do 2, esta sequência contém as seguintes potências de 2:
|
||||
|
||||
$2^2=4$, $2^3=8$, $2^5=32$, $2^7=128$, $2^{11}=2048$, $2^{13}=8192$, $2^{17}=131072$, $2^{19}=524288$, $\\ldots$
|
||||
|
||||
which are the prime powers of 2.
|
||||
que são as principais potências primas de 2.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes a fractran program as a string parameter and returns the first 10 numbers of the program as an array. If the result does not have 10 numbers then return the numbers as is.
|
||||
Escreva uma função que recebe um programa em fractran como um parâmetro de string e retorna os primeiros 10 números do programa como um array. Se o resultado não tiver 10 números, então retorne os números como estão.
|
||||
|
||||
# --hints--
|
||||
|
||||
`fractran` should be a function.
|
||||
`fractran` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof fractran == 'function');
|
||||
```
|
||||
|
||||
`fractran("3/2, 1/3")` should return an array.
|
||||
`fractran("3/2, 1/3")` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(fractran('3/2, 1/3')));
|
||||
```
|
||||
|
||||
`fractran("3/2, 1/3")` should return `[ 2, 3, 1 ]`.
|
||||
`fractran("3/2, 1/3")` deve retornar `[ 2, 3, 1 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fractran('3/2, 1/3'), [2, 3, 1]);
|
||||
```
|
||||
|
||||
`fractran("3/2, 5/3, 1/5")` should return `[ 2, 3, 5, 1 ]`.
|
||||
`fractran("3/2, 5/3, 1/5")` deve retornar `[ 2, 3, 5, 1 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fractran('3/2, 5/3, 1/5'), [2, 3, 5, 1]);
|
||||
```
|
||||
|
||||
`fractran("3/2, 6/3")` should return `[ 2, 3, 6, 9, 18, 27, 54, 81, 162, 243 ]`.
|
||||
`fractran("3/2, 6/3")` deve retornar `[ 2, 3, 6, 9, 18, 27, 54, 81, 162, 243 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fractran('3/2, 6/3'), [2, 3, 6, 9, 18, 27, 54, 81, 162, 243]);
|
||||
```
|
||||
|
||||
`fractran("2/7, 7/2")` should return `[ 2, 7, 2, 7, 2, 7, 2, 7, 2, 7 ]`.
|
||||
`fractran("2/7, 7/2")` deve retornar `[ 2, 7, 2, 7, 2, 7, 2, 7, 2, 7 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(fractran('2/7, 7/2'), [2, 7, 2, 7, 2, 7, 2, 7, 2, 7]);
|
||||
```
|
||||
|
||||
`fractran("17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1")` should return `[ 2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290 ]`.
|
||||
`fractran("17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1")` deve retornar `[ 2, 15, 825, 725, 1925, 2275, 425, 390, 330, 290 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7e76
|
||||
title: Gamma function
|
||||
title: Função gama
|
||||
challengeType: 5
|
||||
forumTopicId: 302271
|
||||
dashedName: gamma-function
|
||||
@ -8,51 +8,51 @@ dashedName: gamma-function
|
||||
|
||||
# --description--
|
||||
|
||||
Implement one algorithm (or more) to compute the [Gamma](https://en.wikipedia.org/wiki/Gamma function) ($\\Gamma$) function (in the real field only).
|
||||
Implemente um algoritmo (ou mais) para calcular a função [Gama](https://en.wikipedia.org/wiki/Gamma function) ($\\Gamma$) (apenas no campo dos reais).
|
||||
|
||||
The Gamma function can be defined as:
|
||||
A função Gama pode ser definida como:
|
||||
|
||||
<div style='padding-left: 4em;'><big><big>$\Gamma(x) = \displaystyle\int_0^\infty t^{x-1}e^{-t} dt$</big></big></div>
|
||||
|
||||
# --hints--
|
||||
|
||||
`gamma` should be a function.
|
||||
`gamma` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof gamma == 'function');
|
||||
```
|
||||
|
||||
`gamma(.1)` should return a number.
|
||||
`gamma(.1)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof gamma(0.1) == 'number');
|
||||
```
|
||||
|
||||
`gamma(.1)` should return `9.513507698668736`.
|
||||
`gamma(.1)` deve retornar `9.513507698668736`.
|
||||
|
||||
```js
|
||||
assert.equal(round(gamma(0.1)), round(9.513507698668736));
|
||||
```
|
||||
|
||||
`gamma(.2)` should return `4.590843711998803`.
|
||||
`gamma(.2)` deve retornar `4.590843711998803`.
|
||||
|
||||
```js
|
||||
assert.equal(round(gamma(0.2)), round(4.590843711998803));
|
||||
```
|
||||
|
||||
`gamma(.3)` should return `2.9915689876875904`.
|
||||
`gamma(.3)` deve retornar `2.9915689876875904`.
|
||||
|
||||
```js
|
||||
assert.equal(round(gamma(0.3)), round(2.9915689876875904));
|
||||
```
|
||||
|
||||
`gamma(.4)` should return `2.218159543757687`.
|
||||
`gamma(.4)` deve retornar `2.218159543757687`.
|
||||
|
||||
```js
|
||||
assert.equal(round(gamma(0.4)), round(2.218159543757687));
|
||||
```
|
||||
|
||||
`gamma(.5)` should return `1.7724538509055159`.
|
||||
`gamma(.5)` deve retornar `1.7724538509055159`.
|
||||
|
||||
```js
|
||||
assert.equal(round(gamma(0.5)), round(1.7724538509055159));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7e77
|
||||
title: Gaussian elimination
|
||||
title: Eliminação gaussiana
|
||||
challengeType: 5
|
||||
forumTopicId: 302272
|
||||
dashedName: gaussian-elimination
|
||||
@ -8,21 +8,21 @@ dashedName: gaussian-elimination
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function to solve \\(Ax = b\\) using Gaussian elimination then backwards substitution.
|
||||
Escreva uma função para calcular \\(Ax = b\\) usando a eliminação gaussiana e, em seguida, a substituição reversa.
|
||||
|
||||
\\(A\\) being an \\(n \\times n\\) matrix. Also, \\(x\\) and \\(b\\) are \\(n\\) by 1 vectors.
|
||||
\\(A\\) sendo uma matriz \\(n \\vezes n\\). Além disso, \\(x\\) e \\(b\\) são vetores \\(n\\) por 1.
|
||||
|
||||
To improve accuracy, please use partial pivoting and scaling.
|
||||
Para melhorar a precisão, use pivô parcial e escala.
|
||||
|
||||
# --hints--
|
||||
|
||||
`gaussianElimination` should be a function.
|
||||
`gaussianElimination` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof gaussianElimination == 'function');
|
||||
```
|
||||
|
||||
`gaussianElimination([[1,1],[1,-1]], [5,1])` should return an array.
|
||||
`gaussianElimination([[1,1],[1,-1]], [5,1])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -38,7 +38,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`gaussianElimination([[1,1],[1,-1]], [5,1])` should return `[ 3, 2 ]`.
|
||||
`gaussianElimination([[1,1],[1,-1]], [5,1])` deve retornar `[ 3, 2 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -53,7 +53,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`gaussianElimination([[2,3],[2,1]] , [8,4])` should return `[ 1, 2 ]`.
|
||||
`gaussianElimination([[2,3],[2,1]] , [8,4])` deve retornar `[ 1, 2 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -68,7 +68,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`gaussianElimination([[1,3],[5,-2]], [14,19])` should return `[ 5, 3 ]`.
|
||||
`gaussianElimination([[1,3],[5,-2]], [14,19])` deve retornar `[ 5, 3 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -83,7 +83,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`gaussianElimination([[1,1],[5,-1]] , [10,14])` should return `[ 4, 6 ]`.
|
||||
`gaussianElimination([[1,1],[5,-1]] , [10,14])` deve retornar `[ 4, 6 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -98,7 +98,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`gaussianElimination([[1,2,3],[4,5,6],[7,8,8]] , [6,15,23])` should return `[ 1, 1, 1 ]`.
|
||||
`gaussianElimination([[1,2,3],[4,5,6],[7,8,8]] , [6,15,23])` deve retornar `[ 1, 1, 1 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7e78
|
||||
title: General FizzBuzz
|
||||
title: FizzBuzz geral
|
||||
challengeType: 5
|
||||
forumTopicId: 302273
|
||||
dashedName: general-fizzbuzz
|
||||
@ -8,25 +8,25 @@ dashedName: general-fizzbuzz
|
||||
|
||||
# --description--
|
||||
|
||||
Write a generalized version of [FizzBuzz](https://rosettacode.org/wiki/FizzBuzz) that works for any list of factors, along with their words.
|
||||
Escreva uma versão generalizada do algoritmo [FizzBuzz](https://rosettacode.org/wiki/FizzBuzz), que funcione para qualquer lista de fatores, juntamente com suas palavras.
|
||||
|
||||
This is basically a "fizzbuzz" implementation where the rules of the game are supplied to the user. Create a function to implement this. The function should take two parameters.
|
||||
Esta é basicamente uma implementação de "fizzbuzz" onde as regras do jogo são fornecidas ao utilizador. Crie uma função para implementar isso. A função deve receber dois parâmetros.
|
||||
|
||||
The first will be an array with the FizzBuzz rules. For example: `[ [3, "Fizz"] , [5, "Buzz"] ]`.
|
||||
O primeiro será um array com as regras para FizzBuzz. Por exemplo: `[ [3, "Fizz"] , [5, "Buzz"] ]`.
|
||||
|
||||
This indicates that `Fizz` should be printed if the number is a multiple of 3 and `Buzz` if it is a multiple of 5. If it is a multiple of both then the strings should be concatenated in the order specified in the array. In this case, `FizzBuzz` if the number is a multiple of 3 and 5.
|
||||
Isso indica que `Fizz` deve ser impresso se o número for múltiplo de 3 e `Buzz` deve ser impresso se for múltiplo de 5. Se for um múltiplo de ambos, as strings devem ser concatenadas na ordem especificada no array. Neste caso, `FizzBuzz` se o número for um múltiplo de 3 e 5.
|
||||
|
||||
The second parameter is the number for which the function should return a string as stated above.
|
||||
O segundo parâmetro é o número para o qual a função deve retornar uma string, conforme indicado acima.
|
||||
|
||||
# --hints--
|
||||
|
||||
`genFizzBuzz` should be a function.
|
||||
`genFizzBuzz` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof genFizzBuzz == 'function');
|
||||
```
|
||||
|
||||
`genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 6)` should return a string.
|
||||
`genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 6)` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -40,7 +40,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 6)` should return `"Fizz"`.
|
||||
`genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 6)` deve retornar `"Fizz"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -55,7 +55,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 10)` should return `"Buzz"`.
|
||||
`genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 10)` deve retornar `"Buzz"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -70,7 +70,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 12)` should return `"Buzz"`.
|
||||
`genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 12)` deve retornar `"Buzz"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -85,7 +85,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 13)` should return `"13"`.
|
||||
`genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 13)` deve retornar `"13"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -100,7 +100,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 15)` should return `"BuzzFizz"`.
|
||||
`genFizzBuzz([[3, "Buzz"],[5, "Fizz"]], 15)` deve retornar `"BuzzFizz"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -115,7 +115,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 15)` should return `"FizzBuzz"`.
|
||||
`genFizzBuzz([[3, "Fizz"],[5, "Buzz"]], 15)` deve retornar `"FizzBuzz"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -130,7 +130,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`genFizzBuzz([[3, "Fizz"],[5, "Buzz"],[7, "Baxx"]], 105)` should return `"FizzBuzzBaxx"`.
|
||||
`genFizzBuzz([[3, "Fizz"],[5, "Buzz"],[7, "Baxx"]], 105)` deve retornar `"FizzBuzzBaxx"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7e7a
|
||||
title: Generate lower case ASCII alphabet
|
||||
title: Gerar alfabeto ASCII em letras minúsculas
|
||||
challengeType: 5
|
||||
forumTopicId: 302274
|
||||
dashedName: generate-lower-case-ascii-alphabet
|
||||
@ -8,47 +8,47 @@ dashedName: generate-lower-case-ascii-alphabet
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function to generate an array of lower case ASCII characters for a given range. For example, given the range `['a', 'd']`, the function should return `['a', 'b', 'c', 'd']`.
|
||||
Escreva uma função para gerar um array de caracteres ASCII em letras minúsculas para um determinado intervalo. Por exemplo, dado o intervalo `['a', 'd']`, a função deve retornar `['a', 'b', 'c', 'd']`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`lascii` should be a function.
|
||||
`lascii` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof lascii == 'function');
|
||||
```
|
||||
|
||||
`lascii("a","d")` should return an array.
|
||||
`lascii("a","d")` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(lascii('a', 'd')));
|
||||
```
|
||||
|
||||
`lascii('a','d')` should return `[ 'a', 'b', 'c', 'd' ]`.
|
||||
`lascii('a','d')` deve retornar `[ 'a', 'b', 'c', 'd' ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(lascii('a', 'd'), results[0]);
|
||||
```
|
||||
|
||||
`lascii('c','i')` should return `[ 'c', 'd', 'e', 'f', 'g', 'h', 'i' ]`.
|
||||
`lascii('c','i')` deve retornar `[ 'c', 'd', 'e', 'f', 'g', 'h', 'i' ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(lascii('c', 'i'), results[1]);
|
||||
```
|
||||
|
||||
`lascii('m','q')` should return `[ 'm', 'n', 'o', 'p', 'q' ]`.
|
||||
`lascii('m','q')` deve retornar `[ 'm', 'n', 'o', 'p', 'q' ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(lascii('m', 'q'), results[2]);
|
||||
```
|
||||
|
||||
`lascii('k','n')` should return `[ 'k', 'l', 'm', 'n' ]`.
|
||||
`lascii('k','n')` deve retornar `[ 'k', 'l', 'm', 'n' ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(lascii('k', 'n'), results[3]);
|
||||
```
|
||||
|
||||
`lascii('t','z')` should return `[ 't', 'u', 'v', 'w', 'x', 'y', 'z' ]`.
|
||||
`lascii('t','z')` deve retornar `[ 't', 'u', 'v', 'w', 'x', 'y', 'z' ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(lascii('t', 'z'), results[4]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7e7b
|
||||
title: Generator/Exponential
|
||||
title: Gerador/exponencial
|
||||
challengeType: 5
|
||||
forumTopicId: 302275
|
||||
dashedName: generatorexponential
|
||||
@ -8,59 +8,59 @@ dashedName: generatorexponential
|
||||
|
||||
# --description--
|
||||
|
||||
A generator is an executable entity (like a function or procedure) that contains code that yields a sequence of values, one at a time, so that each time you call the generator, the next value in the sequence is provided.
|
||||
Um gerador é uma entidade executável (como uma função ou procedimento) que contém um código que retorna uma sequência de valores, um de cada vez, para que a cada vez que você chame o gerador, o próximo valor na sequência seja fornecido.
|
||||
|
||||
Generators are often built on top of coroutines or objects so that the internal state of the object is handled "naturally".
|
||||
Os geradores muitas vezes são criados a partir de co-rotinas ou objetos para que o estado interno do objeto seja tratado "naturalmente".
|
||||
|
||||
Generators are often used in situations where a sequence is potentially infinite, and where it is possible to construct the next value of the sequence with only minimal state.
|
||||
Os geradores são, frequentemente, usados em situações onde uma sequência é potencialmente infinita, e onde é possível construir o valor seguinte da sequência apenas com o estado mínimo.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that uses generators to generate squares and cubes. Create a new generator that filters all cubes from the generator of squares.
|
||||
Escreva uma função que use geradores para gerar quadrados e cubos. Crie um novo gerador que filtre todos os cubos do gerador de quadrados.
|
||||
|
||||
The function should return the \\( n^{th} \\) value of the filtered generator.
|
||||
A função deve retornar o enésimo \\( n^{th} \\) valor do gerador filtrado.
|
||||
|
||||
For example for \\(n=7\\), the function should return 81 as the sequence would be 4, 9, 16, 25, 36, 49, 81. Here 64 is filtered out, as it is a cube.
|
||||
Por exemplo, para \\(n=7\\), a função deve retornar 81, já que a sequência seria 4, 9, 16, 25, 36, 49, 81. Aqui, 64 é removido da sequência por ser um cubo.
|
||||
|
||||
# --hints--
|
||||
|
||||
`exponentialGenerator` should be a function.
|
||||
`exponentialGenerator` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof exponentialGenerator == 'function');
|
||||
```
|
||||
|
||||
`exponentialGenerator()` should return a number.
|
||||
`exponentialGenerator()` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof exponentialGenerator(10) == 'number');
|
||||
```
|
||||
|
||||
`exponentialGenerator(10)` should return `144`.
|
||||
`exponentialGenerator(10)` deve retornar `144`.
|
||||
|
||||
```js
|
||||
assert.equal(exponentialGenerator(10), 144);
|
||||
```
|
||||
|
||||
`exponentialGenerator(12)` should return `196`.
|
||||
`exponentialGenerator(12)` deve retornar `196`.
|
||||
|
||||
```js
|
||||
assert.equal(exponentialGenerator(12), 196);
|
||||
```
|
||||
|
||||
`exponentialGenerator(14)` should return `256`.
|
||||
`exponentialGenerator(14)` deve retornar `256`.
|
||||
|
||||
```js
|
||||
assert.equal(exponentialGenerator(14), 256);
|
||||
```
|
||||
|
||||
`exponentialGenerator(20)` should return `484`.
|
||||
`exponentialGenerator(20)` deve retornar `484`.
|
||||
|
||||
```js
|
||||
assert.equal(exponentialGenerator(20), 484);
|
||||
```
|
||||
|
||||
`exponentialGenerator(25)` should return `784`.
|
||||
`exponentialGenerator(25)` deve retornar `784`.
|
||||
|
||||
```js
|
||||
assert.equal(exponentialGenerator(25), 784);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7e80
|
||||
title: Gray code
|
||||
title: Código de Gray
|
||||
challengeType: 5
|
||||
forumTopicId: 302276
|
||||
dashedName: gray-code
|
||||
@ -8,23 +8,23 @@ dashedName: gray-code
|
||||
|
||||
# --description--
|
||||
|
||||
[Gray code](https://en.wikipedia.org/wiki/Gray code) is a form of binary encoding where transitions between consecutive numbers differ by only one bit.
|
||||
O [Código de Gray](https://en.wikipedia.org/wiki/Gray code) é uma forma de codificação binária, onde as transições entre números consecutivos diferem apenas em um bit.
|
||||
|
||||
This is a useful encoding for reducing hardware data hazards with values that change rapidly and/or connect to slower hardware as inputs.
|
||||
Esta é uma codificação útil para reduzir riscos de dados de hardware com valores que se alteram rapidamente e/ou estejam associados ao hardware mais lento como entradas.
|
||||
|
||||
It is also useful for generating inputs for [Karnaugh maps](https://en.wikipedia.org/wiki/Karnaugh map) in order from left to right or top to bottom.
|
||||
Ele também é útil para gerar entradas para os [mapas de Karnaugh](https://en.wikipedia.org/wiki/Karnaugh map) em ordem, da esquerda para a direita ou de cima para baixo.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a function to encode a number to and decode a number from Gray code. The function should will have 2 parameters.
|
||||
Crie uma função para codificar um número e decodifique um número a partir do código de Gray. A função deve receber dois parâmetros.
|
||||
|
||||
The first would be a boolean. The function should encode for true and decode for false. The second parameter would be the number to be encoded/decoded.
|
||||
O primeiro deve ser um booleano. A função deve codificar para true e decodificar para false. O segundo parâmetro seria o número a ser codificado/decodificado.
|
||||
|
||||
Display the normal binary representations, Gray code representations, and decoded Gray code values for all 5-bit binary numbers (0-31 inclusive, leading 0's not necessary).
|
||||
Exibir as representações binárias normais, as representações do código de Gray e valores do código de Gray decodificados para todos os números binários de 5 bits (0-31 inclusive, mas os 0s iniciais não são necessários).
|
||||
|
||||
There are many possible Gray codes. The following encodes what is called "binary reflected Gray code."
|
||||
Existem muitos códigos de Gray possíveis. A seguir, temos um que codifica o que é chamado de "código de Gray refletido em binário."
|
||||
|
||||
Encoding (MSB is bit 0, b is binary, g is Gray code):
|
||||
Codificação (o MSB - bit mais significativo - é o bit 0, b é binário e g é o código de Gray):
|
||||
|
||||
<pre>if b[i-1] = 1
|
||||
g[i] = not b[i]
|
||||
@ -32,63 +32,63 @@ else
|
||||
g[i] = b[i]
|
||||
</pre>
|
||||
|
||||
Or:
|
||||
Ou:
|
||||
|
||||
<pre>g = b xor (b logically right shifted 1 time)
|
||||
<pre>g = b xor (b deslocado logicamente para a direita 1 vez)
|
||||
</pre>
|
||||
|
||||
Decoding (MSB is bit 0, b is binary, g is Gray code):
|
||||
Decodificação (o MSB - bit mais significativo - é o bit 0, b é binário e g é o código de Gray):
|
||||
|
||||
<pre>b[0] = g[0]<br>
|
||||
for other bits:
|
||||
para outros bits:
|
||||
b[i] = g[i] xor b[i-1]
|
||||
</pre>
|
||||
|
||||
# --hints--
|
||||
|
||||
`gray` should be a function.
|
||||
`gray` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof gray == 'function');
|
||||
```
|
||||
|
||||
`gray(true,177)` should return a number.
|
||||
`gray(true,177)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof gray(true, 177) == 'number');
|
||||
```
|
||||
|
||||
`gray(true,177)` should return `233`.
|
||||
`gray(true,177)` deve retornar `233`.
|
||||
|
||||
```js
|
||||
assert.equal(gray(true, 177), 233);
|
||||
```
|
||||
|
||||
`gray(true,425)` should return `381`.
|
||||
`gray(true,425)` deve retornar `381`.
|
||||
|
||||
```js
|
||||
assert.equal(gray(true, 425), 381);
|
||||
```
|
||||
|
||||
`gray(true,870)` should return `725`.
|
||||
`gray(true,870)` deve retornar `725`.
|
||||
|
||||
```js
|
||||
assert.equal(gray(true, 870), 725);
|
||||
```
|
||||
|
||||
`gray(false,233)` should return `177`.
|
||||
`gray(false,233)` deve retornar `177`.
|
||||
|
||||
```js
|
||||
assert.equal(gray(false, 233), 177);
|
||||
```
|
||||
|
||||
`gray(false,381)` should return `425`.
|
||||
`gray(false,381)` deve retornar `425`.
|
||||
|
||||
```js
|
||||
assert.equal(gray(false, 381), 425);
|
||||
```
|
||||
|
||||
`gray(false,725)` should return `870`.
|
||||
`gray(false,725)` deve retornar `870`.
|
||||
|
||||
```js
|
||||
assert.equal(gray(false, 725), 870);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7e82
|
||||
title: Greatest common divisor
|
||||
title: Máximo divisor comum
|
||||
challengeType: 5
|
||||
forumTopicId: 302277
|
||||
dashedName: greatest-common-divisor
|
||||
@ -8,53 +8,53 @@ dashedName: greatest-common-divisor
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function that returns the greatest common divisor of two integers.
|
||||
Escreva uma função que retorne o máximo divisor comum de dois inteiros.
|
||||
|
||||
# --hints--
|
||||
|
||||
`gcd` should be a function.
|
||||
`gcd` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof gcd == 'function');
|
||||
```
|
||||
|
||||
`gcd(24,36)` should return a number.
|
||||
`gcd(24,36)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof gcd(24, 36) == 'number');
|
||||
```
|
||||
|
||||
`gcd(24,36)` should return `12`.
|
||||
`gcd(24,36)` deve retornar `12`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(24, 36), 12);
|
||||
```
|
||||
|
||||
`gcd(30,48)` should return `6`.
|
||||
`gcd(30,48)` deve retornar `6`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(30, 48), 6);
|
||||
```
|
||||
|
||||
`gcd(10,15)` should return `5`.
|
||||
`gcd(10,15)` deve retornar `5`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(10, 15), 5);
|
||||
```
|
||||
|
||||
`gcd(100,25)` should return `25`.
|
||||
`gcd(100,25)` deve retornar `25`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(100, 25), 25);
|
||||
```
|
||||
|
||||
`gcd(13,250)` should return `1`.
|
||||
`gcd(13,250)` deve retornar `1`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(13, 250), 1);
|
||||
```
|
||||
|
||||
`gcd(1300,250)` should return `50`.
|
||||
`gcd(1300,250)` deve retornar `50`.
|
||||
|
||||
```js
|
||||
assert.equal(gcd(1300, 250), 50);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7e84
|
||||
title: Greatest subsequential sum
|
||||
title: Maior número subsequencial
|
||||
challengeType: 5
|
||||
forumTopicId: 302278
|
||||
dashedName: greatest-subsequential-sum
|
||||
@ -8,31 +8,31 @@ dashedName: greatest-subsequential-sum
|
||||
|
||||
# --description--
|
||||
|
||||
Given a sequence of integers, find a continuous subsequence which maximizes the sum of its elements, that is, the elements of no other single subsequence add up to a value larger than this one.
|
||||
Dada uma sequência de números inteiros, encontre uma subsequência contínua que maximize a soma de seus elementos, ou seja, os elementos de nenhuma outra subsequência somam um valor superior a este.
|
||||
|
||||
An empty subsequence is considered to have the sum of \\( 0 \\); thus if all elements are negative, the result must be the empty sequence.
|
||||
Uma subsequência vazia é considerada ter a soma de \\( 0 \\). Portanto, se todos os elementos são negativos, o resultado deve ser a sequência vazia.
|
||||
|
||||
# --hints--
|
||||
|
||||
`maximumSubsequence` should be a function.
|
||||
`maximumSubsequence` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof maximumSubsequence == 'function');
|
||||
```
|
||||
|
||||
`maximumSubsequence([ 1, 2, -1, 3, 10, -10 ])` should return an array.
|
||||
`maximumSubsequence([ 1, 2, -1, 3, 10, -10 ])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(maximumSubsequence([1, 2, -1, 3, 10, -10])));
|
||||
```
|
||||
|
||||
`maximumSubsequence([ 1, 2, -1, 3, 10, -10 ])` should return `[ 1, 2, -1, 3, 10 ]`.
|
||||
`maximumSubsequence([ 1, 2, -1, 3, 10, -10 ])` deve retornar `[ 1, 2, -1, 3, 10 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(maximumSubsequence([1, 2, -1, 3, 10, -10]), [1, 2, -1, 3, 10]);
|
||||
```
|
||||
|
||||
`maximumSubsequence([ 0, 8, 10, -2, -4, -1, -5, -3 ])` should return `[ 0, 8, 10 ]`.
|
||||
`maximumSubsequence([ 0, 8, 10, -2, -4, -1, -5, -3 ])` deve retornar `[ 0, 8, 10 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(maximumSubsequence([0, 8, 10, -2, -4, -1, -5, -3]), [
|
||||
@ -42,25 +42,25 @@ assert.deepEqual(maximumSubsequence([0, 8, 10, -2, -4, -1, -5, -3]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`maximumSubsequence([ 9, 9, -10, 1 ])` should return `[ 9, 9 ]`.
|
||||
`maximumSubsequence([ 9, 9, -10, 1 ])` deve retornar `[ 9, 9 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(maximumSubsequence([9, 9, -10, 1]), [9, 9]);
|
||||
```
|
||||
|
||||
`maximumSubsequence([ 7, 1, -5, -3, -8, 1 ])` should return `[ 7, 1 ]`.
|
||||
`maximumSubsequence([ 7, 1, -5, -3, -8, 1 ])` deve retornar `[ 7, 1 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(maximumSubsequence([7, 1, -5, -3, -8, 1]), [7, 1]);
|
||||
```
|
||||
|
||||
`maximumSubsequence([ -3, 6, -1, 4, -4, -6 ])` should return `[ 6, -1, 4 ]`.
|
||||
`maximumSubsequence([ -3, 6, -1, 4, -4, -6 ])` deve retornar `[ 6, -1, 4 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(maximumSubsequence([-3, 6, -1, 4, -4, -6]), [6, -1, 4]);
|
||||
```
|
||||
|
||||
`maximumSubsequence([ -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 ])` should return `[ 3, 5, 6, -2, -1, 4 ]`.
|
||||
`maximumSubsequence([ -1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1 ])` deve retornar `[ 3, 5, 6, -2, -1, 4 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(maximumSubsequence([-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1]), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 595608ff8bcd7a50bd490181
|
||||
title: Hailstone sequence
|
||||
title: Sequência de granizo
|
||||
challengeType: 5
|
||||
forumTopicId: 302279
|
||||
dashedName: hailstone-sequence
|
||||
@ -8,48 +8,48 @@ dashedName: hailstone-sequence
|
||||
|
||||
# --description--
|
||||
|
||||
The Hailstone sequence of numbers can be generated from a starting positive integer, `n` by:
|
||||
A sequência de números de granizo (hailstone) pode ser gerada a partir de um inteiro inicial positivo, `n` da seguinte forma:
|
||||
|
||||
- If `n` is `1` then the sequence ends
|
||||
- If `n` is `even` then the next `n` of the sequence `= n/2`
|
||||
- If `n` is `odd` then the next `n` of the sequence `= (3 * n) + 1`
|
||||
- Se `n` for `1`, a sequência termina
|
||||
- Se `n` for `even` (par), o próximo `n` da sequência será `= n/2`
|
||||
- Se `n` for `odd` (ímpar), o próximo `n` da sequência será `= (3 * n) + 1`
|
||||
|
||||
The (unproven) Collatz conjecture is that the hailstone sequence for any starting number always terminates.
|
||||
A conjetura de Collatz (não comprovada) é que a sequência de granizo (hailstone) para qualquer número inicial termina sempre.
|
||||
|
||||
The hailstone sequence is also known as hailstone numbers (because the values are usually subject to multiple descents and ascents like hailstones in a cloud), or as the Collatz sequence.
|
||||
A sequência de granizo também é conhecida como números granizo (porque os valores geralmente estão sujeitos a múltiplas descidas e subidas, como granizo - hailstone, em inglês - em uma nuvem), ou como a sequência de Collatz.
|
||||
|
||||
# --instructions--
|
||||
|
||||
1. Create a routine to generate the hailstone sequence for a number
|
||||
2. Your function should return an array with the number less than `limit` which has the longest hailstone sequence and that sequence's length. (But don't show the actual sequence!)
|
||||
1. Crie uma rotina para gerar a sequência de Hailstone para um número
|
||||
2. A função deve retornar um array com o número menor que `limit` que tenha a maior sequência de hailstone e o tamanho da sequência. (Mas não mostrar a sequência real!)
|
||||
|
||||
# --hints--
|
||||
|
||||
`hailstoneSequence` should be a function.
|
||||
`hailstoneSequence` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof hailstoneSequence === 'function');
|
||||
```
|
||||
|
||||
`hailstoneSequence(30)` should return an array.
|
||||
`hailstoneSequence(30)` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(hailstoneSequence(30)));
|
||||
```
|
||||
|
||||
`hailstoneSequence(30)` should return `[27, 112]`.
|
||||
`hailstoneSequence(30)` deve retornar `[27, 112]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(hailstoneSequence(30), [27, 112]);
|
||||
```
|
||||
|
||||
`hailstoneSequence(50000)` should return `[35655, 324]`.
|
||||
`hailstoneSequence(50000)` deve retornar `[35655, 324]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(hailstoneSequence(50000), [35655, 324]);
|
||||
```
|
||||
|
||||
`hailstoneSequence(100000)` should return `[77031, 351]`.
|
||||
`hailstoneSequence(100000)` deve retornar `[77031, 351]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(hailstoneSequence(100000), [77031, 351]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 594810f028c0303b75339ad1
|
||||
title: Happy numbers
|
||||
title: Números felizes
|
||||
challengeType: 5
|
||||
forumTopicId: 302280
|
||||
dashedName: happy-numbers
|
||||
@ -8,89 +8,89 @@ dashedName: happy-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
A [happy number](https://en.wikipedia.org/wiki/Happy_number) is defined by the following process:
|
||||
Um [número feliz](https://en.wikipedia.org/wiki/Happy_number) é definido pelo processo a seguir:
|
||||
|
||||
Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals `1` (where it will stay), or it loops endlessly in a cycle which does not include `1`. Those numbers for which this process ends in `1` are happy numbers, while those that do not end in `1` are unhappy numbers.
|
||||
Começando por qualquer número inteiro positivo, substitua o número pela soma dos quadrados de seus dígitos. Repita o processo até que o número seja igual a `1` (onde ele permanecerá), ou faça laços infinitamente em um ciclo que não inclui o `1`. Os números para os quais este processo termina em `1` são números felizes, enquanto aqueles que não terminam em `1` são números infelizes.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Implement a function that returns true if the number is happy, or false if not.
|
||||
Implementa uma função que retorna true se o número for feliz ou false se não for.
|
||||
|
||||
# --hints--
|
||||
|
||||
`happy` should be a function.
|
||||
`happy` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof happy === 'function');
|
||||
```
|
||||
|
||||
`happy(1)` should return a boolean.
|
||||
`happy(1)` deve retornar um booleano.
|
||||
|
||||
```js
|
||||
assert(typeof happy(1) === 'boolean');
|
||||
```
|
||||
|
||||
`happy(1)` should return `true`.
|
||||
`happy(1)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(happy(1));
|
||||
```
|
||||
|
||||
`happy(2)` should return `false`.
|
||||
`happy(2)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(!happy(2));
|
||||
```
|
||||
|
||||
`happy(7)` should return `true`.
|
||||
`happy(7)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(happy(7));
|
||||
```
|
||||
|
||||
`happy(10)` should return `true`.
|
||||
`happy(10)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(happy(10));
|
||||
```
|
||||
|
||||
`happy(13)` should return `true`.
|
||||
`happy(13)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(happy(13));
|
||||
```
|
||||
|
||||
`happy(19)` should return `true`.
|
||||
`happy(19)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(happy(19));
|
||||
```
|
||||
|
||||
`happy(23)` should return `true`.
|
||||
`happy(23)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(happy(23));
|
||||
```
|
||||
|
||||
`happy(28)` should return `true`.
|
||||
`happy(28)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(happy(28));
|
||||
```
|
||||
|
||||
`happy(31)` should return `true`.
|
||||
`happy(31)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(happy(31));
|
||||
```
|
||||
|
||||
`happy(32)` should return `true`.
|
||||
`happy(32)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert(happy(32));
|
||||
```
|
||||
|
||||
`happy(33)` should return `false`.
|
||||
`happy(33)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert(!happy(33));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 595668ca4cfe1af2fb9818d4
|
||||
title: Harshad or Niven series
|
||||
title: Séries de Harshad ou de Niven
|
||||
challengeType: 5
|
||||
forumTopicId: 302281
|
||||
dashedName: harshad-or-niven-series
|
||||
@ -8,39 +8,39 @@ dashedName: harshad-or-niven-series
|
||||
|
||||
# --description--
|
||||
|
||||
The Harshad or Niven numbers are positive integers ≥ 1 that are divisible by the sum of their digits.
|
||||
Os números de Harshad ou de Niven são inteiros positivos ≥ 1 que são divisíveis pela soma de seus dígitos.
|
||||
|
||||
For example, `42` is a Harshad number as `42` is divisible by `(4 + 2)` without remainder.
|
||||
Por exemplo, `42` é um número de Harshad, pois `42` é divisível por `(4 + 2)` sem resto.
|
||||
|
||||
Assume that the series is defined as the numbers in increasing order.
|
||||
Considere que as séries são definidas como números em ordem crescente.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Implement a function to generate successive members of the Harshad sequence.
|
||||
Implemente uma função para gerar membros sucessivos da sequência de Harshad.
|
||||
|
||||
Use it to return an array with ten members of the sequence, starting with first Harshad number greater than `n`.
|
||||
Use-a para retornar um array com dez membros da sequência, começando com o primeiro número de Harshad maior que `n`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isHarshadOrNiven` should be a function.
|
||||
`isHarshadOrNiven` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof isHarshadOrNiven === 'function');
|
||||
```
|
||||
|
||||
`isHarshadOrNiven(10)` should return `[12, 18, 20, 21, 24, 27, 30, 36, 40, 42]`
|
||||
`isHarshadOrNiven(10)` deve retornar `[12, 18, 20, 21, 24, 27, 30, 36, 40, 42]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(isHarshadOrNiven(10), [12, 18, 20, 21, 24, 27, 30, 36, 40, 42]);
|
||||
```
|
||||
|
||||
`isHarshadOrNiven(400)` should return `[402, 405, 407, 408, 410, 414, 420, 423, 432, 440]`
|
||||
`isHarshadOrNiven(400)` deve retornar `[402, 405, 407, 408, 410, 414, 420, 423, 432, 440]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(isHarshadOrNiven(400), [402, 405, 407, 408, 410, 414, 420, 423, 432, 440]);
|
||||
```
|
||||
|
||||
`isHarshadOrNiven(1000)` should return `[1002, 1008, 1010, 1011, 1012, 1014, 1015, 1016, 1017, 1020]`
|
||||
`isHarshadOrNiven(1000)` deve retornar `[1002, 1008, 1010, 1011, 1012, 1014, 1015, 1016, 1017, 1020]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(isHarshadOrNiven(1000), [1002, 1008, 1010, 1011, 1012, 1014, 1015, 1016, 1017, 1020]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 595671d4d2cdc305f0d5b36f
|
||||
title: Hash from two arrays
|
||||
title: Hash de dois arrays
|
||||
challengeType: 5
|
||||
forumTopicId: 302283
|
||||
dashedName: hash-from-two-arrays
|
||||
@ -8,53 +8,53 @@ dashedName: hash-from-two-arrays
|
||||
|
||||
# --description--
|
||||
|
||||
Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values).
|
||||
Usando dois array de mesmo tamanho, crie um objeto Hash onde os elementos de um array (as chaves) estão ligados aos elementos do outro array (os valores).
|
||||
|
||||
**Related task:**
|
||||
**Tarefa relacionada:**
|
||||
|
||||
<ul>
|
||||
<li><a href='https://rosettacode.org/wiki/Associative arrays/Creation' title='Associative arrays/Creation' target='_blank'>Associative arrays/Creation</a></li>
|
||||
<li><a href='https://rosettacode.org/wiki/Associative arrays/Creation' title='Arrays associativos/Criação' target='_blank'>Arrays associativos/Criação</a></li>
|
||||
</ul>
|
||||
|
||||
# --hints--
|
||||
|
||||
`arrToObj` should be a function.
|
||||
`arrToObj` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof arrToObj === 'function');
|
||||
```
|
||||
|
||||
`arrToObj([1, 2, 3, 4, 5], ["a", "b", "c", "d", "e"])` should return `{ 1: "a", 2: "b", 3: "c", 4: "d", 5: "e" }`
|
||||
`arrToObj([1, 2, 3, 4, 5], ["a", "b", "c", "d", "e"])` deve retornar `{ 1: "a", 2: "b", 3: "c", 4: "d", 5: "e" }`
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrToObj(...testCases[0]), res[0]);
|
||||
```
|
||||
|
||||
`arrToObj([1, 2, 3, 4, 5], ["a", "b", "c", "d"])` should return `{ 1: "a", 2: "b", 3: "c", 4: "d", 5: undefined }`
|
||||
`arrToObj([1, 2, 3, 4, 5], ["a", "b", "c", "d"])` deve retornar `{ 1: "a", 2: "b", 3: "c", 4: "d", 5: undefined }`
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrToObj(...testCases[1]), res[1]);
|
||||
```
|
||||
|
||||
`arrToObj([1, 2, 3], ["a", "b", "c", "d", "e"])` should return `{ 1: "a", 2: "b", 3: "c" }`
|
||||
`arrToObj([1, 2, 3], ["a", "b", "c", "d", "e"])` deve retornar `{ 1: "a", 2: "b", 3: "c" }`
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrToObj(...testCases[2]), res[2]);
|
||||
```
|
||||
|
||||
`arrToObj(["a", "b", "c", "d", "e"], [1, 2, 3, 4, 5])` should return `{ "a": 1, "b": 2, "c": 3 , "d": 4, "e": 5 }`
|
||||
`arrToObj(["a", "b", "c", "d", "e"], [1, 2, 3, 4, 5])` deve retornar `{ "a": 1, "b": 2, "c": 3 , "d": 4, "e": 5 }`
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrToObj(...testCases[3]), res[3]);
|
||||
```
|
||||
|
||||
`arrToObj(["a", "b", "c", "d", "e"], [1, 2, 3, 4])` should return `{ "a": 1, "b": 2, "c": 3 , "d": 4, "e": undefined }`
|
||||
`arrToObj(["a", "b", "c", "d", "e"], [1, 2, 3, 4])` deve retornar `{ "a": 1, "b": 2, "c": 3 , "d": 4, "e": undefined }`
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrToObj(...testCases[4]), res[4]);
|
||||
```
|
||||
|
||||
`arrToObj(["a", "b", "c"], [1, 2, 3, 4, 5])` should return `{ "a": 1, "b": 2, "c": 3 }`
|
||||
`arrToObj(["a", "b", "c"], [1, 2, 3, 4, 5])` deve retornar `{ "a": 1, "b": 2, "c": 3 }`
|
||||
|
||||
```js
|
||||
assert.deepEqual(arrToObj(...testCases[5]), res[5]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5956795bc9e2c415eb244de1
|
||||
title: Hash join
|
||||
title: União de hashes
|
||||
challengeType: 5
|
||||
forumTopicId: 302284
|
||||
dashedName: hash-join
|
||||
@ -8,40 +8,40 @@ dashedName: hash-join
|
||||
|
||||
# --description--
|
||||
|
||||
An [inner join](https://en.wikipedia.org/wiki/Join_(SQL)#Inner_join "wp: Join\_(SQL)#Inner_join") is an operation that combines two data tables into one table, based on matching column values. The simplest way of implementing this operation is the [nested loop join](https://en.wikipedia.org/wiki/Nested loop join "wp: Nested loop join") algorithm, but a more scalable alternative is the [hash join](https://en.wikipedia.org/wiki/hash join "wp: hash join") algorithm.
|
||||
Uma [inner join](https://en.wikipedia.org/wiki/Join_(SQL)#Inner_join "wp: Join\_(SQL)#Inner_join") (união interna) é uma operação que combina duas tabelas de dados em uma tabela, com base em valores de coluna correspondentes. A maneira mais simples de implementar essa operação é o algoritmo de [união de laços aninhados](https://en.wikipedia.org/wiki/Nested loop join "wp: Nested loop join"), mas uma alternativa mais escalável é o algoritmo de [união de hashes](https://en.wikipedia.org/wiki/hash join "wp: hash join").
|
||||
|
||||
The "hash join" algorithm consists of two steps:
|
||||
O algoritmo de união de hashes (ou "hash join") consiste em duas etapas:
|
||||
|
||||
<ol>
|
||||
<li><strong>Hash phase:</strong> Create a <a href='https://en.wikipedia.org/wiki/Multimap' title='wp: Multimap' target='_blank'>multimap</a> from one of the two tables, mapping from each join column value to all the rows that contain it.</li>
|
||||
<li><strong>Fase de hash:</strong> criar um <a href='https://en.wikipedia.org/wiki/Multimap' title='wp: Multimap' target='_blank'>multimapa</a> de uma das tabelas, mapear a partir do valor de cada coluna de join para todas as linhas que a contêm.</li>
|
||||
<ul>
|
||||
<li>The multimap must support hash-based lookup which scales better than a simple linear search, because that's the whole point of this algorithm.</li>
|
||||
<li>Ideally we should create the multimap for the smaller table, thus minimizing its creation time and memory size.</li>
|
||||
<li>O multimapa deve suportar uma pesquisa baseada em hash, que seja melhor dimensionada do que uma simples pesquisa linear, pois esse é o sentido desse algoritmo.</li>
|
||||
<li>Idealmente, devemos criar o multimapa para a tabela menor, assim minimizando seu tempo de criação e o tamanho da memória.</li>
|
||||
</ul>
|
||||
<li><strong>Join phase:</strong> Scan the other table, and find matching rows by looking in the multimap created before.</li>
|
||||
<li><strong>Fase de união:</strong> escaneie a outra tabela e encontre linhas correspondentes buscando no multimapa criado anteriormente.</li>
|
||||
</ol>
|
||||
|
||||
In pseudo-code, the algorithm could be expressed as follows:
|
||||
Em pseudocódigo, o algoritmo poderia ser expresso da seguinte forma:
|
||||
|
||||
<pre><strong>let</strong> <i>A</i> = the first input table (or ideally, the larger one)
|
||||
<strong>let</strong> <i>B</i> = the second input table (or ideally, the smaller one)
|
||||
<strong>let</strong> <i>j<sub>A</sub></i> = the join column ID of table <i>A</i>
|
||||
<strong>let</strong> <i>j<sub>B</sub></i> = the join column ID of table <i>B</i>
|
||||
<strong>let</strong> <i>M<sub>B</sub></i> = a multimap for mapping from single values to multiple rows of table <i>B</i> (starts out empty)
|
||||
<strong>let</strong> <i>C</i> = the output table (starts out empty)
|
||||
<strong>for each</strong> row <i>b</i> in table <i>B</i>:
|
||||
<strong>place</strong> <i>b</i> in multimap <i>M<sub>B</sub></i> under key <i>b(j<sub>B</sub>)</i>
|
||||
<strong>for each</strong> row <i>a</i> in table <i>A</i>:
|
||||
<strong>for each</strong> row <i>b</i> in multimap <i>M<sub>B</sub></i> under key <i>a(j<sub>A</sub>)</i>:
|
||||
<strong>let</strong> <i>c</i> = the concatenation of row <i>a</i> and row <i>b</i>
|
||||
<strong>place</strong> row <i>c</i> in table <i>C</i>
|
||||
<pre><strong>permita que</strong> <i>A</i> = a primeira tabela de entrada (ou idealmente, a maior)
|
||||
<strong>permita que</strong> <i>B</i> = a segunda tabela de entrada (ou idealmente, a menor)
|
||||
<strong>permita que</strong> <i>j<sub>A</sub></i> = o ID da coluna de união da tabela <i>A</i>
|
||||
<strong>permita que</strong> <i>j<sub>B</sub></i> = o ID da coluna de união da tabela <i>B</i>
|
||||
<strong>permita que</strong> <i>M<sub>B</sub></i> = um multimapa para o mapeamento de valores únicos para múltiplas linhas da tabela <i>B</i> (começa vazio)
|
||||
<strong>permita que</strong> <i>C</i> = a tabela de saída (começa vazia)
|
||||
<strong>para cada</strong> linha <i>b</i> na tabela <i>B</i>:
|
||||
<strong>coloque</strong> <i>b</i> no multimapa <i>M<sub>B</sub></i> com a chave <i>b(j<sub>B</sub>)</i>
|
||||
<strong>para cada</strong> linha <i>a</i> na tabela <i>A</i>:
|
||||
<strong>para cada</strong> linha <i>b</i> no multimapa <i>M<sub>B</sub></i> com a chave <i>a(j<sub>A</sub>)</i>:
|
||||
<strong>permita que</strong> <i>c</i> = a concatenação da linha <i>a</i> e da linha <i>b</i>
|
||||
<strong>coloque</strong> a linha <i>c</i> na tabela <i>C</i>
|
||||
</pre>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Implement the "hash join" algorithm as a function and demonstrate that it passes the test-case listed below. The function should accept two arrays of objects and return an array of combined objects.
|
||||
Implemente o algoritmo de "hash join" como uma função e demonstre que ele passa pelo caso de teste listado abaixo. A função deve aceitar dois arrays de objetos e retornar um array de objetos combinados.
|
||||
|
||||
**Input**
|
||||
**Entrada**
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
@ -52,8 +52,8 @@ Implement the "hash join" algorithm as a function and demonstrate that it passes
|
||||
<td style="border:none">
|
||||
<table>
|
||||
<tr>
|
||||
<th style="padding: 4px; margin: 5px;">Age</th>
|
||||
<th style="padding: 4px; margin: 5px;">Name</th>
|
||||
<th style="padding: 4px; margin: 5px;">Idade</th>
|
||||
<th style="padding: 4px; margin: 5px;">Nome</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 4px; margin: 5px;">27</td>
|
||||
@ -82,8 +82,8 @@ Implement the "hash join" algorithm as a function and demonstrate that it passes
|
||||
<td style="border:none">
|
||||
<table>
|
||||
<tr>
|
||||
<th style="padding: 4px; margin: 5px;">Character</th>
|
||||
<th style="padding: 4px; margin: 5px;">Nemesis</th>
|
||||
<th style="padding: 4px; margin: 5px;">Personagem</th>
|
||||
<th style="padding: 4px; margin: 5px;">Inimigo</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td style="padding: 4px; margin: 5px;">Jonah</td>
|
||||
@ -113,13 +113,13 @@ Implement the "hash join" algorithm as a function and demonstrate that it passes
|
||||
<i>j<sub>A</sub> =</i>
|
||||
</td>
|
||||
<td style="border:none">
|
||||
<i><code>Name</code> (i.e. column 1)</i>
|
||||
<i><code>Name</code> (ou seja, a coluna 1)</i>
|
||||
</td>
|
||||
<td style="border:none">
|
||||
<i>j<sub>B</sub> =</i>
|
||||
</td>
|
||||
<td style="border:none">
|
||||
<i><code>Character</code> (i.e. column 0)</i>
|
||||
<i><code>Character</code> (ou seja, a coluna 0)</i>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
@ -127,7 +127,7 @@ Implement the "hash join" algorithm as a function and demonstrate that it passes
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
**Output**
|
||||
**Saída**
|
||||
|
||||
| A_age | A_name | B_character | B_nemesis |
|
||||
| ----- | ------ | ----------- | --------- |
|
||||
@ -139,17 +139,17 @@ Implement the "hash join" algorithm as a function and demonstrate that it passes
|
||||
| 28 | Alan | Alan | Ghosts |
|
||||
| 28 | Alan | Alan | Zombies |
|
||||
|
||||
The order of the rows in the output table is not significant.
|
||||
A ordem das linhas na tabela de saída não é significativa.
|
||||
|
||||
# --hints--
|
||||
|
||||
`hashJoin` should be a function.
|
||||
`hashJoin` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof hashJoin === 'function');
|
||||
```
|
||||
|
||||
`hashJoin([{ age: 27, name: "Jonah" }, { age: 18, name: "Alan" }, { age: 28, name: "Glory" }, { age: 18, name: "Popeye" }, { age: 28, name: "Alan" }], [{ character: "Jonah", nemesis: "Whales" }, { character: "Jonah", nemesis: "Spiders" }, { character: "Alan", nemesis: "Ghosts" }, { character:"Alan", nemesis: "Zombies" }, { character: "Glory", nemesis: "Buffy" }, { character: "Bob", nemesis: "foo" }])` should return `[{"A_age": 27,"A_name": "Jonah", "B_character": "Jonah", "B_nemesis": "Whales"}, {"A_age": 27,"A_name": "Jonah", "B_character": "Jonah", "B_nemesis": "Spiders"}, {"A_age": 18,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Ghosts"}, {"A_age": 18,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Zombies"}, {"A_age": 28,"A_name": "Glory", "B_character": "Glory", "B_nemesis": "Buffy"}, {"A_age": 28,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Ghosts"}, {"A_age": 28,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Zombies"}]`
|
||||
`hashJoin([{ age: 27, name: "Jonah" }, { age: 18, name: "Alan" }, { age: 28, name: "Glory" }, { age: 18, name: "Popeye" }, { age: 28, name: "Alan" }], [{ character: "Jonah", nemesis: "Whales" }, { character: "Jonah", nemesis: "Spiders" }, { character: "Alan", nemesis: "Ghosts" }, { character:"Alan", nemesis: "Zombies" }, { character: "Glory", nemesis: "Buffy" }, { character: "Bob", nemesis: "foo" }])` deve retornar `[{"A_age": 27,"A_name": "Jonah", "B_character": "Jonah", "B_nemesis": "Whales"}, {"A_age": 27,"A_name": "Jonah", "B_character": "Jonah", "B_nemesis": "Spiders"}, {"A_age": 18,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Ghosts"}, {"A_age": 18,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Zombies"}, {"A_age": 28,"A_name": "Glory", "B_character": "Glory", "B_nemesis": "Buffy"}, {"A_age": 28,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Ghosts"}, {"A_age": 28,"A_name": "Alan", "B_character": "Alan", "B_nemesis": "Zombies"}]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(hashJoin(hash1, hash2), res);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 595b98f8b5a2245e243aa831
|
||||
title: Heronian triangles
|
||||
title: Triângulos Heronianos
|
||||
challengeType: 5
|
||||
forumTopicId: 302285
|
||||
dashedName: heronian-triangles
|
||||
@ -8,57 +8,57 @@ dashedName: heronian-triangles
|
||||
|
||||
# --description--
|
||||
|
||||
[Hero's formula](https://en.wikipedia.org/wiki/Heron's formula "wp: Heron's formula") for the area of a triangle given the length of its three sides `a`, `b`, and `c` is given by:
|
||||
A [fórmula de Heron](https://en.wikipedia.org/wiki/Heron's formula "wp: Heron's formula") para a área de um triângulo dado o comprimento de seus três lados `a`, `b`, e `c`, é dada por:
|
||||
|
||||
$A = \\sqrt{s(s-a)(s-b)(s-c)},$
|
||||
|
||||
where `s` is half the perimeter of the triangle; that is,
|
||||
onde `s` é metade do perímetro do triângulo, ou seja,
|
||||
|
||||
$s=\\frac{a+b+c}{2}.$
|
||||
|
||||
Heronian triangles are triangles whose sides and area are all integers.
|
||||
Os triângulos Heronianos são triângulos cujos lados e área são todos inteiros.
|
||||
|
||||
An example is the triangle with sides `3, 4, 5` whose area is `6` (and whose perimeter is `12`).
|
||||
Um exemplo é o triângulo com os lados `3, 4, 5`, cuja área é `6` (e cujo perímetro é `12`).
|
||||
|
||||
Note that any triangle whose sides are all an integer multiple of `3, 4, 5`; such as `6, 8, 10,` will also be a Heronian triangle.
|
||||
Observe que qualquer triângulo cujos lados são todos números inteiros múltiplo de `3, 4, 5`, como `6, 8, 10,`, por exemplo, também será um triângulo Heroniano.
|
||||
|
||||
Define a Primitive Heronian triangle as a Heronian triangle where the greatest common divisor
|
||||
Defina um triângulo Heroniano Primitivo como um triângulo Heroniano no qual o maior divisor comum
|
||||
|
||||
of all three sides is `1` (unity).
|
||||
de todos os três lados é `1` (unidade).
|
||||
|
||||
This will exclude, for example, triangle `6, 8, 10.`
|
||||
Isso excluirá, por exemplo, o triângulo `6, 8, 10.`
|
||||
|
||||
# --instructions--
|
||||
|
||||
Implement a function based on Hero's formula that returns the first <code>n<sub>th</sub></code> ordered triangles in an array of arrays.
|
||||
Implemente uma função baseada na fórmula de Heron que retorna os primeiros <code>n<sub>th</sub></code> (enésimos) triângulos ordenados em um array de arrays.
|
||||
|
||||
# --hints--
|
||||
|
||||
`heronianTriangle` should be a function.
|
||||
`heronianTriangle` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof heronianTriangle === 'function');
|
||||
```
|
||||
|
||||
`heronianTriangle(10)` should return `[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17]]`
|
||||
`heronianTriangle(10)` deve retornar `[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(heronianTriangle(testCases[0]), res[0]);
|
||||
```
|
||||
|
||||
`heronianTriangle(15)` should return `[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15]],`
|
||||
`heronianTriangle(15)` deve retornar `[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15]],`
|
||||
|
||||
```js
|
||||
assert.deepEqual(heronianTriangle(testCases[1]), res[1]);
|
||||
```
|
||||
|
||||
`heronianTriangle(20)` should return `[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53]],`
|
||||
`heronianTriangle(20)` deve retornar `[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53]],`
|
||||
|
||||
```js
|
||||
assert.deepEqual(heronianTriangle(testCases[2]), res[2]);
|
||||
```
|
||||
|
||||
`heronianTriangle(25)` should return `[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53], [19, 20, 37],[16, 17, 17], [17, 17, 30], [16, 25, 39], [13, 20, 21]]`
|
||||
`heronianTriangle(25)` deve retornar `[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53], [19, 20, 37],[16, 17, 17], [17, 17, 30], [16, 25, 39], [13, 20, 21]]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(heronianTriangle(testCases[3]), res[3]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 59622f89e4e137560018a40e
|
||||
title: Hofstadter Figure-Figure sequences
|
||||
title: Sequências de Figura-Figura de Hofstadter
|
||||
challengeType: 5
|
||||
forumTopicId: 302286
|
||||
dashedName: hofstadter-figure-figure-sequences
|
||||
@ -8,106 +8,106 @@ dashedName: hofstadter-figure-figure-sequences
|
||||
|
||||
# --description--
|
||||
|
||||
These two sequences of positive integers are defined as:
|
||||
Estas duas sequências de inteiros positivos são definidas como:
|
||||
|
||||
$R(1)=1\\ ;\\ S(1)=2 \\\\R(n)=R(n-1)+S(n-1), \\quad n>1.$
|
||||
|
||||
The sequence $S(n)$ is further defined as the sequence of positive integers not present in $R(n)$.
|
||||
A sequência $S(n)$ está definida ainda mais como a sequência de números inteiros positivos não presentes em $R(n)$.
|
||||
|
||||
Sequence $R$ starts:
|
||||
A sequência $R$ inicia assim:
|
||||
|
||||
<pre>1, 3, 7, 12, 18, ...</pre>
|
||||
|
||||
Sequence $S$ starts:
|
||||
A sequência $S$ inicia assim:
|
||||
|
||||
<pre>2, 4, 5, 6, 8, ...</pre>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create two functions named `ffr` and `ffs` that when given `n` return `R(n)` or `S(n)` respectively. (Note that R(1) = 1 and S(1) = 2 to avoid off-by-one errors).
|
||||
Crie duas funções chamadas `ffr` e `ffs` que, ao receber `n`, retornam `R(n)` ou `S(n)`, respectivamente. (Observe que R(1) = 1 e S(1) = 2 para evitar erros de "fora por um").
|
||||
|
||||
No maximum value for `n` should be assumed.
|
||||
Nenhum valor máximo para `n` deve ser assumido.
|
||||
|
||||
**References**
|
||||
**Referências**
|
||||
|
||||
<ul>
|
||||
<li>
|
||||
Sloane's <a href='https://oeis.org/A005228' target='_blank'>A005228</a> and <a href='https://oeis.org/A030124' target='_blank'>A030124</a>.
|
||||
<a href='https://oeis.org/A005228' target='_blank'>A005228</a> e <a href='https://oeis.org/A030124' target='_blank'>A030124</a> de Sloane.
|
||||
</li>
|
||||
<li>
|
||||
Wikipedia: <a href='https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Figure-Figure_sequences' title='wp: Hofstadter_sequence#Hofstadter_Figure-Figure_sequences' target='_blank'>Hofstadter Figure-Figure sequences</a>.
|
||||
Wikipédia: <a href='https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Figure-Figure_sequences' title='wp: Hofstadter_sequence#Hofstadter_Figure-Figure_sequences' target='_blank'>sequências de figura-figura de Hofstadter</a>.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
# --hints--
|
||||
|
||||
`ffr` should be a function.
|
||||
`ffr` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof ffr === 'function');
|
||||
```
|
||||
|
||||
`ffs` should be a function.
|
||||
`ffs` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof ffs === 'function');
|
||||
```
|
||||
|
||||
`ffr` should return integer.
|
||||
`ffr` deve retornar um inteiro.
|
||||
|
||||
```js
|
||||
assert(Number.isInteger(ffr(1)));
|
||||
```
|
||||
|
||||
`ffs` should return integer.
|
||||
`ffs` deve retornar um inteiro.
|
||||
|
||||
```js
|
||||
assert(Number.isInteger(ffs(1)));
|
||||
```
|
||||
|
||||
`ffr(10)` should return `69`
|
||||
`ffr(10)` deve retornar `69`
|
||||
|
||||
```js
|
||||
assert.equal(ffr(ffrParamRes[0][0]), ffrParamRes[0][1]);
|
||||
```
|
||||
|
||||
`ffr(50)` should return `1509`
|
||||
`ffr(50)` deve retornar `1509`
|
||||
|
||||
```js
|
||||
assert.equal(ffr(ffrParamRes[1][0]), ffrParamRes[1][1]);
|
||||
```
|
||||
|
||||
`ffr(100)` should return `5764`
|
||||
`ffr(100)` deve retornar `5764`
|
||||
|
||||
```js
|
||||
assert.equal(ffr(ffrParamRes[2][0]), ffrParamRes[2][1]);
|
||||
```
|
||||
|
||||
`ffr(1000)` should return `526334`
|
||||
`ffr(1000)` deve retornar `526334`
|
||||
|
||||
```js
|
||||
assert.equal(ffr(ffrParamRes[3][0]), ffrParamRes[3][1]);
|
||||
```
|
||||
|
||||
`ffs(10)` should return `14`
|
||||
`ffs(10)` deve retornar `14`
|
||||
|
||||
```js
|
||||
assert.equal(ffs(ffsParamRes[0][0]), ffsParamRes[0][1]);
|
||||
```
|
||||
|
||||
`ffs(50)` should return `59`
|
||||
`ffs(50)` deve retornar `59`
|
||||
|
||||
```js
|
||||
assert.equal(ffs(ffsParamRes[1][0]), ffsParamRes[1][1]);
|
||||
```
|
||||
|
||||
`ffs(100)` should return `112`
|
||||
`ffs(100)` deve retornar `112`
|
||||
|
||||
```js
|
||||
assert.equal(ffs(ffsParamRes[2][0]), ffsParamRes[2][1]);
|
||||
```
|
||||
|
||||
`ffs(1000)` should return `1041`
|
||||
`ffs(1000)` deve retornar `1041`
|
||||
|
||||
```js
|
||||
assert.equal(ffs(ffsParamRes[3][0]), ffsParamRes[3][1]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 59637c4d89f6786115efd814
|
||||
title: Hofstadter Q sequence
|
||||
title: Sequência Q de Hofstadter
|
||||
challengeType: 5
|
||||
forumTopicId: 302287
|
||||
dashedName: hofstadter-q-sequence
|
||||
@ -8,49 +8,49 @@ dashedName: hofstadter-q-sequence
|
||||
|
||||
# --description--
|
||||
|
||||
The [Hofstadter Q sequence](https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Q_sequence "wp: Hofstadter_sequence#Hofstadter_Q_sequence") is defined as:
|
||||
A [sequência Q de Hofstadter](https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Q_sequence "wp: Hofstadter_sequence#Hofstadter_Q_sequence") é definida como:
|
||||
|
||||
$Q(1)=Q(2)=1, \\\\ Q(n)=Q\\big(n-Q(n-1)\\big)+Q\\big(n-Q(n-2)), \\quad n>2.$
|
||||
|
||||
It is defined like the [Fibonacci sequence](https://rosettacode.org/wiki/Fibonacci sequence "Fibonacci sequence"), but whereas the next term in the Fibonacci sequence is the sum of the previous two terms, in the Q sequence the previous two terms tell you how far to go back in the Q sequence to find the two numbers to sum to make the next term of the sequence.
|
||||
Ela é definida como a [sequência de Fibonacci](https://rosettacode.org/wiki/Fibonacci sequence "Fibonacci sequence"), mas enquanto o próximo termo na sequência de Fibonacci é a soma dos dois termos anteriores, na sequência Q, os dois termos anteriores dizer a distância a retornar na sequência Q para encontrar os dois números somados para fazer o próximo termo da sequência.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Implement the Hofstadter Q Sequence equation as a function. The function should accept number, `n`, and return an integer.
|
||||
Implementar a equação da sequência Q de Hofstadter como uma função. A função deve aceitar o número, `n`, e retornar um inteiro.
|
||||
|
||||
# --hints--
|
||||
|
||||
`hofstadterQ` should be a function.
|
||||
`hofstadterQ` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof hofstadterQ === 'function');
|
||||
```
|
||||
|
||||
`hofstadterQ()` should return `integer`
|
||||
`hofstadterQ()` deve retornar um `integer`
|
||||
|
||||
```js
|
||||
assert(Number.isInteger(hofstadterQ(1000)));
|
||||
```
|
||||
|
||||
`hofstadterQ(1000)` should return `502`
|
||||
`hofstadterQ(1000)` deve retornar `502`
|
||||
|
||||
```js
|
||||
assert.equal(hofstadterQ(testCase[0]), res[0]);
|
||||
```
|
||||
|
||||
`hofstadterQ(1500)` should return `755`
|
||||
`hofstadterQ(1500)` deve retornar `755`
|
||||
|
||||
```js
|
||||
assert.equal(hofstadterQ(testCase[1]), res[1]);
|
||||
```
|
||||
|
||||
`hofstadterQ(2000)` should return `1005`
|
||||
`hofstadterQ(2000)` deve retornar `1005`
|
||||
|
||||
```js
|
||||
assert.equal(hofstadterQ(testCase[2]), res[2]);
|
||||
```
|
||||
|
||||
`hofstadterQ(2500)` should return `1261`
|
||||
`hofstadterQ(2500)` deve retornar `1261`
|
||||
|
||||
```js
|
||||
assert.equal(hofstadterQ(testCase[3]), res[3]);
|
||||
|
@ -8,61 +8,61 @@ dashedName: iban
|
||||
|
||||
# --description--
|
||||
|
||||
The [International Bank Account Number (IBAN)](https://en.wikipedia.org/wiki/International_Bank_Account_Number) is an internationally agreed means of identifying bank accounts across national borders with a reduced risk of propagating [transcription errors](https://en.wikipedia.org/wiki/Transcription_error).
|
||||
O [Número de Conta Bancária Internacional (IBAN)](https://en.wikipedia.org/wiki/International_Bank_Account_Number) é uma maneira acordada internacionalmente para identificar contas bancárias através das fronteiras nacionais com um risco reduzido de propagação de [erros de transcrição](https://en.wikipedia.org/wiki/Transcription_error).
|
||||
|
||||
The IBAN consists of up to 34 alphanumeric characters:
|
||||
O IBAN consiste em até 34 caracteres alfanuméricos:
|
||||
|
||||
<ul>
|
||||
<li>first the two-letter ISO 3166-1 alpha-2 country code</li>
|
||||
<li>then two check digits, and</li>
|
||||
<li>finally a country-specific Basic Bank Account Number (BBAN).</li>
|
||||
<li>primeiro o código de país ISO 3166-1 alpha-2 de duas letras</li>
|
||||
<li>depois dois dígitos de verificação, e</li>
|
||||
<li>finalmente, um número de conta bancária básica específico do país (BBAN).</li>
|
||||
</ul>
|
||||
|
||||
The check digits enable a sanity check of the bank account number to confirm its integrity even before submitting a transaction.
|
||||
Os dígitos de verificação habilitam uma verificação de sanidade do número da conta bancária para confirmar a sua integridade mesmo antes de enviar uma transação.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes IBAN string as parameter. If it is valid return true. Otherwise, return false.
|
||||
Escreva uma função que recebe a string de IBAN como parâmetro. Se for válida, retorne true. Caso contrário, retorne false.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isValid` should be a function.
|
||||
`isValid` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof isValid == 'function');
|
||||
```
|
||||
|
||||
`isValid("GB82 WEST 1234 5698 7654 32")` should return a boolean.
|
||||
`isValid("GB82 WEST 1234 5698 7654 32")` deve retornar um booleano.
|
||||
|
||||
```js
|
||||
assert(typeof isValid('GB82 WEST 1234 5698 7654 32') == 'boolean');
|
||||
```
|
||||
|
||||
`isValid("GB82 WEST 1234 5698 7654 32")` should return `true`.
|
||||
`isValid("GB82 WEST 1234 5698 7654 32")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isValid('GB82 WEST 1234 5698 7654 32'), true);
|
||||
```
|
||||
|
||||
`isValid("GB82 WEST 1.34 5698 7654 32")` should return `false`.
|
||||
`isValid("GB82 WEST 1.34 5698 7654 32")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isValid('GB82 WEST 1.34 5698 7654 32'), false);
|
||||
```
|
||||
|
||||
`isValid("GB82 WEST 1234 5698 7654 325")` should return `false`.
|
||||
`isValid("GB82 WEST 1234 5698 7654 325")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isValid('GB82 WEST 1234 5698 7654 325'), false);
|
||||
```
|
||||
|
||||
`isValid("GB82 TEST 1234 5698 7654 32")` should return `false`.
|
||||
`isValid("GB82 TEST 1234 5698 7654 32")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isValid('GB82 TEST 1234 5698 7654 32'), false);
|
||||
```
|
||||
|
||||
`isValid("SA03 8000 0000 6080 1016 7519")` should return `true`.
|
||||
`isValid("SA03 8000 0000 6080 1016 7519")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isValid('SA03 8000 0000 6080 1016 7519'), true);
|
||||
|
Reference in New Issue
Block a user