chore(i18n,curriculum): update translations

This commit is contained in:
camperbot
2021-10-27 15:10:57 +00:00
committed by Mrugesh Mohapatra
parent e139fbcf13
commit c1fb339bbc
539 changed files with 3319 additions and 3352 deletions

View File

@ -8,31 +8,31 @@ dashedName: breadth-first-search
# --description--
So far, we've learned different ways of creating representations of graphs. What now? One natural question to have is what are the distances between any two nodes in the graph? Enter <dfn>graph traversal algorithms</dfn>.
Finora, abbiamo imparato diversi modi per creare rappresentazioni di grafi. E adesso? Una domanda naturale da porsi è quali sono le distanze tra due nodi qualsiasi nel grafo? Qui entrano in gioco gli <dfn>algoritmi di attraversamento di grafi</dfn>.
<dfn>Traversal algorithms</dfn> are algorithms to traverse or visit nodes in a graph. One type of traversal algorithm is the breadth-first search algorithm.
<dfn>Gli algoritmi di attraversamento</dfn> sono algoritmi per attraversare o visitare nodi in un grafo. Un tipo di algoritmo di attraversamento è l'algoritmo Breadth-first Search (di ricerca in ampiezza).
This algorithm starts at one node and visits all its neighbors that are one edge away. It then goes on to visit each of their neighbors and so on until all nodes have been reached.
Questo algoritmo inizia da un nodo e visita tutti i suoi vicini che sono ad un arco di distanza. Poi continua a visitare ciascuno dei loro vicini e così via fino a quando tutti i nodi sono stati raggiunti.
An important data structure that will help implement the breadth-first search algorithm is the queue. This is an array where you can add elements to one end and remove elements from the other end. This is also known as a <dfn>FIFO</dfn> or <dfn>First-In-First-Out</dfn> data structure.
Una struttura dati importante che aiuterà ad implementare l'algoritmo di ricerca in ampiezza è la coda. Questa è un array dove è possibile aggiungere elementi ad una estremità e rimuovere elementi dall'altra estremità. Essa è nota anche come una struttura di dati <dfn>FIFO</dfn> o <dfn>First-In-First-Out</dfn> (NdT: il primo a entrare è il primo a uscire).
Visually, this is what the algorithm is doing. ![Breadth first search algorithm moving through a tree](https://camo.githubusercontent.com/2f57e6239884a1a03402912f13c49555dec76d06/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f342f34362f416e696d617465645f4246532e676966)
Visualmente, questo è ciò che l'algoritmo sta facendo. ![Algoritmo Breadth-first Search che si muove attraverso un albero](https://camo.githubusercontent.com/2f57e6239884a1a03402912f13c49555dec76d06/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f342f34362f416e696d617465645f4246532e676966)
The grey shading represents a node getting added into the queue and the black shading represents a node getting removed from the queue. See how every time a node gets removed from the queue (node turns black), all their neighbors get added into the queue (node turns grey).
L'ombreggiatura grigia rappresenta un nodo che viene aggiunto alla coda e l'ombreggiatura nera rappresenta un nodo che viene rimosso dalla coda. Vedi come ogni volta che un nodo viene rimosso dalla coda (il nodo diventa nero), tutti i vicini vengono aggiunti alla coda (il nodo diventa grigio).
To implement this algorithm, you'll need to input a graph structure and a node you want to start at.
Per implementare questo algoritmo, dovrai inserire una struttura grafo e un nodo da cui vuoi iniziare.
First, you'll want to be aware of the distances from, or number of edges away from, the start node. You'll want to start all your distances with some large number, like `Infinity`. This prevents counting issues for when a node may not be reachable from your start node. Next, you'll want to go from the start node to its neighbors. These neighbors are one edge away and at this point you should add one unit of distance to the distances you're keeping track of.
Innanzitutto, dovrai essere consapevole delle distanze (o del numero di archi di distanza) dal nodo iniziale. Ti consigliamo di inizializzare tutte le distanze con un numero elevato, come `Infinity`. Questo impedisce problemi di conteggio per quando un nodo potrebbe non essere raggiungibile dal nodo iniziale. Successivamente, vorrai andare dal nodo iniziale ai suoi vicini. Questi vicini sono a un arco di distanza e a questo punto dovresti aggiungere un'unità di distanza alle distanze di cui stai tenendo traccia.
# --instructions--
Write a function `bfs()` that takes an adjacency matrix graph (a two-dimensional array) and a node label root as parameters. The node label will just be the integer value of the node between `0` and `n - 1`, where `n` is the total number of nodes in the graph.
Scrivi una funzione `bfs()` che prende un grafo a matrice di adiacenza (un array bidimensionale) e l'etichetta di un nodo radice come parametri. L'etichetta del nodo sarà solo il valore intero del nodo tra `0` e `n - 1`, dove `n` è il numero totale di nodi nel grafico.
Your function will output a JavaScript object key-value pairs with the node and its distance from the root. If the node could not be reached, it should have a distance of `Infinity`.
La tua funzione produrrà coppie chiave-valore di un oggetto JavaScript con il nodo e la sua distanza dalla radice. Se il nodo non può essere raggiunto, dovrebbe avere una distanza di `Infinity`.
# --hints--
The input graph `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` with a start node of `1` should return `{0: 1, 1: 0, 2: 1, 3: 2}`
Il grafico in ingresso `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` con un nodo iniziale di `1` dovrebbe restituire `{0: 1, 1: 0, 2: 1, 3: 2}`
```js
assert(
@ -49,7 +49,7 @@ assert(
);
```
The input graph `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]` with a start node of `1` should return `{0: 1, 1: 0, 2: 1, 3: Infinity}`
Il grafico in ingresso `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]` con un nodo iniziale di `1` dovrebbe restituire `{0: 1, 1: 0, 2: 1, 3: Infinity}`
```js
assert(
@ -66,7 +66,7 @@ assert(
);
```
The input graph `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` with a start node of `0` should return `{0: 0, 1: 1, 2: 2, 3: 3}`
Il grafico in ingresso `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` con un nodo iniziale di `0` dovrebbe restituire `{0: 0, 1: 1, 2: 2, 3: 3}`
```js
assert(
@ -83,7 +83,7 @@ assert(
);
```
The input graph `[[0, 1], [1, 0]]` with a start node of `0` should return `{0: 0, 1: 1}`
Il grafo in ingresso `[[0, 1], [1, 0]]` con un nodo iniziale di `0` dovrebbe restituire `{0: 0, 1: 1}`
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8255367417b2b2512c75
title: Create a Circular Queue
title: Creare una coda circolare
challengeType: 1
forumTopicId: 301625
dashedName: create-a-circular-queue
@ -8,9 +8,9 @@ dashedName: create-a-circular-queue
# --description--
In this challenge you will be creating a Circular Queue. A circular queue is a queue that writes to the end of a collection then begins overwriting itself at the beginning of the collection. This type of data structure is useful in certain situations. For example, a circular queue can be used for streaming media. Once the queue is full, new media data will overwrite old data.
In questa sfida creerai una coda circolare. Una coda circolare è una coda che scrive alla fine di una collezione, poi inizia a sovrascrivere sè stessa all'inizio della collezione. Questo tipo di struttura dati è utile in determinate situazioni. Ad esempio, una coda circolare può essere utilizzata per lo streaming media. Una volta che la coda è piena, i nuovi dati multimediali sovrascriveranno i vecchi dati.
A good way to illustrate this concept is with an array of length `5`:
Un buon modo per illustrare questo concetto è con un array di lunghezza `5`:
```js
[null, null, null, null, null]
@ -18,7 +18,7 @@ A good way to illustrate this concept is with an array of length `5`:
^Write @ 0
```
Here the read and write are both at position `0`. Now the queue gets 3 new records `a`, `b`, and `c`. Our queue now looks like:
Qui la lettura e la scrittura sono entrambe in posizione `0`. Ora la coda ottiene 3 nuovi record `a`, `b`e `c`. La nostra coda ora assomiglia a:
```js
[a, b, c, null, null]
@ -26,7 +26,7 @@ Here the read and write are both at position `0`. Now the queue gets 3 new recor
^Write @ 3
```
As the read head reads, it can remove values or keep them:
Come la testa di lettura legge, può remove valori o conservarli:
```js
[null, null, null, null, null]
@ -34,7 +34,7 @@ As the read head reads, it can remove values or keep them:
^Write @ 3
```
Now we write the values `d`, `e`, and `f` to the queue. Once the write reaches the end of the array it loops back to the beginning:
Ora scriviamo i valori `d`, `e` e `f` nella coda. Una volta che la scrittura raggiunge la fine dell'array si riprende dall'inizio:
```js
[f, null, null, d, e]
@ -42,21 +42,21 @@ Now we write the values `d`, `e`, and `f` to the queue. Once the write reaches t
^Write @ 1
```
This approach requires a constant amount of memory but allows files of a much larger size to be processed.
Questo approccio richiede una quantità costante di memoria, ma consente di elaborare file di dimensioni molto più grandi.
# --instructions--
In this challenge we will implement a circular queue. The circular queue should provide `enqueue` and `dequeue` methods which allow you to read from and write to the queue. The class itself should also accept an integer argument which you can use to specify the size of the queue when created. We've written the starting version of this class for you in the code editor.
In questa sfida implementeremo una coda circolare. La coda circolare dovrebbe fornire i metodi `enqueue` e `dequeue` che ti consentono di leggere e scrivere nella coda. La classe stessa dovrebbe anche accettare un argomento intero che puoi usare per specificare la dimensione della coda quando viene creata. Abbiamo scritto per te la versione iniziale di questa classe nell'editor di codice.
When you enqueue items to the queue, the write pointer should advance forward and loop back to the beginning once it reaches the end of the queue. The `enqueue` method should return the item you enqueued if it is successful; otherwise it will return `null`.
Quando accodi gli elementi alla coda, il puntatore di scrittura dovrebbe andare in avanti e tornare all'inizio una volta che ha raggiunto la fine della coda. Il metodo `enqueue` dovrebbe restituire l'elemento che hai accodato se ha avuto successo; altrimenti restituirà `null`.
Likewise, the read pointer should advance forward as you dequeue items. When you dequeue an item, that item should be returned. If you cannot dequeue an item, you should return `null`.
Allo stesso modo, il puntatore di lettura dovrebbe avanzare come rimuovi oggetti dalla coda. Quando rimuovi un oggetto dalla coda, quell'oggetto dovrebbe essere restituito. Se non puoi rimuovere un oggetto dalla coda, dovresti restituire `null`.
The write pointer should not be allowed to move past the read pointer (our class won't let you overwrite data you haven't read yet) and the read pointer should not be able to advance past data you have written.
Al puntatore di scrittura non dovrebbe essere permesso di muovere oltre il puntatore di lettura (la nostra classe non ti permetterà di sovrascrivere dati che non sono ancora stati letti) e il puntatore di lettura non dovrebbe eessere in grado di andare oltre i dati che hai scritto.
# --hints--
The `enqueue` method should add items to the circular queue.
Il metodo `enqueue` dovrebbe aggiungere elementi alla coda circolare.
```js
assert(
@ -71,7 +71,7 @@ assert(
);
```
You should not enqueue items past the read pointer.
Non dovresti accodare gli elementi oltre il puntatore di lettura.
```js
assert(
@ -89,7 +89,7 @@ assert(
);
```
The `dequeue` method should dequeue items from the queue.
Il metodo `dequeue` dovrebbe rimuovere elementi dalla coda.
```js
assert(
@ -105,7 +105,7 @@ assert(
);
```
After an item is dequeued, its position in the queue should be reset to `null`.
Dopo che un elemento è stato rimosso dalla coda, la sua posizione nella coda dovrebbe essere resettata su `null`.
```js
assert(
@ -122,7 +122,7 @@ assert(
);
```
Trying to dequeue past the write pointer should return `null` and does not advance the write pointer.
Tentare di rimuovere oggetti dalla coda oltre il puntatore di scrittura dovrebbe restituire `null` e non far avanzare il puntatore di scrittura.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d825b367417b2b2512c8e
title: Create a Hash Table
title: Creare una tabella hash
challengeType: 1
forumTopicId: 301627
dashedName: create-a-hash-table
@ -8,23 +8,23 @@ dashedName: create-a-hash-table
# --description--
In this challenge we will learn about hash tables. A Hash table is used to implement associative arrays, or mappings of key-value pairs, like the objects and Maps we have just been studying. A JavaScript object could be implemented as a hash table, for instance (its actual implementation will depend on the environment it's running in). The way a hash table works is that it takes a key input and hashes this key in a deterministic way to some numerical value. This numerical value is then used as the actual key the associated value is stored by. Then, if you try to access the same key again, the hashing function will process the key, return the same numerical result, which will then be used to look up the associated value. This provides very efficient O(1) lookup time on average.
In questa sfida conosceremo le tabelle hash. Una tabella hash viene utilizzata per implementare array associativi, o mappature di coppie chiave-valore, come gli oggetti e le mappe che abbiamo appena studiato. Un oggetto JavaScript ad esempio potrebbe essere implementato come una tabella hash (la sua effettiva implementazione dipenderà dall'ambiente in esecuzione). Il modo in cui funziona una tabella di hash è che richiede un input chiave e fa hash di questa chiave in modo deterministico ad un certo valore numerico. Questo valore numerico viene quindi utilizzato come chiave reale con cui viene memorizzato il valore associato. Quindi, se si tenta di accedere di nuovo alla stessa chiave, la funzione di hash elaborerà la chiave, restituirà lo stesso risultato numerico, che verrà poi utilizzato per cercare il valore associato. Questo fornisce un tempo di ricerca O(1) molto efficiente in media.
Hash tables can be implemented as arrays with hash functions producing array indices within a specified range. In this method, the choice of the array size is important, as is the hashing function. For instance, what if the hashing function produces the same value for two different keys? This is called a collision. One way to handle collisions is to just store both key-value pairs at that index. Then, upon lookup of either, you would have to iterate through the bucket of items to find the key you are looking for. A good hashing function will minimize collisions to maintain efficient search time.
Le tabelle di hash possono essere implementate come array con funzioni di hash che producono indici array all'interno di un intervallo specificato. In questo metodo, la scelta della dimensione dell'array è importante, così come la funzione di hashing. Per esempio, cosa succede se la funzione di hashing produce lo stesso valore per due chiavi diverse? Questa si chiama collisione. Un modo per gestire le collisioni è quello di semplicemente memorizzare entrambe le coppie chiave-valore in quell'indice. Poi, alla ricerca di entrambi, si dovrebbe iterare attraverso il gruppo di oggetti per trovare la chiave che stai cercando. Una buona funzione di hashing minimizzerà le collisioni per mantenere il tempo di ricerca efficiente.
Here, we won't be concerned with the details of hashing or hash table implementation, we will just try to get a general sense of how they work.
Risultati della traduzione Qui non ci occuperemo dei dettagli dell'hashing o dell'implementazione della tabella hash, cercheremo solo di avere un'idea generale di come funzionano.
# --instructions--
Let's create the basic functionality of a hash table. We've created a naive hashing function for you to use. You can pass a string value to the function `hash` and it will return a hashed value you can use as a key for storage. Store items based on this hashed value in the `this.collection` object. Create these three methods: `add`, `remove`, and `lookup`. The first should accept a key value pair to add to the hash table. The second should remove a key-value pair when passed a key. The third should accept a key and return the associated value or `null` if the key is not present.
Creiamo la funzionalità di base di una tabella di hash. Abbiamo creato una funzione di hashing ingenua da usare. Puoi passare un valore di stringa alla funzione `hash` e restituirà un valore hashed che puoi usare come chiave per l'archiviazione. Memorizza gli oggetti in base a questo valore hashed nell'oggetto `this.collection`. Crea questi tre metodi: `add`, `remove` e `lookup`. Il primo dovrebbe accettare una coppia di valori chiave da aggiungere alla tabella hash. Il secondo dovrebbe rimuovere una coppia chiave-valore quando riceve una chiave. Il terzo dovrebbe accettare una chiave e restituire il valore associato o `null` se la chiave non è presente.
Be sure to write your code to account for collisions!
Assicurati di scrivere il tuo codice per gestire le collisioni!
**Note:** The `remove` method tests won't pass until the `add` and `lookup` methods are correctly implemented.
**Nota:** I test del metodo `remove` non passeranno fino a quando i metodi `add` e `lookup` non saranno correttamente implementati.
# --hints--
The HashTable data structure should exist.
La struttura di dati HashTable dovrebbe esistere.
```js
assert(
@ -38,7 +38,7 @@ assert(
);
```
The HashTable should have an add method.
L'HashTable dovrebbe avere un metodo add.
```js
assert(
@ -52,7 +52,7 @@ assert(
);
```
The HashTable should have a lookup method.
L'HashTable dovrebbe avere un metodo lookup.
```js
assert(
@ -66,7 +66,7 @@ assert(
);
```
The HashTable should have a remove method.
L'HashTable dovrebbe avere un metodo remove.
```js
assert(
@ -80,7 +80,7 @@ assert(
);
```
The add method should add key value pairs and the lookup method should return the values associated with a given key.
Il metodo add dovrebbe aggiungere coppie chiave-valore e il metodo di ricerca dovrebbe restituire i valori associati a una determinata chiave.
```js
assert(
@ -95,7 +95,7 @@ assert(
);
```
The remove method should accept a key as input and should remove the associated key value pair.
Il metodo di rimozione dovrebbe accettare una chiave come input e dovrebbe rimuovere la coppia chiave-valore associata.
```js
assert(
@ -113,7 +113,7 @@ assert(
);
```
The remove method should only remove the correct key value pair.
Il metodo di rimozione dovrebbe rimuovere solo la coppia chiave-valore corretta.
```js
assert(
@ -139,7 +139,7 @@ assert(
);
```
Items should be added using the hash function.
Gli elementi devono essere aggiunti usando la funzione hash.
```js
assert(
@ -157,7 +157,7 @@ assert(
);
```
The hash table should handle collisions.
La tabella di hash dovrebbe gestire le collisioni.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8250367417b2b2512c60
title: Creare una classe Coda
title: Creare una classe Queue
challengeType: 1
forumTopicId: 301631
dashedName: create-a-queue-class

View File

@ -1,6 +1,6 @@
---
id: 587d8259367417b2b2512c84
title: Create a Trie Search Tree
title: Crea un albero di ricerca Trie
challengeType: 1
forumTopicId: 301634
dashedName: create-a-trie-search-tree
@ -8,15 +8,15 @@ dashedName: create-a-trie-search-tree
# --description--
Here we will move on from binary search trees and take a look at another type of tree structure called a trie. A trie is an ordered search tree commonly used to hold strings, or more generically associative arrays or dynamic datasets in which the keys are strings. They are very good at storing sets of data when many keys will have overlapping prefixes, for example, all the words in a dictionary. Unlike a binary tree, nodes are not associated with actual values. Instead, the path to a node represents a specific key. For instance, if we wanted to store the string code in a trie, we would have four nodes, one for each letter: c — o — d — e. Following that path through all these nodes will then create code as a string — that path is the key we stored. Then, if we wanted to add the string coding, it would share the first three nodes of code before branching away after the d. In this way, large datasets can be stored very compactly. In addition, search can be very quick because it is effectively limited to the length of the string you are storing. Furthermore, unlike binary trees a node can store any number of child nodes. As you might have guessed from the above example, some metadata is commonly stored at nodes that hold the end of a key so that on later traversals that key can still be retrieved. For instance, if we added codes in our example above we would need some way to know that the e in code represents the end of a key that was previously entered. Otherwise, this information would effectively be lost when we add codes.
Qui ci muoveremo dagli alberi di ricerca binari e daremo un'occhiata ad un altro tipo di struttura ad albero chiamato trie. Un trie è un albero di ricerca ordinato comunemente usato per contenere stringhe, o più generamente array associativi o dataset dinamici in cui le chiavi sono stringhe. Sono un ottimo modo per immagazzinare set di dati quando molte chiavi hanno prefissi che si sovrappongono, per esempio, tutte le parole in un dizionario. A differenza di un albero binario, i nodi non sono associati con valori. Invece, il percorso verso un nodo rappresenta una chiave specifica. Per esempio, se vogliamo salvare la stringa "code" in un trie, avremmo quattri nodi, uno per ogni lettera: c — o — d — e. Seguendo il percorso attraverso tutti questi nodi creerà la stringa "code" — quel percorso è la chiave che abbiamo immagazzinato. Quindi, se vogliamo aggiungere la stringa "coding", avrebbe in comune i primi tre nodi di "code" prima di seguire un altro ramo dopo la d. In questo modo, dataset ampi possono essere immagazzinati in maniera compatta. In aggiunta, una ricerca può essere molto veloce perché è effettivamente limitata alla lunghezza della stringa che stai immagazinnando. Inoltre, a differenza degli alberi binari un nodo può avere qualsiasi numero di nodi figli. Come potresti avere indovinato dall'esempio precedente, alcuni metadata sono comunemente salvati come nodi che contengono la fine della chiave cossicché in traversamenti succestivi la chiave può essere ancora recuperata. Per esempio, se avessimo aggiunto "codes" nell'esempio precedente, avremmo avuto bisogno di qualche modo per sapere che la e in "code" rappresenta la fine di una chiave che era stata inserita precedentemente. Altrimenti, questa informazione andrebbe persa quando aggiungiamo "codes".
# --instructions--
Let's create a trie to store words. It will accept words through an `add` method and store these in a trie data structure. It will also allow us to query if a given string is a word with an `isWord` method, and retrieve all the words entered into the trie with a `print` method. `isWord` should return a boolean value and print should return an array of all these words as string values. In order for us to verify that this data structure is implemented correctly, we've provided a `Node` structure for each node in the tree. Each node will be an object with a `keys` property which is a JavaScript Map object. This will hold the individual letters that are valid keys of each node. We've also created an `end` property on the nodes that can be set to `true` if the node represents the termination of a word.
Creiamo un trie per memorizzare parole. Accetterà parole attraverso un metodo `add` e salverà queste parole in una struttura dati trie. Permetterà anche di chiedere se una certa stringa è una parola con un metodo `isWord`, e estrarre tutte le parole inserite nel trie con un metodo `print`. `isWord` dovrebbe restituire un valore booleano e print dovrebbe restituire un array di tutte queste parole come stringhe. Per poter verificare che la struttura dati è implementata correttamente, abbiamo provveduto una struttura `Node` per ogni nodo dell'albero. Ogni nodo sarà un oggetto con una proprietà `keys` che è un oggetto Map JavaScript. Questo conterrà le lettere individuali che sono chiavi valide per ogni nodo. Abbiamo anche creato una proprietà `end` nel nodo che può essere messa su `true` se il nodo rappresenta la terminazione di una parola.
# --hints--
The Trie should have an add method.
Il Trie dovrebbe avere un metodo add.
```js
assert(
@ -32,7 +32,7 @@ assert(
);
```
The Trie should have a print method.
Il Trie dovrebbe avere un metodo print.
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
The Trie should have an isWord method.
Il Trie dovrebbe avere un metodo isWord.
```js
assert(
@ -64,7 +64,7 @@ assert(
);
```
The print method should return all items added to the trie as strings in an array.
Il metodo print dovrebbe restituire tutti gli elementi aggiunti al trie come stringhe in un array.
```js
assert(
@ -93,7 +93,7 @@ assert(
);
```
The isWord method should return true only for words added to the trie and false for all other words.
Il metodo isWord dovrebbe restituire vero solo per le parole aggiunte al trie e falso per tutte le altre parole.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d825b367417b2b2512c8d
title: Create an ES6 JavaScript Map
title: Creare una mappa JavaScript ES6
challengeType: 1
forumTopicId: 301635
dashedName: create-an-es6-javascript-map
@ -8,21 +8,21 @@ dashedName: create-an-es6-javascript-map
# --description--
The new version of JavaScript provides us with a built-in Map object which provides much of the functionality we wrote by hand in the last challenge. This Map object, although similar to regular JavaScript objects, provides some useful functionality that normal objects lack. For example, an ES6 Map tracks the insertion order of items that are added to it. Here is a more complete overview of its methods: `.has(key)` returns true or false based on the presence of a key `.get(key)` returns the value associated with a key `.set(key, value)` sets a new key, value pair `.delete(key)` removes a key, value pair `.clear()` removes all key, value pairs `.entries()` returns an array of all the keys in insertion order `.values()` returns an array of all the values in insertion order
La nuova versione di JavaScript ci fornisce un oggetto Map incorporato che fornisce gran parte delle funzionalità che abbiamo scritto a mano nell'ultima sfida. Questo oggetto Map, anche se simile a oggetti JavaScript regolari, fornisce alcune funzionalità utili che agli oggetti normali mancano. Ad esempio, una Map ES6 tiene in memoria l'ordine di inserimento degli elementi che vengono aggiunti. Ecco una panoramica più completa dei suoi metodi: `.has(key)` restituisce true o false in base alla presenza di una chiave `.get(key)` restituisce il valore associato con una chiave `.set(key, value)` aggiunge una nuova coppia chiave-valore `.delete(key)` rimuove una coppia chiave-valore `.clear()` rimuove tutte le coppie chiave-valore `.entries()` restituisce un array con tutte le chiavi in ordine di inserimento `.values()` restituisce un array con tutti i valori in ordine di inserzione
# --instructions--
Define a JavaScript Map object and assign to it a variable called myMap. Add the key, value pair `freeCodeCamp`, `Awesome!` to it.
Definisci un oggetto Map JavaScript e assegna ad esso una variabile chiamata myMap. Aggiungi la coppia chiave-valore `freeCodeCamp`, `Awesome!` ad esso.
# --hints--
The myMap object should exist.
L'oggetto myMap dovrebbe esistere.
```js
assert(typeof myMap === 'object');
```
myMap should contain the key value pair `freeCodeCamp`, `Awesome!`.
myMap dovrebbe contenere la coppia chiave-valore `freeCodeCamp`, `Awesome!`.
```js
assert(myMap.get('freeCodeCamp') === 'Awesome!');
@ -39,5 +39,7 @@ assert(myMap.get('freeCodeCamp') === 'Awesome!');
# --solutions--
```js
// solution required
const myMap = new Map();
myMap.set("freeCodeCamp", "Awesome!");
```

View File

@ -1,6 +1,6 @@
---
id: 587d8254367417b2b2512c70
title: Create and Add to Sets in ES6
title: Creare e aggiungere ai set in ES6
challengeType: 1
forumTopicId: 301636
dashedName: create-and-add-to-sets-in-es6
@ -8,34 +8,34 @@ dashedName: create-and-add-to-sets-in-es6
# --description--
Now that you have worked through ES5, you are going to perform something similar in ES6. This will be considerably easier. ES6 contains a built-in data structure `Set` so many of the operations you wrote by hand are now included for you. Let's take a look:
Ora che avete lavorato su ES5, state per eseguire qualcosa di simile in ES6. Questo sarà molto più facile. ES6 contiene una struttura di dati integrata `Set` quindi molte delle operazioni che hai scritto a mano sono ora incluse per te. Diamo un'occhiata:
To create a new empty set:
Per creare un nuovo set vuoto:
```js
var set = new Set();
```
You can create a set with a value:
È possibile creare un set con un valore:
```js
var set = new Set(1);
```
You can create a set with an array:
È possibile creare un set con un array:
```js
var set = new Set([1, 2, 3]);
```
Once you have created a set, you can add the values you wish using the `add` method:
Una volta creato un set, puoi aggiungere i valori che desideri utilizzando il metodo `add`:
```js
var set = new Set([1, 2, 3]);
set.add([4, 5, 6]);
```
As a reminder, a set is a data structure that cannot contain duplicate values:
Come promemoria, un insieme è una struttura di dati che non può contenere valori duplicati:
```js
var set = new Set([1, 2, 3, 1, 2, 3]);
@ -44,11 +44,11 @@ var set = new Set([1, 2, 3, 1, 2, 3]);
# --instructions--
For this exercise, return a set with the following values: `1, 2, 3, 'Taco', 'Cat', 'Awesome'`
Per questo esercizio, restituisci un set con i seguenti valori: `1, 2, 3, 'Taco', 'Cat', 'Awesome'`
# --hints--
Your `Set` should only contain the values `1, 2, 3, Taco, Cat, Awesome`.
Il tuo `Set` deve contenere solo i valori `1, 2, 3, Taco, Cat, Awesome`.
```js
assert(

View File

@ -46,6 +46,25 @@ assert(
);
```
Tentare di rimuovere un elemento da un albero vuoto dovrebbe restituire `null`.
```js
assert(
(function () {
var test = false;
if (typeof BinarySearchTree !== 'undefined') {
test = new BinarySearchTree();
} else {
return false;
}
if (typeof test.remove !== 'function') {
return false;
}
return test.remove(100) == null;
})()
);
```
Tentare di rimuovere un elemento che non esiste dovrebbe restituire `null`.
```js
@ -60,6 +79,8 @@ assert(
if (typeof test.remove !== 'function') {
return false;
}
test.add(15);
test.add(30);
return test.remove(100) == null;
})()
);

View File

@ -1,6 +1,6 @@
---
id: 587d8257367417b2b2512c7d
title: Find the Minimum and Maximum Height of a Binary Search Tree
title: Trovare l'altezza minima e massima di un albero binario di ricerca
challengeType: 1
forumTopicId: 301641
dashedName: find-the-minimum-and-maximum-height-of-a-binary-search-tree
@ -8,19 +8,19 @@ dashedName: find-the-minimum-and-maximum-height-of-a-binary-search-tree
# --description--
In the last challenge we described a scenario in which a tree could become unbalanced. To understand the concept of balance, let's take a look at another tree property: height. Height in a tree represents the distance from the root node to any given leaf node. Different paths in a highly branched tree structure may have different heights, but for a given tree there will be a minimum and maximum height. If the tree is balanced, these values will differ at most by one. This means that in a balanced tree, all the leaf nodes exist within the same level, or if they are not within the same level they are at most one level apart.
Nell'ultima sfida abbiamo descritto uno scenario in cui un albero potrebbe diventare squilibrato. Per capire il concetto di equilibrio, diamo un'occhiata ad un'altra proprietà dell'albero: l'altezza. L'altezza in un albero rappresenta la distanza dal nodo radice a qualsiasi nodo foglia. Percorsi diversi in una struttura ad albero altamente ramificato possono avere altezze diverse, ma per un dato albero ci sarà un'altezza minima e una massima. Se l'albero è bilanciato, questi valori differiranno al massimo di uno. Ciò significa che in un albero bilanciato, tutti i nodi delle foglie sono allo stesso livello, o al massimo a un livello di distanza.
The property of balance is important for trees because it is what determines the efficiency of tree operations. As we explained in the last challenge, we face worst case time complexity for heavily unbalanced trees. Self-balancing trees are commonly used to account for this issue in trees with dynamic data sets. Common examples of these include AVL trees, red-black trees, and B-trees. These trees all contain additional internal logic which re-balance the tree when insertions or deletions create a state of imbalance.
La proprietà dell'equilibrio è importante per gli alberi perché è ciò che determina l'efficienza delle operazioni su di essi. Come abbiamo spiegato nell'ultima sfida, per alberi fortemente squilibrati ci troviamo di fronte alla peggiore complessità temporale. Gli alberi auto-bilancianti sono comunemente utilizzati per tenere conto di questo problema in alberi con serie di dati dinamici. Esempi comuni di questi includono gli alberi AVL, gli alberi rosso-neri e gli alberi B. Tutti questi alberi contengono una logica interna aggiuntiva che riequilibra l'albero quando inserzioni o cancellazioni creano uno stato di squilibrio.
**Note:** A similar property to height is depth, which refers to how far a given node is from the root node.
**Nota:** Una proprietà simile all'altezza è la profondità, che si riferisce a quanto un dato nodo è lontano dal nodo radice.
# --instructions--
Write two methods for our binary tree: `findMinHeight` and `findMaxHeight`. These methods should return an integer value for the minimum and maximum height within a given binary tree, respectively. If the node is empty let's assign it a height of `-1` (that's the base case). Finally, add a third method `isBalanced` which returns `true` or `false` depending on whether the tree is balanced or not. You can use the first two methods you just wrote to determine this.
Scrivi due metodi per il nostro albero binario: `findMinHeight` e `findMaxHeight`. Questi metodi dovrebbero restituire un valore intero per l'altezza minima e massima all'interno di un dato albero binario, rispettivamente. Se il nodo è vuoto, assegniamogli un'altezza di `-1` (questo è il caso di base). Infine, aggiungi un terzo metodo `isBalanced` che restituisce `true` o `false` a seconda che l'albero sia bilanciato o meno. È possibile utilizzare i primi due metodi che hai appena scritto per determinarlo.
# --hints--
The `BinarySearchTree` data structure should exist.
La struttura di dati `BinarySearchTree` dovrebbe esistere.
```js
assert(
@ -34,7 +34,7 @@ assert(
);
```
The binary search tree should have a method called `findMinHeight`.
L'albero binario di ricerca dovrebbe avere un metodo chiamato `findMinHeight`.
```js
assert(
@ -50,7 +50,7 @@ assert(
);
```
The binary search tree should have a method called `findMaxHeight`.
L'albero binario di ricerca dovrebbe avere un metodo chiamato `findMaxHeight`.
```js
assert(
@ -66,7 +66,7 @@ assert(
);
```
The binary search tree should have a method called `isBalanced`.
L'albero binario di ricerca dovrebbe avere un metodo chiamato `isBalanced`.
```js
assert(
@ -82,7 +82,7 @@ assert(
);
```
The `findMinHeight` method should return the minimum height of the tree.
Il metodo `findMinHeight` deve restituire l'altezza minima dell'albero.
```js
assert(
@ -109,7 +109,7 @@ assert(
);
```
The `findMaxHeight` method should return the maximum height of the tree.
Il metodo `findMaxHeight` deve restituire l'altezza massima dell'albero.
```js
assert(
@ -136,7 +136,7 @@ assert(
);
```
An empty tree should return a height of `-1`.
Un albero vuoto dovrebbe restituire un'altezza di `-1`.
```js
assert(
@ -155,7 +155,7 @@ assert(
);
```
The `isBalanced` method should return `false` if the tree is an unbalanced binary search tree.
Il metodo `isBalanced` dovrebbe restituire `false` se l'albero è un albero binario di ricerca sbilanciato.
```js
assert(
@ -182,7 +182,7 @@ assert(
);
```
The `isBalanced` method should return `true` if the tree is a balanced binary search tree.
Il metodo `isBalanced` dovrebbe restituire `true` se l'albero è un albero binario di ricerca equilibrato.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8256367417b2b2512c7a
title: Find the Minimum and Maximum Value in a Binary Search Tree
title: Trovare i valori minimo e massimo di un albero binario di ricerca
challengeType: 1
forumTopicId: 301642
dashedName: find-the-minimum-and-maximum-value-in-a-binary-search-tree
@ -8,11 +8,11 @@ dashedName: find-the-minimum-and-maximum-value-in-a-binary-search-tree
# --description--
In this challenge you will define two methods, `findMin` and `findMax`. These methods should return the minimum and maximum value held in the binary search tree (don't worry about adding values to the tree for now, we have added some in the background). If you get stuck, reflect on the invariant that must be true for binary search trees: each left subtree is less than or equal to its parent and each right subtree is greater than or equal to its parent. Let's also say that our tree can only store integer values. If the tree is empty, either method should return `null`.
In questa sfida definirai due metodi, `findMin` e `findMax`. Questi metodi dovrebbero restituire il valore minimo e massimo contenuto nell'albero binario di ricerca (non preoccuparti di aggiungere valori all'albero per ora, ne abbiamo aggiunti alcuni in background). Se si rimani bloccato, rifletti sull'invariante che deve essere vera per gli alberi di ricerca binari: ogni sottoalbero sinistro è inferiore o uguale al suo genitore e ogni sottoalbero destro è maggiore o uguale al suo genitore. Diciamo anche che il nostro albero può memorizzare solo valori interi. Se l'albero è vuoto, uno dei due metodi dovrebbe restituire `null`.
# --hints--
The `BinarySearchTree` data structure should exist.
La struttura di dati `BinarySearchTree` dovrebbe esistere.
```js
assert(
@ -26,7 +26,7 @@ assert(
);
```
The binary search tree should have a method called `findMin`.
L'albero binario di ricerca dovrebbe avere un metodo chiamato `findMin`.
```js
assert(
@ -42,7 +42,7 @@ assert(
);
```
The binary search tree should have a method called `findMax`.
L'albero di ricerca binario dovrebbe avere un metodo chiamato `findMax`.
```js
assert(
@ -58,7 +58,7 @@ assert(
);
```
The `findMin` method should return the minimum value in the binary search tree.
Il metodo `findMin` dovrebbe restituire il valore minimo nell'albero binario di ricerca.
```js
assert(
@ -85,7 +85,7 @@ assert(
);
```
The `findMax` method should return the maximum value in the binary search tree.
Il metodo `findMax` dovrebbe restituire il valore massimo nell'albero binario di ricerca.
```js
assert(
@ -112,7 +112,7 @@ assert(
);
```
The `findMin` and `findMax` methods should return `null` for an empty tree.
I metodi `findMin` e `findMax` dovrebbero restituire `null` per un albero vuoto.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d825b367417b2b2512c8c
title: Implement Heap Sort with a Min Heap
title: Implementa un Heap Sort con un Min Heap
challengeType: 1
forumTopicId: 301643
dashedName: implement-heap-sort-with-a-min-heap
@ -8,17 +8,17 @@ dashedName: implement-heap-sort-with-a-min-heap
# --description--
Now that we can add and remove elements let's see some of the applications heaps can be used for. Heaps are commonly used to implement priority queues because they always store an item of greatest or least value in first position. In addition, they are used to implement a sorting algorithm called heap sort. We'll see how to do this here. Heap sort uses a min heap, the reverse of a max heap. A min heap always stores the element of least value in the root position.
Ora che possiamo aggiungere e rimuovere elementi vediamo alcune applicazioni per cui gli heap possono essere usati. Gli heap sono comunemente usati per implementare file di priorità perché immagazzinano sempre un elemento di valore massimo o minimo nella prima posizione. In aggiunta, sono usati per implementare un algoritmo di ordinamento chiamato heap sort. Vedremo come farlo qui. Heap sort usa un min heap, l'opposto di un max heap. Un min heap ha sempre l'elemento di valore minore nella posizione root.
Heap sort works by taking an unsorted array, adding each item in the array into a min heap, and then extracting every item out of the min heap into a new array. The min heap structure ensures that the new array will contain the original items in least to greatest order. This is one of the most efficient sorting algorithms with average and worst case performance of O(nlog(n)).
Heap sort funziona prendendo un array non ordinato, aggiungendo ogni elemento dell'array in un min heap, e poi estraendo ogni elemento dal min heap in un array. La struttura min heap assicura che il nuovo array conterra gli elementi originali in ordine dal più piccolo al più grande. Questo è uno degli algoritmi per ordinare più efficienti con una performance media e nel peggiore dei casi di O(nlog(n)).
# --instructions--
Let's implement heap sort with a min heap. Feel free to adapt your max heap code here. Create an object `MinHeap` with `insert`, `remove`, and `sort` methods. The `sort` method should return an array of all the elements in the min heap sorted from smallest to largest.
Implementa un heap sort con un min heap. Adatta liberamente il codice del tuo max heap qui. Crea un oggetto `MinHeap` con metodi `insert`, `remove`, e `sort`. Il metodo `sort` dovrebbe restituire un array degli elementi nel min heap ordinati dal più piccolo al più grande.
# --hints--
The MinHeap data structure should exist.
La struttura dati MinHeap dovrebbe esistere.
```js
assert(
@ -32,7 +32,7 @@ assert(
);
```
MinHeap should have a method called insert.
MinHeap dovrebbe avere un metodo chiamato insert.
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
MinHeap should have a method called remove.
MinHeap dovrebbe avere un metodo chiamato remove.
```js
assert(
@ -64,7 +64,7 @@ assert(
);
```
MinHeap should have a method called sort.
MinHeap dovrebbe avere un metodo chiamato sort.
```js
assert(
@ -80,7 +80,7 @@ assert(
);
```
The sort method should return an array containing all items added to the min heap in sorted order.
Il metodo sort dovrebbe restituire un array che continuete tutto gli elementi aggiunti al min heap ordinati.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d825a367417b2b2512c8a
title: Insert an Element into a Max Heap
title: Inserisci un elemento in un max heap
challengeType: 1
forumTopicId: 301703
dashedName: insert-an-element-into-a-max-heap
@ -8,47 +8,47 @@ dashedName: insert-an-element-into-a-max-heap
# --description--
Now we will move on to another tree data structure, the binary heap. A binary heap is a partially ordered binary tree which satisfies the heap property. The heap property specifies a relationship between parent and child nodes. You may have a max heap, in which all parent nodes are greater than or equal to their child nodes, or a min heap, in which the reverse is true. Binary heaps are also complete binary trees. This means that all levels of the tree are fully filled and if the last level is partially filled it is filled from left to right.
Ora passeremo ad un'altra struttura di dati ad albero, l'heap binario. Un heap binario è un albero binario parzialmente ordinato che soddisfa la proprietà heap. La proprietà heap specifica una relazione tra nodi genitore e figlio. Potresti avere un max heap, in cui tutti i nodi genitori sono maggiori o uguali ai loro nodi figli, o un min heap, in cui il contrario è vero. Gli heap binari sono anche alberi binari completi. Questo significa che tutti i livelli dell'ablero sono completamente pieni e se l'ultimo livello è completo solo parzialmente è riempido da sinistra a destra.
While binary heaps may be implemented as tree structures with nodes that contain left and right references, the partial ordering according to the heap property allows us to represent the heap with an array. The parent-children relationship is what we're interested in and with simple arithmetic we can compute the children of any parent and the parent of any child node.
Anche se gli heap binari possono essere implementati come strutture ad albero con nodi che contengono riferimenti di sinistra e destra, l'ordine parziale in base alla proprietà heap ci permette di rappresentare l'heap con un array. Il rapporto genitore-figlio è quello a cui siamo interessati e con semplice aritmetica possiamo calcolare i figli di qualsiasi genitore e genitore di qualsiasi nodo figlio.
For instance, consider this array representation of a binary min heap:
Per esempio, considera questa rappresentazione array di un min heap binario:
```js
[ 6, 22, 30, 37, 63, 48, 42, 76 ]
```
The root node is the first element, `6`. Its children are `22` and `30`. If we look at the relationship between the array indices of these values, for index `i` the children are `2 * i + 1` and `2 * i + 2`. Similarly, the element at index `0` is the parent of these two children at indices `1` and `2`. More generally, we can find the parent of a node at any index with the following: `Math.floor((i - 1) / 2)`. These patterns will hold true as the binary tree grows to any size. Finally, we can make a slight adjustment to make this arithmetic even easier by skipping the first element in the array. Doing this creates the following relationship for any element at a given index `i`:
Il nodo radice è il primo elemento, `6`. I suoi figli sono `22` e `30`. Se consideriamo il rapporto tra gli indici di questi valori, per indice `i` i figli sono `2 * i + 1` e `2 * i + 2`. Analogamente, l'elemento all'indice `0` è il genitore di questi due figli agli indici `1` e `2`. Più in generale, possiamo trovare il genitore di un nodo in qualsiasi indice con il seguente: `Math.floor((i - 1) / 2)`. Questi pattern resteranno veri come l'albero cresce ad ogni dimensione. Infine, possiamo fare alcuni piccoli aggiustamenti per fare questa aritmetica ancora più semplice saltando il primo elemento dell'array. Facendo ciò si crea la seguente relazione per ogni elemento ad un dato indice `i`:
Example array representation:
Esempio di rappresentazione come array:
```js
[ null, 6, 22, 30, 37, 63, 48, 42, 76 ]
```
An element's left child: `i * 2`
Il figlio sinistro di un elemento: `i * 2`
An element's right child: `i * 2 + 1`
Il figlio destro di un elemento: `i * 2 + 1`
An element's parent: `Math.floor(i / 2)`
Il genitore di un elemento: `Math.floor(i / 2)`
Once you wrap your head around the math, using an array representation is very useful because node locations can be quickly determined with this arithmetic and memory usage is diminished because you don't need to maintain references to child nodes.
Una volta che prendi familiarità con la matematica, usare una rappresentazione ad array è molto utile perché la posizione dei nodi può essere determinata con questa artimetica e l'uso della memoria è diminuito perché non devi mantenere i riferimenti ai nodi figli.
# --instructions--
Instructions: Here we will create a max heap. Start by just creating an `insert` method which adds elements to our heap. During insertion, it is important to always maintain the heap property. For a max heap this means the root element should always have the greatest value in the tree and all parent nodes should be greater than their children. For an array implementation of a heap, this is typically accomplished in three steps:
Istruzioni: qui creeremo un max heap. Inizia creando semplicemente un metodo `insert` che aggiunge elementi al nostro heap. Durante l'inserzione, è importante mantenere sempre la proprietà heap. Per un max heap questo significa che l'elemento root deve sempre avere il valore maggiore nell'albero e tutti i nodi genitori devono essere più grandi dei loro figli. Per una rappresentazione ad array di un heap questo è tipicamente fatto in tre step:
<ol>
<li>Add the new element to the end of the array.</li>
<li>If the element is larger than its parent, switch them.</li>
<li>Continue switching until the new element is either smaller than its parent or you reach the root of the tree.</li>
<li>Aggiungi il nuovo elemento alla fine dell'array.</li>
<li>Se l'elemento è maggiore del suo genitore, scambiali.</li>
<li>Continua a scambiare finché il nuovo elemento è più piccolo del genitore o raggiungi l'elemento root.</li>
</ol>
Finally, add a `print` method which returns an array of all the items that have been added to the heap.
Alla fine, aggiungi un metodo `print` che restituire un array di tutti gli elementi che sono stati aggiunti al heap.
# --hints--
The MaxHeap data structure should exist.
La struttura dati MaxHeap dovrebbe esistere.
```js
assert(
@ -62,7 +62,7 @@ assert(
);
```
MaxHeap should have a method called insert.
MaxHeap dovrebbe avere un metodo chiamato insert.
```js
assert(
@ -78,7 +78,7 @@ assert(
);
```
MaxHeap should have a method called print.
MaxHeap dovrebbe avere un metodo chiamato print.
```js
assert(
@ -94,7 +94,7 @@ assert(
);
```
The insert method should add elements according to the max heap property.
Il metodo insert dovrebbe aggiungere elementi rispettando la proprietà max heap.
```js
assert(
@ -133,20 +133,28 @@ var MaxHeap = function() {
```js
var MaxHeap = function() {
// Only change code below this line
this.heap = [null];
this.insert = (ele) => {
var index = this.heap.length;
var arr = [...this.heap];
arr.push(ele);
while (ele > arr[Math.floor(index / 2)] && index > 1) {
arr[index] = arr[Math.floor(index / 2)];
arr[Math.floor(index / 2)] = ele;
index = arr[Math.floor(index / 2)];
}
this.heap = arr;
this.heap = [];
this.parent = index => {
return Math.floor((index - 1) / 2);
}
this.insert = element => {
this.heap.push(element);
this.heapifyUp(this.heap.length - 1);
}
this.heapifyUp = index => {
let currentIndex = index,
parentIndex = this.parent(currentIndex);
while (currentIndex > 0 && this.heap[currentIndex] > this.heap[parentIndex]) {
this.swap(currentIndex, parentIndex);
currentIndex = parentIndex;
parentIndex = this.parent(parentIndex);
}
}
this.swap = (index1, index2) => {
[this.heap[index1], this.heap[index2]] = [this.heap[index2], this.heap[index1]];
}
this.print = () => {
return this.heap.slice(1);
return this.heap;
}
// Only change code above this line
};

View File

@ -1,6 +1,6 @@
---
id: 587d8259367417b2b2512c83
title: Invert a Binary Tree
title: Invertire un albero binario
challengeType: 1
forumTopicId: 301704
dashedName: invert-a-binary-tree
@ -8,11 +8,11 @@ dashedName: invert-a-binary-tree
# --description--
Here will we create a function to invert a binary tree. Given a binary tree, we want to produce a new tree that is equivalently the mirror image of this tree. Running an inorder traversal on an inverted tree will explore the nodes in reverse order when compared to the inorder traversal of the original tree. Write a method to do this called `invert` on our binary tree. Calling this method should invert the current tree structure. Ideally, we would like to do this in-place in linear time. That is, we only visit each node once and we modify the existing tree structure as we go, without using any additional memory. Good luck!
Qui creeremo una funzione per invertire un albero binario. Dato un albero binario, vogliamo produrre un nuovo albero che sia equivalente all'immagine speculare di questo albero. Eseguire un traversamento inorder su un albero invertito esplora i nodi in ordine inverso rispetto a un traversamento inorder sull'albero originale. Scrivi un metodo per farlo, chiamato `invert` sul nostro albero binario. Chiamare questo metodo dovrebbe invertire la struttura attuale dell'albero. Idealmente, vorremmo fare questo "in-place" (NdT: lavorando sull'array originale, senza crearne una copia) e in tempo lineare. Cioè, visitiamo ogni nodo solo una volta e modifichiamo la struttura di albero esistente mentre procediamo, senza usare memoria aggiuntiva. Buona fortuna!
# --hints--
The `BinarySearchTree` data structure should exist.
La struttura di dati `BinarySearchTree` dovrebbe esistere.
```js
assert(
@ -26,7 +26,7 @@ assert(
);
```
The binary search tree should have a method called `invert`.
L'albero binario di ricerca dovrebbe avere un metodo chiamato `invert`.
```js
assert(
@ -42,7 +42,7 @@ assert(
);
```
The `invert` method should correctly invert the tree structure.
Il metodo `invert` dovrebbe invertire correttamente la struttura dell'albero.
```js
assert(
@ -70,7 +70,7 @@ assert(
);
```
Inverting an empty tree should return `null`.
Invertire un albero vuoto dovrebbe restituire `null`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d825b367417b2b2512c8b
title: Remove an Element from a Max Heap
title: Rimuovere un elemento da una max-heap
challengeType: 1
forumTopicId: 301710
dashedName: remove-an-element-from-a-max-heap
@ -8,21 +8,21 @@ dashedName: remove-an-element-from-a-max-heap
# --description--
Now that we can add elements to our heap let's see how we can remove elements. Removing and inserting elements both require similar logic. In a max heap you will usually want to remove the greatest value, so this involves simply extracting it from the root of our tree. This will break the heap property of our tree, so we must reestablish it in some way. Typically, for a max heap this is done in the following way:
Ora che possiamo aggiungere elementi al nostro heap vediamo come possiamo rimuovere gli elementi. La rimozione e l'inserimento di elementi richiedono una logica simile. In un max-heap di solito si vuole rimuovere il valore maggiore, quindi questo implica semplicemente estrarlo dalla radice del nostro albero. Questo negherà la proprietà heap del nostro albero, quindi dovremo ristabilirla in qualche modo. Tipicamente, per un max-heap questo viene fatto nel modo seguente:
<ol>
<li>Move the last element in the heap into the root position.</li>
<li>If either child of the root is greater than it, swap the root with the child of greater value.</li>
<li>Continue swapping until the parent is greater than both children or you reach the last level in the tree.</li>
<li>Sposta l'ultimo elemento nell'heap alla posizione root.</li>
<li>Se uno dei figli della radice è maggiore di essa, scambiare la radice con il figlio di valore maggiore.</li>
<li>Continuare a scambiare fino a quando il genitore è maggiore di entrambi i figli o si raggiunge l'ultimo livello nell'albero.</li>
</ol>
# --instructions--
Instructions: Add a method to our max heap called `remove`. This method should return the greatest value that has been added to our max heap and remove it from the heap. It should also reorder the heap so the heap property is maintained. After removing an element, the next greatest element remaining in the heap should become the root.
Istruzioni: Aggiungere un metodo al nostro max-heap chiamato `remove`. Questo metodo dovrebbe restituire il massimo valore che è stato aggiunto al nostro max heap e rimuoverlo dal mucchio. Dovrebbe anche riordinare il mucchio in modo che la proprietà heap sia mantenuta. Dopo aver rimosso un elemento, il prossimo elemento più grande che rimane nel heap dovrebbe diventare la radice.
# --hints--
The MaxHeap data structure should exist.
La struttura dati MaxHeap dovrebbe esistere.
```js
assert(
@ -36,7 +36,7 @@ assert(
);
```
MaxHeap should have a method called print.
MaxHeap dovrebbe avere un metodo chiamato print.
```js
assert(
@ -52,7 +52,7 @@ assert(
);
```
MaxHeap should have a method called insert.
MaxHeap dovrebbe avere un metodo chiamato insert.
```js
assert(
@ -68,7 +68,7 @@ assert(
);
```
MaxHeap should have a method called remove.
MaxHeap dovrebbe avere un metodo chiamato remove.
```js
assert(
@ -84,7 +84,7 @@ assert(
);
```
The remove method should remove the greatest element from the max heap while maintaining the max heap property.
Il metodo remove dovrebbe rimuovere l'elemento più grande dal max heap mantenendo la proprietà max heap.
```js
assert(
@ -114,21 +114,29 @@ assert(
## --seed-contents--
```js
var MaxHeap = function() {
this.heap = [null];
this.insert = (ele) => {
var index = this.heap.length;
var arr = [...this.heap];
arr.push(ele);
while (ele > arr[Math.floor(index / 2)] && index > 1) {
arr[index] = arr[Math.floor(index / 2)];
arr[Math.floor(index / 2)] = ele;
index = arr[Math.floor(index / 2)];
var MaxHeap = function () {
this.heap = [];
this.parent = index => {
return Math.floor((index - 1) / 2);
}
this.insert = element => {
this.heap.push(element);
this.heapifyUp(this.heap.length - 1);
}
this.heapifyUp = index => {
let currentIndex = index,
parentIndex = this.parent(currentIndex);
while (currentIndex > 0 && this.heap[currentIndex] > this.heap[parentIndex]) {
this.swap(currentIndex, parentIndex);
currentIndex = parentIndex;
parentIndex = this.parent(parentIndex);
}
this.heap = arr;
}
this.swap = (index1, index2) => {
[this.heap[index1], this.heap[index2]] = [this.heap[index2], this.heap[index1]];
}
this.print = () => {
return this.heap.slice(1);
return this.heap;
}
// Only change code below this line

View File

@ -1,6 +1,6 @@
---
id: 587d8251367417b2b2512c65
title: Remove Elements from a Linked List by Index
title: Rimuovere gli elementi da una lista concatenata usando l'indice
challengeType: 1
forumTopicId: 301711
dashedName: remove-elements-from-a-linked-list-by-index
@ -8,23 +8,23 @@ dashedName: remove-elements-from-a-linked-list-by-index
# --description--
Before we move on to another data structure, let's get a couple of last bits of practice with linked lists.
Prima di passare ad un'altra struttura di dati, otteniamo un altro po' di pratica con liste concatenate.
Let's write a `removeAt` method that removes the `element` at a given `index`. The method should be called `removeAt(index)`. To remove an `element` at a certain `index`, we'll need to keep a running count of each node as we move along the linked list.
Scriviamo un metodo `removeAt` che rimuove l'elemento `element` in un dato `index`. Il metodo dovrebbe essere chiamato `removeAt(index)`. Per rimuovere un `element` a un certo `index`, avremo bisogno di mantenere un conteggio in esecuzione di ogni nodo mentre ci muoviamo lungo la lista concatenata.
A common technique used to iterate through the elements of a linked list involves a <dfn>'runner'</dfn>, or sentinel, that 'points' at the nodes that your code is comparing. In our case, starting at the `head` of our list, we start with a `currentIndex` variable that starts at `0`. The `currentIndex` should increment by one for each node we pass.
Una tecnica comune utilizzata per iterare attraverso gli elementi di una lista concatenata comporta un <dfn>'runner'</dfn>, o sentinella, che 'punti' ai nodi che il tuo codice sta confrontando. Nel nostro caso, a partire dalla `head` della nostra lista, iniziamo con una variabile `currentIndex` che inizia da `0`. Il `currentIndex` dovrebbe aumentare di uno per ogni nodo che passiamo.
Just like our `remove(element)` method, which [we covered in a previous lesson](/learn/coding-interview-prep/data-structures/remove-elements-from-a-linked-list), we need to be careful not to orphan the rest of our list when we remove the node in our `removeAt(index)` method. We keep our nodes contiguous by making sure that the node that has reference to the removed node has a reference to the next node.
Proprio come il nostro metodo `remove(element)`, che [abbiamo coperto in una lezione precedente](/italian/learn/coding-interview-prep/data-structures/remove-elements-from-a-linked-list), dobbiamo stare attenti a non rendere orfano il resto della nostra lista quando rimuoviamo il nodo nel nostro metodo `removeAt(index)`. Manteniamo i nostri nodi contigui assicurandoci che il nodo che fa riferimento al nodo rimosso abbia un riferimento al nodo successivo.
# --instructions--
Write a `removeAt(index)` method that removes and returns a node at a given `index`. The method should return `null` if the given `index` is either negative, or greater than or equal to the `length` of the linked list.
Scrivi un metodo `removeAt(index)` che rimuove e restituisce un nodo a un certo `index`. Il metodo dovrebbe restituire `null` se l'`index` dato è o negativo, o superiore o uguale alla `length` della lista concatenata.
**Note:** Remember to keep count of the `currentIndex`.
**Nota:** Ricordati di mantenere il conteggio del `currentIndex`.
# --hints--
Your `LinkedList` class should have a `removeAt` method.
La tua classe `LinkedList` dovrebbe avere un metodo `removeAt`.
```js
assert(
@ -35,7 +35,7 @@ assert(
);
```
Your `removeAt` method should reduce the `length` of the linked list by one.
Il tuo metodo `removeAt` dovrebbe ridurre `length` della lista collegata di uno.
```js
assert(
@ -50,7 +50,7 @@ assert(
);
```
Your `removeAt` method should remove the element at the specified index from the linked list.
Il tuo metodo `removeAt` dovrebbe rimuovere l'elemento all'indice specificato dalla lista collegata.
```js
assert(
@ -69,7 +69,7 @@ assert(
);
```
When only one element is present in the linked list, your `removeAt` method should remove and return the element at specified index, and reduce the length of the linked list.
Quando un solo elemento è presente nell'elenco collegato, il tuo metodo `removeAt` dovrebbe rimuovere e restituire l'elemento all'indice specificato e ridurre la lunghezza della lista concatenata.
```js
assert(
@ -82,7 +82,7 @@ assert(
);
```
Your `removeAt` method should return the element of the removed node.
Il metodo `removeAt` dovrebbe restituire l'elemento del nodo rimosso.
```js
assert(
@ -96,7 +96,7 @@ assert(
);
```
Your `removeAt` method should return `null` and the linked list should not change if the given index is less than `0`.
Il tuo metodo `removeAt` dovrebbe restituire `null` e la lista concatenata non dovrebbe cambiare se l'indice dato è inferiore a `0`.
```js
assert(
@ -115,7 +115,7 @@ assert(
);
```
Your `removeAt` method should return `null` and the linked list should not change if the given index is greater than or equal to the `length` of the list.
Il tuo metodo `removeAt` dovrebbe restituire `null` e la lista concatenata non dovrebbe cambiare se l'indice dato è maggiore o uguale a `length` dell'elenco.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8251367417b2b2512c63
title: Remove Elements from a Linked List
title: Rimuovi gli elementi da una lista concatenata
challengeType: 1
forumTopicId: 301712
dashedName: remove-elements-from-a-linked-list
@ -8,23 +8,23 @@ dashedName: remove-elements-from-a-linked-list
# --description--
The next important method that any implementation of a linked list will need is a `remove` method. This method should take the element we want to remove as an argument, and then search the list to find and remove the node that contains that element.
Il metodo successivo importante che ogni implementazione di una lista concatenata avrà bisogno è un metodo `remove`. Questo metodo dovrebbe prendere l'elemento che vogliamo rimuovere come un argomento, e quindi cercare l'elenco per trovare e rimuovere il nodo che contiene quell'elemento.
Whenever we remove a node from a linked list, it's important that we don't accidentally orphan the rest of the list in doing so. Recall that every node's `next` property points to the node that follows it in the list. If we're removing the middle element, say, we'll want to make sure that we have a connection from that element's previous node's `next` property to the middle element's `next` property (which is the next node in the list!)
Ogni volta che rimuovi un nodo da una lista collegata, è importante che non orfani accidentalmente il resto della lista nel farlo. Ricorda che la proprietà `next` di ogni nodo punta al nodo che lo segue nella lista. Se stiamo rimuovendo l'elemento di mezzo, vogliamo fare in modo che c'è una connessione tra la proprietà `next` dell'elemento precedente e la proprietà `next` dell'elemento di mezzo (che è il nodo seguente nella lista!)
This might sound really confusing, so let's return to the conga line example so we have a good conceptual model. Picture yourself in a conga line, and the person directly in front of you leaves the line. The person who just left the line no longer has her hands on anyone in line--and you no longer have your hands on the person that left. You step forward and put your hands on next person you see.
Questo può essere davvero confusionario, quindi ritornaimo all'esempio del trenino così abbiamo un buon modello concettuale. Immaginati in un trenino, e la persona direttamente davanti a te lascia la fila. La persona che ha appena lasciato la fina non ha più le mani sulle spalle di nessuno, e tu non hai più le mani sulle spalle della persona che se ne è andata. Fai un passo avanti e metti le mani sulle spalle della persona davanti a te.
If the element we wish to remove is the `head` element, we reassign the `head` to the second node of the linked list.
Se l'elemento che vogliamo rimuovere è l'elemento `head`, assegniamo `head` al secondo nodo della lista concatenata.
# --instructions--
Write a `remove` method that takes an element and removes it from the linked list.
Scrivi un metodo `remove` che prende un elemento e lo rimuove dalla lista collegata.
**Note:** The `length` of the list should decrease by one every time an element is removed from the linked list.
**Nota:** La lunghezza della lista dovrebbe diminuire di uno ogni volta che un elemento viene rimosso dalla lista collegata.
# --hints--
Your `LinkedList` class should have a `remove` method.
La tua classe `LinkedList` dovrebbe avere un metodo `remove`.
```js
assert(
@ -35,7 +35,7 @@ assert(
);
```
Your `remove` method should reassign `head` to the second node when the first node is removed.
Il tuo metodo `remove` dovrebbe riassegnare `head` al secondo nodo quando il primo nodo è rimosso.
```js
assert(
@ -49,7 +49,7 @@ assert(
);
```
Your `remove` method should decrease the `length` of the linked list by one for every node removed.
Il tuo metodo `remove` dovrebbe diminuire `length` della lista concatenata di uno per ogni nodo rimosso.
```js
assert(
@ -65,7 +65,7 @@ assert(
);
```
Your `remove` method should reassign the reference of the previous node of the removed node to the removed node's `next` reference.
Il tuo metodo `remove` dovrebbe riassegnara il riferimento del nodo precedente del nodo rimosso al rifermento `next` del nodo rimosso.
```js
assert(
@ -81,7 +81,7 @@ assert(
);
```
Your `remove` method should not change the linked list if the element does not exist in the linked list.
Il tuo metodo `remove` non dovrebbe cambiare la lista concatenata se l'elemento non esiste nella lista concatenata.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8251367417b2b2512c64
title: Search within a Linked List
title: Cercare in una lista concatenata
challengeType: 1
forumTopicId: 301715
dashedName: search-within-a-linked-list
@ -8,19 +8,19 @@ dashedName: search-within-a-linked-list
# --description--
Let's add a few more useful methods to our linked list class. Wouldn't it be useful if we could tell if our list was empty or not, as with our `Stack` and `Queue` classes?
Aggiungiamo alcuni altri metodi utili alla nostra classe di lista concatenata. Non sarebbe utile se potessimo dire se la nostra lista sia vuota o no, come con le nostre classi `Stack` e `Queue`?
We should also be able to find specific elements in our linked list. Traversing through data structures is something you'll want to get a lot of practice with! Let's create an `indexOf` method that takes an `element` as an argument, and returns that element's `index` in the linked list. If the element is not found in the linked list, return `-1`.
Dovremmo anche essere in grado di trovare elementi specifici nella nostra lista concatenata. Traversare strutture di dati è qualcosa con cui vorrai fare un sacco di pratica! Creiamo un metodo `indexOf` che prende `element` coem argomento, e restituisce l'`index` di quell'elemento nella lista concatenata. Se l'elemento non è trovato nella lista collegata, restituisci `-1`.
Let's also implement a method that does the opposite: an `elementAt` method that takes an `index` as an argument and returns the `element` at the given `index`. If no `element` is found, return `undefined`.
Implementiamo pure un metodo che fa l'opposto: un metodo `elementAt` che accetta un `index` come argomento e restituisce `element` al dato `index`. Se nessun elemento `element` è trovato, restituisci `undefined`.
# --instructions--
Write an `isEmpty` method that checks if the linked list is empty, an `indexOf` method that returns the `index` of a given element, and an `elementAt` that returns an `element` at a given `index.`
Scrivi un metodo `isEmpty` che verifica se la lista concatenata è vuota, un metodo `indexOf` che restituisce l'`index` di un dato elemento, e un metodo `elementAt` che restituisce l'`element` al dato `index.`
# --hints--
Your `LinkedList` class should have an `isEmpty` method.
La tua classe `LinkedList` dovrebbe avere un metodo `isEmpty`.
```js
assert(
@ -31,7 +31,7 @@ assert(
);
```
Your `isEmpty` method should return `false` when there is at least one element in linked list.
Il tuo metodo `isEmpty` dovrebbe restituire `false` quando c'è almeno un elemento nella lista concatenata.
```js
assert(
@ -45,7 +45,7 @@ assert(
);
```
Your `isEmpty` method should return `true` when there are no elements in linked list.
Il tuo metodo `isEmpty` dovrebbe restituire `true` quando non ci sono elementi nella lista concatenata.
```js
assert(
@ -56,7 +56,7 @@ assert(
);
```
Your `LinkedList` class should have an `indexOf` method.
La tua classe `LinkedList` dovrebbe avere un metodo `indexOf`.
```js
assert(
@ -67,7 +67,7 @@ assert(
);
```
Your `indexOf` method should return the index of a given element found in linked list.
Il tuo metodo `indexOf` dovrebbe restituire l'indice di un dato elemento trovato nella lista concatenata.
```js
assert(
@ -81,7 +81,7 @@ assert(
);
```
Your `indexOf` method should return `-1` if the given element is not found in linked list
Il tuo metodo `indexOf` dovrebbe restituire `-1` se l'elemento dato non è trovato nella lista concatenata
```js
assert(
@ -95,7 +95,7 @@ assert(
);
```
Your `LinkedList` class should have an `elementAt` method.
La tua classe `LinkedList` dovrebbe avere un metodo `elementAt`.
```js
assert(
@ -106,7 +106,7 @@ assert(
);
```
Your `elementAt` method should return the element found at a given index in linked list.
Il tuo metodo `elementAt` dovrebbe restituire l'elemento trovato in un dato indice nella lista concatenata.
```js
assert(
@ -120,7 +120,7 @@ assert(
);
```
Your `elementAt` method should return `undefined` if the given element is not found at a given index in linked list.
Il tuo `elementAt` metodo dovrebbe restituire `undefined` se l'elemento dato non è trovato in un dato indice nella lista concatenata.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8253367417b2b2512c6a
title: Typed Arrays
title: Array Digitati
challengeType: 1
forumTopicId: 301716
dashedName: typed-arrays
@ -8,21 +8,21 @@ dashedName: typed-arrays
# --description--
Arrays are JavaScript objects that can hold a lot of different elements.
Gli array sono oggetti JavaScript che possono contenere molti elementi diversi.
```js
var complexArr = [1, 5, "2", "Word", {"name": "James"}];
```
Basically what happens in the background is that your browser will automatically give the right amount of memory space for that array. It will also change as needed if you add or remove data.
Fondamentalmente ciò che accade in background è che il browser darà automaticamente la giusta quantità di spazio di memoria per quell'array. Cambierà anche al bisogno se si aggiungono o rimuovono i dati.
However, in the world of high performance and different element types, sometimes you need to be more specific on how much memory is given to an array.
Tuttavia, nel mondo delle alte prestazioni e dei diversi tipi di elementi, a volte è necessario essere più specifici su quanto memoria viene dato a un array.
<dfn>Typed arrays</dfn> are the answer to this problem. You are now able to say how much memory you want to give an array. Below is a basic overview of the different types of arrays available and the size in bytes for each element in that array.
<dfn>Gli array digitati</dfn> sono la risposta a questo problema. Ora sei in grado di dire quanta memoria vuoi allocare per un dato array. Di seguito una panoramica di base dei diversi tipi di array disponibili e la dimensione in byte per ogni elemento in quell'array.
<table class='table table-striped'><tbody><tr><th>Type</th><th>Each element size in bytes</th></tr><tr><td><code>Int8Array</code></td><td>1</td></tr><tr><td><code>Uint8Array</code></td><td>1</td></tr><tr><td><code>Uint8ClampedArray</code></td><td>1</td></tr><tr><td><code>Int16Array</code></td><td>2</td></tr><tr><td><code>Uint16Array</code></td><td>2</td></tr><tr><td><code>Int32Array</code></td><td>4</td></tr><tr><td><code>Uint32Array</code></td><td>4</td></tr><tr><td><code>Float32Array</code></td><td>4</td></tr><tr><td><code>Float64Array</code></td><td>8</td></tr></tbody></table>
<table class='table table-striped'><tbody><tr><th>Tipo</th><th>La dimensione di ogni elemento in byte</th></tr><tr><td><code>Int8Array</code></td><td>1</td></tr><tr><td><code>Uint8Array</code></td><td>1</td></tr><tr><td><code>Uint8ClampedArray</code></td><td>1</td></tr><tr><td><code>Int16Array</code></td><td>2</td></tr><tr><td><code>Uint16Array</code></td><td>2</td></tr><tr><td><code>Int32Array</code></td><td>4</td></tr><tr><td><code>Uint32Array</code></td><td>4</td></tr><tr><td><code>Float32Array</code></td><td>4</td></tr><tr><td><code>Float64Array</code></td><td>8</td></tr></tbody></table>
There are two ways in creating these kind of arrays. One way is to create it directly. Below is how to create a 3 length `Int16Array`.
Ci sono due modi per creare questi tipi di array. Un modo è di crearli direttamente. Di seguito è riportato come creare un `Int16Array` di lunghezza 3.
```js
var i8 = new Int16Array(3);
@ -30,8 +30,8 @@ console.log(i8);
// Returns [0, 0, 0]
```
You can also create a <dfn>buffer</dfn> to assign how much data (in bytes) you want the array to take up. **Note**
To create typed arrays using buffers, you need to assign the number of bytes to be a multiple of the bytes listed above.
Puoi ache creare un <dfn>buffer</dfn> per assegnare quanti dati (in byte) vuoi che il tuo array occupi. **Nota**
Per creare array digitat usando buffer, devi assegnare il numero di byte come multiple dei byte elencati precedentemente.
```js
// Create same Int16Array array differently
@ -43,35 +43,35 @@ i8View.byteLength; // Returns 6
console.log(i8View); // Returns [0, 0, 0]
```
<dfn>Buffers</dfn> are general purpose objects that just carry data. You cannot access them normally. To access them, you need to first create a <dfn>view</dfn>.
I <dfn>buffer</dfn> sono oggetti a scopo generico che contengono solo dati. Non puoi accedervi normalmente. Per accederci devi prima creare una <dfn>view</dfn>.
```js
i8View[0] = 42;
console.log(i8View); // Returns [42, 0, 0]
```
**Note**
Typed arrays do not have some of the methods traditional arrays have such as `.pop()` or `.push()`. Typed arrays also fail `Array.isArray()` that checks if something is an array. Although simpler, this can be an advantage for less-sophisticated JavaScript engines to implement them.
**Nota**
Array digitati non hanno alcuni dei metodi degli array tradizioni come `.pop()` o `.push()`. Gli array digitati fanno restituire false ad `Array.isArray()` che controlla se qualcosa è un array. Anche se più semplice, questo può essere un vantaggio per i motori JavaScript meno sofisticati per implementarli.
# --instructions--
First create a `buffer` that is 64-bytes. Then create a `Int32Array` typed array with a view of it called `i32View`.
Come prima cosa crea un `buffer` che è 64 byte. Quindi crea un array digitato `Int32Array` con una view chiamata `i32View`.
# --hints--
Your `buffer` should be 64 bytes large.
Il tuo `buffer` dovrebbe occupare 64 byte.
```js
assert(buffer.byteLength === 64);
```
Your `i32View` view of your buffer should be 64 bytes large.
La tua view `i32View` del tuo buffer dovrebbe occupare 64 byte.
```js
assert(i32View.byteLength === 64);
```
Your `i32View` view of your buffer should be 16 elements long.
La tua view `i32View` del tuo buffer dovrebbe avere 16 elementi.
```js
assert(i32View.length === 16);

View File

@ -1,6 +1,6 @@
---
id: 587d8255367417b2b2512c72
title: Use .has and .size on an ES6 Set
title: Usare .has e .size su un set ES6
challengeType: 1
forumTopicId: 301717
dashedName: use--has-and--size-on-an-es6-set
@ -8,21 +8,21 @@ dashedName: use--has-and--size-on-an-es6-set
# --description--
Let's look at the .has and .size methods available on the ES6 Set object.
Diamo un'occhiata ai metodi .has e .size disponibili sull'oggetto Set ES6.
First, create an ES6 Set
Per prima cosa, crea un Set ES6
```js
var set = new Set([1,2,3]);
```
The .has method will check if the value is contained within the set.
Il metodo .has controllerà se il valore è contenuto all'interno del set.
```js
var hasTwo = set.has(2);
```
The .size method will return an integer representing the size of the Set
Il metodo .size restituirà un numero intero rappresentante la dimensione del Set
```js
var howBig = set.size;
@ -30,11 +30,11 @@ var howBig = set.size;
# --instructions--
In this exercise we will pass an array and a value to the checkSet() function. Your function should create an ES6 set from the array argument. Find if the set contains the value argument. Find the size of the set. And return those two values in an array.
In questo esercizio passeremo un array e un valore alla funzione checkSet(). La tua funzione dovrebbe creare un set ES& dall'argomento array. Scopri se il set contiene il valore argomento. Trova la dimensione del set. E restituire questi due valori in un array.
# --hints--
`checkSet([4, 5, 6], 3)` should return [ false, 3 ]
`checkSet([4, 5, 6], 3)` dovrebbe restituire [ false, 3 ]
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8258367417b2b2512c7f
title: Use Breadth First Search in a Binary Search Tree
title: Una la ricerca in ampiezza nella ricerca binaria in un albero
challengeType: 1
forumTopicId: 301718
dashedName: use-breadth-first-search-in-a-binary-search-tree
@ -8,17 +8,17 @@ dashedName: use-breadth-first-search-in-a-binary-search-tree
# --description--
Here we will introduce another tree traversal method: breadth-first search. In contrast to the depth-first search methods from the last challenge, breadth-first search explores all the nodes in a given level within a tree before continuing on to the next level. Typically, queues are utilized as helper data structures in the design of breadth-first search algorithms.
Qui introdurremo un altro metodo traversale di albero: la ricerca in ampiezza. In contrasto con il metodo di ricerca in profondità dell'ultima sfida, La ricerca in ampiezza esplora tutti i nodi in un dato livello all'interno di un albero prima di continuare al livello successivo. Tipicamente, le code sono utilizzate come strutture di dati helper nella progettazione di algoritmi di ricerca in ampiezza.
In this method, we start by adding the root node to a queue. Then we begin a loop where we dequeue the first item in the queue, add it to a new array, and then inspect both its child subtrees. If its children are not null, they are each enqueued. This process continues until the queue is empty.
In questo metodo, iniziamo aggiungendo il nodo radice alla coda. Poi iniziamo un ciclo in cui decodiamo il primo elemento nella coda, aggiungerlo a un nuovo array, e quindi ispezionare entrambi i suoi sottalberi. Se i suoi figli non sono nulli, sono ciascuno messo in coda. Questo processo continua fino a quando la coda non è vuota.
# --instructions--
Let's create a breadth-first search method in our tree called `levelOrder`. This method should return an array containing the values of all the tree nodes, explored in a breadth-first manner. Be sure to return the values in the array, not the nodes themselves. A level should be traversed from left to right. Next, let's write a similar method called `reverseLevelOrder` which performs the same search but in the reverse direction (right to left) at each level.
Creiamo un metodo di ricerca in ampiezza nel nostro albero chiamato `levelOrder`. Questo metodo dovrebbe restituire un array contenente i valori di tutti i nodi degli alberi, esplorati con la ricerca in ampiezza. Assicurati di restituire i valori nell'array, non i nodi stessi. Un livello dovrebbe essere attraversato da sinistra a destra. Poi scriviamo un metodo simile chiamato `reverseLevelOrder` che esegue la stessa ricerca ma nella direzione inversa (da destra a sinistra) ad ogni livello.
# --hints--
The `BinarySearchTree` data structure should exist.
La struttura di dati `BinarySearchTree` dovrebbe esistere.
```js
assert(
@ -32,7 +32,7 @@ assert(
);
```
The binary search tree should have a method called `levelOrder`.
L'albero di ricerca binario dovrebbe avere un metodo chiamato `levelOrder`.
```js
assert(
@ -48,7 +48,7 @@ assert(
);
```
The binary search tree should have a method called `reverseLevelOrder`.
L'albero di ricerca binario dovrebbe avere un metodo chiamato `reverseLevelOrder`.
```js
assert(
@ -64,7 +64,7 @@ assert(
);
```
The `levelOrder` method should return an array of the tree node values explored in level order.
Il metodo `levelOrder` dovrebbe restituire un array dei valori del nodo albero esplorati in ordine di livello.
```js
assert(
@ -94,7 +94,7 @@ assert(
);
```
The `reverseLevelOrder` method should return an array of the tree node values explored in reverse level order.
Il metodo `reverseLevelOrder` dovrebbe restituire un array dei valori del nodo albero esplorati in ordine di livello inverso.
```js
assert(
@ -124,7 +124,7 @@ assert(
);
```
The `levelOrder` method should return `null` for an empty tree.
Il metodo `levelOrder` dovrebbe restituire `null` per un albero vuoto.
```js
assert(
@ -143,7 +143,7 @@ assert(
);
```
The `reverseLevelOrder` method should return `null` for an empty tree.
Il metodo `reverseLevelOrder` dovrebbe restituire `null` per un albero vuoto.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8257367417b2b2512c7e
title: Use Depth First Search in a Binary Search Tree
title: Usa la ricerca in profondità in un alvero di ricerca binario
challengeType: 1
forumTopicId: 301719
dashedName: use-depth-first-search-in-a-binary-search-tree
@ -8,15 +8,15 @@ dashedName: use-depth-first-search-in-a-binary-search-tree
# --description--
We know how to search a binary search tree for a specific value. But what if we just want to explore the entire tree? Or what if we don't have an ordered tree and we need to just search for a value? Here we will introduce some tree traversal methods which can be used to explore tree data structures. First up is depth-first search. In depth-first search, a given subtree is explored as deeply as possible before the search continues on to another subtree. There are three ways this can be done: In-order: Begin the search at the left-most node and end at the right-most node. Pre-order: Explore all the roots before the leaves. Post-order: Explore all the leaves before the roots. As you may guess, you may choose different search methods depending on what type of data your tree is storing and what you are looking for. For a binary search tree, an inorder traversal returns the nodes in sorted order.
Sappiamo come cercare un albero di ricerca binario per un valore specifico. Ma cosa succede se vogliamo solo esplorare l'intero albero? O cosa succede se non abbiamo un albero ordinato e dobbiamo solo cercare un valore? Qui introdurremo alcuni metodi di per traversare l'alvero che possono essere utilizzati per esplorare strutture dati ad albero. Il primo è la prima ricerca in profondità. Nella ricerca in profondità, un dato sotto-albero è esplorato il più profondamente possibile prima che la ricerca continui su un altro sotto-albero. Ci sono tre modi per farlo: In ordine: Iniziare la ricerca al nodo più a sinistra e terminare al nodo più a destra. Pre-ordine: Esplora tutte le radici prima delle foglie. Post-order: Esplora tutte le foglie prima delle radici. Come si può immaginare, è possibile scegliere diversi metodi di ricerca a seconda del tipo di dati che l'albero sta memorizzando e quello che stai cercando. Per un albero di ricerca binario, un attraversamento in ordine restituisce i nodi ordinati.
# --instructions--
Here we will create these three search methods on our binary search tree. Depth-first search is an inherently recursive operation which continues to explore further subtrees so long as child nodes are present. Once you understand this basic concept, you can simply rearrange the order in which you explore the nodes and subtrees to produce any of the three searches above. For example, in post-order search we would want to recurse all the way to a leaf node before we begin to return any of the nodes themselves, whereas in pre-order search we would want to return the nodes first, and then continue recursing down the tree. Define `inorder`, `preorder`, and `postorder` methods on our tree. Each of these methods should return an array of items which represent the tree traversal. Be sure to return the integer values at each node in the array, not the nodes themselves. Finally, return `null` if the tree is empty.
Qui creeremo questi tre metodi di ricerca sul nostro albero di ricerca binario. La ricerca di profondità prima è un'operazione intrinsecamente ricorsiva che continua ad esplorare ulteriori sottalberi, a condizione che siano presenti nodi figli. Una volta che capisci questo concetto fondamentale, si può semplicemente riorganizzare l'ordine in cui si esplorano i nodi e sotto-alberi per produrre una delle tre ricerche sopra. Ad esempio, nella ricerca post-ordine vorremmo arrivare ad un nodo foglia prima di iniziare a restituire uno dei nodi stessi, mentre in pre-ordine di ricerca vorremmo restituire i nodi prima, e poi continuare a ricorsare giù l'albero. Definisci i metodi `inorder`, `preorder`e `postorder` sul nostro albero. Ognuno di questi metodi dovrebbe restituire una serie di oggetti che rappresentano il traversale ad albero. Assicurati di restituire i valori interi ad ogni nodo dell'array, non i nodi stessi. Infine, restituisci `null` se l'albero è vuoto.
# --hints--
The `BinarySearchTree` data structure should exist.
La struttura dati `BinarySearchTree` dovrebbe esistere.
```js
assert(
@ -30,7 +30,7 @@ assert(
);
```
The binary search tree should have a method called `inorder`.
L'albero di ricerca binario dovrebbe avere un metodo chiamato `inorder`.
```js
assert(
@ -46,7 +46,7 @@ assert(
);
```
The binary search tree should have a method called `preorder`.
L'albero di ricerca binario dovrebbe avere un metodo chiamato `preorder`.
```js
assert(
@ -62,7 +62,7 @@ assert(
);
```
The binary search tree should have a method called `postorder`.
L'albero di ricerca binario dovrebbe avere un metodo chiamato `postorder`.
```js
assert(
@ -78,7 +78,7 @@ assert(
);
```
The `inorder` method should return an array of the node values that result from an inorder traversal.
Il metodo `inorder` dovrebbe restituire un array dei valori del nodo che risultano da un traversamento inorder.
```js
assert(
@ -108,7 +108,7 @@ assert(
);
```
The `preorder` method should return an array of the node values that result from a preorder traversal.
Il metodo `preorder` dovrebbe restituire un array dei valori del nodo che risultano da un attraversamento preorder.
```js
assert(
@ -138,7 +138,7 @@ assert(
);
```
The `postorder` method should return an array of the node values that result from a postorder traversal.
Il metodo `postorder` dovrebbe restituire un array dei valori del nodo che risultano da un traversamento postordine.
```js
assert(
@ -168,7 +168,7 @@ assert(
);
```
The `inorder` method should return `null` for an empty tree.
Il metodo `inorder` dovrebbe restituire `null` per un albero vuoto.
```js
assert(
@ -187,7 +187,7 @@ assert(
);
```
The `preorder` method should return `null` for an empty tree.
Il metodo `preorder` dovrebbe restituire `null` per un albero vuoto.
```js
assert(
@ -206,7 +206,7 @@ assert(
);
```
The `postorder` method should return `null` for an empty tree.
Il metodo `postorder` dovrebbe restituire `null` per un albero vuoto.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8255367417b2b2512c73
title: Use Spread and Notes for ES5 Set() Integration
title: Usare sprea e notes per integrazione del Set() ES5
challengeType: 1
forumTopicId: 301720
dashedName: use-spread-and-notes-for-es5-set-integration
@ -8,11 +8,11 @@ dashedName: use-spread-and-notes-for-es5-set-integration
# --description--
Do you remember the ES6 spread operator `...`?
Ricordi l'operatore di diffusione in ES6 `...`?
`...` can take iterable objects in ES6 and turn them into arrays.
`...` può prendere oggetti iterabili in ES6 e trasformarli in array.
Let's create a Set, and check out the spread function.
Creiamo un Set e controlliamo la funzione di diffusione.
```js
var set = new Set([1,2,3]);
@ -22,13 +22,13 @@ console.log(setToArr) // returns [ 1, 2, 3 ]
# --instructions--
In this exercise we will pass a set object to the `checkSet` function. It should return an array containing the values of the Set.
In questo esercizio passeremo un oggetto set alla funzione `checkSet`. Dovrebbe restituire un array contenente i valori del Set.
Now you've successfully learned how to use the ES6 `Set()` object, good job!
Ora hai imparato con successo come usare l'oggetto ES6 `Set()`, buon lavoro!
# --hints--
`checkSet(new Set([1,2,3,4,5,6,7])` should return `[1, 2, 3, 4, 5, 6, 7]`.
`checkSet(new Set([1,2,3,4,5,6,7])` dovrebbe restituire `[1, 2, 3, 4, 5, 6, 7]`.
```js
assert(

View File

@ -1,6 +1,6 @@
---
id: 587d8251367417b2b2512c61
title: Work with Nodes in a Linked List
title: Lavorare con i nodi in una lista concatenata
challengeType: 1
forumTopicId: 301721
dashedName: work-with-nodes-in-a-linked-list
@ -8,25 +8,25 @@ dashedName: work-with-nodes-in-a-linked-list
# --description--
Another common data structure you'll run into in computer science is the <dfn>linked list</dfn>. A linked list is a linear collection of data elements, called 'nodes', each of which points to the next. Each <dfn>node</dfn> in a linked list contains two key pieces of information: the `element` itself, and a reference to the next `node`.
Un'altra struttura dati che incontrerai in computer science è la <dfn>lista concatenata</dfn>. Una lista concatenata è una collezione lineare di elementi di dati, chiamati nodi, ognuno dei quali fa riferimento al successivo. Ogni <dfn>nodo</dfn> in una lista concatenata contiene due informazioni fondamentali: l'elemento stesso, e un riferimento al nodo successivo.
Imagine that you are in a conga line. You have your hands on the next person in the line, and the person behind you has their hands on you. You can see the person straight ahead of you, but they are blocking the view of the other people ahead in line. A node is just like a person in a conga line: they know who they are and they can only see the next person in line, but they are not aware of the other people ahead or behind them.
Immagina di essere in un trenino. Hai le mani sulle spalle della persona davanti a te in fila, e la persona dietro di te ha le mani sulle tue spalle. Puoi vedere la persona direttamente di fronte a te, ma stanno bloccando la vista delle altre persone più in la nel trenino. Un nodo è proprio come una persona in un trenino: sanno chi sono e possono vedere solo la persona successiva nella fila, ma non sono a conoscenza delle altre persone davanti o dietro di loro.
# --instructions--
In our code editor, we've created two nodes, `Kitten` and `Puppy`, and we've manually connected the `Kitten` node to the `Puppy` node.
Nel nostro editor di codice, abbiamo creato due noti, `Kitten` e `Puppy`, e abbiamo connesso il nodo `Kitten` al nodo`Puppy`.
Create a `Cat` and `Dog` node and manually add them to the line.
Crea dei nodi `Cat` e `Dog` e aggiungili manualmente alla lista.
# --hints--
Your `Puppy` node should have a reference to a `Cat` node.
Il tuo nodo `Puppy` dovrebbe avere un riferimento a un nodo `Cat`.
```js
assert(Puppy.next.element === 'Cat');
```
Your `Cat` node should have a reference to a `Dog` node.
Il tuo nodo `Cat` dovrebbe avere un riferimento a un nodo `Dog`.
```js
assert(Cat.next.element === 'Dog');