mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-10-25 10:18:05 +08:00
chore(i18n,learn): processed translations (#47522)
This commit is contained in:
+1
-1
@@ -15,7 +15,7 @@ Si los valores que se comparan no son del mismo tipo, el operador de igualdad re
|
||||
|
||||
**Ejemplos**
|
||||
|
||||
`3 == '3'` devuelve `true` porque JavaScript realiza la conversión de tipo de cadena a número. `3 === '3'` devuelve false porque los tipos son diferentes y la conversión de tipo no se realiza.
|
||||
`3 == '3'` devuelve `true` porque JavaScript realiza la conversión de tipo de cadena a número. `3 === '3'` devuelve `false` porque los tipos son diferentes y la conversión de tipo no se realiza.
|
||||
|
||||
**Nota:** En JavaScript, puedes determinar el tipo de una variable o un valor con el operador `typeof`, de la siguiente manera:
|
||||
|
||||
|
||||
+2
-2
@@ -11,14 +11,14 @@ dashedName: understand-string-immutability
|
||||
|
||||
En JavaScript, los valores de cadena (`String`) son <dfn>inmutables</dfn>, lo que significa que no pueden ser alterados una vez creados.
|
||||
|
||||
Por ejemplo, el siguiente código:
|
||||
Por ejemplo, el siguiente código producirá un error debido a que la letra `B` en la cadena `Bob` no puede ser cambiada por la letra `J`:
|
||||
|
||||
```js
|
||||
let myStr = "Bob";
|
||||
myStr[0] = "J";
|
||||
```
|
||||
|
||||
no puede cambiar el valor de `myStr` a `Job`, porque el contenido de `myStr` no puede ser alterado. Ten en cuenta que esto *no* significa que `myStr` no puede cambiarse, solo que los caracteres individuales de una <dfn>cadena literal</dfn> no pueden ser cambiados. La única forma de cambiar `myStr` sería asignarla con una nueva cadena, como esta:
|
||||
Nota que esto *no* significa que `myStr` no pueda ser reasignado. La única manera de cambiar el valor de `myStr` seria asignándole un nuevo valor, como en el siguiente ejemplo:
|
||||
|
||||
```js
|
||||
let myStr = "Bob";
|
||||
|
||||
+15
-3
@@ -8,7 +8,7 @@ dashedName: build-a-drum-machine
|
||||
|
||||
# --description--
|
||||
|
||||
**Objetivo:** Crear una aplicación que sea funcionalmente similar a <https://codepen.io/freeCodeCamp/full/MJyNMd>.
|
||||
**Objetivo:** Crea una aplicación que sea funcionalmente similar a esta: <a href="https://codepen.io/freeCodeCamp/full/MJyNMd" target="_blank" rel="noopener noreferrer nofollow">https://codepen.io/freeCodeCamp/full/MJyNMd</a>.
|
||||
|
||||
Completa las historias de usuario a continuación y obtén todas las pruebas para aprobar. Utiliza cualquier librería o API que necesites. Dale tu propio estilo.
|
||||
|
||||
@@ -28,9 +28,21 @@ Puedes utilizar cualquier combinación de HTML, JavaScript, CSS, Bootstrap, SASS
|
||||
|
||||
**Historia de usuario #7:** Cuando es un `.drum-pad` es activado, una cadena que describe el clip de audio asociado se muestra como el texto interior del elemento `#display` (cada cadena debe ser única).
|
||||
|
||||
Puedes construir tu proyecto con <a href='https://codepen.io/pen?template=MJjpwO' target='_blank' rel='nofollow'>usando esta plantilla CodePen</a> y haciendo clic en `Save` para crear tu propio pen. O puedes utilizar este enlace CDN para ejecutar las pruebas en cualquier entorno que desees: `https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`
|
||||
Aquí tienes algunas muestras de audio que puedes usar para tu batería electrónica:
|
||||
|
||||
Una vez que hayas terminado, envía la URL de tu proyecto funcional con todas las pruebas pasadas.
|
||||
- [Heater 1](https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3)
|
||||
- [Heater 2](https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3)
|
||||
- [Heater 3](https://s3.amazonaws.com/freecodecamp/drums/Heater-3.mp3)
|
||||
- [Heater 4](https://s3.amazonaws.com/freecodecamp/drums/Heater-4_1.mp3)
|
||||
- [Clap](https://s3.amazonaws.com/freecodecamp/drums/Heater-6.mp3)
|
||||
- [Open-HH](https://s3.amazonaws.com/freecodecamp/drums/Dsc_Oh.mp3)
|
||||
- [Kick-n'-Hat](https://s3.amazonaws.com/freecodecamp/drums/Kick_n_Hat.mp3)
|
||||
- [Kick](https://s3.amazonaws.com/freecodecamp/drums/RP4_KICK_1.mp3)
|
||||
- [Closed-HH](https://s3.amazonaws.com/freecodecamp/drums/Cev_H2.mp3)
|
||||
|
||||
Puedes crear tu proyecto <a href='https://codepen.io/pen?template=MJjpwO' target='_blank' rel="noopener noreferrer nofollow">usando esta plantilla de CodePen</a> y dando clic en `Save` para crear la tuya. O puedes usar este enlace CDN para ejecutar las pruebas en el ambiente que más te guste: `https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js`
|
||||
|
||||
Una vez que hayas terminado, envía la URL a tu proyecto de trabajo con todas sus pruebas verificadas.
|
||||
|
||||
# --solutions--
|
||||
|
||||
|
||||
+9
-9
@@ -10,7 +10,7 @@ dashedName: use-the-caret-character-to-use-the-latest-minor-version-of-a-depende
|
||||
|
||||
Similar a cómo la tilde que aprendimos en el último desafío permite a npm instalar la última PATCH para una dependencia, el caret (`^`) permite a npm instalar futuras actualizaciones también. La diferencia es que el caret permitirá tanto actualizaciones MINOR como PATCHes.
|
||||
|
||||
Tu versión actual de moment debe ser "~2.10.0" lo que permite a npm instalar la última versión 2.10.x. Si se usara el caret (^) como prefijo de versión en su lugar, npm permitiría actualizar a cualquier versión 2.x.x.
|
||||
Tu versión actual de `@freecodecamp/example` debería ser "~1.2.13" que permite a npm instalar a la última versión 1.2.x. Si se usa el símbolo caret (^) como prefijo de versión en su lugar, npm permitiría actualizar a cualquier versión de 1.x.x.
|
||||
|
||||
```json
|
||||
"package": "^1.3.8"
|
||||
@@ -20,13 +20,13 @@ Esto permitiría actualizaciones a cualquier version 1.x.x del paquete.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Usa el caret (`^`) para anteponer la versión de moment en tus dependencias y permitir a npm actualizarlo a cualquier nueva versión MINOR.
|
||||
Usa el caret (`^`) para fijar la versión de `@freecodecamp/example` en su lugar y permitir a npm actualizarla a cualquier versión anterior.
|
||||
|
||||
**Nota:** Los números de versión no deben ser cambiados.
|
||||
|
||||
# --hints--
|
||||
|
||||
"dependencies" debe incluir "moment"
|
||||
`"dependencies"` debería incluir `"@freecodecamp/example"`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -35,8 +35,8 @@ Usa el caret (`^`) para anteponer la versión de moment en tus dependencias y pe
|
||||
var packJson = JSON.parse(data);
|
||||
assert.property(
|
||||
packJson.dependencies,
|
||||
'moment',
|
||||
'"dependencies" does not include "moment"'
|
||||
'@freecodecamp/example',
|
||||
'"dependencies" does not include "@freecodecamp/example"'
|
||||
);
|
||||
},
|
||||
(xhr) => {
|
||||
@@ -45,7 +45,7 @@ Usa el caret (`^`) para anteponer la versión de moment en tus dependencias y pe
|
||||
);
|
||||
```
|
||||
|
||||
la versión de "moment" debe coincidir con "2.x.x"
|
||||
La versión de `"@freecodecamp/example"` debería coincidir con `"^1.x.x"`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -53,9 +53,9 @@ la versión de "moment" debe coincidir con "2.x.x"
|
||||
(data) => {
|
||||
var packJson = JSON.parse(data);
|
||||
assert.match(
|
||||
packJson.dependencies.moment,
|
||||
/^\^2\./,
|
||||
'Wrong version of "moment". It should be ^2.10.2'
|
||||
packJson.dependencies["@freecodecamp/example"],
|
||||
/^\^1\./,
|
||||
'Wrong version of "@freecodecamp/example". It should be ^1.2.13'
|
||||
);
|
||||
},
|
||||
(xhr) => {
|
||||
|
||||
+9
-9
@@ -18,15 +18,15 @@ Para permitir que una dependencia de npm se actualice a la última versión de P
|
||||
|
||||
# --instructions--
|
||||
|
||||
En el archivo package.json, su regla actual para que npm pueda actualizar la dependencia "moment" es usar una versión específica (2.10.2). Pero ahora, quieres permitir la última versión 2.10.x.
|
||||
En el archivo package.json, tu regla actual para como npm puede actualizar `@freecodecamp/example` es utilizando específicamente la versión (1.2.13). Pero ahora quieres permitir la última versión 1.2.x.
|
||||
|
||||
Usa el tilde (`~`) para anteponer la versión de moment en tus dependencias y permitir a npm actualizarlo a cualquier nueva versión PATCH.
|
||||
Usa el carácter tilde (`~`) para fijar la versión de `@freecodecamp/example` en tus dependencias y permitir a npm actualizarla a cualquier nuevo lanzamiento de _patch_.
|
||||
|
||||
**Nota:** Los números de versión no deben ser cambiados.
|
||||
|
||||
# --hints--
|
||||
|
||||
"dependencies" debe incluir "moment"
|
||||
`"dependencies"` debe incluir `"@freecodecamp/example"`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -35,8 +35,8 @@ Usa el tilde (`~`) para anteponer la versión de moment en tus dependencias y pe
|
||||
var packJson = JSON.parse(data);
|
||||
assert.property(
|
||||
packJson.dependencies,
|
||||
'moment',
|
||||
'"dependencies" does not include "moment"'
|
||||
'@freecodecamp/example',
|
||||
'"dependencies" does not include "@freecodecamp/example"'
|
||||
);
|
||||
},
|
||||
(xhr) => {
|
||||
@@ -45,7 +45,7 @@ Usa el tilde (`~`) para anteponer la versión de moment en tus dependencias y pe
|
||||
);
|
||||
```
|
||||
|
||||
la versión de "moment" debe coincidir con "~2.10.2"
|
||||
La versión de `"@freecodecamp/example"` debe coincidir con `"~1.2.13"`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
@@ -53,9 +53,9 @@ la versión de "moment" debe coincidir con "~2.10.2"
|
||||
(data) => {
|
||||
var packJson = JSON.parse(data);
|
||||
assert.match(
|
||||
packJson.dependencies.moment,
|
||||
/^\~2\.10\.2/,
|
||||
'Wrong version of "moment". It should be ~2.10.2'
|
||||
packJson.dependencies["@freecodecamp/example"],
|
||||
/^\~1\.2\.13/,
|
||||
'Wrong version of "@freecodecamp/example". It should be ~1.2.13'
|
||||
);
|
||||
},
|
||||
(xhr) => {
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ Para asegurarse de que los clientes tienen continuamente el recuento actualizado
|
||||
|
||||
**Nota:** Al igual que `'disconnect'`, todos los demás eventos que un socket puede emitir al servidor deben ser manejados dentro del oyente de conexión donde tenemos definido 'socket'.
|
||||
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te encuentras con errores, puedes revisar el proyecto completado hasta este punto [aquí](https://gist.github.com/camperbot/ab1007b76069884fb45b215d3c4496fa).
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te estás encontrando errores, puedes <a href="https://gist.github.com/camperbot/ab1007b76069884fb45b215d3c4496fa" target="_blank" rel="noopener noreferrer nofollow">mirar el proyecto completado hasta este momento</a>.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
||||
+2
-2
@@ -10,7 +10,7 @@ dashedName: hashing-your-passwords
|
||||
|
||||
Volviendo a la sección de seguridad de la información, puedes recordar que almacenar contraseñas en texto plano *nunca* está bien. Ahora es el momento de implementar BCrypt para resolver este problema.
|
||||
|
||||
Agrega `bcrypt@~5.0.0` como dependencia, y requiérelo en tu servidor. Necesitarás manejar el hashing en 2 áreas clave: donde manejas el registro/guardado de una nueva cuenta, y cuando compruebas que una contraseña es correcta al iniciar sesión.
|
||||
`bcrypt@~5.0.0` Ha sido agregado como una dependencia, así que requiérelo en tu servidor. Necesitarás manejar el hashing en 2 áreas clave: donde manejas el registro/guardado de una nueva cuenta, y cuando compruebas que una contraseña es correcta al iniciar sesión.
|
||||
|
||||
Actualmente en nuestra ruta de registro, se inserta la contraseña de un usuario en la base de datos así: `password: req.body.password`. Una forma sencilla de implementar el guardado de un hash en su lugar es agregar lo siguiente antes de tu lógica de base de datos `const hash = bcrypt.hashSync(req.body.password, 12);`, y sustituir el `req.body.password` en el guardado de la base de datos por sólo `password: hash`.
|
||||
|
||||
@@ -24,7 +24,7 @@ if (!bcrypt.compareSync(password, user.password)) {
|
||||
|
||||
¡Eso es todo lo que se necesita para implementar una de las características de seguridad más importantes cuando tienes que almacenar contraseñas!
|
||||
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te encuentras con errores, puedes revisar el proyecto completado hasta este punto [aquí](https://gist.github.com/camperbot/dc16cca09daea4d4151a9c36a1fab564).
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te encuentras con errores, puedes consultar el <a href="https://gist.github.com/camperbot/dc16cca09daea4d4151a9c36a1fab564" target="_blank" rel="noopener noreferrer nofollow">proyecto completado hasta este momento</a>.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ Además, en `profile.pug`, añade un enlace que haga referencia a la ruta `/logo
|
||||
a(href='/logout') Logout
|
||||
```
|
||||
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te encuentras con errores, puedes revisar el proyecto completado hasta este punto [aquí](https://gist.github.com/camperbot/136b3ad611cc80b41cab6f74bb460f6a).
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te estás encontrando errores, puedes <a href="https://gist.github.com/camperbot/136b3ad611cc80b41cab6f74bb460f6a" target="_blank" rel="noopener noreferrer nofollow">mirar el proyecto completado hasta este punto</a>.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
||||
+2
-2
@@ -10,7 +10,7 @@ dashedName: implement-the-serialization-of-a-passport-user
|
||||
|
||||
Ahora mismo, no estamos cargando un objeto de usuario real ya que no hemos configurado nuestra base de datos. Esto puede hacerse de muchas maneras, pero para nuestro proyecto nos conectaremos a la base de datos una vez cuando iniciemos el servidor y mantendremos una conexión persistente durante todo el ciclo de vida de la aplicación. Para hacer esto, agrega la cadena de conexión de tu base de datos (por ejemplo: `mongodb+srv://:@cluster0-jvwxi.mongodb.net/?retryWrites=true&w=majority`) a la variable de entorno `MONGO_URI`. Esto se utiliza en el archivo `connection.js`.
|
||||
|
||||
*Si tienes problemas para configurar una base de datos gratuita en MongoDB Atlas, consulta [tutorial](https://www.freecodecamp.org/news/get-started-with-mongodb-atlas/).*
|
||||
*Si tienes problemas para configurar una base de datos gratuita en MongoDB Atlas, consulta este <a href="https://www.freecodecamp.org/news/get-started-with-mongodb-atlas/" target="_blank" rel="noopener noreferrer nofollow">tutorial</a>.*
|
||||
|
||||
Ahora queremos conectarnos a nuestra base de datos y empezar a escuchar las peticiones. El propósito de esto es no permitir peticiones antes de que nuestra base de datos esté conectada o si hay un error en la base de datos. Para lograr esto, querrás englobar tu serialización y las rutas de tu aplicación en el siguiente código:
|
||||
|
||||
@@ -40,7 +40,7 @@ myDB(async client => {
|
||||
|
||||
Asegúrate de descomentar el código `myDataBase` en `deserializeUser`, y edita tu `done(null, null)` para incluir el `doc`.
|
||||
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te encuentras con errores, puedes revisar el proyecto completado hasta este punto [aquí](https://gist.github.com/camperbot/175f2f585a2d8034044c7e8857d5add7).
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te estás encontrando errores, puedes <a href="https://gist.github.com/camperbot/175f2f585a2d8034044c7e8857d5add7" target="_blank" rel="noopener noreferrer nofollow">mirar el proyecto completado hasta este punto</a>.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ dashedName: implementation-of-social-authentication-ii
|
||||
|
||||
# --description--
|
||||
|
||||
La última parte de configurar tu autentificación de GitHub es crear la propia estrategia. Para esto, necesitarás agregar la dependencia de `passport-github@~1.1.0` a tu proyecto y requiérelo en tu `auth.js` como `GithubStrategy` así: `const GitHubStrategy = require('passport-github').Strategy;`. No olvides requerir y configurar `dotenv` para usar tus variables de entorno.
|
||||
La última parte de configurar tu autentificación de GitHub es crear la propia estrategia. `passport-github@~1.1.0` ya ha sido añadido como dependencia, así que requiérelo en tu archivo `auth.js` como `GithubStrategy` así: `const GitHubStrategy = require('passport-github').Strategy;`. No olvides requerir y configurar `dotenv` para usar tus variables de entorno.
|
||||
|
||||
Para configurar la estrategia de GitHub, debes decirle a Passport que utilice una instancia de `GitHubStrategy`, que acepta 2 argumentos: un objeto (que contiene `clientID`, `clientSecret`, y `callbackURL`) y una función a ser llamada cuando un usuario es autentificado con éxito, que determinará si el usuario es nuevo y qué campos guardar inicialmente en el objeto de base de datos del usuario. Esto es común en muchas estrategias, pero algunas pueden requerir más información como se indica en el README de GitHub de esa estrategia específica. Por ejemplo, Google requiere un *ámbito* también que determina qué tipo de información está pidiendo que se le devuelva y pide al usuario que apruebe dicho acceso.
|
||||
|
||||
@@ -31,7 +31,7 @@ passport.use(new GitHubStrategy({
|
||||
|
||||
¡Tu autenticación aún no será exitosa, y en realidad arrojará un error sin la lógica de la base de datos y el callback, pero debería registrar tu perfil de GitHub en tu consola si lo intentas!
|
||||
|
||||
Envía tu página cuando creas que la tienes correcta. Si te encuentras con errores, puedes consultar el proyecto completado hasta este punto [Aquí](https://gist.github.com/camperbot/ff3a1166684c1b184709ac0bee30dee6).
|
||||
Envía tu página cuando creas que la tienes correcta. Si te encuentras con errores, puedes consultar el <a href="https://gist.github.com/camperbot/ff3a1166684c1b184709ac0bee30dee6" target="_blank" rel="noopener noreferrer nofollow">proyecto completado hasta este momento</a>.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
||||
+2
-2
@@ -30,11 +30,11 @@ app.use((req, res, next) => {
|
||||
});
|
||||
```
|
||||
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te encuentras con errores, puedes revisar el proyecto completado hasta este punto [aquí](https://gist.github.com/camperbot/c3eeb8a3ebf855e021fd0c044095a23b).
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te encuentras con errores, puedes consultar el <a href="https://gist.github.com/camperbot/c3eeb8a3ebf855e021fd0c044095a23b" target="_blank" rel="noopener noreferrer nofollow">proyecto completado hasta este momento</a>.
|
||||
|
||||
# --hints--
|
||||
|
||||
`req.Logout` debe ser llamado en la ruta `/logout`.
|
||||
`req.logout()` debe ser llamado en la ruta `/logout`.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@ app.route('/register')
|
||||
);
|
||||
```
|
||||
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te encuentras con errores, puedes revisar el proyecto completado hasta este punto [aquí](https://gist.github.com/camperbot/b230a5b3bbc89b1fa0ce32a2aa7b083e).
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te estás encontrando errores, puedes <a href="https://gist.github.com/camperbot/b230a5b3bbc89b1fa0ce32a2aa7b083e" target="_blank" rel="noopener noreferrer nofollow">mirar el proyecto completado hasta este punto</a>.
|
||||
|
||||
**NOTA:** A partir de este punto, pueden surgir problemas relacionados con el uso del navegador *picture-in-picture*. Si está utilizando un IDE en línea que ofrece una vista previa de la aplicación dentro del editor, se recomienda abrir esta vista previa en una nueva pestaña.
|
||||
|
||||
|
||||
+2
-2
@@ -12,7 +12,7 @@ Serialización y deserialización son conceptos importantes en lo que respecta a
|
||||
|
||||
Para configurarlo correctamente, necesitamos tener una función serializada y una función deserializada. En Passport los creamos con `passport.serializeUser( OURFUNCTION )` y `passport.deserializeUser( OURFUNCTION )`
|
||||
|
||||
El `serializeUser` es llamado con 2 argumentos, el objeto de usuario completo y un callback usado por passport. Una clave única para identificar que el usuario debe ser devuelto en el callback, el más fácil de usar es el `_id` del usuario en el objeto. Debe ser único ya que es generado por MongoDB. De manera similar, `deserializeUser` es llamado con esa clave y también una función de callback para passport, pero, esta vez, tenemos que tomar esa clave y devolver el objeto de usuario completo al callback. Para hacer una consulta de búsqueda para Mongo `_id`, tendrás que crear `const ObjectID = require('mongodb').ObjectID;`, y para usarlo llama a `new ObjectID(THE_ID)`. Asegúrate de agregar `mongodb@~3.6.0` como una dependencia. Puedes ver esto en los ejemplos siguientes:
|
||||
El `serializeUser` es llamado con 2 argumentos, el objeto de usuario completo y un callback usado por passport. Una clave única para identificar que el usuario debe ser devuelto en el callback, el más fácil de usar es el `_id` del usuario en el objeto. Debe ser único ya que es generado por MongoDB. De manera similar, `deserializeUser` es llamado con esa clave y también una función de callback para passport, pero, esta vez, tenemos que tomar esa clave y devolver el objeto de usuario completo al callback. Para hacer una consulta de búsqueda para Mongo `_id`, tendrás que crear `const ObjectID = require('mongodb').ObjectID;`, y para usarlo llama a `new ObjectID(THE_ID)`. `mongodb@~3.6.0` ya ha sido añadido como dependencia. Puedes ver esto en los ejemplos siguientes:
|
||||
|
||||
```js
|
||||
passport.serializeUser((user, done) => {
|
||||
@@ -28,7 +28,7 @@ passport.deserializeUser((id, done) => {
|
||||
|
||||
NOTA: Este `deserializeUser` arrojará un error hasta que establezcamos la BD en el siguiente paso, así que por ahora comenta todo el bloque y simplemente llama a `done(null, null)` en la función `deserializeUser`.
|
||||
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te encuentras con errores, puedes revisar el proyecto completado hasta este punto [aquí](https://gist.github.com/camperbot/7068a0d09e61ec7424572b366751f048).
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te encuentras con errores, puedes consultar el <a href="https://gist.github.com/camperbot/7068a0d09e61ec7424572b366751f048" target="_blank" rel="noopener noreferrer nofollow">proyecto completado hasta este momento</a>.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
||||
+7
-7
@@ -10,25 +10,25 @@ dashedName: set-up-a-template-engine
|
||||
|
||||
Trabajar en estos desafíos implica escribir tu código usando uno de los siguientes métodos:
|
||||
|
||||
- Clona [este repositorio de GitHub](https://github.com/freeCodeCamp/boilerplate-advancednode/) y completa estos desafíos localmente.
|
||||
- Usa [nuestro proyecto inicial de Replit](https://replit.com/github/freeCodeCamp/boilerplate-advancednode) para completar estos desafíos.
|
||||
- Clone este repositorio de <a href="https://github.com/freeCodeCamp/boilerplate-advancednode/" target="_blank" rel="noopener noreferrer nofollow"> GitHub</a> y complete estos desafíos localmente.
|
||||
- Usa <a href="https://replit.com/github/freeCodeCamp/boilerplate-advancednode" target="_blank" rel="noopener noreferrer nofollow">nuestro proyecto de inicio Replit</a> para completar estos desafíos.
|
||||
- Utiliza un constructor de sitios de tu elección para completar el proyecto. Asegúrate de incorporar todos los archivos de nuestro repositorio de GitHub.
|
||||
|
||||
Cuando hayas terminado, asegúrate de que un demo funcional de tu proyecto esté alojado en algún lugar público. Luego, envía la URL en el campo `Solution Link`.
|
||||
|
||||
Un motor de plantillas te permite usar plantillas estáticas (como las escritas en *Pug*) en tu aplicación. En tiempo de ejecución, el motor de plantillas reemplaza variables en un archivo de plantilla con valores reales que pueden ser suministrados por tu servidor. Luego transforma la plantilla en un archivo HTML estático que se envía al cliente. Este enfoque hace más fácil el diseño de una página HTML y permite mostrar variables en la página sin necesidad de hacer una llamada API desde el cliente.
|
||||
|
||||
Añade `pug@~3.0.0` como una dependencia en tu archivo `package.json`.
|
||||
`pug@~3.0.0` ya ha sido instalado, y se muestra como una dependencia en tu archivo `package.json`.
|
||||
|
||||
Express necesita saber qué motor de plantillas está utilizando. Utilizaremos el método `set` para asignar `pug` como el valor de `view engine` de la propiedad: `app.set('view engine', 'pug')`
|
||||
|
||||
La página no se cargará hasta que procese correctamente el archivo de índice en el directorio `views/pug`.
|
||||
Tu página estará en blanco hasta que proceses correctamente el archivo de índice en el directorio `views/pug`.
|
||||
|
||||
Cambia el argumento de la sentencia `res.render()` en la ruta `/` para que sea la ruta del archivo al directorio `views/pug`. La ruta puede ser una ruta relativa (relativa a las vistas), o una ruta absoluta, y no requiere una extensión de archivo.
|
||||
Para renderizar la plantilla `pug`, necesitas usar `res.render()` en la ruta `/`. Pasa la ruta del archivo al directorio `views/pug` como argumento al método. La ruta puede ser una ruta relativa (relativa a las vistas), o una ruta absoluta, y no requiere una extensión de archivo.
|
||||
|
||||
Si todo ha ido según lo previsto, ¡la página de inicio de tu aplicación dejará de mostrar el mensaje "`Pug template is not defined.`" y ahora mostrará un mensaje indicando que has renderizado con éxito la plantilla Pug!
|
||||
Si todo salió según lo planeado, la página de inicio de tu aplicación ya no estará en blanco y mostrará un mensaje indicando que has renderizado correctamente la plantilla Pug!
|
||||
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te encuentras con errores, puedes revisar el proyecto completado hasta este punto [aquí](https://gist.github.com/camperbot/3515cd676ea4dfceab4e322f59a37791).
|
||||
Envía tu página cuando creas que lo has hecho bien. Si te estás encontrando errores, puedes <a href="https://gist.github.com/camperbot/3515cd676ea4dfceab4e322f59a37791" target="_blank" rel="noopener noreferrer nofollow">mirar el proyecto completado hasta este punto</a>.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
||||
+6
-8
@@ -8,15 +8,13 @@ dashedName: set-up-passport
|
||||
|
||||
# --description--
|
||||
|
||||
¡Es hora de configurar *Passport* para que finalmente podamos empezar a permitir que un usuario se registre o inicie sesión en una cuenta! Además de Passport, usaremos Express-session para manejar sesiones. El uso de este middleware guarda el session id como cookie en el cliente y nos permite acceder a los datos de sesión utilizando ese id en el servidor. De esta manera mantenemos la información de la cuenta personal fuera de la cookie utilizada por el cliente para verificar a nuestro servidor que están autenticados y solo mantenemos la *clave* para acceder a los datos almacenados en el servidor.
|
||||
¡Es hora de configurar *Passport* para que finalmente podamos empezar a permitir que un usuario se registre o inicie sesión en una cuenta! Además de Passport, usaremos Express-session para manejar sesiones. La sesión express tiene muchas funciones avanzadas que puedes usar, pero por ahora solo vamos a usar lo básico! Usar este middleware te guarda el id de la sesión como una cookie en el cliente y nos permite acceder a los datos de la sesión usando ese id en el servidor. De esta manera guardamos información personal de la cuenta fuera de la cookie usada por el cliente para verificar en nuestro servidor que están autentificadas y mantener la *llave* para acceder a los datos guardados en el servidor.
|
||||
|
||||
Para configurar Passport para su uso en tu proyecto, necesitarás añadirlo primero como dependencia en tu package.json. `passport@~0.4.1`
|
||||
`passport@~0.4.1` y `express-session@~1.17.1` ya están instalados, y los dos están apuntados como dependencias en tu archivo `package.json`.
|
||||
|
||||
Además, agrega también Express-session como dependencia. Express-session tiene un montón de características avanzadas que puedes usar, pero por ahora solo vamos a usar lo básico! `express-session@~1.17.1`
|
||||
Necesitarás configurar la configuración de sesión ahora e inicializar Passport. Asegurate de primero crear las variables 'session' y 'passport' para requerir 'express-session' y 'passport' respectivamente.
|
||||
|
||||
Necesitarás configurar la configuración de sesión ahora e inicializar Passport. Asegúrate de crear primero las variables 'session' y 'passport' para requerir 'express-session' y 'passport' respectivamente.
|
||||
|
||||
Para configurar tu aplicación express para usar la sesión definiremos sólo algunas opciones básicas. Asegúrate de añadir 'SESSION_SECRET' a tu archivo .env y darle un valor aleatorio. ¡Esto se utiliza para calcular el hash utilizado para cifrar tu cookie!
|
||||
Para configurar tu aplicación express para usar la sesión definiremos sólo algunas opciones básicas. Asegúrate de agregar 'SESSION_SECRET' a tu archivo .env y dale un valor aleatorio. ¡Esto es usado para computar el hash usado para encriptar tus cookie!
|
||||
|
||||
```js
|
||||
app.use(session({
|
||||
@@ -29,7 +27,7 @@ app.use(session({
|
||||
|
||||
También puedes seguir adelante y decirle a tu aplicación express que **usé** 'passport.initialize()' y 'passport.session()'. (Por ejemplo, `app.use(passport.initialize());`)
|
||||
|
||||
Envía tu página cuando creas que lo has hecho bien. Si estás experimentando errores, puedes revisar el proyecto completado hasta este punto [aquí](https://gist.github.com/camperbot/4068a7662a2f9f5d5011074397d6788c).
|
||||
Envía tu página cuando pienses que la tengas correcto. Si te encuentras con errores, puedes consultar el <a href="https://gist.github.com/camperbot/4068a7662a2f9f5d5011074397d6788c" target="_blank" rel="noopener noreferrer nofollow">proyecto completado hasta este momento</a>.
|
||||
|
||||
# --hints--
|
||||
|
||||
@@ -103,7 +101,7 @@ La aplicación Express debe usar nuevas dependencias.
|
||||
);
|
||||
```
|
||||
|
||||
Debe establecerse correctamente el secreto de sesión y sesión.
|
||||
La sesión y el secreto de la sesión deben estar configurados correctamente.
|
||||
|
||||
```js
|
||||
(getUserInput) =>
|
||||
|
||||
+2
-2
@@ -10,7 +10,7 @@ dashedName: set-up-the-environment
|
||||
|
||||
Los siguientes desafíos harán uso del archivo `chat.pug`. Así que, en tu archivo `routes.js`, añade una ruta GET que apunte a `/chat` que hace uso de `ensureAuthenticated`, y procesa `chat.pug`, con `{ user: req.user }` pasado como argumento a la respuesta. Ahora, modifique la ruta `/auth/github/callback` existente para establecerla `req.session.user_id = req.user.id`, y redirigirla a `/chat`.
|
||||
|
||||
Añade `socket.io@~2.3.0` como una dependencia y requiérela/instancia la en tu servidor definido de la siguiente manera, con `http` (viene integrado con Nodejs):
|
||||
`socket.io@~2.3.0` ya ha sido añadido como dependencia, así que require/instantiate en tu servidor de la siguiente manera con `http` (viene integrado con Nodejs):
|
||||
|
||||
```javascript
|
||||
const http = require('http').createServer(app);
|
||||
@@ -42,7 +42,7 @@ Ahora intenta cargar tu aplicación asimismo autenticarte y deberías ver en la
|
||||
|
||||
**Nota:**`io()` funciona sólo cuando se conecta a un socket alojado en la misma url/servidor. Para conectar a un socket externo alojado en otro lugar, debes usar `io.connect('URL');`.
|
||||
|
||||
Envía tu página cuando creas que está correcto. Si estás experimentando errores, puedes revisar el proyecto completado hasta este punto [aquí](https://gist.github.com/camperbot/aae41cf59debc1a4755c9a00ee3859d1).
|
||||
Envía tu página cuando creas que está correcto. Si te estás encontrando errores, puedes <a href="https://gist.github.com/camperbot/aae41cf59debc1a4755c9a00ee3859d1" target="_blank" rel="noopener noreferrer nofollow">mirar el proyecto completado hasta este punto</a>.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
||||
+2
-2
@@ -8,11 +8,11 @@ dashedName: run-functional-tests-using-a-headless-browser-ii
|
||||
|
||||
# --description--
|
||||
|
||||
Como recordatorio, este proyecto está siendo construido con base en el siguiente proyecto inicial [Replit](https://replit.com/github/freeCodeCamp/boilerplate-mochachai), o clonado desde [GitHub](https://github.com/freeCodeCamp/boilerplate-mochachai/).
|
||||
Como recordatorio, este proyecto está siendo construido con base en el siguiente proyecto inicial <a href="https://replit.com/github/freeCodeCamp/boilerplate-mochachai" target="_blank" rel="noopener noreferrer nofollow">Repl. it</a>, o clonado desde <a href="https://github.com/freeCodeCamp/boilerplate-mochachai/" target="_blank" rel="noopener noreferrer nofollow">GitHub</a>.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Dentro `tests/2_functional-tests.js`, en `'Submit the surname "Vespucci" in the HTML form'` prueba (`// #5`), automatiza lo siguiente:
|
||||
Dentro `tests/2_functional-tests.js`, en el `'Submit the surname "Vespucci" in the HTML form'` prueba (`// #6`), automatiza lo siguiente:
|
||||
|
||||
1. Rellena el formulario con el apellido `Vespucci`
|
||||
2. Presiona el botón enviar
|
||||
|
||||
+15
-13
@@ -8,10 +8,10 @@ dashedName: sudoku-solver
|
||||
|
||||
# --description--
|
||||
|
||||
Construye una aplicación full stack de JavaScript que sea funcionalmente similar a esta: <https://sudoku-solver.freecodecamp.rocks/>. Trabajar en este proyecto implicará escribir tu código utilizando uno de los siguientes métodos:
|
||||
Crea una aplicación full stack de JavaScript que sea funcionalmente similar a esta: <a href="https://sudoku-solver.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://sudoku-solver.freecodecamp.rocks/</a>. Trabajar en este proyecto implicará escribir tu código utilizando uno de los siguientes métodos:
|
||||
|
||||
- Clona [este repositorio de GitHub](https://github.com/freecodecamp/boilerplate-project-sudoku-solver) y completa tu proyecto localmente.
|
||||
- Usa [nuestro proyecto inicial de Replit](https://replit.com/github/freeCodeCamp/boilerplate-project-sudoku-solver) para completar tu proyecto.
|
||||
- Clone este repositorio de <a href="https://github.com/freecodecamp/boilerplate-project-sudoku-solver" target="_blank" rel="noopener noreferrer nofollow"> GitHub</a> y complete estos desafíos localmente.
|
||||
- Usa este <a href="https://replit.com/github/freeCodeCamp/boilerplate-project-sudoku-solver" target="_blank" rel="noopener noreferrer nofollow"> proyecto inicial de Replit</a> para completar tu proyecto.
|
||||
- Usa un constructor de sitios de tu elección para completar el proyecto. Asegúrate de incorporar todos los archivos de nuestro repositorio de GitHub.
|
||||
|
||||
Cuando hayas terminado, asegúrate de que una demostración funcional de tu proyecto esté alojado en algún lugar público. Luego, envía la URL en el campo `Solution Link`. Opcionalmente, también envía un enlace al código fuente de tu proyecto en el campo `GitHub Link`.
|
||||
@@ -270,7 +270,7 @@ async (getUserInput) => {
|
||||
};
|
||||
```
|
||||
|
||||
Si el objeto enviado a `/api/check` no existe `puzzle`,`coordinate` o `value`, el valor devuelto será `{ error: Required field(s) missing }`
|
||||
Si el objeto enviado a `/api/check` no existe `puzzle`,`coordinate` o `value`, el valor devuelto será `{ error: 'Required field(s) missing' }`
|
||||
|
||||
```js
|
||||
async (getUserInput) => {
|
||||
@@ -353,9 +353,11 @@ async (getUserInput) => {
|
||||
try {
|
||||
const getTests = await $.get(getUserInput('url') + '/_api/get-tests');
|
||||
assert.isArray(getTests);
|
||||
const units = getTests.filter((el) => el.context.includes('UnitTests'));
|
||||
assert.isAtLeast(units.length, 12, 'At least 12 tests passed');
|
||||
units.forEach((test) => {
|
||||
const unitTests = getTests.filter((test) => {
|
||||
return !!test.context.match(/Unit\s*Tests/gi);
|
||||
});
|
||||
assert.isAtLeast(unitTests.length, 12, 'At least 12 tests passed');
|
||||
unitTests.forEach((test) => {
|
||||
assert.equal(test.state, 'passed', 'Test in Passed State');
|
||||
assert.isAtLeast(
|
||||
test.assertions.length,
|
||||
@@ -369,18 +371,18 @@ async (getUserInput) => {
|
||||
};
|
||||
```
|
||||
|
||||
Las 14 pruebas funcionales están completas y pasan. Consulta `/tests/2_functional-tests.js` para la funcionalidad para la que debes escribir pruebas.
|
||||
Las 14 pruebas funcionales están completas y pasan. Consulta `/tests/2_functional-tests.js` para conocer la funcionalidad de la cual debes escribir pruebas.
|
||||
|
||||
```js
|
||||
async (getUserInput) => {
|
||||
try {
|
||||
const getTests = await $.get(getUserInput('url') + '/_api/get-tests');
|
||||
assert.isArray(getTests);
|
||||
const funcs = getTests.filter((el) =>
|
||||
el.context.includes('Functional Tests')
|
||||
);
|
||||
assert.isAtLeast(funcs.length, 14, 'At least 14 tests passed');
|
||||
funcs.forEach((test) => {
|
||||
const functTests = getTests.filter((test) => {
|
||||
return !!test.context.match(/Functional\s*Tests/gi);
|
||||
});
|
||||
assert.isAtLeast(functTests.length, 14, 'At least 14 tests passed');
|
||||
functTests.forEach((test) => {
|
||||
assert.equal(test.state, 'passed', 'Test in Passed State');
|
||||
assert.isAtLeast(
|
||||
test.assertions.length,
|
||||
|
||||
+7
-7
@@ -14,19 +14,19 @@ dashedName: data-visualization-mailing-lists
|
||||
|
||||
Más recursos:
|
||||
|
||||
\- [Ejercicio: Geodatos](https://www.youtube.com/watch?v=KfhslNzopxo)
|
||||
\- <a href="https://www.youtube.com/watch?v=KfhslNzopxo" target="_blank" rel="noopener noreferrer nofollow">Ejercicio: Geodatos</a>
|
||||
|
||||
\- [Ejercicio: Gmane Model](https://www.youtube.com/watch?v=wSpl1-7afAk)
|
||||
\-<a href="https://www.youtube.com/watch?v=wSpl1-7afAk" target="_blank" rel="noopener noreferrer nofollow">Ejercicio: Modelo Gmane</a>
|
||||
|
||||
\- [Ejercicio: Gmane Spider](https://www.youtube.com/watch?v=H3w4lOFBUOI)
|
||||
\-<a href="https://www.youtube.com/watch?v=H3w4lOFBUOI" target="_blank" rel="noopener noreferrer nofollow">Ejercicio: Araña Gmane</a>
|
||||
|
||||
\- [Ejercicio: Gmane Viz](https://www.youtube.com/watch?v=LRqVPMEXByw)
|
||||
\- <a href="https://www.youtube.com/watch?v=LRqVPMEXByw" target="_blank" rel="noopener noreferrer nofollow">Ejercicio: Gmane Viz</a>
|
||||
|
||||
\- [Ejercicio: Page Rank](https://www.youtube.com/watch?v=yFRAZBkBDBs)
|
||||
\- <a href="https://www.youtube.com/watch?v=yFRAZBkBDBs" target="_blank" rel="noopener noreferrer nofollow">Ejercicio: Rango de la página</a>
|
||||
|
||||
\- [Ejercicio: Page Spider](https://www.youtube.com/watch?v=sXedPQ_AnWA)
|
||||
\-<a href="https://www.youtube.com/watch?v=sXedPQ_AnWA" target="_blank" rel="noopener noreferrer nofollow">Ejercicio: Araña de página</a>
|
||||
|
||||
\- [Ejercicio: Page Viz](https://www.youtube.com/watch?v=Fm0hpkxsZoo)
|
||||
\-<a href="https://www.youtube.com/watch?v=Fm0hpkxsZoo" target="_blank" rel="noopener noreferrer nofollow">Ejercicio: Página Viz</a>
|
||||
|
||||
# --question--
|
||||
|
||||
|
||||
+2
-2
@@ -14,9 +14,9 @@ dashedName: intermediate-expressions
|
||||
|
||||
Más recursos:
|
||||
|
||||
\- [Ejercicio 1](https://youtu.be/t_4DPwsaGDY)
|
||||
\- <a href="https://youtu.be/t_4DPwsaGDY" target="_blank" rel="noopener noreferrer nofollow">Ejercicio 1</a>
|
||||
|
||||
\- [Ejercicio 2](https://youtu.be/wgkC8SxraAQ)
|
||||
\- <a href="https://youtu.be/wgkC8SxraAQ" target="_blank" rel="noopener noreferrer nofollow">Ejercicio 2</a>
|
||||
|
||||
# --question--
|
||||
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ dashedName: intermediate-strings
|
||||
|
||||
Más recursos:
|
||||
|
||||
\- [Ejercicio](https://www.youtube.com/watch?v=1bSqHot-KwE)
|
||||
\- <a href="https://www.youtube.com/watch?v=1bSqHot-KwE" target="_blank" rel="noopener noreferrer nofollow">Ejercicio</a>
|
||||
|
||||
# --question--
|
||||
|
||||
|
||||
+2
-2
@@ -18,9 +18,9 @@ dashedName: introduction-why-program
|
||||
|
||||
Más recursos:
|
||||
|
||||
\- [Instalar Python en Windows](https://youtu.be/F7mtLrYzZP8)
|
||||
\- <a href="https://youtu.be/F7mtLrYzZP8" target="_blank" rel="noopener noreferrer nofollow">Instalar Python en Windows</a>
|
||||
|
||||
\- [Instalar Python en MacOS](https://youtu.be/wfLnZP-4sZw)
|
||||
\- <a href="https://youtu.be/wfLnZP-4sZw" target="_blank" rel="noopener noreferrer nofollow">Instalar Python en MacOS</a>
|
||||
|
||||
# --question--
|
||||
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ dashedName: iterations-more-patterns
|
||||
|
||||
Más recursos:
|
||||
|
||||
\- [Ejercicio](https://www.youtube.com/watch?v=kjxXZQw0uPg)
|
||||
\- <a href="https://www.youtube.com/watch?v=kjxXZQw0uPg" target="_blank" rel="noopener noreferrer nofollow">Ejercicio</a>
|
||||
|
||||
# --question--
|
||||
|
||||
|
||||
+2
-2
@@ -14,9 +14,9 @@ dashedName: more-conditional-structures
|
||||
|
||||
Más recursos:
|
||||
|
||||
\- [Ejercicio 1](https://www.youtube.com/watch?v=crLerB4ZxMI)
|
||||
\- <a href="https://www.youtube.com/watch?v=crLerB4ZxMI" target="_blank" rel="noopener noreferrer nofollow">Ejercicio 1</a>
|
||||
|
||||
\- [Ejercicio 2](https://www.youtube.com/watch?v=KJN3-7HH6yk)
|
||||
\- <a href="https://www.youtube.com/watch?v=KJN3-7HH6yk" target="_blank" rel="noopener noreferrer nofollow">Ejercicio 2</a>
|
||||
|
||||
# --question--
|
||||
|
||||
|
||||
+3
-3
@@ -14,11 +14,11 @@ dashedName: networking-web-scraping-with-python
|
||||
|
||||
Más recursos:
|
||||
|
||||
\- [Ejercicio: socket1](https://www.youtube.com/watch?v=dWLdI143W-g)
|
||||
\- <a href="https://www.youtube.com/watch?v=dWLdI143W-g" target="_blank" rel="noopener noreferrer nofollow">Ejercicio: socket1</a>
|
||||
|
||||
\- [Ejercicio: urllib](https://www.youtube.com/watch?v=8yis2DvbBkI)
|
||||
\- <a href="https://www.youtube.com/watch?v=8yis2DvbBkI" target="_blank" rel="noopener noreferrer nofollow">Ejercicio: urllib</a>
|
||||
|
||||
\- [Ejercicio: urllinks](https://www.youtube.com/watch?v=g9flPDG9nnY)
|
||||
\- <a href="https://www.youtube.com/watch?v=g9flPDG9nnY" target="_blank" rel="noopener noreferrer nofollow">Ejercicio: urllinks</a>
|
||||
|
||||
# --question--
|
||||
|
||||
|
||||
+4
-4
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e7b9f170b6c005b0e76f08a
|
||||
title: Base de datos relaciones y SQLite
|
||||
title: Base de datos relacionales y SQLite
|
||||
challengeType: 11
|
||||
videoId: QlNod5-kFpA
|
||||
bilibiliIds:
|
||||
@@ -12,9 +12,9 @@ dashedName: relational-databases-and-sqlite
|
||||
|
||||
# --description--
|
||||
|
||||
[Descargar SQLite](https://www.sqlite.org/download.html)
|
||||
[Descargar el navegador DB para SQLite](https://sqlitebrowser.org/dl/)
|
||||
[uso de SQLite](https://www.sqlite.org/famous.html)
|
||||
<a href="https://www.sqlite.org/download.html" target="_blank" rel="noopener noreferrer nofollow">Descargar SQLite</a>
|
||||
<a href="https://sqlitebrowser.org/dl/" target="_blank" rel="noopener noreferrer nofollow">Descargar el navegador DB para SQLite</a>
|
||||
<a href="https://www.sqlite.org/famous.html" target="_blank" rel="noopener noreferrer nofollow">uso de SQLite</a>
|
||||
|
||||
# --question--
|
||||
|
||||
|
||||
+5
-5
@@ -14,15 +14,15 @@ dashedName: relational-databases-many-to-many-relationships
|
||||
|
||||
Mas recursos:
|
||||
|
||||
\- [Ejercicio: Email](https://www.youtube.com/watch?v=uQ3Qv1z_Vao)
|
||||
\- <a href="https://www.youtube.com/watch?v=uQ3Qv1z_Vao" target="_blank" rel="noopener noreferrer nofollow">Ejercicio: Correo electrónico</a>
|
||||
|
||||
\- [Ejercicio: Planilla](https://www.youtube.com/watch?v=qEkUEAz8j3o)
|
||||
\- <a href="https://www.youtube.com/watch?v=qEkUEAz8j3o" target="_blank" rel="noopener noreferrer nofollow">Ejercicio: Lista</a>
|
||||
|
||||
\- [Ejercicio: Pistas](https://www.youtube.com/watch?v=I-E7avcPeSE)
|
||||
\- <a href="https://www.youtube.com/watch?v=I-E7avcPeSE" target="_blank" rel="noopener noreferrer nofollow">Ejercicio: Pistas</a>
|
||||
|
||||
\- [Ejercicio: Twfriends](https://www.youtube.com/watch?v=RZRAoBFIH6A)
|
||||
\- <a href="https://www.youtube.com/watch?v=RZRAoBFIH6A" target="_blank" rel="noopener noreferrer nofollow">Ejercicio: Twfriends</a>
|
||||
|
||||
\- [Ejercicio: Twspider](https://www.youtube.com/watch?v=xBaJddvJL4A)
|
||||
\- <a href="https://www.youtube.com/watch?v=xBaJddvJL4A" target="_blank" rel="noopener noreferrer nofollow">Ejercicio: Twspider</a>
|
||||
|
||||
# --question--
|
||||
|
||||
|
||||
+1
-1
@@ -14,7 +14,7 @@ dashedName: strings-and-lists
|
||||
|
||||
Mas recursos:
|
||||
|
||||
\- [Ejercicio](https://www.youtube.com/watch?v=-9TfJF2dwHI)
|
||||
\- <a href="https://www.youtube.com/watch?v=-9TfJF2dwHI" target="_blank" rel="noopener noreferrer nofollow">Ejercicio</a>
|
||||
|
||||
# --question--
|
||||
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ dashedName: arithmetic-formatter
|
||||
|
||||
# --description--
|
||||
|
||||
Estarás [trabajando en este proyecto con nuestro código inicial de Replit](https://replit.com/github/freeCodeCamp/boilerplate-arithmetic-formatter).
|
||||
Estarás <a href="https://replit.com/github/freeCodeCamp/boilerplate-arithmetic-formatter" target="_blank" rel="noopener noreferrer nofollow">trabajando en este proyecto con nuestro código inicial en Replit</a>.
|
||||
|
||||
# --instructions--
|
||||
|
||||
@@ -64,7 +64,7 @@ La función devolverá la conversión correcta si los problemas suministrados es
|
||||
- Cada número (operando) debe contener solo dígitos. De lo contrario, la función devolverá: `Error: Numbers must only contain digits.`
|
||||
- Cada operando (también conocido como número en cada lado del operador) tiene un máximo de cuatro dígitos de ancho. De lo contrario, la cadena de error devuelta será: `Error: Numbers cannot be more than four digits.`
|
||||
- Si el usuario proporcionó el formato correcto de los problemas, la conversión que devuelva seguirá estas reglas:
|
||||
- Debe haber un solo espacio entre el operador y el más largo de los dos operandos, el operador estará en la misma línea que el segundo operando, ambos operandos estarán en el mismo orden proporcionado (el primero será el superior y el segundo el inferior.
|
||||
- Debe haber un solo espacio entre el operador y el más largo de los dos operandos, el operador estará en la misma línea que el segundo operando, ambos operandos estarán en el mismo orden proporcionado (el primero será el superior y el segundo el inferior).
|
||||
- Los números deben estar alineados a la derecha.
|
||||
- Debe haber cuatro espacios entre cada problema.
|
||||
- Debe haber guiones en la parte inferior de cada problema. Los guiones deben recorrer toda la longitud de cada problema individualmente. (El ejemplo anterior muestra el aspecto que debe tener.)
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@ dashedName: probability-calculator
|
||||
|
||||
# --description--
|
||||
|
||||
Estarás [trabajando en este proyecto con nuestro código inicial de Replit](https://replit.com/github/freeCodeCamp/boilerplate-probability-calculator).
|
||||
Estarás <a href="https://replit.com/github/freeCodeCamp/boilerplate-probability-calculator" target="_blank" rel="noopener noreferrer nofollow">trabajando en este proyecto con nuestro código inicial en Replit</a>.
|
||||
|
||||
# --instructions--
|
||||
|
||||
@@ -37,7 +37,7 @@ A continuación, crea una función `experiment` en `prob_calculator.py` (no dent
|
||||
|
||||
La función `experiment` debe devolver una probabilidad.
|
||||
|
||||
Por ejemplo, digamos que quieres determinar la probabilidad de obtener al menos 2 bolas rojas y 1 bola verde cuando dibujas 5 bolas de un sombrero que contiene 6 negras, 4 rojos y 3 verdes. Para hacer esto, realizamos `N` experimentos, cuántas veces `M` obtenemos al menos 2 bolas rojas y 1 bola verde, y estimar la probabilidad como `M/N`. Cada experimento consiste en comenzar con un sombrero que contiene las bolas especificadas, dibujar una serie de bolas, y comprobar si conseguimos las bolas que estábamos tratando de dibujar.
|
||||
Por ejemplo, digamos que quieres determinar la probabilidad de obtener al menos 2 bolas rojas y 1 bola verde cuando dibujas 5 bolas de un sombrero que contiene 6 negras, 4 rojos y 3 verdes. Para hacer esto, realizarás `N` experimentos, contarás cuantas `M` veces obtienes al menos 2 bolas rojas y 1 bola verde, y estimarás la probabilidad como `M/N`. Cada experimento consiste en comenzar con un sombrero que contiene las bolas especificadas, dibujar una serie de bolas, y comprobar si conseguimos las bolas que estábamos tratando de dibujar.
|
||||
|
||||
Así es como se llamaría la función de `experiment` basada en el ejemplo anterior con 2000 experimentos:
|
||||
|
||||
|
||||
+96
-42
@@ -8,71 +8,125 @@ dashedName: demographic-data-analyzer
|
||||
|
||||
# --description--
|
||||
|
||||
Trabajarás [este proyecto utilizando nuestro código inicial Replit](https://replit.com/github/freeCodeCamp/boilerplate-demographic-data-analyzer).
|
||||
Estarás <a href="https://replit.com/github/freeCodeCamp/boilerplate-demographic-data-analyzer" target="_blank" rel="noopener noreferrer nofollow">trabajando en este proyecto con nuestro código inicial en Replit</a>.
|
||||
|
||||
Todavía estamos desarrollando la parte interactiva del currículo de Python. Por el momento, aquí hay algunos videos en el canal de YouTube de freeCodeCamp.org que te enseñaran todo lo que necesitas saber para completar este proyecto:
|
||||
|
||||
- [Curso de vídeo de Python para todos](https://www.freecodecamp.org/news/python-for-everybody/) (14 horas)
|
||||
- [Curso de vídeo para aprender Python](https://www.freecodecamp.org/news/learn-python-video-course/) (10 horas)
|
||||
- <a href="https://www.freecodecamp.org/news/python-for-everybody/" target="_blank" rel="noopener noreferrer nofollow">Curso de video de Python para todos< /a>(14 horas)</p></li>
|
||||
|
||||
<li>
|
||||
<p spaces-before="0">
|
||||
<a href="https://www.freecodecamp.org/news/how-to-analyze-data-with-python-pandas/" target="_blank" rel="noopener noreferrer nofollow">Cómo analizar datos con Python Pandas</a> (10 horas)
|
||||
</p>
|
||||
</li></ul>
|
||||
|
||||
# --instructions--
|
||||
<h1 spaces-before="0">
|
||||
--instructions--
|
||||
</h1>
|
||||
|
||||
En este desafío debe analizar los datos demográficos usando Pandas. Se le da un conjunto de datos demográficos que fueron extraidos de la base de datos del censo de 1994. Aquí hay un ejemplo de cómo se debería ver:
|
||||
<p spaces-before="0">
|
||||
En este desafío debe analizar los datos demográficos usando Pandas. Se le da un conjunto de datos demográficos que fueron extraidos de la base de datos del censo de 1994. Aquí hay un ejemplo de cómo se debería ver:
|
||||
</p>
|
||||
|
||||
```markdown
|
||||
| | age | workclass | fnlwgt | education | education-num | marital-status | occupation | relationship | race | sex | capital-gain | capital-loss | hours-per-week | native-country | salary |
|
||||
<pre><code class="markdown">| | age | workclass | fnlwgt | education | education-num | marital-status | occupation | relationship | race | sex | capital-gain | capital-loss | hours-per-week | native-country | salary |
|
||||
|---:|------:|:-----------------|---------:|:------------|----------------:|:-------------------|:------------------|:---------------|:-------|:-------|---------------:|---------------:|-----------------:|:-----------------|:---------|
|
||||
| 0 | 39 | State-gov | 77516 | Bachelors | 13 | Never-married | Adm-clerical | Not-in-family | White | Male | 2174 | 0 | 40 | United-States | <=50K |
|
||||
| 1 | 50 | Self-emp-not-inc | 83311 | Bachelors | 13 | Married-civ-spouse | Exec-managerial | Husband | White | Male | 0 | 0 | 13 | United-States | <=50K |
|
||||
| 2 | 38 | Private | 215646 | HS-grad | 9 | Divorced | Handlers-cleaners | Not-in-family | White | Male | 0 | 0 | 40 | United-States | <=50K |
|
||||
| 3 | 53 | Private | 234721 | 11th | 7 | Married-civ-spouse | Handlers-cleaners | Husband | Black | Male | 0 | 0 | 40 | United-States | <=50K |
|
||||
| 4 | 28 | Private | 338409 | Bachelors | 13 | Married-civ-spouse | Prof-specialty | Wife | Black | Female | 0 | 0 | 40 | Cuba | <=50K |
|
||||
```
|
||||
| 0 | 39 | State-gov | 77516 | Bachelors | 13 | Never-married | Adm-clerical | Not-in-family | White | Male | 2174 | 0 | 40 | United-States | <=50K |
|
||||
| 1 | 50 | Self-emp-not-inc | 83311 | Bachelors | 13 | Married-civ-spouse | Exec-managerial | Husband | White | Male | 0 | 0 | 13 | United-States | <=50K |
|
||||
| 2 | 38 | Private | 215646 | HS-grad | 9 | Divorced | Handlers-cleaners | Not-in-family | White | Male | 0 | 0 | 40 | United-States | <=50K |
|
||||
| 3 | 53 | Private | 234721 | 11th | 7 | Married-civ-spouse | Handlers-cleaners | Husband | Black | Male | 0 | 0 | 40 | United-States | <=50K |
|
||||
| 4 | 28 | Private | 338409 | Bachelors | 13 | Married-civ-spouse | Prof-specialty | Wife | Black | Female | 0 | 0 | 40 | Cuba | <=50K |
|
||||
</code></pre>
|
||||
|
||||
Debes usar Pandas para responder a las siguientes preguntas:
|
||||
<p spaces-before="0">
|
||||
Debes usar Pandas para responder a las siguientes preguntas:
|
||||
</p>
|
||||
|
||||
- ¿Cuántas personas de cada raza están representadas en este dataset? Esta debería ser una Pandas series con nombres de raza como las etiquetas de índice. (columna `race`)
|
||||
- ¿Cuál es la edad promedio de los hombres?
|
||||
- ¿Cuál es el porcentaje de personas que tienen un grado de licenciatura?
|
||||
- ¿Que porcentaje de personas con una educación avanzada (`Bachelors`, `Masters` o `Doctorate`) generan mas de 50k?
|
||||
- ¿Que porcentaje de personas sin una educación avanzada generan mas de 50k?
|
||||
- ¿Cuál es el mínimo número de horas que una persona trabaja por semana?
|
||||
- ¿Qué porcentaje de personas que trabajan el minimo de horas por semana tienen un salario de mas de 50k?
|
||||
- ¿Qué país tiene el mas alto porcentaje de personjas que ganan >50k y cual es ese porcentaje?
|
||||
- Identifica la ocupacion mas popular de aquellos que ganan >50k en India.
|
||||
<ul>
|
||||
<li>
|
||||
¿Cuántas personas de cada raza están representadas en este dataset? Esta debería ser una Pandas series con nombres de raza como las etiquetas de índice. (columna <code>race</code>)
|
||||
</li>
|
||||
<li>
|
||||
¿Cuál es la edad promedio de los hombres?
|
||||
</li>
|
||||
<li>
|
||||
¿Cuál es el porcentaje de personas que tienen un grado de licenciatura?
|
||||
</li>
|
||||
<li>
|
||||
¿Que porcentaje de personas con una educación avanzada (<code>Bachelors</code>, <code>Masters</code> o <code>Doctorate</code>) generan mas de 50k?
|
||||
</li>
|
||||
<li>
|
||||
¿Que porcentaje de personas sin una educación avanzada generan mas de 50k?
|
||||
</li>
|
||||
<li>
|
||||
¿Cuál es el mínimo número de horas que una persona trabaja por semana?
|
||||
</li>
|
||||
<li>
|
||||
¿Qué porcentaje de personas que trabajan el minimo de horas por semana tienen un salario de mas de 50k?
|
||||
</li>
|
||||
<li>
|
||||
¿Qué país tiene el mas alto porcentaje de personjas que ganan >50k y cual es ese porcentaje?
|
||||
</li>
|
||||
<li>
|
||||
Identifica la ocupacion mas popular de aquellos que ganan >50k en India.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
Utilice el código de inicio en el archivo `demographic_data_analyzer`. Actualice el código para que todas las variables definidas como "None" se establezcan al cálculo o código apropiado. Redondea todos los decimales a la décima más cercana.
|
||||
<p spaces-before="0">
|
||||
Utilice el código de inicio en el archivo <code>demographic_data_analyzer</code>. Actualice el código para que todas las variables definidas como "None" se establezcan al cálculo o código apropiado. Redondea todos los decimales a la décima más cercana.
|
||||
</p>
|
||||
|
||||
Las pruebas unitarias están escritas para ti en `test_module.py`.
|
||||
<p spaces-before="0">
|
||||
Las pruebas unitarias están escritas para ti en <code>test_module.py</code>.
|
||||
</p>
|
||||
|
||||
## Desarrollo
|
||||
<h2 spaces-before="0">
|
||||
Desarrollo
|
||||
</h2>
|
||||
|
||||
Para el desarrollo, puedes utilizar `main.py` para probar tus funciones. Haz clic en el botón "run" y se ejecutará `main.py`.
|
||||
<p spaces-before="0">
|
||||
Para el desarrollo, puedes utilizar <code>main.py</code> para probar tus funciones. Haz clic en el botón "run" y se ejecutará <code>main.py</code>.
|
||||
</p>
|
||||
|
||||
## Pruebas
|
||||
<h2 spaces-before="0">
|
||||
Pruebas
|
||||
</h2>
|
||||
|
||||
Importamos las pruebas de `test_module.py` a `main.py` para tu conveniencia. Las pruebas se ejecutarán automáticamente cada vez que presiones el botón "run".
|
||||
<p spaces-before="0">
|
||||
Importamos las pruebas de <code>test_module.py</code> a <code>main.py</code> para tu conveniencia. Las pruebas se ejecutarán automáticamente cada vez que presiones el botón "run".
|
||||
</p>
|
||||
|
||||
## Envío
|
||||
<h2 spaces-before="0">
|
||||
Envío
|
||||
</h2>
|
||||
|
||||
Copia el enlace de tu proyecto y envíalo a freeCodeCamp.
|
||||
<p spaces-before="0">
|
||||
Copia el enlace de tu proyecto y envíalo a freeCodeCamp.
|
||||
</p>
|
||||
|
||||
## Fuente de datos
|
||||
<h2 spaces-before="0">
|
||||
Fuente de datos
|
||||
</h2>
|
||||
|
||||
Dua, D. y Graff, C. (2019). [UCI Machine Learning Repository](http://archive.ics.uci.edu/ml). Irvine, CA: University of California, School of Information and Computer Science.
|
||||
<p spaces-before="0">
|
||||
Dua, D. y Graff, C. (2019). <a href="http://archive.ics.uci.edu/ml" target="_blank" rel="noopener noreferrer nofollow">UCI Machine Learning Repositorio</a>. Irvine, CA: University of California, School of Information and Computer Science.
|
||||
</p>
|
||||
|
||||
# --hints--
|
||||
<h1 spaces-before="0">
|
||||
--hints--
|
||||
</h1>
|
||||
|
||||
Debería pasar todas las pruebas de Python.
|
||||
<p spaces-before="0">
|
||||
Debería pasar todas las pruebas de Python.
|
||||
</p>
|
||||
|
||||
```js
|
||||
<pre><code class="js">
|
||||
</code></pre>
|
||||
|
||||
```
|
||||
<h1 spaces-before="0">
|
||||
--solutions--
|
||||
</h1>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
# Python challenges don't need solutions,
|
||||
<pre><code class="py"> # Python challenges don't need solutions,
|
||||
# because they would need to be tested against a full working project.
|
||||
# Please check our contributing guidelines to learn more.
|
||||
```
|
||||
</code></pre>
|
||||
|
||||
+64
-31
@@ -8,23 +8,35 @@ dashedName: mean-variance-standard-deviation-calculator
|
||||
|
||||
# --description--
|
||||
|
||||
Estarás [trabajando en este proyecto con nuestro código inicial en Replit](https://replit.com/github/freeCodeCamp/boilerplate-mean-variance-standard-deviation-calculator).
|
||||
Estarás <a href="https://replit.com/github/freeCodeCamp/boilerplate-mean-variance-standard-deviation-calculator" target="_blank" rel="noopener noreferrer nofollow" mark="crwd-mark ">trabajando en este proyecto con nuestro código de inicio Replit</a>.
|
||||
|
||||
Todavía estamos desarrollando la parte interactiva del currículo de Python. Por ahora, aquí hay algunos videos en el canal de YouTube de freeCodeCamp.org que te enseñaran todo lo que necesitas saber para completar este proyecto:
|
||||
|
||||
- [Python para todo el mundo Curso en Video](https://www.freecodecamp.org/news/python-for-everybody/) (14 horas)
|
||||
- [Aprende el Video Curso de Python](https://www.freecodecamp.org/news/learn-python-video-course/) (10 horas)
|
||||
- <a href="https://www.freecodecamp.org/news/python-for-everybody/" target="_blank" rel="noopener noreferrer nofollow">Curso de video de Python para todos< /a>(14 horas)</p></li>
|
||||
|
||||
<li>
|
||||
<p spaces-before="0">
|
||||
<a href="https://www.freecodecamp.org/news/how-to-analyze-data-with-python-pandas/" target="_blank" rel="noopener noreferrer nofollow">Cómo analizar datos con Python Pandas</a> (10 horas)
|
||||
</p>
|
||||
</li></ul>
|
||||
|
||||
# --instructions--
|
||||
<h1 spaces-before="0">
|
||||
--instructions--
|
||||
</h1>
|
||||
|
||||
Crea una función llamada `calculate()` en `mean_var_std.py` que usa Numpy para producir la media, varianza, desviación estándar, max, min, y suma de las filas, columnas y elementos en una matriz de 3 x 3.
|
||||
<p spaces-before="0">
|
||||
Crea una función llamada <code>calculate()</code> en <code>mean_var_std.py</code> que usa Numpy para producir la media, varianza, desviación estándar, max, min, y suma de las filas, columnas y elementos en una matriz de 3 x 3.
|
||||
</p>
|
||||
|
||||
La entrada de la función debe ser una lista que contenga 9 dígitos. La función debe convertir la lista en una matriz numérica de 3 x 3, y luego devolver un diccionario que contenga la media, varianza, desviación estándar, max, min, y suma a lo largo de ambos ejes y para la matriz aplanada.
|
||||
<p spaces-before="0">
|
||||
La entrada de la función debe ser una lista que contenga 9 dígitos. La función debe convertir la lista en una matriz numérica de 3 x 3, y luego devolver un diccionario que contenga la media, varianza, desviación estándar, max, min, y suma a lo largo de ambos ejes y para la matriz aplanada.
|
||||
</p>
|
||||
|
||||
El diccionario retornado debería seguir este formato:
|
||||
<p spaces-before="0">
|
||||
El diccionario retornado debería seguir este formato:
|
||||
</p>
|
||||
|
||||
```py
|
||||
{
|
||||
<pre><code class="py">{
|
||||
'mean': [axis1, axis2, flattened],
|
||||
'variance': [axis1, axis2, flattened],
|
||||
'standard deviation': [axis1, axis2, flattened],
|
||||
@@ -32,14 +44,17 @@ El diccionario retornado debería seguir este formato:
|
||||
'min': [axis1, axis2, flattened],
|
||||
'sum': [axis1, axis2, flattened]
|
||||
}
|
||||
```
|
||||
</code></pre>
|
||||
|
||||
Si una lista que contiene menos de 9 elementos es pasada a la función, debería levantar una excepción de `ValueError` con el mensaje: "La lista debe contener nueve números". Los valores en el diccionario devuelto deben ser listas y no matrices Numpy.
|
||||
<p spaces-before="0">
|
||||
Si una lista que contiene menos de 9 elementos es pasada a la función, debería levantar una excepción de <code>ValueError</code> con el mensaje: "La lista debe contener nueve números". Los valores en el diccionario devuelto deben ser listas y no matrices Numpy.
|
||||
</p>
|
||||
|
||||
Por ejemplo, `calculate([0,1,2,3,4,5,6,7,8])` debe regresar:
|
||||
<p spaces-before="0">
|
||||
Por ejemplo, <code>calculate([0,1,2,3,4,5,6,7,8])</code> debe regresar:
|
||||
</p>
|
||||
|
||||
```py
|
||||
{
|
||||
<pre><code class="py">{
|
||||
'mean': [[3.0, 4.0, 5.0], [1.0, 4.0, 7.0], 4.0],
|
||||
'variance': [[6.0, 6.0, 6.0], [0.6666666666666666, 0.6666666666666666, 0.6666666666666666], 6.666666666666667],
|
||||
'standard deviation': [[2.449489742783178, 2.449489742783178, 2.449489742783178], [0.816496580927726, 0.816496580927726, 0.816496580927726], 2.581988897471611],
|
||||
@@ -47,34 +62,52 @@ Por ejemplo, `calculate([0,1,2,3,4,5,6,7,8])` debe regresar:
|
||||
'min': [[0, 1, 2], [0, 3, 6], 0],
|
||||
'sum': [[9, 12, 15], [3, 12, 21], 36]
|
||||
}
|
||||
```
|
||||
</code></pre>
|
||||
|
||||
Las pruebas unitarias para este proyecto están en `test_module.py`.
|
||||
<p spaces-before="0">
|
||||
Las pruebas unitarias para este proyecto están en <code>test_module.py</code>.
|
||||
</p>
|
||||
|
||||
## Desarrollo
|
||||
<h2 spaces-before="0">
|
||||
Desarrollo
|
||||
</h2>
|
||||
|
||||
Durante el desarrollo, puede usar `main.py` para probar su función `calculate()`. Haz clic en el botón "run" y se ejecutará `main.py`.
|
||||
<p spaces-before="0">
|
||||
Durante el desarrollo, puede usar <code>main.py</code> para probar su función <code>calculate()</code>. Haz clic en el botón "run" y se ejecutará <code>main.py</code>.
|
||||
</p>
|
||||
|
||||
## Pruebas
|
||||
<h2 spaces-before="0">
|
||||
Pruebas
|
||||
</h2>
|
||||
|
||||
Hemos importado las pruebas de `test_module.py` a `main.py` para tu conveniencia. Las pruebas se ejecutarán automáticamente cada vez que pulses el botón "run".
|
||||
<p spaces-before="0">
|
||||
Hemos importado las pruebas de <code>test_module.py</code> a <code>main.py</code> para tu conveniencia. Las pruebas se ejecutarán automáticamente cada vez que pulses el botón "run".
|
||||
</p>
|
||||
|
||||
## Envío
|
||||
<h2 spaces-before="0">
|
||||
Envío
|
||||
</h2>
|
||||
|
||||
Copia el enlace de tu proyecto y envíalo a freeCodeCamp.
|
||||
<p spaces-before="0">
|
||||
Copia el enlace de tu proyecto y envíalo a freeCodeCamp.
|
||||
</p>
|
||||
|
||||
# --hints--
|
||||
<h1 spaces-before="0">
|
||||
--hints--
|
||||
</h1>
|
||||
|
||||
Debería pasar todas las pruebas de Python.
|
||||
<p spaces-before="0">
|
||||
Debería pasar todas las pruebas de Python.
|
||||
</p>
|
||||
|
||||
```js
|
||||
<pre><code class="js">
|
||||
</code></pre>
|
||||
|
||||
```
|
||||
<h1 spaces-before="0">
|
||||
--solutions--
|
||||
</h1>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
# Python challenges don't need solutions,
|
||||
<pre><code class="py"> # Python challenges don't need solutions,
|
||||
# because they would need to be tested against a full working project.
|
||||
# Please check our contributing guidelines to learn more.
|
||||
```
|
||||
</code></pre>
|
||||
|
||||
+337
-52
@@ -8,83 +8,368 @@ dashedName: medical-data-visualizer
|
||||
|
||||
# --description--
|
||||
|
||||
Estarás [trabajando en este proyecto con nuestro código inicial de Replit](https://replit.com/github/freeCodeCamp/boilerplate-medical-data-visualizer).
|
||||
Estarás <a href="https://replit.com/github/freeCodeCamp/boilerplate-medical-data-visualizer" target="_blank" rel="noopener noreferrer nofollow">trabajando en este proyecto con nuestro código de inicio Replit</a>.
|
||||
|
||||
Todavía estamos desarrollando la parte interactiva del currículo de Python. Por ahora, aquí hay algunos vídeos en nuestro canal de YouTube freeCodeCamp.org que te enseñará todo lo que necesitas saber para completer este proyecto:
|
||||
|
||||
- [Curso: Python para todos](https://www.freecodecamp.org/news/python-for-everybody/) (14 horas)
|
||||
- [Curso: Aprende Python](https://www.freecodecamp.org/news/learn-python-video-course/) (10 horas)
|
||||
- <a href="https://www.freecodecamp.org/news/python-for-everybody/" target="_blank" rel="noopener noreferrer nofollow">Curso de video de Python para todos< /a>(14 horas)</p></li>
|
||||
|
||||
<li>
|
||||
<p spaces-before="0">
|
||||
<a href="https://www.freecodecamp.org/news/how-to-analyze-data-with-python-pandas/" target="_blank" rel="noopener noreferrer nofollow">Cómo analizar datos con Python Pandas</a> (10 horas)
|
||||
</p>
|
||||
</li></ul>
|
||||
|
||||
# --instructions--
|
||||
<h1 spaces-before="0">
|
||||
--instructions--
|
||||
</h1>
|
||||
|
||||
En este proyecto, visualizarás y harás algunos cálculos a partir de datos de exámenes médicos utilizando matplotlib, seabron y pandas. Los valores del conjunto de datos (dataset) se recogieron durante los exámenes médicos.
|
||||
<p spaces-before="0">
|
||||
En este proyecto, visualizarás y harás algunos cálculos a partir de datos de exámenes médicos utilizando matplotlib, seabron y pandas. Los valores del conjunto de datos (dataset) se recogieron durante los exámenes médicos.
|
||||
</p>
|
||||
|
||||
## Descripción de datos
|
||||
<h2 spaces-before="0">
|
||||
Descripción de datos
|
||||
</h2>
|
||||
|
||||
Las filas del conjunto de datos representan a los pacientes y las columnas representan información como medidas corporales, resultados de varios análisis de sangre y opciones de estilo de vida. Utilizarás el conjunto de datos para explorar la relación entre enfermedades cardiacas, medidas del cuerpo, indicadores sanguíneos y opciones de estilo de vida.
|
||||
<p spaces-before="0">
|
||||
Las filas del conjunto de datos representan a los pacientes y las columnas representan información como medidas corporales, resultados de varios análisis de sangre y opciones de estilo de vida. Utilizarás el conjunto de datos para explorar la relación entre enfermedades cardiacas, medidas del cuerpo, indicadores sanguíneos y opciones de estilo de vida.
|
||||
</p>
|
||||
|
||||
Nombre del archivo: medical_examination.csv
|
||||
<p spaces-before="0">
|
||||
Nombre del archivo: medical_examination.csv
|
||||
</p>
|
||||
|
||||
| Característica | Tipo de variable | Variable | Tipo de unidad |
|
||||
|:-----------------------------------------------------:|:--------------------------:|:----------:|:---------------------------------------------------------------------:|
|
||||
| Edad | Característica objetivo | edad | int (días) |
|
||||
| Altura | Característica objetivo | altura | int (cm) |
|
||||
| Peso | Característica objetivo | peso | float (kg) |
|
||||
| Sexo | Característica objetivo | género | código de categoría |
|
||||
| Presión arterial sistólica | Características del examen | ap_hi | int |
|
||||
| Presión arterial diastólica | Característica del examen | ap_lo | int |
|
||||
| Colesterol | Característica del examen | colesterol | 1: normal, 2: por encima de lo normal, 3: muy por encima de lo normal |
|
||||
| Glucosa | Característica del examen | glúcido | 1: normal, 2: por encima de lo normal, 3: muy por encima de lo normal |
|
||||
| Fumador | Característica subjetiva | humo | binario |
|
||||
| Consumo de alcohol | Característica subjetiva | alco | binario |
|
||||
| Actividad física | Característica subjetiva | activo | binario |
|
||||
| Presencia o ausencia de enfermedades cardiovasculares | Variable objetivo | cardiaco | binario |
|
||||
<table spaces-before="0">
|
||||
<tr>
|
||||
<th align="center">
|
||||
Característica
|
||||
</th>
|
||||
|
||||
<th align="center">
|
||||
Tipo de variable
|
||||
</th>
|
||||
|
||||
<th align="center">
|
||||
Variable
|
||||
</th>
|
||||
|
||||
<th align="center">
|
||||
Tipo de unidad
|
||||
</th>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align="center">
|
||||
Edad
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
Característica objetivo
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
edad
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
int (días)
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align="center">
|
||||
Altura
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
Característica objetivo
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
altura
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
int (cm)
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align="center">
|
||||
Peso
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
Característica objetivo
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
peso
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
float (kg)
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align="center">
|
||||
Sexo
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
Característica objetivo
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
género
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
código de categoría
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align="center">
|
||||
Presión arterial sistólica
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
Características del examen
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
ap_hi
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
int
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align="center">
|
||||
Presión arterial diastólica
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
Característica del examen
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
ap_lo
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
int
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align="center">
|
||||
Colesterol
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
Característica del examen
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
colesterol
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
1: normal, 2: por encima de lo normal, 3: muy por encima de lo normal
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align="center">
|
||||
Glucosa
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
Característica del examen
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
glúcido
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
1: normal, 2: por encima de lo normal, 3: muy por encima de lo normal
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align="center">
|
||||
Fumador
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
Característica subjetiva
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
humo
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
binario
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align="center">
|
||||
Consumo de alcohol
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
Característica subjetiva
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
alco
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
binario
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align="center">
|
||||
Actividad física
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
Característica subjetiva
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
activo
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
binario
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<td align="center">
|
||||
Presencia o ausencia de enfermedades cardiovasculares
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
Variable objetivo
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
cardiaco
|
||||
</td>
|
||||
|
||||
<td align="center">
|
||||
binario
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## Tareas
|
||||
<h2 spaces-before="0">
|
||||
Tareas
|
||||
</h2>
|
||||
|
||||
Crear un gráfico similar a `ejemplos/Figure_1. ng`, donde mostramos las cifras de resultados buenos y malos para las variables `colesterol`, `gluc`, `alco`, `activo` y `humo` en los pacientes con cardio=1 y cardio=0 en diferentes paneles.
|
||||
<p spaces-before="0">
|
||||
Crear un gráfico similar a <code>ejemplos/Figure_1. ng</code>, donde mostramos las cifras de resultados buenos y malos para las variables <code>colesterol</code>, <code>gluc</code>, <code>alco</code>, <code>activo</code> y <code>humo</code> en los pacientes con cardio=1 y cardio=0 en diferentes paneles.
|
||||
</p>
|
||||
|
||||
Utiliza los datos para completar las siguientes tareas en `medical_data_visualizer.py`:
|
||||
<p spaces-before="0">
|
||||
Utiliza los datos para completar las siguientes tareas en <code>medical_data_visualizer.py</code>:
|
||||
</p>
|
||||
|
||||
- Agrega una columna de `sobrepeso` a los datos. Para determinar si una persona tiene sobrepeso, primero calcule su IMC dividiendo su peso en kilogramos por el cuadrado de su altura en metros. Si ese valor es > 25 entonces la persona tiene sobrepeso. Utilice el valor 0 para NO sobrepeso y el valor 1 para el sobrepeso.
|
||||
- Normaliza los datos haciendo 0 siempre bueno y 1 siempre malo. Si el valor de `cholesterol` o `gluc` es 1, haga que el valor 0. Si el valor es mayor que 1, haga el valor 1.
|
||||
- Convierte los datos en formato largo y crea un gráfico que muestre el recuento de valores de las características categóricas usando `catplot()` de seaborn. El conjunto de datos debe dividirse por 'Cardio', así que hay un gráfico por cada valor de `cardio`. El gráfico debería verse como `examples/Figure_1.png`.
|
||||
- Limpia los datos. Filtrar los siguientes segmentos de pacientes que representan datos incorrectos:
|
||||
- la presión diastólica es más alta que la máxima (Mantén los datos correctos con `(df['ap_lo'] <= df['ap_hi'])`)
|
||||
- la altura es menor que el 2.5º percentil (Mantén los datos correctos con `(df['height'] >= df['height'].quantile(0.025))`)
|
||||
- la altura es superior al 97,5º percentil
|
||||
- el peso es menor que el 2,5º percentil
|
||||
- el peso es superior al 97,5º percentil
|
||||
- Crear una matriz de correlación usando el conjunto de datos. Grafica la matriz de correlación usando la función `heatmap()` de seaborn. Enmascarar el triángulo superior de la matriz. El gráfico debería verse como `examples/Figure_2.png`.
|
||||
<ul>
|
||||
<li>
|
||||
Agrega una columna de <code>sobrepeso</code> a los datos. Para determinar si una persona tiene sobrepeso, primero calcule su IMC dividiendo su peso en kilogramos por el cuadrado de su altura en metros. Si ese valor es > 25 entonces la persona tiene sobrepeso. Utilice el valor 0 para NO sobrepeso y el valor 1 para el sobrepeso.
|
||||
</li>
|
||||
<li>
|
||||
Normaliza los datos haciendo 0 siempre bueno y 1 siempre malo. Si el valor de <code>cholesterol</code> o <code>gluc</code> es 1, haga que el valor 0. Si el valor es mayor que 1, haga el valor 1.
|
||||
</li>
|
||||
<li>
|
||||
Convierte los datos en formato largo y crea un gráfico que muestre el recuento de valores de las características categóricas usando <code>catplot()</code> de seaborn. El conjunto de datos debe dividirse por 'Cardio', así que hay un gráfico por cada valor de <code>cardio</code>. El gráfico debería verse como <code>examples/Figure_1.png</code>.
|
||||
</li>
|
||||
<li>
|
||||
Limpia los datos. Filtrar los siguientes segmentos de pacientes que representan datos incorrectos: <ul>
|
||||
<li>
|
||||
la presión diastólica es más alta que la máxima (Mantén los datos correctos con <code>(df['ap_lo'] <= df['ap_hi'])</code>)
|
||||
</li>
|
||||
<li>
|
||||
la altura es menor que el 2.5º percentil (Mantén los datos correctos con <code>(df['height'] >= df['height'].quantile(0.025))</code>)
|
||||
</li>
|
||||
<li>
|
||||
la altura es superior al 97,5º percentil
|
||||
</li>
|
||||
<li>
|
||||
el peso es menor que el 2,5º percentil
|
||||
</li>
|
||||
<li>
|
||||
el peso es superior al 97,5º percentil
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
Crear una matriz de correlación usando el conjunto de datos. Grafica la matriz de correlación usando la función <code>heatmap()</code> de seaborn. Enmascarar el triángulo superior de la matriz. El gráfico debería verse como <code>examples/Figure_2.png</code>.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
Cada vez que una variable está establecida en `Ninguno`, asegúrese de establecerla en el código correcto.
|
||||
<p spaces-before="0">
|
||||
Cada vez que una variable está establecida en <code>Ninguno</code>, asegúrese de establecerla en el código correcto.
|
||||
</p>
|
||||
|
||||
Las pruebas unitarias están escritas en `test_module.py`.
|
||||
<p spaces-before="0">
|
||||
Las pruebas unitarias están escritas en <code>test_module.py</code>.
|
||||
</p>
|
||||
|
||||
## Desarrollo
|
||||
<h2 spaces-before="0">
|
||||
Desarrollo
|
||||
</h2>
|
||||
|
||||
Para el desarrollo, puedes usar `main.py` para probar tus funciones. Haz clic en el botón "run" y se ejecutará `main.py`.
|
||||
<p spaces-before="0">
|
||||
Para el desarrollo, puedes usar <code>main.py</code> para probar tus funciones. Haz clic en el botón "run" y se ejecutará <code>main.py</code>.
|
||||
</p>
|
||||
|
||||
## Pruebas
|
||||
<h2 spaces-before="0">
|
||||
Pruebas
|
||||
</h2>
|
||||
|
||||
Hemos importado las pruebas de `test_module.py` a `main.py` para tu conveniencia. Las pruebas se ejecutarán automáticamente cada vez que pulses el botón "run".
|
||||
<p spaces-before="0">
|
||||
Hemos importado las pruebas de <code>test_module.py</code> a <code>main.py</code> para tu conveniencia. Las pruebas se ejecutarán automáticamente cada vez que pulses el botón "run".
|
||||
</p>
|
||||
|
||||
## Envío
|
||||
<h2 spaces-before="0">
|
||||
Envío
|
||||
</h2>
|
||||
|
||||
Copia el enlace de tu proyecto y envíalo a freeCodeCamp.
|
||||
<p spaces-before="0">
|
||||
Copia el enlace de tu proyecto y envíalo a freeCodeCamp.
|
||||
</p>
|
||||
|
||||
# --hints--
|
||||
<h1 spaces-before="0">
|
||||
--hints--
|
||||
</h1>
|
||||
|
||||
Debería pasar todas las pruebas de Python.
|
||||
<p spaces-before="0">
|
||||
Debería pasar todas las pruebas de Python.
|
||||
</p>
|
||||
|
||||
```js
|
||||
<pre><code class="js">
|
||||
</code></pre>
|
||||
|
||||
```
|
||||
<h1 spaces-before="0">
|
||||
--solutions--
|
||||
</h1>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
# Python challenges don't need solutions,
|
||||
<pre><code class="py"> # Python challenges don't need solutions,
|
||||
# because they would need to be tested against a full working project.
|
||||
# Please check our contributing guidelines to learn more.
|
||||
```
|
||||
</code></pre>
|
||||
|
||||
+8
-7
@@ -8,12 +8,13 @@ dashedName: page-view-time-series-visualizer
|
||||
|
||||
# --description--
|
||||
|
||||
Estarás [trabajando en este proyecto con nuestro proyecto inicial de Replit](https://replit.com/github/freeCodeCamp/boilerplate-page-view-time-series-visualizer).
|
||||
Estarás <a href="https://replit.com/github/freeCodeCamp/boilerplate-page-view-time-series-visualizer" target="_blank" rel="noopener noreferrer nofollow">trabajando en este proyecto con nuestro código de inicio Replit</a>.
|
||||
|
||||
Todavía estamos desarrollando la parte interactiva del currículo de Python. Por el momento, aquí hay algunos videos en el canal de YouTube de freeCodeCamp.org que te enseñaran todo lo que necesitas saber para completar este proyecto:
|
||||
|
||||
- [Curso: Python para todos](https://www.freecodecamp.org/news/python-for-everybody/) (14 horas)
|
||||
- [Curso: Aprende Python](https://www.freecodecamp.org/news/learn-python-video-course/) (10 horas)
|
||||
- <a href="https://www.freecodecamp.org/news/python-for-everybody/" target="_blank" rel="noopener noreferrer nofollow">Curso de vídeo de Python para todos</a>(14 horas)
|
||||
|
||||
- <a href="https://www.freecodecamp.org/news/how-to-analyze-data-with-python-pandas/" target="_blank" rel="noopener noreferrer nofollow">Cómo analizar datos con Python Pandas</a> (10 horas)
|
||||
|
||||
# --instructions--
|
||||
|
||||
@@ -21,11 +22,11 @@ Para este proyecto, visualizarás los datos de las series temporales utilizando
|
||||
|
||||
Utiliza los datos para completar las siguientes tareas:
|
||||
|
||||
- Utiliza Pandas para importar los datos de "fcc-forum-pageviews.csv". Establece como índice la columna "fecha".
|
||||
- Utiliza Pandas para importar los datos de "fcc-forum-pageviews.csv". Establece el índice de la columna `date`.
|
||||
- Limpiar los datos filtrando los días en que las vistas de la página se encuentran en el 2,5% superior del conjunto de datos o en el 2,5% inferior del conjunto de datos.
|
||||
- Crea una función llamada `draw_line_plot` que utilice Matplotlib para dibujar un gráfico de línea similar a "examples/Figure_1.png". El título debe ser "Daily freeCodeCamp Forum Page Views 5/2016-12/2019". La etiqueta en el eje x debe ser "Date" y la etiqueta en el eje y debe ser "Page Views".
|
||||
- Crea una función llamada `draw_bar_plot` que dibuje un gráfico de barras similar a "examples/Figure_2.png". Debe mostrar el número promedio de vistas diarias de cada mes, agrupadas por año. La leyenda debe mostrar etiquetas mensuales y tener un título de "Months". En el gráfico, la etiqueta en el eje x debe ser "Years" y la etiqueta en el eje y debe ser "Average Page Views".
|
||||
- Crea una función llamada `draw_box_plot` que utilice Seaborn para dibujar dos diagramas de caja adyacentes similares a "examples/Figure_3.png". Estos diagramas de caja deben mostrar cómo se distribuyen los valores dentro de un año o mes determinado y cómo se compara con el tiempo. El título del primer gráfico debe ser "Year-wise Box Plot (Trend)" y el título del segundo gráfico debe ser "Month-wise Box Plot (Seasonality)". Asegúrese de que las etiquetas del mes en la parte inferior comienzan en "Jan" y los ejes x están etiquetados correctamente. El boilerplate incluye comandos para preparar los datos.
|
||||
- Crea una función llamada `draw_line_plot` que utilice Matplotlib para dibujar un gráfico de línea similar a "examples/Figure_1.png". El título debe ser `Daily freeCodeCamp Forum Page Views 5/2016-12/2019`. La etiqueta en el eje x debe ser `Date` y la etiqueta en el eje y debe ser `Page Views`.
|
||||
- Crea una función llamada `draw_bar_plot` que dibuje un gráfico de barras similar a "examples/Figure_2.png". Debe mostrar el número promedio de vistas diarias de cada mes, agrupadas por año. La leyenda debe mostrar las etiquetas de los meses y tener un título de `Months`. En el gráfico, la etiqueta en el eje x debe ser `Years` y la etiqueta en el eje y debe ser `Average Page Views`.
|
||||
- Crea una función llamada `draw_box_plot` que utilice Seaborn para dibujar dos diagramas de caja adyacentes similares a "examples/Figure_3.png". Estos diagramas de caja deben mostrar cómo se distribuyen los valores dentro de un año o mes determinado y cómo se compara con el tiempo. El título del primer gráfico debe ser `Year-wise Box Plot (Trend)` y el título del segundo gráfico debe ser `Month-wise Box Plot (Seasonality)`. Asegúrese de que las etiquetas de los meses en la parte inferior comiencen en `Jan` y que los ejes x e y estén etiquetados correctamente. El boilerplate incluye comandos para preparar los datos.
|
||||
|
||||
Para cada gráfico, asegúrese de usar una copia de los datos. Las pruebas unitarias están escritas para en `test_module.py`.
|
||||
|
||||
|
||||
+80
-30
@@ -8,57 +8,107 @@ dashedName: sea-level-predictor
|
||||
|
||||
# --description--
|
||||
|
||||
Estarás [trabajando en este proyecto con nuestro código inicial de Replit](https://replit.com/github/freeCodeCamp/boilerplate-sea-level-predictor).
|
||||
Estarás <a href="https://replit.com/github/freeCodeCamp/boilerplate-sea-level-predictor" target="_blank" rel="noopener noreferrer nofollow">trabajando en este proyecto con nuestro código de inicio Replit</a>.
|
||||
|
||||
Todavía estamos desarrollando la parte interactiva del currículo de Python. Por ahora, aquí hay algunos videos en el canal de YouTube de freeCodeCamp.org que te enseñaran todo lo que necesitas saber para completar este proyecto:
|
||||
|
||||
- [Python para Todos Curso en Video](https://www.freecodecamp.org/news/python-for-everybody/) (14 horas)
|
||||
- [Aprende Python Curso en Video](https://www.freecodecamp.org/news/learn-python-video-course/) (10 horas)
|
||||
- <a href="https://www.freecodecamp.org/news/python-for-everybody/" target="_blank" rel="noopener noreferrer nofollow">Curso de video de Python para todos< /a>(14 horas)</p></li>
|
||||
|
||||
<li>
|
||||
<p spaces-before="0">
|
||||
<a href="https://www.freecodecamp.org/news/how-to-analyze-data-with-python-pandas/" target="_blank" rel="noopener noreferrer nofollow">Cómo analizar datos con Python Pandas</a> (10 horas)
|
||||
</p>
|
||||
</li></ul>
|
||||
|
||||
# --instructions--
|
||||
<h1 spaces-before="0">
|
||||
--instructions--
|
||||
</h1>
|
||||
|
||||
Analizará un conjunto de datos sobre el cambio del nivel medio del mar a nivel mundial desde 1880. Utilizarás los datos para predecir el cambio del nivel del mar hasta el año 2050.
|
||||
<p spaces-before="0">
|
||||
Analizará un conjunto de datos sobre el cambio del nivel medio del mar a nivel mundial desde 1880. Utilizarás los datos para predecir el cambio del nivel del mar hasta el año 2050.
|
||||
</p>
|
||||
|
||||
Utiliza los datos para completar las siguientes tareas:
|
||||
<p spaces-before="0">
|
||||
Utiliza los datos para completar las siguientes tareas:
|
||||
</p>
|
||||
|
||||
- Utiliza Pandas para importar los datos de `epa-sea-level.csv`.
|
||||
- Usa matplotlib para crear un diagrama de dispersión usando la columna "Year" como el eje x y la columna "CSIRO Adjusted Sea Level" como el eje y.
|
||||
- Usa la función `linregress` de `scipy.stats` para obtener la pendiente e intersección con el eje y de la línea de mejor encaje. Dibuja la línea de mejor encaje sobre el diagrama de dispersión. Haz que la línea pase por el año 2050 para predecir el aumento del nivel del mar en ese año.
|
||||
- Traza una nueva línea de mejor encaje utilizando datos del año 2000 hasta el año más reciente del conjunto de datos. Haz que la línea pase también por el año 2050 para predecir la subida del nivel del mar en 2050 si el ritmo de subida continúa como desde el año 2000.
|
||||
- La etiqueta del eje x debe ser "Year", la etiqueta del eje y debe ser "Sea Level (inches)", y el título debe ser "Rise in Sea Level".
|
||||
<ul>
|
||||
<li>
|
||||
Utiliza Pandas para importar los datos de <code>epa-sea-level.csv</code>.
|
||||
</li>
|
||||
<li>
|
||||
Utilice matplotlib para crear un gráfico de dispersión utilizando la columna <code>Year</code> como eje x y la columna <code>CSIRO Adjusted Sea Level</code> como eje y.
|
||||
</li>
|
||||
<li>
|
||||
Usa la función <code>linregress</code> de <code>scipy.stats</code> para obtener la pendiente e intersección con el eje y de la línea de mejor encaje. Dibuja la línea de mejor encaje sobre el diagrama de dispersión. Haz que la línea pase por el año 2050 para predecir el aumento del nivel del mar en ese año.
|
||||
</li>
|
||||
<li>
|
||||
Traza una nueva línea de mejor encaje utilizando datos del año 2000 hasta el año más reciente del conjunto de datos. Haz que la línea pase también por el año 2050 para predecir la subida del nivel del mar en 2050 si el ritmo de subida continúa como desde el año 2000.
|
||||
</li>
|
||||
<li>
|
||||
La etiqueta x debe ser <code>Year</code>, la etiqueta y debe ser <code>Sea Level (pulgadas)</code> y el título debe ser <code>Rise in Sea Level</code>.
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
Las pruebas unitarias están escritas para en `test_module.py`.
|
||||
<p spaces-before="0">
|
||||
Las pruebas unitarias están escritas para en <code>test_module.py</code>.
|
||||
</p>
|
||||
|
||||
El boilerplate también incluye los comandos para guardar y devolver la imagen.
|
||||
<p spaces-before="0">
|
||||
El boilerplate también incluye los comandos para guardar y devolver la imagen.
|
||||
</p>
|
||||
|
||||
## Desarrollo
|
||||
<h2 spaces-before="0">
|
||||
Desarrollo
|
||||
</h2>
|
||||
|
||||
Para el desarrollo, puedes utilizar `main.py` para probar tus funciones. Haz clic en el botón "run" y se ejecutará `main.py`.
|
||||
<p spaces-before="0">
|
||||
Para el desarrollo, puedes utilizar <code>main.py</code> para probar tus funciones. Haz clic en el botón "run" y se ejecutará <code>main.py</code>.
|
||||
</p>
|
||||
|
||||
## Pruebas
|
||||
<h2 spaces-before="0">
|
||||
Pruebas
|
||||
</h2>
|
||||
|
||||
Importamos las pruebas de `test_module.py` a `main.py` para tu conveniencia. Las pruebas se ejecutarán automáticamente cada vez que pulses el botón "run".
|
||||
<p spaces-before="0">
|
||||
Importamos las pruebas de <code>test_module.py</code> a <code>main.py</code> para tu conveniencia. Las pruebas se ejecutarán automáticamente cada vez que pulses el botón "run".
|
||||
</p>
|
||||
|
||||
## Envío
|
||||
<h2 spaces-before="0">
|
||||
Envío
|
||||
</h2>
|
||||
|
||||
Copia el enlace de tu proyecto y envíalo a freeCodeCamp.
|
||||
<p spaces-before="0">
|
||||
Copia el enlace de tu proyecto y envíalo a freeCodeCamp.
|
||||
</p>
|
||||
|
||||
## Fuente de datos
|
||||
[Global Average Absolute Sea Level Change](https://datahub.io/core/sea-level-rise), 1880-2014 de la Agencia de Protección Ambiental de los Estados Unidos utilizando datos de CSIRO, 2015; NOAA, 2015.
|
||||
<h2 spaces-before="0">
|
||||
Fuente de datos
|
||||
</h2>
|
||||
|
||||
<p spaces-before="0">
|
||||
|
||||
|
||||
<a href="https://datahub.io/core/sea-level-rise" target="_blank" rel="noopener noreferrer nofollow">Global Average Absolute Sea Level Change</a>, 1880-2014 de la Agencia de Protección Ambiental de los Estados Unidos utilizando datos de CSIRO, 2015; NOAA, 2015.
|
||||
</p>
|
||||
|
||||
|
||||
# --hints--
|
||||
<h1 spaces-before="0">
|
||||
--hints--
|
||||
</h1>
|
||||
|
||||
Debería pasar todas las pruebas de Python.
|
||||
<p spaces-before="0">
|
||||
Debería pasar todas las pruebas de Python.
|
||||
</p>
|
||||
|
||||
```js
|
||||
<pre><code class="js">
|
||||
</code></pre>
|
||||
|
||||
```
|
||||
<h1 spaces-before="0">
|
||||
--solutions--
|
||||
</h1>
|
||||
|
||||
# --solutions--
|
||||
|
||||
```py
|
||||
# Python challenges don't need solutions,
|
||||
<pre><code class="py"> # Python challenges don't need solutions,
|
||||
# because they would need to be tested against a full working project.
|
||||
# Please check our contributing guidelines to learn more.
|
||||
```
|
||||
</code></pre>
|
||||
|
||||
+3
-3
@@ -8,12 +8,12 @@ dashedName: anonymous-message-board
|
||||
|
||||
# --description--
|
||||
|
||||
Construye una aplicación full stack de JavaScript que sea funcionalmente similar a esta: <https://anonymous-message-board.freecodecamp.rocks/>.
|
||||
Construye una aplicación full stack JavaScript similar a este: <a href="https://anonymous-message-board.freecodecamp.rocks/" target="_blank" rel="noopener noreferrer nofollow">https://anonymous-message-board.freecodecamp.rocks/</a>.
|
||||
|
||||
Trabajar en este proyecto implicará escribir tu código utilizando uno de los siguientes métodos:
|
||||
|
||||
- Clona [este repositorio de GitHub](https://github.com/freeCodeCamp/boilerplate-project-messageboard/) y completa tu proyecto localmente.
|
||||
- Usa [nuestro proyecto inicial de Replit](https://replit.com/github/freeCodeCamp/boilerplate-project-messageboard) para completar tu proyecto.
|
||||
- Clona <a href="https://github.com/freeCodeCamp/boilerplate-project-messageboard/" target="_blank" rel="noopener noreferrer nofollow">este repositorio GitHub</a> y completa el proyecto localmente.
|
||||
- Usa <a href="https://replit.com/github/freeCodeCamp/boilerplate-project-messageboard" target="_blank" rel="noopener noreferrer nofollow">nuestra plantilla en Replit</a> para completar tu proyecto.
|
||||
- Utiliza un constructor de sitios de tu elección para completar el proyecto. Asegúrate de incorporar todos los archivos de nuestro repositorio GitHub.
|
||||
|
||||
Cuando hayas terminado, asegúrate de que un demo funcional de tu proyecto esté alojado en algún lugar público. Luego, envía la URL en el campo `Solution Link`. Opcionalmente, también envía un enlace al código fuente de tu proyecto en el campo `GitHub Link`.
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
---
|
||||
id: a3f503de51cf954ede28891d
|
||||
title: Encuentra la diferencia simétrica
|
||||
challengeType: 5
|
||||
challengeType: 1
|
||||
forumTopicId: 301611
|
||||
dashedName: find-the-symmetric-difference
|
||||
---
|
||||
@@ -54,7 +54,7 @@ assert.sameMembers(sym([1, 2, 3], [5, 2, 1, 4, 5]), [3, 4, 5]);
|
||||
assert.equal(sym([1, 2, 3], [5, 2, 1, 4, 5]).length, 3);
|
||||
```
|
||||
|
||||
`sym([1, 2, 5], [2, 3, 5], [3, 4, 5])` debería retornar `[1, 4, 5]`
|
||||
`sym([1, 2, 5], [2, 3, 5], [3, 4, 5])` debería retornar `[1, 4, 5]`.
|
||||
|
||||
```js
|
||||
assert.sameMembers(sym([1, 2, 5], [2, 3, 5], [3, 4, 5]), [1, 4, 5]);
|
||||
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
---
|
||||
id: 61abc7ebf3029b56226de5b6
|
||||
title: Implementar la búsqueda binaria
|
||||
challengeType: 1
|
||||
forumTopicId: 487618
|
||||
dashedName: implement-binary-search
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
La búsqueda binaria es un algoritmo de eficiencia **O(log(n))** para la busqueda de elementos en un arreglo ordenado. Funciona de la siguiente manera:
|
||||
|
||||
1. Encuentra el valor (`value`) intermedio de un arreglo ordenado. Si este valor es igual al valor que estamos buscando (`value == target`) return (¡Lo encontramos!).
|
||||
1. Si el valor intermedio es menor del valor que estamos buscando (`value < target`), repetiremos el paso uno en la mitad más chica de nuestro arreglo.
|
||||
1. Si el valor intermedio es menor del valor que estamos buscando (`value > target`), repetiremos el paso uno en la mitad más chica de nuestro arreglo.
|
||||
|
||||
Como lo habrás notado, estamos dividiendo al mitad a un arreglo sucesivamente, por lo que tendremos una eficiencia de log(n). Para este desafío, queremos que muestres tu trabajo: cómo llegaste al valor objetivo... ¡el camino que tomaste!
|
||||
|
||||
# --instructions--
|
||||
|
||||
Escribe la función `binarySearch` (búsqueda binaria) que implemente el algoritmo de búsqueda binaria en un arreglo, devolviendo el camino tomado (cada valor intermedio comparado) para encontrar el valor en un arreglo.
|
||||
|
||||
La función recibe como parametros un arreglo de números enteros y el número que queremos buscar. Devuleve un arreglo (ordenado) que contiene todos los valores intermedios del arreglo original descartados antes de encontrar el valor deseado. El valor que estamos buscando deberá ser el ultima elemento de nuestro arreglo retornado. Si no encontramos el valor estabamos buscando, devolvemos la cadena `Value Not Found` (Valor no encontrado).
|
||||
|
||||
Por ejemplo `binarySearch([1,2,3,4,5,6,7], 5)` deberá retornar `[4,6,5]`.
|
||||
|
||||
Para este reto, cuando dividas a la mitad deberás de usar la función `Math.floor()` Ejemplo `Math.floor(x/2)`. Proporcionando un camino consistente y estable.
|
||||
|
||||
**Nota:** el siguiente arreglo será usado en las pruebas:
|
||||
|
||||
```js
|
||||
const testArray = [
|
||||
0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
|
||||
23, 49, 70
|
||||
];
|
||||
```
|
||||
|
||||
# --hints--
|
||||
|
||||
`binarySearch` deberá ser una función.
|
||||
|
||||
```js
|
||||
assert(typeof binarySearch == 'function');
|
||||
```
|
||||
|
||||
`binarySearch(testArray, 0)` deberá retornar `[13, 5, 2, 0]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(binarySearch(_testArray, 0), [13, 5, 2, 0]);
|
||||
```
|
||||
|
||||
`binarySearch(testArray, 1)` deberá retornar `[13, 5, 2, 0, 1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(binarySearch(_testArray, 1), [13, 5, 2, 0, 1]);
|
||||
```
|
||||
|
||||
|
||||
`binarySearch(testArray, 2)` deberá retornar `[13, 5, 2]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(binarySearch(_testArray, 2), [13, 5, 2]);
|
||||
```
|
||||
|
||||
`binarySearch(testArray, 6)` deberá retornar `Value Not Found`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(binarySearch(_testArray, 6), 'Value Not Found');
|
||||
```
|
||||
|
||||
`binarySearch(testArray, 11)` deberá retornar `[13, 5, 10, 11]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(binarySearch(_testArray, 11), [13, 5, 10, 11])
|
||||
```
|
||||
|
||||
`binarySearch(testArray, 13)` deberá retornar `[13]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(binarySearch(_testArray, 13), [13]);
|
||||
```
|
||||
|
||||
`binarySearch(testArray, 70)` deberá retornar `[13, 19, 22, 49, 70]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(binarySearch(_testArray, 70), [13, 19, 22, 49, 70]);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
|
||||
```js
|
||||
const _testArray = [
|
||||
0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
|
||||
23, 49, 70
|
||||
];
|
||||
```
|
||||
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function binarySearch(searchList, value) {
|
||||
let arrayPath = [];
|
||||
return arrayPath;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
let binarySearch = (searchList, value) => {
|
||||
let arrayPath = [];
|
||||
|
||||
// set initial L - M - R
|
||||
let left = 0;
|
||||
let right = searchList.length - 1;
|
||||
let middle = Math.floor(right / 2);
|
||||
|
||||
// if first comparison finds value
|
||||
if (searchList[middle] == value) {
|
||||
arrayPath.push(searchList[middle]);
|
||||
return arrayPath;
|
||||
}
|
||||
|
||||
while (searchList[middle] !== value) {
|
||||
// add to output array
|
||||
arrayPath.push(searchList[middle]);
|
||||
|
||||
// not found
|
||||
if (right < left) {
|
||||
return 'Value Not Found';
|
||||
}
|
||||
// value is in left or right portion of array
|
||||
// update L - M - R
|
||||
if (searchList[middle] > value) {
|
||||
right = middle - 1;
|
||||
middle = left + Math.floor((right - left) / 2);
|
||||
} else {
|
||||
left = middle + 1;
|
||||
middle = left + Math.floor((right - left) / 2);
|
||||
}
|
||||
|
||||
// if found update output array and exit
|
||||
if (searchList[middle] == value) {
|
||||
arrayPath.push(searchList[middle]);
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
return arrayPath;
|
||||
};
|
||||
```
|
||||
+11
-13
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d825c367417b2b2512c8f
|
||||
title: Implement Merge Sort
|
||||
title: Implementar ordenamiento por mezcla (merge sort)
|
||||
challengeType: 1
|
||||
forumTopicId: 301614
|
||||
dashedName: implement-merge-sort
|
||||
@@ -8,27 +8,27 @@ dashedName: implement-merge-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Another common intermediate sorting algorithm is merge sort. Like quick sort, merge sort also uses a divide-and-conquer, recursive methodology to sort an array. It takes advantage of the fact that it is relatively easy to sort two arrays as long as each is sorted in the first place. But we'll start with only one array as input, so how do we get to two sorted arrays from that? Well, we can recursively divide the original input in two until we reach the base case of an array with one item. A single-item array is naturally sorted, so then we can start combining. This combination will unwind the recursive calls that split the original array, eventually producing a final sorted array of all the elements. The steps of merge sort, then, are:
|
||||
El ordenamiento por mezcla (merge sort) es otro algoritmo intermedio de ordenamiento. Así como el ordenamiento rápido (quick sort), el ordenamiento por mezcla (merge sort) usa el enfoque divide y conquistaras con recurisidad para ordenar un arreglo. Este algoritmo aprovecha que es relativamente fácil juntar dos arreglos en uno solo de manera ordenada, siempre y cuando ambos arreglos esten ordenadps desde un inicio. Pero si solo empezamos con único arreglo desordenado ¿Cómo conseguimos dos arreglos ordenados? Bueno podemos dividir recursivamente nuestro arreglo de entrada, hasta alcanzar un caso base de un arreglo con un solo elemento. Un arreglo de un solo elemento naturalmente está ordenado, entoces podemos empezar a combinar. Esta combinación resolverá las llamadas recursivas que separarón el arreglo, finalemente creando un arreglo ordenado con todos los elementos. Los pasos del ordenamiento por mezcla (merge sort) son:
|
||||
|
||||
**1)** Recursively split the input array in half until a sub-array with only one element is produced.
|
||||
**1)** Separa recursivamente el arreglo de entrada a la mitad hasta que un subarreglo con un solo elemento es producido.
|
||||
|
||||
**2)** Merge each sorted sub-array together to produce the final sorted array.
|
||||
**2)**Mezcla cada subarreglo ordenado para que al final produzcas un solo arreglo ordenado.
|
||||
|
||||
Merge sort is an efficient sorting method, with time complexity of *O(nlog(n))*. This algorithm is popular because it is performant and relatively easy to implement.
|
||||
El ordenamiento por mezcla (merge sort) es un metodo eficiente para ordenar, con complejidad algoritmica de *O(nlog(n))*. Este algotimo es muy popular, debido a su rendimiento y es relativamente sencillo de implementar.
|
||||
|
||||
As an aside, this will be the last sorting algorithm we cover here. However, later in the section on tree data structures we will describe heap sort, another efficient sorting method that requires a binary heap in its implementation.
|
||||
Por otro lado esté será el último algoritmo de ordenamiento que cubriremos aquí. Aunque posteriormente en la sección sobre estructura de datos de árboles describiremos el ordenamiento por montículos (heap sort) y otros métodos de ordenamiento más eficientes que requieren un montículo binario (binary heap) para su implementación.
|
||||
|
||||
**Instructions:** Write a function `mergeSort` which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest. A good way to implement this is to write one function, for instance `merge`, which is responsible for merging two sorted arrays, and another function, for instance `mergeSort`, which is responsible for the recursion that produces single-item arrays to feed into merge. Good luck!
|
||||
**Instrucciones:**Escribe una función `mergeSort`(ordenamiento por mezcla) que toma un arreglo de enterós como entrada y regresa un arreglo de esos enteros de manera ordenada del más pequeño al más grande. Una bunea manera de implementarlo es escrbiendo una función llamada `merge` (mezcla), la cuál es responsable de mezclar dos arreglos ordenados y otra función llamada `mergeSort`(ordenamiento por mezlca), la cuál usando recursividad produciendo arreglos de un solo elemento, con los que alimentaremos a la función merge (mezcla). ¡Buena suerte!
|
||||
|
||||
# --hints--
|
||||
|
||||
`mergeSort` should be a function.
|
||||
`mergeSort` debe ser una función.
|
||||
|
||||
```js
|
||||
assert(typeof mergeSort == 'function');
|
||||
```
|
||||
|
||||
`mergeSort` should return a sorted array (least to greatest).
|
||||
`mergeSort` Debería retornar un arreglo ordenado (menor a mayor).
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -56,7 +56,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`mergeSort` should return an array that is unchanged except for order.
|
||||
`mergeSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])`debe retornar un arreglo sin cambios excepto por el orden.
|
||||
|
||||
```js
|
||||
assert.sameMembers(
|
||||
@@ -83,7 +83,7 @@ assert.sameMembers(
|
||||
);
|
||||
```
|
||||
|
||||
`mergeSort` should not use the built-in `.sort()` method.
|
||||
`mergeSort`no debe de usar el método incorporada (built-in)`.sort()`.
|
||||
|
||||
```js
|
||||
assert(isBuiltInSortUsed());
|
||||
@@ -117,8 +117,6 @@ function mergeSort(array) {
|
||||
return array;
|
||||
// Only change code above this line
|
||||
}
|
||||
|
||||
mergeSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
+8
-8
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d825a367417b2b2512c89
|
||||
title: Implement Quick Sort
|
||||
title: Implementar Ordenación Rápido
|
||||
challengeType: 1
|
||||
forumTopicId: 301615
|
||||
dashedName: implement-quick-sort
|
||||
@@ -8,21 +8,21 @@ dashedName: implement-quick-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Here we will move on to an intermediate sorting algorithm: quick sort. Quick sort is an efficient, recursive divide-and-conquer approach to sorting an array. In this method, a pivot value is chosen in the original array. The array is then partitioned into two subarrays of values less than and greater than the pivot value. We then combine the result of recursively calling the quick sort algorithm on both sub-arrays. This continues until the base case of an empty or single-item array is reached, which we return. The unwinding of the recursive calls return us the sorted array.
|
||||
Aquí pasaremos a un algoritmo de ordenación intermedio: la ordenación rápida. La ordenación rápida es un método eficiente y recursivo de dividir y conquistar para ordenar un arreglo. En este método, es elegido un valor pivote en el arreglo original. A continuación, el arreglo se divide en dos submatrices de valores menores y mayores que el valor pivote. A continuación, combinamos el resultado de llamar recursivamente al algoritmo de ordenación rápida en ambos subarreglos. Esto continúa hasta llegar al caso base de un arreglo vacío o de un solo elemento, que devolvemos. El desenvolvimiento de las llamadas recursivas nos devuelve el arreglo ordenado.
|
||||
|
||||
Quick sort is a very efficient sorting method, providing *O(nlog(n))* performance on average. It is also relatively easy to implement. These attributes make it a popular and useful sorting method.
|
||||
La ordenación rápida es un método de ordenación muy eficiente, que proporciona un rendimiento *O(nlog(n))* de media. También es relativamente fácil de implementar. Estos atributos lo convierten en un método de ordenación popular y útil.
|
||||
|
||||
**Instructions:** Write a function `quickSort` which takes an array of integers as input and returns an array of these integers in sorted order from least to greatest. While the choice of the pivot value is important, any pivot will do for our purposes here. For simplicity, the first or last element could be used.
|
||||
**Instrucciones:** Escribe una función `quickSort` que tomará un arreglo de enteros y retornará un arreglo con estos números, ordenados de menor a mayor. Si bien la elección del valor del pivote es importante, cualquier pivote lo será para nuestros propósitos. Por simplicidad, el primero o el último elemento podría ser utilizado.
|
||||
|
||||
# --hints--
|
||||
|
||||
`quickSort` should be a function.
|
||||
`quickSort` debería ser una función.
|
||||
|
||||
```js
|
||||
assert(typeof quickSort == 'function');
|
||||
```
|
||||
|
||||
`quickSort` should return a sorted array (least to greatest).
|
||||
`quickSort` deberia que retornar un arreglo ordenado (menor a mayor).
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -50,7 +50,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`quickSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])` should return an array that is unchanged except for order.
|
||||
`quickSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92])` debe retornar un arreglo sin cambios excepto por el orden.
|
||||
|
||||
```js
|
||||
assert.sameMembers(
|
||||
@@ -77,7 +77,7 @@ assert.sameMembers(
|
||||
);
|
||||
```
|
||||
|
||||
`quickSort` should not use the built-in `.sort()` method.
|
||||
`quickSort` no debe que utilizar el método incorporado `.sort()`.
|
||||
|
||||
```js
|
||||
assert(isBuiltInSortUsed());
|
||||
|
||||
+9
-9
@@ -1,18 +1,18 @@
|
||||
---
|
||||
id: a56138aff60341a09ed6c480
|
||||
title: Inventory Update
|
||||
challengeType: 5
|
||||
title: Actualización de Inventario
|
||||
challengeType: 1
|
||||
forumTopicId: 16019
|
||||
dashedName: inventory-update
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Compare and update the inventory stored in a 2D array against a second 2D array of a fresh delivery. Update the current existing inventory item quantities (in `arr1`). If an item cannot be found, add the new item and quantity into the inventory array. The returned inventory array should be in alphabetical order by item.
|
||||
Compara y actualiza el inventario en un arreglo de 2 dimensiones contra un segundo arreglo de 2 dimensiones de una entrega nueva. Actualizar las cantidades actuales del artículo del inventario (en `arr1`). Si un artículo no se puede encontrar, agregue el nuevo artículo con su cantidad al arreglo de inventario. El arreglo de inventario devuelto deberá estar en orden alfabético por elemento.
|
||||
|
||||
# --hints--
|
||||
|
||||
The function `updateInventory` should return an array.
|
||||
La función `updateInventory` debe devolver un arreglo.
|
||||
|
||||
```js
|
||||
assert.isArray(
|
||||
@@ -33,7 +33,7 @@ assert.isArray(
|
||||
);
|
||||
```
|
||||
|
||||
`updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])` should return an array with a length of 6.
|
||||
Traducciónes: update inventory: actualización del inventario. Bowling ball: bola de boliche. Dirty sock: calcetín sucio. Hair pin: pasador de cabello. Microphone: micrófono. Half-eaten apple: manzana media comida. Toothpaste: pasta de dientes. `updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])` debería devolver un arreglo con una longitud de 6.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@@ -55,7 +55,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])` should return `[[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]`.
|
||||
`updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])` debería devolver `[[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@@ -84,7 +84,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [])` should return `[[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]]`.
|
||||
`updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [])` debería regresar `[[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@@ -106,7 +106,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])` should return `[[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]]`.
|
||||
`updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])` debería regresar `[[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@@ -128,7 +128,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]])` should return `[[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]]`.
|
||||
`updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]])` debería regresar `[[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
||||
+14
-14
@@ -1,74 +1,74 @@
|
||||
---
|
||||
id: a7bf700cd123b9a54eef01d5
|
||||
title: No Repeats Please
|
||||
challengeType: 5
|
||||
title: No repetir por favor
|
||||
challengeType: 1
|
||||
forumTopicId: 16037
|
||||
dashedName: no-repeats-please
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Return the number of total permutations of the provided string that don't have repeated consecutive letters. Assume that all characters in the provided string are each unique.
|
||||
Devuele el numero total de permutaciones posibles de una cadena (string) que no tiene soa letras iguales consecutivas. Supongamos que todos los caracteres de la cadena proporcionada son únicos de cada una.
|
||||
|
||||
For example, `aab` should return 2 because it has 6 total permutations (`aab`, `aab`, `aba`, `aba`, `baa`, `baa`), but only 2 of them (`aba` and `aba`) don't have the same letter (in this case `a`) repeating.
|
||||
Por ejemplo `aab` deberá retornar 2 por qué tiene 6 permutaciones (`aab`, `aab`, `aba`, `aba`, `baa`, `baa`), pero solo 2 (`aba` y `aba`) no tiene la misma letra repetida consecutivamente (en este caso `a`).
|
||||
|
||||
# --hints--
|
||||
|
||||
`permAlone("aab")` should return a number.
|
||||
`permAlone("aab")` deberá retornar un número.
|
||||
|
||||
```js
|
||||
assert.isNumber(permAlone('aab'));
|
||||
```
|
||||
|
||||
`permAlone("aab")` should return 2.
|
||||
`permAlone("aab")` deberá retornar 2.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permAlone('aab'), 2);
|
||||
```
|
||||
|
||||
`permAlone("aaa")` should return 0.
|
||||
`permAlone("aaa")` deberá retornar 0.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permAlone('aaa'), 0);
|
||||
```
|
||||
|
||||
`permAlone("aabb")` should return 8.
|
||||
`permAlone("aabb")` deberá retornar 8.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permAlone('aabb'), 8);
|
||||
```
|
||||
|
||||
`permAlone("abcdefa")` should return 3600.
|
||||
`permAlone("abcdefa")` deberá retornar 3600.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permAlone('abcdefa'), 3600);
|
||||
```
|
||||
|
||||
`permAlone("abfdefa")` should return 2640.
|
||||
`permAlone("abfdefa")` deberá retornar 2640.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permAlone('abfdefa'), 2640);
|
||||
```
|
||||
|
||||
`permAlone("zzzzzzzz")` should return 0.
|
||||
`permAlone("zzzzzzzz")` deberá retornar 0.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permAlone('zzzzzzzz'), 0);
|
||||
```
|
||||
|
||||
`permAlone("a")` should return 1.
|
||||
`permAlone("a")` deberá retornar 1.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permAlone('a'), 1);
|
||||
```
|
||||
|
||||
`permAlone("aaab")` should return 0.
|
||||
`permAlone("aaab")` deberá retornar 0.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permAlone('aaab'), 0);
|
||||
```
|
||||
|
||||
`permAlone("aaabb")` should return 12.
|
||||
`permAlone("aaabb")` deberá retornar 12.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permAlone('aaabb'), 12);
|
||||
|
||||
@@ -1,64 +1,64 @@
|
||||
---
|
||||
id: a3f503de51cfab748ff001aa
|
||||
title: Pairwise
|
||||
challengeType: 5
|
||||
title: Emparejamiento inteligente
|
||||
challengeType: 1
|
||||
forumTopicId: 301617
|
||||
dashedName: pairwise
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given an array `arr`, find element pairs whose sum equal the second argument `arg` and return the sum of their indices.
|
||||
Dado un arreglo `arr`, encuentra pares de elementos que sumen igual al segundo argumento `arg` y regresa la suma de sus índices.
|
||||
|
||||
You may use multiple pairs that have the same numeric elements but different indices. Each pair should use the lowest possible available indices. Once an element has been used it cannot be reused to pair with another element. For instance, `pairwise([1, 1, 2], 3)` creates a pair `[2, 1]` using the 1 at index 0 rather than the 1 at index 1, because 0+2 < 1+2.
|
||||
Podrías utilizar múltiples pares que tengan los mismo elementos numéricos, pero con diferentes índices. Cada par debe usar los índices más bajos posibles. Una vez un elemento se ha utilizado, no se puede emprejar otra vez con otro elemento. Por ejemplo `pairwise([1, 1, 2], 3)` crea un par `[2, 1]` usando el 1 del índice 0, en vez del 1 de el índice 1, por qué la suma de los indíces 0 + 2 < (es menor que) 1+2.
|
||||
|
||||
For example `pairwise([7, 9, 11, 13, 15], 20)` returns `6`. The pairs that sum to 20 are `[7, 13]` and `[9, 11]`. We can then write out the array with their indices and values.
|
||||
Por ejemplo `pairwise([7, 9, 11, 13, 15], 20)` devuelve `6`. Los pares que suman 20 son `[7, 13]` y `[9, 11]`. Para llegar a la soulción podríamos escribir el arreglo con sus índices y valores.
|
||||
|
||||
<div style='margin-left: 2em;'>
|
||||
|
||||
| Index | 0 | 1 | 2 | 3 | 4 |
|
||||
| Índice | 0 | 1 | 2 | 3 | 4 |
|
||||
| ----- | - | - | -- | -- | -- |
|
||||
| Value | 7 | 9 | 11 | 13 | 15 |
|
||||
| Valor | 7 | 9 | 11 | 13 | 15
|
||||
|
||||
</div>
|
||||
|
||||
Below we'll take their corresponding indices and add them.
|
||||
A continuación tomaremos los índices correspondientes a los pares y los sumamos.
|
||||
|
||||
<div style='margin-left: 2em;'>
|
||||
|
||||
7 + 13 = 20 → Indices 0 + 3 = 3
|
||||
9 + 11 = 20 → Indices 1 + 2 = 3
|
||||
3 + 3 = 6 → Return `6`
|
||||
9 + 11 = 20 → Índices 1 + 2 = 3
|
||||
3 + 3 = 6 → Devuelve `6`
|
||||
|
||||
</div>
|
||||
|
||||
# --hints--
|
||||
|
||||
`pairwise([1, 4, 2, 3, 0, 5], 7)` should return 11.
|
||||
`pairwise([1, 4, 2, 3, 0, 5], 7)` debe devolver 11.
|
||||
|
||||
```js
|
||||
assert.deepEqual(pairwise([1, 4, 2, 3, 0, 5], 7), 11);
|
||||
```
|
||||
|
||||
`pairwise([1, 3, 2, 4], 4)` should return 1.
|
||||
`pairwise([1, 3, 2, 4], 4)` debe devolver 1.
|
||||
|
||||
```js
|
||||
assert.deepEqual(pairwise([1, 3, 2, 4], 4), 1);
|
||||
```
|
||||
|
||||
`pairwise([1, 1, 1], 2)` should return 1.
|
||||
`pairwise([1, 1, 1], 2)` debe devolver 1.
|
||||
|
||||
```js
|
||||
assert.deepEqual(pairwise([1, 1, 1], 2), 1);
|
||||
```
|
||||
|
||||
`pairwise([0, 0, 0, 0, 1, 1], 1)` should return 10.
|
||||
`pairwise([0, 0, 0, 0, 1, 1], 1)` debe devolver 10.
|
||||
|
||||
```js
|
||||
assert.deepEqual(pairwise([0, 0, 0, 0, 1, 1], 1), 10);
|
||||
```
|
||||
|
||||
`pairwise([], 100)` should return 0.
|
||||
`pairwise([], 100)` debería devolver 0.
|
||||
|
||||
```js
|
||||
assert.deepEqual(pairwise([], 100), 0);
|
||||
|
||||
+12
-12
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8257367417b2b2512c7b
|
||||
title: Add a New Element to a Binary Search Tree
|
||||
title: Añadir un nuevo elemento a un Árbol Binario de Búsqueda
|
||||
challengeType: 1
|
||||
forumTopicId: 301618
|
||||
dashedName: add-a-new-element-to-a-binary-search-tree
|
||||
@@ -8,27 +8,27 @@ dashedName: add-a-new-element-to-a-binary-search-tree
|
||||
|
||||
# --description--
|
||||
|
||||
This series of challenges will introduce the tree data structure. Trees are an important and versatile data structure in computer science. Of course, their name comes from the fact that when visualized they look much like the trees we are familiar with in the natural world. A tree data structure begins with one node, typically referred to as the root, and from here branches out to additional nodes, each of which may have more child nodes, and so on and so forth. The data structure is usually visualized with the root node at the top; you can think of it as a natural tree flipped upside down.
|
||||
Esta serie de desafíos introducen la estructura de datos de árbol. Los árboles son una estructura de datos importante y versátil en las ciencias de la computación. Por supuesto, el nombre proviene del hecho que cuando las visualizamos se parecen mucho a los árboles con los que estamos familiarizados en el mundo natural. Una estructura de datos de árbol inicia con un nodo, comúnmente llamado raíz, y desde aquí se ramifica hacia nodos adicionales, cada uno de los cuales podría tener más nodos hijos, y así sucesivamente. La estructura de datos es usualmente visualizada con el nodo raíz en la parte superior; tu puedes pensar en él como un árbol natural invertido hacia abajo.
|
||||
|
||||
First, let's describe some common terminology we will encounter with trees. The root node is the top of the tree. Data points in the tree are called nodes. Nodes with branches leading to other nodes are referred to as the parent of the node the branch leads to (the child). Other more complicated familial terms apply as you might expect. A subtree refers to all the descendants of a particular node, branches may be referred to as edges, and leaf nodes are nodes at the end of the tree that have no children. Finally, note that trees are inherently recursive data structures. That is, any children of a node are parents of their own subtree, and so on. The recursive nature of trees is important to understand when designing algorithms for common tree operations.
|
||||
Primero, vamos a describir alguna terminología común que encontraremos con los árboles. El nodo raíz es la parte superior del árbol. Los puntos de datos en el árbol son llamados nodos. Los nodos con ramas que unen a otros nodos son llamados como el padre del nodo al que la rama conduce ( el hijo). Otros términos familiares más complicados son aplicados como podría esperarse. Un subárbol se refiere a todos los descendientes de un nodo en particular, las ramas pueden ser llamadas aristas, y los nodos hojas son los nodos al final del árbol que no tienen hijos. Finalmente, tenga en cuenta que los árboles son inherentemente estructuras de datos recursivas. Esto quiere decir, que todos los hijos de un nodo son padres de su propio subárbol y así sucesivamente. Es importante entender la naturaleza recursiva de los árboles cuando diseñamos algoritmos para las operaciones comunes en árboles.
|
||||
|
||||
To begin, we will discuss a particular type of a tree, the binary tree. In fact, we will actually discuss a particular binary tree, a binary search tree. Let's describe what this means. While the tree data structure can have any number of branches at a single node, a binary tree can only have two branches for every node. Furthermore, a binary search tree is ordered with respect to the child subtrees, such that the value of each node in the left subtree is less than or equal to the value of the parent node, and the value of each node in the right subtree is greater than or equal to the value of the parent node. It's very helpful to visualize this relationship in order to understand it better:
|
||||
Para comenzar, discutiremos un tipo de árbol en particular, el árbol binario. De hecho, en realidad discutiremos un árbol binario en particular, un árbol binario de búsqueda. Describiremos lo que esto significa. Mientras que la estructura de datos de árbol puede tener cualquier número de ramas en un solo nodo, un árbol binario solamente puede tener dos ramas para cada nodo. Además, un árbol binario de búsqueda se ordena respecto a los subárboles hijos, el valor de cada nodo en el subárbol izquierdo es menor o igual que el valor del nodo padre, y el valor de cada nodo en el subárbol derecho es mayor o igual que el valor del nodo padre. Es muy útil visualizar esta relación de orden para entenderla mejor:
|
||||
|
||||
<div style='width: 100%; display: flex; justify-content: center; align-items: center;'><img style='width: 100%; max-width: 350px; background-color: var(--gray-05);' src='https://user-images.githubusercontent.com/18563015/32136009-1e665d98-bbd6-11e7-9133-63184f9f9182.png'></div>
|
||||
|
||||
Now this ordered relationship is very easy to see. Note that every value to the left of 8, the root node, is less than 8, and every value to the right is greater than 8. Also notice that this relationship applies to each of the subtrees as well. For example, the first left child is a subtree. 3 is the parent node, and it has exactly two child nodes — by the rules governing binary search trees, we know without even looking that the left child of this node (and any of its children) will be less than 3, and the right child (and any of its children) will be greater than 3 (but also less than the structure's root value), and so on.
|
||||
Ahora esta relación de orden es fácil de ver. Observa que cada valor a la izquierda de 8, el nodo raíz, es menor que 8, y cada valor a la derecha es mayor que 8. Además note que esta relación también es aplicada para cada de los subárboles. Por ejemplo, el primer hijo izquierdo es un subárbol. 3 es el nodo padre, y tiene exactamente dos nodos hijos - debido a las reglas de los árboles binarios de búsqueda, sabemos sin siquiera ver que el hijo izquierdo de este nodo ( y cualquiera de sus hijos) será menor que, y el hijo derecho(y cualquiera de sus hijos) será mayor que 3 (pero además menor que el valor de la raíz de la estructura).
|
||||
|
||||
Binary search trees are very common and useful data structures because they provide logarithmic time in the average case for several common operations such as lookup, insertion, and deletion.
|
||||
Los árboles binarios de búsqueda son estructuras de datos muy comunes y útiles porque proveen tiempo logarítmico en el caso promedio en varias operaciones comunes como la búsqueda, inserción y eliminación.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We'll start simple. We've defined the skeleton of a binary search tree structure here in addition to a function to create nodes for our tree. Observe that each node may have a left and right value. These will be assigned child subtrees if they exist. In our binary search tree, you will create a method to add new values to our binary search tree. The method should be called `add` and it should accept an integer value to add to the tree. Take care to maintain the invariant of a binary search tree: the value in each left child should be less than or equal to the parent value, and the value in each right child should be greater than or equal to the parent value. Here, let's make it so our tree cannot hold duplicate values. If we try to add a value that already exists, the method should return `null`. Otherwise, if the addition is successful, `undefined` should be returned.
|
||||
Iniciaremos de manera simple. Hemos definido el esqueleto de un árbol binario de búsqueda además de una función para la creación de nodos para nuestro árbol. Observa que cada nodo puede tener un valor izquierdo y derecho. A estos se le asignarán subárboles si existen. En nuestro árbol binario de búsqueda, crearás un método para añadir nuevos valores al árbol. El método deberá ser llamado `add` y deberá aceptar un valor entero para añadir al árbol. Ten cuidado de mantener el balance de un árbol de búsqueda binaria: el valor de cada hijo izquierdo debe ser menor o igual al valor del padre, y el valor de cada hijo derecho debe ser mayor o igual que el valor del padre. Aquí, haremos que nuestro árbol no pueda tener valores duplicados. Si intentamos añadir un valor que ya existe, el método bebe devolver `null`. De otra forma, si la inserción es exitosa, `undefined` debe ser devuelto.
|
||||
|
||||
**Hint:** trees are naturally recursive data structures!
|
||||
**Pista:** los árboles son naturalmente estructuras de datos recursivas!
|
||||
|
||||
# --hints--
|
||||
|
||||
The `BinarySearchTree` data structure should exist.
|
||||
Debe existir la estrucutura de datos `BinarySearchTree`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -42,7 +42,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The binary search tree should have a method called `add`.
|
||||
El árbol de búsqueda debe tener un método llamado `add`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -58,7 +58,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The add method should add elements according to the binary search tree rules.
|
||||
El método add debe añadir elementos de acuerdo a las reglas de los árboles binarios de búsqueda.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -87,7 +87,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Adding an element that already exists should return `null`.
|
||||
La inserción de un elemento que ya existe debe devolver `null`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+8
-8
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8252367417b2b2512c67
|
||||
title: Add Elements at a Specific Index in a Linked List
|
||||
title: Agregar un elemento a un índice específico en una lista enlazada
|
||||
challengeType: 1
|
||||
forumTopicId: 301619
|
||||
dashedName: add-elements-at-a-specific-index-in-a-linked-list
|
||||
@@ -8,15 +8,15 @@ dashedName: add-elements-at-a-specific-index-in-a-linked-list
|
||||
|
||||
# --description--
|
||||
|
||||
Let's create a addAt(index,element) method that adds an element at a given index. Just like how we remove elements at a given index, we need to keep track of the currentIndex as we traverse the linked list. When the currentIndex matches the given index, we would need to reassign the previous node's next property to reference the new added node. And the new node should reference the next node in the currentIndex. Returning to the conga line example, a new person wants to join the line, but he wants to join in the middle. You are in the middle of the line, so you take your hands off of the person ahead of you. The new person walks over and puts his hands on the person you once had hands on, and you now have your hands on the new person.
|
||||
Vamos a crear un método llamado addAt(index, element) que inserte un elemento en un índice dado. Tal y como eliminamos elementos en un índice dado, tenemos que mantener el valor del índice actual mientras atravesamos la lista enlazada. Cuando el índice actual coincida con el índice dado, neceesitaríamos reasignar la propiedad siguiente del nodo anterior para referenciar el nuevo nodo añadido. Y el nuevo nodo debe referenciar al índice actual como el nodo siguiente. Regresando al ejemplo de línea conga, una nueva persona quiere ingresar a la línea, pero quiere ingresar en el medio. Tu estás en el medio de la línea, entonces quitas tus manos de la persona enfrente de tí. La nueva persona camina y pone sus manos sobre la persona en la que antes tenías tus manos, y ahora tienes tus manos sobre la nueva persona.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create an `addAt(index,element)` method that adds an element at a given index. Return false if an element could not be added. **Note:** Remember to check if the given index is a negative or is longer than the length of the linked list.
|
||||
Crea un método `addAt(index,element)` que inserte un elemento en un índice dado. Devuelva false si un elemento no pudo ser insertado. **Nota:** recuerda verificar si el índice dado es negativo o es mayor que el largo de la lista enlazada.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your `addAt` method should reassign `head` to the new node when the given index is 0.
|
||||
Tu método `addAt` deberá reasignar `head` al nuevo nodo cuando el índice dado es 0.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -24,13 +24,13 @@ assert(
|
||||
var test = new LinkedList();
|
||||
test.add('cat');
|
||||
test.add('dog');
|
||||
test.addAt(0, 'cat');
|
||||
return test.head().element === 'cat';
|
||||
test.addAt(0, 'fish');
|
||||
return test.head().element === 'fish' && test.head().next.element === 'cat';
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
Your `addAt` method should increase the length of the linked list by one for each new node added to the linked list.
|
||||
Tu método `addAt` debe incrementar el largo de la lista enlazada en uno por cada nuevo nodo añadido en la lista enlazada.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -44,7 +44,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `addAt` method should return `false` if a node was unable to be added.
|
||||
Tu método `addAt` deberá devolver `false` si un nodo no pudo ser insertado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+10
-10
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8256367417b2b2512c77
|
||||
title: Adjacency List
|
||||
title: Lista de Adyacencia
|
||||
challengeType: 1
|
||||
forumTopicId: 301620
|
||||
dashedName: adjacency-list
|
||||
@@ -8,11 +8,11 @@ dashedName: adjacency-list
|
||||
|
||||
# --description--
|
||||
|
||||
Graphs can be represented in different ways. Here we describe one way, which is called an <dfn>adjacency list</dfn>. An adjacency list is essentially a bulleted list where the left side is the node and the right side lists all the other nodes it's connected to. Below is a representation of an adjacency list.
|
||||
Los gráficos pueden ser representados en diferentes formas. Aquí describimos una forma, llamada <dfn>lista de adyacencia</dfn>. Una lista de adyacencia es esencialmente una lista numerada donde el lado izquierdo es el nodo y el lado derecho lista todos los nodos a los que está conectada. A continuación se muestra una representación de una lista de adyacencia.
|
||||
|
||||
<blockquote>Node1: Node2, Node3<br>Node2: Node1<br>Node3: Node1</blockquote>
|
||||
|
||||
Above is an undirected graph because `Node1` is connected to `Node2` and `Node3`, and that information is consistent with the connections `Node2` and `Node3` show. An adjacency list for a directed graph would mean each row of the list shows direction. If the above was directed, then `Node2: Node1` would mean there the directed edge is pointing from `Node2` towards `Node1`. We can represent the undirected graph above as an adjacency list by putting it within a JavaScript object.
|
||||
El gráfico anterior descrito es uno no dirigido porque `Node1` está conectado al `Node2` y `Node3`, y esa información es consistente con las conexiones que muestran `Node2` y `Node3`. Una lista de adyacencia para un gráfico dirigido significaría que cada fila de la lista muestra una dirección. Si el gráfico anterior fuera dirigido, entonces `Node2: Node1` significaría que la dirección de la arista está apuntando desde `Node2` hacia `Node1`. Podemos representar el anterior gráfico no dirigido como una lista de adyacencia poniendolo en un objeto JavaScript.
|
||||
|
||||
```js
|
||||
var undirectedG = {
|
||||
@@ -22,7 +22,7 @@ var undirectedG = {
|
||||
};
|
||||
```
|
||||
|
||||
This can also be more simply represented as an array where the nodes just have numbers rather than string labels.
|
||||
Esta además puede ser respresentado más simple como una matriz donde los nodos solo tienen números en lugar de etiquetas de cadena.
|
||||
|
||||
```js
|
||||
var undirectedGArr = [
|
||||
@@ -34,17 +34,17 @@ var undirectedGArr = [
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a social network as an undirected graph with 4 nodes/people named `James`, `Jill`, `Jenny`, and `Jeff`. There are edges/relationships between James and Jeff, Jill and Jenny, and Jeff and Jenny.
|
||||
Crea una red social como un gráfico no dirigido con 4 nodos/personar llamados `James`, `Jill`, `Jenny`, y `Jeff`. Hay aristas/relaciones entre James y Jeff, Jill y Jenny, y Jeff y Jenny.
|
||||
|
||||
# --hints--
|
||||
|
||||
`undirectedAdjList` should only contain four nodes.
|
||||
`undirectedAdjList` debe tener solo cuatro nodos.
|
||||
|
||||
```js
|
||||
assert(Object.keys(undirectedAdjList).length === 4);
|
||||
```
|
||||
|
||||
There should be an edge between `Jeff` and `James`.
|
||||
Debe haber una arista entre `Jeff` y `James`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -53,16 +53,16 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
There should be an edge between `Jill` and `Jenny`.
|
||||
Debe haber una arista entre `Jill` y `Jenny`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
undirectedAdjList.Jill.indexOf('Jenny') !== -1 &&
|
||||
undirectedAdjList.Jill.indexOf('Jenny') !== -1
|
||||
undirectedAdjList.Jenny.indexOf('Jill') !== -1
|
||||
);
|
||||
```
|
||||
|
||||
There should be an edge between `Jeff` and `Jenny`.
|
||||
Debe haber una arista entre `Jeff` y `Jenny`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+12
-12
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8256367417b2b2512c78
|
||||
title: Adjacency Matrix
|
||||
title: Matriz de Adyacencia
|
||||
challengeType: 1
|
||||
forumTopicId: 301621
|
||||
dashedName: adjacency-matrix
|
||||
@@ -8,9 +8,9 @@ dashedName: adjacency-matrix
|
||||
|
||||
# --description--
|
||||
|
||||
Another way to represent a graph is to put it in an <dfn>adjacency matrix</dfn>. An <dfn>adjacency matrix</dfn> is a two-dimensional (2D) array where each nested array has the same number of elements as the outer array. In other words, it is a matrix or grid of numbers, where the numbers represent the edges.
|
||||
Otra forma de representar un grafo es ponerlo en una <dfn>matriz de adyacencia</dfn>. Una <dfn>matriz de adyacencia</dfn> es un arreglo de 2 dos-dimensiones (2D) donde cada arreglo anidado tiene el mismo número de elementos que el arreglo externo. En otras palabras, es una matriz o cuadrícula de números, donde los numeros representas las aristas.
|
||||
|
||||
**Note**: The numbers to the top and left of the matrix are just labels for the nodes. Inside the matrix, ones mean there exists an edge between the vertices (nodes) representing the row and column. Finally, zeros mean there is no edge or relationship.
|
||||
**Nota**: los números de la parte superios y a la izquierda de la matriz son solo etiquetas para los nodos. Dentro de la matriz, los unos indican que existe una arista entre los vertices (nodos) que representan la fila y la columna. Finalmente, los ceros indican que no existe una arista o relación.
|
||||
|
||||
<pre>
|
||||
1 2 3
|
||||
@@ -20,7 +20,7 @@ Another way to represent a graph is to put it in an <dfn>adjacency matrix</dfn>.
|
||||
3 | 1 0 0
|
||||
</pre>
|
||||
|
||||
Above is a very simple, undirected graph where you have three nodes, where the first node is connected to the second and third node. Below is a JavaScript implementation of the same thing.
|
||||
El grafo anterior es muy simple, grafo no dirigido donde tienes tres nodos, donde el primer nodo está conectado al segundo y tercer nodo. A continuación se muestra una implementación en JavaScript del mismo objeto.
|
||||
|
||||
```js
|
||||
var adjMat = [
|
||||
@@ -30,7 +30,7 @@ var adjMat = [
|
||||
];
|
||||
```
|
||||
|
||||
Unlike an adjacency list, each "row" of the matrix has to have the same number of elements as nodes in the graph. Here we have a three by three matrix, which means we have three nodes in our graph. A directed graph would look similar. Below is a graph where the first node has an edge pointing toward the second node, and then the second node has an edge pointing to the third node.
|
||||
A diferencia de una lista de adyacencia, cada "fila" de la matriz tiene que tener el mismo número de elementos como nodos en el grafo. Aquí tenemos una matriz de tres por tres, esto significa que tenemos tres nodos en nuestro grafo. Un grafo dirigido sería similar. A continuación se muestra un grafo donde el primer nodo tiene una arista apuntanto al segundo nodo, y luego el segundo nodo tiene una arista apuntando al terecer nodo.
|
||||
|
||||
```js
|
||||
var adjMatDirected = [
|
||||
@@ -40,15 +40,15 @@ var adjMatDirected = [
|
||||
];
|
||||
```
|
||||
|
||||
Graphs can also have <dfn>weights</dfn> on their edges. So far, we have <dfn>unweighted</dfn> edges where just the presence and lack of edge is binary (`0` or `1`). You can have different weights depending on your application.
|
||||
Los grafos tambien pueden tener <dfn>pesos</dfn> en sus aristas. Hasta el momento, tenemos aristas <dfn>no ponderadas</dfn> donde solo la presencia y falta de arista es binaria(`0` o `1`). Puedes tener diferentes pesos dependiendo de tu aplicación.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create an adjacency matrix of an undirected graph with five nodes. This matrix should be in a multi-dimensional array. These five nodes have relationships between the first and fourth node, the first and third node, the third and fifth node, and the fourth and fifth node. All edge weights are one.
|
||||
Crear una matriz de adyacencia de un grafo no dirigido con cinco nodos. Esta matriz debe estar en un arreglo muti-dimensional. Estos cinco nodos tienen relaciones entre el primero y el cuarto nodo, el primero y el tercer nodo, el tercer y quinto nodo, y el cuarto y el quinto nodo. Todos los pesos de las aristas son uno.
|
||||
|
||||
# --hints--
|
||||
|
||||
`undirectedAdjList` should only contain five nodes.
|
||||
`undirectedAdjList` debe contener solamente cinco nodos.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -63,25 +63,25 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
There should be an edge between the first and fourth node.
|
||||
Debe hacer una arista entre el primer y cuarto nodo.
|
||||
|
||||
```js
|
||||
assert(adjMatUndirected[0][3] === 1 && adjMatUndirected[3][0] === 1);
|
||||
```
|
||||
|
||||
There should be an edge between the first and third node.
|
||||
Debe haber una arista entre el primer y tercer nodo.
|
||||
|
||||
```js
|
||||
assert(adjMatUndirected[0][2] === 1 && adjMatUndirected[2][0] === 1);
|
||||
```
|
||||
|
||||
There should be an edge between the third and fifth node.
|
||||
Debe haber una arista entre el tercer y quinto nodo.
|
||||
|
||||
```js
|
||||
assert(adjMatUndirected[2][4] === 1 && adjMatUndirected[4][2] === 1);
|
||||
```
|
||||
|
||||
There should be an edge between the fourth and fifth node.
|
||||
Debe haber una arista entre el cuarto y quinto nodo.
|
||||
|
||||
```js
|
||||
assert(adjMatUndirected[3][4] === 1 && adjMatUndirected[4][3] === 1);
|
||||
|
||||
+15
-15
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d825c367417b2b2512c90
|
||||
title: Breadth-First Search
|
||||
title: Búsqueda en Anchura
|
||||
challengeType: 1
|
||||
forumTopicId: 301622
|
||||
dashedName: breadth-first-search
|
||||
@@ -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>.
|
||||
Hasta ahora, hemos aprendido diferentes formas de crear representaciones de grafos. ¿Y ahora qué? Una pregunta natural a tener es ¿cuál es la distancia entre dos cualquiera en el grafo? Introduciremos los <dfn>algoritmos de recorrido de grafos</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>Los Algoritmos de Recorrido</dfn> son algoritmos para atravesar o visitar los nodos en un grafo. Un tipo de algoritmo de recorrido es el algoritmo de búsqueda en anchura.
|
||||
|
||||
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.
|
||||
Este algoritmo empieza en un nodo y visita todos los vecinos que están a una arista de distancia. Luego visita cada uno de los vecinos hasta que todos los nodos hayan sido visitados.
|
||||
|
||||
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 estructura de datos importante que ayudará a implementar el algoritmo de búsqueda en anchura es la cola. Esta es un arreglo donde tu puedes agregar elementos en un extremos y eliminarlos desde el otro extremo. Esta también es conocida como una estructura de datos <dfn>FIFO</dfn> o <dfn>First-In-First-Out</dfn>.
|
||||
|
||||
Visually, this is what the algorithm is doing. 
|
||||
Visualmente, esto es lo que el algoritmo hace. 
|
||||
|
||||
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).
|
||||
El sombreado gris representa un nodo siendo agregado a la cola y el sombreado negro representa un nodo siendo removido de la cola. Ve como cada vez un nodo se elimina de la cola (el nodo se vuelve negro), todos los vecinos son agregados en la cola ( los nodos se vuelven gris).
|
||||
|
||||
To implement this algorithm, you'll need to input a graph structure and a node you want to start at.
|
||||
Para implementar este algoritmo, necesitarás un estructura de grafo y un nodo en el que quieras comenzar.
|
||||
|
||||
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.
|
||||
Primero, querrá ser consciente de las distancias desde, o números de aristas de distancias, el nodo inicial. Querrás empezar todas las distancias con un número largo como el `Infinity`. Esto evita que existan problemas cuando un nodo no puede ser alcanzado desde el nodo inicial. Luego, querrás ir desde el nodo inicial a sus vecinos. Estos vecinos estan a una arista de distancia y en este punto debes agregar una unidad de distancia a las distancia que has estado guardando.
|
||||
|
||||
# --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.
|
||||
Escribe una función `bfs()` que tome una matriz de adyacencia de un grafo ( un arreglo de dos-dimensiones) y una etiqueta para el nodo raíz como parámetro. La etiqueta del nodo solo debe ser el valor entero del nodo entre `0` y `n - 1`, donde `n` es el total de números de nodos en el grafo.
|
||||
|
||||
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`.
|
||||
Tu función mostrará pares clave-valor como un objeto JavaScript con el nodo y su distancia desde la raíz. Si el nodo no puede ser alcanzado, deberá tener una distancia de `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}`
|
||||
El grafo de entrada `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` con un nodo inicial `1` debe devolver `{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}`
|
||||
El grafo de entrada `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]` con un nodo inicial `1` debe devolver `{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}`
|
||||
El grafo de entrada `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` con un nodo inicial `0` debe devolver `{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}`
|
||||
El grafo de entrada `[[0, 1], [1, 0]]` con un nodo inicial `0` debe devolver `{0: 0, 1: 1}`
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+7
-7
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8257367417b2b2512c7c
|
||||
title: Check if an Element is Present in a Binary Search Tree
|
||||
title: Verificar si un Elemento está presente en un Árbol Binario de Búsqueda
|
||||
challengeType: 1
|
||||
forumTopicId: 301623
|
||||
dashedName: check-if-an-element-is-present-in-a-binary-search-tree
|
||||
@@ -8,15 +8,15 @@ dashedName: check-if-an-element-is-present-in-a-binary-search-tree
|
||||
|
||||
# --description--
|
||||
|
||||
Now that we have a general sense of what a binary search tree is let's talk about it in a little more detail. Binary search trees provide logarithmic time for the common operations of lookup, insertion, and deletion in the average case, and linear time in the worst case. Why is this? Each of those basic operations requires us to find an item in the tree (or in the case of insertion to find where it should go) and because of the tree structure at each parent node we are branching left or right and effectively excluding half the size of the remaining tree. This makes the search proportional to the logarithm of the number of nodes in the tree, which creates logarithmic time for these operations in the average case. Ok, but what about the worst case? Well, consider constructing a tree from the following values, adding them left to right: `10`, `12`, `17`, `25`. Following our rules for a binary search tree, we will add `12` to the right of `10`, `17` to the right of this, and `25` to the right of this. Now our tree resembles a linked list and traversing it to find `25` would require us to traverse all the items in linear fashion. Hence, linear time in the worst case. The problem here is that the tree is unbalanced. We'll look a little more into what this means in the following challenges.
|
||||
Ahora que tenemos un sentido general de lo que es un árbol binario de búsqueda vamos a hablar sobre ello con un poco más de detalle. Un árbol binario de búsqueda provee tiempo lograítmico para las operaciones comunes de búsqueda, inserción y eliminación en el caso promedio, y tiempo linear en el peor de los casos. ¿Porqué es esto? Cada uno de estas operaciones básicas requieren que encontremos un elemento en el árbol ( o en el caso de la inserción encontrar donde debe ir) y debido a que en la estructura de árbol para cada nodo padre estamos yendo a la derecha o izquierda efectivamente excluimos la mitad del tamaño del árbol restante. Esto hace que la búsqueda sea proporcional al logaritmo del numero de nodos en el árbol, lo que crea tiempo logarítmico para estas operaciones en el caso promedio. Bien, pero ¿qué pasa en el peor de los casos? Bueno, considerando construir un árbol a patir de los siguientes valores agregandolos a la izquierdo o derecha: `10`,`12`, `17`, `25`. Siguiendo nuestras reglas para un árbol binario de búsqueda, vamos a añadir `12` a la derecha de `10`, `17` a la derecha de este, y `25` a la derecha de este. Ahora nuestro árbol se parece a una lista enlazada y recorrerlo para encontrar `25` requeriría que atravesemos todos los elementos de manera lineal. Po lo tanto, el tiempo es lineal en el peror caso. El problema aquí es que el árbol está desbalanceado. Veremos un poco más sobre lo que esto significa en los siguientes desafíos.
|
||||
|
||||
# --instructions--
|
||||
|
||||
In this challenge, we will create a utility for our tree. Write a method `isPresent` which takes an integer value as input and returns a boolean value for the presence or absence of that value in the binary search tree.
|
||||
En este desafío, vamos a crear una utilidad para nuestro árbol. Escribe un método `isPresent` que tome un valor entero como entrada y devuelva un valor booleano para la presencia o ausencia de ese valor en el árbol binario de búsqueda.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `BinarySearchTree` data structure should exist.
|
||||
La estructura de datos `BinarySearchTree` debe existir.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -30,7 +30,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The binary search tree should have a method called `isPresent`.
|
||||
El árbol binario de búsqueda debe tener un método llamado `isPresent`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -46,7 +46,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `isPresent` method should correctly check for the presence or absence of elements added to the tree.
|
||||
El método `isPresent` deber verificar correctamente la presencia o ausencia de los elementos añadidos en el árbol.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -74,7 +74,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`isPresent` should handle cases where the tree is empty.
|
||||
`isPresent` debe manejar los casos donde el árbol esté vacío.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+24
-6
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5cc0c1b32479e176caf3b422
|
||||
title: Check if Tree is Binary Search Tree
|
||||
title: Verificar si un árbol es un Árbol Binario de Búsqueda
|
||||
challengeType: 1
|
||||
forumTopicId: 301624
|
||||
dashedName: check-if-tree-is-binary-search-tree
|
||||
@@ -8,17 +8,17 @@ dashedName: check-if-tree-is-binary-search-tree
|
||||
|
||||
# --description--
|
||||
|
||||
Since you already know what a binary search tree is, this challenge will establish how it is you can tell that a tree is a binary search tree or not.
|
||||
Como ya sabes lo que es un árbol binario de búsqueda, este desafío establecerá como es que puedes decir que un árbol es un árbol binario de búsqueda o no lo es.
|
||||
|
||||
The main distinction of a binary search tree is that the nodes are ordered in an organized fashion. Nodes have at most 2 child nodes (placed to the right and/or left) based on if the child node's value is greater than or equal to (right) or less than (left) the parent node.
|
||||
La principal distinción de un árbol de binario de búsqueda es que los nodos están ordenados de forma organizada. Los nodos tienen como máximo 2 nodos hijos (ubicados a la derecha y/o a la izquierda) basados en si el valor de los nodos hijos es mayor o igual que (derecha) o menor que (izquierda) el nodo padre.
|
||||
|
||||
# --instructions--
|
||||
|
||||
In this challenge, you will create a utility for your tree. Write a JavaScript method `isBinarySearchTree` which takes a tree as an input and returns a boolean value for whether the tree is a binary search tree or not. Use recursion whenever possible.
|
||||
En este desafío, crearás una utilidad para tu árbol. Escribe un método en JavaScript `isBinarySearchTree` el cual tomará un árbol como entrada y devolverá un valor booleano si el árbol es un árbol binario de búsqueda o no. Usa recursividad cuando sea posible.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your Binary Search Tree should return true when checked with `isBinarySearchTree()`.
|
||||
Tu árbol binario de búsqueda debe devolver true cuando se compruebe con `isBinarySearchTree()`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -39,6 +39,24 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`isBinarySearchTree()` debe devolver false cuando compruebe que un árbol no es un árbol binario de búsqueda.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
var test = false;
|
||||
if (typeof BinarySearchTree !== 'undefined') {
|
||||
test = new BinarySearchTree();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
test.push(1);
|
||||
test.root.left = new Node(1);
|
||||
return isBinarySearchTree(test) == false;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
|
||||
## --after-user-code--
|
||||
@@ -114,7 +132,7 @@ function isBinarySearchTree(tree) {
|
||||
function checkTree(node) {
|
||||
if (node.left != null) {
|
||||
const left = node.left;
|
||||
if (left.value > node.value) {
|
||||
if (left.value >= node.value) {
|
||||
isBST = false;
|
||||
} else {
|
||||
checkTree(left);
|
||||
|
||||
+16
-16
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8255367417b2b2512c75
|
||||
title: Create a Circular Queue
|
||||
title: Crear un Cola Circular
|
||||
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.
|
||||
En este desafío crearás un cola circular. Una cola circular es una cola que escribe al final de una colección luego comienza a sobreecribirse al principio de la colección. Este tipo de estructura de datos es útil en ciertas situaciones. Por ejemplo, una cola circular puede ser usada para streaming de medios. Una vez que la cola esté llena, los nuevos datos de multimedia reescribirán a los datos antiguos.
|
||||
|
||||
A good way to illustrate this concept is with an array of length `5`:
|
||||
Una buena forma de ilustrar este concepto es con un arreglo de longitud `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:
|
||||
Aquí la lectura y escritura están ambos en la posición `0`. Ahora la cola obtiene 3 nuevos registros `a`,`b`, y `c`. Nuestra cola ahora luce así:
|
||||
|
||||
```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:
|
||||
Como la lectura lee el encabezado, puede eliminar los valores o mantenerlos:
|
||||
|
||||
```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:
|
||||
Ahora escribimos los valores `d`,`e`, y `f` a la cola. Una vez que la escritura alcance el final del arreglo vuelve al inicio:
|
||||
|
||||
```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.
|
||||
Esta aproximación requiere una constante cantidad de memoria pero permite procesar archivos de un tamaño muy grande.
|
||||
|
||||
# --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.
|
||||
En este desafío implementaremos una cola circular. La cola circular debe proporcionar los métodos `enqueue` y `dequeue` que permitan leer y escribir en la cola. La clase misma debe también aceptar un argumento entero el cual puedes usar para especificar el tamaño de la cola cuado sea creada. Hemos escrito la versión inicial de esta clase para tí en el editor de código.
|
||||
|
||||
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`.
|
||||
Cuando añades elementos a la cola, el puntero de escritura debe avazar hacia adelante y volver al inicio una vez que llegue al final de la cola. El método `enqueue` debe devolver el elemento que añadido a la cola si es exitoso; de lo contrario devolverá `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`.
|
||||
De la misma forma, el puntero de lectura debe avanzar hacia adelante mientras elimines elementos de la cola. Cuando elimines un elemento de la cola, ese elemento debe ser devuelto. Si tu no puedes eliminar el elemento de la cola, debes devolver `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.
|
||||
El puntero de escritura no debe sobrepasar el puntero de lectura ( nuestra clase no permitirá sobreescribir datos sin haberlo leído antes) y el puntero de lectura no debe avanzar más que sobre los datos que se han escrito.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `enqueue` method should add items to the circular queue.
|
||||
El método `enqueue` debe agregar elementos a la cola circular.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -71,7 +71,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
You should not enqueue items past the read pointer.
|
||||
No debes agregar elementos más allá del puntero de lectura.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -89,7 +89,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `dequeue` method should dequeue items from the queue.
|
||||
El método `dequeue` debe remover elementos de la cola.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -105,7 +105,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
After an item is dequeued, its position in the queue should be reset to `null`.
|
||||
Después de que un elemento sea removido de la cola, su posición en la cola debe volver a `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.
|
||||
Al tratar de eliminar un elemento más allá del puntero de lectura debe devolver `null` y no avanzará el puntero de escritura.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+13
-13
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d825a367417b2b2512c87
|
||||
title: Create a Doubly Linked List
|
||||
title: Crear una Lista Doblemente Enlazada
|
||||
challengeType: 1
|
||||
forumTopicId: 301626
|
||||
dashedName: create-a-doubly-linked-list
|
||||
@@ -8,19 +8,19 @@ dashedName: create-a-doubly-linked-list
|
||||
|
||||
# --description--
|
||||
|
||||
All of the linked lists we've created so far are singly linked lists. Here, we'll create a <dfn>doubly linked list</dfn>. As the name implies, nodes in a doubly linked list have references to the next and previous node in the list.
|
||||
Todas las listas enlazadas que hemos creado son listas simplemente enlazadas. Aquí, crearemos una <dfn>lista doblemente enlazada</dfn>. Como el nombre lo implica, los nodos en una lista doblemente enlazada tiene referencias al siguiente y anterior nodo en la lista.
|
||||
|
||||
This allows us to traverse the list in both directions but it also requires more memory to be used because every node must contain an additional reference to the previous node in the list.
|
||||
Esto nos permite recorrer la lista en ambas direcciones pero también requiere usar más memoria ya que cada nodo debe contener una referencia adicional al nodo anterior en la lista.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We've provided a `Node` object and started our `DoublyLinkedList`. Let's add two methods to our doubly linked list called `add` and `remove`. The `add` method should add the given element to the list while the `remove` method should remove all occurrences of a given element in the list.
|
||||
Hemos proporcionado un objeto `Node` e iniciado nuestra `DoublyLinkedList`. Vamos a agregar dos métodos para nuestra lista doblemente enlazada llamados `add` y `remove`. El método `add` debe agregar el elemento dado a lista mietnra que el método `remove` debe eliminar todas las ocurrencias de un elemento dado en la lista.
|
||||
|
||||
Be careful to handle any possible edge cases when writing these methods, such as deletions for the first or last element. Also, removing any item on an empty list should return `null`.
|
||||
Ten cuidado de manejar cualquier caso de arista cuando escribas estos métodos, tales como la eliminación para el primer o el último elemento. Además, eliminar cualquier elemento de una lista vacía debe devolver `null`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The DoublyLinkedList data structure should exist.
|
||||
La estructura de datos `DoublyLinkedList` debe existir.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -34,7 +34,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The DoublyLinkedList should have a method called add.
|
||||
La `DoublyLinkedList` debe tener un método llamado `add`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -51,7 +51,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The DoublyLinkedList should have a method called remove.
|
||||
La `DoublyLinkedList` debe tener un método llamado `remove`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -68,7 +68,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Removing an item from an empty list should return null.
|
||||
Eliminar un elemento de una lista vacía debe devolver `null`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -82,7 +82,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The add method should add items to the list.
|
||||
El método `add` debe agregar elementos a la lista.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -99,7 +99,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Each node should keep track of the previous node.
|
||||
Cada node debe mantener un puntero al nodo anterior.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -116,7 +116,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The first item should be removable from the list.
|
||||
El primer elemento debe ser extraíble de la lista.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -134,7 +134,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The last item should be removable from the list.
|
||||
El último elemento debe ser extraíble de la lista.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+16
-16
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d825b367417b2b2512c8e
|
||||
title: Create a Hash Table
|
||||
title: Crear una tabla 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.
|
||||
En este desafío aprenderemos sobre las tablas Hash. Una tabla hash es usada para implementar arreglos asociativos, o mapeos de pares clave-valor, como los objetos y mapas que acabamos de estudiar. Un objeto JavaScript podría ser implementado como una tabala hash, por ejemplo, (su implementación actual dependerpa del entorno en el que se ejecute). La forma en la que funciona una tabla hash es tomar una llave de entrada y hacer hash esta llave en una forma determinista a un valor numérico. Este valor numérico luego se utiliza como la clave real en la que se almacena el valor asociado. Entonces, si tu tratas de acceder a la misma clave otra vez, la funcion hashing procesará la clave, devuelve el mismo resultado numérco, el cual será usado para buscar el valor asociado. Esto proporciona un tiempo de búsqueda O(1) muy eficiente en promedio.
|
||||
|
||||
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.
|
||||
Las tablas hash pueden ser implementadas como arreglos con funciones hash que producen índices del arreglo dentro de un rango específico. En este método, la elección del tamaño del arreglo es importante, al igual que la función de hashing. Por ejemplo, ¿qué pasa si la función de hashing produce el mismo valor para dos diferentes claves? Esto es llamado una colisión. Una forma de manejar las colisiones es solamente almacenar ambos pares clave-valor en ese índice. Luego, al buscar ambos, tendríamos que iterar a través del cubo de objetos para encontrar la llave que estamos buscando. Una buena función de Hashing minimizará las colisiones para mantener un tiempo de búsqueda eficiente.
|
||||
|
||||
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.
|
||||
Aquí, no nos preocuparemos de los detalles de la implementación de la tabal de hash, solamente trataremos de obtener un sentido general de como funcionan.
|
||||
|
||||
# --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.
|
||||
Vamos a crear una funcionalidad básica de una tabla de hash. Hemos creado una función hashing sencilla para que la utilices. Puedes pasar un valor de cadena a la función `hash` y retornará un valor hash que puedes usar como una clave para almacenar. Almacenar elementos basado en este valor hash en el objeto `this.collection`. Crea estos tres métodos; `add`,`remove`, y `lookup`. El primero debe aceptar un par clave valor para añadir a la tabla hash. El segundo debe eliminar un par clave valor cuando pasemos una clave. El tercero debe aceptar una clave y devolver el valor asociado o `null` si la llave no está presente.
|
||||
|
||||
Be sure to write your code to account for collisions!
|
||||
Asegúrate de escribir tu código tomando en cuenta las colisiones!
|
||||
|
||||
**Note:** The `remove` method tests won't pass until the `add` and `lookup` methods are correctly implemented.
|
||||
**Nota:** Las pruebas del método `remove` no pasarán hasta que los métodos `add` y `lookup` sean correctamente implementados.
|
||||
|
||||
# --hints--
|
||||
|
||||
The HashTable data structure should exist.
|
||||
La estructura de datos `HashTable` debe existir.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -38,7 +38,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The HashTable should have an add method.
|
||||
La `HashTable` debe tener un método `add`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -52,7 +52,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The HashTable should have a lookup method.
|
||||
La `HashTable` debe tener un método `lookup`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -66,7 +66,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The HashTable should have a remove method.
|
||||
La `HashTable` debe tener un método `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.
|
||||
El método `add` debe agregar pares clave valor y el método `lookup` debe devolver los valores asociados con una clave dada.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -95,7 +95,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The remove method should accept a key as input and should remove the associated key value pair.
|
||||
El método `remove` debe aceptar una clave como entrada y debe eliminar el par clave valor asociado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -113,7 +113,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The remove method should only remove the correct key value pair.
|
||||
El método `remove` solo debe eliminar el par clave valor correcto.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -139,7 +139,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Items should be added using the hash function.
|
||||
Los elementos deben ser agregados usando la función hash.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -157,7 +157,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The hash table should handle collisions.
|
||||
La tabla Hash debe manejar las colisiones.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+14
-13
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8251367417b2b2512c62
|
||||
title: Create a Linked List Class
|
||||
title: Crea una clase de Lista Enlazada
|
||||
challengeType: 1
|
||||
forumTopicId: 301628
|
||||
dashedName: create-a-linked-list-class
|
||||
@@ -8,25 +8,25 @@ dashedName: create-a-linked-list-class
|
||||
|
||||
# --description--
|
||||
|
||||
Let's create a `linked list` class. Every linked list should start out with a few basic properties: a `head` (the first item in your list) and a `length` (number of items in your list). Sometimes you'll see implementations of linked lists that incorporate a `tail` for the last element of the list, but for now we'll just stick with these two. Whenever we add an element to the linked list, our `length` property should be incremented by one.
|
||||
Vamos a crear un clase `linked list`. Cada lista enlazada debe comenzar con unas cuantas propiedades básicas: una `head` ( el primer elemento en tu lista) y un `length` (numero de elementos en tu lista). A veces verás implementaciones de listas enlazadas que incorporan una `tail` para el último elemento en la lista, por ahora solamente nos quedaremos con estos dos. Cuando agreguemos un elemento a la lista enlazada, nuestra propiedad `length` debe incrementarse en uno.
|
||||
|
||||
We'll want to have a way to add items to our linked list, so the first method we'll want to create is the `add` method.
|
||||
Queremos tener una forma de agregar elementos a nuestra lista enlazada, por eso el primer método que queremos crear es el método `add`.
|
||||
|
||||
If our list is empty, adding an element to our linked list is straightforward enough: we just wrap that element in a `Node` class, and we assign that node to the `head` of our linked list.
|
||||
Si nuestra lista está vacía, agregar un elemento a nuestra lista enlazada es bastante sencillo, simplemente envolver ese elemento en una clase `Node`, y asignar ese nodo a `head` de nuestra lista enlazada.
|
||||
|
||||
But what if our list already has one or more members? How do we add an element to the list? Recall that each node in a linked list has a `next` property. To add a node to the list, find the last node in the list, and point that last node's `next` property at our new node. (Hint: you know you've reached the end of a linked list when a node's `next` property is `null`.)
|
||||
Pero ¿qué pasa si nuestra lista ya tiene uno o más elementos? ¿Como agregarmos un elemento a la lista? Recuerda que cada nodo en una lista enlazada tiene una propiedad `next`. Para agregar un nodo a la lista, encuentra el último nodo en la lista, y apunta la propiedad `next` del último nodo a nuestro nuevo nodo. (Sugerencia: sabes que has llegado el final de una lista enlazada cuando la propiedad `next` de un nodo es `null`.)
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write an add method that assigns the first node you push to the linked list to the `head`; after that, whenever adding a node, every node should be referenced by the previous node's `next` property.
|
||||
Escribe un método agregar que asigne el primer nodo que pongas en la lista enlazada al `head`; después de esto, siempre que agreguemos un nodo, cada node debe ser referenciado en la propiedad `next` del nodo anterior.
|
||||
|
||||
Note
|
||||
Nota
|
||||
|
||||
Your list's `length` should increase by one every time an element is added to the linked list.
|
||||
La propiedad `length` de tu lista debe incrementarse en uno al momento que un elemento es añadido a la lista enlazada.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your `LinkedList` class should have a `add` method.
|
||||
Tu clase `LinkedList` debe tener un método `add`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -37,7 +37,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `LinkedList` class should assign `head` to the first node added.
|
||||
Tu clase `LinkedList` debe asignar al `head` el primer nodo agregado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -49,7 +49,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The previous `node` in your `LinkedList` class should have reference to the newest node created.
|
||||
El `node` anterior en tu clase `LinkedList` debe tener una referencia al nuevo nodo creado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -57,12 +57,13 @@ assert(
|
||||
var test = new LinkedList();
|
||||
test.add('cat');
|
||||
test.add('dog');
|
||||
return test.head().next.element === 'dog';
|
||||
test.add('fish');
|
||||
return test.head().next.element === 'dog' && test.head().next.next.element === 'fish';
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
The `size` of your `LinkedList` class should equal the amount of nodes in the linked list.
|
||||
El `size` de tu clase `LinkedList` deber ser igual a la cantidad de nodos en la lista enlazada.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+17
-17
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 8d5823c8c441eddfaeb5bdef
|
||||
title: Create a Map Data Structure
|
||||
title: Crea una Estructura de Datos de Mapa
|
||||
challengeType: 1
|
||||
forumTopicId: 301629
|
||||
dashedName: create-a-map-data-structure
|
||||
@@ -8,25 +8,25 @@ dashedName: create-a-map-data-structure
|
||||
|
||||
# --description--
|
||||
|
||||
The next few challenges will cover maps and hash tables. Maps are data structures that store key-value pairs. In JavaScript, these are available to us as objects. Maps provide rapid lookup of stored items based on key values and are very common and useful data structures.
|
||||
Los siguientes desafíos cubrirán los mapas y tablas hash. Los mapas son estructuras de datos que almacenan pares clave-valor. En JavaScript, estos están disponibles como objetos. Los mapas proveen una búsqueda rápida de elementos almacenados basados en valores de clave y son estructuras de datos muy comunes y útiles.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Let's get some practice creating our own map. Because JavaScript objects provide a much more efficient map structure than anything we could write here, this is intended primarily as a learning exercise. However, JavaScript objects only provide us with certain operations. What if we wanted to define custom operations? Use the `Map` object provided here as a wrapper around a JavaScript `object`. Create the following methods and operations on the Map object:
|
||||
Vamos a adquirir práctica creando nuestro propio mapa. Debido a que los objetos JavaScript proveen una estructura de mapa mucho más eficiente que lo que podríamos escribir aquí, esto pretende ser un ejercicio principalemente de aprendizaje. Sin embargo, los objetos JavaScript solamente proveen ciertas operaciones. ¿Qué sucedería sin quisiéramos definir las operaciones personalizadas? Usa el objeto `Map` proporcionado aquí como un envoltorio alrededor de un JavaScript `object`. Crea los siguientes métodos y operaciones en el objeto Map:
|
||||
|
||||
<ul>
|
||||
<li><code>add</code> accepts a <code>key, value</code> pair to add to the map.</li>
|
||||
<li><code>remove</code> accepts a key and removes the associated <code>key, value</code> pair</li>
|
||||
<li><code>get</code> accepts a <code>key</code> and returns the stored <code>value</code></li>
|
||||
<li><code>has</code> accepts a <code>key</code> and returns <dfn>true</dfn> if the key exists or <dfn>false</dfn> if it doesn't.</li>
|
||||
<li><code>values</code> returns an array of all the values in the map</li>
|
||||
<li><code>size</code> returns the number of items in the map</li>
|
||||
<li><code>clear</code> empties the map</li>
|
||||
<li><code>add</code> acepta un par de <code>key, value</code> para añadir al mapa.</li>
|
||||
<li><code>remove</code> acepta una clave y elimina el par <code>key, value</code> asociado</li>
|
||||
<li><code>get</code> acepta un <code>key</code> y devuelve el <code>value</code> almacenado</li>
|
||||
<li><code>has</code> acepta un <code>key</code> y devuelve <dfn>true</dfn> si la clave existe o devuelve <dfn>false</dfn> si no esxiste.</li>
|
||||
<li><code>values</code> devuelve un arreglo de todos los valores en el mapa</li>
|
||||
<li><code>size</code> devuelve el número de elementos en el mapa</li>
|
||||
<li><code>clear</code> vacía el mapa</li>
|
||||
</ul>
|
||||
|
||||
# --hints--
|
||||
|
||||
The Map data structure should exist.
|
||||
La estructura de datos `Map` debe existir.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -40,7 +40,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The Map object should have the following methods: add, remove, get, has, values, clear, and size.
|
||||
El objeto `Map` debe tener los siguientes métodos: `add`, `remove`, `get`, `has`, `values`, `clear`, y `size`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -62,7 +62,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The add method should add items to the map.
|
||||
El método `add` debe agregar elementos al mapa.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -79,7 +79,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The has method should return true for added items and false for absent items.
|
||||
El método `has` debe devolver `true` para elementos añadios y `false` para elementos ausentes.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -94,7 +94,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The get method should accept keys as input and should return the associated values.
|
||||
El método `get` debe aceptar una clave como entrad y devolver el valor asociado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -109,7 +109,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The values method should return all the values stored in the map as strings in an array.
|
||||
El método `values` debe devolver todos los valores almacenado en el mapa como cadenas en un arreglo.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -131,7 +131,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The clear method should empty the map and the size method should return the number of items present in the map.
|
||||
El método `clear` debe vaiar el mapa y el método `size` debe devolver el número de elementos presentes en el mapa.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+15
-15
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8255367417b2b2512c74
|
||||
title: Create a Priority Queue Class
|
||||
title: Crear una Clase Cola de Prioridad
|
||||
challengeType: 1
|
||||
forumTopicId: 301630
|
||||
dashedName: create-a-priority-queue-class
|
||||
@@ -8,27 +8,27 @@ dashedName: create-a-priority-queue-class
|
||||
|
||||
# --description--
|
||||
|
||||
In this challenge you will be creating a Priority Queue. A Priority Queue is a special type of Queue in which items may have additional information which specifies their priority. This could be simply represented with an integer. Item priority will override placement order in determining the sequence items are dequeued. If an item with a higher priority is enqueued after items with lower priority, the higher priority item will be dequeued before all the others.
|
||||
En este desafío crearás una Cola de Prioridad. Una cola de Prioridad es un tipo especial de cola en la que los elementos pueden tener una información adicional que especifica su proridad. Esto podría ser simplemente representado con un entero. La prioridad del elemento anulará el orden de colocación para determinar la secuencia de los elementos se debe sacar los elementos de la cola. Si un elemento con una prioridad más alta se pone en cola después de elementos con una prioridad más baja, el elemento con mayor prioridad será extraído antes que los demás elementos.
|
||||
|
||||
For instance, let’s imagine we have a priority queue with three items:
|
||||
Por ejemplo, imaginemos que tenemos una cola de prioridad con tres elementos:
|
||||
|
||||
```js
|
||||
[['kitten', 2], ['dog', 2], ['rabbit', 2]]
|
||||
```
|
||||
|
||||
Here the second value (an integer) represents item priority. If we enqueue `['human', 1]` with a priority of `1` (assuming lower priorities are given precedence) it would then be the first item to be dequeued. The collection would look like this:
|
||||
Aquí el segundo valor ( un entero) representa la prioridad del elemento. Si ponemos en cola `['human', 1]` con una prioridad `1` ( asumiendo que las prioridades inferiores tengan precedencia) entonces sería el primer elemento en ser extraído de la cola. La colección se vería así:
|
||||
|
||||
```js
|
||||
[['human', 1], ['kitten', 2], ['dog', 2], ['rabbit', 2]]
|
||||
```
|
||||
|
||||
We’ve started writing a `PriorityQueue` in the code editor. You will need to add an `enqueue` method for adding items with a priority, a `dequeue` method for removing and returning items, a `size` method to return the number of items in the queue, a `front` method to return the element at the front of the queue, and finally an `isEmpty` method that will return `true` if the queue is empty or `false` if it is not.
|
||||
Hemos empezado a escribir una `PriorityQueue` en el editor de código. Necesitarás agregar un método `enqueue` para agregar elementos con una prioridad, un método `dequeue` para eliminar y devolver elementos, un método `size` que devuelva el número de elementos en la cola, un método `front` que devuelva el elemento al inicio de la cola, y finalmente un método `isEmpty` que devolverá `true` si la cola esta vacía o `false` si no lo está.
|
||||
|
||||
The `enqueue` should accept items with the format shown above (`['human', 1]`) where `1` represents the priority. `dequeue` and `front` should return only the item's name, not its priority.
|
||||
`enqueue` debe aceptar elementos con el formato mostrado arriba(`['human', 1]`) donde `1` representa la prioridad. `dequeue` y `front` debe devolver sole el nombre del elementos, no su prioridad.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your `PriorityQueue` class should have a `enqueue` method.
|
||||
Tu clase `PriorityQueue` debe tener un método `enqueue`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -39,7 +39,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `PriorityQueue` class should have a `dequeue` method.
|
||||
Tu clase `PriorityQueue` debe tener una método `dequeue`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -50,7 +50,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `PriorityQueue` class should have a `size` method.
|
||||
Tu clase `PriorityQueue` debe tener un método `size`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -61,7 +61,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `PriorityQueue` class should have a `front` method.
|
||||
Tu clase `PriorityQueue` debe tener un método `front`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -72,7 +72,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `PriorityQueue` class should have an `isEmpty` method.
|
||||
Tu clase `PriorityQueue` debe tener un método `isEmpty`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -83,7 +83,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `PriorityQueue` class should correctly keep track of the current number of items using the `size` method as items are enqueued and dequeued.
|
||||
Tu clase `PriorityQueue` debe guardar un seguimiento correctamente al número actual de elementos usando el método `size` como elementos encolados y desencolados.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -102,7 +102,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `front` method should return the correct item at the front of the queue as items are enqueued and dequeued.
|
||||
El método `front` debe devolver el elemento correcto que está al frente de la cola ya que los elementos están encolados y desencolados.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -129,7 +129,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `isEmpty` method should return `true` when the queue is empty.
|
||||
El método `isEmpty` debe devolver `true` cuando la cola esté vacía.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -145,7 +145,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The priority queue should return items with a higher priority before items with a lower priority and return items in first-in-first-out order otherwise.
|
||||
La cola de prioridad debe devolver los elementos con una prioridad mayor antes que los elementos con una prioridad más baja y devolver los elementos en orden first-in-first-out de lo contrario.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+14
-14
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8250367417b2b2512c60
|
||||
title: Create a Queue Class
|
||||
title: Crea una clase Cola
|
||||
challengeType: 1
|
||||
forumTopicId: 301631
|
||||
dashedName: create-a-queue-class
|
||||
@@ -8,19 +8,19 @@ dashedName: create-a-queue-class
|
||||
|
||||
# --description--
|
||||
|
||||
Like stacks, queues are a collection of elements. But unlike stacks, queues follow the FIFO (First-In First-Out) principle. Elements added to a queue are pushed to the tail, or the end, of the queue, and only the element at the front of the queue is allowed to be removed.
|
||||
Como las pilas, las colas son una colleción de elementos. Pero a diferencia de las pilas, las colas siguen el principio FIFO (First-In First-Out). Los elementos que son añadidos a la cola son puestos en la cola, o al final, de la cola, y solo el elemento del frente de la cola es posible extraerlo.
|
||||
|
||||
We could use an array to represent a queue, but just like stacks, we want to limit the amount of control we have over our queues.
|
||||
Podríamos usar un arreglo para representar una cola, pero como las pilas, queremos limitar la cantidad de control que tenemos sobre nuestras colas.
|
||||
|
||||
The two main methods of a queue class is the enqueue and the dequeue method. The enqueue method pushes an element to the tail of the queue, and the dequeue method removes and returns the element at the front of the queue. Other useful methods are the front, size, and isEmpty methods.
|
||||
Los métodos principales de una clase cola son el enqueue y el dequeue. El método enqueue coloca un elemento al final de la cola, y el método dequeue elimina y devuelve el elemento al frente de la cola. Otros métodos útiles son el front, size e isEmpty.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write an `enqueue` method that pushes an element to the tail of the queue, a `dequeue` method that removes and returns the front element, a `front` method that lets us see the front element, a `size` method that shows the length, and an `isEmpty` method to check if the queue is empty.
|
||||
Escribe un método `enqueue` que ponga un elemento al final de la cola, un método `dequeue` que elimine y devuelva el elemento del frente, un método `front` que nos permita ver el elemento del frente, un método `size` que muestre la longitud, y un método `isEmpty` que compruebe si la cola está vacía.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your `Queue` class should have a `enqueue` method.
|
||||
La clase `Queue` debe tener un método `enqueue`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -31,7 +31,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `Queue` class should have a `dequeue` method.
|
||||
La clase `Queue` debe tener un método `dequeue`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -42,7 +42,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `Queue` class should have a `front` method.
|
||||
La clase `Queue` debe tener un método `front`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -53,7 +53,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `Queue` class should have a `size` method.
|
||||
La clase `Queue` deber tener un método `size`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -64,7 +64,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `Queue` class should have an `isEmpty` method.
|
||||
La clase `Queue` debe tener un método `isEmpty`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -75,7 +75,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `dequeue` method should remove and return the front element of the queue
|
||||
El método `dequeue` debe eliminar y devolver el elemento del frente de la cola
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -88,7 +88,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `front` method should return value of the front element of the queue
|
||||
El método `front` debe devolver el valor del elemento del frente de la cola
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -101,7 +101,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `size` method should return the length of the queue
|
||||
El método `size` debe devolver la longitud de la cola
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -113,7 +113,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `isEmpty` method should return `false` if there are elements in the queue
|
||||
El método `isEmpty` debe devolver `false` si hay elementos en la cola
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+14
-14
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 8d1323c8c441eddfaeb5bdef
|
||||
title: Create a Set Class
|
||||
title: Crea una Clase Set
|
||||
challengeType: 1
|
||||
forumTopicId: 301632
|
||||
dashedName: create-a-set-class
|
||||
@@ -8,7 +8,7 @@ dashedName: create-a-set-class
|
||||
|
||||
# --description--
|
||||
|
||||
In this exercise we are going to create a class named `Set` to emulate an abstract data structure called "set". A set is like an array, but it cannot contain duplicate values. The typical use for a set is to simply check for the presence of an item. We can see how the ES6 `Set` object works in the example below:
|
||||
En este ejercicio vamos a crear una clase llamada `Set` para simular una estructura de datos abstracta llamada "set". Un set es como un arreglo, pero no puede contener valores duplicados. El uso típico para un set es simplemente verificar la presencia de un elemento. Podemos ver como funciona el objeto `Set` ES6 en el siguiente ejemplo:
|
||||
|
||||
```js
|
||||
const set1 = new Set([1, 2, 3, 5, 5, 2, 0]);
|
||||
@@ -20,17 +20,17 @@ console.log(set1.has(6));
|
||||
// output: false
|
||||
```
|
||||
|
||||
First, we will create an add method that adds a value to our set collection as long as the value does not already exist in the set. Then we will create a remove method that removes a value from the set collection if it already exists. And finally, we will create a size method that returns the number of elements inside the set collection.
|
||||
Primero, crearemos un método add que agregará un valor a nuestra colección siempre y cuando el valor aun no exista en el set. Luego crearemos un método remove que eliminará un valor de la colleción set si ya existe. Y finalmente, crearemos un método size que devolverá el número de elementos en el interior de la colleción set.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create an `add` method that adds a unique value to the set collection and returns `true` if the value was successfully added and `false` otherwise.
|
||||
Cre un método `add` que añada un valor único a la colleción set y devuelva `true` si el valor fue añadido exitosamente y `false` de lo contrario.
|
||||
|
||||
Create a `remove` method that accepts a value and checks if it exists in the set. If it does, then this method should remove it from the set collection, and return `true`. Otherwise, it should return `false`. Create a `size` method that returns the size of the set collection.
|
||||
Crea un método `remove` que acepte un valor y compruebe si existe en el set. Si existe, entonces este método debe eliminarlo de la colección set, y devolver `true`. De lo contrario, debe devolver `false`. Crea un método `size` que devuelva el tamaño de la colleción set.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your `Set` class should have an `add` method.
|
||||
Tu clase `Set` debe tener un método `add`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -41,7 +41,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `add` method should not add duplicate values.
|
||||
Tu método `add` no debe agregar valores duplicados.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -56,7 +56,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `add` method should return `true` when a value has been successfully added.
|
||||
Tu método `add` debe devolver `true` cuando un valor ha sido añadido exitosamente.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -68,7 +68,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `add` method should return `false` when a duplicate value is added.
|
||||
Tu método `add` debe devolver `false` cuando un valor duplicado es añadido.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -81,7 +81,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `Set` class should have a `remove` method.
|
||||
Tu clase `Set` debe tener un método `remove`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -92,7 +92,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `remove` method should only remove items that are present in the set.
|
||||
Tu método `remove` solo debe eliminar elementos que estén presentes en el set.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@@ -107,7 +107,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
Your `remove` method should remove the given item from the set.
|
||||
Tu método `remove` debe eliminar el elemento dado del set.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -122,7 +122,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `Set` class should have a `size` method.
|
||||
Tu clase `Set` debe tener un método `size`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -133,7 +133,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `size` method should return the number of elements in the collection.
|
||||
El método `size` debe devolver el número de elementos en la colleción.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+12
-12
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8250367417b2b2512c5f
|
||||
title: Create a Stack Class
|
||||
title: Crea una Clase Pila
|
||||
challengeType: 1
|
||||
forumTopicId: 301633
|
||||
dashedName: create-a-stack-class
|
||||
@@ -8,15 +8,15 @@ dashedName: create-a-stack-class
|
||||
|
||||
# --description--
|
||||
|
||||
In the last section, we talked about what a stack is and how we can use an array to represent a stack. In this section, we will be creating our own stack class. Although you can use arrays to create stacks, sometimes it is best to limit the amount of control we have with our stacks. Apart from the `push` and `pop` method, stacks have other useful methods. Let's add a `peek`, `isEmpty`, and `clear` method to our stack class.
|
||||
En la última sección, hablamos sobre lo que es una pila y como podemos usar un arreglo para representar una pila. En esta sección, crearemos nuestra propia clase pila. Aunque puedes usar arreglos para crear pilas, a veces es mejor limitar la cantidad de control que tenemos con nuestras pilas. Aparte de los métodos `push` y `pop`, las pilas tienen otros métodos. Añadamos métodos `peek`, `isEmpty`, y `clear` para nuestra clase pila.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a `push` method that pushes an element to the top of the stack, a `pop` method that removes and returns the element on the top of the stack, a `peek` method that looks at the top element in the stack, an `isEmpty` method that checks if the stack is empty, and a `clear` method that removes all elements from the stack. Normally stacks don't have this, but we've added a `print` helper method that console logs the collection.
|
||||
Escribe un método `push` que ponga un elemento en el tope de la pila, un método `pop` que elimine y devuelva el elemento del tope de la pila, un método `peek` que muestre el elemento del tope de la pila, un método `isEmpty` que compruebe si la pila esta vacía, y un método `clear` que elimine todos los elementos de la pila. Normalmente las pilas no tienen esto, pero hemos añadido un método ayudante `print` que registre en consola la colección.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your `Stack` class should have a `push` method.
|
||||
La clase `Stack` debe tener un método `push`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -27,7 +27,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `Stack` class should have a `pop` method.
|
||||
La clase `Stack` debe tener un método `pop`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -38,7 +38,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `Stack` class should have a `peek` method.
|
||||
La clase `Stack` debe tener un método `peek`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -49,7 +49,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `Stack` class should have a `isEmpty` method.
|
||||
La clase `Stack` debe tener un método `isEmpty`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -60,7 +60,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `Stack` class should have a `clear` method.
|
||||
La clase `Stack` debe tener un método `clear`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -71,7 +71,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `peek` method should return the top element of the stack
|
||||
El método `peek` debe devolver el elemento del tope de la pila
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -84,7 +84,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `pop` method should remove and return the top element of the stack
|
||||
El método `pop` debe eliminar y devolver el elemento del tope de la pila
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -97,7 +97,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `isEmpty` method should return true if a stack does not contain any elements
|
||||
El método `isEmpty` debe devolver true si la pila no contiene elementos
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -108,7 +108,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `clear` method should remove all element from the stack
|
||||
El método `clear` debe eliminar todos los elementos de la pila
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+8
-8
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8259367417b2b2512c84
|
||||
title: Create a Trie Search Tree
|
||||
title: Crea un Árbol Trie de búsqueda
|
||||
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.
|
||||
Aquí pasaremos del árbol binario de búsqueda y veremos otro tipo de estructura llamada un Trie. Un Trie es un árbol de búsqueda ordenado comúnmente usado para contener cadenas, o más generalmente arreglos asociativos o conjuntos de datos dinámicos en los cuales las claves son cadenas. Son muy buenos para almacenar conjuntos de datos cuando muchas claves tendrán prefijos superpuestos, por ejemplo, todas las palabras en un diccionario. A diferencia de un árbol binario, los nodos no están asociado con valores reales. En su lugar, la ruta a un nodo representa una clave específica. Por ejemplo, si queremos almacenar la cadena code en un trie. tendríamos cuatro nodos, uno por cada letra: c - o - d - e. Siguiendo esta ruta a través de estos nodos creará la cadena code - esa ruta es la clave que almacenamos. Entonces, si queremos agregar la cadena coding, compartiríamos los primeros tres nodos de code antes desviarnos después de la d. De esta forma, los grandes conjuntos de datos pueden ser almacenados muy compactamente. Además, la búsqueda puede ser muy rápida ya que está efectivamente limitada al largo de la cadena que está almacenada. Además, a diferencia de los árboles binarios un nodo puede almacenar cualquier número de nodos hijos. Como podrías haber adivinado en el ejemplo anterior, algunos metadatos son comúnmente almacenados en los nodos que contienen el final de una clave de manera que en los trayectos posteriores esa clave todavía puede ser recuperada. Por ejemplo, si agregamos codes en nuestro ejemplo anterior necesitaríamos una forma de saber que la e en code representa el final de una clave que fue previamente ingresada. De otra manera, esta información se perdería cuando agregamos 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.
|
||||
Vamos a crear un Trie para almacenar palabras. Aceptará palabras a través de un método `add` y almacenará esas palabras en una estructura de datos Trie. También nos permitirá consultar si una cadena dada es una palabra con un método `isWord`, y recuperar todas las palabras ingresadas en el trie con un método `print`. `isWord` debe devolver un valor booleano y `print` debe devolver un arreglo de todas estas palabras como valores de cadena. Para que podamos verificar que esta estructura de datos se implementa correctamente, hemos proveído una estructura `Node` para cada nodo en el árbol. Cada nodo será un objeto con una propiedad `keys` la cual es un objeto Mapa de JavaScript. Esto mantendrá las letras individuales que son claves válidas de cada nodo. También hemos creado una propiedad `end` en los nodos que puede ser establecids a `true` si el nodo representa la terminación de una palabra.
|
||||
|
||||
# --hints--
|
||||
|
||||
The Trie should have an add method.
|
||||
El `Trie` debe tener un método `add`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -32,7 +32,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The Trie should have a print method.
|
||||
El `Trie` debe tener un método `print`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -48,7 +48,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The Trie should have an isWord method.
|
||||
El `Trie` debe tener un método `isWord`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -64,7 +64,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The print method should return all items added to the trie as strings in an array.
|
||||
El método `print` debe devolver todos los elementos añadidos al Trie como un arrreglo de cadenas.
|
||||
|
||||
```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.
|
||||
El método `isWord` debe devolver `true` solo para las palabras añadidas al trie y `false` para todas las otras palabras.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+16
-6
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d825b367417b2b2512c8d
|
||||
title: Create an ES6 JavaScript Map
|
||||
title: Crea un Mapa ES6 JavaScript
|
||||
challengeType: 1
|
||||
forumTopicId: 301635
|
||||
dashedName: create-an-es6-javascript-map
|
||||
@@ -8,21 +8,29 @@ 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 nueva version de JavaScript os proporciona un objeto de Mapa integrado que proporciona muchas de las funcionalidades que escribimos a mano en el último desafío. Este objeto mapa, aunque similar a los objetos JavaScript regulares, provee algunas funcionalidades útiles que los objetos normales no tienen. Por ejemplo, un Mapa ES6 ratrea el orden de inserción de los elementos que se le añaden. Aquí hay un resumen más completo de sus métodos:
|
||||
|
||||
- `.has(key)` devuelve true o false basado en la presencia de una clave
|
||||
- `.get(key)` devuelve el valor asociado a una clave
|
||||
- `.set(key, value)` establece un nuevo par clave, valor
|
||||
- `.delete(key)` elimina un par clave, valor
|
||||
- `.clear()` elimina todos los pares clave, valor
|
||||
- `.entries()` devuelve un arreglo de todas las claves en orden de inserción
|
||||
- `.values()` devuelve un arreglo de todos los valores en orden de inserción
|
||||
|
||||
# --instructions--
|
||||
|
||||
Define a JavaScript Map object and assign to it a variable called myMap. Add the key, value pair `freeCodeCamp`, `Awesome!` to it.
|
||||
Define un objeto Mapar JavaScript y asignalo a una variable llamada myMap. Agrega el par clave, valor `freeCodeCamp`, `Awesome!` a el.
|
||||
|
||||
# --hints--
|
||||
|
||||
The myMap object should exist.
|
||||
El objeto `myMap` debe existir.
|
||||
|
||||
```js
|
||||
assert(typeof myMap === 'object');
|
||||
```
|
||||
|
||||
myMap should contain the key value pair `freeCodeCamp`, `Awesome!`.
|
||||
`myMap` debe contener el par clave valor `freeCodeCamp`, `Awesome!`.
|
||||
|
||||
```js
|
||||
assert(myMap.get('freeCodeCamp') === 'Awesome!');
|
||||
@@ -39,5 +47,7 @@ assert(myMap.get('freeCodeCamp') === 'Awesome!');
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// solution required
|
||||
const myMap = new Map();
|
||||
|
||||
myMap.set("freeCodeCamp", "Awesome!");
|
||||
```
|
||||
|
||||
+9
-9
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8254367417b2b2512c70
|
||||
title: Create and Add to Sets in ES6
|
||||
title: Crear y añadir Sets en 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:
|
||||
Ahora que has trabajado a través de ES5, vas a hcer algo similar en ES6. Esto será considerablemente fácil. ES6 contiene una estructura de datos integrada `Set` muchas de las operaciones que escribiste a mano ahora están disponibles para tí. Echemos un vistazo:
|
||||
|
||||
To create a new empty set:
|
||||
Para crear un nuevo set vacío:
|
||||
|
||||
```js
|
||||
var set = new Set();
|
||||
```
|
||||
|
||||
You can create a set with a value:
|
||||
Tu puedes crear un set con un valor:
|
||||
|
||||
```js
|
||||
var set = new Set(1);
|
||||
```
|
||||
|
||||
You can create a set with an array:
|
||||
Puedes crear un set con un arreglo:
|
||||
|
||||
```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 vez que hayas creado un set, puedes añadir los valores que desees usando el método `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:
|
||||
Como un recordatorio, un set es una estructura de datos que no puede contener valores duplicados:
|
||||
|
||||
```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'`
|
||||
Para este ejercicio, devuelve un set con los siguientes valores:`1, 2, 3, 'Taco', 'Cat', 'Awesome'`
|
||||
|
||||
# --hints--
|
||||
|
||||
Your `Set` should only contain the values `1, 2, 3, Taco, Cat, Awesome`.
|
||||
Tu `Set` debe contener solamente los valores `1, 2, 3, Taco, Cat, Awesome`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+29
-8
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8258367417b2b2512c80
|
||||
title: Delete a Leaf Node in a Binary Search Tree
|
||||
title: Elimina un Nodo Hoja en un Arbol de búsqueda binaria
|
||||
challengeType: 1
|
||||
forumTopicId: 301637
|
||||
dashedName: delete-a-leaf-node-in-a-binary-search-tree
|
||||
@@ -8,15 +8,15 @@ dashedName: delete-a-leaf-node-in-a-binary-search-tree
|
||||
|
||||
# --description--
|
||||
|
||||
This is the first of three challenges where we will implement a more difficult operation in binary search trees: deletion. Deletion is difficult because removing nodes breaks links in the tree. These links must be carefully reestablished to ensure the binary tree structure is maintained. For some deletions, this means the tree must be rearranged. In general, you will encounter one of three cases when trying to delete a node: Leaf Node: The target to delete has zero children. One Child: The target to delete only has one child. Two Children: The target to delete has two child nodes. Removing a leaf node is easy, we simply remove it. Deleting a node with one child is also relatively easy, we simply remove it and link its parent to child of the node we deleted. Removing a node with two children is more difficult, however, because this creates two child nodes that need to be reconnected to the parent tree. We'll see how to deal with this case in the third challenge. Additionally, you need to be mindful of some edge cases when handling deletion. What if the tree is empty? What if the node to delete is the root node? What if there are only two elements in the tree? For now, let's handle the first case where we delete a leaf node.
|
||||
Este es el primero de tres desafíos donde implementaremos una operación más difícil en un árboles binarios de búsqueda: eliminación. La eliminación es difícil porque la eliminación de nodos rompe enlaces en el árbol. Estos enlaces deben ser restablecidos de manera cuidadosa para asegurar que la estructura del árbol binario es mantenida. Para algunas eliminaciones, esto significa que el árbol debe ser reorganizado. En general, econtrarás uno de los tres casos cuando trates de eliminar un nodo: Nodo Hoja: El objetivo a eliminar tiene cero hijos. Un Hijo: el objetivo a eliminar solo tiene un hijo. Dos hijos: El objetivo a eliminar tiene dos hijos. Eliminar un nodo hoja es fácil, simplemente lo eliminamos. Eliminar un nodo con un hijo es también relativamente fácil, simplemente los eliminamos y vinculamos a su padres el hijo del nodo que eliminamos. Eliminar un nodo con dos hijos es más difícil, sin embargo, porque esto crea dos nodos hijos que necesitan ser reconectados al árbol padre. Veremos como tratar con este caso en el tercer desafío. Adicionalmente, debe tener en cuenta algunos casos de aristas cuando manejemos la eliminación. ¿Qué pasa si el árbol está vacío? ¿Qué pasa si el nodo a eliminar es el nodo raíz? ¿Qué pasa si sólo hay dos elementos en el árbol? Por ahora, vamos a manejar el primer caso donde eliminamos un nodo hoja.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a method on our binary tree called `remove`. We'll build the logic for our deletion operation in here. First, you'll want to create a function within remove that finds the node we are trying to delete in the current tree. If the node is not present in the tree, `remove` should return `null`. Now, if the target node is a leaf node with no children, then the parent reference to it should be set to `null`. This effectively deletes the node from the tree. To do this, you will have to keep track of the parent of the node we are trying to delete as well. It will also be useful to create a way to track the number of children the target node has, as this will determine which case our deletion falls under. We will handle the second and third cases in the next challenges. Good luck!
|
||||
Crea un método en nuestro árbol binario llamado `remove`. Construiremos la lógica de nuestra operación de eliminación aquí. Primero, querrás crear una función dentro de la eliminación que encuentre el nodo que estamos tratando de eliminar en el árbol actual. Si el nodo no está presente en el árbol, `remove` debe devolver `null`. Ahora, si el nodo objetivo es un nodo hoja sin hijos, entonces la referencia al padre debe ser establecida a `null`. Esto elimina efectivamente el nodo del árbol. Para hacer esto, deberás mantener el seguimiento del padre del nodo que estamos tratando de eliminar también. También será útil crear una forma de rastrear el número de hijos que tiene el nodo objetivo, ya que esto determinará que casp de eliminación tenemos. Manejaremos el segundo y tercer caso en los siguientes desafíos. ¡Buena Suerte!
|
||||
|
||||
# --hints--
|
||||
|
||||
The `BinarySearchTree` data structure should exist.
|
||||
La estructura de datos `BinarySearchTree` debe existir.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -30,7 +30,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The binary search tree should have a method called `remove`.
|
||||
El árbol binario de búsqueda debe tener un método llamado `remove`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -46,7 +46,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Trying to remove an element that does not exist should return `null`.
|
||||
Tratar de eliminar un elemento de un árbol vacío debe devolver `null`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -65,7 +65,28 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
If the root node has no children, deleting it should set the root to `null`.
|
||||
Tratar de eliminar un elemento que no existe debe devolver `null`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
(function () {
|
||||
var test = false;
|
||||
if (typeof BinarySearchTree !== 'undefined') {
|
||||
test = new BinarySearchTree();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
if (typeof test.remove !== 'function') {
|
||||
return false;
|
||||
}
|
||||
test.add(15);
|
||||
test.add(30);
|
||||
return test.remove(100) == null;
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
Si el nodo raís no tiene hijos, eliminarlo debe establecer la raíz a `null`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -86,7 +107,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `remove` method should remove leaf nodes from the tree.
|
||||
El método `remove` debe eliminar nodos hojas en el árbol.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+17
-16
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8258367417b2b2512c81
|
||||
title: Delete a Node with One Child in a Binary Search Tree
|
||||
title: Eliminar un nodo con un Hijo en un árbol binario de búsqueda
|
||||
challengeType: 1
|
||||
forumTopicId: 301638
|
||||
dashedName: delete-a-node-with-one-child-in-a-binary-search-tree
|
||||
@@ -8,15 +8,15 @@ dashedName: delete-a-node-with-one-child-in-a-binary-search-tree
|
||||
|
||||
# --description--
|
||||
|
||||
Now that we can delete leaf nodes let's move on to the second case: deleting a node with one child. For this case, say we have a tree with the following nodes 1 — 2 — 3 where 1 is the root. To delete 2, we simply need to make the right reference in 1 point to 3. More generally to delete a node with only one child, we make that node's parent reference the next node in the tree.
|
||||
Ahora que podemos eliminar nodos hoja pasaremos el segundo caso: eliminar un nodo con un hijo. Para este caso, digamos que tenemos un árbol con los siguientes nodos 1 - 2 - 3 donde 1 es la raíz. Para eliminar 2, simplemente necesitamos hacer que la referencia derecha en 1 apunte a 3. Más generalmente para eliminar un nodo con sólo un hijo, hacemos que la referencia padre del nodo sea el siguiente nodo en el árbol.
|
||||
|
||||
# --instructions--
|
||||
|
||||
We've provided some code in our `remove` method that accomplishes the tasks from the last challenge. We find the target to delete and its parent and define the number of children the target node has. Let's add the next case here for target nodes with only one child. Here, we'll have to determine if the single child is a left or right branch in the tree and then set the correct reference in the parent to point to this node. In addition, let's account for the case where the target is the root node (this means the parent node will be `null`). Feel free to replace all the starter code with your own as long as it passes the tests.
|
||||
Hemos proporcionado algún código en nuestro método `remove` que cumple con las tareas del último desafío. Encontramos el objetivo a eliminar y su padre y definimos el número de hijos que el nodo objetivo tiene. Vamos a añadir el siguiente caso aquí para los nodos objetivos con sólo un hijo. Aquí, tendremos que determinar si el hijo individual es un hijo izquierdo o derecho y luego establecer la referencia correcta en el padre para apuntar a este nodo. Adicionalmente, vamos a tener en cuenta el caso done el objetivo en el nodo raíz (esto significa que el padre será `null`). Sientéte libre de reemplazar el código inicial por el tuyo mientras pase las pruebas.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `BinarySearchTree` data structure should exist.
|
||||
La estructura de datos `BinarySearchTree` debe existir.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -30,7 +30,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The binary search tree should have a method called `remove`.
|
||||
El árbol binario de búsqueda debe tener un método llamado `remove`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -46,7 +46,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Trying to remove an element that does not exist should return `null`.
|
||||
Tratar de eliminar un elemento que no existe debe devolver `null`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -65,7 +65,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
If the root node has no children, deleting it should set the root to `null`.
|
||||
Si el nodo raíz no tiene hijos, eliminar debe establecer la raíz a `null`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -86,7 +86,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `remove` method should remove leaf nodes from the tree.
|
||||
El método `remove` debe nodos hojas del árbol.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -114,7 +114,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `remove` method should remove nodes with one child.
|
||||
El método `remove` debe eliminar nodos con un hijo.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -128,19 +128,20 @@ assert(
|
||||
if (typeof test.remove !== 'function') {
|
||||
return false;
|
||||
}
|
||||
test.add(-1);
|
||||
test.add(1);
|
||||
test.add(4);
|
||||
test.add(3);
|
||||
test.add(7);
|
||||
test.add(16);
|
||||
test.remove(16);
|
||||
test.remove(7);
|
||||
test.add(2);
|
||||
test.add(6);
|
||||
test.add(8);
|
||||
test.remove(6);
|
||||
test.remove(3);
|
||||
return test.inorder().join('') == '-1';
|
||||
return test.inorder().join('') == '1248';
|
||||
})()
|
||||
);
|
||||
```
|
||||
|
||||
Removing the root in a tree with two nodes should set the second to be the root.
|
||||
Eliminar la raíz en un árbol con dos nodos debe establecer el segundo para ser la raíz.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+12
-12
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8258367417b2b2512c82
|
||||
title: Delete a Node with Two Children in a Binary Search Tree
|
||||
title: Elimina un nodo con dos hijos en un árbol binario de búsqueda
|
||||
challengeType: 1
|
||||
forumTopicId: 301639
|
||||
dashedName: delete-a-node-with-two-children-in-a-binary-search-tree
|
||||
@@ -8,15 +8,15 @@ dashedName: delete-a-node-with-two-children-in-a-binary-search-tree
|
||||
|
||||
# --description--
|
||||
|
||||
Removing nodes that have two children is the hardest case to implement. Removing a node like this produces two subtrees that are no longer connected to the original tree structure. How can we reconnect them? One method is to find the smallest value in the right subtree of the target node and replace the target node with this value. Selecting the replacement in this way ensures that it is greater than every node in the left subtree it becomes the new parent of but also less than every node in the right subtree it becomes the new parent of. Once this replacement is made the replacement node must be removed from the right subtree. Even this operation is tricky because the replacement may be a leaf or it may itself be the parent of a right subtree. If it is a leaf we must remove its parent's reference to it. Otherwise, it must be the right child of the target. In this case, we must replace the target value with the replacement value and make the target reference the replacement's right child.
|
||||
La eliminación de nodos que tienen dos hijos es el caso más difícil de implementar. Eliminar un nodo como este produce dos subárboles que ya no están conectados a la estructura de árbol original. ¿Cómo podemos reconectarlos? Un método es encontrar el valor más pequeño en el subárbol derecho del nodo objetivo y reemplazar el nodo objetivo con este valor. La selección del reemplazo de esta forma asegura que es mayor que cada nodo en el subárbol izquiero se convierte en el nuevo padre del subárbol pero también es menor que cada nodo en el subárbol derecho se convierte en el nuevo padre del subárbol. Una vez reemplazados el nodo debe ser eliminado del subárbol derecho. Incluso esta operación es complicada porque el remplazo puede ser una hoja o puede ser el padre de un subárbol derecho. Si se trata de una hoja debemos eliminar la referencia de su padre. De otra forma, debe ser el hijo derecho del objetivo. En este caso, debemos reemplazar el valor objetivo con el valor del reemplazo y hacer que la referencia objetivo sea el hijo derecho del reemplazo.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Let's finish our `remove` method by handling the third case. We've provided some code again for the first two cases. Add some code now to handle target nodes with two children. Any edge cases to be aware of? What if the tree has only three nodes? Once you are finished this will complete our deletion operation for binary search trees. Nice job, this is a pretty hard problem!
|
||||
Finalicemos nuesto método `remove` manejando el tercer caso. Hemos provisto un código de nuevo para los dos primeros casos. Agrega algo de código para maneja nodos objetivos con dos hijos. ¿Algún caso de arista para tener en cuenta? ¿Qué pasa si el árbol solo tiene tres nodos? Una vez que finalicemos esto completará nuestra operación de eliminación para los árboles binarios de búsqueda. ¡Buen trabajo, este es un problema bastante difícil!
|
||||
|
||||
# --hints--
|
||||
|
||||
The `BinarySearchTree` data structure should exist.
|
||||
La estructura de datos `BinarySearchTree` debe exisitr.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -30,7 +30,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The binary search tree should have a method called `remove`.
|
||||
El árbol binario de búsqueda debe tener un método llamado `remove`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -46,7 +46,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Trying to remove an element that does not exist should return `null`.
|
||||
Tratar de eliminar un elemento que no existe debe devolver `null`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -62,7 +62,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
If the root node has no children, deleting it should set the root to `null`.
|
||||
Si el nodo raíz no tiene hijos, eliminar debe establecer la raíz a `null`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -80,7 +80,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `remove` method should remove leaf nodes from the tree.
|
||||
El método `remove` debe eliminar nodos hojas del árbol.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -107,7 +107,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `remove` method should remove nodes with one child.
|
||||
El método `remove` debe eliminar nodos con un hijo.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -133,7 +133,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Removing the root in a tree with two nodes should set the second to be the root.
|
||||
Eliminar la raíz en un árbol con dos nodos debe establecer el segundo para ser la raíz.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -155,7 +155,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `remove` method should remove nodes with two children while maintaining the binary search tree structure.
|
||||
El método `remove` debe eliminar nodos con dos hijos manteniendo la estructura del árbol binario de búsqueda.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -212,7 +212,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The root should be removable on a tree of three nodes.
|
||||
La raíz debe ser extraíble en un árbol de tres nodos.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+35
-18
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d825d367417b2b2512c96
|
||||
title: Depth-First Search
|
||||
title: Búsqueda en Profundidad
|
||||
challengeType: 1
|
||||
forumTopicId: 301640
|
||||
dashedName: depth-first-search
|
||||
@@ -8,31 +8,31 @@ dashedName: depth-first-search
|
||||
|
||||
# --description--
|
||||
|
||||
Similar to <dfn>breadth-first search</dfn>, here we will learn about another graph traversal algorithm called <dfn>depth-first search</dfn>.
|
||||
Similar a <dfn>breadth-first-search</dfn>, aquí aprendermos sobre otro algoritmo de recorrido de grafos llamado <dfn>depth-first-search</dfn>.
|
||||
|
||||
Whereas the breadth-first search searches incremental edge lengths away from the source node, <dfn>depth-first search</dfn> first goes down a path of edges as far as it can.
|
||||
Donde la búsqueda en profundidad busca de manera incremental arista alejándose del nodo fuente, <dfn>depth-first-search</dfn> primero baja sobre un camino se aristas tan lejos como pueda.
|
||||
|
||||
Once it reaches one end of a path, the search will backtrack to the last node with an un-visited edge path and continue searching.
|
||||
Una vez que alcance el extremo de una ruta, la búsqueda retrocederá al último nodo con una arista no visitado y continuará la búsqueda.
|
||||
|
||||
The animation below shows how the algorithm works. The algorithm starts with the top node and visits the nodes in the numbered order.
|
||||
La animación siguiente muestra como funciona el algoritmo. El algoritmo inicia con el nodo de arriba y visita los nodos en orden numerado.
|
||||
|
||||
<img class='img-responsive' src='https://camo.githubusercontent.com/aaad9e39961daf34d967c616edeb50abf3bf1235/68747470733a2f2f75706c6f61642e77696b696d656469612e6f72672f77696b6970656469612f636f6d6d6f6e732f372f37662f44657074682d46697273742d5365617263682e676966' />
|
||||
|
||||
Notice how, unlike breadth-first search, every time a node is visited, it doesn't visit all of its neighbors. Instead, it first visits one of its neighbors and continues down that path until there are no more nodes to be visited on that path.
|
||||
Observa como, a diferencia de la búsqueda en anchura, cada vez que un nodo es visitado, no visita a todos sus vecinos. En cambio, primero visita uno de sus vecinos y continúa por ese camino hasta que no haya más nodos para ser visitados en ese camino.
|
||||
|
||||
To implement this algorithm, you'll want to use a stack. A stack is an array where the last element added is the first to be removed. This is also known as a <dfn>Last-In-First-Out</dfn> data structure. A stack is helpful in depth-first search algorithms because, as we add neighbors to the stack, we want to visit the most recently added neighbors first and remove them from the stack.
|
||||
Para implementar este algoritmo, querrás usar una pila. Una pila es un arreglo donde el último elemento añadido es el primero en ser eliminado. Esto también es conocido como una estructura de datos <dfn>Last-In-First-Out</dfn>. Una pila es útil en el algoritmo de búsqueda en profundidad porque, como agregamos vecinos a la pila, queremos visitar los vecinos añadido más recientes y eliminarlo de la pila.
|
||||
|
||||
A simple output of this algorithm is a list of nodes which are reachable from a given node. Therefore, you'll also want to keep track of the nodes you visit.
|
||||
Un salida simple de este algoritmo es una lista de nodos los cuales son alcanzables desde un nodo determinado. Por lo tanto, también querrá llevar un seguimiento de los nodos que visita.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function `dfs()` that takes an undirected, adjacency matrix `graph` and a node label `root` as parameters. The node label will just be the numeric value of the node between `0` and `n - 1`, where `n` is the total number of nodes in the graph.
|
||||
Escribe una función `dfs()` que tome una matriz, de adyacencia de un `graph` no dirigido y una etiqueta de nodo `root` como parámetros. La etiqueta de nodo solo debe ser el valor numérico del nodo entre `0` y `n - 1`, donde `n` es el número total de nodos en el grafo.
|
||||
|
||||
Your function should output an array of all nodes reachable from `root`.
|
||||
Tu función debe mostrar un arreglo de todos los nodos alcanzables desde `root`.
|
||||
|
||||
# --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 an array with `0`, `1`, `2`, and `3`.
|
||||
La entrada del grafo `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` con un nodo inicial de `1` debe devolver un arreglo con `0`, `1`,`2`, y `3`.
|
||||
|
||||
```js
|
||||
assert.sameMembers(
|
||||
@@ -49,7 +49,24 @@ assert.sameMembers(
|
||||
);
|
||||
```
|
||||
|
||||
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 an array with four elements.
|
||||
La entrada del grafo `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` con un nodo inicial `3` debe devolver un arreglo con `3`,`2`,`1`, y `0`.
|
||||
|
||||
```js
|
||||
assert.sameMembers(
|
||||
(function () {
|
||||
var graph = [
|
||||
[0, 1, 0, 0],
|
||||
[1, 0, 1, 0],
|
||||
[0, 1, 0, 1],
|
||||
[0, 0, 1, 0]
|
||||
];
|
||||
return dfs(graph, 3);
|
||||
})(),
|
||||
[3, 2, 1, 0]
|
||||
);
|
||||
```
|
||||
|
||||
El grafo de entrada `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0]]` con un nodo de inicio `1` debe devolver un arreglo con cuatro elementos.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -65,7 +82,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 `3` should return an array with `3`.
|
||||
El grafo de entrada `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]` con un nodo de inicio `3` debe devolver un arreglo con `3`.
|
||||
|
||||
```js
|
||||
assert.sameMembers(
|
||||
@@ -82,7 +99,7 @@ assert.sameMembers(
|
||||
);
|
||||
```
|
||||
|
||||
The input graph `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]` with a start node of `3` should return an array with one element.
|
||||
El grafo de entrada `[[0, 1, 0, 0], [1, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 0]]` con un nodo de inicio `3` debe devolver un arreglo con un elemento.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -98,7 +115,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The input graph `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` with a start node of `3` should return an array with `2` and `3`.
|
||||
El grafo de entrada `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` con un nodo de inicio `3` debe devolver un arreglo con `2` y `3`.
|
||||
|
||||
```js
|
||||
assert.sameMembers(
|
||||
@@ -115,7 +132,7 @@ assert.sameMembers(
|
||||
);
|
||||
```
|
||||
|
||||
The input graph `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` with a start node of `3` should return an array with two elements.
|
||||
El grafo de entrada `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` con un nodo de inicio `3` debe devolver un arreglo con dos elementos.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -131,7 +148,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The input graph `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` with a start node of `0` should return an array with `0` and `1`.
|
||||
El grafo de entrada `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` con un nodo de inicio `0` debe devolver un arreglo con `0` y `1`.
|
||||
|
||||
```js
|
||||
assert.sameMembers(
|
||||
@@ -148,7 +165,7 @@ assert.sameMembers(
|
||||
);
|
||||
```
|
||||
|
||||
The input graph `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` with a start node of `0` should return an array with two elements.
|
||||
El grafo de entrada `[[0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0]]` con un nodo de inicio `0` debe devolver un arreglo con dos elementos.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+14
-14
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8257367417b2b2512c7d
|
||||
title: Find the Minimum and Maximum Height of a Binary Search Tree
|
||||
title: Encuentra el Altura Mínimo y Máximo de un Árbol Binario de Búsqueda
|
||||
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.
|
||||
En último desafío describimos un escenario en el cual un árbol podría desequilibrarse. Para entender el concepto de balance, echemos un vistazo a otra propiedad del árbol: altura. La altura em um árbol representa la distancia desde el nodo raíz hasta una hoja determinada. Diferentes caminos en una estructura de árboles altamente ramificada puede tener diferentes alturas, pero para un árbol dado habrá una altura mínima y máxima. Si el árbol es balanceado, estos valores diferirán a lo mucho por uno. Esto significa que en un árbol balanceado, todos los nodos hojas existen dentro del mismo nivel, o si no están en el mismo nivel estám como mucho un nivel aparte.
|
||||
|
||||
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 propiedad de balance es importante para los árboles porque es lo que determina la eficiencia de las operaciones de árboles. Como explicamos en el último desafío, nos enfrentamos al peor caso de complejidad temporal de los árboles altamente desbalanceados. Los árboles que se autobalancean son comunmente usados para dar cuente de este problema en árboles con conjuntos de datos dinámicos. Ejemplos comunes de estos incluyen los árboles AVL, árboles rojo-negro y árboles B. Todos estos árboles contienen lógica interna adicional que rebalancea el árbol cuando inserciones o eliminaciones crean un estado de desbalanceo.
|
||||
|
||||
**Note:** A similar property to height is depth, which refers to how far a given node is from the root node.
|
||||
**Nota:** Una propiedad similar a la altura es la profundidad, lo cual se refiere a que tan lejos está un nodo dado desde la raíz.
|
||||
|
||||
# --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.
|
||||
Escribe dos métodos para nuestro árbol binario: `findMinHeight` y `findMaxHeight`. Estos métodos deben devolver un valor entero para la mínima y máxima altura dentreo de un árbol binario determinado, respectivamente. Si el nodo está vacío, asignemos una altura de `-1` ( ese es el caso base). Finalmente, agrega un tercer método `isBalanced` el cual devuelva `true` o `false` dependiendo de si el árbol está equilibrado o no. Puedes utilizar los primeros dos métodos que acabas de escribir para determinar esto.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `BinarySearchTree` data structure should exist.
|
||||
La estructura de datos `BinarySearchTree` debe existir.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -34,7 +34,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The binary search tree should have a method called `findMinHeight`.
|
||||
El árbol binario de búsqueda debe tener un método llamado `findMinHeight`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -50,7 +50,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The binary search tree should have a method called `findMaxHeight`.
|
||||
El árbol binario de búsqueda debe tener un método llamado `findMaxHeight`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -66,7 +66,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The binary search tree should have a method called `isBalanced`.
|
||||
El árbol binario de búsqueda debe tener un método llamado `isBalanced`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -82,7 +82,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `findMinHeight` method should return the minimum height of the tree.
|
||||
El método `findMinHeight` debe devolver la altura mínima del árbol.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -109,7 +109,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `findMaxHeight` method should return the maximum height of the tree.
|
||||
El método `findMaxHeight` debe devolver la altura máxima del árbol.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -136,7 +136,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
An empty tree should return a height of `-1`.
|
||||
Un árbol vacío debe devolver una altura de `-1`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -155,7 +155,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `isBalanced` method should return `false` if the tree is an unbalanced binary search tree.
|
||||
El método `isBalanced` debe devolver `false` si el árbol es un árbol binario de búsqueda desbalanceado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -182,7 +182,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `isBalanced` method should return `true` if the tree is a balanced binary search tree.
|
||||
El método `isBalanced` debe devolver `true` si el árbol binario de búsqueda está balanceado.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+8
-8
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8256367417b2b2512c7a
|
||||
title: Find the Minimum and Maximum Value in a Binary Search Tree
|
||||
title: Encuentra el Valor Mínimo y Máximo en un Árbol Binario de Búsqueda
|
||||
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`.
|
||||
En este desafío definirás dos métodos, `findMin` and `findMax`. Estos métodos deben devolver el valor mínimo y máximo en el árbol binario de búsqueda ( no te preocupes por agregar valores al árbol por ahora, hemos agregado algunos por defecto). Si te quedas estancado, reflexiona sobre el invariante que debe ser true para los árboles binarios de búsqueda: cada subárbol izquierdo es menor o igual que su padre y cada subárbol derecho es mayor o igual que su padre. Digamos también que nuestro árbol solo puede almacenar valores enteros. Si el árbol está vacío, cualquiera de los métodos debe devolver `null`.
|
||||
|
||||
# --hints--
|
||||
|
||||
The `BinarySearchTree` data structure should exist.
|
||||
La estructura de datos `BinarySearchTree` debe existir.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -26,7 +26,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The binary search tree should have a method called `findMin`.
|
||||
El árbol binario de búsqueda debe tener un método llamado `findMin`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -42,7 +42,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The binary search tree should have a method called `findMax`.
|
||||
El árbol binario de búsqueda debe tener un método llamado `findMax`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -58,7 +58,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `findMin` method should return the minimum value in the binary search tree.
|
||||
El método `findMin` debe devolver el valor mínimo del árbol binario de búsqueda.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -85,7 +85,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `findMax` method should return the maximum value in the binary search tree.
|
||||
El método `findMax` debe devolver el valor máximo en el árbol binario de búsqueda.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -112,7 +112,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `findMin` and `findMax` methods should return `null` for an empty tree.
|
||||
Los métodos `findMin` y `findMax` deben devolver `null` para un árbol vacío.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+9
-9
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d825b367417b2b2512c8c
|
||||
title: Implement Heap Sort with a Min Heap
|
||||
title: Implementar la clasificación Heap (Montón) con un Heap mínimo
|
||||
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.
|
||||
Ahora que podemos añadir y remover elementos, podremos ver que algunos de los montones de aplicaciones podran ser utilizados. Los Heaps (montones) son comunmente utilizados para implementar colas prioritarias porque siempre almacenan elementos de mayor o menor valor en la primera posición. Además, se usan para implementar un algoritmo de clasificación llamado ''orden de montón'' (orden Heap). Aquí veremos cómo hacer esto. La clasificación por montónes usa un montón mínimo (Heap mínimo), el opuesto del montón máximo (Heap máximo). Un montón mínimo siempre almacena el elemento de menor valor en la posición raíz.
|
||||
|
||||
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)).
|
||||
La clasificación por montón (Heap Sort) trabaja tomando una colección sin ordenar, añadiendo cada item en la colección dentro de un montón mínimo (min Heap), y luego extrayendo cada item desde el montón mínimo a una nueva colección. La estructura de montón mínimo asegura que la nueva colección contendrá los elementos originales en orden de menor a mayor. Este es uno de los mas eficientes algoritmos de clasificación con un rendimiento tanto promedio como en el peor de los casos de 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.
|
||||
Implementemos la ordenación de montón con un montón mínimo. Siéntase libre de adaptar su código de montón máximo aquí. Cree un objeto `MinHeap` con los métodos `insert`, `remove` y `sort`. El método `sort` debe devolver una matriz de todos los elementos en el montón mínimo ordenados de menor a mayor.
|
||||
|
||||
# --hints--
|
||||
|
||||
The MinHeap data structure should exist.
|
||||
Debe existir la estructura de datos `MinHeap`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -32,7 +32,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
MinHeap should have a method called insert.
|
||||
`MinHeap` debe tener un método llamado `insert`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -48,7 +48,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
MinHeap should have a method called remove.
|
||||
`MinHeap` debe tener un método llamado `remove`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -64,7 +64,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
MinHeap should have a method called sort.
|
||||
`MinHeap` debe tener un método llamado `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.
|
||||
El método `sort` debe devolver una matriz que contiene todos los elementos al monto mínimo en orden.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+17
-17
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8256367417b2b2512c79
|
||||
title: Incidence Matrix
|
||||
title: Matriz de incidencia
|
||||
challengeType: 1
|
||||
forumTopicId: 301644
|
||||
dashedName: incidence-matrix
|
||||
@@ -8,21 +8,21 @@ dashedName: incidence-matrix
|
||||
|
||||
# --description--
|
||||
|
||||
Yet another way to represent a graph is to put it in an <dfn>incidence matrix.</dfn>
|
||||
Otra forma de representar un gráfico es ponerlo en un <dfn> matriz de incidencia.</dfn>
|
||||
|
||||
An <dfn>incidence matrix</dfn> is a two-dimensional (2D) array. Generally speaking, an incidence matrix relates two different classes of objects between its two dimensions. This kind of matrix is similar to an adjacency matrix. However, the rows and columns mean something else here.
|
||||
Un <dfn>matriz de incidencia.</dfn> es una matriz bidimensional (2D). En términos generales, una matriz de incidencia relaciona dos clases diferentes de objetos entre sus dos dimensiones. Este tipo de matriz es similar a una matriz de adyacencia. Sin embargo, las filas y columnas significan algo más aquí.
|
||||
|
||||
In graphs, we have edges and nodes. These will be our "two different classes of objects". This matrix will have the rows be the nodes and columns be the edges. This means that we can have an uneven number of rows and columns.
|
||||
En los gráficos, tenemos aristas y nodos. Estas serán nuestras "dos clases diferentes de objetos". Esta matriz tendrá las filas como nodos y las columnas como aristas. Esto significa que podemos tener un número desigual de filas y columnas.
|
||||
|
||||
Each column will represent a unique edge. Also, each edge connects two nodes. To show that there is an edge between two nodes, you will put a 1 in the two rows of a particular column. Below is a 3 node graph with one edge between node 1 and node 3.
|
||||
Cada columna representará un borde único. Además, cada borde conecta dos nodos. Para mostrar que hay un borde entre dos nodos, se pondrá un 1 en las dos filas de una columna en particular. Debajo hay un gráfico de 3 nodos con un borde entre el nodo 1 y el nodo 3.
|
||||
|
||||
<blockquote> 1<br> ---<br>1 | 1<br>2 | 0<br>3 | 1</blockquote>
|
||||
|
||||
Here is an example of an `incidence matrix` with 4 edges and 4 nodes. Remember, the columns are the edges and rows are the nodes themselves.
|
||||
He aquí un ejemplo de una matriz de incidencia con 4 bordes y 4 nodos. Recuerde que las columnas son los bordes y las filas son los propios nodos.
|
||||
|
||||
<blockquote> 1 2 3 4<br> --------<br>1 | 0 1 1 1<br>2 | 1 1 0 0<br>3 | 1 0 0 1<br>4 | 0 0 1 0</blockquote>
|
||||
<blockquote> 1 2 3 4<br> --------<br>1 | 0 1 1 1<br>2 | 1 0 0<br>3 | 1 0 0 1<br>4 | 0 0 1 0 0 0 0 0 0 0 0</blockquote>
|
||||
|
||||
Below is a JavaScript implementation of the same thing.
|
||||
A continuación se muestra una implementación en JavaScript del mismo objeto.
|
||||
|
||||
```js
|
||||
var incMat = [
|
||||
@@ -33,7 +33,7 @@ var incMat = [
|
||||
];
|
||||
```
|
||||
|
||||
To make a directed graph, use `-1` for an edge leaving a particular node and `1` for an edge entering a node.
|
||||
Para hacer una gráfica dirigida, use `-1` para que un borde deje un nodo en particular y `1` para que un borde entre en un nodo.
|
||||
|
||||
```js
|
||||
var incMatDirected = [
|
||||
@@ -44,17 +44,17 @@ var incMatDirected = [
|
||||
];
|
||||
```
|
||||
|
||||
Graphs can also have <dfn>weights</dfn> on their edges. So far, we have <dfn>unweighted</dfn> edges where just the presence and lack of edge is binary (`0` or `1`). You can have different weights depending on your application. A different weight is represented as numbers greater than 1.
|
||||
Los grafos tambien pueden tener <dfn>pesos</dfn> en sus aristas. Hasta el momento, tenemos aristas <dfn>no ponderadas</dfn> donde solo la presencia y falta de arista es binaria(`0` o `1`). Puedes tener diferentes pesos dependiendo de tu aplicación. Un peso diferente se representa como números mayores que 1.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create an incidence matrix of an undirected graph with five nodes and four edges. This matrix should be in a multi-dimensional array.
|
||||
Crea una matriz de incidencia de un gráfico no dirigido con cinco nodos y cuatro bordes. Esta matriz debe estar en un arreglo muti-dimensional.
|
||||
|
||||
These five nodes have the following relationships. The first edge is between the first and second node. The second edge is between the second and third node. The third edge is between the third and fifth node. The fourth edge is between the fourth and second node. All edge weights are one and the edge order matters.
|
||||
Estos cinco nodos tienen las siguientes relaciones. El primer borde está entre el primer y el segundo nodo. El segundo borde está entre el segundo y el tercer nodo. El tercer borde está entre el tercer y el quinto nodo. El cuarto borde está entre el cuarto y el segundo nodo. Todos los pesos de bordes son uno y el orden de ventaja importa.
|
||||
|
||||
# --hints--
|
||||
|
||||
`incMatUndirected` should only contain five nodes.
|
||||
`incMatUndirected` solo debe contener cinco nodos.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -69,25 +69,25 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
There should be a first edge between the first and second node.
|
||||
Debería haber un primer borde entre el primer y el segundo nodo.
|
||||
|
||||
```js
|
||||
assert(incMatUndirected[0][0] === 1 && incMatUndirected[1][0] === 1);
|
||||
```
|
||||
|
||||
There should be a second edge between the second and third node.
|
||||
Debería haber un segundo borde entre el segundo y el tercer nodo.
|
||||
|
||||
```js
|
||||
assert(incMatUndirected[1][1] === 1 && incMatUndirected[2][1] === 1);
|
||||
```
|
||||
|
||||
There should be a third edge between the third and fifth node.
|
||||
Debería haber un tercer borde entre el tercer y el quinto nodo.
|
||||
|
||||
```js
|
||||
assert(incMatUndirected[2][2] === 1 && incMatUndirected[4][2] === 1);
|
||||
```
|
||||
|
||||
There should be a fourth edge between the second and fourth node.
|
||||
Debería haber un cuarto borde entre el segundo y el cuarto nodo.
|
||||
|
||||
```js
|
||||
assert(incMatUndirected[1][3] === 1 && incMatUndirected[3][3] === 1);
|
||||
|
||||
+45
-33
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d825a367417b2b2512c8a
|
||||
title: Insert an Element into a Max Heap
|
||||
title: Inserta un elemento en un montón máximo
|
||||
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.
|
||||
Ahora pasaremos a otra estructura de datos de árbol, la pila binaria. Una pila binaria es un árbol binario parcialmente ordenado que satisface la propiedad de la pila. La propiedad heap especifica una relación entre los nodos padre e hijo. Puede tener una pila máxima, en la que todos los nodos padre son mayores o iguales a sus nodos secundarios, o un montón de minutos, en el que lo contrario es cierto. Los montones binarios también son árboles binarios completos. Esto significa que todos los niveles del árbol se llenan completamente y si el último nivel está parcialmente llenado se llena de izquierda a derecha.
|
||||
|
||||
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.
|
||||
Mientras que los montones binarios pueden ser implementados como estructuras de árbol con nodos que contienen referencias izquierdas y derechas, el orden parcial según la propiedad del montón nos permite representar el montón con una matriz. La relación padre-hijos es lo que estamos interesados y con aritmética simple podemos calcular los hijos de cualquier padre y el padre de cualquier nodo hijo.
|
||||
|
||||
For instance, consider this array representation of a binary min heap:
|
||||
Por ejemplo, considere esta representación de matriz de un montón de minutos binarios:
|
||||
|
||||
```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`:
|
||||
El nodo raíz es el primer elemento, `6`. Sus hijos son `22` y `30`. Si analizamos la relación entre los índices de matriz de estos valores, para el índice `i` los hijos son `2 * i + 1` y `2 * i + 2`. Del mismo modo, el elemento en índice `0` es el padre de estos dos hijos en los índices `1` y `2`. Más generalmente, podemos encontrar el padre de un nodo en cualquier índice con lo siguiente: `Math.floor((i - 1) / 2)`. Estos patrones se mantendrán verdadero a medida que el árbol binario crece a cualquier tamaño. Por último, podemos hacer un ligero ajuste para facilitar aún más esta aritmética saltando el primer elemento de la matriz. Al hacer esto se crea la siguiente relación para cualquier elemento en un índice determinado `i`:
|
||||
|
||||
Example array representation:
|
||||
Ejemplo de representación de matrices:
|
||||
|
||||
```js
|
||||
[ null, 6, 22, 30, 37, 63, 48, 42, 76 ]
|
||||
```
|
||||
|
||||
An element's left child: `i * 2`
|
||||
Un hijo izquierdo de un elemento: `i * 2`
|
||||
|
||||
An element's right child: `i * 2 + 1`
|
||||
Niño derecho de un elemento: `i * 2 + 1`
|
||||
|
||||
An element's parent: `Math.floor(i / 2)`
|
||||
Padre de 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 vez envueltas la cabeza alrededor de las matemáticas, usar una representación de array es muy útil porque las ubicaciones de nodos se pueden determinar rápidamente con esta aritmética y el uso de memoria se disminuye porque no necesita mantener referencias a nodos secundarios.
|
||||
|
||||
# --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:
|
||||
Instrucciones: Aquí crearemos una pila máxima. Comienza por crear un método `insert` que añade elementos a nuestra pila. Durante la inserción, es importante mantener siempre la propiedad del montón. Para una pila máxima, esto significa que el elemento raíz siempre debe tener el mayor valor en el árbol y todos los nodos padre deben ser mayores que sus hijos. Para una implementación de array de un montón, esto se logra típicamente en tres pasos:
|
||||
|
||||
<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>Agrega el nuevo elemento al final de la matriz.</li>
|
||||
<li>Si el elemento es más grande que su padre, conmutalos.</li>
|
||||
<li>Continúe cambiando hasta que el nuevo elemento sea más pequeño que el padre o llegue a la raíz del árbol.</li>
|
||||
</ol>
|
||||
|
||||
Finally, add a `print` method which returns an array of all the items that have been added to the heap.
|
||||
Finalmente, añade un método `print` que devuelve un array de todos los elementos que se han añadido al heap.
|
||||
|
||||
# --hints--
|
||||
|
||||
The MaxHeap data structure should exist.
|
||||
Debe existir la estructura de datos de `MaxHeap`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -62,7 +62,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
MaxHeap should have a method called insert.
|
||||
`MaxHeap` debe tener un método llamado `insert`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -78,7 +78,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
MaxHeap should have a method called print.
|
||||
`MaxHeap` debe tener un método llamado `print`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -94,7 +94,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The insert method should add elements according to the max heap property.
|
||||
El método `insert` debe añadir elementos de acuerdo a la propiedad máxima del heap.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -110,8 +110,12 @@ assert(
|
||||
test.insert(700);
|
||||
test.insert(32);
|
||||
test.insert(51);
|
||||
let result = test.print();
|
||||
return result.length == 5 ? result[0] == 700 : result[1] == 700;
|
||||
test.insert(800);
|
||||
const result = test.print();
|
||||
const solution = JSON.stringify([null,800,51,700,32,50,100]);
|
||||
const solutionWithoutNull = JSON.stringify([800,51,700,32,50,100]);
|
||||
|
||||
return (result.length == 6) ? (JSON.stringify(result) == solutionWithoutNull) : (JSON.stringify(result) == solution);
|
||||
})()
|
||||
);
|
||||
```
|
||||
@@ -133,20 +137,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
|
||||
};
|
||||
|
||||
+6
-6
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8259367417b2b2512c83
|
||||
title: Invert a Binary Tree
|
||||
title: Invertir un árbol 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!
|
||||
Aquí crearemos una función para invertir un árbol binario. Dado un árbol binario, queremos producir un nuevo árbol que sea equivalentemente la imagen espejo de este árbol. Ejecutar un transversal en orden inverso en un árbol invertido explorará los nodos en orden inverso, cuando se compara con el travesía en orden inordenado del árbol original. Escribe un método para hacer esto llamado `invert` en nuestro árbol binario. Llamar a este método debería invertir la estructura actual del árbol. Idealmente, nos gustaría hacerlo en su lugar en el tiempo lineal. Es decir, sólo visitamos cada nodo una vez y modificamos la estructura de árbol existente a medida que vamos, sin necesidad de usar ningún recuerdo adicional. ¡Buena suerte!
|
||||
|
||||
# --hints--
|
||||
|
||||
The `BinarySearchTree` data structure should exist.
|
||||
La estructura de datos `BinarySearchTree` debe existir.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -26,7 +26,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The binary search tree should have a method called `invert`.
|
||||
El árbol binario de búsqueda debe tener un método llamado `invert`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -42,7 +42,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The `invert` method should correctly invert the tree structure.
|
||||
El método `invert` debe invertir correctamente la estructura del árbol.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -70,7 +70,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Inverting an empty tree should return `null`.
|
||||
Invertir una lista vacía debe devolver `null`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+12
-12
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8250367417b2b2512c5e
|
||||
title: Learn how a Stack Works
|
||||
title: Aprende cómo funciona una Pila
|
||||
challengeType: 1
|
||||
forumTopicId: 301705
|
||||
dashedName: learn-how-a-stack-works
|
||||
@@ -8,43 +8,43 @@ dashedName: learn-how-a-stack-works
|
||||
|
||||
# --description--
|
||||
|
||||
You are probably familiar with stack of books on your table. You have likely used the undo feature of a text editor. You are also probably used to hitting the back button on your phone to go back to the previous view in your app.
|
||||
Probablemente esté familiarizado con la pila de libros en su mesa. Es probable que haya usado la característica de deshacer de un editor de texto. Probablemente también estés acostumbrado a pulsar el botón atrás de tu teléfono para volver a la vista anterior de tu aplicación.
|
||||
|
||||
You know what they all have in common? They all store the data in a way so that you can traverse backwards.
|
||||
¿Sabes lo que todos tienen en común? Todos almacenan los datos de una manera que usted puede atravesar hacia atrás.
|
||||
|
||||
The topmost book in the stack was the one that was put there last. If you remove that book from your stack's top, you would expose the book that was put there before the last book and so on.
|
||||
El libro más alto de la pila fue el que se puso a lo último. Si eliminas ese libro de la parte superior de tu pila, expondrías el libro que se puso allí antes del último libro y así sucesivamente.
|
||||
|
||||
If you think about it, in all the above examples, you are getting <dfn>Last-In-First-Out</dfn> type of service. We will try to mimic this with our code.
|
||||
Si lo piensas, en todos los ejemplos anteriores, obtienes el tipo de servicio de <dfn>Last-In-First-Out</dfn>. Intentaremos imitar esto con nuestro código.
|
||||
|
||||
This data storage scheme is called a <dfn>Stack</dfn>. In particular, we would have to implement the `push()` method that pushes JavaScript objects at the top of the stack; and `pop()` method, that removes the JavaScript object that's at the top of the stack at the current moment.
|
||||
Este esquema de almacenamiento de datos se llama una pila <dfn></dfn>. En particular, tendríamos que implementar el método `push()` que empuja objetos JavaScript en la parte superior de la pila; y el método `pop()` , que elimina el objeto JavaScript que está en la parte superior de la pila en el momento actual.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Here we have a stack of homework assignments represented as an array: `"BIO12"` is at the base, and `"PSY44"` is at the top of the stack.
|
||||
Aquí tenemos una pila de tareas de inicio representadas como un arreglo: `"BIO12"` está en la base, y `"PSY44"` está en la parte superior de la pila.
|
||||
|
||||
Modify the given array and treat it like a `stack` using the JavaScript methods mentioned above. Remove the top element `"PSY44"` from the stack. Then add `"CS50"` to be the new top element of the stack.
|
||||
Modifique el array dado y trate como una pila `` usando los métodos de JavaScript mencionados anteriormente. Elimina el elemento superior `"PSY44"` de la pila. Luego añade `"CS50"` para ser el nuevo elemento superior de la pila.
|
||||
|
||||
# --hints--
|
||||
|
||||
`homeworkStack` should only contain 4 elements.
|
||||
`homeworkStack` solo debe contener 4 elementos.
|
||||
|
||||
```js
|
||||
assert(homeworkStack.length === 4);
|
||||
```
|
||||
|
||||
The last element in `homeworkStack` should be `"CS50"`.
|
||||
El último elemento en `homeworkStack` debe ser `"CS50"`.
|
||||
|
||||
```js
|
||||
assert(homeworkStack[3] === 'CS50');
|
||||
```
|
||||
|
||||
`homeworkStack` should not contain `"PSY44"`.
|
||||
`homeworkStack` no debe contener `"PSY44"`.
|
||||
|
||||
```js
|
||||
assert(homeworkStack.indexOf('PSY44') === -1);
|
||||
```
|
||||
|
||||
The initial declaration of the `homeworkStack` should not be changed.
|
||||
La declaración inicial de `homeworkStack` no debe ser cambiada.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+5
-5
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8254367417b2b2512c6e
|
||||
title: Perform a Difference on Two Sets of Data
|
||||
title: Realizar una diferencia en dos conjuntos de datos
|
||||
challengeType: 1
|
||||
forumTopicId: 301706
|
||||
dashedName: perform-a-difference-on-two-sets-of-data
|
||||
@@ -8,13 +8,13 @@ dashedName: perform-a-difference-on-two-sets-of-data
|
||||
|
||||
# --description--
|
||||
|
||||
In this exercise we are going to perform a difference on 2 sets of data. We will create a method on our `Set` data structure called `difference`. A difference of sets should compare two sets and return the items present in the first set that are absent in the second. This method should take another `Set` as an argument and return the `difference` of the two sets.
|
||||
En este ejercicio vamos a hacer una diferencia en dos conjuntos de datos. Crearemos un método en nuestra estructura de datos `Set` llamada `diferencia`. Una diferencia de conjuntos debe comparar dos conjuntos y devolver los elementos presentes en el primer conjunto que están ausentes en el segundo. Este método debe tomar otro `Set` como argumento y retornar la `diferencia` de los dos sets.
|
||||
|
||||
For example, if `setA = ['a','b','c']` and `setB = ['a','b','d','e']`, then the difference of setA and setB is: `setA.difference(setB) = ['c']`.
|
||||
Por ejemplo, si `setA = ['a','b','c']` y `setB = ['a', b','d','e']`, entonces la diferencia de setA y setB es: `setA. ifference(setB) = ['c']`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your `Set` class should have a `difference` method.
|
||||
Tu clase `Set` debe tener un método `remove`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -25,7 +25,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Your `difference` method should return the proper collection.
|
||||
El método `difference` debe retornar la colección adecuada.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+7
-7
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8254367417b2b2512c71
|
||||
title: Remove items from a set in ES6
|
||||
title: Eliminar elementos de un conjunto en ES6
|
||||
challengeType: 1
|
||||
forumTopicId: 301713
|
||||
dashedName: remove-items-from-a-set-in-es6
|
||||
@@ -8,15 +8,15 @@ dashedName: remove-items-from-a-set-in-es6
|
||||
|
||||
# --description--
|
||||
|
||||
Let's practice removing items from an ES6 Set using the `delete` method.
|
||||
Vamos a practicar eliminar elementos de un Set ES6 utilizando el método `delete`.
|
||||
|
||||
First, create an ES6 Set:
|
||||
Primero, crear un conjunto ES6:
|
||||
|
||||
```js
|
||||
var set = new Set([1,2,3]);
|
||||
```
|
||||
|
||||
Now remove an item from your Set with the `delete` method.
|
||||
Ahora elimine un elemento del Set con el método `delete`.
|
||||
|
||||
```js
|
||||
set.delete(1);
|
||||
@@ -25,13 +25,13 @@ console.log([...set]) // should return [ 2, 3 ]
|
||||
|
||||
# --instructions--
|
||||
|
||||
Now, create a set with the integers 1, 2, 3, 4, & 5.
|
||||
Ahora, cree un conjunto con los enteros 1, 2, 3, 4, & 5.
|
||||
|
||||
Remove the values 2 and 5, and then return the set.
|
||||
Elimina los valores 2 y 5, y luego devuelve el conjunto.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your Set should contain the values 1, 3, & 4
|
||||
Tu Set debe contener los valores 1, 3, & 4
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+7
-7
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d825a367417b2b2512c88
|
||||
title: Reverse a Doubly Linked List
|
||||
title: Invertir una lista de enlaces dobles
|
||||
challengeType: 1
|
||||
forumTopicId: 301714
|
||||
dashedName: reverse-a-doubly-linked-list
|
||||
@@ -8,11 +8,11 @@ dashedName: reverse-a-doubly-linked-list
|
||||
|
||||
# --description--
|
||||
|
||||
Let's create one more method for our doubly linked list called reverse which reverses the list in place. Once the method is executed the head should point to the previous tail and the tail should point to the previous head. Now, if we traverse the list from head to tail we should meet the nodes in a reverse order compared to the original list. Trying to reverse an empty list should return null.
|
||||
Vamos a crear un método más para nuestra lista de doble enlazada llamada reversa, la cual revierte la lista en su lugar. Una vez que se ejecuta el método, la cabeza debe apuntar a la cola anterior y la cola debe apuntar a la cabeza anterior. Ahora, si recorremos la lista de cabeza a cola, deberíamos encontrar los nodos en orden inverso en comparación con la lista original. Intentar revertir una lista vacía debe devolver nulo.
|
||||
|
||||
# --hints--
|
||||
|
||||
The DoublyLinkedList data structure should exist.
|
||||
La estructura de datos `DoublyLinkedList` debe existir.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -26,7 +26,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The DoublyLinkedList should have a method called reverse.
|
||||
La `DoublyLinkedList` debería tener un método llamado `reverse`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -43,7 +43,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Reversing an empty list should return null.
|
||||
Invertir una lista vacía debe devolver `null`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -57,7 +57,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The reverse method should reverse the list.
|
||||
El método `reverse` debe revertir la lista.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@@ -77,7 +77,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
The next and previous references should be correctly maintained when a list is reversed.
|
||||
Las referencias `next` y `previous` deben ser mantenidas correctamente cuando se revierte una lista.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
||||
+15
-15
@@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d8253367417b2b2512c6a
|
||||
title: Typed Arrays
|
||||
title: Matrices tipeadas
|
||||
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.
|
||||
Los matrices son objetos JavaScript que pueden contener muchos elementos diferentes.
|
||||
|
||||
```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.
|
||||
Básicamente, lo que sucede en segundo plano es que el navegador automáticamente le dará la cantidad correcta de espacio de memoria para esa matriz. También cambiará según sea necesario si añade o elimina datos.
|
||||
|
||||
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.
|
||||
Sin embargo, en el mundo de alto rendimiento y diferentes tipos de elementos, a veces es necesario ser más específico en cuanto a la cantidad de memoria que se da a una matriz.
|
||||
|
||||
<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>Los arreglos escritos</dfn> son la respuesta a este problema. Ahora puedes decir cuánta memoria quieres dar a una matriz. Debajo hay una visión general básica de los diferentes tipos de matrices disponibles y el tamaño en bytes para cada elemento de esa matriz.
|
||||
|
||||
<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>Cada tamaño de elemento en 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>
|
||||
|
||||
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`.
|
||||
Hay dos formas de crear este tipo de matriz. Una forma es crearla directamente. A continuación se muestra cómo crear una longitud de 3 `Int16Array`.
|
||||
|
||||
```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.
|
||||
También puede crear un <dfn>búfer</dfn> para asignar cuántos datos (en bytes) desea que el array ocupe. **Nota**
|
||||
Para crear arreglos escritos usando búferes, necesita asignar el número de bytes para ser un múltiplo de los bytes listados arriba.
|
||||
|
||||
```js
|
||||
// Create same Int16Array array differently
|
||||
@@ -43,7 +43,7 @@ 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>.
|
||||
<dfn>Los búferes</dfn> son objetos de propósito general que solo llevan datos. No puedes acceder a ellos normalmente. Para acceder a ellos, primero necesita crear una <dfn>vista</dfn>.
|
||||
|
||||
```js
|
||||
i8View[0] = 42;
|
||||
@@ -51,27 +51,27 @@ 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.
|
||||
Los arrays tipeados no tienen algunos de los métodos que tienen arrays tradicionales como `.pop()` o `.push()`. Los arreglos escritos también fallan `Array.isArray()` que comprueba si algo es un arreglo. Aunque más sencillo, esto puede ser una ventaja para los motores JavaScript menos sofisticados para implementarlos.
|
||||
|
||||
# --instructions--
|
||||
|
||||
First create a `buffer` that is 64-bytes. Then create a `Int32Array` typed array with a view of it called `i32View`.
|
||||
Primero cree un `búfer` de 64 bytes. Luego crea un array tipeado de `Int32Array` con una vista llamada `i32View`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Your `buffer` should be 64 bytes large.
|
||||
El búfer `` debe tener 64 bytes de tamaño.
|
||||
|
||||
```js
|
||||
assert(buffer.byteLength === 64);
|
||||
```
|
||||
|
||||
Your `i32View` view of your buffer should be 64 bytes large.
|
||||
La vista `i32View` del búfer debe ser de 64 bytes.
|
||||
|
||||
```js
|
||||
assert(i32View.byteLength === 64);
|
||||
```
|
||||
|
||||
Your `i32View` view of your buffer should be 16 elements long.
|
||||
La vista `i32View` del búfer debe tener 16 elementos de largo.
|
||||
|
||||
```js
|
||||
assert(i32View.length === 16);
|
||||
|
||||
+9
-9
@@ -1,44 +1,44 @@
|
||||
---
|
||||
id: 5900f36e1000cf542c50fe80
|
||||
title: 'Problem 1: Multiples of 3 and 5'
|
||||
challengeType: 5
|
||||
title: 'Problema 1: Múltiples de 3 y 5'
|
||||
challengeType: 1
|
||||
forumTopicId: 301722
|
||||
dashedName: problem-1-multiples-of-3-and-5
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
|
||||
Si enumeramos todos los números naturales menores a 10 que sean múltiplos de 3 o 5, obtenemos 3, 5, 6 y 9. La suma de estos múltiplos es 23.
|
||||
|
||||
Find the sum of all the multiples of 3 or 5 below the provided parameter value `number`.
|
||||
Encuentra la suma de todos los múltiplos de 3 o 5 menores que el valor del parámetro proporcionado `number`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`multiplesOf3and5(10)` should return a number.
|
||||
`multiplesOf3and5(10)` debería retornar un número.
|
||||
|
||||
```js
|
||||
assert(typeof multiplesOf3and5(10) === 'number');
|
||||
```
|
||||
|
||||
`multiplesOf3and5(49)` should return 543.
|
||||
`multiplesOf3and5(49)` debería retornar 543.
|
||||
|
||||
```js
|
||||
assert.strictEqual(multiplesOf3and5(49), 543);
|
||||
```
|
||||
|
||||
`multiplesOf3and5(1000)` should return 233168.
|
||||
`multiplesOf3and5(1000)` debería retornar 233168.
|
||||
|
||||
```js
|
||||
assert.strictEqual(multiplesOf3and5(1000), 233168);
|
||||
```
|
||||
|
||||
`multiplesOf3and5(8456)` should return 16687353.
|
||||
`multiplesOf3and5(8456)` debería retornar 16687353.
|
||||
|
||||
```js
|
||||
assert.strictEqual(multiplesOf3and5(8456), 16687353);
|
||||
```
|
||||
|
||||
`multiplesOf3and5(19564)` should return 89301183.
|
||||
`multiplesOf3and5(19564)` debería retornar 89301183.
|
||||
|
||||
```js
|
||||
assert.strictEqual(multiplesOf3and5(19564), 89301183);
|
||||
|
||||
+33
-22
@@ -1,44 +1,44 @@
|
||||
---
|
||||
id: 5900f3761000cf542c50fe89
|
||||
title: 'Problem 10: Summation of primes'
|
||||
challengeType: 5
|
||||
title: 'Problema 10: Sumatoria de números primos'
|
||||
challengeType: 1
|
||||
forumTopicId: 301723
|
||||
dashedName: problem-10-summation-of-primes
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
|
||||
La suma de los números primos menores que 10 es 2 + 3 + 5 + 7 = 17.
|
||||
|
||||
Find the sum of all the primes below `n`.
|
||||
Encuentra la suma de todos los números primos menores que `n`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`primeSummation(17)` should return a number.
|
||||
`primeSummation(17)` debería retornar un número.
|
||||
|
||||
```js
|
||||
assert(typeof primeSummation(17) === 'number');
|
||||
```
|
||||
|
||||
`primeSummation(17)` should return 41.
|
||||
`primeSummation(17)` debería retornar 41.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primeSummation(17), 41);
|
||||
```
|
||||
|
||||
`primeSummation(2001)` should return 277050.
|
||||
`primeSummation(2001)` debería retornar 277050.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primeSummation(2001), 277050);
|
||||
```
|
||||
|
||||
`primeSummation(140759)` should return 873608362.
|
||||
`primeSummation(140759)` debería retornar 873608362.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primeSummation(140759), 873608362);
|
||||
```
|
||||
|
||||
`primeSummation(2000000)` should return 142913828922.
|
||||
`primeSummation(2000000)` debería retornar 142913828922.
|
||||
|
||||
```js
|
||||
assert.strictEqual(primeSummation(2000000), 142913828922);
|
||||
@@ -60,22 +60,33 @@ primeSummation(2000000);
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
function primeSummation(n) {
|
||||
if (n < 3) { return 0 };
|
||||
let nums = [0, 0, 2];
|
||||
for (let i = 3; i < n; i += 2){
|
||||
nums.push(i);
|
||||
nums.push(0);
|
||||
}
|
||||
let sum = 2;
|
||||
for (let i = 3; i < n; i += 2){
|
||||
if (nums[i] !== 0){
|
||||
sum += nums[i];
|
||||
for (let j = i*i; j < n; j += i){
|
||||
nums[j] = 0;
|
||||
const NUM_PRIMES = 2000000;
|
||||
const PRIME_SEIVE = Array(Math.floor((NUM_PRIMES-1)/2)).fill(true);
|
||||
(function initPrimes(num) {
|
||||
const upper = Math.floor((num - 1) / 2);
|
||||
const sqrtUpper = Math.floor((Math.sqrt(num) - 1) / 2);
|
||||
for (let i = 0; i <= sqrtUpper; i++) {
|
||||
if (PRIME_SEIVE[i]) {
|
||||
// Mark value in PRIMES array
|
||||
const prime = 2 * i + 3;
|
||||
// Mark all multiples of this number as false (not prime)
|
||||
const primeSqaredIndex = 2 * i ** 2 + 6 * i + 3;
|
||||
for (let j = primeSqaredIndex; j < upper; j += prime) {
|
||||
PRIME_SEIVE[j] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
})(NUM_PRIMES);
|
||||
|
||||
function isOddNumberPrime(num) {
|
||||
return PRIME_SEIVE[(num - 3) / 2];
|
||||
}
|
||||
|
||||
function primeSummation(n) {
|
||||
let sum = 2;
|
||||
for (let i = 3; i < n; i += 2) {
|
||||
if (isOddNumberPrime(i)) sum += i;
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
```
|
||||
|
||||
+8
-8
@@ -1,14 +1,14 @@
|
||||
---
|
||||
id: 5900f3781000cf542c50fe8a
|
||||
title: 'Problem 11: Largest product in a grid'
|
||||
challengeType: 5
|
||||
title: 'Problema 11: Producto más grande en una cuadrícula'
|
||||
challengeType: 1
|
||||
forumTopicId: 301734
|
||||
dashedName: problem-11-largest-product-in-a-grid
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
|
||||
En la cuadrícula de 20×20 de abajo, cuatro números a lo largo de una línea diagonal han sido marcados en rojo.
|
||||
|
||||
<div style='text-align: center;'>
|
||||
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08<br>
|
||||
@@ -33,25 +33,25 @@ In the 20×20 grid below, four numbers along a diagonal line have been marked in
|
||||
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48<br>
|
||||
</div>
|
||||
|
||||
The product of these numbers is 26 × 63 × 78 × 14 = 1788696.
|
||||
El producto de estos números es 26 × 63 × 78 × 14 = 1788696.
|
||||
|
||||
What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in a given `arr` grid?
|
||||
¿Cuál es el mayor producto de cuatro números adyacentes en la misma dirección (hacia arriba, abajo, izquierda, derecha o diagonalmente) en una cuadrícula de `arr`?
|
||||
|
||||
# --hints--
|
||||
|
||||
`largestGridProduct(testGrid)` should return a number.
|
||||
`largestGridProduct(testGrid)` debería devolver un número.
|
||||
|
||||
```js
|
||||
assert(typeof largestGridProduct(testGrid) === 'number');
|
||||
```
|
||||
|
||||
`largestGridProduct(testGrid)` should return 14169081.
|
||||
`largestGridProduct(testGrid)` debería devolver 14169081.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largestGridProduct(testGrid), 14169081);
|
||||
```
|
||||
|
||||
`largestGridProduct(grid)` should return 70600674.
|
||||
`largestGridProduct(grid)` debería devolver 70600674.
|
||||
|
||||
```js
|
||||
assert.strictEqual(largestGridProduct(grid), 70600674);
|
||||
|
||||
+9
-9
@@ -1,25 +1,25 @@
|
||||
---
|
||||
id: 5900f3e91000cf542c50fefc
|
||||
title: 'Problem 125: Palindromic sums'
|
||||
challengeType: 5
|
||||
title: 'Problema 125: Sumas palindromicas'
|
||||
challengeType: 1
|
||||
forumTopicId: 301752
|
||||
dashedName: problem-125-palindromic-sums
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The palindromic number 595 is interesting because it can be written as the sum of consecutive squares: 62 + 72 + 82 + 92 + 102 + 112 + 122.
|
||||
El número palindromico 595 es interesante, pues puede escribirse como la suma de cuadrados consecutivos: $6^2 + 7^2 + 8^2 + 9^2 + 10^2 + 11^2 + 12^2$.
|
||||
|
||||
There are exactly eleven palindromes below one-thousand that can be written as consecutive square sums, and the sum of these palindromes is 4164. Note that 1 = 02 + 12 has not been included as this problem is concerned with the squares of positive integers.
|
||||
Hay exactamente once palindromes por debajo de un millar que se pueden escribir como sumas cuadradas consecutivas, y la suma de estos palindromes es 4164. Tenga en cuenta que $1 = 0^2 + 1^2$ no ha sido incluido ya que este problema se refiere a los cuadrados de enteros positivos.
|
||||
|
||||
Find the sum of all the numbers less than 108 that are both palindromic and can be written as the sum of consecutive squares.
|
||||
Encuentre la suma de todos los números menores a $10^8$ que son palindromicos y pueden ser escritos como la suma de cuadrados consecutivos.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler125()` should return 2906969179.
|
||||
`palindromicSums()` debe devolver `2906969179`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler125(), 2906969179);
|
||||
assert.strictEqual(palindromicSums(), 2906969179);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@@ -27,12 +27,12 @@ assert.strictEqual(euler125(), 2906969179);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler125() {
|
||||
function palindromicSums() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler125();
|
||||
palindromicSums();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
+9
-9
@@ -1,25 +1,25 @@
|
||||
---
|
||||
id: 5900f3f11000cf542c50ff03
|
||||
title: 'Problem 132: Large repunit factors'
|
||||
challengeType: 5
|
||||
title: 'Problema 132: Factorización de grandes repitunos'
|
||||
challengeType: 1
|
||||
forumTopicId: 301760
|
||||
dashedName: problem-132-large-repunit-factors
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A number consisting entirely of ones is called a repunit. We shall define R(k) to be a repunit of length k.
|
||||
Un número que consiste enteramente en unos se llama repituno. Definiremos que $R(k)$ para ser un repituno de longitud $k$.
|
||||
|
||||
For example, R(10) = 1111111111 = 11×41×271×9091, and the sum of these prime factors is 9414.
|
||||
Por ejemplo, $R(10) = 1111111111 = 11 × 41 × 271 × 9091$, y la suma de estos factores primos es 9414.
|
||||
|
||||
Find the sum of the first forty prime factors of R(109).
|
||||
Encuentra la suma de los primeros cuarenta factores primos de $R({10}^9)$.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler132()` should return 843296.
|
||||
`largeRepunitFactors()` debe devolver `843296`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler132(), 843296);
|
||||
assert.strictEqual(largeRepunitFactors(), 843296);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@@ -27,12 +27,12 @@ assert.strictEqual(euler132(), 843296);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler132() {
|
||||
function largeRepunitFactors() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler132();
|
||||
largeRepunitFactors();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
+14
-8
@@ -1,23 +1,29 @@
|
||||
---
|
||||
id: 5900f3f61000cf542c50ff09
|
||||
title: 'Problem 138: Special isosceles triangles'
|
||||
challengeType: 5
|
||||
title: 'Problema 138: Triángulos de isóceles especiales'
|
||||
challengeType: 1
|
||||
forumTopicId: 301766
|
||||
dashedName: problem-138-special-isosceles-triangles
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Consider the isosceles triangle with base length, b = 16, and legs, L = 17.
|
||||
Considere el triángulo de isóceles con longitud base, $b = 16$, y lados, $L = 17$.
|
||||
|
||||
By using the Pythagorean theorem it can be seen that the height of the triangle, h = √(172 − 82) = 15, which is one less than the base length. With b = 272 and L = 305, we get h = 273, which is one more than the base length, and this is the second smallest isosceles triangle with the property that h = b ± 1. Find ∑ L for the twelve smallest isosceles triangles for which h = b ± 1 and b, L are positive integers.
|
||||
<img class="img-responsive center-block" alt="triángulo isóceles con bordes llamados L - dos bordes con la misma longitud y base del triángulo como b; y altura del triángulo - h desde la base del triángulo hasta el ángulo entre los bordes L" src="https://cdn.freecodecamp.org/curriculum/project-euler/special-isosceles-triangles.png" style="background-color: white; padding: 10px;" />
|
||||
|
||||
Usando el teorema Pitágórico, se puede ver que la altura del triángulo, $h = \sqrt{{17}^2 8^2} = 15$, que es una longitud menor que la de la base.
|
||||
|
||||
Con $b = 272$ y $L = 305$, obtenemos $h = 273$, que es uno más que la longitud base, y este es el segundo triángulo isóceles más pequeño con la propiedad $h = b ± 1$.
|
||||
|
||||
Encuentra $\sum{L}$ para los doce triángulos de isócelas más pequeños para los cuales $h = b ± 1$ y $b$, $L$ son enteros positivos.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler138()` should return 1118049290473932.
|
||||
`isoscelesTriangles()` debe devolver `1118049290473932`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler138(), 1118049290473932);
|
||||
assert.strictEqual(isoscelesTriangles(), 1118049290473932);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@@ -25,12 +31,12 @@ assert.strictEqual(euler138(), 1118049290473932);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler138() {
|
||||
function isoscelesTriangles() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler138();
|
||||
isoscelesTriangles();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
+17
-11
@@ -1,29 +1,35 @@
|
||||
---
|
||||
id: 5900f42b1000cf542c50ff3e
|
||||
title: 'Problem 191: Prize Strings'
|
||||
challengeType: 5
|
||||
title: 'Problema N° 191: Cadenas de premios'
|
||||
challengeType: 1
|
||||
forumTopicId: 301829
|
||||
dashedName: problem-191-prize-strings
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
A particular school offers cash rewards to children with good attendance and punctuality. If they are absent for three consecutive days or late on more than one occasion then they forfeit their prize.
|
||||
Una escuela ofrece premios en efectivo a los niños que asistan todos los días y sean puntuales. Si no asisten por tres días consecutivos o lleguen tarde en más de una ocasión, entonces pierden su premio.
|
||||
|
||||
During an n-day period a trinary string is formed for each child consisting of L's (late), O's (on time), and A's (absent).
|
||||
Durante el día se forma una cadena trinaria (Trinary string) para cada niño que consiste en L's (Llegada tarde), O's (A tiempo), y A's (No asistió).
|
||||
|
||||
Although there are eighty-one trinary strings for a 4-day period that can be formed, exactly forty-three strings would lead to a prize:
|
||||
Aunque hay 83 cadenas trinarias posibles durante 4 días, exactamente 43 cadenas llevarían a un premio:
|
||||
|
||||
OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA LAOO LAOA LAAO
|
||||
```
|
||||
OOOO OOOA OOOL OOAO OOAA OOAL OOLO OOLA OAOO OAOA
|
||||
OAOL OAAO OAAL OALO OALA OLOO OLOA OLAO OLAA AOOO
|
||||
AOOA AOOL AOAO AOAA AOAL AOLO AOLA AAOO AAOA AAOL
|
||||
AALO AALA ALOO ALOA ALAO ALAA LOOO LOOA LOAO LOAA
|
||||
LAOO LAOA LAAO
|
||||
```
|
||||
|
||||
How many "prize" strings exist over a 30-day period?
|
||||
¿Cuántas cadenas o strings de "premios" existen durante un período de 30 días?
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler191()` should return 1918080160.
|
||||
`prizeStrings()` debería devolver `1918080160`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler191(), 1918080160);
|
||||
assert.strictEqual(prizeStrings(), 1918080160);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@@ -31,12 +37,12 @@ assert.strictEqual(euler191(), 1918080160);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler191() {
|
||||
function prizeStrings() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler191();
|
||||
prizeStrings();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
+21
-15
@@ -1,37 +1,43 @@
|
||||
---
|
||||
id: 5900f4301000cf542c50ff42
|
||||
title: 'Problem 196: Prime triplets'
|
||||
challengeType: 5
|
||||
title: 'Problema 196: Triplete de números primos'
|
||||
challengeType: 1
|
||||
forumTopicId: 301834
|
||||
dashedName: problem-196-prime-triplets
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Build a triangle from all positive integers in the following way:
|
||||
Construye un triángulo de todos los enteros positivos de la siguiente manera:
|
||||
|
||||
1 2 3 4 5 6 7 8 9 1011 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 2829 30 31 32 33 34 35 3637 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 . . .
|
||||
$$\begin{array}{rrr} & 1 \\\\
|
||||
& \color{red}{2} & \color{red}{3} \\\\ & 4 & \color{red}{5} & 6 \\\\
|
||||
& \color{red}{7} & 8 & 9 & 10 \\\\ & \color{red}{11} & 12 & \color{red}{13} & 14 & 15 \\\\
|
||||
& 16 & \color{red}{17} & 18 & \color{red}{19} & 20 & 21 \\\\ & 22 & \color{red}{23} & 24 & 25 & 26 & 27 & 28 \\\\
|
||||
& \color{red}{29} & 30 & \color{red}{31} & 32 & 33 & 34 & 35 & 36 \\\\ & \color{red}{37} & 38 & 39 & 40 & \color{red}{41} & 42 & \color{red}{43} & 44 & 45 \\\\
|
||||
& 46 & \color{red}{47} & 48 & 49 & 50 & 51 & 52 & \color{red}{53} & 54 & 55 \\\\ & 56 & 57 & 58 & \color{red}{59} & 60 & \color{red}{61} & 62 & 63 & 64 & 65 & 66 \\\\
|
||||
& \cdots \end{array}$$
|
||||
|
||||
Each positive integer has up to eight neighbours in the triangle.
|
||||
Cada entero positivo tiene hasta ocho vecinos en el triángulo.
|
||||
|
||||
A set of three primes is called a prime triplet if one of the three primes has the other two as neighbours in the triangle.
|
||||
Un conjunto de tres primos se llama triplete si uno de los tres primos tiene los otros dos como vecinos en el triángulo.
|
||||
|
||||
For example, in the second row, the prime numbers 2 and 3 are elements of some prime triplet.
|
||||
Por ejemplo, en la segunda fila, los números primos 2 y 3 son elementos de algún triplete primo.
|
||||
|
||||
If row 8 is considered, it contains two primes which are elements of some prime triplet, i.e. 29 and 31. If row 9 is considered, it contains only one prime which is an element of some prime triplet: 37.
|
||||
Si se considera la fila 8, contiene dos primos que son elementos de algún triplete primo, es decir, 29 y 31. Si se considera la fila 9, sólo contiene un número primo que es uno de los elementos de algún triplete primo: 37.
|
||||
|
||||
Define S(n) as the sum of the primes in row n which are elements of any prime triplet. Then S(8)=60 and S(9)=37.
|
||||
Define $S(n)$ como la suma de los primos en la fila $n$ que son elementos de cualquier triplete primo. Entonces $S(8) = 60$ y $S(9) = 37$.
|
||||
|
||||
You are given that S(10000)=950007619.
|
||||
Tienes que $S(10000) = 950007619$.
|
||||
|
||||
Find S(5678027) + S(7208785).
|
||||
Calcula $S(5678027) + S(7208785)$.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler196()` should return 322303240771079940.
|
||||
`primeTriplets()` debería devolver `322303240771079940`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler196(), 322303240771079940);
|
||||
assert.strictEqual(primeTriplets(), 322303240771079940);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@@ -39,12 +45,12 @@ assert.strictEqual(euler196(), 322303240771079940);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler196() {
|
||||
function primeTriplets() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler196();
|
||||
primeTriplets();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
+13
-13
@@ -1,33 +1,33 @@
|
||||
---
|
||||
id: 5900f4481000cf542c50ff5a
|
||||
title: 'Problem 219: Skew-cost coding'
|
||||
challengeType: 5
|
||||
title: 'Problema 219: Código de coste sesgado'
|
||||
challengeType: 1
|
||||
forumTopicId: 301861
|
||||
dashedName: problem-219-skew-cost-coding
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Let A and B be bit strings (sequences of 0's and 1's).
|
||||
Que $A$ y $B$ sean cadenas de bits (secuencias de 0 y 1's).
|
||||
|
||||
If A is equal to the leftmost length(A) bits of B, then A is said to be a prefix of B.
|
||||
Si $A$ es igual a la <u>izquierda</u>más larga($A$) de bits de $B$, entonces se dice que $A$ es un prefijo de $B$.
|
||||
|
||||
For example, 00110 is a prefix of 001101001, but not of 00111 or 100110.
|
||||
Por ejemplo, 00110 es un prefijo de <u>00110</u>1001, pero no de 00111 o 100110.
|
||||
|
||||
A prefix-free code of size n is a collection of n distinct bit strings such that no string is a prefix of any other. For example, this is a prefix-free code of size 6:
|
||||
Un código sin prefijo de tamaño $n$ es una colección de $n$ cadenas de bits distintas tales que ninguna cadena es un prefijo de cualquier otra. Por ejemplo, este es un código sin prefijo de tamaño 6:
|
||||
|
||||
0000, 0001, 001, 01, 10, 11
|
||||
$$0000, 0001, 001, 01, 10, 11$$
|
||||
|
||||
Now suppose that it costs one penny to transmit a '0' bit, but four pence to transmit a '1'. Then the total cost of the prefix-free code shown above is 35 pence, which happens to be the cheapest possible for the skewed pricing scheme in question. In short, we write Cost(6) = 35.
|
||||
Ahora supongamos que cuesta un centavo transmitir un bit '0', pero cuatro centavos transmitir un '1'. Entonces el costo total del código sin prefijo que se muestra arriba es 35 centavos, que es lo más barato posible para el sistema de precios sesgados en cuestión. En resumen, escribimos $Cost(6) = 35$.
|
||||
|
||||
What is Cost(109) ?
|
||||
¿Qué es $Cost(10^9)$?
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler219()` should return 64564225042.
|
||||
`skewCostCoding()` debería devolver `64564225042`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler219(), 64564225042);
|
||||
assert.strictEqual(skewCostCoding(), 64564225042);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@@ -35,12 +35,12 @@ assert.strictEqual(euler219(), 64564225042);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler219() {
|
||||
function skewCostCoding() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler219();
|
||||
skewCostCoding();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
+16
-11
@@ -1,29 +1,34 @@
|
||||
---
|
||||
id: 5900f51d1000cf542c51002f
|
||||
title: 'Problem 433: Steps in Euclid''s algorithm'
|
||||
challengeType: 5
|
||||
title: 'Problema 433: Pasos en el algoritmo de Euclides'
|
||||
challengeType: 1
|
||||
forumTopicId: 302104
|
||||
dashedName: problem-433-steps-in-euclids-algorithm
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Let E(x0, y0) be the number of steps it takes to determine the greatest common divisor of x0 and y0 with Euclid's algorithm. More formally:x1 = y0, y1 = x0 mod y0xn = yn-1, yn = xn-1 mod yn-1
|
||||
Sea $E(x_0, y_0)$ el número de pasos que se necesitan para determinar el divisor común más grande de $x_0$ y $y_0$ con el algoritmo de Euclides. Más formalmente:
|
||||
|
||||
E(x0, y0) is the smallest n such that yn = 0.
|
||||
$$\begin{align} & x_1 = y_0, y_1 = x_0\bmod y_0 \\\\
|
||||
& x_n = y_{n - 1}, y_n = x_{n - 1}\bmod y_{n - 1} \end{align}$$
|
||||
|
||||
We have E(1,1) = 1, E(10,6) = 3 and E(6,10) = 4.
|
||||
$E(x_0, y_0)$ es el $n$ más pequeño tal que $y_n = 0$.
|
||||
|
||||
Define S(N) as the sum of E(x,y) for 1 ≤ x,y ≤ N. We have S(1) = 1, S(10) = 221 and S(100) = 39826.
|
||||
Tenemos $E(1, 1) = 1$, $E(10, 6) = 3$ y $E(6, 10) = 4$.
|
||||
|
||||
Find S(5·106).
|
||||
Define $S(N)$ como la suma de $E(x, y)$ para $1 ≤ x$, $y ≤ N$.
|
||||
|
||||
Tenemos $S(1) = 1$, $S(10) = 221$ y $S(100) = 39\\,826$.
|
||||
|
||||
Calcula $S(5 \times {10}^6)$.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler433()` should return 326624372659664.
|
||||
`stepsInEuclidsAlgorithm()` debería devolver `326624372659664`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler433(), 326624372659664);
|
||||
assert.strictEqual(stepsInEuclidsAlgorithm(), 326624372659664);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@@ -31,12 +36,12 @@ assert.strictEqual(euler433(), 326624372659664);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler433() {
|
||||
function stepsInEuclidsAlgorithm() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler433();
|
||||
stepsInEuclidsAlgorithm();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
+11
-11
@@ -1,29 +1,29 @@
|
||||
---
|
||||
id: 5900f5361000cf542c510048
|
||||
title: 'Problem 457: A polynomial modulo the square of a prime'
|
||||
challengeType: 5
|
||||
title: 'Problema 457: Un módulo polinomial al cuadrado de un primo'
|
||||
challengeType: 1
|
||||
forumTopicId: 302131
|
||||
dashedName: problem-457-a-polynomial-modulo-the-square-of-a-prime
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Let f(n) = n2 - 3n - 1.
|
||||
Sean: $f(n) = n^2 - 3n - 1$.
|
||||
|
||||
Let p be a prime.
|
||||
$p$ un primo.
|
||||
|
||||
Let R(p) be the smallest positive integer n such that f(n) mod p2 = 0 if such an integer n exists, otherwise R(p) = 0.
|
||||
$R(p)$ el entero positivo más pequeño $n$ tal que $f(n)\bmod p^2 = 0$ si existe un entero $n$, de lo contrario $R(p) = 0$.
|
||||
|
||||
Let SR(L) be ∑R(p) for all primes not exceeding L.
|
||||
$SR(L)$ $\sum R(p)$ para todos los primos que no superen $L$.
|
||||
|
||||
Find SR(107).
|
||||
Calcular $SR({10}^7)$.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler457()` should return 2647787126797397000.
|
||||
`polynomialModuloSquareOfPrime()` debería retornar `2647787126797397000`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler457(), 2647787126797397000);
|
||||
assert.strictEqual(polynomialModuloSquareOfPrime(), 2647787126797397000);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@@ -31,12 +31,12 @@ assert.strictEqual(euler457(), 2647787126797397000);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler457() {
|
||||
function polynomialModuloSquareOfPrime() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler457();
|
||||
polynomialModuloSquareOfPrime();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
+10
-10
@@ -1,27 +1,27 @@
|
||||
---
|
||||
id: 5900f5361000cf542c510049
|
||||
title: 'Problem 458: Permutations of Project'
|
||||
challengeType: 5
|
||||
title: 'Problema 458: Permutaciones de "Project"'
|
||||
challengeType: 1
|
||||
forumTopicId: 302132
|
||||
dashedName: problem-458-permutations-of-project
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Consider the alphabet A made out of the letters of the word "project": A={c,e,j,o,p,r,t}.
|
||||
Considere el alfabeto $A$ hecho de las letras de la palabra `project`: $A = \\{c, e, j, o, p, r, t\\}$.
|
||||
|
||||
Let T(n) be the number of strings of length n consisting of letters from A that do not have a substring that is one of the 5040 permutations of "project".
|
||||
Sea $T(n)$ el número de cadenas de longitud $n$ consistentes en letras de $A$ que no tengan una subcadena que sea una de las 5040 permutaciones del `project`.
|
||||
|
||||
T(7)=77-7!=818503.
|
||||
$T(7) = 7^7 - 7! = 818\\,503$.
|
||||
|
||||
Find T(1012). Give the last 9 digits of your answer.
|
||||
Calcular $T({10}^{12})$. Proporcione los últimos 9 dígitos de su respuesta.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler458()` should return 423341841.
|
||||
`permutationsOfProject()` debería retornar `423341841`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler458(), 423341841);
|
||||
assert.strictEqual(permutationsOfProject(), 423341841);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@@ -29,12 +29,12 @@ assert.strictEqual(euler458(), 423341841);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler458() {
|
||||
function permutationsOfProject() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler458();
|
||||
permutationsOfProject();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
+12
-12
@@ -1,50 +1,50 @@
|
||||
---
|
||||
id: 5900f53a1000cf542c51004c
|
||||
title: 'Problem 461: Almost Pi'
|
||||
challengeType: 5
|
||||
title: 'Problema 461: Casi Pi'
|
||||
challengeType: 1
|
||||
forumTopicId: 302136
|
||||
dashedName: problem-461-almost-pi
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Let `f(k, n)` = $e^\frac{k}{n} - 1$, for all non-negative integers `k`.
|
||||
Sea `f(k, n)` = $e^\frac{k}{n} - 1$, para todos los enteros no negativos `k`.
|
||||
|
||||
Remarkably, `f(6, 200) + f(75, 200) + f(89, 200) + f(226, 200)` = 3.1415926… ≈ π.
|
||||
Remostradamente, `f(6, 200) + f(75, 200) + f(89, 200) + f(226, 200)` = 3.1415926… ≈ π.
|
||||
|
||||
In fact, it is the best approximation of π of the form `f(a, 200) + f(b, 200) + f(c, 200) + f(d, 200)`.
|
||||
De hecho, es la mejor aproximación de la forma `f(a, 200) + f(b, 200) + f(c, 200) + f(d, 200)`.
|
||||
|
||||
Let `almostPi(n)` = a<sup>2</sup> + b<sup>2</sup> + c<sup>2</sup> + d<sup>2</sup> for a, b, c, d that minimize the error: $\lvert f(a,n) + f(b,n) + f(c,n) + f(d,n) - \Pi\rvert$
|
||||
Deja `almostPi(n)` = a<sup>2</sup> + b<sup>2</sup> + c<sup>2</sup> + d<sup>2</sup> por a, b, c, d que minimiza el error: $\lvert f(a,n) + f(b,n) + f(c,n) + f(d,n) - \Pi\rvert$
|
||||
|
||||
You are given `almostPi(200)` = 6<sup>2</sup> + 75<sup>2</sup> + 89<sup>2</sup> + 226<sup>2</sup> = 64658.
|
||||
Te han dado `almostPi(200)` = 6<sup>2</sup> + 75<sup>2</sup> + 89<sup>2</sup> + 226<sup>2</sup> = 64658.
|
||||
|
||||
# --hints--
|
||||
|
||||
`almostPi` should be a function.
|
||||
`timesFive` debe ser una función.
|
||||
|
||||
```js
|
||||
assert(typeof almostPi === 'function')
|
||||
```
|
||||
|
||||
`almostPi` should return a number.
|
||||
`abTest()` debe devolver un número.
|
||||
|
||||
```js
|
||||
assert.strictEqual(typeof almostPi(10), 'number');
|
||||
```
|
||||
|
||||
`almostPi(29)` should return `1208`.
|
||||
`abTest(29)` debe devolver `1208`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(almostPi(29), 1208);
|
||||
```
|
||||
|
||||
`almostPi(50)` should return `4152`.
|
||||
`abTest(50)` debe devolver `4152`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(almostPi(50), 4152);
|
||||
```
|
||||
|
||||
`almostPi(200)` should return `64658`.
|
||||
`abTest(200)` debe devolver `64658`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(almostPi(200), 64658);
|
||||
|
||||
+19
-13
@@ -1,35 +1,41 @@
|
||||
---
|
||||
id: 5900f53b1000cf542c51004d
|
||||
title: 'Problem 462: Permutation of 3-smooth numbers'
|
||||
challengeType: 5
|
||||
title: 'Problema 462: Permutación de números 3 suaves'
|
||||
challengeType: 1
|
||||
forumTopicId: 302137
|
||||
dashedName: problem-462-permutation-of-3-smooth-numbers
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
<!-- TODO use MathJax -->
|
||||
Un número 3-suave es un entero que no tiene un factor primo mayor que 3. Para un entero $N$, definimos $S(N)$ como el conjunto de números 3 suaves menores o iguales a $N$. Por ejemplo, $S(20) = \\{1, 2, 3, 4, 6, 8, 9, 12, 16, 18\\}$.
|
||||
|
||||
A 3-smooth number is an integer which has no prime factor larger than 3. For an integer N, we define S(N) as the set of 3-smooth numbers less than or equal to N . For example, S(20) = { 1, 2, 3, 4, 6, 8, 9, 12, 16, 18 }.
|
||||
Definimos $F(N)$ como el número de permutaciones de $S(N)$ en el cual cada elemento viene después de todos sus divisores adecuados.
|
||||
|
||||
We define F(N) as the number of permutations of S(N) in which each element comes after all of its proper divisors.
|
||||
|
||||
This is one of the possible permutations for N = 20.
|
||||
Esta es una de las posibles permutaciones para $N = 20$.
|
||||
|
||||
- 1, 2, 4, 3, 9, 8, 16, 6, 18, 12.
|
||||
|
||||
This is not a valid permutation because 12 comes before its divisor 6.
|
||||
Esto no es una permutación válida, porque 12 se anteponen a su divisor 6.
|
||||
|
||||
- 1, 2, 4, 3, 9, 8, 12, 16, 6, 18.
|
||||
|
||||
We can verify that F(6) = 5, F(8) = 9, F(20) = 450 and F(1000) ≈ 8.8521816557e21. Find F(1018). Give as your answer its scientific notation rounded to ten digits after the decimal point. When giving your answer, use a lowercase e to separate mantissa and exponent. E.g. if the answer is 112,233,445,566,778,899 then the answer format would be 1.1223344557e17.
|
||||
Podemos verificar que $F(6) = 5$, $F(8) = 9$, $F(20) = 450$ y $F(1000).8521816557e\\,21$.
|
||||
|
||||
Calcular $F({10}^{18})$. Dar como respuesta una cadena en su noción científica redondeada a diez dígitos después del punto decimal. Al dar tu respuesta, usa una minúscula `e` para separar mantissa y exponente. Ejemplo. si la respuesta es $112\\,233\\,445\\,566\\,778\\,899$, entonces el formato de respuesta sería `1.1223344557e17`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler462()` should return Infinity.
|
||||
`permutationOf3SmoothNumbers()` debería devolver una cadena.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler462(), Infinity);
|
||||
assert.strictEqual(typeof permutationOf3SmoothNumbers() === 'string');
|
||||
```
|
||||
|
||||
`permutationOf3SmoothNumbers()` debe devolver la cadena `5.5350769703e1512`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(permutationOf3SmoothNumbers(), '5.5350769703e1512');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@@ -37,12 +43,12 @@ assert.strictEqual(euler462(), Infinity);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler462() {
|
||||
function permutationOf3SmoothNumbers() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler462();
|
||||
permutationOf3SmoothNumbers();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
+9
-9
@@ -1,14 +1,14 @@
|
||||
---
|
||||
id: 5900f3cc1000cf542c50fedf
|
||||
title: 'Problem 96: Su Doku'
|
||||
challengeType: 5
|
||||
title: 'Problema 96: Sudoku'
|
||||
challengeType: 1
|
||||
forumTopicId: 302213
|
||||
dashedName: problem-96-su-doku
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Su Doku (Japanese meaning *number place*) is the name given to a popular puzzle concept. Its origin is unclear, but credit must be attributed to Leonhard Euler who invented a similar, and much more difficult, puzzle idea called Latin Squares. The objective of Su Doku puzzles, however, is to replace the blanks (or zeros) in a 9 by 9 grid in such that each row, column, and 3 by 3 box contains each of the digits 1 to 9. Below is an example of a typical starting puzzle grid and its solution grid.
|
||||
Sudoku (japonés que significa *número sólo*) es el nombre dado a un concepto de rompecabezas popular. Su origen no está claro, pero el crédito debe ser atribuido a Leonhard Euler, quien inventó una idea similar y mucho más difícil de rompecabezas llamada Plaza Latina. Sin embargo, el objetivo del Sudoku es reemplazar los blancos (o ceros) en una cuadrícula de 9 por 9 números en cada fila, agrupados en cajas de 3 x 3, cada caja contiene los dígitos del 1 a 9. A continuación se muestra un ejemplo típico del inicio y solución de un rompecabezas.
|
||||
|
||||
<div style="margin: auto; background-color: white; padding: 10px; width: 80%; text-align: center;">
|
||||
<table border="0" cellpadding="0" cellspacing="0" align="center">
|
||||
@@ -100,27 +100,27 @@ Su Doku (Japanese meaning *number place*) is the name given to a popular puzzle
|
||||
</table>
|
||||
</div>
|
||||
|
||||
A well constructed Su Doku puzzle has a unique solution and can be solved by logic, although it may be necessary to employ "guess and test" methods in order to eliminate options (there is much contested opinion over this). The complexity of the search determines the difficulty of the puzzle; the example above is considered easy because it can be solved by straight forward direct deduction.
|
||||
Un Sudoku bien construido tiene una solución única y puede resolverse por lógica, aunque puede ser necesario emplear métodos de "adivinar y probar" para eliminar opciones (hay muchas opiniones diversas sobre el tema). La complejidad de las búsquedas determina la dificultad del rompecabezas; el ejemplo anterior se considera fácil porque puede ser resuelto por una sencilla deducción.
|
||||
|
||||
The `puzzlesArr` array contains different Su Doku puzzle strings ranging in difficulty, but all with unique solutions.
|
||||
El array `puzzlesArr` contiene diferentes combinaciones de Sudoku que varían en dificultades, pero todas con una solución única.
|
||||
|
||||
By solving all puzzles in `puzzlesArr`, find the sum of the 3-digit numbers found in the top left corner of each solution grid; for example, 483 is the 3-digit number found in the top left corner of the solution grid above.
|
||||
Al resolver todos los rompecabezas de `puzzlesArr`, se encuentra la suma de los números de 3 dígitos situados en la esquina superior izquierda de cada cuadrícula de solución; por ejemplo, 483 es el número de 3 dígitos que se encuentra en la esquina superior izquierda de la cuadrícula de la solución anterior.
|
||||
|
||||
# --hints--
|
||||
|
||||
`suDoku(testPuzzles1)` should return a number.
|
||||
`suDoku(testPuzzles1)` debe devolver un número.
|
||||
|
||||
```js
|
||||
assert(typeof suDoku(_testPuzzles1) === 'number');
|
||||
```
|
||||
|
||||
`suDoku(testPuzzles1)` should return `1190`.
|
||||
`suDoku(testPuzzles1)` debe devolver `1190`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(suDoku(_testPuzzles1), 1190);
|
||||
```
|
||||
|
||||
`suDoku(testPuzzles2)` should return `24702`.
|
||||
`suDoku(testPuzzles2)` debe devolver `24702`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(suDoku(_testPuzzles2), 24702);
|
||||
|
||||
@@ -1,34 +1,34 @@
|
||||
---
|
||||
id: 594810f028c0303b75339acb
|
||||
title: 100 doors
|
||||
challengeType: 5
|
||||
title: 100 puertas
|
||||
challengeType: 1
|
||||
forumTopicId: 302217
|
||||
dashedName: 100-doors
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
There are 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, visit every door and 'toggle' the door (if the door is closed, open it; if it is open, close it). The second time, only visit every 2nd door (i.e., door #2, #4, #6, ...) and toggle it. The third time, visit every 3rd door (i.e., door #3, #6, #9, ...), etc., until you only visit the 100th door.
|
||||
Hay 100 puertas seguidas que están cerradas inicialmente. Haz 100 pases por las puertas. La primera vez, visita cada puerta y "cambia" la puerta (si la puerta está cerrada, ábrela; si está abierta, ciérrela). La segunda vez, sólo visita cada 2da puerta (por ejemplo, la puerta #2, #4, #6, ...) y cámbiala. La tercera vez, visita cada 3ª puerta (por ejemplo, la puerta #3, #6, #9, ...), etc., hasta que sólo visite la puerta 100.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Implement a function to determine the state of the doors after the last pass. Return the final result in an array, with only the door number included in the array if it is open.
|
||||
Implementa una función para determinar el estado de las puertas después del último paso. Devuelve el resultado final en una matriz, con sólo el número de puerta incluido en la matriz si está abierta.
|
||||
|
||||
# --hints--
|
||||
|
||||
`getFinalOpenedDoors` should be a function.
|
||||
`getFinalOpenedDoors` debe ser una función.
|
||||
|
||||
```js
|
||||
assert(typeof getFinalOpenedDoors === 'function');
|
||||
```
|
||||
|
||||
`getFinalOpenedDoors` should return an array.
|
||||
`getFinalOpenedDoors` debe devolver una matriz.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(getFinalOpenedDoors(100)));
|
||||
```
|
||||
|
||||
`getFinalOpenedDoors` should produce the correct result.
|
||||
`getFinalOpenedDoors` debe producir el resultado correcto.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getFinalOpenedDoors(100), solution);
|
||||
|
||||
+15
-15
@@ -1,14 +1,14 @@
|
||||
---
|
||||
id: 594810f028c0303b75339acc
|
||||
title: ABC Problem
|
||||
challengeType: 5
|
||||
title: Problema ABC
|
||||
challengeType: 1
|
||||
forumTopicId: 302220
|
||||
dashedName: abc-problem
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
You are given a collection of ABC blocks (e.g., childhood alphabet blocks). There are 20 blocks with two letters on each block. A complete alphabet is guaranteed amongst all sides of the blocks. The sample collection of blocks:
|
||||
Te dan una colección de bloques ABC (por ejemplo, bloques de alfabeto infantil). Hay 20 bloques con dos letras en cada bloque. Se garantiza un alfabeto completo entre todos los lados de los bloques. La muestra de la colección de bloques:
|
||||
|
||||
<pre>(B O)
|
||||
(X K)
|
||||
@@ -34,60 +34,60 @@ You are given a collection of ABC blocks (e.g., childhood alphabet blocks). Ther
|
||||
|
||||
# --instructions--
|
||||
|
||||
Implement a function that takes a string (word) and determines whether the word can be spelled with the given collection of blocks.
|
||||
Implementa una función que toma una cadena (palabra) y determina si la palabra puede ser escrita con la colección dada de bloques.
|
||||
|
||||
Some rules to keep in mind:
|
||||
Algunas reglas a tener en cuenta:
|
||||
|
||||
<ul>
|
||||
<li>Once a letter on a block is used, that block cannot be used again.</li>
|
||||
<li>The function should be case-insensitive.</li>
|
||||
<li>Una vez que una letra de un bloque es usada, ese bloque no puede ser utilizado de nuevo.</li>
|
||||
<li>La función debería ser insensible a mayúsculas y minúsculas.</li>
|
||||
</ul>
|
||||
|
||||
# --hints--
|
||||
|
||||
`canMakeWord` should be a function.
|
||||
`canMakeWord` debe ser una función.
|
||||
|
||||
```js
|
||||
assert(typeof canMakeWord === 'function');
|
||||
```
|
||||
|
||||
`canMakeWord` should return a boolean.
|
||||
`canMakeWord` debe devolver un valor booleano.
|
||||
|
||||
```js
|
||||
assert(typeof canMakeWord('hi') === 'boolean');
|
||||
```
|
||||
|
||||
`canMakeWord("bark")` should return true.
|
||||
`canMakeWord("cork")` debe devolver verdadero.
|
||||
|
||||
```js
|
||||
assert(canMakeWord(words[0]));
|
||||
```
|
||||
|
||||
`canMakeWord("BooK")` should return false.
|
||||
`canMakeWord("BooK")` debe devolver falso.
|
||||
|
||||
```js
|
||||
assert(!canMakeWord(words[1]));
|
||||
```
|
||||
|
||||
`canMakeWord("TReAT")` should return true.
|
||||
`canMakeWord("TReAT")` debe devolver verdadero.
|
||||
|
||||
```js
|
||||
assert(canMakeWord(words[2]));
|
||||
```
|
||||
|
||||
`canMakeWord("COMMON")` should return false.
|
||||
`canMakeWord("COMMON")` debe devolver falso.
|
||||
|
||||
```js
|
||||
assert(!canMakeWord(words[3]));
|
||||
```
|
||||
|
||||
`canMakeWord("squAD")` should return true.
|
||||
`canMakeWord("squAD")` debe devolver verdadero.
|
||||
|
||||
```js
|
||||
assert(canMakeWord(words[4]));
|
||||
```
|
||||
|
||||
`canMakeWord("conFUSE")` should return true.
|
||||
`canMakeWord("conFUSE")` debe devolver verdadero.
|
||||
|
||||
```js
|
||||
assert(canMakeWord(words[5]));
|
||||
|
||||
+15
-15
@@ -1,62 +1,62 @@
|
||||
---
|
||||
id: 594810f028c0303b75339acd
|
||||
title: 'Abundant, deficient and perfect number classifications'
|
||||
challengeType: 5
|
||||
title: 'Clasificación de números abundante, deficiente y perfecta'
|
||||
challengeType: 1
|
||||
forumTopicId: 302221
|
||||
dashedName: abundant-deficient-and-perfect-number-classifications
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
These define three classifications of positive integers based on their proper divisors.
|
||||
Estos definen tres clasificaciones de enteros positivos basadas en sus divisores apropiados.
|
||||
|
||||
Let $P(n)$ be the sum of the proper divisors of `n` where proper divisors are all positive integers `n` other than `n` itself.
|
||||
Sea $P(n)$ la suma de los divisores apropiados de `n` donde los divisores apropiados son todos enteros positivos `n` distintos de `n` en sí mismo.
|
||||
|
||||
If `P(n) < n` then `n` is classed as `deficient`
|
||||
Si `P(n) < n` entonces `n` se clasifica como `deficient`
|
||||
|
||||
If `P(n) === n` then `n` is classed as `perfect`
|
||||
Si `P(n) === n` entonces `n` se clasifica como `perfect`
|
||||
|
||||
If `P(n) > n` then `n` is classed as `abundant`
|
||||
Si `P(n) > n` entonces `n` se clasifica como `abundant`
|
||||
|
||||
**Example**: `6` has proper divisors of `1`, `2`, and `3`. `1 + 2 + 3 = 6`, so `6` is classed as a perfect number.
|
||||
**Ejemplo**: `6` tiene los divisores apropiados `1`, `2`, y `3`. `1 + 2 + 3 = 6`, así que `6` está clasificado como un número perfecto.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Implement a function that calculates how many of the integers from `1` to `num` (inclusive) are in each of the three classes. Output the result as an array in the following format `[deficient, perfect, abundant]`.
|
||||
Implementar una función que calcule cuántos enteros de `1` a `num` (incluido) están en cada una de las tres clases. Muestra el resultado como una matriz en el siguiente formato `[deficient, perfect, abundant]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`getDPA` should be a function.
|
||||
`getDPA` debe ser una función.
|
||||
|
||||
```js
|
||||
assert(typeof getDPA === 'function');
|
||||
```
|
||||
|
||||
`getDPA(5000)` should return an array.
|
||||
`getDPA(5000)` debe devolver una matriz.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(getDPA(5000)));
|
||||
```
|
||||
|
||||
`getDPA(5000)` return array should have a length of `3`.
|
||||
`getDPA(5000)` la matriz de retorno debe tener una longitud de `3`.
|
||||
|
||||
```js
|
||||
assert(getDPA(5000).length === 3);
|
||||
```
|
||||
|
||||
`getDPA(5000)` should return `[3758, 3, 1239]`.
|
||||
`getDPA(5000)` debe devolver `[3758, 3, 1239]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getDPA(5000), [3758, 3, 1239]);
|
||||
```
|
||||
|
||||
`getDPA(10000)` should return `[7508, 4, 2488]`.
|
||||
`getDPA(10000)` debe devolver `[7508, 4, 2488]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getDPA(10000), [7508, 4, 2488]);
|
||||
```
|
||||
|
||||
`getDPA(20000)` should return `[15043, 4, 4953]`.
|
||||
`getDPA(20000)` debe devolver `[15043, 4, 4953]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(getDPA(20000), [15043, 4, 4953]);
|
||||
|
||||
+27
-2
@@ -1,14 +1,39 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7e03
|
||||
title: Desviación estándar acumulada
|
||||
challengeType: 5
|
||||
challengeType: 1
|
||||
forumTopicId: 302240
|
||||
dashedName: cumulative-standard-deviation
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Escriba una función que tome un array de números como parámetro y devuelva la [ desviación estándard](https://en.wikipedia.org/wiki/Standard_deviation) de la serie.
|
||||
Suponiendo que la población total de interés es de ocho estudiantes de una clase en particular. Para un conjunto finito de números, la desviación del estándar de población se encuentra tomando la raíz cuadrada del promedio de las desviaciones cuadradas de los valores restados de su valor medio. Las marcas de una clase de ocho estudiantes (es decir, una población estadística) son los siguientes ocho valores:
|
||||
|
||||
$2, 4, 4, 4, 5, 5, 7, 9$
|
||||
|
||||
Estos ocho puntos de datos tienen la media (media) de 5:
|
||||
|
||||
$$\mu ={\frac {2+4+4+4+5+5+7+9}{8}}={\frac {40}{8}}=5$$
|
||||
|
||||
Primero, calcular las desviaciones de cada punto de datos de la media y cuadra el resultado de cada una:
|
||||
|
||||
| Desviaciones de cada dato | Cuadra el resultado |
|
||||
| ------------------------- | -------------------- |
|
||||
| $(2-5)^{2}=(-3)^{2}=9$ | $(5-5)^{2}=0^{2}=0$ |
|
||||
| $(4-5)^{2}=(-1)^{2}=1$ | $(5-5)^{2}=0^{2}=0$ |
|
||||
| $(4-5)^{2}=(-1)^{2}=1$ | $(7-5)^{2}=2^{2}=4$ |
|
||||
| $(4-5)^{2}=(-1)^{2}=1$ | $(9-5)^{2}=4^{2}=16$ |
|
||||
|
||||
La variación es la media de estos valores:
|
||||
|
||||
$$\sigma ^{2}={\frac {9+1+1+1+0+0+4+16}{8}}={\frac {32}{8}}=4$$
|
||||
|
||||
y la desviación del estándar de población es igual a la raíz cuadrada de la varianza:
|
||||
|
||||
$$\sigma ={\sqrt {4}}=2$$
|
||||
|
||||
Escriba una función que tome una matríz de números como parámetros y devuelva la <a href="https://rosettacode.org/wiki/Standard_deviation" target="_blank" rel="noopener noreferrer nofollow"> desviación estándar</a> de las series.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
||||
+11
-11
@@ -1,50 +1,50 @@
|
||||
---
|
||||
id: 597f24c1dda4e70f53c79c81
|
||||
title: Fibonacci sequence
|
||||
challengeType: 5
|
||||
title: Secuencia Fibonacci
|
||||
challengeType: 1
|
||||
forumTopicId: 302268
|
||||
dashedName: fibonacci-sequence
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function to generate the <code>n<sup>th</sup></code> Fibonacci number.
|
||||
Escriba una función para generar el <code>n<sup>th</sup></code> número de Fibonacci.
|
||||
|
||||
The <code>n<sup>th</sup></code> Fibonacci number is given by:
|
||||
El <code>n<sup>th</sup></code> número de Fibonacci viene dado por:
|
||||
|
||||
<code>F<sub>n</sub> = F<sub>n-1</sub> + F<sub>n-2</sub></code>
|
||||
|
||||
The first two terms of the series are 0 and 1.
|
||||
Los dos primeros términos de la serie son 0 y 1.
|
||||
|
||||
Hence, the series is: 0, 1, 1, 2, 3, 5, 8, 13...
|
||||
Por lo tanto, la serie es: 0, 1, 1, 2, 3, 5, 8, 13...
|
||||
|
||||
# --hints--
|
||||
|
||||
`fibonacci` should be a function.
|
||||
`fibonacci` debe ser una función.
|
||||
|
||||
```js
|
||||
assert(typeof fibonacci === 'function');
|
||||
```
|
||||
|
||||
`fibonacci(2)` should return a number.
|
||||
`fibonacci(2)` debería devolver un número.
|
||||
|
||||
```js
|
||||
assert(typeof fibonacci(2) == 'number');
|
||||
```
|
||||
|
||||
`fibonacci(3)` should return 2.
|
||||
`fibonacci(3)` debería devolver 2.
|
||||
|
||||
```js
|
||||
assert.equal(fibonacci(3), 2);
|
||||
```
|
||||
|
||||
`fibonacci(5)` should return 5.
|
||||
`fibonacci(5)` debería devolver 5.
|
||||
|
||||
```js
|
||||
assert.equal(fibonacci(5), 5);
|
||||
```
|
||||
|
||||
`fibonacci(10)` should return 55.
|
||||
`fibonacci(10)` debería devolver 55.
|
||||
|
||||
```js
|
||||
assert.equal(fibonacci(10), 55);
|
||||
|
||||
+16
-16
@@ -1,77 +1,77 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7eb0
|
||||
title: I before E except after C
|
||||
challengeType: 5
|
||||
title: I antes de E excepto después de C
|
||||
challengeType: 1
|
||||
forumTopicId: 302288
|
||||
dashedName: i-before-e-except-after-c
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
The phrase ["I before E, except after C"](https://en.wikipedia.org/wiki/I before E except after C) is a widely known mnemonic which is supposed to help when spelling English words.
|
||||
**<a href="http://www.rosettacode.org/wiki/I_before_E_except_after_C" target="_blank" rel="noopener noreferrer nofollow">"I antes de E, excepto despúes de C" </a>** es una regla general para la ortografïa del idioma Inglés. Si uno no está seguro si una palabra se escribe con el digraph `ei` o `ie`, el rima sugiere que la orden correcta es `ie` a menos que la carta anterior sea `c`, en tal caso puede ser `ei`.
|
||||
|
||||
Using the words provided, check if the two sub-clauses of the phrase are plausible individually:
|
||||
Utilizando las palabras proporcionadas, verifica si las dos subcláusulas de la frase son plausibles individualmente:
|
||||
|
||||
<ol>
|
||||
<li>
|
||||
<i>"I before E when not preceded by C".</i>
|
||||
<i>"I antes de E cuando no está precedido por C".</i>
|
||||
</li>
|
||||
<li>
|
||||
<i>"E before I when preceded by C".</i>
|
||||
<i>"E antes que I cuando esté precedido por C".</i>
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
If both sub-phrases are plausible then the original phrase can be said to be plausible.
|
||||
Si ambas subfrases son plausibles, entonces se puede decir que la frase original es plausible.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that accepts a word and check if the word follows this rule. The function should return true if the word follows the rule and false if it does not.
|
||||
Escribe una función que acepte una palabra y comprueba si la palabra sigue esta regla. La función debería devolver verdadero si la palabra sigue la regla y falso si no lo hace.
|
||||
|
||||
# --hints--
|
||||
|
||||
`IBeforeExceptC` should be a function.
|
||||
`IBeforeExceptC` debería ser una función.
|
||||
|
||||
```js
|
||||
assert(typeof IBeforeExceptC == 'function');
|
||||
```
|
||||
|
||||
`IBeforeExceptC("receive")` should return a boolean.
|
||||
`IBeforeExceptC("receive")` debería devolver un booleano.
|
||||
|
||||
```js
|
||||
assert(typeof IBeforeExceptC('receive') == 'boolean');
|
||||
```
|
||||
|
||||
`IBeforeExceptC("receive")` should return `true`.
|
||||
`IBeforeExceptC("receive")` debería devolver `true`.
|
||||
|
||||
```js
|
||||
assert.equal(IBeforeExceptC('receive'), true);
|
||||
```
|
||||
|
||||
`IBeforeExceptC("science")` should return `false`.
|
||||
`IBeforeExceptC("science")` debería devolver `false`.
|
||||
|
||||
```js
|
||||
assert.equal(IBeforeExceptC('science'), false);
|
||||
```
|
||||
|
||||
`IBeforeExceptC("imperceivable")` should return `true`.
|
||||
`IBeforeExceptC("imperceivable")` debería devolver `true`.
|
||||
|
||||
```js
|
||||
assert.equal(IBeforeExceptC('imperceivable'), true);
|
||||
```
|
||||
|
||||
`IBeforeExceptC("inconceivable")` should return `true`.
|
||||
`IBeforeExceptC("inconceivable")` debería devolver `true`.
|
||||
|
||||
```js
|
||||
assert.equal(IBeforeExceptC('inconceivable'), true);
|
||||
```
|
||||
|
||||
`IBeforeExceptC("insufficient")` should return `false`.
|
||||
`IBeforeExceptC("insufficient")` debería devolver `false`.
|
||||
|
||||
```js
|
||||
assert.equal(IBeforeExceptC('insufficient'), false);
|
||||
```
|
||||
|
||||
`IBeforeExceptC("omniscient")` should return `false`.
|
||||
`IBeforeExceptC("omniscient")` debería devolver `false`.
|
||||
|
||||
```js
|
||||
assert.equal(IBeforeExceptC('omniscient'), false);
|
||||
|
||||
+26
-25
@@ -1,65 +1,66 @@
|
||||
---
|
||||
id: 5eb3e4af7d0e7b760b46cedc
|
||||
title: Set consolidation
|
||||
challengeType: 5
|
||||
title: Establecer consolidación
|
||||
challengeType: 1
|
||||
forumTopicId: 385319
|
||||
dashedName: set-consolidation
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
Given two sets of items then if any item is common to any set then the result of applying *consolidation* to those sets is a set of sets whose contents is:
|
||||
Dados dos conjuntos de elementos, y si cualquier elemento es común a cualquier conjunto entonces el resultado de aplicar *consolidación* a esos conjuntos es un conjunto de conjuntos cuyo contenido es:
|
||||
|
||||
<ul>
|
||||
<li>The two input sets if no common item exists between the two input sets of items.</li>
|
||||
<li>The single set that is the union of the two input sets if they share a common item.</li>
|
||||
<li>The two input sets if no common item exists between the two input sets of items.
|
||||
Las dos entradas se ajustan si no tienen elementos en común.</li>
|
||||
<li>El único conjunto que es la unión de los dos conjuntos de entrada si comparten un elemento común.</li>
|
||||
</ul>
|
||||
|
||||
Given N sets of items where N > 2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible. If N < 2 then consolidation has no strict meaning and the input can be returned.
|
||||
Dado N conjuntos de elementos donde N > 2 entonces el resultado es el mismo que reemplazando repetidamente todas las combinaciones de dos conjuntos por su consolidación hasta que no sea posible una mayor consolidación entre pares de conjunto. Si N < 2 entonces la consolidación no tiene un significado estricto y el valor de entrada puede ser devuelto.
|
||||
|
||||
Here are some examples:
|
||||
Aquí hay un par de ejemplos:
|
||||
|
||||
**Example 1:**
|
||||
**Ejemplo 1:**
|
||||
|
||||
Given the two sets `{A,B}` and `{C,D}` then there is no common element between the sets and the result is the same as the input.
|
||||
Dados los dos conjuntos `{A,B}` y `{C,D}`, entonces no hay un elemento común entre los conjuntos y el resultado es el mismo que la entrada.
|
||||
|
||||
**Example 2:**
|
||||
**Ejemplo 2:**
|
||||
|
||||
Given the two sets `{A,B}` and `{B,D}` then there is a common element `B` between the sets and the result is the single set `{B,D,A}`. (Note that order of items in a set is immaterial: `{A,B,D}` is the same as `{B,D,A}` and `{D,A,B}`, etc).
|
||||
Dados los dos conjuntos `{A,B}` y `{B,D}`, entonces hay un elemento común `B` entre los conjuntos y el resultado es el conjunto único `{B,D,A}`. (Tenga en cuenta que el orden de los artículos en un conjunto es inmaterial: `{A,B,D}` es lo mismo que `{B,D,A}` y `{D,A,B}`, etc.
|
||||
|
||||
**Example 3:**
|
||||
**Ejemplo 3:**
|
||||
|
||||
Given the three sets `{A,B}` and `{C,D}` and `{D,B}` then there is no common element between the sets `{A,B}` and `{C,D}` but the sets `{A,B}` and `{D,B}` do share a common element that consolidates to produce the result `{B,D,A}`. On examining this result with the remaining set, `{C,D}`, they share a common element and so consolidate to the final output of the single set `{A,B,C,D}`
|
||||
Dados los tres conjuntos `{A,B}`, `{C,D}` y `{D,B}` se conoce que no hay ningún elemento en común entre los conjuntos `{A,B}` y `{C,D}`, pero los conjuntos `{A,B}` y `{D,B}` sí comparten un elemento en común que se combina para producir el resultado `{B,D,A}`. Al analizar este resultado con el conjunto restante, `{C,D}`, comparten un elemento común y así consolidar el resultado final del conjunto único `{A,B,C,D}`
|
||||
|
||||
**Example 4:**
|
||||
**Ejemplo 4:**
|
||||
|
||||
The consolidation of the five sets:
|
||||
Consolidación de las cinco partes:
|
||||
|
||||
`{H,I,K}`, `{A,B}`, `{C,D}`, `{D,B}`, and `{F,G,H}`
|
||||
`{H,I,K}`, `{A,B}`, `{C,D}`, `{D,B}`, y `{F,G,H}`
|
||||
|
||||
Is the two sets:
|
||||
Son las dos partes:
|
||||
|
||||
`{A, C, B, D}`, and `{G, F, I, H, K}`
|
||||
`{A, C, B, D}`, y `{G, F, I, H, K}`
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes an array of strings as a parameter. Each string is represents a set with the characters representing the set elements. The function should return a 2D array containing the consolidated sets. Note: Each set should be sorted.
|
||||
Escribe uná función que tome un arreglo de cadenas como parámetro. Cada cadena es representa un establecer con los caracteres representan los establecer elementos. La función debe devolver un 2D arreglo que contenga los consolidado conjuntos. Nota: Cada conjunto debe ser ordenado.
|
||||
|
||||
# --hints--
|
||||
|
||||
`setConsolidation` should be a function.
|
||||
`setConsolidation` deberian ser un función.
|
||||
|
||||
```js
|
||||
assert(typeof setConsolidation === 'function');
|
||||
```
|
||||
|
||||
`setConsolidation(["AB", "CD"])` should return a array.
|
||||
`setConsolidation(["AB", "CD"])` deberian devolver un arreglo.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(setConsolidation(['AB', 'CD'])));
|
||||
```
|
||||
|
||||
`setConsolidation(["AB", "CD"])` should return `[["C", "D"], ["A", "B"]]`.
|
||||
`setConsolidation(["AB", "CD"])` deberian devolver `[["C", "D"], ["A", "B"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(setConsolidation(['AB', 'CD']), [
|
||||
@@ -68,19 +69,19 @@ assert.deepEqual(setConsolidation(['AB', 'CD']), [
|
||||
]);
|
||||
```
|
||||
|
||||
`setConsolidation(["AB", "BD"])` should return `[["A", "B", "D"]]`.
|
||||
`setConsolidation(["AB", "BD"])` deberian devolver `[["A", "B", "D"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(setConsolidation(['AB', 'BD']), [['A', 'B', 'D']]);
|
||||
```
|
||||
|
||||
`setConsolidation(["AB", "CD", "DB"])` should return `[["A", "B", "C", "D"]]`.
|
||||
`setConsolidation(["AB", "CD", "DB"])` deberian devolver `[["A", "B", "C", "D"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(setConsolidation(['AB', 'CD', 'DB']), [['A', 'B', 'C', 'D']]);
|
||||
```
|
||||
|
||||
`setConsolidation(["HIK", "AB", "CD", "DB", "FGH"])` should return `[["F", "G", "H", "I", "K"], ["A", "B", "C", "D"]]`.
|
||||
`setConsolidation(["HIK", "AB", "CD", "DB", "FGH"])` deberian devolver `[["F", "G", "H", "I", "K"], ["A", "B", "C", "D"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(setConsolidation(['HIK', 'AB', 'CD', 'DB', 'FGH']), [
|
||||
|
||||
+21
-23
@@ -1,82 +1,80 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8028
|
||||
title: Stern-Brocot sequence
|
||||
challengeType: 5
|
||||
title: Secuencia de Stern-Brocot
|
||||
challengeType: 1
|
||||
forumTopicId: 302324
|
||||
dashedName: stern-brocot-sequence
|
||||
---
|
||||
|
||||
# --description--
|
||||
|
||||
For this task, the Stern-Brocot sequence is to be generated by an algorithm similar to that employed in generating the [Fibonacci sequence](https://rosettacode.org/wiki/Fibonacci sequence).
|
||||
Para esta tarea, la secuencia Stern-Brocot debe ser generada por un algoritmo similar al empleado en la generación de la <a href="https://rosettacode.org/wiki/Fibonacci_sequence" target="_blank" rel="noopener noreferrer nofollow">secuencia Fibonacci</a>.
|
||||
|
||||
<ol>
|
||||
<li>The first and second members of the sequence are both 1:</li>
|
||||
<li>El primer y segundo miembros de la secuencia son ambos uno:</li>
|
||||
<ul><li>1, 1</li></ul>
|
||||
<li>Start by considering the second member of the sequence</li>
|
||||
<li>Sum the considered member of the sequence and its precedent, (1 + 1) = 2, and append it to the end of the
|
||||
sequence:</li>
|
||||
<li>Empezar por considerar el segundo miembro de la secuencia</li>
|
||||
<li>Sume el miembro considerado de la secuencia y su precedente, (1 + 1) = 2, y añádelo al final de la secuencia:</li>
|
||||
<ul><li>1, 1, 2</li></ul>
|
||||
<li>Append the considered member of the sequence to the end of the sequence:</li>
|
||||
<li>Añadir el miembro considerado de la secuencia al final de la secuencia:</li>
|
||||
<ul><li>1, 1, 2, 1</li></ul>
|
||||
<li>Consider the next member of the series, (the third member i.e. 2)</li>
|
||||
<li>Considere al siguiente miembro de la serie, (el tercer miembro es 2)</li>
|
||||
<li>GOTO 3 </li>
|
||||
<ul>
|
||||
<li></li>
|
||||
<li> ─── Expanding another loop we get: ───</li>
|
||||
<li> ► Expandiendo otro bucle que obtenemos: Adicionalmente</li>
|
||||
<li></li>
|
||||
</ul>
|
||||
<li>Sum the considered member of the sequence and its precedent, (2 + 1) = 3, and append it to the end of the
|
||||
sequence:</li>
|
||||
<li>Suma el miembro considerado de la secuencia y su precedente, (2 + 1) = 3, y añádelo al final de la secuencia:</li>
|
||||
<ul><li>1, 1, 2, 1, 3</li></ul>
|
||||
<li>Append the considered member of the sequence to the end of the sequence:</li>
|
||||
<ul><li>1, 1, 2, 1, 3, 2</li></ul>
|
||||
<li>Consider the next member of the series, (the fourth member i.e. 1)</li>
|
||||
<li>Agrega el miembro considerado de la secuencia al final de la secuencia:</li>
|
||||
<ul><li>1, 1, 2, 1, 3</li></ul>
|
||||
<li>Considere al siguiente miembro de la serie, (el cuarto miembro es decir, 1)</li>
|
||||
</ol>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a function that returns the position in the Stern-Brocot sequence at which $ n $ is first encountered, where the sequence is generated with the method outlined above. Note that this sequence uses 1 based indexing.
|
||||
Crear una función que devuelva la posición en la secuencia de Stern-Brocot en la que $ n $ se encuentra por primera vez, donde la secuencia se genera con el método descrito arriba. Tenga en cuenta que esta secuencia utiliza un índice basado en 1.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sternBrocot` should be a function.
|
||||
`sternBrocot` debe ser una función.
|
||||
|
||||
```js
|
||||
assert(typeof sternBrocot == 'function');
|
||||
```
|
||||
|
||||
`sternBrocot(2)` should return a number.
|
||||
`sternBrocot(2)` debe devolver un número.
|
||||
|
||||
```js
|
||||
assert(typeof sternBrocot(2) == 'number');
|
||||
```
|
||||
|
||||
`sternBrocot(2)` should return `3`.
|
||||
`sternBrocot(2)` debe devolver `3`.
|
||||
|
||||
```js
|
||||
assert.equal(sternBrocot(2), 3);
|
||||
```
|
||||
|
||||
`sternBrocot(3)` should return `5`.
|
||||
`sternBrocot(3)` debe devolver `5`.
|
||||
|
||||
```js
|
||||
assert.equal(sternBrocot(3), 5);
|
||||
```
|
||||
|
||||
`sternBrocot(5)` should return `11`.
|
||||
`sternBrocot(5)` debería devolver `11`.
|
||||
|
||||
```js
|
||||
assert.equal(sternBrocot(5), 11);
|
||||
```
|
||||
|
||||
`sternBrocot(7)` should return `19`.
|
||||
`sternBrocot(7)` debería devolver `19`.
|
||||
|
||||
```js
|
||||
assert.equal(sternBrocot(7), 19);
|
||||
```
|
||||
|
||||
`sternBrocot(10)` should return `39`.
|
||||
`sternBrocot(10)` debería devolver `39`.
|
||||
|
||||
```js
|
||||
assert.equal(sternBrocot(10), 39);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user