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

This commit is contained in:
camperbot
2021-08-02 23:05:44 +09:00
committed by GitHub
parent 3350cb4522
commit 6b82f3831c
123 changed files with 1300 additions and 1301 deletions

View File

@ -1,6 +1,6 @@
---
id: 594810f028c0303b75339acb
title: 100 doors
title: 100 portas
challengeType: 5
forumTopicId: 302217
dashedName: 100-doors
@ -8,27 +8,27 @@ dashedName: 100-doors
# --description--
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and 'toggle' the door (if the door is closed, open it; if it is open, close it). The second time, only visit every 2nd door (i.e., door #2, #4, #6, ...) and toggle it. The third time, visit every 3rd door (i.e., door #3, #6, #9, ...), etc., until you only visit the 100th door.
Há 100 portas seguidas que estão todas fechadas inicialmente. Você faz 100 passagens pelas portas. A primeira vez que passar, visite todas as portas e 'alterne' a porta (se a porta estiver fechada, abra-a; se estiver aberta, feche-a). Na segunda vez, só visite as portas pares (ou seja, as porta 2, 4, 6, ...) e alterne-as. Na terceira vez, visite as portas de 3 em 3 (por exemplo, as portas 3, 6, 9, ...), até que você só visite a porta 100.
# --instructions--
Implement a function to determine the state of the doors after the last pass. Return the final result in an array, with only the door number included in the array if it is open.
Implemente uma função para determinar o estado das portas após a último passagem. Retorne o resultado final em um array, com o número da porta incluído no array apenas se ela estiver aberta.
# --hints--
`getFinalOpenedDoors` should be a function.
`getFinalOpenedDoors` deve ser uma função.
```js
assert(typeof getFinalOpenedDoors === 'function');
```
`getFinalOpenedDoors` should return an array.
`getFinalOpenedDoors` deve retornar um array.
```js
assert(Array.isArray(getFinalOpenedDoors(100)));
```
`getFinalOpenedDoors` should produce the correct result.
`getFinalOpenedDoors` deve produzir o resultado correto.
```js
assert.deepEqual(getFinalOpenedDoors(100), solution);

View File

@ -1,6 +1,6 @@
---
id: 5951e88f64ebf159166a1176
title: 24 game
title: Jogo dos 24
challengeType: 5
forumTopicId: 302218
dashedName: 24-game
@ -8,23 +8,23 @@ dashedName: 24-game
# --description--
The [24 Game](https://en.wikipedia.org/wiki/24_Game) tests a person's mental arithmetic.
O [Jogo dos 24](https://en.wikipedia.org/wiki/24_Game) testa a aritmética mental das pessoas.
The aim of the game is to arrange four numbers in a way that when evaluated, the result is 24
O objetivo do jogo é organizar quatro números de maneira que, quando avaliados, o resultado seja 24
# --instructions--
Implement a function that takes a string of four digits as its argument, with each digit from 1 to 9 (inclusive) with repetitions allowed, and returns an arithmetic expression that evaluates to the number 24. If no such solution exists, return "no solution exists".
Implemente uma função que receba uma string de quatro algarismos como argumento, com cada algarismo de 1 a 9 (inclusive), com repetições permitidas, e que retorne uma expressão aritmética que avalie como chegar ao número 24. Se essa solução não existir, retorne "no solution exists".
**Rules:**
**Regras:**
<ul>
<li> Only the following operators/functions are allowed: multiplication, division, addition, subtraction. </li>
<li> Division should use floating point or rational arithmetic, etc, to preserve remainders. </li>
<li> Forming multiple digit numbers from the supplied digits is disallowed. (So an answer of 12+12 when given 1, 2, 2, and 1 is wrong). </li>
<li> The order of the digits when given does not have to be preserved. </li>
<li> Apenas os operadores/funções seguintes são permitidos: multiplicação, divisão, adição, subtração. </li>
<li> A divisão deve usar o ponto flutuante ou a aritmética de racionais, etc., para preservar os restos. </li>
<li> Formar números com mais de um dígito a partir dos que foram fornecidos não é permitido. (Portanto, uma resposta de 12+12 quando for fornecido 1, 2, 2 e 1 está errada). </li>
<li> A ordem dos dígitos fornecida não precisa ser preservada. </li>
</ul>
| Example input | Example output |
| Exemplo de entrada | Exemplo de saída |
| ------------------------- | ------------------------- |
| <code>solve24("4878");</code> | <code>(7-8/8)\*4</code> |
| <code>solve24("1234");</code> | <code>3\*1\*4\*2</code> |
@ -33,31 +33,31 @@ Implement a function that takes a string of four digits as its argument, with ea
# --hints--
`solve24` should be a function.
`solve24` deve ser uma função.
```js
assert(typeof solve24 === 'function');
```
`solve24("4878")` should return `(7-8/8)*4` or `4*(7-8/8)`
`solve24("4878")` deve retornar `(7-8/8)*4` ou `4*(7-8/8)`
```js
assert(include(answers[0], removeParentheses(solve24(testCases[0]))));
```
`solve24("1234")` should return any arrangement of `1*2*3*4`
`solve24("1234")` deve retornar qualquer combinação de `1*2*3*4`
```js
assert(include(answers[1], removeParentheses(solve24(testCases[1]))));
```
`solve24("6789")` should return `(6*8)/(9-7)` or `(8*6)/(9-7)`
`solve24("6789")` deve retornar `(6*8)/(9-7)` ou `(8*6)/(9-7)`
```js
assert(include(answers[2], removeParentheses(solve24(testCases[2]))));
```
`solve24("1127")` should return a permutation of `(1+7)*(1+2)`
`solve24("1127")` deve retornar uma permutação de `(1+7)*(1+2)`
```js
assert(include(answers[3], removeParentheses(solve24(testCases[3]))));

View File

@ -1,6 +1,6 @@
---
id: 5949b579404977fbaefcd736
title: 9 billion names of God the integer
title: 9 bilhões de nomes de Deus, o inteiro
challengeType: 5
forumTopicId: 302219
dashedName: 9-billion-names-of-god-the-integer
@ -8,21 +8,21 @@ dashedName: 9-billion-names-of-god-the-integer
# --description--
This task is a variation of the [short story by Arthur C. Clarke](https://en.wikipedia.org/wiki/The Nine Billion Names of God#Plot_summary "wp: The Nine Billion Names of God#Plot_summary").
Esta tarefa é uma variação do [conto escrito por Arthur C. Clarke](https://en.wikipedia.org/wiki/The Nine Billion Names of God#Plot_summary "wp: The Nine Billion Names of God#Plot_summary").
(Solvers should be aware of the consequences of completing this task.)
(Quem chegar à solução deve estar ciente das consequências de concluir esta tarefa.)
In detail, to specify what is meant by a "name":
Em detalhes, para especificar o que significa um "nome":
<ul>
<li>The integer 1 has 1 name "1".</li>
<li>The integer 2 has 2 names "1+1" and "2".</li>
<li>The integer 3 has 3 names "1+1+1", "2+1", and "3".</li>
<li>The integer 4 has 5 names "1+1+1+1", "2+1+1", "2+2", "3+1", "4".</li>
<li>The integer 5 has 7 names "1+1+1+1+1", "2+1+1+1", "2+2+1", "3+1+1", "3+2", "4+1", "5".</li>
<li>O inteiro 1 tem 1 nome: "1".</li>
<li>O inteiro 2 tem 2 nomes: "1+1" e "2".</li>
<li>O inteiro 3 tem 3 nomes: "1+1+1", "2+1" e "3".</li>
<li>O inteiro 4 tem 5 nomes: "1+1+1+1", "2+1+1", "2+2", "3+1", "4".</li>
<li>O inteiro 5 tem 7 nomes: "1+1+1+1+1", "2+1+1+1", "2+2+1", "3+1+1", "3+2", "4+1", "5".</li>
</ul>
This can be visualized in the following form:
Isto pode ser visualizado do seguinte modo:
<pre> 1
1 1
@ -32,53 +32,53 @@ This can be visualized in the following form:
1 3 3 2 1 1
</pre>
Where row $n$ corresponds to integer $n$, and each column $C$ in row $m$ from left to right corresponds to the number of names beginning with $C$.
Onde a linha $n$ corresponde ao inteiro $n$ e cada coluna $C$ na linha $m$ da esquerda para a direita corresponde ao número de nomes que começam com $C$.
Optionally note that the sum of the $n$-th row $P(n)$ is the integer partition function.
Como opção, note que a soma da $n$-ésima linha $P(n)$ é a função de partição de inteiros.
# --instructions--
Implement a function that returns the sum of the $n$-th row.
Implemente uma função que retorna a soma da $n$-ésima linha.
# --hints--
`numberOfNames` should be function.
`numberOfNames` deve ser uma função.
```js
assert(typeof numberOfNames === 'function');
```
`numberOfNames(5)` should equal 7.
`numberOfNames(5)` deve ser igual a 7.
```js
assert.equal(numberOfNames(5), 7);
```
`numberOfNames(12)` should equal 77.
`numberOfNames(12)` deve ser igual a 77.
```js
assert.equal(numberOfNames(12), 77);
```
`numberOfNames(18)` should equal 385.
`numberOfNames(18)` deve ser igual a 385.
```js
assert.equal(numberOfNames(18), 385);
```
`numberOfNames(23)` should equal 1255.
`numberOfNames(23)` deve ser igual a 1255.
```js
assert.equal(numberOfNames(23), 1255);
```
`numberOfNames(42)` should equal 53174.
`numberOfNames(42)` deve ser igual a 53174.
```js
assert.equal(numberOfNames(42), 53174);
```
`numberOfNames(123)` should equal 2552338241.
`numberOfNames(123)` deve ser igual a 2552338241.
```js
assert.equal(numberOfNames(123), 2552338241);

View File

@ -1,6 +1,6 @@
---
id: 594810f028c0303b75339acc
title: ABC Problem
title: Problema do ABC
challengeType: 5
forumTopicId: 302220
dashedName: abc-problem
@ -8,7 +8,7 @@ dashedName: abc-problem
# --description--
You are given a collection of ABC blocks (e.g., childhood alphabet blocks). There are 20 blocks with two letters on each block. A complete alphabet is guaranteed amongst all sides of the blocks. The sample collection of blocks:
Você recebe uma coleção de blocos ABC (por exemplo, blocos de alfabeto de infância). Há 20 blocos com duas letras em cada bloco. Um alfabeto completo é garantido entre todos os lados dos blocos. A coleção de amostra de blocos:
<pre>(B O)
(X K)
@ -34,60 +34,60 @@ You are given a collection of ABC blocks (e.g., childhood alphabet blocks). Ther
# --instructions--
Implement a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
Implemente uma função que recebe uma string (palavra) e determina se a palavra pode ser escrita com a coleção de blocos fornecida.
Some rules to keep in mind:
Algumas regras para se ter em mente:
<ul>
<li>Once a letter on a block is used, that block cannot be used again.</li>
<li>The function should be case-insensitive.</li>
<li>Quando uma letra em um bloco é usada, esse bloco não pode ser usado novamente.</li>
<li>A função não deve distinguir maiúsculas e minúsculas.</li>
</ul>
# --hints--
`canMakeWord` should be a function.
`canMakeWord` deve ser uma função.
```js
assert(typeof canMakeWord === 'function');
```
`canMakeWord` should return a boolean.
`canMakeWord` deve retornar um booleano.
```js
assert(typeof canMakeWord('hi') === 'boolean');
```
`canMakeWord("bark")` should return true.
`canMakeWord("bark")` deve retornar true.
```js
assert(canMakeWord(words[0]));
```
`canMakeWord("BooK")` should return false.
`canMakeWord("BooK")` deve retornar false.
```js
assert(!canMakeWord(words[1]));
```
`canMakeWord("TReAT")` should return true.
`canMakeWord("TReAT")` deve retornar true.
```js
assert(canMakeWord(words[2]));
```
`canMakeWord("COMMON")` should return false.
`canMakeWord("COMMON")` deve retornar false.
```js
assert(!canMakeWord(words[3]));
```
`canMakeWord("squAD")` should return true.
`canMakeWord("squAD")` deve retornar true.
```js
assert(canMakeWord(words[4]));
```
`canMakeWord("conFUSE")` should return true.
`canMakeWord("conFUSE")` deve retornar true.
```js
assert(canMakeWord(words[5]));

View File

@ -1,6 +1,6 @@
---
id: 594810f028c0303b75339acd
title: 'Abundant, deficient and perfect number classifications'
title: 'Classificações de números abundantes, deficientes e perfeitos'
challengeType: 5
forumTopicId: 302221
dashedName: abundant-deficient-and-perfect-number-classifications
@ -8,55 +8,55 @@ dashedName: abundant-deficient-and-perfect-number-classifications
# --description--
These define three classifications of positive integers based on their proper divisors.
Estas classificações definem três categorias de inteiros positivos com base nos seus divisores.
Let $P(n)$ be the sum of the proper divisors of `n` where proper divisors are all positive integers `n` other than `n` itself.
Vamos considerar que $P(n)$ é a soma dos divisores apropriados de `n`, onde todos os divisores adequados são inteiros positivos `n` diferentes de `n`.
If `P(n) < n` then `n` is classed as `deficient`
Se `P(n) < n`, `n` é classificado como `deficient`
If `P(n) === n` then `n` is classed as `perfect`
Se `P(n) === n`, `n` é classificado como `perfect`
If `P(n) > n` then `n` is classed as `abundant`
Se `P(n) > n`, `n` é classificado como `abundant`
**Example**: `6` has proper divisors of `1`, `2`, and `3`. `1 + 2 + 3 = 6`, so `6` is classed as a perfect number.
**Exemplo**: `6` tem divisores adequados em `1`, `2`e `3`. `1 + 2 + 3 = 6`, então `6` é classificado como um número perfeito.
# --instructions--
Implement a function that calculates how many of the integers from `1` to `num` (inclusive) are in each of the three classes. Output the result as an array in the following format `[deficient, perfect, abundant]`.
Implementar uma função que calcule quantos números inteiros de `1` a `num` (inclusive) estão em cada uma das três classes. Exiba o resultado como um array no seguinte formato: `[deficient, perfect, abundant]`.
# --hints--
`getDPA` should be a function.
`getDPA` deve ser uma função.
```js
assert(typeof getDPA === 'function');
```
`getDPA(5000)` should return an array.
`getDPA(5000)` deve retornar um array.
```js
assert(Array.isArray(getDPA(5000)));
```
`getDPA(5000)` return array should have a length of `3`.
O array de retorno de `getDPA(5000)` deve ter tamanho `3`.
```js
assert(getDPA(5000).length === 3);
```
`getDPA(5000)` should return `[3758, 3, 1239]`.
`getDPA(5000)` deve retornar `[3758, 3, 1239]`.
```js
assert.deepEqual(getDPA(5000), [3758, 3, 1239]);
```
`getDPA(10000)` should return `[7508, 4, 2488]`.
`getDPA(10000)` deve retornar `[7508, 4, 2488]`.
```js
assert.deepEqual(getDPA(10000), [7508, 4, 2488]);
```
`getDPA(20000)` should return `[15043, 4, 4953]`.
`getDPA(20000)` deve retornar `[15043, 4, 4953]`.
```js
assert.deepEqual(getDPA(20000), [15043, 4, 4953]);

View File

@ -1,6 +1,6 @@
---
id: 594810f028c0303b75339ace
title: Accumulator factory
title: Fábrica de acumuladores
challengeType: 5
forumTopicId: 302222
dashedName: accumulator-factory
@ -8,41 +8,41 @@ dashedName: accumulator-factory
# --description--
A problem posed by [Paul Graham](https://en.wikipedia.org/wiki/Paul_Graham_(programmer)) is that of creating a function that takes a single (numeric) argument and which returns another function that is an accumulator. The returned accumulator function in turn also takes a single numeric argument, and returns the sum of all the numeric values passed in so far to that accumulator (including the initial value passed when the accumulator was created).
Um problema proposto por [Paul Graham](https://en.wikipedia.org/wiki/Paul_Graham_(programmer)) é o de criar uma função que recebe um único argumento (numérico) e que retorna outra função que é um acumulador. A função de acumulador retornada, por sua vez, também recebe um único argumento numérico e retorna a soma de todos os valores numéricos passados até aquele momento para esse acumulador (incluindo o valor inicial passado quando o acumulador foi criado).
# --instructions--
Create a function that takes a number $n$ and generates accumulator functions that return the sum of every number ever passed to them.
Crie uma função que receba um número $n$ e gere funções acumuladoras que retornam a soma de cada número já passado para elas.
**Rules:**
**Regras:**
Do not use global variables.
Não use variáveis globais.
**Hint:**
**Dica:**
Closures save outer state.
Closures salvam o estado externo.
# --hints--
`accumulator` should be a function.
`accumulator` deve ser uma função.
```js
assert(typeof accumulator === 'function');
```
`accumulator(0)` should return a function.
`accumulator(0)` deve retornar uma função.
```js
assert(typeof accumulator(0) === 'function');
```
`accumulator(0)(2)` should return a number.
`accumulator(0)(2)` deve retornar um número.
```js
assert(typeof accumulator(0)(2) === 'number');
```
Passing in the values 3, -4, 1.5, and 5 should return 5.5.
Ao passar os valores 3, -4, 1.5 e 5, o valor retornado deve ser 5.5.
```js
assert(testFn(5) === 5.5);

View File

@ -1,6 +1,6 @@
---
id: 594810f028c0303b75339acf
title: Ackermann function
title: Função de Ackermann
challengeType: 5
forumTopicId: 302223
dashedName: ackermann-function
@ -8,45 +8,45 @@ dashedName: ackermann-function
# --description--
The Ackermann function is a classic example of a recursive function, notable especially because it is not a primitive recursive function. It grows very quickly in value, as does the size of its call tree.
A função de Ackermann é um exemplo clássico de uma função recursiva, especialmente porque não é uma função recursiva primitiva. Ela cresce muito rapidamente em valor, assim como no tamanho da sua árvore de chamadas.
The Ackermann function is usually defined as follows:
A função de Ackermann é geralmente definida da seguinte forma:
$A(m, n) = \\begin{cases} n+1 & \\mbox{if } m = 0 \\\\ A(m-1, 1) & \\mbox{if } m > 0 \\mbox{ and } n = 0 \\\\ A(m-1, A(m, n-1)) & \\mbox{if } m > 0 \\mbox{ and } n > 0. \\end{cases}$
Its arguments are never negative and it always terminates.
Os argumentos nunca são negativos e sempre terminam.
# --instructions--
Write a function which returns the value of $A(m, n)$. Arbitrary precision is preferred (since the function grows so quickly), but not required.
Escreva uma função que retorne o valor de $A(m, n)$. A precisão arbitrária é a preferida aqui (já que a função cresce tão rapidamente), mas não é necessária.
# --hints--
`ack` should be a function.
`ack` deve ser uma função.
```js
assert(typeof ack === 'function');
```
`ack(0, 0)` should return 1.
`ack(0, 0)` deve retornar 1.
```js
assert(ack(0, 0) === 1);
```
`ack(1, 1)` should return 3.
`ack(1, 1)` deve retornar 3.
```js
assert(ack(1, 1) === 3);
```
`ack(2, 5)` should return 13.
`ack(2, 5)` deve retornar 13.
```js
assert(ack(2, 5) === 13);
```
`ack(3, 3)` should return 61.
`ack(3, 3)` deve retornar 61.
```js
assert(ack(3, 3) === 61);

View File

@ -1,6 +1,6 @@
---
id: 594810f028c0303b75339ad0
title: Align columns
title: Alinhar colunas
challengeType: 5
forumTopicId: 302224
dashedName: align-columns
@ -8,11 +8,11 @@ dashedName: align-columns
# --description--
Given an array of many lines, where fields within a line are delineated by a single `$` character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column.
Dado um array de muitas linhas, onde os campos dentro de uma linha são delineados por um único caractere `$`, escreva um programa que alinha cada coluna de campos, garantindo que as palavras em cada coluna estejam separadas por pelo menos um espaço. Além disso, permita que cada palavra em uma coluna seja deixada justificada à esquerda, justificada à direita ou justificada ao centro em sua coluna.
# --instructions--
Use the following text to test your programs:
Use o texto a seguir para testar seus programas:
```js
const testText = [
@ -29,16 +29,16 @@ const testText = [
];
```
**Note that:**
**Observe que:**
- The example input texts lines may, or may not, have trailing dollar characters.
- All columns should share the same alignment.
- Consecutive space characters produced adjacent to the end of lines are insignificant for the purposes of the task.
- Output text will be viewed in a mono-spaced font on a plain text editor or basic terminal. Lines in it should be joined using new line character (`\n`).
- The minimum space between columns should be computed from the text and not hard-coded.
- It is not a requirement to add separating characters between or around columns.
- As linhas de textos de entrada de exemplo podem, ou não, ter caracteres de dólar à frente.
- Todas as colunas devem compartilhar o mesmo alinhamento.
- Caracteres de espaço consecutivos adjacentes produzidos ao final das linhas são insignificantes para os propósitos da tarefa.
- O texto de saída será visto em uma fonte monoespaçada em um editor de texto simples ou em um terminal básico. As linhas nele devem ser unidas usando o caractere de nova linha (`\n`).
- O espaço mínimo entre colunas deve ser calculado a partir do texto e não inserido no código de antemão.
- Não é um requisito adicionar caracteres separados entre ou em torno das colunas.
For example, one of the lines from the `testText`, after jusitifing to the right, left and center respectivelly:
Por exemplo, uma das linhas do `testText`, após justificar à direita, à esquerda e ao centro, respectivamente, será:
```js
' column are separated by at least one space.\n'
@ -48,25 +48,25 @@ For example, one of the lines from the `testText`, after jusitifing to the right
# --hints--
`formatText` should be a function.
`formatText` deve ser uma função.
```js
assert(typeof formatText === 'function');
```
`formatText(testText, 'right')` should produce text with columns justified to the right.
`formatText(testText, 'right')` deve produzir texto com colunas justificadas à direita.
```js
assert.strictEqual(formatText(_testText, 'right'), rightAligned);
```
`formatText(testText, 'left')` should produce text with columns justified to the left.
`formatText(testText, 'left')` deve produzir texto com colunas justificadas à esquerda.
```js
assert.strictEqual(formatText(_testText, 'left'), leftAligned);
```
`formatText(testText, 'center')` should produce text with columns justified to the center.
`formatText(testText, 'center')` deve produzir texto com colunas justificadas ao centro.
```js
assert.strictEqual(formatText(_testText, 'center'), centerAligned);

View File

@ -1,6 +1,6 @@
---
id: 5949b579404977fbaefcd737
title: Amicable pairs
title: Pares amigáveis
challengeType: 5
forumTopicId: 302225
dashedName: amicable-pairs
@ -8,42 +8,42 @@ dashedName: amicable-pairs
# --description--
Two integers $N$ and $M$ are said to be [amicable pairs](https://en.wikipedia.org/wiki/Amicable numbers "wp: Amicable numbers") if $N \\neq M$ and the sum of the [proper divisors](https://rosettacode.org/wiki/Proper divisors "Proper divisors") of $N$ ($\\mathrm{sum}(\\mathrm{propDivs}(N))$) $= M$ as well as $\\mathrm{sum}(\\mathrm{propDivs}(M)) = N$.
Dizem que dois inteiros $N$ e $M$ são [pares amigáveis](https://en.wikipedia.org/wiki/Amicable numbers "wp: Amicable numbers") se $N \\neq M$ e a soma dos [divisores adequados](https://rosettacode.org/wiki/Proper divisors "Proper divisors") de $N$ ($\\mathrm{sum}(\\mathrm{propDivs}(N))$) $= M$, bem como $\\mathrm{sum}(\\mathrm{propDivs}(M)) = N$.
**Example:**
**Exemplo:**
**1184** and **1210** are an amicable pair, with proper divisors:
**1184** e **1210** são um par amigável, com divisores adequados:
<ul>
<li>1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 and</li>
<li>1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605 respectively.</li>
<li>1, 2, 4, 8, 16, 32, 37, 74, 148, 296, 592 e</li>
<li>1, 2, 5, 10, 11, 22, 55, 110, 121, 242, 605, respectivamente.</li>
</ul>
# --instructions--
Calculate and show here the Amicable pairs below 20,000 (there are eight).
Calcule e mostre aqui os pares amigáveis abaixo de 20.000 (há oito).
# --hints--
`amicablePairsUpTo` should be a function.
`amicablePairsUpTo` deve ser uma função.
```js
assert(typeof amicablePairsUpTo === 'function');
```
`amicablePairsUpTo(300)` should return `[[220,284]]`.
`amicablePairsUpTo(300)` deve retornar `[[220,284]]`.
```js
assert.deepEqual(amicablePairsUpTo(300), answer300);
```
`amicablePairsUpTo(3000)` should return `[[220,284],[1184,1210],[2620,2924]]`.
`amicablePairsUpTo(3000)` deve retornar `[[220,284],[1184,1210],[2620,2924]]`.
```js
assert.deepEqual(amicablePairsUpTo(3000), answer3000);
```
`amicablePairsUpTo(20000)` should return `[[220,284],[1184,1210],[2620,2924],[5020,5564],[6232,6368],[10744,10856],[12285,14595],[17296,18416]]`.
`amicablePairsUpTo(20000)` deve retornar `[[220,284],[1184,1210],[2620,2924],[5020,5564],[6232,6368],[10744,10856],[12285,14595],[17296,18416]]`.
```js
assert.deepEqual(amicablePairsUpTo(20000), answer20000);

View File

@ -1,6 +1,6 @@
---
id: 594d8d0ab97724821379b1e6
title: Averages/Mode
title: Médias/Moda
challengeType: 5
forumTopicId: 302226
dashedName: averagesmode
@ -8,27 +8,27 @@ dashedName: averagesmode
# --description--
Write a program to find the [mode](https://en.wikipedia.org/wiki/Mode (statistics) "wp: Mode (statistics)") value of a collection.
Escreva um programa que encontre o valor da [moda](https://en.wikipedia.org/wiki/Mode (statistics) "wp: Mode (statistics)") de uma coleção.
The case where the collection is empty may be ignored. Care must be taken to handle the case where the mode is non-unique.
O caso em que a coleção está vazia pode ser ignorado. É preciso ter cuidado para lidar com o caso em que a moda não é única.
If it is not appropriate or possible to support a general collection, use a vector (array), if possible. If it is not appropriate or possible to support an unspecified value type, use integers.
Se não for apropriado ou possível dar suporte a uma coleção geral, use um vetor (array), se possível. Se não é apropriado ou possível dar suporte a um tipo de valor não especificado, use números inteiros.
# --hints--
`mode` should be a function.
`mode` deve ser uma função.
```js
assert(typeof mode === 'function');
```
`mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])` should equal `[6]`
`mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])` deve ser igual a `[6]`
```js
assert.deepEqual(mode(arr1), [6]);
```
`mode([1, 2, 4, 4, 1])` should equal `[1, 4]`.
`mode([1, 2, 4, 4, 1])` deve ser igual a `[1, 4]`.
```js
assert.deepEqual(mode(arr2).sort(), [1, 4]);

View File

@ -1,6 +1,6 @@
---
id: 594d966a1467eb84194f0086
title: Averages/Pythagorean means
title: Média/Médias pitagóricas
challengeType: 5
forumTopicId: 302227
dashedName: averagespythagorean-means
@ -8,24 +8,24 @@ dashedName: averagespythagorean-means
# --description--
Compute all three of the [Pythagorean means](https://en.wikipedia.org/wiki/Pythagorean means "wp: Pythagorean means") of the set of integers $1$ through $10$ (inclusive).
Calcule as três [médias pitagóricas](https://en.wikipedia.org/wiki/Pythagorean means "wp: Pythagorean means") do conjunto de inteiros de $1$ a $10$ (inclusive).
Show that $A(x_1,\\ldots,x_n) \\geq G(x_1,\\ldots,x_n) \\geq H(x_1,\\ldots,x_n)$ for this set of positive integers.
Exiba $A(x_1,\\ldots,x_n) \\geq G(x_1,\\ldots,x_n) \\geq H(x_1,\\ldots,x_n)$ para este conjunto de inteiros positivos.
<ul>
<li>The most common of the three means, the <a class='rosetta__link--rosetta' href='https://rosettacode.org/wiki/Averages/Arithmetic mean' title='Averages/Arithmetic mean' target='_blank'>arithmetic mean</a>, is the sum of the list divided by its length:<br>
<li>A mais comum das três médias, a <a class='rosetta__link--rosetta' href='https://rosettacode.org/wiki/Averages/Arithmetic mean' title='Averages/Arithmetic mean' target='_blank'>média aritmética</a>, é a soma da lista dividida pelo seu tamanho:<br>
<big>$ A(x_1, \ldots, x_n) = \frac{x_1 + \cdots + x_n}{n}$</big></li>
<li>The <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Geometric mean' title='wp: Geometric mean' target='_blank'>geometric mean</a> is the $n$th root of the product of the list:<br>
<li>A <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Geometric mean' title='wp: Geometric mean' target='_blank'>média geométrica</a> é a $n$-ésima raiz do produto da lista:<br>
<big>$ G(x_1, \ldots, x_n) = \sqrt[n]{x_1 \cdots x_n} $</big></li>
<li>The <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Harmonic mean' title='wp: Harmonic mean' target='_blank'>harmonic mean</a> is $n$ divided by the sum of the reciprocal of each item in the list:<br>
<li>A <a class='rosetta__link--wiki' href='https://en.wikipedia.org/wiki/Harmonic mean' title='wp: Harmonic mean' target='_blank'>média harmônica</a> é $n$ dividido pela soma dos recíprocos de cada item da lista:<br>
<big>$ H(x_1, \ldots, x_n) = \frac{n}{\frac{1}{x_1} + \cdots + \frac{1}{x_n}} $</big></li>
</ul>
# --instructions--
When writing your function, assume the input is an ordered array of all inclusive numbers.
Ao escrever sua função, assuma que a entrada é um array ordenado incluindo todos os números.
For the answer, please output an object in the following format:
Para a resposta, dê como resultado um objeto com o seguinte formato:
```js
{
@ -40,13 +40,13 @@ For the answer, please output an object in the following format:
# --hints--
`pythagoreanMeans` should be a function.
`pythagoreanMeans` deve ser uma função.
```js
assert(typeof pythagoreanMeans === 'function');
```
`pythagoreanMeans([1, 2, ..., 10])` should equal the same output above.
`pythagoreanMeans([1, 2, ..., 10])` deve ser igual ao mesmo resultado acima.
```js
assert.deepEqual(pythagoreanMeans(range1), answer1);

View File

@ -1,6 +1,6 @@
---
id: 594da033de4190850b893874
title: Averages/Root mean square
title: Média/Valor eficaz
challengeType: 5
forumTopicId: 302228
dashedName: averagesroot-mean-square
@ -8,23 +8,23 @@ dashedName: averagesroot-mean-square
# --description--
Compute the [Root mean square](https://en.wikipedia.org/wiki/Root mean square "wp: Root mean square") of the numbers 1 through 10 inclusive.
Calcule o [vaor eficaz](https://en.wikipedia.org/wiki/Root mean square "wp: Root mean square") dos números de 1 a 10 inclusive.
The *root mean square* is also known by its initials RMS (or rms), and as the **quadratic mean**.
O *valor eficaz* (ou raiz do valor quadrático médio) também é conhecido por suas iniciais RMS (ou rms) e como **média quadrática**.
The RMS is calculated as the mean of the squares of the numbers, square-rooted:
O RMS é calculado como a raiz quadrada da média dos quadrados dos números:
$$x\_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\over n}. $$
$$x\_{\\mathrm{rms}} = \\sqrt {{{x_1}^2 + {x_2}^2 + \\cdots + {x_n}^2} \\sobre n}. $$
# --hints--
`rms` should be a function.
`rms` deve ser uma função.
```js
assert(typeof rms === 'function');
```
`rms([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])` should equal `6.2048368229954285`.
`rms([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])` deve ser igual a `6.2048368229954285`.
```js
assert.equal(rms(arr1), answer1);

View File

@ -1,6 +1,6 @@
---
id: 594db4d0dedb4c06a2a4cefd
title: Babbage problem
title: Problema de Babbage
challengeType: 5
forumTopicId: 302229
dashedName: babbage-problem
@ -8,30 +8,30 @@ dashedName: babbage-problem
# --description--
[Charles Babbage](https://en.wikipedia.org/wiki/Charles_Babbage "wp: Charles_Babbage"), looking ahead to the sorts of problems his Analytical Engine would be able to solve, gave this example:
[Charles Babbage](https://en.wikipedia.org/wiki/Charles_Babbage "wp: Charles_Babbage"), olhando para os tipos de problemas que seu mecanismo analítico poderia resolver, deu este exemplo:
<blockquote>
What is the smallest positive integer whose square ends in the digits 269,696?
<footer style='margin-left: 2em;'>Babbage, letter to Lord Bowden, 1837; see Hollingdale and Tootill, <i>Electronic Computers</i>, second edition, 1970, p. 125.</footer>
Qual é o menor inteiro positivo cujo quadrado termina nos dígitos 269.696?
<footer style='margin-left: 2em;'>Babbage, em carta ao Lord Bowden, 1837; veja Hollingdale e Tootill, <i>Electronic Computers</i>, segunda edição, 1970, p. 125.</footer>
</blockquote>
He thought the answer might be 99,736, whose square is 9,947,269,696; but he couldn't be certain.
Ele acreditava que a resposta seria 99.736, cujo quadrado é 9.947.269.696, mas ele não tinha certeza.
The task is to find out if Babbage had the right answer.
A tarefa é descobrir se Babbage achou a resposta certa.
# --instructions--
Implement a function to return the lowest integer that satisfies the Babbage problem. If Babbage was right, return Babbage's number.
Implemente uma função que retorna o menor inteiro que satisfaça o problema de Babbage. Se Babbage estava certo, retorne o número de Babbage.
# --hints--
`babbage` should be a function.
`babbage` deve ser uma função.
```js
assert(typeof babbage === 'function');
```
`babbage(99736, 269696)` should not return 99736 (there is a smaller answer).
`babbage(99736, 269696)` não deve retornar 99736 (existe uma resposta menor).
```js
assert.equal(babbage(babbageAns, endDigits), answer);

View File

@ -1,6 +1,6 @@
---
id: 594dc6c729e5700999302b45
title: Balanced brackets
title: Colchetes balanceados
challengeType: 5
forumTopicId: 302230
dashedName: balanced-brackets
@ -8,129 +8,129 @@ dashedName: balanced-brackets
# --description--
Determine whether a generated string of brackets is balanced; that is, whether it consists entirely of pairs of opening/closing brackets (in that order), none of which mis-nest.
Determine se uma sequência de colchetes gerada é equilibrada, ou seja, se consiste inteiramente de pares de colchetes de abertura/fechamento (nessa ordem), nenhum dos quais colocado incorretamente.
**Examples:**
| Input | Output |
| ------------------------- | ------ |
| <code>\[]</code> | true |
| <code>]\[</code> | false |
| <code>[][]</code> | true |
| <code>]\[]</code> | false |
| <code>\[]]\[\[]</code> | false |
| <code>\[\[\[\[]]]]</code> | true |
**Exemplos:**
| Entrada | Saída |
| ------------------------- | ----- |
| <code>\[]</code> | true |
| <code>]\[</code> | false |
| <code>[][]</code> | true |
| <code>]\[]</code> | false |
| <code>\[]]\[\[]</code> | false |
| <code>\[\[\[\[]]]]</code> | true |
# --hints--
`isBalanced` should be a function.
`isBalanced` deve ser uma função.
```js
assert(typeof isBalanced === 'function');
```
`isBalanced("[]")` should return true.
`isBalanced("[]")` deve retornar true.
```js
assert(isBalanced(testCases[0]));
```
`isBalanced("]][[[][][][]][")` should return false.
`isBalanced("]][[[][][][]][")` deve retornar false.
```js
assert(!isBalanced(testCases[1]));
```
`isBalanced("[][[[[][][[[]]]]]]")` should return true.
`isBalanced("[][[[[][][[[]]]]]]")` deve retornar true.
```js
assert(isBalanced(testCases[2]));
```
`isBalanced("][")` should return false.
`isBalanced("][")` deve retornar false.
```js
assert(!isBalanced(testCases[3]));
```
`isBalanced("[[[]]]][[]")` should return false.
`isBalanced("[[[]]]][[]")` deve retornar false.
```js
assert(!isBalanced(testCases[4]));
```
`isBalanced("][[]")` should return false.
`isBalanced("][[]")` deve retornar false.
```js
assert(!isBalanced(testCases[5]));
```
`isBalanced("][[][]][[[]]")` should return false.
`isBalanced("][[][]][[[]]")` deve retornar false.
```js
assert(!isBalanced(testCases[6]));
```
`isBalanced("[[][]]][")` should return false.
`isBalanced("[[][]]][")` deve retornar false.
```js
assert(!isBalanced(testCases[7]));
```
`isBalanced("[[[]]][[]]]][][[")` should return false.
`isBalanced("[[[]]][[]]]][][[")` deve retornar false.
```js
assert(!isBalanced(testCases[8]));
```
`isBalanced("[]][[]]][[[[][]]")` should return false.
`isBalanced("[]][[]]][[[[][]]")` deve retornar false.
```js
assert(!isBalanced(testCases[9]));
```
`isBalanced("][]][[][")` should return false.
`isBalanced("][]][[][")` deve retornar false.
```js
assert(!isBalanced(testCases[10]));
```
`isBalanced("[[]][[][]]")` should return true.
`isBalanced("[[]][[][]]")` deve retornar true.
```js
assert(isBalanced(testCases[11]));
```
`isBalanced("[[]]")` should return true.
`isBalanced("[[]]")` deve retornar true.
```js
assert(isBalanced(testCases[12]));
```
`isBalanced("]][]][[]][[[")` should return false.
`isBalanced("]][]][[]][[[")` deve retornar false.
```js
assert(!isBalanced(testCases[13]));
```
`isBalanced("][]][][[")` should return false.
`isBalanced("][]][][[")` deve retornar false.
```js
assert(!isBalanced(testCases[14]));
```
`isBalanced("][][")` should return false.
`isBalanced("][][")` deve retornar false.
```js
assert(!isBalanced(testCases[15]));
```
`isBalanced("[]]]")` should return false.
`isBalanced("[]]]")` deve retornar false.
```js
assert(!isBalanced(testCases[16]));
```
`isBalanced("")` should return true.
`isBalanced("")` deve retornar true.
```js
assert(isBalanced(testCases[17]));

View File

@ -1,6 +1,6 @@
---
id: 5951815dd895584b06884620
title: Circles of given radius through two points
title: Círculos de raio determinado através de dois pontos
challengeType: 5
forumTopicId: 302231
dashedName: circles-of-given-radius-through-two-points
@ -8,30 +8,30 @@ dashedName: circles-of-given-radius-through-two-points
# --description--
Given two points on a plane and a radius, usually two circles of given radius can be drawn through the points.
Dados dois pontos em um plano e num raio, geralmente dois círculos de um determinado raio podem ser traçados através dos pontos.
**Exceptions:**
**Exceções:**
<ul>
<li>A radius of zero should be treated as never describing circles (except in the case where the points are coincident).</li>
<li>If the points are coincident then an infinite number of circles with the point on their circumference can be drawn, unless the radius is equal to zero as well which then collapses the circles to a point.</li>
<li>If the points form a diameter then return a single circle.</li>
<li>If the points are too far apart then no circles can be drawn.</li>
<li>Um raio de zero deve ser tratado como nunca descrevendo círculos (exceto no caso em que os pontos são coincidentes).</li>
<li>Se os pontos forem coincidentes, pode haver um número infinito de círculos em que o ponto de sua circunferência pode ser desenhado, a não ser que o raio seja igual a zero, o que fará com que os círculos não passem de um ponto.</li>
<li>Se os pontos formarem um diâmetro, então retorne um único círculo.</li>
<li>Se os pontos estiverem muito distantes, não será possível desenhar os círculos.</li>
</ul>
# --instructions--
Implement a function that takes two points and a radius and returns the two circles through those points. For each resulting circle, provide the coordinates for the center of each circle rounded to four decimal digits. Return each coordinate as an array, and coordinates as an array of arrays.
Implementa uma função que recebe dois pontos e um raio e retorna os dois círculos através desses pontos. Para cada círculo resultante, forneça as coordenadas para o centro de cada círculo arredondadas para quatro casas decimais. Retorne cada coordenada como um array, e as coordenadas como um array de arrays.
**For edge cases, return the following:**
**Para casos extremos, retorne o seguinte:**
<ul>
<li>If points are on the diameter, return one point. If the radius is also zero however, return <code>"Radius Zero"</code>.</li>
<li>If points are coincident, return <code>"Coincident point. Infinite solutions"</code>.</li>
<li>If points are farther apart than the diameter, return <code>"No intersection. Points further apart than circle diameter"</code>.</li>
<li>Se os pontos estão no diâmetro, retorne um ponto. No entanto, se o raio também for zero, retorne <code>"Radius Zero"</code>.</li>
<li>Se os pontos forem coincidentes, retorne <code>"Coincident point. Infinite solutions"</code>.</li>
<li>Se os pontos estiverem mais distantes do que o diâmetro, retorne <code>"No intersection. Points further apart than circle diameter"</code>.</li>
</ul>
**Sample inputs:**
**Exemplo de entradas:**
<pre> p1 p2 r
0.1234, 0.9876 0.8765, 0.2345 2.0
@ -43,37 +43,37 @@ Implement a function that takes two points and a radius and returns the two circ
# --hints--
`getCircles` should be a function.
`getCircles` deve ser uma função.
```js
assert(typeof getCircles === 'function');
```
`getCircles([0.1234, 0.9876], [0.8765, 0.2345], 2.0)` should return `[[1.8631, 1.9742], [-0.8632, -0.7521]]`.
`getCircles([0.1234, 0.9876], [0.8765, 0.2345], 2.0)` deve retornar `[[1.8631, 1.9742], [-0.8632, -0.7521]]`.
```js
assert.deepEqual(getCircles(...testCases[0]), answers[0]);
```
`getCircles([0.0000, 2.0000], [0.0000, 0.0000], 1.0)` should return `[0, 1]`
`getCircles([0.0000, 2.0000], [0.0000, 0.0000], 1.0)` deve retornar `[0, 1]`
```js
assert.deepEqual(getCircles(...testCases[1]), answers[1]);
```
`getCircles([0.1234, 0.9876], [0.1234, 0.9876], 2.0)` should return `Coincident point. Infinite solutions`
`getCircles([0.1234, 0.9876], [0.1234, 0.9876], 2.0)` deve retornar `Coincident point. Infinite solutions`
```js
assert.deepEqual(getCircles(...testCases[2]), answers[2]);
```
`getCircles([0.1234, 0.9876], [0.8765, 0.2345], 0.5)` should return `No intersection. Points further apart than circle diameter`
`getCircles([0.1234, 0.9876], [0.8765, 0.2345], 0.5)` deve retornar `No intersection. Points further apart than circle diameter`
```js
assert.deepEqual(getCircles(...testCases[3]), answers[3]);
```
`getCircles([0.1234, 0.9876], [0.1234, 0.9876], 0.0)` should return `Radius Zero`
`getCircles([0.1234, 0.9876], [0.1234, 0.9876], 0.0)` deve retornar `Radius Zero`
```js
assert.deepEqual(getCircles(...testCases[4]), answers[4]);

View File

@ -1,6 +1,6 @@
---
id: 5951a53863c8a34f02bf1bdc
title: Closest-pair problem
title: Problema do par mais próximo
challengeType: 5
forumTopicId: 302232
dashedName: closest-pair-problem
@ -8,66 +8,66 @@ dashedName: closest-pair-problem
# --description--
Provide a function to find the closest two points among a set of given points in two dimensions.
Forneça uma função para encontrar os dois pontos mais próximos entre um conjunto de pontos dados em duas dimensões.
The straightforward solution is a $O(n^2)$ algorithm (which we can call *brute-force algorithm*); the pseudo-code (using indexes) could be simply:
A solução simples é um algoritmo $O(n^2)$ (que podemos chamar de *algoritmo de força bruta*). O pseudocódigo (usando índices) poderia ser, simplesmente:
<pre><strong>bruteForceClosestPair</strong> of P(1), P(2), ... P(N)
<strong>if</strong> N &#x3C; 2 <strong>then</strong>
<strong>return</strong>
<strong>else</strong>
<pre><strong>bruteForceClosestPair</strong> de P(1), P(2), ... P(N)
<strong>se</strong> N &#x3C; 2 <strong>então</strong>
<strong>retorne</strong>
<strong>senão</strong>
minDistance ← |P(1) - P(2)|
minPoints ← { P(1), P(2) }
<strong>foreach</strong> i ∈ [1, N-1]
<strong>foreach</strong> j ∈ [i+1, N]
<strong>if</strong> |P(i) - P(j)| &#x3C; minDistance <strong>then</strong>
<strong>paraCada</strong> i ∈ [1, N-1]
<strong>paraCada</strong> j ∈ [i+1, N]
<strong>se</strong> |P(i) - P(j)| &#x3C; minDistance <strong>então</strong>
minDistance ← |P(i) - P(j)|
minPoints ← { P(i), P(j) }
<strong>endif</strong>
<strong>endfor</strong>
<strong>endfor</strong>
<strong>return</strong> minDistance, minPoints
<strong>endif</strong>
<strong>fimSe</strong>
<strong>fimPara</strong>
<strong>fimPara</strong>
<strong>retorne</strong> minDistance, minPoints
<strong>fimSe</strong>
</pre>
A better algorithm is based on the recursive divide and conquer approach, which is $O(n\log n)$ a pseudo-code could be:
Um algoritmo melhor com base na abordagem recursiva de dividir e conquistar, com complexidade $O(n\log n)$, teria, como pseudocódigo:
<pre><strong>closestPair</strong> of (xP, yP)
where xP is P(1) .. P(N) sorted by x coordinate, and
yP is P(1) .. P(N) sorted by y coordinate (ascending order)
<strong>if</strong> N ≤ 3 <strong>then</strong>
<strong>return</strong> closest points of xP using brute-force algorithm
<strong>else</strong>
xL ← points of xP from 1 to ⌈N/2⌉
xR ← points of xP from ⌈N/2⌉+1 to N
<pre><strong>closestPair</strong> de (xP, yP)
onde xP é P(1) .. P(N) ordenado pela coordenada x, e
yP é P(1) .. P(N) ordenado pela coordenada y (ordem ascendente)
<strong>se</strong> N ≤ 3 <strong>então</strong>
<strong>retorne</strong> pontos mais próximos de xP usando o algoritmo de força bruta
<strong>senão</strong>
xL ← pontos de xP de 1 a ⌈N/2⌉
xR ← pontos de xP de ⌈N/2⌉+1 a N
xm ← xP(⌈N/2⌉)<sub>x</sub>
yL ← { p ∈ yP : p<sub>x</sub> ≤ xm }
yR ← { p ∈ yP : p<sub>x</sub> > xm }
(dL, pairL) ← closestPair of (xL, yL)
(dR, pairR) ← closestPair of (xR, yR)
(dL, pairL) ← closestPair de (xL, yL)
(dR, pairR) ← closestPair de (xR, yR)
(dmin, pairMin) ← (dR, pairR)
<strong>if</strong> dL &#x3C; dR <strong>then</strong>
<strong>se</strong> dL &#x3C; dR <strong>então</strong>
(dmin, pairMin) ← (dL, pairL)
<strong>endif</strong>
<strong>fimSe</strong>
yS ← { p ∈ yP : |xm - p<sub>x</sub>| &#x3C; dmin }
nS ← number of points in yS
nS ← número de pontos em yS
(closest, closestPair) ← (dmin, pairMin)
<strong>for</strong> i <strong>from</strong> 1 <strong>to</strong> nS - 1
<strong>para</strong> i <strong>de</strong> 1 <strong>a</strong> nS - 1
k ← i + 1
<strong>while</strong> k ≤ nS <strong>and</strong> yS(k)<sub>y</sub> - yS(i)<sub>y</sub> &#x3C; dmin
<strong>if</strong> |yS(k) - yS(i)| &#x3C; closest <strong>then</strong>
<strong>enquanto</strong> k ≤ nS <strong>e</strong> yS(k)<sub>y</sub> - yS(i)<sub>y</sub> &#x3C; dmin
<strong>se</strong> |yS(k) - yS(i)| &#x3C; closest <strong>então</strong>
(closest, closestPair) ← (|yS(k) - yS(i)|, {yS(k), yS(i)})
<strong>endif</strong>
<strong>fimSe</strong>
k ← k + 1
<strong>endwhile</strong>
<strong>endfor</strong>
<strong>return</strong> closest, closestPair
<strong>endif</strong>
<strong>fimEnquanto</strong>
<strong>fimPara</strong>
<strong>retorne</strong> closest, closestPair
<strong>fimSe</strong>
</pre>
For the input, expect the argument to be an array of `Point` objects with `x` and `y` members set to numbers. Return an object containing the key:value pairs for `distance` and `pair` (the pair of two closest points).
Para a entrada, espere que o argumento seja um array de objetos `Point` com membros `x` e `y` definidos como números. Retorna um objeto que contém os pares chave-valor de `distance` e `pair` (o par com os dois pontos mais próximos).
For example `getClosestPair` with input array `points`:
Por exemplo, `getClosestPair` com o array de entrada `points`:
```js
const points = [
@ -77,7 +77,7 @@ const points = [
];
```
Would return:
Retornaria:
```js
{
@ -95,24 +95,24 @@ Would return:
}
```
**Note:** Sort the `pair` array by their `x` values in incrementing order.
**Observação:** ordene o array de `pair` por seus valores em `x` na ordem de incrementação.
# --hints--
`getClosestPair` should be a function.
`getClosestPair` deve ser uma função.
```js
assert(typeof getClosestPair === 'function');
```
`getClosestPair(points1).distance` should be `0.0894096443343775`.
`getClosestPair(points1).distance` deve ser `0.0894096443343775`.
```js
assert.equal(getClosestPair(points1).distance, answer1.distance);
```
`getClosestPair(points1).pair` should be `[ { x: 7.46489, y: 4.6268 }, { x: 7.46911, y: 4.71611 } ]`.
`getClosestPair(points1).pair` deve ser `[ { x: 7.46489, y: 4.6268 }, { x: 7.46911, y: 4.71611 } ]`.
```js
assert.deepEqual(
@ -121,13 +121,13 @@ assert.deepEqual(
);
```
`getClosestPair(points2).distance` should be `65.06919393998976`.
`getClosestPair(points2).distance` deve ser `65.06919393998976`.
```js
assert.equal(getClosestPair(points2).distance, answer2.distance);
```
`getClosestPair(points2).pair` should be `[ { x: 37134, y: 1963 }, { x: 37181, y: 2008 } ]`.
`getClosestPair(points2).pair` deve ser `[ { x: 37134, y: 1963 }, { x: 37181, y: 2008 } ]`.
```js
assert.deepEqual(
@ -136,13 +136,13 @@ assert.deepEqual(
);
```
`getClosestPair(points3).distance` should be `6754.625082119658`.
`getClosestPair(points3).distance` deve ser `6754.625082119658`.
```js
assert.equal(getClosestPair(points3).distance, answer3.distance);
```
`getClosestPair(points3).pair` should be `[ { x: 46817, y: 64975 }, { x: 48953, y: 58567 } ]`.
`getClosestPair(points3).pair` deve ser `[ { x: 46817, y: 64975 }, { x: 48953, y: 58567 } ]`.
```js
assert.deepEqual(

View File

@ -1,6 +1,6 @@
---
id: 5958469238c0d8d2632f46db
title: Combinations
title: Combinações
challengeType: 5
forumTopicId: 302233
dashedName: combinations
@ -8,11 +8,11 @@ dashedName: combinations
# --description--
Given non-negative integers `m` and `n`, generate all size `m` combinations of the integers from `0` (zero) to `n-1` in sorted order (each combination is sorted and the entire table is sorted).
Dado os números inteiros não negativos `m` e `n`, gere todas as combinações de tamanho `m` dos inteiros de `0` (zero) a `n-1` em ordem (cada combinação é ordenada, assim como a tabela inteira).
**Example:**
**Exemplo:**
`3` comb `5` is:
`3` comb `5` é:
<pre>0 1 2
0 1 3
@ -28,19 +28,19 @@ Given non-negative integers `m` and `n`, generate all size `m` combinations of t
# --hints--
`combinations` should be a function.
`combinations` deve ser uma função.
```js
assert(typeof combinations === 'function');
```
`combinations(3, 5)` should return `[[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]`.
`combinations(3, 5)` deve retornar `[[0, 1, 2], [0, 1, 3], [0, 1, 4], [0, 2, 3], [0, 2, 4], [0, 3, 4], [1, 2, 3], [1, 2, 4], [1, 3, 4], [2, 3, 4]]`.
```js
assert.deepEqual(combinations(testInput1[0], testInput1[1]), testOutput1);
```
`combinations(4, 6)` should return `[[0,1,2,3], [0,1,2,4], [0,1,2,5], [0,1,3,4], [0,1,3,5], [0,1,4,5], [0,2,3,4], [0,2,3,5], [0,2,4,5], [0,3,4,5], [1,2,3,4], [1,2,3,5], [1,2,4,5], [1,3,4,5], [2,3,4,5]]`
`combinations(4, 6)` deve retornar `[[0,1,2,3], [0,1,2,4], [0,1,2,5], [0,1,3,4], [0,1,3,5], [0,1,4,5], [0,2,3,4], [0,2,3,5], [0,2,4,5], [0,3,4,5], [1,2,3,4], [1,2,3,5], [1,2,4,5], [1,3,4,5], [2,3,4,5]]`
```js
assert.deepEqual(combinations(testInput2[0], testInput2[1]), testOutput2);

View File

@ -1,6 +1,6 @@
---
id: 596e414344c3b2872167f0fe
title: Comma quibbling
title: Entre vírgulas
challengeType: 5
forumTopicId: 302234
dashedName: comma-quibbling
@ -8,63 +8,63 @@ dashedName: comma-quibbling
# --description--
Comma quibbling is a task originally set by Eric Lippert in his [blog](https://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx).
Entre vírgulas é uma tarefa originalmente criada por Eric Lippert em seu [blog](https://blogs.msdn.com/b/ericlippert/archive/2009/04/15/comma-quibbling.aspx).
# --instructions--
Write a function to generate a string output which is the concatenation of input words from a list/sequence where:
Escreva uma função para gerar uma saída de string que é a concatenação das palavras de entrada a partir de uma lista/sequência, onde:
<ol>
<li>An input of no words produces the output string of just the two brace characters (<code>"{}"</code>)</li>
<li>An input of just one word, e.g. <code>["ABC"]</code>, produces the output string of the word inside the two braces, e.g. <code>"{ABC}"</code></li>
<li>An input of two words, e.g. <code>["ABC", "DEF"]</code>, produces the output string of the two words inside the two braces with the words separated by the string <code>" and "</code>, e.g. <code>"{ABC and DEF}"</code></li>
<li>An input of three or more words, e.g. <code>["ABC", "DEF", "G", "H"]</code>, produces the output string of all but the last word separated by <code>", "</code> with the last word separated by <code>" and "</code> and all within braces; e.g. <code>"{ABC, DEF, G and H}"</code></li>
<li>Uma entrada sem palavra produz como string de saída apenas dois caracteres de chaves (<code>"{}"</code>)</li>
<li>Uma entrada de apenas uma palavra, por exemplo, <code>["ABC"]</code>, produz a string de saída com a palavra dentro de duas chaves. <code>"{ABC}"</code></li>
<li>Uma entrada de duas palavras, por exemplo, <code>["ABC", "DEF"]</code>, produz uma string de saída com as duas palavras dentro de duas chaves com as palavras separadas pela string <code>" and "</code>, por exemplo, <code>"{ABC and DEF}"</code></li>
<li>Uma entrada de três ou mais palavras, por exemplo <code>["ABC", "DEF", "G", "H"]</code>, produz a string de saída de todas elas separadas por <code>", "</code>, exceto a última palavra, que é separada por <code>" and "</code>, com todas elas dentro de duas chaves, por exemplo, <code>"{ABC, DEF, G and H}"</code></li>
</ol>
Test your function with the following series of inputs showing your output here on this page:
Teste sua função com a série de entradas a seguir mostrando a saída aqui nesta página:
<ul>
<li>[] # (No input words).</li>
<li>[] # (Sem palavras de entrada).</li>
<li>["ABC"]</li>
<li>["ABC", "DEF"]</li>
<li>["ABC", "DEF", "G", "H"]</li>
</ul>
**Note:** Assume words are non-empty strings of uppercase characters for this task.
**Observação:** assuma que as palavras são strings não vazias de caracteres maiúsculos para esta tarefa.
# --hints--
`quibble` should be a function.
`quibble` deve ser uma função.
```js
assert(typeof quibble === 'function');
```
`quibble(["ABC"])` should return a string.
`quibble(["ABC"])` deve retornar uma string.
```js
assert(typeof quibble(['ABC']) === 'string');
```
`quibble([])` should return "{}".
`quibble([])` deve retornar "{}".
```js
assert.equal(quibble(testCases[0]), results[0]);
```
`quibble(["ABC"])` should return "{ABC}".
`quibble(["ABC"])` deve retornar "{ABC}".
```js
assert.equal(quibble(testCases[1]), results[1]);
```
`quibble(["ABC", "DEF"])` should return "{ABC and DEF}".
`quibble(["ABC", "DEF"])` deve retornar "{ABC and DEF}".
```js
assert.equal(quibble(testCases[2]), results[2]);
```
`quibble(["ABC", "DEF", "G", "H"])` should return "{ABC,DEF,G and H}".
`quibble(["ABC", "DEF", "G", "H"])` deve retornar "{ABC,DEF,G and H}".
```js
assert.equal(quibble(testCases[3]), results[3]);

View File

@ -1,6 +1,6 @@
---
id: 596e457071c35c882915b3e4
title: Compare a list of strings
title: Comparar uma lista de strings
challengeType: 5
forumTopicId: 302235
dashedName: compare-a-list-of-strings
@ -8,82 +8,82 @@ dashedName: compare-a-list-of-strings
# --description--
Given a [list](https://en.wikipedia.org/wiki/List_(abstract_data_type) "wp: List\_(abstract_data_type)") of arbitrarily many strings, implement a function for each of the following conditions:
Dada uma [lista](https://en.wikipedia.org/wiki/List_(abstract_data_type) "wp: List\_(abstract_data_type)") de várias strings arbitrárias, implemente uma função para cada uma das seguintes condições:
<ul>
<li>test if they are all lexically equal</li>
<li>test if every string is lexically less than the one after it (i.e. whether the list is in strict ascending order)</li>
<li>testar se todas são lexicalmente iguais</li>
<li>testar se cada string é lexicalmente menor do que a string imediatamente posterior (ou seja, se a lista está em ordem ascendente estrita)</li>
</ul>
# --hints--
`allEqual` should be a function.
`allEqual` deve ser uma função.
```js
assert(typeof allEqual === 'function');
```
`azSorted` should be a function.
`azSorted` deve ser uma função.
```js
assert(typeof azSorted === 'function');
```
`allEqual(["AA", "AA", "AA", "AA"])` should return true.
`allEqual(["AA", "AA", "AA", "AA"])` deve retornar true.
```js
assert(allEqual(testCases[0]));
```
`azSorted(["AA", "AA", "AA", "AA"])` should return false.
`azSorted(["AA", "AA", "AA", "AA"])` deve retornar false.
```js
assert(!azSorted(testCases[0]));
```
`allEqual(["AA", "ACB", "BB", "CC"])` should return false.
`allEqual(["AA", "ACB", "BB", "CC"])` deve retornar false.
```js
assert(!allEqual(testCases[1]));
```
`azSorted(["AA", "ACB", "BB", "CC"])` should return true.
`azSorted(["AA", "ACB", "BB", "CC"])` deve retornar true.
```js
assert(azSorted(testCases[1]));
```
`allEqual([])` should return true.
`allEqual([])` deve retornar true.
```js
assert(allEqual(testCases[2]));
```
`azSorted([])` should return true.
`azSorted([])` deve retornar true.
```js
assert(azSorted(testCases[2]));
```
`allEqual(["AA"])` should return true.
`allEqual(["AA"])` deve retornar true.
```js
assert(allEqual(testCases[3]));
```
`azSorted(["AA"])` should return true.
`azSorted(["AA"])` deve retornar true.
```js
assert(azSorted(testCases[3]));
```
`allEqual(["BB", "AA"])` should return false.
`allEqual(["BB", "AA"])` deve retornar false.
```js
assert(!allEqual(testCases[4]));
```
`azSorted(["BB", "AA"])` should return false.
`azSorted(["BB", "AA"])` deve retornar false.
```js
assert(!azSorted(testCases[4]));