chore(i18n,curriculum): update translations (#43267)
This commit is contained in:
@ -46,7 +46,7 @@ Here's a <a href="https://www.freecodecamp.org" target="_blank">link to www.free
|
||||
|
||||
# --instructions--
|
||||
|
||||
Annida l'elemento `a` esistente all'interno di un nuovo elemento `p`. Il nuovo paragrafo dovrebbe contenere un testo che dice `View more cat photos`, dove `cat photos` è un collegamento, e il resto è testo semplice.
|
||||
Annida l'elemento `a` esistente all'interno di un nuovo elemento `p`. Non creare un nuovo elemento di ancoraggio. Il nuovo paragrafo dovrebbe contenere testo che dice `View more cat photos`, dove `cat photos` è un collegamento, e il resto è testo semplice.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -27,7 +27,7 @@ Se si omette l'attributo `value`, i dati del modulo inviato usano il valore pred
|
||||
|
||||
# --instructions--
|
||||
|
||||
Dai a ciascuno degli input `radio` e `checkbox` l'attributo `value`. Usa il testo dell'etichetta, in minuscolo, come valore per l'attributo.
|
||||
Dai a ciascuno degli elementi di input esistenti di tipo `radio` e `checkbox` l'attributo `value`. Non creare alcun nuovo elemento radio o casella di controllo. Usa il testo dell'etichetta, in minuscolo, come valore per l'attributo.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -8,7 +8,7 @@ dashedName: render-conditionally-from-props
|
||||
|
||||
# --description--
|
||||
|
||||
Fino ad ora hai visto come usare `if/else`, `&&`, e l'operatore ternario (`condition ? expressionIfTrue : expressionIfFalse`) per fare decisioni condizionali su cosa e quando presentare. Tuttavia, c'è ancora un argomento importante da discutere che consente di combinare uno o tutti questi concetti con un'altra potente funzionalità di React: le props. Usare le proprietà (props) per presentare il codice condizionalmente è molto comune tra gli sviluppatori di React — cioè essi usano il valore di una determinata proprietà per prendere automaticamente delle decisioni su cosa presentare.
|
||||
Finora, hai visto come usare `if/else`, `&&`, e l'operatore ternario (`condition ? expressionIfTrue : expressionIfFalse`) per prendere decisioni condizionali su cosa presentare e quando. Tuttavia, c'è ancora un argomento importante da discutere che consente di combinare uno o tutti questi concetti con un'altra potente funzionalità di React: le props. Usare le proprietà (props) per presentare il codice condizionalmente è molto comune tra gli sviluppatori di React — cioè essi usano il valore di una determinata proprietà per prendere automaticamente delle decisioni su cosa presentare.
|
||||
|
||||
In questa sfida, configurerai un componente figlio per prendere decisioni di rendering basate sulle props. Utilizzerai anche l'operatore ternario, ma puoi vedere come molti degli altri concetti che sono stati trattati nelle ultime sfide potrebbero essere altrettanto utili in questo contesto.
|
||||
|
||||
|
@ -8,7 +8,7 @@ dashedName: copy-an-object-with-object-assign
|
||||
|
||||
# --description--
|
||||
|
||||
Le ultime sfide funzionavano con gli array, ma ci sono modi per aiutare a far rispettare l'immutabilità dello stato anche quando esso è un `object`. Uno strumento utile per gestire gli oggetti è l'utilità `Object.assign()`. `Object.assign()` prende un oggetto di destinazione e degli oggetti di origine e mappa le proprietà dagli oggetti di origine all'oggetto di destinazione. Tutte le proprietà corrispondenti sono sovrascritte dalle proprietà degli oggetti sorgente. Questo comportamento è comunemente usato per fare copie superficiali di oggetti passando un oggetto vuoto come primo argomento seguito dall'oggetto o dagli oggetti che si desidera copiare. Ecco un esempio:
|
||||
Le ultime sfide funzionavano con gli array, ma ci sono modi per aiutare a far rispettare l'immutabilità dello stato anche quando esso è un `object`. Uno strumento utile per gestire gli oggetti è l'utilità `Object.assign()`. `Object.assign()` prende un oggetto di destinazione e degli oggetti di origine e mappa le proprietà dagli oggetti di origine all'oggetto di destinazione. Tutte le proprietà corrispondenti sono sovrascritte dalle proprietà degli oggetti sorgente. Questo comportamento è comunemente usato per fare copie superficiali di oggetti passando un oggetto vuoto come primo argomento seguito dall'oggetto o dagli oggetti che si desidera copiare. Qui un esempio:
|
||||
|
||||
```js
|
||||
const newObject = Object.assign({}, obj1, obj2);
|
||||
|
@ -10,7 +10,7 @@ dashedName: handle-an-action-in-the-store
|
||||
|
||||
Dopo che un'azione è stata creata e spedita, lo store di Redux deve sapere come rispondere a quell'azione. Questo è il lavoro di una funzione `reducer` (riduttore). I reducer in Redux sono responsabili delle modifiche allo stato che si verificano in risposta alle azioni. Un `reducer` prende `state` e `action` come argomenti, e restituisce sempre un nuovo `state`. È importante capire che questo è l'**unico** ruolo del reducer. Questo non ha effetti collaterali - non chiama mai un endpoint API e non ha mai sorprese nascoste. Il reducer è semplicemente una funzione pura che prende uno stato e un'azione, e restituisce un nuovo stato.
|
||||
|
||||
Un altro principio chiave in Redux è che lo `state` è di sola lettura. In altre parole, la funzione `reducer` deve **sempre** restituire una nuova copia dello `state` e non modificare mai direttamente lo state. Redux non applica l'immutabilità dello stato, tuttavia sei responsabile di applicarlo nel codice delle tue funzioni reducer. Nelle prossime sfide farai pratica con questo.
|
||||
Un altro principio chiave in Redux è che lo `state` è di sola lettura. In altre parole, la funzione `reducer` deve **sempre** restituire una nuova copia dello `state` e non modificare mai direttamente lo state. Redux non forza l'immutabilità dello stato, tuttavia sei responsabile di applicarlo nel codice delle tue funzioni reducer. Nelle prossime sfide farai pratica con questo.
|
||||
|
||||
# --instructions--
|
||||
|
||||
|
@ -12,7 +12,7 @@ Queste ultime sfide descrivono diversi metodi per far rispettare il principio fo
|
||||
|
||||
Se scattassi un'istantanea dello stato di un'applicazione Redux nel tempo, vedresti qualcosa come `state 1`, `state 2`, `state 3`,`state 4`, `...` e così via dove ogni stato può essere simile al precedente, ma ognuno è un dato distinto. Questa immutabilità, infatti, è ciò che fornisce caratteristiche come il debugging time-travel (viaggio nel tempo) di cui potresti aver sentito parlare.
|
||||
|
||||
Redux non applica attivamente l'immutabilità dello stato nel suo store o nei reducer: questa responsabilità ricade sul programmatore. Fortunatamente, JavaScript (specialmente ES6) fornisce diversi strumenti utili che puoi usare per far rispettare l'immutabilità del tuo stato, che si tratti di una `string`, `number`, `array` o `object`. Nota che le stringhe e i numeri sono valori primitivi e sono immutabili per natura. In altre parole, 3 è sempre 3. Non è possibile modificare il valore del numero 3. Un `array` o `object`, invece, è mutabile. In pratica, il tuo stato sarà probabilmente costituito da un `array` o da un `object`, trattandosi di strutture di dati utili per rappresentare molti tipi di informazioni.
|
||||
Redux non obbliga attivamente l'immutabilità dello stato nel suo store o nei reducer: questa responsabilità ricade sul programmatore. Fortunatamente, JavaScript (specialmente ES6) fornisce diversi strumenti utili che puoi usare per far rispettare l'immutabilità del tuo stato, che si tratti di una `string`, `number`, `array` o `object`. Nota che le stringhe e i numeri sono valori primitivi e sono immutabili per natura. In altre parole, 3 è sempre 3. Non è possibile modificare il valore del numero 3. Un `array` o `object`, invece, è mutabile. In pratica, il tuo stato sarà probabilmente costituito da un `array` o da un `object`, trattandosi di strutture di dati utili per rappresentare molti tipi di informazioni.
|
||||
|
||||
# --instructions--
|
||||
|
||||
|
@ -32,7 +32,7 @@ Ci sarebbe molto da digitare per riscrivere questa regola per tutti gli elementi
|
||||
}
|
||||
```
|
||||
|
||||
La definizione inizia con `@mixin` seguito da un nome personalizzato. I parametri ( `$x`, `$y`, `$blur`e `$c` nell'esempio sopra) sono opzionali. Ora ogni volta che è necessaria una regola `box-shadow`, invece di dover digitare tutti i prefissi dei venditori dovremo solo scrivere una singola linea che chiama il mixin. Un mixin è chiamato con la direttiva `@include`:
|
||||
La definizione inizia con `@mixin` seguito da un nome personalizzato. I parametri ( `$x`, `$y`, `$blur`e `$c` nell'esempio sopra) sono opzionali. Ora ogni volta che è necessaria una regola `box-shadow`, invece di dover digitare tutti i prefissi dei venditori dovremo scrivere una singola linea che chiama il mixin. Un mixin è chiamato con la direttiva `@include`:
|
||||
|
||||
```scss
|
||||
div {
|
||||
|
@ -30,7 +30,7 @@ Supponi ora di volere un altro pannello chiamato `.big-panel`. Ha le stesse prop
|
||||
}
|
||||
```
|
||||
|
||||
Il `.big-panel` avrà le stesse proprietà di `.panel` in aggiunta ai nuovi stili.
|
||||
`.big-panel` avrà le stesse proprietà di `.panel` in aggiunta ai nuovi stili.
|
||||
|
||||
# --instructions--
|
||||
|
||||
|
@ -26,7 +26,7 @@ nav ul li {
|
||||
}
|
||||
```
|
||||
|
||||
Per un grande progetto però, il file CSS avrà molte linee e regole. Questo è dove la nidificazione può aiutare a organizzare il codice inserendo le regole di stile figlie all'interno dei rispettivi elementi genitori:
|
||||
Per un grande progetto però, il file CSS avrà molte linee e regole. Qui la nidificazione può aiutare a organizzare il codice inserendo le regole di stile figlie all'interno dei rispettivi elementi genitori:
|
||||
|
||||
```scss
|
||||
nav {
|
||||
@ -45,7 +45,7 @@ nav {
|
||||
|
||||
# --instructions--
|
||||
|
||||
Utilizzare la tecnica di nidificazione mostrata sopra per riorganizzare le regole CSS per entrambi i figli dell'elemento `.blog-post`. Ai fini dei test, l'elemento `h1` dovrebbe venire prima dell'elemento `p`.
|
||||
Utilizza la tecnica di nidificazione mostrata sopra per riorganizzare le regole CSS per entrambi i figli dell'elemento `.blog-post`. Ai fini dei test, l'elemento `h1` dovrebbe venire prima dell'elemento `p`.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -32,7 +32,7 @@ Un esempio in cui le variabili sono utili è quando un certo numero di elementi
|
||||
|
||||
# --instructions--
|
||||
|
||||
Crea una variabile `$text-color` e impostala su `red`. Quindi cambiare il valore della proprietà `color` per il `.blog-post` e per `h2` impostandoli alla variabile `$text-color`.
|
||||
Crea una variabile `$text-color` e impostala su `red`. Quindi cambia il valore della proprietà `color` per `.blog-post` e per `h2` impostandoli alla variabile `$text-color`.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dbf367417b2b2512bba
|
||||
title: Usare @each per iterare sugli elementi in una lista
|
||||
title: Usare @each per iterare sugli elementi di una lista
|
||||
challengeType: 0
|
||||
forumTopicId: 301461
|
||||
dashedName: use-each-to-map-over-items-in-a-list
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dbe367417b2b2512bb8
|
||||
title: Usare @if e @else per aggiungere logica ai tuoi stili
|
||||
title: Usare @if e @else per aggiungere logica agli stili
|
||||
challengeType: 0
|
||||
forumTopicId: 301463
|
||||
dashedName: use-if-and-else-to-add-logic-to-your-styles
|
||||
|
@ -12,13 +12,55 @@ Costruisci un'app JavaScript full-stack che sia funzionalmente simile a questa:
|
||||
|
||||
- Clonare [questa repository GitHub](https://github.com/freeCodeCamp/boilerplate-project-exercisetracker/) e completa il tuo progetto localmente.
|
||||
- Usare [la nostra bozza di progetto su Replit](https://replit.com/github/freeCodeCamp/boilerplate-project-exercisetracker) per completare il tuo progetto.
|
||||
- Usare un costruttore di siti di tua scelta per completare il progetto. Assicurati di incorporare tutti i file della nostra repository GitHub.
|
||||
- Usare un costruttore di siti di tua scelta per completare il progetto. Assicurati di incorporare tutti i file del nostro repository GitHub.
|
||||
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata pubblicamente da qualche parte. Quindi invia l'URL nel campo `Solution Link`. Facoltativamente, invia anche un link al codice sorgente del tuo progetto nel campo `GitHub Link`.
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata in qualche percorso pubblico. Quindi invia l'URL nel campo `Solution Link`. Facoltativamente, invia anche un link al codice sorgente del tuo progetto nel campo `GitHub Link`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Le tue risposte dovrebbero avere le seguenti strutture.
|
||||
|
||||
Exercise:
|
||||
|
||||
```js
|
||||
{
|
||||
username: "fcc_test"
|
||||
description: "test",
|
||||
duration: 60,
|
||||
date: "Mon Jan 01 1990",
|
||||
_id: "5fb5853f734231456ccb3b05"
|
||||
}
|
||||
```
|
||||
|
||||
User:
|
||||
|
||||
```js
|
||||
{
|
||||
username: "fcc_test",
|
||||
_id: "5fb5853f734231456ccb3b05"
|
||||
}
|
||||
```
|
||||
|
||||
Log:
|
||||
|
||||
```js
|
||||
{
|
||||
username: "fcc_test",
|
||||
count: 1,
|
||||
_id: "5fd01a41c5b5cf05d080502f",
|
||||
log: [{
|
||||
description: "test",
|
||||
duration: 60,
|
||||
date: "Mon Jan 01 1990",
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
**Suggerimento:** Per la prorpietà `date`, puoi usare il metodo `toDateString` della API `Date` per ottenere l'output previsto.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti inviare il tuo progetto, non l'URL di esempio.
|
||||
È necessario fornire il proprio progetto, non l'URL di esempio.
|
||||
|
||||
```js
|
||||
(getUserInput) => {
|
||||
|
@ -12,9 +12,9 @@ Costruisci un'app JavaScript full-stack che sia funzionalmente simile a questa:
|
||||
|
||||
- Clonare [questa repository GitHub](https://github.com/freeCodeCamp/boilerplate-project-filemetadata/) e completare il tuo progetto localmente.
|
||||
- Usare [la nostra bozza di progetto su Replit](https://replit.com/github/freeCodeCamp/boilerplate-project-filemetadata) per completare il tuo progetto.
|
||||
- Usare un costruttore di siti di tua scelta per completare il progetto. Assicurati di incorporare tutti i file della nostra repository GitHub.
|
||||
- Usare un costruttore di siti di tua scelta per completare il progetto. Assicurati di incorporare tutti i file del nostro repository GitHub.
|
||||
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata da qualche parte di pubblico. Quindi invia l'URL nel campo `Solution Link`. Facoltativamente, invia anche un link al codice sorgente dei tuoi progetti nel campo `GitHub Link`.
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata in qualche percorso pubblico. Quindi invia l'URL nel campo `Solution Link`. Facoltativamente, invia anche un link al codice sorgente dei tuoi progetti nel campo `GitHub Link`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
|
@ -12,9 +12,9 @@ Costruisci un'app JavaScript full-stack che sia funzionalmente simile a questa:
|
||||
|
||||
- Clonare [questa repository GitHub](https://github.com/freeCodeCamp/boilerplate-project-headerparser/) e completare il tuo progetto localmente.
|
||||
- Usare [la nostra bozza di progetto su Replit](https://replit.com/github/freeCodeCamp/boilerplate-project-headerparser) per completare il tuo progetto.
|
||||
- Usare un costruttore di siti di tua scelta per completare il progetto. Assicurati di incorporare tutti i file della nostra repository GitHub.
|
||||
- Usare un costruttore di siti di tua scelta per completare il progetto. Assicurati di incorporare tutti i file del nostro repository GitHub.
|
||||
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata da qualche parte di pubblico. Quindi invia l'URL nel campo `Solution Link`. Facoltativamente, invia anche un link al codice sorgente del tuo progetto nel campo `GitHub Link`.
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata in qualche percorso pubblico. Quindi invia l'URL nel campo `Solution Link`. Facoltativamente, invia anche un link al codice sorgente del tuo progetto nel campo `GitHub Link`.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -12,9 +12,9 @@ Costruisci un'app JavaScript full-stack che sia funzionalmente simile a questa:
|
||||
|
||||
- Clonare [questa repository GitHub](https://github.com/freeCodeCamp/boilerplate-project-timestamp/) e completare il tuo progetto localmente.
|
||||
- Usare [la nostra bozza di progetto su Replit](https://replit.com/github/freeCodeCamp/boilerplate-project-timestamp) per completare il tuo progetto.
|
||||
- Usare un costruttore di siti di tua scelta per completare il progetto. Assicurati di incorporare tutti i file della nostra repository GitHub.
|
||||
- Usare un costruttore di siti di tua scelta per completare il progetto. Assicurati di incorporare tutti i file del nostro repository GitHub.
|
||||
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata da qualche parte di pubblico. Quindi invia l'URL nel campo `Solution Link`. Facoltativamente, invia anche un link al codice sorgente dei tuoi progetti nel campo `GitHub Link`.
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata in qualche percorso pubblico. Quindi invia l'URL nel campo `Solution Link`. Facoltativamente, invia anche un link al codice sorgente dei tuoi progetti nel campo `GitHub Link`.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -12,9 +12,9 @@ Costruisci un'app JavaScript full-stack che sia funzionalmente simile a questa:
|
||||
|
||||
- Clonare [questa repository GitHub](https://github.com/freeCodeCamp/boilerplate-project-urlshortener/) e completare il tuo progetto localmente.
|
||||
- Usare [la nostra bozza di progetto su Replit](https://replit.com/github/freeCodeCamp/boilerplate-project-urlshortener) per completare il tuo progetto.
|
||||
- Usare un costruttore di siti di tua scelta per completare il progetto. Assicurati di incorporare tutti i file della nostra repository GitHub.
|
||||
- Usare un costruttore di siti di tua scelta per completare il progetto. Assicurati di incorporare tutti i file del nostro repository GitHub.
|
||||
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata da qualche parte di pubblico. Quindi invia l'URL nel campo `Solution Link`. Facoltativamente, invia anche un link al codice sorgente dei tuoi progetti nel campo `GitHub Link`.
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata in qualche percorso pubblico. Quindi invia l'URL nel campo `Solution Link`. Facoltativamente, invia anche un link al codice sorgente dei tuoi progetti nel campo `GitHub Link`.
|
||||
|
||||
# --instructions--
|
||||
|
||||
|
@ -10,7 +10,7 @@ dashedName: chain-middleware-to-create-a-time-server
|
||||
|
||||
Il middleware può essere montato su un percorso specifico utilizzando `app.METHOD(path, middlewareFunction)`. Il middleware può anche essere concatenato all'interno della definizione del percorso.
|
||||
|
||||
Guarda l'esempio seguente:
|
||||
Considera l'esempio seguente:
|
||||
|
||||
```js
|
||||
app.get('/user', function(req, res, next) {
|
||||
|
@ -12,9 +12,9 @@ Lavorare su queste sfide ti porterà a scrivere il tuo codice utilizzando uno de
|
||||
|
||||
- Clonare [questo repository GitHub](https://github.com/freeCodeCamp/boilerplate-express/) e completare queste sfide localmente.
|
||||
- Usare [la nostra bozza di progetto su Replit](https://replit.com/github/freeCodeCamp/boilerplate-express) per completare queste sfide.
|
||||
- Usa un costruttore di siti di tua scelta per completare il progetto. Assicurati di incorporare tutti i file della nostra repository GitHub.
|
||||
- Usare un costruttore di siti di tua scelta per completare il progetto. Assicurati di incorporare tutti i file del nostro repository GitHub.
|
||||
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata da qualche parte di pubblico. Quindi invia l'URL nel campo `Solution Link`.
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata in qualche percorso pubblico. Quindi invia l'URL nel campo `Solution Link`.
|
||||
|
||||
Durante il processo di sviluppo, è importante essere in grado di controllare cosa sta succedendo nel tuo codice.
|
||||
|
||||
|
@ -8,7 +8,7 @@ dashedName: add-a-version-to-your-package-json
|
||||
|
||||
# --description--
|
||||
|
||||
`version` è uno dei campi obbligatori del file package.json. Questo campo descrive la versione corrente del tuo progetto. Ecco un esempio:
|
||||
`version` è uno dei campi obbligatori del file package.json. Questo campo descrive la versione corrente del tuo progetto. Qui un esempio:
|
||||
|
||||
```json
|
||||
"version": "1.2.0",
|
||||
|
@ -8,7 +8,7 @@ dashedName: add-keywords-to-your-package-json
|
||||
|
||||
# --description--
|
||||
|
||||
Il campo `keywords` è dove puoi descrivere il tuo progetto usando le parole chiave correlate. Ecco un esempio:
|
||||
Il campo `keywords` è dove puoi descrivere il tuo progetto usando le parole chiave correlate. Qui un esempio:
|
||||
|
||||
```json
|
||||
"keywords": [ "descriptive", "related", "words" ],
|
||||
|
@ -12,9 +12,9 @@ Lavorare su queste sfide ti porterà a scrivere il tuo codice utilizzando uno de
|
||||
|
||||
- Clonare [questo repository GitHub](https://github.com/freeCodeCamp/boilerplate-npm/) e completare queste sfide localmente.
|
||||
- Usare [la nostra bozza di progetto su Replit](https://replit.com/github/freeCodeCamp/boilerplate-npm) per completare queste sfide.
|
||||
- Usare un costruttore di siti a tua scelta per completare il progetto. Assicurati di incorporare tutti i file dal nostro repository GitHub.
|
||||
- Usare un costruttore di siti di tua scelta per completare il progetto. Assicurati di incorporare tutti i file del nostro repository GitHub.
|
||||
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata pubblicamente da qualche parte. Quindi invia l'URL nel campo `Solution Link`. Facoltativamente, invia anche un link al codice sorgente del tuo progetto nel campo `GitHub Link`.
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata in qualche percorso pubblico. Quindi invia l'URL nel campo `Solution Link`. Facoltativamente, invia anche un link al codice sorgente del tuo progetto nel campo `GitHub Link`.
|
||||
|
||||
Il file `package.json` è il centro di qualsiasi progetto Node.js o pacchetto npm. Memorizza informazioni sul tuo progetto, in modo simile a come la sezione <head> di un documento HTML descrive il contenuto di una pagina web. Consiste di un singolo oggetto JSON dove le informazioni sono memorizzate in coppie chiave-valore. Ci sono solo due campi obbligatori; "name" e "version", ma è buona pratica fornire ulteriori informazioni sul tuo progetto che potrebbero essere utili per futuri utenti o manutentori.
|
||||
|
||||
|
@ -12,9 +12,9 @@ Lavorare su queste sfide ti porterà a scrivere il tuo codice utilizzando uno de
|
||||
|
||||
- Clonare [questo repository GitHub](https://github.com/freeCodeCamp/boilerplate-mongomongoose/) e completare queste sfide localmente.
|
||||
- Usare [la nostra bozza di progetto su Replit](https://replit.com/github/freeCodeCamp/boilerplate-mongomongoose) per completare queste sfide.
|
||||
- Usa un costruttore di siti a tua scelta per completare il progetto. Assicurati di incorporare tutti i file dal nostro repository GitHub.
|
||||
- Usare un costruttore di siti di tua scelta per completare il progetto. Assicurati di incorporare tutti i file del nostro repository GitHub.
|
||||
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata pubblicamente da qualche parte. Quindi invia l'URL nel campo `Solution Link`.
|
||||
Quando hai finito, assicurati che una demo funzionante del tuo progetto sia ospitata in qualche percorso pubblico. Quindi invia l'URL nel campo `Solution Link`.
|
||||
|
||||
In questa sfida, imposterai un database MongoDB Atlas e importerai i pacchetti necessari per connetterti ad esso.
|
||||
|
||||
|
@ -8,15 +8,17 @@ dashedName: run-functional-tests-on-an-api-response-using-chai-http-iv---put-met
|
||||
|
||||
# --description--
|
||||
|
||||
Come promemoria, questo progetto verrà costruito a partire dalla seguente bozza su [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), o clonato da [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/). Questo esercizio è simile a quello precedente. Guardalo per i dettagli.
|
||||
Come promemoria, questo progetto verrà costruito a partire dalla seguente bozza su [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), o clonato da [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
|
||||
|
||||
Ora che hai visto come si fa, tocca a te farlo da zero.
|
||||
Questo esercizio è simile a quello precedente.
|
||||
|
||||
Ora che sai come testare una richiesta `PUT`, è il tuo turno di farlo da zero.
|
||||
|
||||
# --instructions--
|
||||
|
||||
All'interno di `tests/2_functional-tests.js`, modifica il test `'send {surname: "da Verrazzano"}'` (`// #4`):
|
||||
All'interno di `tests/2_functional-tests.js`, cambia il test `'Send {surname: "da Verrazzano"}'` (`// #4`) e usa i metodi `put` e `send` per testare l'endpoint `'/travellers'`.
|
||||
|
||||
Invia la seguente risposta JSON come carico utile sulla rotta `/travellers`:
|
||||
Invia il seguente oggetto JSON con la tua richiesta PUT:
|
||||
|
||||
```json
|
||||
{
|
||||
@ -26,16 +28,16 @@ Invia la seguente risposta JSON come carico utile sulla rotta `/travellers`:
|
||||
|
||||
Controlla quanto segue, all'interno della callback `request.end`:
|
||||
|
||||
1. `status`
|
||||
2. `type`
|
||||
3. `body.name`
|
||||
4. `body.surname`
|
||||
1. Lo `status` dovrebbe essere `200`
|
||||
2. Il `type` dovrebbe essere `application/json`
|
||||
3. Il `body.name` dovrebbe essere `Giovanni`
|
||||
4. Il `body.surname` dovrebbe essere `da Verrazzano`
|
||||
|
||||
Segui l'ordine di asserzione indicato sopra - facciamo affidamento su di esso. Assicurati di rimuovere `assert.fail()`, una volta finito.
|
||||
Segui l'ordine di asserzione indicato sopra - facciamo affidamento su di esso. Inoltre, assicurati di rimuovere `assert.fail()` una volta completato.
|
||||
|
||||
# --hints--
|
||||
|
||||
Tutti i test dovrebbero essere superati
|
||||
Tutti i test dovrebbero passare
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -49,7 +51,7 @@ Tutti i test dovrebbero essere superati
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti verificare che 'res.status' sia 200
|
||||
Dovresti verificare che `res.status` sia 200
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -65,7 +67,7 @@ Dovresti verificare che 'res.status' sia 200
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti verificare che 'res.type' sia 'application/json'
|
||||
Dovresti verificare che `res.type` sia `'application/json'`
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -81,7 +83,7 @@ Dovresti verificare che 'res.type' sia 'application/json'
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti verificare che 'res.body.name' sia 'Giovanni'
|
||||
Dovresti verificare che `res.body.name` sia `'Giovanni'`
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -97,7 +99,7 @@ Dovresti verificare che 'res.body.name' sia 'Giovanni'
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti verificare che 'res.body.surname' sia 'da Verrazzano''
|
||||
Dovresti verificare che `res.body.surname` sia `'da Verrazzano'`
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -12,9 +12,9 @@ Come promemoria, questo progetto verrà costruito a partire dalla seguente bozza
|
||||
|
||||
# --instructions--
|
||||
|
||||
All'interno di `tests/2_functional-tests.js`, modifica il test `'Test GET /hello with your name'` (`// #2`) per asserire che le risposte `status` e `text` facciano passare i test.
|
||||
All'interno di `tests/2_functional-tests.js`, modifica il test `'Test GET /hello with your name'` (`// #2`) per asserire che lo `status` e il `text` della risposta facciano passare i test.
|
||||
|
||||
Invia il tuo nome nella query, aggiungendo `?name=<your_name>` alla rotta. L'endpoint risponde con `'hello <your_name>'`.
|
||||
Invia il tuo nome come query URL, aggiungendo `?name=<your_name>` alla rotta. L'endpoint risponde con `'hello <your_name>'`.
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -32,7 +32,7 @@ Tutti i test dovrebbero essere superati
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti verificare che 'res.status' == 200
|
||||
Dovresti verificare che `res.status` sia 200
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -48,7 +48,7 @@ Dovresti verificare che 'res.status' == 200
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti verificare che 'res.text' == 'hello Guest'
|
||||
Dovresti verificare che `res.text` == `'hello <your_name>'`
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -10,41 +10,40 @@ dashedName: run-functional-tests-on-api-endpoints-using-chai-http
|
||||
|
||||
Come promemoria, questo progetto verrà costruito a partire dalla seguente bozza su [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), o clonato da [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
|
||||
|
||||
Mocha consente di testare operazioni asincrone. C'è una piccola (GRANDE) differenza. Riesce a individuarla?
|
||||
Mocha consente di testare le operazioni asincrone come le chiamate agli endpoint API con un plugin chiamato `chai-http`.
|
||||
|
||||
Possiamo testare i nostri endpoint API utilizzando un plugin, chiamato `chai-http`. Vediamo come funziona. E ricorda, le chiamate API sono asincrone.
|
||||
|
||||
Il seguente è un esempio di test che utilizza `chai-http` per la suite `'GET /hello?name=[name] => "hello [name]"'`. Il test invia un nome in una stringa di query URL (`?name=John`) utilizzando una richiesta `GET` al `server`. Nella funzione di callback del metodo `end`, l'oggetto di risposta (`res`) viene ricevuto e contiene la proprietà `status`. Il primo `assert.equal` controlla se lo stato è pari a `200`. Il secondo `assert.equal` verifica che la stringa di risposta (`res.text`) sia uguale a `"hello John"`.
|
||||
Il seguente esempio è un esempio di test che utilizza `chai-http` per una suite chiamata `'GET /hello?name=[name] => "hello [name]"'`:
|
||||
|
||||
```js
|
||||
suite('GET /hello?name=[name] => "hello [name]"', function () {
|
||||
test("?name=John", function (done) {
|
||||
test('?name=John', function (done) {
|
||||
chai
|
||||
.request(server)
|
||||
.get("/hello?name=John")
|
||||
.get('/hello?name=John')
|
||||
.end(function (err, res) {
|
||||
assert.equal(res.status, 200, "response status should be 200");
|
||||
assert.equal(
|
||||
res.text,
|
||||
"hello John",
|
||||
'response should be "hello John"'
|
||||
);
|
||||
assert.equal(res.status, 200, 'Response status should be 200');
|
||||
assert.equal(res.text, 'hello John', 'Response should be "hello John"');
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
Nota il parametro `done` nella funzione di callback del test. Chiamarlo alla fine senza un argomento è necessario per segnalare il successo del completamento asincrono.
|
||||
Il test invia una richiesta `GET` al server con un nome come stringa di ricerca URL (`?name=John`). Nella funzione di callback del metodo `end`, l'oggetto di risposta (`res`) viene ricevuto e contiene la proprietà `status`.
|
||||
|
||||
Il primo `assert.equal` controlla se lo stato è pari a `200`. Il secondo `assert.equal` verifica che la stringa di risposta (`res.text`) sia uguale a `"hello John"`.
|
||||
|
||||
Inoltre, nota il parametro `done` nella funzione di callback del test. Chiamarlo senza un argomento alla fine di un test è necessario per segnalare che l'operazione asincrona è completa.
|
||||
|
||||
# --instructions--
|
||||
|
||||
All'interno di `tests/2_functional-tests.js`, modifica il test `'Test GET /hello with no name'` (`// #1`) per asserire che le risposte `status` e `text` facciano passare i test. Non alterare gli argomenti passati alle asserzioni.
|
||||
All'interno di `tests/2_functional-tests.js`, modifica il test `'Test GET /hello with no name'` (`// #1`) per asserire che lo `status` e il `text` della risposta facciano passare i test. Non alterare gli argomenti passati alle asserzioni.
|
||||
|
||||
Non ci dovrebbe essere alcun nome nella query; l'endpoint risponde con `hello Guest`.
|
||||
Non ci dovrebbe essere una URL di query. Senza un nome nella query URL, l'endpoint risponde con `hello Guest`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Tutti i test dovrebbero essere superati
|
||||
Tutti i test dovrebbero passare
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -58,7 +57,7 @@ Tutti i test dovrebbero essere superati
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti verificare che 'res.status' == 200
|
||||
Dovresti verificare che `res.status` sia 200
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@ -74,7 +73,7 @@ Dovresti verificare che 'res.status' == 200
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti testare che 'res.text' == 'hello Guest'
|
||||
Dovresti verificare che `res.text` == `'hello Guest'`
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
@ -12,17 +12,17 @@ Come promemoria, questo progetto verrà costruito a partire dalla seguente bozza
|
||||
|
||||
# --instructions--
|
||||
|
||||
All'interno di `tests/2_functional-tests.js`, nel test `'submit "surname" : "Vespucci" - write your e2e test...'` (`// #6`), automatizza la compilazione e invia il modulo:
|
||||
All'interno di `tests/2_functional-tests.js`, nel `'Submit the surname "Vespucci" in the HTML form'` test (`// #5`), automatizza quanto segue:
|
||||
|
||||
1. Compila il modulo con il `surname` di `Vespucci`
|
||||
2. Invia premendo il pulsante `'submit'`
|
||||
1. Compila il modulo con il cognome `Vespucci`
|
||||
2. Premi il pulsante submit
|
||||
|
||||
All'interno della callback:
|
||||
E all'interno della callback `pressButton`:
|
||||
|
||||
1. asserisci che lo stato è `200`
|
||||
2. asserisci che il testo all'interno dell'elemento `span#name` è `'Amerigo'`
|
||||
3. asserisci che il testo all'interno dell'elemento `span#surname` è `'Vespucci'`
|
||||
4. asserisci che gli elementi `span#dates` esistono e il loro conteggio è `1`
|
||||
1. Asserisci che lo stato sia OK `200`
|
||||
2. Asserisci che il testo all'interno dell'elemento `span#name` è `'Amerigo'`
|
||||
3. Asserisci che il testo all'interno dell'elemento `span#surname` è `'Vespucci'`
|
||||
4. Asserisci che gli elementi `span#dates` esistono e il loro conteggio è `1`
|
||||
|
||||
Non dimenticare di rimuovere la chiamata `assert.fail()`.
|
||||
|
||||
@ -32,7 +32,7 @@ Tutti i test dovrebbero essere superati.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=5').then(
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=6').then(
|
||||
(data) => {
|
||||
assert.equal(data.state, 'passed');
|
||||
},
|
||||
@ -46,7 +46,7 @@ Dovresti asserire che la richiesta dell'headless browser sia riuscita.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=5').then(
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=6').then(
|
||||
(data) => {
|
||||
assert.equal(data.assertions[0].method, 'browser.success');
|
||||
},
|
||||
@ -56,11 +56,11 @@ Dovresti asserire che la richiesta dell'headless browser sia riuscita.
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti asserire che il testo all'interno dell'elemento 'span#name' sia 'Amerigo'.
|
||||
Dovresti controllare che il testo all'interno dell'elemento `span#name` è `'Amerigo'`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=5').then(
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=6').then(
|
||||
(data) => {
|
||||
assert.equal(data.assertions[1].method, 'browser.text');
|
||||
assert.match(data.assertions[1].args[0], /('|")span#name\1/);
|
||||
@ -72,11 +72,11 @@ Dovresti asserire che il testo all'interno dell'elemento 'span#name' sia 'Amerig
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti asserire che il testo all'interno dell'elemento 'span#surname' sia 'Vespucci'.
|
||||
Dovresti verificare che il testo all'interno dell'elemento `span#surname` è `'Vespucci'`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=5').then(
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=6').then(
|
||||
(data) => {
|
||||
assert.equal(data.assertions[2].method, 'browser.text');
|
||||
assert.match(data.assertions[2].args[0], /('|")span#surname\1/);
|
||||
@ -88,11 +88,11 @@ Dovresti asserire che il testo all'interno dell'elemento 'span#surname' sia 'Ves
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti asserire che l'elemento 'span#dates' esista e il suo conteggio sia 1.
|
||||
Dovresti affermare che l'elemento `span#dates` esiste e il suo conteggio è 1.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=5').then(
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=6').then(
|
||||
(data) => {
|
||||
assert.equal(data.assertions[3].method, 'browser.elements');
|
||||
assert.match(data.assertions[3].args[0], /('|")span#dates\1/);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8250367417b2b2512c5d
|
||||
title: Eseguire test funzionali usando un headless browser
|
||||
title: Eseguire test funzionali utilizzando un browser senza intestazione
|
||||
challengeType: 2
|
||||
forumTopicId: 301595
|
||||
dashedName: run-functional-tests-using-a-headless-browser
|
||||
@ -10,23 +10,31 @@ dashedName: run-functional-tests-using-a-headless-browser
|
||||
|
||||
Come promemoria, questo progetto verrà costruito a partire dalla seguente bozza su [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), o clonato da [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
|
||||
|
||||
Nella vista principale HTML abbiamo fornito un modulo di input. Esso invia con una richiesta Ajax i dati all'endpoint `PUT /travellers` che abbiamo usato sopra. Quando la richiesta è completata con successo, il codice client aggiunge un `<div>` contenente le informazioni restituite dalla chiamata al DOM. Ecco un esempio di come interagire con questo modulo:
|
||||
Nella pagina c'è un modulo di inserimento. Esso invia i dati all'endpoint `PUT /travellers` come richiesta AJAX.
|
||||
|
||||
Quando la richiesta è completata con successo, il codice client aggiunge al DOM un `<div>` contenente le informazioni nella risposta.
|
||||
|
||||
Ecco un esempio di come usare Zombie.js per interagire con il modulo:
|
||||
|
||||
```js
|
||||
test('#test - submit the input "surname" : "Polo"', function (done) {
|
||||
browser.fill('surname', 'Polo').pressButton('submit', function () {
|
||||
test('Submit the surname "Polo" in the HTML form', function (done) {
|
||||
browser.fill('surname', 'Polo').then(() => {
|
||||
browser.pressButton('submit', () => {
|
||||
browser.assert.success();
|
||||
browser.assert.text('span#name', 'Marco');
|
||||
browser.assert.text('span#surname', 'Polo');
|
||||
browser.assert.elements('span#dates', 1);
|
||||
done();
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
In primo luogo, il metodo `fill` dell'oggetto `browser` compila il campo `surname` del modulo con il valore `'Polo'`. Subito dopo, il metodo `pressButton` invoca l'event lister `submit` del modulo. Il metodo `pressButton` è asincrono.
|
||||
Per prima cosa, il metodo `fill` dell'oggetto `browser` compila il campo `surname` del modulo con il valore `'Polo'`. `fill` restituisce una promessa, quindi `then` viene incatenato fuori.
|
||||
|
||||
Poi, una volta ricevuta una risposta dalla richiesta AJAX, vengono fatte alcune asserzioni, confermando che:
|
||||
All'interno della callback `then`, il metodo `pressButton` dell'oggetto `browser` viene utilizzato per invocare l'event listener `submit` del modulo. Il metodo `pressButton` è asincrono.
|
||||
|
||||
Poi, una volta ricevuta una risposta dalla richiesta AJAX, vengono fatte alcune asserzioni confermando:
|
||||
|
||||
1. Lo stato della risposta è `200`
|
||||
2. Il testo all'interno dell'elemento `<span id='name'></span>` corrisponde a `'Marco'`
|
||||
@ -37,17 +45,17 @@ Infine, viene invocata la callback `done`, che è necessaria a causa del test as
|
||||
|
||||
# --instructions--
|
||||
|
||||
All'interno di `tests/2_functional-tests.js`, nel test `'submit "surname" : "Colombo" - write your e2e test...'` (`// #5`), automatizza la compilazione e invia il modulo:
|
||||
All'interno di `tests/2_functional-tests.js`, nel test `'Submit the surname "Colombo" in the HTML form'` (`// #5`), automatizza quanto segue:
|
||||
|
||||
1. Compila il modulo
|
||||
2. Invia premendo il pulsante `'submit'`.
|
||||
1. Compila il modulo con il cognome `Colombo`
|
||||
2. Premi il pulsante submit
|
||||
|
||||
All'interno della callback:
|
||||
E all'interno della callback `pressButton`:
|
||||
|
||||
1. asserisci che lo stato è OK `200`
|
||||
2. asserisci che il testo all'interno dell'elemento `span#name` è `'Cristoforo'`
|
||||
3. asserisci che il testo all'interno dell'elemento `span#surname` è `'Colombo'`
|
||||
4. asserisci che gli elementi `span#dates` esistono e il loro conteggio è `1`
|
||||
1. Asserisci che lo stato sia OK `200`
|
||||
2. Asserisci che il testo all'interno dell'elemento `span#name` sia `'Cristoforo'`
|
||||
3. Asserisci che il testo all'interno dell'elemento `span#surname` sia `'Colombo'`
|
||||
4. Asserisci che gli elementi `span#dates` esistono e il loro conteggio è `1`
|
||||
|
||||
Non dimenticare di rimuovere la chiamata `assert.fail()`.
|
||||
|
||||
@ -57,7 +65,7 @@ Tutti i test dovrebbero essere superati.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=4').then(
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=5').then(
|
||||
(data) => {
|
||||
assert.equal(data.state, 'passed');
|
||||
},
|
||||
@ -71,7 +79,7 @@ Dovresti asserire che la richiesta dell'headless browser sia riuscita.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=4').then(
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=5').then(
|
||||
(data) => {
|
||||
assert.equal(data.assertions[0].method, 'browser.success');
|
||||
},
|
||||
@ -81,11 +89,11 @@ Dovresti asserire che la richiesta dell'headless browser sia riuscita.
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti asserire che il testo all'interno dell'elemento 'span#name' sia 'Cristoforo'.
|
||||
Dovresti asserire che il testo all'interno dell'elemento `span#name` è `'Cristoforo'`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=4').then(
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=5').then(
|
||||
(data) => {
|
||||
assert.equal(data.assertions[1].method, 'browser.text');
|
||||
assert.match(data.assertions[1].args[0], /('|")span#name\1/);
|
||||
@ -97,11 +105,11 @@ Dovresti asserire che il testo all'interno dell'elemento 'span#name' sia 'Cristo
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti asserire che il testo all'interno dell'elemento 'span#surname' sia 'Colombo'.
|
||||
Dovresti asserire che il testo all'interno dell'elemento `span#surname` è `'Colombo'`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=4').then(
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=5').then(
|
||||
(data) => {
|
||||
assert.equal(data.assertions[2].method, 'browser.text');
|
||||
assert.match(data.assertions[2].args[0], /('|")span#surname\1/);
|
||||
@ -113,11 +121,11 @@ Dovresti asserire che il testo all'interno dell'elemento 'span#surname' sia 'Col
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti asserire che l'elemento 'span#dates' esiste e il suo conteggio sia 1.
|
||||
Dovresti affermare che l'elemento `span#dates` esiste e il suo conteggio è 1.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=4').then(
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=5').then(
|
||||
(data) => {
|
||||
assert.equal(data.assertions[3].method, 'browser.elements');
|
||||
assert.match(data.assertions[3].args[0], /('|")span#dates\1/);
|
||||
|
@ -9,37 +9,35 @@ dashedName: simulate-actions-using-a-headless-browser
|
||||
|
||||
Come promemoria, questo progetto verrà costruito a partire dalla seguente bozza su [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), o clonato da [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
|
||||
|
||||
Nelle prossime sfide simuleremo l'interazione umana con una pagina utilizzando un dispositivo chiamato 'Headless Browser' (browser senza testa).
|
||||
Nelle prossime sfide, simulerai l'interazione umana con una pagina utilizzando un headless browser (browser senza testa).
|
||||
|
||||
Un headless browser è un browser web senza interfaccia utente grafica. Questo tipo di strumento è particolarmente utile per testare le pagine web, poiché è in grado di renderizzare e capire HTML, CSS, e JavaScript proprio come farebbe un browser.
|
||||
I browser senza intestazione sono browser web senza interfaccia grafica. Essi sono in grado di visualizzare e interpretare HTML, CSS, e JavaScript allo stesso modo in cui farebbe un browser normale, rendendoli particolarmente utili per testare le pagine web.
|
||||
|
||||
Per queste sfide stiamo usando Zombie.JS. È un browser leggero che è totalmente basato su JS, che non richiede binari aggiuntivi da installare. Questa funzione lo rende utilizzabile in un ambiente come Replit. Ci sono molte altre opzioni (più potenti).
|
||||
Per le seguenti sfide userai Zombie.js, che è un browser senza testa leggero che non si basa su binari aggiuntivi da installare. Questa funzione lo rende utilizzabile in ambienti limitati come Replit. Ma ci sono molte altre, più potenti opzioni di browser senza intestazione.
|
||||
|
||||
Mocha ti consente di preparare il terreno eseguendo del codice prima dei test effettivi. Questo può essere utile, ad esempio, per creare elementi nel database, che saranno utilizzati nei test successivi.
|
||||
Mocha consente di eseguire qualche codice prima dell'effettiva esecuzione dei test. Questo può essere utile per fare cose come aggiungere voci a un database che sarà utilizzato nel resto dei test.
|
||||
|
||||
Con un headless browser, prima del test effettivo, abbiamo bisogno di **visitare** la pagina che stiamo per controllare. L'hook' `suiteSetup` viene eseguito solo una volta all'avvio della suite. Altri tipi di hook possono essere esuiti prima di ogni test, dopo ogni test, o alla fine della suite. Vedi la documentazione di Mocha per maggiori informazioni.
|
||||
Con un browser senza testa, prima di eseguire i test, è necessario **visitare** la pagina da testare.
|
||||
|
||||
L'hook `suiteSetup` viene eseguito solo una volta all'inizio di una suite di test.
|
||||
|
||||
Ci sono diversi altri tipi di hook che possono eseguire il codice prima di ogni test, dopo ogni test, o alla fine di una suite di test. Vedi la documentazione di Mocha per maggiori informazioni.
|
||||
|
||||
# --instructions--
|
||||
|
||||
All'interno di `tests/2_functional-tests.js`, immediatamente dopo la dichiarazione `Browser`, aggiungi l'URL del tuo progetto alla proprietà `site` della variabile:
|
||||
|
||||
```js
|
||||
Browser.site = 'https://sincere-cone.gomix.me'; // Your URL here
|
||||
Browser.site = 'https://boilerplate-mochachai.your-username.repl.co'; // Your URL here
|
||||
```
|
||||
|
||||
Se stai testando su un ambiente locale, sostituisci la riga precedente con
|
||||
|
||||
```js
|
||||
Browser.localhost('example.com', process.env.PORT || 3000);
|
||||
```
|
||||
|
||||
All'interno di `tests/2_functional-tests.js`, al livello root della suite `'Functional Tests with Zombie.js'`, crea una nuova istanza dell'oggetto `Browser` con il seguente codice:
|
||||
Poi al livello di root della suite `'Functional Tests with Zombie.js'`, instanzia una nuova istanza dell'oggetto `Browser` con il seguente codice:
|
||||
|
||||
```js
|
||||
const browser = new Browser();
|
||||
```
|
||||
|
||||
Quindi, utilizza l'hook `suiteSetup` per indirizzare il `browser` al percorso `/` con il seguente codice:
|
||||
E usa l'hook `suiteSetup` per indirizzare il `browser` al percorso `/` con il seguente codice:
|
||||
|
||||
```js
|
||||
suiteSetup(function(done) {
|
||||
@ -53,11 +51,9 @@ Tutti i test dovrebbero essere superati.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional').then(
|
||||
$.get(getUserInput('url') + '/_api/get-tests?type=functional&n=4').then(
|
||||
(data) => {
|
||||
data.slice(0, 4).forEach((test) => {
|
||||
assert.equal(test.state, 'passed');
|
||||
})
|
||||
assert.equal(data.state, 'passed');
|
||||
},
|
||||
(xhr) => {
|
||||
throw new Error(xhr.responseText);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 602da04c22201c65d2a019f4
|
||||
title: Number Guessing Game
|
||||
title: Gioco di indovinare il numero
|
||||
challengeType: 12
|
||||
helpCategory: Relational Databases
|
||||
url: https://github.com/moT01/.number-guessing-game
|
||||
|
@ -8,7 +8,7 @@ dashedName: write-arrow-functions-with-parameters
|
||||
|
||||
# --description--
|
||||
|
||||
Assim como uma função normal, você pode passar argumentos para uma função de seta.
|
||||
Assim como uma função normal, você pode passar argumentos para uma arrow function.
|
||||
|
||||
```js
|
||||
const doubler = (item) => item * 2;
|
||||
@ -17,13 +17,13 @@ doubler(4);
|
||||
|
||||
`doubler(4)` retornaria o valor `8`.
|
||||
|
||||
Se uma função de seta tiver um único parâmetro, os parênteses envolvendo o parâmetro podem ser omitidos.
|
||||
Se uma arrow function tiver um único parâmetro, os parênteses envolvendo o parâmetro podem ser omitidos.
|
||||
|
||||
```js
|
||||
const doubler = item => item * 2;
|
||||
```
|
||||
|
||||
É possível passar mais de um argumento para uma função de seta.
|
||||
É possível passar mais de um argumento para uma arrow function.
|
||||
|
||||
```js
|
||||
const multiplier = (item, multi) => item * multi;
|
||||
@ -50,7 +50,7 @@ Você deve substituir a palavra-chave `var`.
|
||||
(getUserInput) => assert(getUserInput('index').match(/const\s+myConcat/g));
|
||||
```
|
||||
|
||||
`myConcat` deve ser uma função de seta com dois parâmetros
|
||||
`myConcat` deve ser uma arrow function com dois parâmetros
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -28,7 +28,7 @@ Quando o React encontra uma tag HTML personalizada que faz referência a outro c
|
||||
|
||||
No editor de código, há um simples componente funcional chamado `ChildComponent` e um componente de classe chamado `ParentComponent`. Componha as duas juntas ao renderizar o `ChildComponent` dentro do `ParentComponent`. Certifique-se de fechar a tag `ChildComponent` com uma barra avançada.
|
||||
|
||||
**Observação:** `ChildComponent` é definida com uma arrow function do ES6, porque esta é uma prática muito comum ao usar React. No entanto, é do conhecimento geral que se trata apenas de uma função. Se você não estiver familiarizado com a sintaxe de função de seta, consulte a seção de JavaScript.
|
||||
**Observação:** `ChildComponent` é definida com uma arrow function do ES6, porque esta é uma prática muito comum ao usar React. No entanto, é do conhecimento geral que se trata apenas de uma função. Se você não estiver familiarizado com a sintaxe de arrow function, consulte a seção de JavaScript.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3d61000cf542c50fee8
|
||||
title: 'Problem 105: Special subset sums: testing'
|
||||
title: 'Problema 105: Somas especiais de subconjuntos: testes'
|
||||
challengeType: 5
|
||||
forumTopicId: 301729
|
||||
dashedName: problem-105-special-subset-sums-testing
|
||||
@ -8,20 +8,20 @@ dashedName: problem-105-special-subset-sums-testing
|
||||
|
||||
# --description--
|
||||
|
||||
Let $S(A)$ represent the sum of elements in set A of size n. We shall call it a special sum set if for any two non-empty disjoint subsets, B and C, the following properties are true:
|
||||
Considere que $S(A)$ representa a soma dos elementos no conjunto A, de tamanho n. Vamos chamá-la de uma soma especial definida se, para dois subconjuntos disjuntos, B e C, as seguintes propriedades são verdadeiras:
|
||||
|
||||
1. $S(B) ≠ S(C)$; that is, sums of subsets cannot be equal.
|
||||
2. If B contains more elements than C then $S(B) > S(C)$.
|
||||
1. $S(B) ≠ S(C)$; isto é, as somas de subconjuntos não podem ser iguais.
|
||||
2. Se B contém mais elementos que C, $S(B) > S(C)$.
|
||||
|
||||
For example, {81, 88, 75, 42, 87, 84, 86, 65} is not a special sum set because 65 + 87 + 88 = 75 + 81 + 84, whereas {157, 150, 164, 119, 79, 159, 161, 139, 158} satisfies both rules for all possible subset pair combinations and $S(A) = 1286$.
|
||||
Por exemplo, {81, 88, 75, 42, 87, 84, 86, 65} não é uma soma especial porque 65 + 87 + 88 = 75 + 81 + 84, enquanto {157, 150, 164, 119, 79, 159, 161, 139, 158} satisfaz as duas regras para todas as combinações possíveis de pares de subconjuntos e $S(A) = 1286$.
|
||||
|
||||
Using `sets`, an array with one-hundred sets, containing seven to twelve elements (the two examples given above are the first two sets), identify all the special sum sets, $A_1, A_2, \ldots, A_k$, and find the value of $(A_1) + S(A_2) + \cdots + S(A_k)$.
|
||||
Usando `sets` (conjuntos), um array com cem conjuntos, contendo de sete a doze elementos (os dois exemplos citados acima são os dois primeiros conjuntos), identifique todos os conjuntos especiais de soma, $A_1, A_2, \ldots, A_k$, e encontre o valor de $(A_1) + S(A_2) + \cdots + S(A_k)$.
|
||||
|
||||
**Note:** This problem is related to Problem 103 and Problem 106.
|
||||
**Observação:** este problema está relacionado aos problemas 103 e 106.
|
||||
|
||||
# --hints--
|
||||
|
||||
`testingSpecialSubsetSums(testSets)` should return `73702`.
|
||||
`testingSpecialSubsetSums(testSets)` deve retornar `73702`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(testingSpecialSubsetSums(_testSets), 73702);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3d71000cf542c50fee9
|
||||
title: 'Problem 106: Special subset sums: meta-testing'
|
||||
title: 'Problema 106: Somas especiais de subconjuntos: meta-testes'
|
||||
challengeType: 5
|
||||
forumTopicId: 301730
|
||||
dashedName: problem-106-special-subset-sums-meta-testing
|
||||
@ -8,22 +8,22 @@ dashedName: problem-106-special-subset-sums-meta-testing
|
||||
|
||||
# --description--
|
||||
|
||||
Let $S(A)$ represent the sum of elements in set A of size n. We shall call it a special sum set if for any two non-empty disjoint subsets, B and C, the following properties are true:
|
||||
Considere que $S(A)$ representa a soma dos elementos no conjunto A, de tamanho n. Vamos chamá-la de uma soma especial definida se, para dois subconjuntos disjuntos, B e C, as seguintes propriedades são verdadeiras:
|
||||
|
||||
1. $S(B) ≠ S(C)$; that is, sums of subsets cannot be equal.
|
||||
2. If B contains more elements than C then $S(B) > S(C)$.
|
||||
1. $S(B) ≠ S(C)$; isto é, as somas de subconjuntos não podem ser iguais.
|
||||
2. Se B contém mais elementos que C, $S(B) > S(C)$.
|
||||
|
||||
For this problem we shall assume that a given set contains n strictly increasing elements and it already satisfies the second rule.
|
||||
Para este problema, vamos supor que um determinado conjunto contém n elementos estritamente crescentes e já satisfaz a segunda regra.
|
||||
|
||||
Surprisingly, out of the 25 possible subset pairs that can be obtained from a set for which n = 4, only 1 of these pairs need to be tested for equality (first rule). Similarly, when n = 7, only 70 out of the 966 subset pairs need to be tested.
|
||||
Notavelmente, dos 25 pares de subconjuntos possíveis que podem ser obtidos a partir de um conjunto para o qual n = 4, apenas 1 destes pares precisa ser testado para a igualdade (primeira regra). Da mesma forma, quando n = 7, apenas 70 dos 966 pares de subconjunto precisam ser testados.
|
||||
|
||||
For n = 12, how many of the 261625 subset pairs that can be obtained need to be tested for equality?
|
||||
Para n = 12, quantos dos 261625 pares de subconjunto que podem ser obtidos precisam ser testados para a igualdade?
|
||||
|
||||
**Note:** This problem is related to Problem 103 and Problem 105.
|
||||
**Observação:** este problema está relacionado aos problemas 103 e 105.
|
||||
|
||||
# --hints--
|
||||
|
||||
`subsetSumsMetaTesting()` should return `21384`.
|
||||
`subsetSumsMetaTesting()` deve retornar `21384`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(subsetSumsMetaTesting(), 21384);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3d91000cf542c50feea
|
||||
title: 'Problem 107: Minimal network'
|
||||
title: 'Problema 107: Rede mínima'
|
||||
challengeType: 5
|
||||
forumTopicId: 301731
|
||||
dashedName: problem-107-minimal-network
|
||||
@ -8,11 +8,11 @@ dashedName: problem-107-minimal-network
|
||||
|
||||
# --description--
|
||||
|
||||
The following undirected network consists of seven vertices and twelve edges with a total weight of 243.
|
||||
A rede não direcionada a seguir consiste em sete vértices e doze arestas com um peso total de 243.
|
||||
|
||||
<img class="img-responsive center-block" alt="Network with seven vertices and twelve edges" src="https://cdn.freecodecamp.org/curriculum/project-euler/minimal-network-1.png" style="background-color: white; padding: 10px;" />
|
||||
<img class="img-responsive center-block" alt="Rede com sete vértices e doze arestas" src="https://cdn.freecodecamp.org/curriculum/project-euler/minimal-network-1.png" style="background-color: white; padding: 10px;" />
|
||||
|
||||
The same network can be represented by the matrix below.
|
||||
A mesma rede pode ser representada pela matriz abaixo.
|
||||
|
||||
| | A | B | C | D | E | F | G |
|
||||
| - | -- | -- | -- | -- | -- | -- | -- |
|
||||
@ -25,15 +25,15 @@ The same network can be represented by the matrix below.
|
||||
| G | - | - | - | 23 | 11 | 27 | - |
|
||||
|
||||
|
||||
However, it is possible to optimise the network by removing some edges and still ensure that all points on the network remain connected. The network which achieves the maximum saving is shown below. It has a weight of 93, representing a saving of 243 − 93 = 150 from the original network.
|
||||
No entanto, é possível otimizar a rede removendo algumas arestas e ainda garantindo que todos os pontos na rede permaneçam ligados. A rede que alcança o máximo de economia é mostrada abaixo. Tem um peso de 93, representando uma economia de 243 - 93 = 150 da rede original.
|
||||
|
||||
<img class="img-responsive center-block" alt="Network wtih seven vertices and left six edges: AB, BD, CA, DE, DF, EG" src="https://cdn.freecodecamp.org/curriculum/project-euler/minimal-network-2.png" style="background-color: white; padding: 10px;" />
|
||||
<img class="img-responsive center-block" alt="A rede possui sete vértices e seis arestas: AB, BD, CA, DE, DF, EG" src="https://cdn.freecodecamp.org/curriculum/project-euler/minimal-network-2.png" style="background-color: white; padding: 10px;" />
|
||||
|
||||
Using `network`, an 2D array representing network in matrix form, find the maximum saving which can be achieved by removing redundant edges whilst ensuring that the network remains connected. Vertices not having connection will be represented with `-1`.
|
||||
Usando `network` (rede), um array 2D representando a rede em forma de matriz, encontre a economia máxima que pode ser alcançada removendo as arestas redundantes, assegurando simultaneamente que a rede permaneça ligada. Vértices que não tiverem conexão serão representados com `-1`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`minimalNetwork(testNetwork)` should return `259679`.
|
||||
`minimalNetwork(testNetwork)` deve retornar `259679`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(minimalNetwork(_testNetwork), 259679);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3981000cf542c50feab
|
||||
title: 'Problem 44: Pentagon numbers'
|
||||
title: 'Problema 44: Números pentagonais'
|
||||
challengeType: 5
|
||||
forumTopicId: 302111
|
||||
dashedName: problem-44-pentagon-numbers
|
||||
@ -8,23 +8,23 @@ dashedName: problem-44-pentagon-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
Pentagonal numbers are generated by the formula, P<sub>n</sub>=`n`(3`n`−1)/2. The first ten pentagonal numbers are:
|
||||
Números pentagonais são gerados pela fórmula P<sub>n</sub> = `n`(3`n` − 1) / 2. Os primeiros dez números pentagonais são:
|
||||
|
||||
1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...
|
||||
|
||||
It can be seen that P<sub>4</sub> + P<sub>7</sub> = 22 + 70 = 92 = P<sub>8</sub>. However, their difference, 70 − 22 = 48, is not pentagonal.
|
||||
Pode ser visto que P<sub>4</sub> + P<sub>7</sub> = 22 + 70 = 92 = P<sub>8</sub>. No entanto, a sua diferença, 70 - 22 = 48, não forma um número pentagonal.
|
||||
|
||||
Find the pair of pentagonal numbers, P<sub>j</sub> and P<sub>k</sub>, for which their sum and difference are pentagonal and D = |P<sub>k</sub> − P<sub>j</sub>| is minimized; what is the value of D?
|
||||
Encontre o par de números pentagonais, P<sub>j</sub> e P<sub>k</sub>, cuja soma e a diferença formem um número pentagonal e cuja equação D = |P<sub>k</sub> − P<sub>j</sub>| é minimizada. Qual o valor de D?
|
||||
|
||||
# --hints--
|
||||
|
||||
`pentagonNumbers()` should return a number.
|
||||
`pentagonNumbers()` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof pentagonNumbers() === 'number');
|
||||
```
|
||||
|
||||
`pentagonNumbers()` should return 5482660.
|
||||
`pentagonNumbers()` deve retornar 5482660.
|
||||
|
||||
```js
|
||||
assert.strictEqual(pentagonNumbers(), 5482660);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3991000cf542c50feac
|
||||
title: 'Problem 45: Triangular, pentagonal, and hexagonal'
|
||||
title: 'Problema 45: Triangular, pentagonal e hexagonal'
|
||||
challengeType: 5
|
||||
forumTopicId: 302122
|
||||
dashedName: problem-45-triangular-pentagonal-and-hexagonal
|
||||
@ -8,25 +8,25 @@ dashedName: problem-45-triangular-pentagonal-and-hexagonal
|
||||
|
||||
# --description--
|
||||
|
||||
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:
|
||||
Os números triangulares, pentagonais e hexagonais são gerados pelas seguintes fórmulas:
|
||||
|
||||
<div style='display: inline-grid; text-align: center; grid-template-columns: 135px 135px 260px; grid-template-rows: auto;'><div>Triangle</div><div>T<sub>n</sub>=<var>n</var>(<var>n</var>+1)/2</div><div>1, 3, 6, 10, 15, ...</div></div>
|
||||
<div style='display: inline-grid; text-align: center; grid-template-columns: 135px 135px 260px; grid-template-rows: auto;'><div>Triangular</div><div>T<sub>n</sub> = <var>n</var>(<var>n</var> + 1) / 2</div><div>1, 3, 6, 10, 15, ...</div></div>
|
||||
<div style='display: inline-grid; text-align: center; grid-template-columns: 135px 135px 260px; grid-template-rows: auto;'><div>Pentagonal</div><div>P<sub>n</sub> = <var>n</var>(3<var>n</var> − 1) / 2</div><div>1, 5, 12, 22, 35, ...</div></div>
|
||||
<div style='display: inline-grid; text-align: center; grid-template-columns: 135px 135px 260px; grid-template-rows: auto;'><div>Hexagonal</div><div>H<sub>n</sub> = <var>n</var>(2<var>n</var> − 1)</div><div>1, 6, 15, 28, 45, ...</div></div>
|
||||
|
||||
It can be verified that T<sub>285</sub> = P<sub>165</sub> = H<sub>143</sub> = 40755.
|
||||
Pode ser verificado que T<sub>285</sub> = P<sub>165</sub> = H<sub>143</sub> = 40755.
|
||||
|
||||
Find the next triangle number that is also pentagonal and hexagonal.
|
||||
Calcule o próximo número triangular que é também pentagonal e hexagonal.
|
||||
|
||||
# --hints--
|
||||
|
||||
`triPentaHexa(40756)` should return a number.
|
||||
`triPentaHexa(40756)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof triPentaHexa(40756) === 'number');
|
||||
```
|
||||
|
||||
`triPentaHexa(40756)` should return 1533776805.
|
||||
`triPentaHexa(40756)` deve retornar 1533776805.
|
||||
|
||||
```js
|
||||
assert.strictEqual(triPentaHexa(40756), 1533776805);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f39a1000cf542c50fead
|
||||
title: 'Problem 46: Goldbach''s other conjecture'
|
||||
title: 'Problema 46: Outra conjectura de Goldbach'
|
||||
challengeType: 5
|
||||
forumTopicId: 302134
|
||||
dashedName: problem-46-goldbachs-other-conjecture
|
||||
@ -8,7 +8,7 @@ dashedName: problem-46-goldbachs-other-conjecture
|
||||
|
||||
# --description--
|
||||
|
||||
It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
|
||||
Foi proposto por Christian Goldbach que todos os números compostos ímpares podem ser obtidos pela soma de um primo e duas vezes um número ao quadrado.
|
||||
|
||||
<div style='margin-left: 2em;'>
|
||||
9 = 7 + 2×1<sup>2</sup><br>
|
||||
@ -19,19 +19,19 @@ It was proposed by Christian Goldbach that every odd composite number can be wri
|
||||
33 = 31 + 2×1<sup>2</sup>
|
||||
</div>
|
||||
|
||||
It turns out that the conjecture was false.
|
||||
Acontece que a conjectura era falsa.
|
||||
|
||||
What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?
|
||||
Qual é o menor número composto ímpar que não pode ser escrito como a soma de um primo e duas vezes um número ao quadrado?
|
||||
|
||||
# --hints--
|
||||
|
||||
`goldbachsOtherConjecture()` should return a number.
|
||||
`goldbachsOtherConjecture()` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof goldbachsOtherConjecture() === 'number');
|
||||
```
|
||||
|
||||
`goldbachsOtherConjecture()` should return 5777.
|
||||
`goldbachsOtherConjecture()` deve retornar 5777.
|
||||
|
||||
```js
|
||||
assert.strictEqual(goldbachsOtherConjecture(), 5777);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f39c1000cf542c50feae
|
||||
title: 'Problem 47: Distinct primes factors'
|
||||
title: 'Problema 47: Fatores primos distintos'
|
||||
challengeType: 5
|
||||
forumTopicId: 302145
|
||||
dashedName: problem-47-distinct-primes-factors
|
||||
@ -8,14 +8,14 @@ dashedName: problem-47-distinct-primes-factors
|
||||
|
||||
# --description--
|
||||
|
||||
The first two consecutive numbers to have two distinct prime factors are:
|
||||
Os dois primeiros números consecutivos a terem dois fatores primos distintos são:
|
||||
|
||||
<div style='padding-left: 4em;'>
|
||||
14 = 2 × 7<br>
|
||||
15 = 3 × 5
|
||||
</div>
|
||||
|
||||
The first three consecutive numbers to have three distinct prime factors are:
|
||||
Os três primeiros números consecutivos a ter três fatores primos distintos são:
|
||||
|
||||
<div style='padding-left: 4em;'>
|
||||
644 = 2<sup>2</sup> × 7 × 23<br>
|
||||
@ -23,29 +23,29 @@ The first three consecutive numbers to have three distinct prime factors are:
|
||||
646 = 2 × 17 × 19
|
||||
</div>
|
||||
|
||||
Find the first four consecutive integers to have four distinct prime factors each. What is the first of these numbers?
|
||||
Encontre os primeiros quatro números inteiros consecutivos que têm quatro fatores primos distintos. Qual é o primeiro desses números?
|
||||
|
||||
# --hints--
|
||||
|
||||
`distinctPrimeFactors(2, 2)` should return a number.
|
||||
`distinctPrimeFactors(2, 2)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof distinctPrimeFactors(2, 2) === 'number');
|
||||
```
|
||||
|
||||
`distinctPrimeFactors(2, 2)` should return 14.
|
||||
`distinctPrimeFactors(2, 2)` deve retornar 14.
|
||||
|
||||
```js
|
||||
assert.strictEqual(distinctPrimeFactors(2, 2), 14);
|
||||
```
|
||||
|
||||
`distinctPrimeFactors(3, 3)` should return 644.
|
||||
`distinctPrimeFactors(3, 3)` deve retornar 644.
|
||||
|
||||
```js
|
||||
assert.strictEqual(distinctPrimeFactors(3, 3), 644);
|
||||
```
|
||||
|
||||
`distinctPrimeFactors(4, 4)` should return 134043.
|
||||
`distinctPrimeFactors(4, 4)` deve retornar 134043.
|
||||
|
||||
```js
|
||||
assert.strictEqual(distinctPrimeFactors(4, 4), 134043);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f39c1000cf542c50feaf
|
||||
title: 'Problem 48: Self powers'
|
||||
title: 'Problema 48: Elevado à base'
|
||||
challengeType: 5
|
||||
forumTopicId: 302157
|
||||
dashedName: problem-48-self-powers
|
||||
@ -8,37 +8,37 @@ dashedName: problem-48-self-powers
|
||||
|
||||
# --description--
|
||||
|
||||
The series, 1<sup>1</sup> + 2<sup>2</sup> + 3<sup>3</sup> + ... + 10<sup>10</sup> = 10405071317.
|
||||
A série, 1<sup>1</sup> + 2<sup>2</sup> + 3<sup>3</sup> + ... + 10<sup>10</sup> = 10405071317.
|
||||
|
||||
Find the last ten digits of the series, 1<sup>1</sup> + 2<sup>2</sup> + 3<sup>3</sup> + ... + 1000<sup>1000</sup>.
|
||||
Encontre os últimos dez dígitos da série, 1<sup>1</sup> + 2<sup>2</sup> + 3<sup>3</sup> + ... + 1000<sup>1000</sup>.
|
||||
|
||||
# --hints--
|
||||
|
||||
`selfPowers(10, 3)` should return a number.
|
||||
`selfPowers(10, 3)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof selfPowers(10, 3) === 'number');
|
||||
```
|
||||
|
||||
`selfPowers(10, 3)` should return 317.
|
||||
`selfPowers(10, 3)` deve retornar 317.
|
||||
|
||||
```js
|
||||
assert.strictEqual(selfPowers(10, 3), 317);
|
||||
```
|
||||
|
||||
`selfPowers(150, 6)` should return 29045.
|
||||
`selfPowers(150, 6)` deve retornar 29045.
|
||||
|
||||
```js
|
||||
assert.strictEqual(selfPowers(150, 6), 29045);
|
||||
```
|
||||
|
||||
`selfPowers(673, 7)` should return 2473989.
|
||||
`selfPowers(673, 7)` deve retornar 2473989.
|
||||
|
||||
```js
|
||||
assert.strictEqual(selfPowers(673, 7), 2473989);
|
||||
```
|
||||
|
||||
`selfPowers(1000, 10)` should return 9110846700.
|
||||
`selfPowers(1000, 10)` deve retornar 9110846700.
|
||||
|
||||
```js
|
||||
assert.strictEqual(selfPowers(1000, 10), 9110846700);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f39d1000cf542c50feb0
|
||||
title: 'Problem 49: Prime permutations'
|
||||
title: 'Problema 49: Permutações de números primos'
|
||||
challengeType: 5
|
||||
forumTopicId: 302159
|
||||
dashedName: problem-49-prime-permutations
|
||||
@ -8,21 +8,21 @@ dashedName: problem-49-prime-permutations
|
||||
|
||||
# --description--
|
||||
|
||||
The arithmetic sequence, 1487, 4817, 8147, in which each of the terms increases by 3330, is unusual in two ways: (i) each of the three terms are prime, and, (ii) each of the 4-digit numbers are permutations of one another.
|
||||
A sequência aritmética, 1487, 4817, 8147, em que cada um dos termos aumenta em 3330, é incomum por dois motivos: (i) todos os três números são primos, e, (ii) cada um dos números de 4 dígitos são permutações um do outro.
|
||||
|
||||
There are no arithmetic sequences made up of three 1-, 2-, or 3-digit primes, exhibiting this property, but there is one other 4-digit increasing sequence.
|
||||
Não existem sequências aritméticas de números primos de 1, 2 ou 3 dígitos que possuem essas mesmas propriedades. Mas existe outra sequência crescente de 4 dígitos.
|
||||
|
||||
What 12-digit number do you form by concatenating the three terms in this sequence?
|
||||
Qual número de 12 dígitos você forma ao concatenar os três termos nessa sequência?
|
||||
|
||||
# --hints--
|
||||
|
||||
`primePermutations()` should return a number.
|
||||
`primePermutations()` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof primePermutations() === 'number');
|
||||
```
|
||||
|
||||
`primePermutations()` should return 296962999629.
|
||||
`primePermutations()` deve retornar 296962999629.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primePermutations(), 296962999629);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f39e1000cf542c50feb1
|
||||
title: 'Problem 50: Consecutive prime sum'
|
||||
title: 'Problema 50: Soma dos números primos consecutivos'
|
||||
challengeType: 5
|
||||
forumTopicId: 302161
|
||||
dashedName: problem-50-consecutive-prime-sum
|
||||
@ -8,31 +8,31 @@ dashedName: problem-50-consecutive-prime-sum
|
||||
|
||||
# --description--
|
||||
|
||||
The prime 41, can be written as the sum of six consecutive primes:
|
||||
O número primo 41 pode ser escrito como a soma de seis números primos consecutivos:
|
||||
|
||||
<div style='text-align: center;'>41 = 2 + 3 + 5 + 7 + 11 + 13</div>
|
||||
|
||||
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
|
||||
Esta é a soma mais longa de números primos consecutivos abaixo de 100 que resultam em um número primo.
|
||||
|
||||
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
|
||||
A soma mais longa de números primos consecutivos abaixo de 1000 contém 21 termos e resulta em 953.
|
||||
|
||||
Which prime, below one-million, can be written as the sum of the most consecutive primes?
|
||||
Qual número primo, abaixo de um milhão, é o resultado da soma da maior sequência de números primos?
|
||||
|
||||
# --hints--
|
||||
|
||||
`consecutivePrimeSum(1000)` should return a number.
|
||||
`consecutivePrimeSum(1000)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof consecutivePrimeSum(1000) === 'number');
|
||||
```
|
||||
|
||||
`consecutivePrimeSum(1000)` should return 953.
|
||||
`consecutivePrimeSum(1000)` deve retornar 953.
|
||||
|
||||
```js
|
||||
assert.strictEqual(consecutivePrimeSum(1000), 953);
|
||||
```
|
||||
|
||||
`consecutivePrimeSum(1000000)` should return 997651.
|
||||
`consecutivePrimeSum(1000000)` deve retornar 997651.
|
||||
|
||||
```js
|
||||
assert.strictEqual(consecutivePrimeSum(1000000), 997651);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f39f1000cf542c50feb2
|
||||
title: 'Problem 51: Prime digit replacements'
|
||||
title: 'Problema 51: Substituição de dígitos primos'
|
||||
challengeType: 5
|
||||
forumTopicId: 302162
|
||||
dashedName: problem-51-prime-digit-replacements
|
||||
@ -8,33 +8,33 @@ dashedName: problem-51-prime-digit-replacements
|
||||
|
||||
# --description--
|
||||
|
||||
By replacing the 1st digit of the 2-digit number \*3, it turns out that six of the nine possible values: 13, 23, 43, 53, 73, and 83, are all prime.
|
||||
Ao substituir o primeiro algarismo do número de dois algarismos, \*3, seis dos nove valores possíveis (13, 23, 43, 53, 73 e 83) são todos primos.
|
||||
|
||||
By replacing the 3rd and 4th digits of 56\*\*3 with the same digit, this 5-digit number is the first example having seven primes among the ten generated numbers, yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and 56993. Consequently 56003, being the first member of this family, is the smallest prime with this property.
|
||||
Ao substituir o terceiro e o quarto dígitos do número 56\*\*3 pelo mesmo dígito, este número de 5 dígitos é o primeiro exemplo com sete primos entre os dez números gerados, criando a sequência de termos: 56003, 56113, 56333, 56443, 56663, 56773 e 56993. O número 56003, por ser o primeiro termo desta sequência, é o menor primo com essa propriedade.
|
||||
|
||||
Find the smallest prime which, by replacing part of the number (not necessarily adjacent digits) with the same digit, is part of an `n` prime value family.
|
||||
Encontre o menor número primo que, ao substituir parte do número (não necessariamente dígitos adjacentes) pelo mesmo algarismo, é parte de uma sequência de `n` termos.
|
||||
|
||||
# --hints--
|
||||
|
||||
`primeDigitReplacements(6)` should return a number.
|
||||
`primeDigitReplacements(6)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof primeDigitReplacements(6) === 'number');
|
||||
```
|
||||
|
||||
`primeDigitReplacements(6)` should return `13`.
|
||||
`primeDigitReplacements(6)` deve retornar `13`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primeDigitReplacements(6), 13);
|
||||
```
|
||||
|
||||
`primeDigitReplacements(7)` should return `56003`.
|
||||
`primeDigitReplacements(7)` deve retornar `56003`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primeDigitReplacements(7), 56003);
|
||||
```
|
||||
|
||||
`primeDigitReplacements(8)` should return `121313`.
|
||||
`primeDigitReplacements(8)` deve retornar `121313`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primeDigitReplacements(8), 121313);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3a01000cf542c50feb3
|
||||
title: 'Problem 52: Permuted multiples'
|
||||
title: 'Problema 52: Múltiplos permutados'
|
||||
challengeType: 5
|
||||
forumTopicId: 302163
|
||||
dashedName: problem-52-permuted-multiples
|
||||
@ -8,25 +8,25 @@ dashedName: problem-52-permuted-multiples
|
||||
|
||||
# --description--
|
||||
|
||||
It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order.
|
||||
Podemos notar que o número, 125874, e o seu dobro, 251748, contêm exatamente os mesmos dígitos, mas em uma ordem diferente.
|
||||
|
||||
Find the smallest positive integer, such that multiplied by integers $\\{2, 3, \ldots, n\\}$, contain the same digits.
|
||||
Encontre o menor número inteiro positivo, tal que, multiplicado por números inteiros $\\{2, 3, \ldots, n\\}$, contém os mesmos algarismos.
|
||||
|
||||
# --hints--
|
||||
|
||||
`permutedMultiples(2)` should return a number.
|
||||
`permutedMultiples(2)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof permutedMultiples(2) === 'number');
|
||||
```
|
||||
|
||||
`permutedMultiples(2)` should return `125874`.
|
||||
`permutedMultiples(2)` deve retornar `125874`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permutedMultiples(2), 125874);
|
||||
```
|
||||
|
||||
`permutedMultiples(6)` should return `142857`.
|
||||
`permutedMultiples(6)` deve retornar `142857`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permutedMultiples(6), 142857);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3a11000cf542c50feb4
|
||||
title: 'Problem 53: Combinatoric selections'
|
||||
title: 'Problema 53: Seleção de combinações'
|
||||
challengeType: 5
|
||||
forumTopicId: 302164
|
||||
dashedName: problem-53-combinatoric-selections
|
||||
@ -8,45 +8,45 @@ dashedName: problem-53-combinatoric-selections
|
||||
|
||||
# --description--
|
||||
|
||||
There are exactly ten ways of selecting three from five, 12345:
|
||||
Existem exatamente dez maneiras de selecionar um número de 3 dígitos a partir de um número de 5 dígitos, 12345:
|
||||
|
||||
<div style='text-align: center;'>123, 124, 125, 134, 135, 145, 234, 235, 245, and 345</div>
|
||||
<div style='text-align: center;'>123, 124, 125, 134, 135, 145, 234, 235, 245 e 345</div>
|
||||
|
||||
In combinatorics, we use the notation, $\\displaystyle \\binom 5 3 = 10$
|
||||
Na combinatória, usamos a notação $\\displaystyle \\binom 5 3 = 10$
|
||||
|
||||
In general, $\\displaystyle \\binom n r = \\dfrac{n!}{r!(n-r)!}$, where $r \\le n$, $n! = n \\times (n-1) \\times ... \\times 3 \\times 2 \\times 1$, and $0! = 1$.
|
||||
No geral, $\\displaystyle \\binom n r = \\dfrac{n!}{r!(n-r)!}$, onde $r \\le n$, $n! = n \\times (n-1) \\times ... \\times 3 \\times 2 \\times 1$, e $0! = 1$.
|
||||
|
||||
It is not until $n = 23$, that a value exceeds one-million: $\\displaystyle \\binom {23} {10} = 1144066$.
|
||||
É só depois de $n = 23$ que um valor excede um milhão: $\\displaystyle \\binom {23} {10} = 1144066$.
|
||||
|
||||
How many, not necessarily distinct, values of $\\displaystyle \\binom n r$ for $1 \\le n \\le 100$, are greater than one-million?
|
||||
Quantos valores de $\\displaystyle \\binom n r$ para $1 \\le n \\le 100$, não necessariamente distintos, são maiores que um milhão?
|
||||
|
||||
# --hints--
|
||||
|
||||
`combinatoricSelections(1000)` should return a number.
|
||||
`combinatoricSelections(1000)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof combinatoricSelections(1000) === 'number');
|
||||
```
|
||||
|
||||
`combinatoricSelections(1000)` should return 4626.
|
||||
`combinatoricSelections(1000)` deve retornar 4626.
|
||||
|
||||
```js
|
||||
assert.strictEqual(combinatoricSelections(1000), 4626);
|
||||
```
|
||||
|
||||
`combinatoricSelections(10000)` should return 4431.
|
||||
`combinatoricSelections(10000)` deve retornar 4431.
|
||||
|
||||
```js
|
||||
assert.strictEqual(combinatoricSelections(10000), 4431);
|
||||
```
|
||||
|
||||
`combinatoricSelections(100000)` should return 4255.
|
||||
`combinatoricSelections(100000)` deve retornar 4255.
|
||||
|
||||
```js
|
||||
assert.strictEqual(combinatoricSelections(100000), 4255);
|
||||
```
|
||||
|
||||
`combinatoricSelections(1000000)` should return 4075.
|
||||
`combinatoricSelections(1000000)` deve retornar 4075.
|
||||
|
||||
```js
|
||||
assert.strictEqual(combinatoricSelections(1000000), 4075);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3a21000cf542c50feb5
|
||||
title: 'Problem 54: Poker hands'
|
||||
title: 'Problema 54: Mãos do pôquer'
|
||||
challengeType: 5
|
||||
forumTopicId: 302165
|
||||
dashedName: problem-54-poker-hands
|
||||
@ -8,54 +8,54 @@ dashedName: problem-54-poker-hands
|
||||
|
||||
# --description--
|
||||
|
||||
In the card game poker, a hand consists of five cards and are ranked, from lowest to highest, in the following way:
|
||||
No pôquer, uma mão consiste em cinco cartas e é classificada, da menor para a maior (mão), da seguinte maneira:
|
||||
|
||||
<ul>
|
||||
<li>High Card: Highest value card.</li>
|
||||
<li>One Pair: Two cards of the same value.</li>
|
||||
<li>Two Pairs: Two different pairs.</li>
|
||||
<li>Three of a Kind: Three cards of the same value.</li>
|
||||
<li>Straight: All cards are consecutive values.</li>
|
||||
<li>Flush: All cards of the same suit.</li>
|
||||
<li>Full House: Three of a kind and a pair.</li>
|
||||
<li>Four of a Kind: Four cards of the same value.</li>
|
||||
<li>Straight Flush: All cards are consecutive values of same suit.</li>
|
||||
<li>Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.</li>
|
||||
<li>Carta alta: qualquer mão que não esteja nas categorias abaixo.</li>
|
||||
<li>Um par: duas cartas de mesmo valor e três outras cartas não relacionadas.</li>
|
||||
<li>Dois pares: dois pares de valores diferentes cada e uma outra carta não relacionada.</li>
|
||||
<li>Trinca: três cartas de mesmo valor e duas outras cartas não relacionadas.</li>
|
||||
<li>Sequência: cinco cartas em sequência.</li>
|
||||
<li>Flush: cinco cartas do mesmo naipe.</li>
|
||||
<li>Full House: três cartas de mesmo valor e duas outras cartas diferentes de mesmo valor.</li>
|
||||
<li>Quadra: quatro cartas de mesmo valor e uma outra carta não relacionada.</li>
|
||||
<li>Straight Flush: cinco cartas em ordem numérica, todas do mesmo naipe.</li>
|
||||
<li>Royal Flush: Dez, Valete, Rainha, Rei e Ás, todos do mesmo naipe.</li>
|
||||
</ul>
|
||||
|
||||
The cards are valued in the order: 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.
|
||||
A ordem das cartas é a seguinte: 2, 3, 4, 5, 6, 7, 8, 9, 10, Valete, Rainha, Rei e Ás.
|
||||
|
||||
If two players have the same ranked hands then the rank made up of the highest value wins; for example, a pair of eights beats a pair of fives (see example 1 below). But if two ranks tie, for example, both players have a pair of queens, then highest cards in each hand are compared (see example 4 below); if the highest cards tie then the next highest cards are compared, and so on.
|
||||
Se dois jogadores tiverem as mesmas mãos, o jogador com as cartas de valor mais alto vence. Por exemplo, um par de oito vence um par de cinco (veja o exemplo 1 abaixo). Se os dois jogadores tiverem a mesma mão com os mesmos valores, as cartas mais altas de cada jogador são comparadas (veja exemplo 4 abaixo) para fim de desempate. Se as cartas mais altas empatarem de novo, então outras cartas são comparadas, e assim por diante.
|
||||
|
||||
Consider the following five hands dealt to two players:
|
||||
Considere as cinco mãos a seguir dadas a dois jogadores:
|
||||
|
||||
| Hand | Player 1 | Player 2 | Winner |
|
||||
| ------------------------- | --------------------------------------------------------------------- | ---------------------------------------------------------------------- | -------- |
|
||||
| <strong>1</strong> | 5H 5C 6S 7S KD <br> Pair of Fives | 2C 3S 8S 8D TD <br> Pair of Eights | Player 2 |
|
||||
| <strong>2</strong> | 5D 8C 9S JS AC <br> Highest card Ace | 2C 5C 7D 8S QH <br> Highest card Queen | Player 1 |
|
||||
| <strong>3</strong> | 2D 9C AS AH AC <br> Three Aces | 3D 6D 7D TD QD <br> Flush with Diamonds | Player 2 |
|
||||
| <strong>4</strong> | 4D 6S 9H QH QC <br> Pair of Queens <br> Highest card Nine | 3D 6D 7H QD QS <br> Pair of Queens <br> Highest card Seven | Player 1 |
|
||||
| <strong>5</strong> | 2H 2D 4C 4D 4S <br> Full House <br> with Three Fours | 3C 3D 3S 9S 9D <br> Full House <br> with Three Threes | Player 1 |
|
||||
| Mão | Jogador 1 | Jogador 2 | Vencedor |
|
||||
| ------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------ | --------- |
|
||||
| <strong>1</strong> | 5H 5C 6S 7S KD <br> Par de cincos | 2C 3S 8S 8D TD <br> Par de oitos | Jogador 2 |
|
||||
| <strong>2</strong> | 5D 8C 9S JS AC <br> Maior carta é o Ás | 2C 5C 7D 8S QH <br> Maior carta é a Rainha | Jogador 1 |
|
||||
| <strong>3</strong> | 2D 9C AS AH AC <br> Três Ases | 3D 6D 7D TD QD <br> Flush de ouros | Jogador 2 |
|
||||
| <strong>4</strong> | 4D 6S 9H QH QC <br> Par de Rainhas <br> A maior carta é Nove | 3D 6D 7H QD QS <br> Par de Rainhas <br> A maior carta é Sete | Jogador 1 |
|
||||
| <strong>5</strong> | 2H 2D 4C 4D 4S <br> Full House <br> com três Quatros | 3C 3D 3S 9S 9D <br> Full House <br> com três Três | Jogador 1 |
|
||||
|
||||
The global array (`handsArr`) passed to the function, contains one-thousand random hands dealt to two players. Each line of the file contains ten cards (separated by a single space): the first five are Player 1's cards and the last five are Player 2's cards. You can assume that all hands are valid (no invalid characters or repeated cards), each player's hand is in no specific order, and in each hand there is a clear winner.
|
||||
O array global (`handsArr`) passado para a função contém mil mãos aleatórias dadas a dois jogadores. Cada linha do arquivo contém dez cartas (separadas por um único espaço): as cinco primeiras são as cartas do Jogador 1 e as últimas cinco são cartas do Jogador 2. Você pode assumir que todas as mãos são válidas (sem caracteres inválidos ou cartas repetidas). A mão de cada jogador não está em uma ordem específica e em cada mão há um vencedor claro.
|
||||
|
||||
How many hands does Player 1 win?
|
||||
Quantas mãos o Jogador 1 vence?
|
||||
|
||||
# --hints--
|
||||
|
||||
`pokerHands(testArr)` should return a number.
|
||||
`pokerHands(testArr)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof pokerHands(testArr) === 'number');
|
||||
```
|
||||
|
||||
`pokerHands(testArr)` should return 2.
|
||||
`pokerHands(testArr)` deve retornar 2.
|
||||
|
||||
```js
|
||||
assert.strictEqual(pokerHands(testArr), 2);
|
||||
```
|
||||
|
||||
`pokerHands(handsArr)` should return 376.
|
||||
`pokerHands(handsArr)` deve retornar 376.
|
||||
|
||||
```js
|
||||
assert.strictEqual(pokerHands(handsArr), 376);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3a31000cf542c50feb6
|
||||
title: 'Problem 55: Lychrel numbers'
|
||||
title: 'Problema 55: Números de Lychrel'
|
||||
challengeType: 5
|
||||
forumTopicId: 302166
|
||||
dashedName: problem-55-lychrel-numbers
|
||||
@ -8,9 +8,9 @@ dashedName: problem-55-lychrel-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
|
||||
Se pegarmos o número 47, invertemos e somarmos, 47 + 74 = 121, temos um número palíndromo.
|
||||
|
||||
Not all numbers produce palindromes so quickly. For example,
|
||||
Nem todos os números, no entanto, produzem palíndromos tão facilmente. Por exemplo:
|
||||
|
||||
<div style="margin-left: 4em;">
|
||||
349 + 943 = 1292,<br>
|
||||
@ -18,49 +18,49 @@ Not all numbers produce palindromes so quickly. For example,
|
||||
4213 + 3124 = 7337<br>
|
||||
</div>
|
||||
|
||||
That is, 349 took three iterations to arrive at a palindrome.
|
||||
Ou seja, 349 precisou de três iterações para chegar a um palíndromo.
|
||||
|
||||
Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits).
|
||||
Embora ninguém tenha provado ainda, pensa-se que alguns números, como 196, nunca produzem um palíndromo. Um número que nunca produz um palíndromo através do processo de inversão e adição é conhecido como um número de Lychrel. Devido à natureza teórica destes números e para fins de aprendizado, partiremos do princípio de que todo número é um número de Lychrel até que se prove o contrário. Além disso, você irá assumir que para cada número abaixo de dez mil, ou (i) ele se torna um palíndromo em menos de cinquenta iterações, ou, (ii) ninguém, com todo o poder de computação que existe, conseguiu mapeá-lo para um palíndromo. Na verdade, 10677 é o primeiro número que exige mais de cinquenta iterações antes de produzir um palíndromo: 4668731596684224866951378664 (53 iterações, gerando um número com 28 dígitos).
|
||||
|
||||
Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.
|
||||
Surpreendentemente, há números palíndromos que são, ao mesmo tempo, um número de Lychrel. O primeiro exemplo é o 4994.
|
||||
|
||||
How many Lychrel numbers are there below `num`?
|
||||
Quantos números de Lychrel existem abaixo de `num`?
|
||||
|
||||
**Note:** Wording was modified slightly on 24 April 2007 to emphasize the theoretical nature of Lychrel numbers.
|
||||
**Observação:** o texto foi ligeiramente modificado em 24 de abril de 2007 para enfatizar a natureza teórica dos números de Lychrel.
|
||||
|
||||
# --hints--
|
||||
|
||||
`countLychrelNumbers(1000)` should return a number.
|
||||
`countLychrelNumbers(1000)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof countLychrelNumbers(1000) === 'number');
|
||||
```
|
||||
|
||||
`countLychrelNumbers(1000)` should return 13.
|
||||
`countLychrelNumbers(1000)` deve retornar 13.
|
||||
|
||||
```js
|
||||
assert.strictEqual(countLychrelNumbers(1000), 13);
|
||||
```
|
||||
|
||||
`countLychrelNumbers(3243)` should return 39.
|
||||
`countLychrelNumbers(3243)` deve retornar 39.
|
||||
|
||||
```js
|
||||
assert.strictEqual(countLychrelNumbers(3243), 39);
|
||||
```
|
||||
|
||||
`countLychrelNumbers(5000)` should return 76.
|
||||
`countLychrelNumbers(5000)` deve retornar 76.
|
||||
|
||||
```js
|
||||
assert.strictEqual(countLychrelNumbers(5000), 76);
|
||||
```
|
||||
|
||||
`countLychrelNumbers(7654)` should return 140.
|
||||
`countLychrelNumbers(7654)` deve retornar 140.
|
||||
|
||||
```js
|
||||
assert.strictEqual(countLychrelNumbers(7654), 140);
|
||||
```
|
||||
|
||||
`countLychrelNumbers(10000)` should return 249.
|
||||
`countLychrelNumbers(10000)` deve retornar 249.
|
||||
|
||||
```js
|
||||
assert.strictEqual(countLychrelNumbers(10000), 249);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3a41000cf542c50feb7
|
||||
title: 'Problem 56: Powerful digit sum'
|
||||
title: 'Problema 56: Poderosa soma de dígitos'
|
||||
challengeType: 5
|
||||
forumTopicId: 302167
|
||||
dashedName: problem-56-powerful-digit-sum
|
||||
@ -8,43 +8,43 @@ dashedName: problem-56-powerful-digit-sum
|
||||
|
||||
# --description--
|
||||
|
||||
A googol ($10^{100}$) is a massive number: one followed by one-hundred zeros; $100^{100}$ is almost unimaginably large: one followed by two-hundred zeros. Despite their size, the sum of the digits in each number is only 1.
|
||||
Um googol ($10^{100}$) é um número absurdamente enorme: um seguido por cem zeros. Já $100^{100}$ é quase inimaginavelmente grande: um seguido por duzentos zeros. Apesar do seu tamanho, a soma dos algarismos em cada número é de apenas 1.
|
||||
|
||||
Considering natural numbers of the form, $a^b$, where `a`, `b` < `n`, what is the maximum digital sum?
|
||||
Considerando os números naturais da fórmula $a^b$, onde `a`, `b` < `n`, qual é a soma máxima dos dígitos?
|
||||
|
||||
# --hints--
|
||||
|
||||
`powerfulDigitSum(3)` should return a number.
|
||||
`powerfulDigitSum(3)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof powerfulDigitSum(3) === 'number');
|
||||
```
|
||||
|
||||
`powerfulDigitSum(3)` should return `4`.
|
||||
`powerfulDigitSum(3)` deve retornar `4`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(powerfulDigitSum(3), 4);
|
||||
```
|
||||
|
||||
`powerfulDigitSum(10)` should return `45`.
|
||||
`powerfulDigitSum(10)` deve retornar `45`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(powerfulDigitSum(10), 45);
|
||||
```
|
||||
|
||||
`powerfulDigitSum(50)` should return `406`.
|
||||
`powerfulDigitSum(50)` deve retornar `406`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(powerfulDigitSum(50), 406);
|
||||
```
|
||||
|
||||
`powerfulDigitSum(75)` should return `684`.
|
||||
`powerfulDigitSum(75)` deve retornar `684`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(powerfulDigitSum(75), 684);
|
||||
```
|
||||
|
||||
`powerfulDigitSum(100)` should return `972`.
|
||||
`powerfulDigitSum(100)` deve retornar `972`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(powerfulDigitSum(100), 972);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3a51000cf542c50feb8
|
||||
title: 'Problem 57: Square root convergents'
|
||||
title: 'Problema 57: Convergentes da raiz quadrada'
|
||||
challengeType: 5
|
||||
forumTopicId: 302168
|
||||
dashedName: problem-57-square-root-convergents
|
||||
@ -8,11 +8,11 @@ dashedName: problem-57-square-root-convergents
|
||||
|
||||
# --description--
|
||||
|
||||
It is possible to show that the square root of two can be expressed as an infinite continued fraction.
|
||||
É possível mostrar que a raiz quadrada de dois pode ser expressa como uma fração que se repete infinitamente.
|
||||
|
||||
<div style='text-align: center;'>$\sqrt 2 =1+ \frac 1 {2+ \frac 1 {2 +\frac 1 {2+ \dots}}}$</div>
|
||||
|
||||
By expanding this for the first four iterations, we get:
|
||||
Entrando em detalhes, as primeiras quatro iterações são:
|
||||
|
||||
$1 + \\frac 1 2 = \\frac 32 = 1.5$
|
||||
|
||||
@ -22,31 +22,31 @@ $1 + \\frac 1 {2 + \\frac 1 {2+\\frac 1 2}} = \\frac {17}{12} = 1.41666 \\dots$
|
||||
|
||||
$1 + \\frac 1 {2 + \\frac 1 {2+\\frac 1 {2+\\frac 1 2}}} = \\frac {41}{29} = 1.41379 \\dots$
|
||||
|
||||
The next three expansions are $\\frac {99}{70}$, $\\frac {239}{169}$, and $\\frac {577}{408}$, but the eighth expansion, $\\frac {1393}{985}$, is the first example where the number of digits in the numerator exceeds the number of digits in the denominator.
|
||||
As três próximas iterações são $\\frac {99}{70}$, $\\frac {239}{169}$ e $\\frac {577}{408}$. Mas a oitava iteração, $\\frac {1393}{985}$, é o primeiro exemplo em que o número de dígitos no numerador excede o número de dígitos no denominador.
|
||||
|
||||
In the first `n` expansions, how many fractions contain a numerator with more digits than denominator?
|
||||
Nas primeiras `n` iterações, quantas frações contém um numerador com mais dígitos que o denominador?
|
||||
|
||||
# --hints--
|
||||
|
||||
`squareRootConvergents(10)` should return a number.
|
||||
`squareRootConvergents(10)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof squareRootConvergents(10) === 'number');
|
||||
```
|
||||
|
||||
`squareRootConvergents(10)` should return 1.
|
||||
`squareRootConvergents(10)` deve retornar 1.
|
||||
|
||||
```js
|
||||
assert.strictEqual(squareRootConvergents(10), 1);
|
||||
```
|
||||
|
||||
`squareRootConvergents(100)` should return 15.
|
||||
`squareRootConvergents(100)` deve retornar 15.
|
||||
|
||||
```js
|
||||
assert.strictEqual(squareRootConvergents(100), 15);
|
||||
```
|
||||
|
||||
`squareRootConvergents(1000)` should return 153.
|
||||
`squareRootConvergents(1000)` deve retornar 153.
|
||||
|
||||
```js
|
||||
assert.strictEqual(squareRootConvergents(1000), 153);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3a61000cf542c50feb9
|
||||
title: 'Problem 58: Spiral primes'
|
||||
title: 'Problema 58: Espiral de números primos'
|
||||
challengeType: 5
|
||||
forumTopicId: 302169
|
||||
dashedName: problem-58-spiral-primes
|
||||
@ -8,7 +8,7 @@ dashedName: problem-58-spiral-primes
|
||||
|
||||
# --description--
|
||||
|
||||
Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.
|
||||
Começando com o número 1 e movendo-se em espiral no sentido anti-horário, uma espiral quadrada com cada lado contendo 7 números é formada.
|
||||
|
||||
<div style='text-align: center;'>
|
||||
<strong><span style='color: red;'>37</span></strong> 36 35 34 33 32 <strong><span style='color: red;'>31</span></strong><br>
|
||||
@ -20,31 +20,31 @@ Starting with 1 and spiralling anticlockwise in the following way, a square spir
|
||||
<strong><span style='color: red;'>43</span></strong> 44 45 46 47 48 49<br>
|
||||
</div>
|
||||
|
||||
It is interesting to note that the odd squares lie along the bottom right diagonal, but what is more interesting is that 8 out of the 13 numbers lying along both diagonals are prime; that is, a ratio of 8/13 ≈ 62%.
|
||||
É interessante notar que os números ímpares estão ao longo da diagonal inferior direita. Mas o mais interessante é que 8 dos 13 números que estão em ambas as diagonais são primos, ou seja, uma proporção de 8/13 ≈ 62%.
|
||||
|
||||
If one complete new layer is wrapped around the spiral above, a square spiral with side length 9 will be formed. If this process is continued, what is the side length of the square spiral for which the percent of primes along both diagonals first falls below `percent`?
|
||||
Se envolvermos a espiral acima com uma nova camada, a espiral passará a ter 9 números em cada lado. Se este processo continuar, qual será o comprimento de cada lado da espiral onde a porcentagem de números primos ao longo de ambas as diagonais é menor que `percent`?
|
||||
|
||||
# --hints--
|
||||
|
||||
`spiralPrimes(50)` should return a number.
|
||||
`spiralPrimes(50)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof spiralPrimes(50) === 'number');
|
||||
```
|
||||
|
||||
`spiralPrimes(50)` should return `11`.
|
||||
`spiralPrimes(50)` deve retornar `11`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(spiralPrimes(50), 11);
|
||||
```
|
||||
|
||||
`spiralPrimes(15)` should return `981`.
|
||||
`spiralPrimes(15)` deve retornar `981`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(spiralPrimes(15), 981);
|
||||
```
|
||||
|
||||
`spiralPrimes(10)` should return `26241`.
|
||||
`spiralPrimes(10)` deve retornar `26241`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(spiralPrimes(10), 26241);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3a81000cf542c50feba
|
||||
title: 'Problem 59: XOR decryption'
|
||||
title: 'Problema 59: Descriptografia XOR'
|
||||
challengeType: 5
|
||||
forumTopicId: 302170
|
||||
dashedName: problem-59-xor-decryption
|
||||
@ -8,25 +8,25 @@ dashedName: problem-59-xor-decryption
|
||||
|
||||
# --description--
|
||||
|
||||
Each character on a computer is assigned a unique code and the preferred standard is ASCII (American Standard Code for Information Interchange). For example, uppercase A = 65, asterisk (\*) = 42, and lowercase k = 107.
|
||||
Cada caractere em um computador é atribuído a um código único. O padrão preferido é o ASCII (American Standard Code for Information Interchange). Por exemplo: a letra A maiúscula = 65, asterisco * = 42 e a letra k minúscula = 107.
|
||||
|
||||
A modern encryption method is to take a text file, convert the bytes to ASCII, then XOR each byte with a given value, taken from a secret key. The advantage with the XOR function is that using the same encryption key on the cipher text, restores the plain text; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.
|
||||
Um dos métodos de criptografia moderno é pegar um arquivo de texto, converter seus bytes para ASCII e então XOR cada byte com um determinado valor, retirado de uma chave secreta. A vantagem da função XOR é que usar a mesma chave de criptografia no texto criptografado restaura o texto ao seu conteúdo original. Por exemplo: 65 XOR 42 = 107, depois 107 XOR 42 = 65.
|
||||
|
||||
For unbreakable encryption, the key is the same length as the plain text message, and the key is made up of random bytes. The user would keep the encrypted message and the encryption key in different locations, and without both "halves", it is impossible to decrypt the message.
|
||||
Para uma criptografia inquebrável, a chave deve ter o mesmo comprimento que a mensagem de texto e a chave deve ser composta por bytes aleatórios. O usuário deve manter a mensagem criptografada e a chave de criptografia em diferentes locais. Sem possuir ambas, é impossível descriptografar a mensagem.
|
||||
|
||||
Unfortunately, this method is impractical for most users, so the modified method is to use a password as a key. If the password is shorter than the message, which is likely, the key is repeated cyclically throughout the message. The balance for this method is using a sufficiently long password key for security, but short enough to be memorable.
|
||||
Infelizmente, este método é inviável para a maioria das pessoas e, por isso, o método modificado é usar uma senha como chave. Se a senha for menor que a mensagem, o que é comum, a senha é repetida ciclicamente em toda a mensagem. O equilíbrio aqui está em usar uma senha suficientemente longa para segurança, mas curta o suficiente para ser memorizável.
|
||||
|
||||
Your task has been made easy, as the encryption key consists of three lower case characters. Using `cipher`, an array containing the encrypted ASCII codes, and the knowledge that the plain text must contain common English words, decrypt the message and find the sum of the ASCII values in the original text.
|
||||
Neste desafio, sua tarefa foi facilitada. A chave de criptografia consiste em apenas três caracteres minúsculos. Usando `cipher`, um array contendo códigos ASCII criptografados, e o conhecimento de que o conteúdo do texto contém apenas palavras comuns em inglês, descriptografe a mensagem e encontre a soma dos valores em ASCII no texto original.
|
||||
|
||||
# --hints--
|
||||
|
||||
`XORDecryption(cipher)` should return a number.
|
||||
`XORDecryption(cipher)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof XORDecryption(cipher) === 'number');
|
||||
```
|
||||
|
||||
`XORDecryption(cipher)` should return 129448.
|
||||
`XORDecryption(cipher)` deve retornar 129448.
|
||||
|
||||
```js
|
||||
assert.strictEqual(XORDecryption(cipher), 129448);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3a81000cf542c50febb
|
||||
title: 'Problem 60: Prime pair sets'
|
||||
title: 'Problema 60: Pares de números primos'
|
||||
challengeType: 5
|
||||
forumTopicId: 302172
|
||||
dashedName: problem-60-prime-pair-sets
|
||||
@ -8,19 +8,19 @@ dashedName: problem-60-prime-pair-sets
|
||||
|
||||
# --description--
|
||||
|
||||
The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.
|
||||
Os números primos 3, 7, 109 e 673 são notáveis. Ao pegar quaisquer dois primos e concatená-los em qualquer ordem, o resultado sempre será um número primo. Por exemplo: ao pegar 7 e 109, ambos 7109 e 1097 são primos. A soma destes quatro números primos, 792, representa a soma mais baixa para um conjunto de quatro números primos com esta propriedade.
|
||||
|
||||
Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.
|
||||
Encontre a soma mais baixa de um conjunto de cinco números primos, onde dois números primos concatenados produzem outro número primo.
|
||||
|
||||
# --hints--
|
||||
|
||||
`primePairSets()` should return a number.
|
||||
`primePairSets()` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof primePairSets() === 'number');
|
||||
```
|
||||
|
||||
`primePairSets()` should return 26033.
|
||||
`primePairSets()` deve retornar 26033.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primePairSets(), 26033);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7ecb
|
||||
title: K-d tree
|
||||
title: Árvore k-d
|
||||
challengeType: 5
|
||||
forumTopicId: 302295
|
||||
dashedName: k-d-tree
|
||||
@ -8,21 +8,21 @@ dashedName: k-d-tree
|
||||
|
||||
# --description--
|
||||
|
||||
A k-d tree (short for *k*-dimensional tree) is a space-partitioning data structure for organizing points in a k-dimensional space. k-d trees are a useful data structure for several applications, such as searches involving a multidimensional search key (e.g. range searches and nearest neighbor searches). k-d trees are a special case of binary space partitioning trees. k-d trees are not suitable, however, for efficiently finding the nearest neighbor in high dimensional spaces. As a general rule, if the dimensionality is *k*, the number of points in the data, *N*, should be *N* ≫ 2<sup><i>k</i></sup>. Otherwise, when k-d trees are used with high-dimensional data, most of the points in the tree will be evaluated and the efficiency is no better than exhaustive search, and other methods such as approximate nearest-neighbor are used instead.
|
||||
Uma árvore k-d (abreviação de árvore *k*-dimensional) é uma estrutura de dados de particionamento de espaço para organizar pontos em um espaço k-dimensional. Árvores k-d são uma estrutura de dados útil para várias aplicações, como pesquisas envolvendo uma chave de pesquisa multidimensional (por exemplo, pesquisas por intervalo e pesquisas pelo vizinho mais próximo). As árvores k-d são um caso especial de árvores de particionamento de espaço binário. As árvores k-d não são adequadas, no entanto, para encontrar com eficiência o vizinho mais próximo em espaços de alta dimensão. Como regra geral, se a dimensionalidade for *k*, o número de pontos nos dados, *N*, deve ser *N* ≫ 2<sup><i>k</i></sup>. Caso contrário, quando as árvores k-d forem usadas com dados de alta dimensão, a maioria dos pontos na árvore será avaliada e a eficiência não será melhor do que em uma pesquisa exaustiva. Outros métodos, como o vizinho mais próximo aproximado, devem ser usados.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function to perform a nearest neighbour search using k-d tree. The function takes two parameters: an array of k-dimensional points, and a single k-dimensional point whose nearest neighbour should be returned by the function. A k-dimensional point will be given as an array of k elements.
|
||||
Escreva uma função para realizar a busca de um vizinho mais próximo usando uma árvore k-d. A função recebe dois parâmetros: um array de pontos k-dimensionais e um único ponto k-dimensional, cujo vizinho mais próximo deve ser retornado pela função. Será dado um ponto k-dimensional como um conjunto de k elementos.
|
||||
|
||||
# --hints--
|
||||
|
||||
`kdNN` should be a function.
|
||||
`kdNN` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof kdNN == 'function');
|
||||
```
|
||||
|
||||
`kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2])` should return an array.
|
||||
`kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -42,7 +42,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2])` should return `[ 8, 1 ]`.
|
||||
`kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [9, 2])` deve retornar `[ 8, 1 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -61,7 +61,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [7, 1])` should return `[ 8, 1 ]`.
|
||||
`kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [7, 1])` deve retornar `[ 8, 1 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -80,7 +80,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [3, 2])` should return `[ 2, 3 ]`.
|
||||
`kdNN([[[2, 3], [5, 4], [9, 6], [4, 7], [8, 1], [7, 2]], [3, 2])` deve retornar `[ 2, 3 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -99,7 +99,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [1, 2, 3])` should return `[ 1, 2, 5 ]`.
|
||||
`kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [1, 2, 3])` deve retornar `[ 1, 2, 5 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -118,7 +118,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [4, 5, 6])` should return `[ 4, 6, 7 ]`.
|
||||
`kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [4, 5, 6])` deve retornar `[ 4, 6, 7 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -137,7 +137,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [8, 8, 8])` should return `[ 7, 8, 9 ]`.
|
||||
`kdNN([[2, 3, 1], [9, 4, 5], [4, 6, 7], [1, 2, 5], [7, 8, 9], [3, 6, 1]], [8, 8, 8])` deve retornar `[ 7, 8, 9 ]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7eca
|
||||
title: Kaprekar numbers
|
||||
title: Números de Kaprekar
|
||||
challengeType: 5
|
||||
forumTopicId: 302296
|
||||
dashedName: kaprekar-numbers
|
||||
@ -8,77 +8,77 @@ dashedName: kaprekar-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
A positive integer is a [Kaprekar number](https://en.wikipedia.org/wiki/Kaprekar number) if:
|
||||
Um número inteiro positivo é um [número de Kaprekar](https://en.wikipedia.org/wiki/Kaprekar number) se:
|
||||
|
||||
<ul>
|
||||
<li>It is 1, or,</li>
|
||||
<li>The decimal representation of its square may be split once into two parts consisting of positive integers which sum to the original number. </li>
|
||||
<li>É o número 1, ou</li>
|
||||
<li>A representação decimal de seu quadrado puder ser dividida uma vez em duas partes, que consistem em inteiros positivos que, somados, resultam no número original. </li>
|
||||
</ul>
|
||||
|
||||
Note that a split resulting in a part consisting purely of 0s is not valid, as 0 is not considered positive.Example
|
||||
Note que uma divisão resultando em uma parte que consiste puramente em 0s não é válida, já que 0 não é considerado um número positivo. Veja o exemplo abaixo:
|
||||
|
||||
Kaprekar numbers:
|
||||
Números de Kaprekar:
|
||||
|
||||
<ul>
|
||||
<li><code>2223</code> is a Kaprekar number, as <code>2223 * 2223 = 4941729</code>, <code>4941729</code> may be split to <code>494</code> and <code>1729</code>, and <code>494 + 1729 = 2223</code></li>
|
||||
<li>The series of Kaprekar numbers is known as <a href='https://oeis.org/A006886' target='_blank'>A006886</a>, and begins as <code>1, 9, 45, 55, ...</code></li>
|
||||
<li><code>2223</code> é um número de Kaprekar, pois <code>2223 * 2223 = 4941729</code>, <code>4941729</code> pode ser dividido em <code>494</code> e <code>1729</code>, e <code>494 + 1729 = 2223</code></li>
|
||||
<li>A série de números de Kaprekar é conhecida como <a href='https://oeis.org/A006886' target='_blank'>A006886</a> e começa assim: <code>1, 9, 45, 55, ...</code></li>
|
||||
</ul>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes a number $n$, a base $bs$, and returns true if the number is a Kaprekar number for the given base. Otherwise, the function returns false.
|
||||
Escreva uma função que receba um número $n$, uma base $bs$, e retorne true se o número for um número de Kaprekar para a base fornecida. Caso contrário, a função retornará false.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isKaprekar` should be a function.
|
||||
`isKaprekar` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof isKaprekar == 'function');
|
||||
```
|
||||
|
||||
`isKaprekar(1, 10)` should return a boolean.
|
||||
`isKaprekar(1, 10)` deve retornar um booleano.
|
||||
|
||||
```js
|
||||
assert(typeof isKaprekar(1, 10) == 'boolean');
|
||||
```
|
||||
|
||||
`isKaprekar(1, 10)` should return `true`.
|
||||
`isKaprekar(1, 10)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isKaprekar(1, 10), true);
|
||||
```
|
||||
|
||||
`isKaprekar(9, 10)` should return `true`.
|
||||
`isKaprekar(9, 10)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isKaprekar(9, 10), true);
|
||||
```
|
||||
|
||||
`isKaprekar(2223, 10)` should return `true`.
|
||||
`isKaprekar(2223, 10)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isKaprekar(2223, 10), true);
|
||||
```
|
||||
|
||||
`isKaprekar(22823, 10)` should return `false`.
|
||||
`isKaprekar(22823, 10)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isKaprekar(22823, 10), false);
|
||||
```
|
||||
|
||||
`isKaprekar(9, 17)` should return `false`.
|
||||
`isKaprekar(9, 17)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isKaprekar(9, 17), false);
|
||||
```
|
||||
|
||||
`isKaprekar(225, 17)` should return `true`.
|
||||
`isKaprekar(225, 17)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isKaprekar(225, 17), true);
|
||||
```
|
||||
|
||||
`isKaprekar(999, 17)` should return `false`.
|
||||
`isKaprekar(999, 17)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isKaprekar(999, 17), false);
|
||||
|
Reference in New Issue
Block a user