chore(i18n,curriculum): update translations (#43375)
This commit is contained in:
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bad87fee1348bd9aec908855
|
||||
title: Dale a cada elemento un id único
|
||||
title: Dale un id único a cada elemento
|
||||
challengeType: 0
|
||||
forumTopicId: 18191
|
||||
dashedName: give-each-element-a-unique-id
|
||||
@ -8,11 +8,11 @@ dashedName: give-each-element-a-unique-id
|
||||
|
||||
# --description--
|
||||
|
||||
También vamos a querer poder usar jQuery para apuntar a cada botón por su identificación única.
|
||||
También vamos a querer poder usar jQuery para seleccionar cada botón por su id único.
|
||||
|
||||
Da a cada uno de tus botones un id único, empezando con `target1` y terminando con `target6`.
|
||||
Dale a cada uno de tus botones un id único, empezando con `target1` y finalizando con `target6`.
|
||||
|
||||
Asegúrate de que `target1` a `target3` estén en `#left-well`, y `target4` a `target6` están en `#right-well`.
|
||||
Asegúrate de que `target1` a `target3` se encuentren en `#left-well` y `target4` a `target6` se encuentren en `#right-well`.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bad87fee1348bd9aec908746
|
||||
title: Aloja nuestra página dentro de un container-fluid de Bootstrap div
|
||||
title: Aloja nuestra página dentro de un container-fluid div de Bootstrap
|
||||
challengeType: 0
|
||||
forumTopicId: 18198
|
||||
dashedName: house-our-page-within-a-bootstrap-container-fluid-div
|
||||
@ -8,7 +8,7 @@ dashedName: house-our-page-within-a-bootstrap-container-fluid-div
|
||||
|
||||
# --description--
|
||||
|
||||
Ahora asegurémonos de que todo el contenido de tu página sea compatible con dispositivos móviles.
|
||||
Ahora vamos a asegurarnos que todo el contenido de tu página es mobile-responsive.
|
||||
|
||||
Anidemos tu elemento `h3` dentro de un elemento `div` con la clase `container-fluid`.
|
||||
|
||||
@ -20,7 +20,7 @@ Tu elemento `div` debe tener la clase `container-fluid`.
|
||||
assert($('div').hasClass('container-fluid'));
|
||||
```
|
||||
|
||||
Cada uno de tus elementos `div` deben tener etiquetas de cierre.
|
||||
Cada uno de tus elementos `div` debe tener etiquetas de cierre.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bad87fee1348bd9aec908856
|
||||
title: Etiquetas Buttons Bootstrap
|
||||
title: Etiqueta botones de Bootstrap
|
||||
challengeType: 0
|
||||
forumTopicId: 18222
|
||||
dashedName: label-bootstrap-buttons
|
||||
@ -8,9 +8,9 @@ dashedName: label-bootstrap-buttons
|
||||
|
||||
# --description--
|
||||
|
||||
Al igual que hemos etiquetado nuestros "wells", queremos etiquetar nuestros botones.
|
||||
Así como etiquetamos nuestros "wells", también queremos etiquetar nuestros botones.
|
||||
|
||||
Da a cada uno de tus elementos `button` el texto que corresponde a su id.
|
||||
Dale a cada uno de tus elementos `button`, texto que corresponde a su id.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bad87fee1348bd9aec908854
|
||||
title: Etiqueta Wells de Boostrap
|
||||
title: Etiqueta wells de Bootstrap
|
||||
challengeType: 0
|
||||
forumTopicId: 18223
|
||||
dashedName: label-bootstrap-wells
|
||||
@ -8,15 +8,15 @@ dashedName: label-bootstrap-wells
|
||||
|
||||
# --description--
|
||||
|
||||
Para mayor claridad, etiquetemos ambos `well` con sus ids.
|
||||
Para mayor claridad, vamos a etiquetar nuestros dos wells con sus ids.
|
||||
|
||||
Sobre tu "left-well", dentro del elemento `col-xs-6` `div`, agrega el elemento `h4` con el texto `#left-well`.
|
||||
Sobre tu "left-well", dentro de su elemento `div` `col-xs-6`, agrega un elemento `h4` con el texto `#left-well`.
|
||||
|
||||
Sobre tu "right-well", dentro del elemento `col-xs-6` `div`, agrega el elemento `h4` con el texto `#right-well`.
|
||||
Sobre tu "right-well", dentro de su elemento `div` `col-xs-6` agrega un elemento `h4` con el texto `#right-well`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Debes añadir un elemento `h4` para cada uno de sus elementos `<div class="col-xs-6">`.
|
||||
Debes agregar un elemento `h4` a cada uno de tus elementos `<div class="col-xs-6">`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bad87fee1348bd9aec908845
|
||||
title: Alinee elementos de formulario de forma responsiva con Bootstrap
|
||||
title: Alinea elementos de formulario de manera responsiva con Bootstrap
|
||||
challengeType: 0
|
||||
forumTopicId: 18225
|
||||
required:
|
||||
@ -13,15 +13,15 @@ dashedName: line-up-form-elements-responsively-with-bootstrap
|
||||
|
||||
# --description--
|
||||
|
||||
Ahora coloquemos tu formulario `input` y tu `button`de envío en la misma línea. Lo haremos de la misma forma que lo hemos hecho anteriormente: usando un elemento `div` con la clase `row`, y otros elementos `div` dentro de el usando la clase `col-xs-*`.
|
||||
Ahora coloquemos tus `input` de formulario y tu `button` de envío en la misma línea. Vamos a hacer esto de la misma forma que antes: Usando un elemento `div` con la clase `row`, y otros elementos `div` dentro de este usando la clase `col-xs-*`.
|
||||
|
||||
Anida tanto el campo de texto `input` del formulario como el botón de envío `button` dentro de un `div` con la clase `row`. Incrusta tu campo de texto `input` del formulario dentro de un div con la clase `col-xs-7`. Incrusta tu botón de envió `button` del formulario dentro de un `div`con la clase `col-xs-5`.
|
||||
Coloca juntos tu campo de texto `input` y tu `button` de envío dentro de un `div` con la clase `row`. Anida tu campo de texto `input` dentro de un div con la clase `col-xs-7`. Anida tu `button` de envío del formulario dentro de un `div` con la clase `col-xs-5`.
|
||||
|
||||
Este es el ultimo desafío que haremos para nuestra aplicación de fotos de gatos por ahora. ¡Esperamos que hayas disfrutado aprendiendo Font Awesome, Bootstrap y diseño responsivo!
|
||||
Este es el ultima desafio que vamos a hacer para nuestro 'Cat Photo App' por ahora. ¡Esperamos que hayas disfrutado aprendiendo Font Awesome, Bootstrap y diseño responsivo!
|
||||
|
||||
# --hints--
|
||||
|
||||
Tu botón de envío del formulario y la entrada de texto deben anidarse en un div con la clase `row`.
|
||||
Tu botón de envío del formulario y el campo de texto deben anidarse en un div con la clase `row`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -30,7 +30,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Tu entrada de texto del formulario debe estar anidada en un div con la clase `col-xs-7`.
|
||||
Tu campo de texto debe estar anidado en un div con la clase `col-xs-7`.
|
||||
|
||||
```js
|
||||
assert($('div.col-xs-7:has(input[type="text"])').length > 0);
|
||||
@ -42,7 +42,7 @@ Tu botón de envío del formulario debe estar anidado en un div con la clase `co
|
||||
assert($('div.col-xs-5:has(button[type="submit"])').length > 0);
|
||||
```
|
||||
|
||||
Todos sus elementos `div` deben tener etiquetas de cierre.
|
||||
Todos tus elementos `div` deben tener etiquetas de cierre.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bad87fee1348bd9acde08812
|
||||
title: Hacer que las imágenes se adapten a dispositivos móviles
|
||||
title: Haz que las imágenes se adapten a dispositivos móviles
|
||||
challengeType: 0
|
||||
forumTopicId: 18232
|
||||
dashedName: make-images-mobile-responsive
|
||||
@ -8,39 +8,39 @@ dashedName: make-images-mobile-responsive
|
||||
|
||||
# --description--
|
||||
|
||||
Primero, agregue una nueva imagen debajo de la existente. Establezca su atributo `src` en `https://bit.ly/fcc-running-cats`.
|
||||
Primero, agrega una nueva imagen debajo de la existente. Establece su atributo `src` a `https://bit.ly/fcc-running-cats`.
|
||||
|
||||
Sería genial si esta imagen pudiera tener exactamente el ancho de la pantalla de nuestro teléfono.
|
||||
|
||||
Afortunadamente, con Bootstrap, todo lo que tenemos que hacer es agregar la clase `img-responsive` a tus imágenes. Haga esto y la imagen debe ajustarse perfectamente al ancho de su página.
|
||||
Afortunadamente, con Bootstrap, todo lo que necesitamos hacer es agregar la clase `img-responsive` a nuestra imagen. Hazlo, y la imagen debería caber perfectamente en el ancho de tu página.
|
||||
|
||||
# --hints--
|
||||
|
||||
Debe tener un total de dos imágenes.
|
||||
Debes tener un total de dos imágenes.
|
||||
|
||||
```js
|
||||
assert($('img').length === 2);
|
||||
```
|
||||
|
||||
Tu nueva imagen debería estar debajo de la anterior y tener la clase `img-responsive`.
|
||||
Tu nueva imagen debe estar debajo de la anterior y tener la clase `img-responsive`.
|
||||
|
||||
```js
|
||||
assert($('img:eq(1)').hasClass('img-responsive'));
|
||||
```
|
||||
|
||||
Tu nueva imagen no debería tener la clase `smaller-image`.
|
||||
Tu nueva imagen no debe tener la clase `smaller-image`.
|
||||
|
||||
```js
|
||||
assert(!$('img:eq(1)').hasClass('smaller-image'));
|
||||
```
|
||||
|
||||
Tu nueva imagen debe tener el atributo `src` en `https://bit.ly/fcc-running-cats`.
|
||||
Tu nueva imagen debe tener el atributo `src` con el valor `https://bit.ly/fcc-running-cats`.
|
||||
|
||||
```js
|
||||
assert($('img:eq(1)').attr('src') === 'https://bit.ly/fcc-running-cats');
|
||||
```
|
||||
|
||||
Tu nuevo elemento `img` debe tener una etiqueta de cierre.
|
||||
Tu nuevo elemento `img` debe tener etiqueta de cierre.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -13,11 +13,11 @@ dashedName: responsively-style-checkboxes
|
||||
|
||||
# --description--
|
||||
|
||||
Dado que las clases `col-xs-*` de Bootstrap son aplicables a todos los elementos `form`, ¡también puedes usarlas en tus casillas de verificación! De esta manera, las casillas de verificación se distribuirán uniformemente por toda la página, independientemente de la amplitud de la resolución de la pantalla.
|
||||
Dado que las clases de Bootstrap `col-xs-*` son aplicables a todos los elementos `form`, ¡también puedes usarlas para tus casillas de verificación! De esta manera, las casillas de verificación se distribuirán uniformemente por toda la página, independientemente de la amplitud de la resolución de la pantalla.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Anida las tres casillas de verificación en un elemento `<div class="row">`. Luego incrusta cada uno de ellos en un elemento `<div class="col-xs-4">`.
|
||||
Anida las tres casillas de verificación en un elemento `<div class="row">`. Luego, anida cada uno de ellos en un elemento `<div class="col-xs-4">`.
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -27,13 +27,13 @@ Todas las casillas de verificación deben anidarse dentro de un `div` con la cla
|
||||
assert($('div.row:has(input[type="checkbox"])').length > 0);
|
||||
```
|
||||
|
||||
Cada casilla de verificación debe inscrustarse dentro de un `div` con la clase `row`.
|
||||
Cada casilla de verificación debe anidarse dentro de un `div` con la clase `col-xs-4`.
|
||||
|
||||
```js
|
||||
assert($('div.col-xs-4:has(input[type="checkbox"])').length > 2);
|
||||
```
|
||||
|
||||
Todos los elementos `div` deben tener etiquetas de cierre.
|
||||
Todos tus elementos `div` deben tener etiquetas de cierre.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bad87fee1348bd9aedb08845
|
||||
title: Botones radio con estilo responsivo
|
||||
title: Botones de radio con estilo responsivo
|
||||
challengeType: 0
|
||||
forumTopicId: 18270
|
||||
required:
|
||||
@ -13,27 +13,27 @@ dashedName: responsively-style-radio-buttons
|
||||
|
||||
# --description--
|
||||
|
||||
¡También puedes usar las clases `col-xs-*` de Bootstrap en los elementos `form`! De esta manera, nuestros botones de radio se distribuirán uniformemente por toda la página, independientemente del ancho de la resolución de la pantalla.
|
||||
¡Puedes utilizar también las clases `col-xs-*` de Bootstrap en elementos `form`! De esta forma nuestros botones de radio se distribuirán uniformemente a través de la página, sin importar el ancho de la resolución de pantalla.
|
||||
|
||||
Anida ambos botones de radio dentro de un elemento `<div class="row">`. Luego anida cada uno de ellos en un elemento `<div class="col-xs-6">`.
|
||||
Anida tus dos botones de radio dentro de un elemento `<div class="row">`. Luego, anida cada uno de ellos dentro de un elemento `<div class="col-xs-6">`.
|
||||
|
||||
**Nota:** Como recordatorio, los botones de radio son `entradas`, elementos de tipo `radio`.
|
||||
**Nota:** Como recordatorio, los botones de radio son elementos `input` con el valor de tipo `radio`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Todas las casillas de radio deben anidarse dentro de un `div` con la clase `row`.
|
||||
Todos tus botones de radio deben estar anidados dentro de un `div` con la clase `row`.
|
||||
|
||||
```js
|
||||
assert($('div.row:has(input[type="radio"])').length > 0);
|
||||
```
|
||||
|
||||
Cada uno de tus botones de radio debe inscrustarse dentro un `div` con la clase `col-xs-6`.
|
||||
Cada uno de tus botones de radio debe estar anidado dentro de su propio `div` con la clase `col-xs-6`.
|
||||
|
||||
```js
|
||||
assert($('div.col-xs-6:has(input[type="radio"])').length > 1);
|
||||
```
|
||||
|
||||
Todos sus elementos `div` deben tener etiquetas de cierre.
|
||||
Todos tus elementos `div` deben tener etiquetas de cierre.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -8,7 +8,7 @@ dashedName: split-your-bootstrap-row
|
||||
|
||||
# --description--
|
||||
|
||||
Ahora que tenemos una fila de Bootstrap, vamos a dividirla en dos columnas para albergar nuestros elementos.
|
||||
Ahora que tenemos una fila de Bootstrap, vamos a dividirla en dos columnas para hospedar nuestros elementos.
|
||||
|
||||
Crea dos elementos `div` dentro de tu fila, ambos con la clase `col-xs-6`.
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bad87fee1348bd9aed908845
|
||||
title: Estilo de entradas de texto como controles de formulario
|
||||
title: Estiliza entradas de texto como controles de formulario
|
||||
challengeType: 0
|
||||
forumTopicId: 18312
|
||||
required:
|
||||
@ -13,27 +13,27 @@ dashedName: style-text-inputs-as-form-controls
|
||||
|
||||
# --description--
|
||||
|
||||
Puedes añadir el icono `fa-paper-plane` de Font Awesome, agregando `<i class="fa fa-paper-plane"></i>` dentro del elemento `button` de tipo `submit`.
|
||||
Puedes agregar el icono `fa-paper-plane` de Font Awesome agregando `<i class="fa fa-paper-plane"></i>` dentro de tu elemento `button` de envío.
|
||||
|
||||
Da al input(campo de entrada de texto) de tu formulario una clase `form-control`. Da el botón de envío(submit) de tu formulario las clases `btn btn-primary`. También da a este botón el icono de Font Awesome con `fa-paper-plane`.
|
||||
Dale a tu campo de entrada de texto la clase `form-control`. Dale a tu botón de envío de formulario las clases `btn btn-primary`. También asígnale a este botón el icono de Font Awesome `fa-paper-plane`.
|
||||
|
||||
Todo el texto en los elementos `<input>`, `<textarea>`, y `<select>` con la clase `.form-control` deben tener un ancho del 100%.
|
||||
Todos los elementos textuales `<input>`, `<textarea>`, y `<select>` con la clase `.form-control` tienen un ancho de 100%.
|
||||
|
||||
# --hints--
|
||||
|
||||
El botón de envío submit en tu formulario debe tener las clases `btn btn-primary`.
|
||||
El botón de envío en tu formulario debe tener las clases `btn btn-primary`.
|
||||
|
||||
```js
|
||||
assert($('button[type="submit"]').hasClass('btn btn-primary'));
|
||||
```
|
||||
|
||||
Debes añadir `<i class="fa fa-paper-plane"></i>` dentro de tu elemento button.
|
||||
Debes añadir un `<i class="fa fa-paper-plane"></i>` dentro de tu elemento `button`.
|
||||
|
||||
```js
|
||||
assert($('button[type="submit"]:has(i.fa.fa-paper-plane)').length > 0);
|
||||
```
|
||||
|
||||
El texto en `input` en tu formulario debe tener la clase `form-control`.
|
||||
El `input` de tipo texto en tu formulario debe tener la clase `form-control`.
|
||||
|
||||
```js
|
||||
assert($('input[type="text"]').hasClass('form-control'));
|
||||
|
@ -8,11 +8,11 @@ dashedName: taste-the-bootstrap-button-color-rainbow
|
||||
|
||||
# --description--
|
||||
|
||||
La clase `btn-primary` es el color principal que usarás en tu aplicación. Es útil para resaltar las acciones que quieres que tome tu usuario.
|
||||
La clase `btn-primary` es el color principal que usarás en tu aplicación. Es útil para resaltar acciones que deseas que tu usuario realice.
|
||||
|
||||
Reemplaza la clase de Bootstrap `btn-default` con `btn-primary` en tu botón.
|
||||
Reemplaza la clase `btn-default` de Bootstrap por `btn-primary` en tu botón.
|
||||
|
||||
Ten en cuenta que este botón todavía necesitará las clases `btn` y `btn-block`.
|
||||
Ten en cuenta que este botón aún necesitará las clases `btn` y `btn-block`.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -14,11 +14,11 @@ Puedes usar spans para crear elementos en línea. ¿Recuerdas cuando usamos la c
|
||||
|
||||
<button class='btn btn-block' style='background-color: rgb(0, 100, 0); color: rgb(255, 255, 255);'>botón btn-block</button>
|
||||
|
||||
Esto ilustra la diferencia entre un elemento "en línea" y un elemento de "bloque".
|
||||
Eso ilustra la diferencia entre un elemento "inline" y un elemento "block".
|
||||
|
||||
Usando el elemento en línea `span`, puedes alinear varios elementos, e incluso estilizar diferentes partes de la misma línea de manera diferente.
|
||||
|
||||
Usando un elemento `span`, anida la palabra `love` dentro del elemento `p` que actualmente contiene el texto `Things cats love`. Luego asigna al `span` la clase `text-danger` para hacer al texto rojo.
|
||||
Usando un elemento `span`, anida la palabra `love` dentro del elemento `p` que actualmente tiene el texto `Things cats love`. Luego dale a `span` la clase `text-danger` para cambiar el texto a rojo.
|
||||
|
||||
Así es como harías esto para el elemento `p` que tiene el texto `Top 3 things cats hate`:
|
||||
|
||||
@ -34,7 +34,7 @@ Tu elemento `span` debe estar dentro de tu elemento `p`.
|
||||
assert($('p span') && $('p span').length > 0);
|
||||
```
|
||||
|
||||
Tu elemento `span` solo debe tener el texto `love`.
|
||||
Tu elemento `span` debe tener solo el texto `love`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bad87fee1348bd9aec908857
|
||||
title: Use los comentarios para aclarar el código
|
||||
title: Usa comentarios para aclarar el código
|
||||
challengeType: 0
|
||||
forumTopicId: 18347
|
||||
dashedName: use-comments-to-clarify-code
|
||||
@ -8,35 +8,35 @@ dashedName: use-comments-to-clarify-code
|
||||
|
||||
# --description--
|
||||
|
||||
Cuando comencemos a utilizar jQuery, modificaremos los elementos HTML sin necesidad de cambiarlos en HTML.
|
||||
Cuando empecemos a usar jQuery, vamos a modificar elementos HTML sin necesidad de cambiarlos en HTML.
|
||||
|
||||
Asegurémonos de que todos sepan que en realidad no deben modificar nada de este código directamente.
|
||||
Vamos a asegurarnos de que todos sepan que no deben modificar nada de este código directamente.
|
||||
|
||||
Recuerda que puedes comenzar un comentario con `<!--` y terminar con `-->`
|
||||
Recuerda que puedes empezar un comentario con `<!--` y terminarlo con `-->`
|
||||
|
||||
Añade un comentario en la parte superior de tu HTML que diga `Code below this line should not be changed`
|
||||
Agrega un comentario en la parte superior de tu HTML que diga `Code below this line should not be changed`
|
||||
|
||||
# --hints--
|
||||
|
||||
En la parte superior de tu HTML debe comenzar un comentario con `<!--`.
|
||||
Debes comenzar un comentario en la parte superior de tu HTML con `<!--`.
|
||||
|
||||
```js
|
||||
assert(code.match(/^\s*<!--/));
|
||||
```
|
||||
|
||||
El comentario debe contener el texto `Code below this line should not be changed`.
|
||||
Tu comentario debe tener el texto `Code below this line should not be changed`.
|
||||
|
||||
```js
|
||||
assert(code.match(/<!--(?!(>|->|.*-->.*this line))\s*.*this line.*\s*-->/gi));
|
||||
```
|
||||
|
||||
Debe cerrar el comentario con `-->`.
|
||||
Debes cerrar tu comentario con`-->`.
|
||||
|
||||
```js
|
||||
assert(code.match(/-->.*\n+.+/g));
|
||||
```
|
||||
|
||||
Debe tener el mismo número de aperturas y cierres de comentario.
|
||||
Debes tener el mismo número de aperturas y cierres de comentarios.
|
||||
|
||||
```js
|
||||
assert(code.match(/<!--/g).length === code.match(/-->/g).length);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bad87fee1348bd9acde08712
|
||||
title: Utiliza diseño responsivo con contenedores de fluido Bootstrap
|
||||
title: Utiliza diseño responsivo con contenedores de fluido de Bootstrap
|
||||
challengeType: 0
|
||||
forumTopicId: 18362
|
||||
dashedName: use-responsive-design-with-bootstrap-fluid-containers
|
||||
@ -8,19 +8,19 @@ dashedName: use-responsive-design-with-bootstrap-fluid-containers
|
||||
|
||||
# --description--
|
||||
|
||||
En la sección de HTML5 y CSS de freeCodeCamp, creamos una aplicación de fotos de gatos. Ahora vamos de vuelta a la aplicación. Esta vez, lo estilizaremos usando el popular framework CSS responsivo de Bootstrap.
|
||||
En la seccion de HTML5 y CSS de freeCodeCamp construimos un 'Cat Photo App'. Ahora volvamos a él. Esta vez, vamos a estilizarlo utilizando el popular framework CSS responsivo de Bootstrap.
|
||||
|
||||
Bootstap averiguará la anchura de tu pantalla y responderá redimensionando los elementos HTML, de aquí el nombre <dfn>diseño responsivo</dfn>.
|
||||
Bootstrap averiguará cuan ancha es tu pantalla y responderá redimensionando tus elementos HTML - de ahí el nombre <dfn>diseño responsivo</dfn>.
|
||||
|
||||
Con diseño responsivo, no hay necesidad de diseñar una versión móvil de tu sitio web. Se verá bien en dispositivos con pantallas de cualquier anchura.
|
||||
Con diseño responsivo, no hay necesidad de diseñar una versión móvil de tu sitio web. Se verá bien en dispositivos con pantallas de cualquier ancho.
|
||||
|
||||
Puedes añadir Bootstrap a cualquier aplicación al agregar el siguiente código encima de tu HTML:
|
||||
Puedes añadir Bootstrap a cualquier aplicación agregando el siguiente código en la parte superior de tu HTML:
|
||||
|
||||
```html
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"/>
|
||||
```
|
||||
|
||||
En este caso, ya lo añadimos a esta página. Ten en cuenta que para cerrar la etiqueta `link` puedes utilizar `>` o `/>`.
|
||||
En este caso, ya lo hemos añadido por ti en esta página, tras bambalinas. Ten en cuenta que para cerrar la etiqueta `link` puedes utilizar `>` o `/>`.
|
||||
|
||||
Para comenzar, debemos anidar todo nuestro HTML (menos la etiqueta `link` y el elemento `style`) en un elemento `div` con la clase `container-fluid`.
|
||||
|
||||
@ -42,7 +42,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Todos los elementos HTML después de la etiqueta de cierre `style` deben anidarse en `.container-fluid`.
|
||||
Todos los elementos HTML después de la etiqueta de cierre de `style` deben estar anidados dentro de `.container-fluid`.
|
||||
|
||||
```js
|
||||
assert($('.container-fluid').children().length >= 8 && !$('.container-fluid').has("style").length && !$('.container-fluid').has("link").length);
|
||||
|
@ -10,31 +10,31 @@ dashedName: use-the-bootstrap-grid-to-put-elements-side-by-side
|
||||
|
||||
Bootstrap utiliza un sistema responsivo de cuadrilla de 12 columnas, el cual hace que sea fácil poner elementos en dos filas y especificar la anchura relativa de cada elemento. La mayoría de las clases de Bootstrap pueden ser aplicadas a un elemento `div`.
|
||||
|
||||
Bootstrap tiene diferentes atributos de anchura de columna que utiliza con respecto a la anchura de la pantalla del usuario. Por ejemplo, los teléfonos tienen pantallas más angostas y las computadoras portátiles tienen pantallas más anchas.
|
||||
Bootstrap tiene diferentes atributos de ancho de columna que usa dependiendo cuan ancha es la pantalla del usuario. Por ejemplo, los teléfonos tienen pantallas más angostas y las laptops tienen pantallas más anchas.
|
||||
|
||||
Ten como ejemplo la clase de Bootstrap `col-md-*`. Aquí, `md` significa mediano y `*` es un número que especifica cuántas columnas de ancho deben tener los elementos. En este caso, se especifica el ancho de la columna de un elemento en una pantalla de tamaño mediano, como un portátil.
|
||||
Tomemos por ejemplo la clase de Bootstrap `col-md-*`. Aquí, `md` significa mediano y `*` es un número que especifica cuántas columnas de ancho deben tener los elementos. En este caso, el ancho de columna de un elemento en una pantalla de tamaño mediano, como una laptop, está siendo especificado.
|
||||
|
||||
En la aplicación de fotos de gatitos que estamos creando, utilizaremos `col-xs-*`, donde `xs` significa extra pequeño (como una pantalla de teléfono celular extra pequeña) y `*` es el número de columnas que especifica cuántas columnas de ancho debe tener un elemento.
|
||||
En el 'Cat Photo App' que estamos armando, vamos a usar `col-xs-*`, donde `xs` significa extra pequeño ("extra small" como una pantalla de teléfono), y `*` es el número de columnas que va a tomar el elemento en anchura.
|
||||
|
||||
Pon los botones `Like`, `Info` y `Delete` de lado a lado anidando los tres dentro de un elemento `<div class="row">`, luego cada uno de ellos dentro de un elemento `<div class="col-xs-4">`.
|
||||
Pon los botones `Like`, `Info` y `Delete` lado a lado, anidando los tres dentro de un elemento `<div class="row">`, luego, cada uno de ellos dentro de un elemento `<div class="col-xs-4">`.
|
||||
|
||||
La clase `row` se aplica a un `div` y los mismos botones pueden anidarse dentro de ella.
|
||||
La clase `row` es aplicada a un `div`, y los botones mismos pueden ser anidados dentro de él.
|
||||
|
||||
# --hints--
|
||||
|
||||
Todos los botones deben estar anidados dentro del mismo elemento `div` con la clase `row`.
|
||||
Todos tus botones deben estar anidados dentro del mismo elemento `div` con la clase `row`.
|
||||
|
||||
```js
|
||||
assert($('div.row:has(button)').length > 0);
|
||||
```
|
||||
|
||||
Cada uno de los botones de Bootstap debe anidarse dentro de su propio elemento `div` con la clase `col-xs-4`.
|
||||
Cada uno de tus botones de Bootstrap deben estar anidados dentro de su propio elemento `div` con la clase `col-xs-4`.
|
||||
|
||||
```js
|
||||
assert($('div.col-xs-4:has(button)').length > 2);
|
||||
```
|
||||
|
||||
Cada uno de los elementos `button` debe tener una etiqueta de cierre.
|
||||
Cada uno de tus elementos `button` deben tener una etiqueta de cierre.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -44,7 +44,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Cada uno de loselementos `div` debe tener una etiqueta de cierre.
|
||||
Cada uno de tus elementos `div` deben tener una etiqueta de cierre.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -8,7 +8,7 @@ dashedName: warn-your-users-of-a-dangerous-action-with-btn-danger
|
||||
|
||||
# --description--
|
||||
|
||||
Bootstrap viene con diferentes colores predefinidos para botones. La clase `btn-danger` es el color del botón que usarás para notificar a los usuarios que el botón realiza una acción destructiva, como eliminar una foto de gato.
|
||||
Bootstrap viene con varios colores predefinidos para botones. La clase `btn-danger` es el color del botón que usarás para notificar a los usuarios que el botón realiza una acción destructiva, como eliminar la foto de un gato.
|
||||
|
||||
Crea un botón con el texto `Delete` y dale la clase `btn-danger`.
|
||||
|
||||
@ -22,7 +22,7 @@ Debes crear un nuevo elemento `button` con el texto `Delete`.
|
||||
assert(new RegExp('Delete', 'gi').test($('button').text()));
|
||||
```
|
||||
|
||||
Todos tus botones de Bootstrap deben tener clases `btn` y `btn-block`.
|
||||
Todos tus botones de Bootstrap deben tener las clases `btn` y `btn-block`.
|
||||
|
||||
```js
|
||||
assert($('button.btn-block.btn').length > 2);
|
||||
@ -34,7 +34,7 @@ Tu nuevo botón debe tener la clase `btn-danger`.
|
||||
assert($('button').hasClass('btn-danger'));
|
||||
```
|
||||
|
||||
Todos los elementos `button` deben tener etiquetas de cierre.
|
||||
Todos tus elementos `button` deben tener etiquetas de cierre.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -8,26 +8,24 @@ dashedName: understanding-the-differences-between-the-freecodecamp-and-browser-c
|
||||
|
||||
# --description--
|
||||
|
||||
Potresti aver notato che alcune sfide JavaScript di freeCodeCamp includono la propria console. Questa console si comporta in modo leggermente diverso rispetto alla console del browser utilizzata nell'ultima sfida.
|
||||
Potresti aver notato che alcune sfide di freeCodeCamp includono la propria console. Questa console si comporta in modo leggermente diverso rispetto alla console del browser.
|
||||
|
||||
La seguente sfida è destinata a evidenziare la differenza principale tra la console di freeCodeCamp e la console del browser.
|
||||
|
||||
Quando eseguirai del JavaScript ordinario, la console del browser ti farà visualizzare i comandi `console.log()` per il numero esatto di volte che li hai chiamati.
|
||||
|
||||
La console freeCodeCamp ti farà visualizzare i comandi `console.log()` poco tempo dopo che l'editor rileva un cambiamento nello script, così come durante i test.
|
||||
|
||||
La console freeCodeCamp viene cancellata prima che i test vengano eseguiti e, per evitare spam, visualizza i log solo durante il primo test (cfr. la nota sottostante per le eccezioni).
|
||||
|
||||
Se desideri vedere ogni log per ogni test, esegui i test e apri la console del browser. Se preferisci usare la console del browser, e vuoi che imiti la console di freeCodeCamp, posiziona il comando `console.clear()` prima di qualsiasi altra chiamata `console`, per pulire la console del browser.
|
||||
|
||||
**Nota:** le chiamate `console.log` all'interno delle funzioni vengono visualizzate sulla console di freeCodeCamp ogni volta che queste funzioni vengono chiamate. Questo può aiutare a fare il debug delle funzioni che vengono chiamate nel test.
|
||||
Ci sono molti metodi che possono essere usati con `console` per scrivere messaggi sulla console. Alcuni di questi sono `log`, `warn`, e `clear`. Sulla console freeCodeCamp verranno scritti solo messaggi log `log`, mentre sulla console del browser tutti i messaggi. Quando fai modifiche al tuo codice, questo eseguirà automaticamente e mostrerà i log sulla console. La console di freeCodeCamp viene svuotata ogni volta che il tuo codice esegue.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Innanzitutto, usa `console.log` per visualizzare la variabile `output`. Quindi, utilizza `console.clear` per pulire la console del browser.
|
||||
Per prima cosa, apri la console del tuo browser affinché tu possa vedere il log. Per farlo, puoi cliccare con il taso destro la barra di navigazione di freeCodeCamp in cima alla pagina e cliccare `inspect` (o "Ispeziona") nella maggior parte dei browser. Quindi trova la scheda `console` nella finestra che si apre.
|
||||
|
||||
Dopo questo, usa `console.log` per scrivere il valore della variabile `output` nella console. Guarda le due console per vedere il log. Infine, usa `console.clear` dopo il tuo log per pulire la console del browser. Vedi la differenza nelle due console.
|
||||
|
||||
# --hints--
|
||||
|
||||
Dovresti usare `console.log()` per visualizzare la variabile `output`.
|
||||
|
||||
```js
|
||||
assert(__helpers.removeWhiteSpace(code).match(/console\.log\(output\)/));
|
||||
```
|
||||
|
||||
Dovresti usare `console.clear()` per cancellare la console del browser.
|
||||
|
||||
```js
|
||||
@ -38,10 +36,14 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Dovresti usare `console.log()` per visualizzare la variabile `output`.
|
||||
Dovresti pulire la console con `console.clear` dopo il tuo log.
|
||||
|
||||
```js
|
||||
assert(__helpers.removeWhiteSpace(code).match(/console\.log\(output\)/));
|
||||
assert(
|
||||
__helpers
|
||||
.removeWhiteSpace(code)
|
||||
.match(/console\.log\(output\)[\s\S]*console.clear\(\)/)
|
||||
);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -49,25 +51,15 @@ assert(__helpers.removeWhiteSpace(code).match(/console\.log\(output\)/));
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
// Open your browser console.
|
||||
let output = "Get this to log once in the freeCodeCamp console and twice in the browser console";
|
||||
// Use console.log() to print the output variable.
|
||||
let output = "Get this to show once in the freeCodeCamp console and not at all in the browser console";
|
||||
|
||||
// Run the tests to see the difference between the two consoles.
|
||||
|
||||
// Now, add console.clear() before your console.log() to clear the browser console, and pass the tests.
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
||||
```js
|
||||
// Open your browser console.
|
||||
let output = "Get this to log once in the freeCodeCamp console and twice in the browser console";
|
||||
// Use console.log() to print the output variable.
|
||||
console.clear();
|
||||
let output = "Get this to show once in the freeCodeCamp console and not at all in the browser console";
|
||||
|
||||
console.log(output);
|
||||
|
||||
// Run the tests to see the difference between the two consoles.
|
||||
|
||||
// Now, add console.clear() before your console.log() to clear the browser console, and pass the tests.
|
||||
console.clear();
|
||||
```
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 561add10cb82ac38a17523bc
|
||||
title: Certificado de APIs e desenvolvimento de back-end
|
||||
title: Certificação de APIs e desenvolvimento de back-end
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
@ -15,7 +15,7 @@ tests:
|
||||
title: Microsserviço redutor de URL
|
||||
-
|
||||
id: 5a8b073d06fa14fcfde687aa
|
||||
title: Rastreador de exercícios
|
||||
title: Registrador de exercícios
|
||||
-
|
||||
id: bd7158d8c443edefaeb5bd0f
|
||||
title: Microsserviço de metadados de arquivos
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e46fc95ac417301a38fb934
|
||||
title: Certificado de análise de dados com Python
|
||||
title: Certificação de análise de dados com Python
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a553ca864b52e1d8bceea14
|
||||
title: Certificado de visualização de dados
|
||||
title: Certificação de visualização de dados
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 561acd10cb82ac38a17513bc
|
||||
title: Certificado de desenvolvimento com bibliotecas de front-end
|
||||
title: Certificação de desenvolvimento com bibliotecas de front-end
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
@ -15,7 +15,7 @@ tests:
|
||||
title: Criar uma bateria eletrônica
|
||||
-
|
||||
id: bd7158d8c442eddfaeb5bd17
|
||||
title: Criar uma calculadora JavaScript
|
||||
title: Cria uma calculadora em JavaScript
|
||||
-
|
||||
id: bd7158d8c442eddfaeb5bd0f
|
||||
title: Criar um Relógio 25 + 5
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e6021435ac9d0ecd8b94b00
|
||||
title: Certificado de segurança da informação
|
||||
title: Certificação de segurança da informação
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 561abd10cb81ac38a17513bc
|
||||
title: Certificado de algoritmos e estruturas de dados em JavaScript
|
||||
title: Certificação de algoritmos e estruturas de dados em JavaScript
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 660add10cb82ac38a17513be
|
||||
title: Certificado de back-end legado
|
||||
title: Certificação de back-end legada
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
@ -9,7 +9,7 @@ tests:
|
||||
title: Microsserviço de timestamp
|
||||
-
|
||||
id: bd7158d8c443edefaeb5bdff
|
||||
title: Microsserviço parseador de cabeçalho de requisição
|
||||
title: Microsserviço conversor de requisição de cabeçalho
|
||||
-
|
||||
id: bd7158d8c443edefaeb5bd0e
|
||||
title: Microsserviço redutor de URL
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 561add10cb82ac39a17513bc
|
||||
title: Certificado de visualização de dados legado
|
||||
title: Certificação de visualização de dados legado
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 561add10cb82ac38a17513be
|
||||
title: Certificado de back-end legado
|
||||
title: Certificação de front-end legada
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
@ -15,7 +15,7 @@ tests:
|
||||
title: Criar um Relógio 25 + 5
|
||||
-
|
||||
id: bd7158d8c442eddfaeb5bd17
|
||||
title: Criar uma calculadora JavaScript
|
||||
title: Criar uma calculadora em JavaScript
|
||||
-
|
||||
id: bd7158d8c442eddfaeb5bd10
|
||||
title: Exibir o clima local
|
||||
|
@ -1,24 +1,24 @@
|
||||
---
|
||||
id: 561add10cb82ac38a17213bd
|
||||
title: Certificado de full stack legado
|
||||
title: Certificação de full stack legada
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
-
|
||||
id: 561add10cb82ac38a17513bc
|
||||
title: Certificado de design responsivo para a web
|
||||
title: Certificação de design responsivo para a web
|
||||
-
|
||||
id: 561abd10cb81ac38a17513bc
|
||||
title: Certificado de algoritmos e estruturas de dados em JavaScript
|
||||
title: Certificação de algoritmos e estruturas de dados em JavaScript
|
||||
-
|
||||
id: 561acd10cb82ac38a17513bc
|
||||
title: Certificado de bibliotecas de front-end
|
||||
title: Certificação de bibliotecas de front-end
|
||||
-
|
||||
id: 5a553ca864b52e1d8bceea14
|
||||
title: Certificado de visualização de dados
|
||||
title: Certificação de visualização de dados
|
||||
-
|
||||
id: 561add10cb82ac38a17523bc
|
||||
title: Certificado de APIs e microsserviços
|
||||
title: Certificação de APIs e microsserviços
|
||||
-
|
||||
id: 561add10cb82ac38a17213bc
|
||||
title: Certificado de garantia da qualidade e segurança da informação legado
|
||||
title: Certificação de garantia da qualidade e segurança da informação legada
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 561add10cb82ac38a17213bc
|
||||
title: Certificado de garantia da qualidade e segurança da informação legado
|
||||
title: Certificação de garantia da qualidade e segurança da informação legada
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e46fc95ac417301a38fb935
|
||||
title: Certificado de aprendizagem de máquina com Python
|
||||
title: Certificação de aprendizagem de máquina com Python
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e611829481575a52dc59c0e
|
||||
title: Certificado de garantia de qualidade
|
||||
title: Certificação de garantia de qualidade
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 606243f50267e718b1e755f4
|
||||
title: Certificado de banco de dados relacional
|
||||
title: Certificação de banco de dados relacional
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 561add10cb82ac38a17513bc
|
||||
title: Certificado de design responsivo para a web
|
||||
title: Certificação de design responsivo para a web
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e44431b903586ffb414c951
|
||||
title: Certificado de computação científica em Python
|
||||
title: Certificação de computação científica em Python
|
||||
challengeType: 7
|
||||
isPrivate: true
|
||||
tests:
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3db1000cf542c50feec
|
||||
title: 'Problem 109: Darts'
|
||||
title: 'Problema 109: Dardos'
|
||||
challengeType: 5
|
||||
forumTopicId: 301733
|
||||
dashedName: problem-109-darts
|
||||
@ -8,25 +8,25 @@ dashedName: problem-109-darts
|
||||
|
||||
# --description--
|
||||
|
||||
In the game of darts a player throws three darts at a target board which is split into twenty equal sized sections numbered one to twenty.
|
||||
No jogo de dardos, um jogador joga três dardos em um alvo que é dividido em vinte seções de tamanho igual, numeradas de um a vinte.
|
||||
|
||||
<img class="img-responsive center-block" alt="Darts board" src="https://cdn.freecodecamp.org/curriculum/project-euler/darts.png" style="background-color: white; padding: 10px;" />
|
||||
<img class="img-responsive center-block" alt="Alvo dos dardos" src="https://cdn.freecodecamp.org/curriculum/project-euler/darts.png" style="background-color: white; padding: 10px;" />
|
||||
|
||||
The score of a dart is determined by the number of the region that the dart lands in. A dart landing outside the red/green outer ring scores zero. The black and cream regions inside this ring represent single scores. However, the red/green outer ring and middle ring score double and treble scores respectively.
|
||||
A pontuação de um dardo é determinada pelo número da região que o dardo atinge. Um dardo aterrissando fora do anel externo vermelho/verde, marca zero. As regiões preta e creme dentro deste anel representam pontuações únicas. No entanto, o anel externo vermelho/verde e o anel do meio têm pontuações duplas e triplas, respectivamente.
|
||||
|
||||
At the center of the board are two concentric circles called the bull region, or bulls-eye. The outer bull is worth 25 points and the inner bull is a double, worth 50 points.
|
||||
No centro do tabuleiro, há dois círculos concêntricos chamados de região chamada bull, ou, bullseye. O bull externo vale 25 pontos e o bull interno é um duplo, valendo 50 pontos.
|
||||
|
||||
There are many variations of rules but in the most popular game the players will begin with a score of 301 or 501 and the first player to reduce their running total to zero is a winner. However, it is normal to play a "doubles out" system, which means that the player must land a double (including the double bulls-eye at the center of the board) on their final dart to win; any other dart that would reduce their running total to one or lower means the score for that set of three darts is "bust".
|
||||
Há muitas variações de regras, mas, no jogo mais popular, os jogadores começarão com uma pontuação de 301 ou 501 e o primeiro jogador a reduzir seu total de aproveitamento para zero é um vencedor. No entanto, é normal jogar um sistema de "duplos fora", o que significa que o jogador deve acertar um duplo (incluindo o alvo duplo no centro do tabuleiro) em seu dardo final para vencer; qualquer outro dardo que reduziria seu total de corrida para um ou menos significa que a pontuação para aquele conjunto de três dardos foi um "fracasso".
|
||||
|
||||
When a player is able to finish on their current score it is called a "checkout" and the highest checkout is 170: T20 T20 D25 (two treble 20s and double bull). There are exactly eleven distinct ways to checkout on a score of 6:
|
||||
Quando um jogador consegue terminar na pontuação atual, ela é chamada de "check-out". O check-out mais alto vale 170: T20 T20 D25 (dois 20s triplos e um duplo bull). Há exatamente onze maneiras distintas de marcar uma pontuação de 6:
|
||||
|
||||
$$\begin{array} \text{D3} & & \\\\ D1 & D2 & \\\\ S2 & D2 & \\\\ D2 & D1 & \\\\ S4 & D1 & \\\\ S1 & S1 & D2 \\\\ S1 & T1 & D1 \\\\ S1 & S3 & D1 \\\\ D1 & D1 & D1 \\\\ D1 & S2 & D1 \\\\ S2 & S2 & D1 \end{array}$$
|
||||
|
||||
Note that D1 D2 is considered different from D2 D1 as they finish on different doubles. However, the combination S1 T1 D1 is considered the same as T1 S1 D1. In addition, we shall not include misses in considering combinations; for example, D3 is the same as 0 D3 and 0 0 D3. Incredibly there are 42336 distinct ways of checking out in total. How many distinct ways can a player checkout with a score less than 100?
|
||||
Observe que D1 D2 é considerado diferente de D2 D1, pois terminam em duplas diferentes. No entanto, a combinação S1 T1 D1 é considerada a mesma que T1 S1 D1. Além disso, não devemos incluir erros ao considerar as combinações; por exemplo, D3 é o mesmo que 0 D3 e 0 0 D3. Incrivelmente, no total, existem 42336 maneiras distintas de fazer checkout. De quantas maneiras diferentes um jogador pode finalizar com uma pontuação inferior a 100?
|
||||
|
||||
# --hints--
|
||||
|
||||
`darts()` should return `38182`.
|
||||
`darts()` deve retornar `38182`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(darts(), 38182);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7ed1
|
||||
title: Knapsack problem/0-1
|
||||
title: O problema da mochila/0-1
|
||||
challengeType: 5
|
||||
forumTopicId: 323649
|
||||
dashedName: knapsack-problem0-1
|
||||
@ -8,17 +8,17 @@ dashedName: knapsack-problem0-1
|
||||
|
||||
# --description--
|
||||
|
||||
The 0-1 knapsack problem is defined as follows:
|
||||
O problema da mochila 0-1 é definido da seguinte forma:
|
||||
|
||||
You are given an array of objects representing items to be put in a knapsack. The objects have 3 attributes: name, weight, and value. The items need to be selected so that the total weight does not exceed the maximum weight and the value is maximized.
|
||||
Você recebe um array de objetos que representa os itens a serem colocados em uma mochila. Os objetos têm 3 atributos: nome, peso e valor. Os itens precisam ser selecionados de maneira que o peso total não exceda o peso máximo e que o valor seja maximizado.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function to solve the knapsack problem. The function is given the array of objects and the maximum weight as parameters. It should return the maximum total value possible.
|
||||
Escreva uma função para resolver o problema da mochila. A função recebe o array de objetos e o peso máximo como parâmetros. Ela deve devolver o valor máximo total possível.
|
||||
|
||||
# --hints--
|
||||
|
||||
`knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 100)` should return `405`.
|
||||
`knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 100)` deve retornar `405`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -39,7 +39,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 200)` should return `510`.
|
||||
`knapsack([{ name:'map', weight:9, value:150 }, { name:'compass', weight:13, value:35 }, { name:'water', weight:153, value:200 }, { name:'sandwich', weight:50, value:160 }, { name:'glucose', weight:15, value:60 }, { name:'tin', weight:68, value:45 }, { name:'banana', weight:27, value:60 }, { name:'apple', weight:39, value:40 }], 200)` deve retornar `510`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -60,7 +60,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 100)` should return `145`.
|
||||
`knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 100)` deve retornar `145`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -80,7 +80,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 200)` should return `185`.
|
||||
`knapsack([{ name:'cheese', weight:23, value:30 }, { name:'beer', weight:52, value:10 }, { name:'suntan cream', weight:11, value:70 }, { name:'camera', weight:32, value:30 }, { name:'T-shirt', weight:24, value:15 }, { name:'trousers', weight:48, value:10 }, { name:'umbrella', weight:73, value:40 }], 200)` deve retornar `185`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -100,7 +100,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 100)` should return `237`.
|
||||
`knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 100)` deve retornar `237`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -120,7 +120,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 200)` should return `317`.'
|
||||
`knapsack([{ name:'waterproof trousers', weight:42, value:70 }, { name:'waterproof overclothes', weight:43, value:75 }, { name:'note-case', weight:22, value:80 }, { name:'sunglasses', weight:7, value:20 }, { name:'towel', weight:18, value:12 }, { name:'socks', weight:4, value:50 }, { name:'book', weight:30, value:10 }], 200)` deve retornar `317`.'
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7ed2
|
||||
title: Knapsack problem/Bounded
|
||||
title: O problema da mochila/limitado
|
||||
challengeType: 5
|
||||
forumTopicId: 323652
|
||||
dashedName: knapsack-problembounded
|
||||
@ -8,17 +8,17 @@ dashedName: knapsack-problembounded
|
||||
|
||||
# --description--
|
||||
|
||||
The bounded knapsack problem is defined as follows:
|
||||
O problema da mochila limitado é definido da seguinte forma:
|
||||
|
||||
You are given an array of objects representing items to be put in a knapsack. The objects have 4 attributes: name, pieces (the number of the particular item), weight, and value. The items need to be selected so that the total weight does not exceed the maximum weight and the value is maximized. Keep in mind that each item can appear between 0 and `pieces` times.
|
||||
Você recebe um array de objetos que representa os itens a serem colocados em uma mochila. Os objetos têm 4 atributos: nome, peças (a quantidade de um item específico), peso e valor. Os itens precisam ser selecionados de maneira que o peso total não exceda o peso máximo e que o valor seja maximizado. Tenha em mente que cada item pode aparecer entre 0 e `pieces` (peças) vezes.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function to solve the knapsack problem. The function is given the array of objects and the maximum weight as parameters. It should return the maximum total value possible.
|
||||
Escreva uma função para resolver o problema da mochila. A função recebe o array de objetos e o peso máximo como parâmetros. Ela deve devolver o valor máximo total possível.
|
||||
|
||||
# --hints--
|
||||
|
||||
`findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 300)` should return `755`.
|
||||
`findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 300)` deve retornar `755`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -44,7 +44,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 400)` should return `875`.
|
||||
`findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 400)` deve retornar `875`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -70,7 +70,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 500)` should return `1015`.
|
||||
`findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 500)` deve retornar `1015`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -96,7 +96,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 600)` should return `1120`.
|
||||
`findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 600)` deve retornar `1120`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -122,7 +122,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 700)` should return `1225`.
|
||||
`findBestPack([{ name:'map', weight:9, value:150, pieces:1 }, { name:'compass', weight:13, value:35, pieces:1 }, { name:'water', weight:153, value:200, pieces:2 }, { name:'sandwich', weight:50, value:60, pieces:2 }, { name:'glucose', weight:15, value:60, pieces:2 }, { name:'tin', weight:68, value:45, pieces:3 }, { name:'banana', weight:27, value:60, pieces:3 }, { name:'apple', weight:39, value:40, pieces:3 }, { name:'cheese', weight:23, value:30, pieces:1 }, { name:'beer', weight:52, value:10, pieces:3 }, { name:'suntan, cream', weight:11, value:70, pieces:1 }, { name:'camera', weight:32, value:30, pieces:1 }, { name:'T-shirt', weight:24, value:15, pieces:2 }], 700)` deve retornar `1225`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7ed3
|
||||
title: Knapsack problem/Continuous
|
||||
title: O problema da mochila/contínuo
|
||||
challengeType: 5
|
||||
forumTopicId: 323654
|
||||
dashedName: knapsack-problemcontinuous
|
||||
@ -8,17 +8,17 @@ dashedName: knapsack-problemcontinuous
|
||||
|
||||
# --description--
|
||||
|
||||
A thief burgles a butcher's shop, where he can select from some items.
|
||||
Um ladrão rouba um açougue, onde ele pode escolher entre alguns itens.
|
||||
|
||||
The thief knows the weights and prices of each items. Because he has a knapsack with a limit on the maximum weight that it can carry, he wants to select the items such that he would have his profit maximized. He may cut the items; the item has a reduced price after cutting that is proportional to the original price by the ratio of masses. That means: half of an item has half the price of the original.
|
||||
O ladrão sabe os pesos e os preços de cada um dos itens. Como ele tem uma mochila com um limite máximo de peso que ele pode carregar, ele quer selecionar os itens que farão com que ele tenha o máximo de lucro. Ele pode cortar os itens. O item tem um preço reduzido após o corte, que é proporcional ao preço original em razão da proporção das massas. Isso significa que metade de um item tem metade do preço original.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes an array of objects representing the items available in the shop. Each object has 3 attributes: name, weight, and value. The function also takes the maximum weight as a parameter. The function should return the maximum value possible, and the total weight of the selected items should not exceed the maximum weight.
|
||||
Escreva uma função que recebe um array de objetos representando os itens disponíveis no açougue. Cada objeto tem 3 atributos: nome, peso e valor. A função também recebe o peso máximo como parâmetro. A função deve retornar o valor máximo possível. Além disso, o peso total dos itens selecionados não deve exceder o peso máximo.
|
||||
|
||||
# --hints--
|
||||
|
||||
`knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 10)` should return `257.875`.
|
||||
`knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 10)` deve retornar `257.875`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -40,7 +40,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 12)` should return `295.05405405405406`.
|
||||
`knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 12)` deve retornar `295.05405405405406`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -62,7 +62,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 15)` should return `349.3783783783784`.
|
||||
`knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 15)` deve retornar `349.3783783783784`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -84,7 +84,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 22)` should return `459.5263157894737`.
|
||||
`knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 22)` deve retornar `459.5263157894737`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -106,7 +106,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 24)` should return `478.4736842105263`.
|
||||
`knapContinuous([{ "weight":3.8, "value":36, name:"beef" }, { "weight":5.4, "value":43, name:"pork" }, { "weight":3.6, "value":90, name:"ham" }, { "weight":2.4, "value":45, name:"greaves" }, { "weight":4.0, "value":30, name:"flitch" }, { "weight":2.5, "value":56, name:"brawn" }, { "weight":3.7, "value":67, name:"welt" }, { "weight":3.0, "value":95, name:"salami" }, { "weight":5.9, "value":98, name:"sausage" }], 24)` deve retornar `478.4736842105263`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7ed4
|
||||
title: Knapsack problem/Unbounded
|
||||
title: O problema da mochila/ilimitado
|
||||
challengeType: 5
|
||||
forumTopicId: 323655
|
||||
dashedName: knapsack-problemunbounded
|
||||
@ -8,21 +8,21 @@ dashedName: knapsack-problemunbounded
|
||||
|
||||
# --description--
|
||||
|
||||
A traveler gets diverted and has to make an unscheduled stop in what turns out to be Shangri-La. Opting to leave, he is allowed to take as much as he likes of the items available there, so long as it will fit in his knapsack, and he can carry it.
|
||||
Um viajante se perde e tem que fazer uma parada não programada em um lugar conhecido como Xangrilá. Quando decide ir embora, permitem que ele leve o quanto quiser dos itens disponíveis lá, desde que caibam em sua mochila e que ele consiga carregar a mochila.
|
||||
|
||||
He knows that he can carry no more than a particular value of maximum weight in total; and that the capacity of his knapsack has a limited volume.
|
||||
Ele sabe que não pode ter carregar mais do que um valor específico de peso máximo e que a mochila tem um volume limitado de capacidade.
|
||||
|
||||
Looking just above the bar codes on the items he finds their weights and volumes. He digs out his recent copy of a financial paper and gets the value of each item.
|
||||
Olhando logo acima dos códigos de barras dos itens, ele encontra os pesos e volumes. Ele procura e encontra uma cópia de um jornal financeiro e obtém o valor de cada item.
|
||||
|
||||
He can only take whole units of any item, but there is much more of any item than he could ever carry.
|
||||
Ele pode carregar apenas unidades inteiras de qualquer item, mas há muito mais coisas do que ele jamais poderia transportar.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes an array of objects, maximum weight, and maximum volume as parameters. Each object has 4 attributes: name, value, weight, and volume. The function should return the maximum value of items the traveller can take with him.
|
||||
Escreva uma função que recebe um array de objetos, o peso máximo e o volume máximo como parâmetros. Cada objeto tem 4 atributos: nome, valor, peso e volume. A função deve retornar o valor máximo de itens que o viajante pode levar com ele.
|
||||
|
||||
# --hints--
|
||||
|
||||
`knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.25)` should return `54500`.
|
||||
`knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.25)` deve retornar `54500`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -39,7 +39,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 55, 0.25)` should return `88400`.
|
||||
`knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 55, 0.25)` deve retornar `88400`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -56,7 +56,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.15)` should return `42500`.
|
||||
`knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 25, 0.15)` deve retornar `42500`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -73,7 +73,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 35, 0.35)` should return `75900`.
|
||||
`knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 35, 0.35)` deve retornar `75900`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -90,7 +90,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 15, 0.25)` should return `43200`.
|
||||
`knapsackUnbounded([{ name:"panacea", value:3000, weight:0.3, volume:0.025 }, { name:"ichor", value:1800, weight:0.2, volume:0.015 }, { name:"gold", value:2500, weight:2, volume:0.002 }], 15, 0.25)` deve retornar `43200`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7ed5
|
||||
title: Knight's tour
|
||||
title: O passeio do cavalo
|
||||
challengeType: 5
|
||||
forumTopicId: 302297
|
||||
dashedName: knights-tour
|
||||
@ -8,51 +8,51 @@ dashedName: knights-tour
|
||||
|
||||
# --description--
|
||||
|
||||
[Knight's Tour](https://en.wikipedia.org/wiki/Knight%27s_tour) Problem: You have an empty `w` \* `h` chessboard, but for a single knight on some square. The knight must perform a sequence of legal moves that result in the knight visiting every square on the chessboard exactly once. Note that it is *not* a requirement that the tour be "closed"; that is, the knight need not end within a single move of its start position.
|
||||
O problema do [Passeio do cavalo](https://en.wikipedia.org/wiki/Knight%27s_tour): você tem um tabuleiro de xadrez vazio de `w` \* `h`, exceto por um único cavalo em uma das posições. O cavalo deve realizar uma sequência de movimentos legais que resultem na visita de todas as posições do tabuleiro exatamente uma única vez. Observe que *não* é um requisito que o passeio seja "fechado". Em outras palavras, o cavalo não precisa terminar a um único movimento de sua posição inicial.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes `w` and `h` as parameters and returns the number of initial positions from where it is possible to achieve the task stated above.
|
||||
Escreva uma função que receba `w` e `h` como parâmetros e retorne o número de posições iniciais de onde é possível realizar a tarefa indicada acima.
|
||||
|
||||
# --hints--
|
||||
|
||||
`knightTour` should be a function.
|
||||
`knightTour` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof knightTour == 'function');
|
||||
```
|
||||
|
||||
`knightTour(6, 6)` should return a number.
|
||||
`knightTour(6, 6)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof knightTour(6, 6) == 'number');
|
||||
```
|
||||
|
||||
`knightTour(6, 6)` should return `36`.
|
||||
`knightTour(6, 6)` deve retornar `36`.
|
||||
|
||||
```js
|
||||
assert.equal(knightTour(6, 6), 36);
|
||||
```
|
||||
|
||||
`knightTour(5, 6)` should return `30`.
|
||||
`knightTour(5, 6)` deve retornar `30`.
|
||||
|
||||
```js
|
||||
assert.equal(knightTour(5, 6), 30);
|
||||
```
|
||||
|
||||
`knightTour(4, 6)` should return `12`.
|
||||
`knightTour(4, 6)` deve retornar `12`.
|
||||
|
||||
```js
|
||||
assert.equal(knightTour(4, 6), 12);
|
||||
```
|
||||
|
||||
`knightTour(7, 3)` should return `10`.
|
||||
`knightTour(7, 3)` deve retornar `10`.
|
||||
|
||||
```js
|
||||
assert.equal(knightTour(7, 3), 10);
|
||||
```
|
||||
|
||||
`knightTour(8, 6)` should return `48`.
|
||||
`knightTour(8, 6)` deve retornar `48`.
|
||||
|
||||
```js
|
||||
assert.equal(knightTour(8, 6), 48);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7edb
|
||||
title: Largest int from concatenated ints
|
||||
title: Maior int de ints concatenados
|
||||
challengeType: 5
|
||||
forumTopicId: 302298
|
||||
dashedName: largest-int-from-concatenated-ints
|
||||
@ -8,47 +8,47 @@ dashedName: largest-int-from-concatenated-ints
|
||||
|
||||
# --description--
|
||||
|
||||
Given a set of positive integers, write a function to order the integers in such a way that the concatenation of the numbers forms the largest possible integer and return this integer.
|
||||
Dado um conjunto de números inteiros positivos, escreva uma função para ordenar os números de tal forma que a concatenação dos números forme o maior número inteiro possível e retorne este inteiro.
|
||||
|
||||
# --hints--
|
||||
|
||||
`maxCombine` should be a function.
|
||||
`maxCombine` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof maxCombine == 'function');
|
||||
```
|
||||
|
||||
`maxCombine([1, 3, 3, 4, 55])` should return a number.
|
||||
`maxCombine([1, 3, 3, 4, 55])` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof maxCombine([1, 3, 3, 4, 55]) == 'number');
|
||||
```
|
||||
|
||||
`maxCombine([1, 3, 3, 4, 55])` should return `554331`.
|
||||
`maxCombine([1, 3, 3, 4, 55])` deve retornar `554331`.
|
||||
|
||||
```js
|
||||
assert.equal(maxCombine([1, 3, 3, 4, 55]), 554331);
|
||||
```
|
||||
|
||||
`maxCombine([71, 45, 23, 4, 5])` should return `71545423`.
|
||||
`maxCombine([71, 45, 23, 4, 5])` deve retornar `71545423`.
|
||||
|
||||
```js
|
||||
assert.equal(maxCombine([71, 45, 23, 4, 5]), 71545423);
|
||||
```
|
||||
|
||||
`maxCombine([14, 43, 53, 114, 55])` should return `55534314114`.
|
||||
`maxCombine([14, 43, 53, 114, 55])` deve retornar `55534314114`.
|
||||
|
||||
```js
|
||||
assert.equal(maxCombine([14, 43, 53, 114, 55]), 55534314114);
|
||||
```
|
||||
|
||||
`maxCombine([1, 34, 3, 98, 9, 76, 45, 4])` should return `998764543431`.
|
||||
`maxCombine([1, 34, 3, 98, 9, 76, 45, 4])` deve retornar `998764543431`.
|
||||
|
||||
```js
|
||||
assert.equal(maxCombine([1, 34, 3, 98, 9, 76, 45, 4]), 998764543431);
|
||||
```
|
||||
|
||||
`maxCombine([54, 546, 548, 60])` should return `6054854654`.
|
||||
`maxCombine([54, 546, 548, 60])` deve retornar `6054854654`.
|
||||
|
||||
```js
|
||||
assert.equal(maxCombine([54, 546, 548, 60]), 6054854654);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7edc
|
||||
title: Last Friday of each month
|
||||
title: Última sexta-feira de cada mês
|
||||
challengeType: 5
|
||||
forumTopicId: 302299
|
||||
dashedName: last-friday-of-each-month
|
||||
@ -8,65 +8,65 @@ dashedName: last-friday-of-each-month
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function that returns the date of the last Friday of a given month for a given year.
|
||||
Escreva uma função que retorne a data da última sexta-feira de um mês fornecido para um determinado ano.
|
||||
|
||||
# --hints--
|
||||
|
||||
`lastFriday` should be a function.
|
||||
`lastFriday` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof lastFriday == 'function');
|
||||
```
|
||||
|
||||
`lastFriday(2018, 1)` should return a number.
|
||||
`lastFriday(2018, 1)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof lastFriday(2018, 1) == 'number');
|
||||
```
|
||||
|
||||
`lastFriday(2018, 1)` should return `26`.
|
||||
`lastFriday(2018, 1)` deve retornar `26`.
|
||||
|
||||
```js
|
||||
assert.equal(lastFriday(2018, 1), 26);
|
||||
```
|
||||
|
||||
`lastFriday(2017, 2)` should return `24`.
|
||||
`lastFriday(2017, 2)` deve retornar `24`.
|
||||
|
||||
```js
|
||||
assert.equal(lastFriday(2017, 2), 24);
|
||||
```
|
||||
|
||||
`lastFriday(2012, 3)` should return `30`.
|
||||
`lastFriday(2012, 3)` deve retornar `30`.
|
||||
|
||||
```js
|
||||
assert.equal(lastFriday(2012, 3), 30);
|
||||
```
|
||||
|
||||
`lastFriday(1900, 4)` should return `27`.
|
||||
`lastFriday(1900, 4)` deve retornar `27`.
|
||||
|
||||
```js
|
||||
assert.equal(lastFriday(1900, 4), 27);
|
||||
```
|
||||
|
||||
`lastFriday(2000, 5)` should return `26`.
|
||||
`lastFriday(2000, 5)` deve retornar `26`.
|
||||
|
||||
```js
|
||||
assert.equal(lastFriday(2000, 5), 26);
|
||||
```
|
||||
|
||||
`lastFriday(2006, 6)` should return `30`.
|
||||
`lastFriday(2006, 6)` deve retornar `30`.
|
||||
|
||||
```js
|
||||
assert.equal(lastFriday(2006, 6), 30);
|
||||
```
|
||||
|
||||
`lastFriday(2010, 7)` should return `30`.
|
||||
`lastFriday(2010, 7)` deve retornar `30`.
|
||||
|
||||
```js
|
||||
assert.equal(lastFriday(2010, 7), 30);
|
||||
```
|
||||
|
||||
`lastFriday(2005, 8)` should return `26`.
|
||||
`lastFriday(2005, 8)` deve retornar `26`.
|
||||
|
||||
```js
|
||||
assert.equal(lastFriday(2005, 8), 26);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e4ce2b6ac708cc68c1df25e
|
||||
title: Last letter-first letter
|
||||
title: Última letra-primeira letra
|
||||
challengeType: 5
|
||||
forumTopicId: 385256
|
||||
dashedName: last-letter-first-letter
|
||||
@ -8,30 +8,30 @@ dashedName: last-letter-first-letter
|
||||
|
||||
# --description--
|
||||
|
||||
A certain children's game involves starting with a word in a particular category. Each participant in turn says a word, but that word must begin with the final letter of the previous word. Once a word has been given, it cannot be repeated. If an opponent cannot give a word in the category, they fall out of the game.
|
||||
Um certo jogo infantil envolve começar com uma palavra em uma determinada categoria. Cada participante, em sua vez, diz uma palavra, mas essa palavra deve começar com a letra final da palavra anterior. Quando uma palavra é dita, ela não pode ser repetida. Se o oponente não disser uma palavra da categoria, ele sai do jogo.
|
||||
|
||||
For example, with "animals" as the category,
|
||||
Por exemplo, com a categoria "animais",
|
||||
|
||||
<pre>Child 1: dog
|
||||
Child 2: goldfish
|
||||
Child 1: hippopotamus
|
||||
Child 2: snake
|
||||
<pre>Criança 1: cachorro
|
||||
Criança 2: onça
|
||||
Criança 1: antílope
|
||||
Criança 2: elefante
|
||||
...
|
||||
</pre>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes an input array of words. The function should return an array of words where the first letter of each word is the same as the last letter of the previous word. Only use the words in the input array, and once a word is used it cannot be repeated. The words in the return array should be selected and sequenced so that that its length is maximized.
|
||||
Escreva uma função que receba um array de palavras. A função deve retornar um array de palavras em que a primeira letra de cada palavra é a mesma que a última letra da palavra anterior. Use apenas as palavras do array de entrada. Quando uma palavra for usada, ela não poderá ser repetida. As palavras no array de retorno devem ser selecionadas e sequenciadas para que o comprimento do array seja maximizado.
|
||||
|
||||
# --hints--
|
||||
|
||||
`findLongestChain` should be a function.
|
||||
`findLongestChain` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof findLongestChain == 'function');
|
||||
```
|
||||
|
||||
`findLongestChain(["certain", "each", "game", "involves", "starting", "with", "word"])` should return an array.
|
||||
`findLongestChain(["certain", "each", "game", "involves", "starting", "with", "word"])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -49,7 +49,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestChain(["certain", "each", "game", "involves", "starting", "with", "word"])` should return `["involves", "starting", "game", "each"]`.
|
||||
`findLongestChain(["certain", "each", "game", "involves", "starting", "with", "word"])` deve retornar `["involves", "starting", "game", "each"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -66,7 +66,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestChain(["audino", "bagon", "kangaskhan", "banette", "bidoof", "braviary", "exeggcute", "yamask"])` should return `["braviary", "yamask", "kangaskhan"]`
|
||||
`findLongestChain(["audino", "bagon", "kangaskhan", "banette", "bidoof", "braviary", "exeggcute", "yamask"])` deve retornar `["braviary", "yamask", "kangaskhan"]`
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -84,7 +84,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestChain(["harp", "poliwrath", "poochyena", "porygon2", "porygonz", "archana"])` should return `["poliwrath", "harp", "poochyena", "archana"]`.
|
||||
`findLongestChain(["harp", "poliwrath", "poochyena", "porygon2", "porygonz", "archana"])` deve retornar `["poliwrath", "harp", "poochyena", "archana"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -100,7 +100,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestChain(["scolipede", "elephant", "zeaking", "sealeo", "silcoon", "tigers"])` should return `["scolipede", "elephant", "tigers", "sealeo"]`.
|
||||
`findLongestChain(["scolipede", "elephant", "zeaking", "sealeo", "silcoon", "tigers"])` deve retornar `["scolipede", "elephant", "tigers", "sealeo"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -116,7 +116,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`findLongestChain(["loudred", "lumineon", "lunatone", "machamp", "magnezone", "nosepass", "petilil", "pidgeotto", "pikachu"])` should return `["machamp", "petilil", "lumineon", "nosepass"]`.
|
||||
`findLongestChain(["loudred", "lumineon", "lunatone", "machamp", "magnezone", "nosepass", "petilil", "pidgeotto", "pikachu"])` deve retornar `["machamp", "petilil", "lumineon", "nosepass"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7ede
|
||||
title: Leap year
|
||||
title: Ano bissexto
|
||||
challengeType: 5
|
||||
forumTopicId: 302300
|
||||
dashedName: leap-year
|
||||
@ -8,53 +8,53 @@ dashedName: leap-year
|
||||
|
||||
# --description--
|
||||
|
||||
Determine whether a given year is a leap year in the Gregorian calendar.
|
||||
Determine se o ano fornecido é um ano bissexto no calendário Gregoriano.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isLeapYear` should be a function.
|
||||
`isLeapYear` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof isLeapYear == 'function');
|
||||
```
|
||||
|
||||
`isLeapYear()` should return a boolean.
|
||||
`isLeapYear()` deve retornar um booleano.
|
||||
|
||||
```js
|
||||
assert(typeof isLeapYear(2018) == 'boolean');
|
||||
```
|
||||
|
||||
`isLeapYear(2018)` should return `false`.
|
||||
`isLeapYear(2018)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isLeapYear(2018), false);
|
||||
```
|
||||
|
||||
`isLeapYear(2016)` should return `true`.
|
||||
`isLeapYear(2016)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isLeapYear(2016), true);
|
||||
```
|
||||
|
||||
`isLeapYear(2000)` should return `true`.
|
||||
`isLeapYear(2000)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isLeapYear(2000), true);
|
||||
```
|
||||
|
||||
`isLeapYear(1900)` should return `false`.
|
||||
`isLeapYear(1900)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isLeapYear(1900), false);
|
||||
```
|
||||
|
||||
`isLeapYear(1996)` should return `true`.
|
||||
`isLeapYear(1996)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isLeapYear(1996), true);
|
||||
```
|
||||
|
||||
`isLeapYear(1800)` should return `false`.
|
||||
`isLeapYear(1800)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isLeapYear(1800), false);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7edf
|
||||
title: Least common multiple
|
||||
title: Mínimo múltiplo comum
|
||||
challengeType: 5
|
||||
forumTopicId: 302301
|
||||
dashedName: least-common-multiple
|
||||
@ -8,51 +8,51 @@ dashedName: least-common-multiple
|
||||
|
||||
# --description--
|
||||
|
||||
The least common multiple of 12 and 18 is 36, because 12 is a factor (12 × 3 = 36), and 18 is a factor (18 × 2 = 36), and there is no positive integer less than 36 that has both factors. As a special case, if either *m* or *n* is zero, then the least common multiple is zero. One way to calculate the least common multiple is to iterate all the multiples of *m*, until you find one that is also a multiple of *n*. If you already have *gcd* for [greatest common divisor](https://rosettacode.org/wiki/greatest common divisor), then this formula calculates *lcm*. ( \\operatorname{lcm}(m, n) = \\frac{|m \\times n|}{\\operatorname{gcd}(m, n)} )
|
||||
O mínimo múltiplo comum de 12 e 18 é 36, porque 12 é um fator (12 × 3 = 36) e 18 é um fator (18 × 2 = 36). Além disso, não há nenhum inteiro positivo menor que 36 que tenha ambos os fatores. Por ser um caso especial, se *m* ou *n* for zero, o mínimo múltiplo comum é zero. Uma maneira de calcular o mínimo múltiplo comum é iterar todos os múltiplos de *m*, até encontrar um que também seja múltiplo de *n*. Se você já tiver o *gcd* para o [máximo divisor comum](https://rosettacode.org/wiki/greatest common divisor), esta fórmula calcula o *lcm*. ( \\operatorname{lcm}(m, n) = \\frac{|m \\times n|}{\\operatorname{gcd}(m, n)} )
|
||||
|
||||
# --instructions--
|
||||
|
||||
Compute the least common multiple of an array of integers. Given *m* and *n*, the least common multiple is the smallest positive integer that has both *m* and *n* as factors.
|
||||
Calcule o mínimo múltiplo comum de um array de números inteiros. Dados *m* e *n*, o mínimo múltiplo comum é o menor número inteiro positivo que tenha tanto *m* quanto *n* como fatores.
|
||||
|
||||
# --hints--
|
||||
|
||||
`LCM` should be a function.
|
||||
`LCM` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof LCM == 'function');
|
||||
```
|
||||
|
||||
`LCM([2, 4, 8])` should return a number.
|
||||
`LCM([2, 4, 8])` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof LCM([2, 4, 8]) == 'number');
|
||||
```
|
||||
|
||||
`LCM([2, 4, 8])` should return `8`.
|
||||
`LCM([2, 4, 8])` deve retornar `8`.
|
||||
|
||||
```js
|
||||
assert.equal(LCM([2, 4, 8]), 8);
|
||||
```
|
||||
|
||||
`LCM([4, 8, 12])` should return `24`.
|
||||
`LCM([4, 8, 12])` deve retornar `24`.
|
||||
|
||||
```js
|
||||
assert.equal(LCM([4, 8, 12]), 24);
|
||||
```
|
||||
|
||||
`LCM([3, 4, 5, 12, 40])` should return `120`.
|
||||
`LCM([3, 4, 5, 12, 40])` deve retornar `120`.
|
||||
|
||||
```js
|
||||
assert.equal(LCM([3, 4, 5, 12, 40]), 120);
|
||||
```
|
||||
|
||||
`LCM([11, 33, 90])` should return `990`.
|
||||
`LCM([11, 33, 90])` deve retornar `990`.
|
||||
|
||||
```js
|
||||
assert.equal(LCM([11, 33, 90]), 990);
|
||||
```
|
||||
|
||||
`LCM([-50, 25, -45, -18, 90, 447])` should return `67050`.
|
||||
`LCM([-50, 25, -45, -18, 90, 447])` deve retornar `67050`.
|
||||
|
||||
```js
|
||||
assert.equal(LCM([-50, 25, -45, -18, 90, 447]), 67050);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7ee0
|
||||
title: Left factorials
|
||||
title: Fatoriais restantes
|
||||
challengeType: 5
|
||||
forumTopicId: 302302
|
||||
dashedName: left-factorials
|
||||
@ -8,75 +8,75 @@ dashedName: left-factorials
|
||||
|
||||
# --description--
|
||||
|
||||
**Left factorials**, $ !n $, may refer to either *subfactorials* or to *factorial sums*. The same notation can be confusingly seen used for the two different definitions. Sometimes, *subfactorials* (also known as *derangements*) may use any of the notations:
|
||||
**Fatoriais restantes**, $ !n $, podem se referir a *subfatoriais* ou a *somas de fatorial*. A mesma notação pode ser vista de modo confuso para as duas definições diferentes. Às vezes, *subfatoriais* (também conhecidos como *desarranjos*) podem usar qualquer uma das notações a seguir:
|
||||
|
||||
<ul>
|
||||
<li>$!n`$</li>
|
||||
<li>$!n$</li>
|
||||
<li>$!n$</li>
|
||||
<li>$n¡$</li>
|
||||
</ul>
|
||||
|
||||
(It may not be visually obvious, but the last example uses an upside-down exclamation mark.) This task will be using this formula for **left factorial**:
|
||||
(Pode não ser visualmente óbvio, mas o último exemplo utiliza um ponto de exclamação ascendente.) Esta tarefa usará essa fórmula para o **fatorial restante**:
|
||||
|
||||
$ !n = \\sum\_{k=0}^{n-1} k! $
|
||||
|
||||
where $!0 = 0$
|
||||
onde $!0 = 0$
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function to calculate the left factorial of a given number.
|
||||
Escreva uma função que calcule o fatorial restante de um certo número.
|
||||
|
||||
# --hints--
|
||||
|
||||
`leftFactorial` should be a function.
|
||||
`leftFactorial` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof leftFactorial == 'function');
|
||||
```
|
||||
|
||||
`leftFactorial(0)` should return a number.
|
||||
`leftFactorial(0)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof leftFactorial(0) == 'number');
|
||||
```
|
||||
|
||||
`leftFactorial(0)` should return `0`.
|
||||
`leftFactorial(0)` deve retornar `0`.
|
||||
|
||||
```js
|
||||
assert.equal(leftFactorial(0), 0);
|
||||
```
|
||||
|
||||
`leftFactorial(1)` should return `1`.
|
||||
`leftFactorial(1)` deve retornar `1`.
|
||||
|
||||
```js
|
||||
assert.equal(leftFactorial(1), 1);
|
||||
```
|
||||
|
||||
`leftFactorial(2)` should return `2`.
|
||||
`leftFactorial(2)` deve retornar `2`.
|
||||
|
||||
```js
|
||||
assert.equal(leftFactorial(2), 2);
|
||||
```
|
||||
|
||||
`leftFactorial(3)` should return `4`.
|
||||
`leftFactorial(3)` deve retornar `4`.
|
||||
|
||||
```js
|
||||
assert.equal(leftFactorial(3), 4);
|
||||
```
|
||||
|
||||
`leftFactorial(10)` should return `409114`.
|
||||
`leftFactorial(10)` deve retornar `409114`.
|
||||
|
||||
```js
|
||||
assert.equal(leftFactorial(10), 409114);
|
||||
```
|
||||
|
||||
`leftFactorial(17)` should return `22324392524314`.
|
||||
`leftFactorial(17)` deve retornar `22324392524314`.
|
||||
|
||||
```js
|
||||
assert.equal(leftFactorial(17), 22324392524314);
|
||||
```
|
||||
|
||||
`leftFactorial(19)` should return `6780385526348314`.
|
||||
`leftFactorial(19)` deve retornar `6780385526348314`.
|
||||
|
||||
```js
|
||||
assert.equal(leftFactorial(19), 6780385526348314);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e4ce2bbac708cc68c1df25f
|
||||
title: Letter frequency
|
||||
title: Frequência de letras
|
||||
challengeType: 5
|
||||
forumTopicId: 385263
|
||||
dashedName: letter-frequency
|
||||
@ -8,33 +8,33 @@ dashedName: letter-frequency
|
||||
|
||||
# --description--
|
||||
|
||||
Given a string, calculate the frequency of each character.
|
||||
Ao receber uma string, calcule a frequência de cada caractere.
|
||||
|
||||
All characters should be counted. This includes lower and upper case letters, digits, whitespace, special characters, or any other distinct characters.
|
||||
Todos os caracteres devem ser contados. Isto inclui letras minúsculas e maiúsculas, dígitos, espaços em branco, caracteres especiais ou quaisquer outros caracteres distintos.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function to count the occurrences of each character in a given string.
|
||||
Escreva uma função para contar as ocorrências de cada caractere em uma determinada string.
|
||||
|
||||
The function should return a 2D array with each of the elements in the following form: `['char', freq]`. The character should be a string with a length of 1, and frequency is a number denoting the count.
|
||||
A função deve retornar um array bidimensional com cada um dos elementos na seguinte forma: `['char', freq]`. O caractere deve ser uma string de comprimento 1, e a frequência deve ser um número que indique a contagem.
|
||||
|
||||
For example, given the string "ab", your function should return `[['a', 1], ['b', 1]]`.
|
||||
Por exemplo, dada a string "ab", sua função deve retornar `[['a', 1], ['b', 1]]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`letterFrequency` should be a function.
|
||||
`letterFrequency` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof letterFrequency == 'function');
|
||||
```
|
||||
|
||||
`letterFrequency("Not all that Mrs. Bennet, however")` should return an array.
|
||||
`letterFrequency("Not all that Mrs. Bennet, however")` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(letterFrequency('Not all that Mrs. Bennet, however')));
|
||||
```
|
||||
|
||||
`letterFrequency("Not all that Mrs. Bennet, however")` should return `[[" ", 5], [",", 1], [".", 1], ["B", 1], ["M", 1], ["N", 1], ["a", 2], ["e", 4], ["h", 2], ["l", 2], ["n", 2], ["o", 2], ["r", 2], ["s", 1], ["t", 4], ["v", 1], ["w", 1]]`.
|
||||
`letterFrequency("Not all that Mrs. Bennet, however")` deve retornar `[[" ", 5], [",", 1], [".", 1], ["B", 1], ["M", 1], ["N", 1], ["a", 2], ["e", 4], ["h", 2], ["l", 2], ["n", 2], ["o", 2], ["r", 2], ["s", 1], ["t", 4], ["v", 1], ["w", 1]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(letterFrequency('Not all that Mrs. Bennet, however'), [
|
||||
@ -58,7 +58,7 @@ assert.deepEqual(letterFrequency('Not all that Mrs. Bennet, however'), [
|
||||
]);
|
||||
```
|
||||
|
||||
`letterFrequency("daughters, could ask on the ")` should return `[[" ", 5],[",", 1],["a", 2],["c", 1],["d", 2],["e", 2],["g", 1],["h", 2],["k", 1],["l", 1],["n", 1],["o", 2],["r", 1],["s", 2],["t", 2],["u", 2]]`.
|
||||
`letterFrequency("daughters, could ask on the ")` deve retornar `[[" ", 5],[",", 1],["a", 2],["c", 1],["d", 2],["e", 2],["g", 1],["h", 2],["k", 1],["l", 1],["n", 1],["o", 2],["r", 1],["s", 2],["t", 2],["u", 2]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(letterFrequency('daughters, could ask on the '), [
|
||||
@ -81,7 +81,7 @@ assert.deepEqual(letterFrequency('daughters, could ask on the '), [
|
||||
]);
|
||||
```
|
||||
|
||||
`letterFrequency("husband any satisfactory description")` should return `[[" ", 3], ["a", 4], ["b", 1], ["c", 2], ["d", 2], ["e", 1], ["f", 1], ["h", 1], ["i", 3], ["n", 3], ["o", 2], ["p", 1], ["r", 2], ["s", 4], ["t", 3], ["u", 1], ["y", 2]]`.
|
||||
`letterFrequency("husband any satisfactory description")` deve retornar `[[" ", 3], ["a", 4], ["b", 1], ["c", 2], ["d", 2], ["e", 1], ["f", 1], ["h", 1], ["i", 3], ["n", 3], ["o", 2], ["p", 1], ["r", 2], ["s", 4], ["t", 3], ["u", 1], ["y", 2]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(letterFrequency('husband any satisfactory description'), [
|
||||
@ -105,7 +105,7 @@ assert.deepEqual(letterFrequency('husband any satisfactory description'), [
|
||||
]);
|
||||
```
|
||||
|
||||
`letterFrequency("in various ways--with barefaced")` should return `[[" ", 3], ["-", 2], ["a", 4], ["b", 1], ["c", 1], ["d", 1], ["e", 2], ["f", 1], ["h", 1], ["i", 3], ["n", 1], ["o", 1], ["r", 2], ["s", 2], ["t", 1], ["u", 1], ["v", 1], ["w", 2], ["y", 1]]`.
|
||||
`letterFrequency("in various ways--with barefaced")` deve retornar `[[" ", 3], ["-", 2], ["a", 4], ["b", 1], ["c", 1], ["d", 1], ["e", 2], ["f", 1], ["h", 1], ["i", 3], ["n", 1], ["o", 1], ["r", 2], ["s", 2], ["t", 1], ["u", 1], ["v", 1], ["w", 2], ["y", 1]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(letterFrequency('in various ways--with barefaced'), [
|
||||
@ -131,7 +131,7 @@ assert.deepEqual(letterFrequency('in various ways--with barefaced'), [
|
||||
]);
|
||||
```
|
||||
|
||||
`letterFrequency("distant surmises; but he eluded")` should return `[[" ", 4], [";", 1], ["a", 1], ["b", 1], ["d", 3], ["e", 4], ["h", 1], ["i", 2], ["l", 1], ["m", 1], ["n", 1], ["r", 1], ["s", 4], ["t", 3], ["u", 3]]`.
|
||||
`letterFrequency("distant surmises; but he eluded")` deve retornar `[[" ", 4], [";", 1], ["a", 1], ["b", 1], ["d", 3], ["e", 4], ["h", 1], ["i", 2], ["l", 1], ["m", 1], ["n", 1], ["r", 1], ["s", 4], ["t", 3], ["u", 3]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(letterFrequency('distant surmises; but he eluded'), [
|
||||
@ -153,7 +153,7 @@ assert.deepEqual(letterFrequency('distant surmises; but he eluded'), [
|
||||
]);
|
||||
```
|
||||
|
||||
`letterFrequency("last obliged to accept the second-hand,")` should return `[[" ", 5], [",", 1], ["-", 1], ["a", 3], ["b", 1], ["c", 3], ["d", 3], ["e", 4], ["g", 1], ["h", 2], ["i", 1], ["l", 2], ["n", 2], ["o", 3], ["p", 1], ["s", 2], ["t", 4]]`.
|
||||
`letterFrequency("last obliged to accept the second-hand,")` deve retornar `[[" ", 5], [",", 1], ["-", 1], ["a", 3], ["b", 1], ["c", 3], ["d", 3], ["e", 4], ["g", 1], ["h", 2], ["i", 1], ["l", 2], ["n", 2], ["o", 3], ["p", 1], ["s", 2], ["t", 4]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(letterFrequency('last obliged to accept the second-hand,'), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e4ce2eaac708cc68c1df260
|
||||
title: Levenshtein distance
|
||||
title: Distância de Levenshtein
|
||||
challengeType: 5
|
||||
forumTopicId: 385264
|
||||
dashedName: levenshtein-distance
|
||||
@ -8,71 +8,71 @@ dashedName: levenshtein-distance
|
||||
|
||||
# --description--
|
||||
|
||||
In information theory and computer science, the **Levenshtein distance** is a [metric](https://en.wikipedia.org/wiki/string metric) for measuring the amount of difference between two sequences (i.e. an [edit distance](https://en.wikipedia.org/wiki/edit distance)). The Levenshtein distance between two strings is defined as the minimum number of edits needed to transform one string into the other, with the allowable edit operations being insertion, deletion, or substitution of a single character.
|
||||
Em teoria da informação e em ciência da computação, a **distância de Levenshtein** é uma [medida](https://en.wikipedia.org/wiki/string metric) para estimar o valor da diferença entre duas sequências (ou seja, uma [distância de edição](https://en.wikipedia.org/wiki/edit distance)). A distância de Levenshtein entre duas strings é definida como o número mínimo de edições necessárias para transformar uma sequência de caracteres em outra, com as operações de edição permitidas sendo inserção, exclusão ou substituição de um único caractere.
|
||||
|
||||
Example:
|
||||
Exemplo:
|
||||
|
||||
The Levenshtein distance between "**kitten**" and "**sitting**" is 3, since the following three edits change one into the other, and there isn't a way to do it with fewer than three edits:
|
||||
A distância de Levenshtein entre "**kitten**" e "**sitting**" é 3, já que as três edições a seguir mudam de uma palavra para a outra e não há modo de fazer isso com menos de três edições:
|
||||
|
||||
<ul>
|
||||
<li><strong>k</strong>itten <strong>s</strong>itten (substitution of 'k' with 's')</li>
|
||||
<li>sitt<strong>e</strong>n sitt<strong>i</strong>n (substitution of 'e' with 'i')</li>
|
||||
<li>sittin sittin<strong>g</strong> (insert 'g' at the end).</li>
|
||||
<li><strong>k</strong>itten <strong>s</strong>itten (substituição do 'k' pelo 's')</li>
|
||||
<li>sitt<strong>e</strong>n sitt<strong>i</strong>n (substituição do 'e' pelo 'i')</li>
|
||||
<li>sittin sittin<strong>g</strong> (inserção de 'g' ao final).</li>
|
||||
</ul>
|
||||
|
||||
*The Levenshtein distance between "**rosettacode**", "**raisethysword**" is **8**.*
|
||||
*A distância de Levenshtein entre "**rosettacode**" e "**raisethysword**" é de **8**.*
|
||||
|
||||
*The distance between two strings is same as that when both strings are reversed.*
|
||||
*A distância entre duas strings é a mesma que aquela quando ambas as strings são invertidas.*
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that returns the Levenshtein distance between two strings given as parameters.
|
||||
Escreva uma função que retorne a distância de Levenshtein entre duas strings dadas como parâmetros.
|
||||
|
||||
# --hints--
|
||||
|
||||
`levenshtein` should be a function.
|
||||
`levenshtein` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof levenshtein == 'function');
|
||||
```
|
||||
|
||||
`levenshtein("mist", "dist")` should return a number.
|
||||
`levenshtein("mist", "dist")` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof levenshtein('mist', 'dist') == 'number');
|
||||
```
|
||||
|
||||
`levenshtein("mist", "dist")` should return `1`.
|
||||
`levenshtein("mist", "dist")` deve retornar `1`.
|
||||
|
||||
```js
|
||||
assert.equal(levenshtein('mist', 'dist'), 1);
|
||||
```
|
||||
|
||||
`levenshtein("tier", "tor")` should return `2`.
|
||||
`levenshtein("tier", "tor")` deve retornar `2`.
|
||||
|
||||
```js
|
||||
assert.equal(levenshtein('tier', 'tor'), 2);
|
||||
```
|
||||
|
||||
`levenshtein("kitten", "sitting")` should return `3`.
|
||||
`levenshtein("kitten", "sitting")` deve retornar `3`.
|
||||
|
||||
```js
|
||||
assert.equal(levenshtein('kitten', 'sitting'), 3);
|
||||
```
|
||||
|
||||
`levenshtein("stop", "tops")` should return `2`.
|
||||
`levenshtein("stop", "tops")` deve retornar `2`.
|
||||
|
||||
```js
|
||||
assert.equal(levenshtein('stop', 'tops'), 2);
|
||||
```
|
||||
|
||||
`levenshtein("rosettacode", "raisethysword")` should return `8`.
|
||||
`levenshtein("rosettacode", "raisethysword")` deve retornar `8`.
|
||||
|
||||
```js
|
||||
assert.equal(levenshtein('rosettacode', 'raisethysword'), 8);
|
||||
```
|
||||
|
||||
`levenshtein("mississippi", "swiss miss")` should return `8`.
|
||||
`levenshtein("mississippi", "swiss miss")` deve retornar `8`.
|
||||
|
||||
```js
|
||||
assert.equal(levenshtein('mississippi', 'swiss miss'), 8);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e4ce2f5ac708cc68c1df261
|
||||
title: Linear congruential generator
|
||||
title: Gerador congruente linear
|
||||
challengeType: 5
|
||||
forumTopicId: 385266
|
||||
dashedName: linear-congruential-generator
|
||||
@ -8,65 +8,65 @@ dashedName: linear-congruential-generator
|
||||
|
||||
# --description--
|
||||
|
||||
The [linear congruential generator](https://en.wikipedia.org/wiki/linear congruential generator) is a very simple example of a [random number generator](http://rosettacode.org/wiki/random number generator). All linear congruential generators use this formula:
|
||||
O [gerador congruente linear](https://en.wikipedia.org/wiki/linear congruential generator) é um exemplo muito simples de um [gerador de números aleatórios](http://rosettacode.org/wiki/random number generator). Todos os geradores congruentes lineares usam esta fórmula:
|
||||
|
||||
$$r_{n + 1} = (a \times r_n + c) \bmod m$$
|
||||
|
||||
Where:
|
||||
Onde:
|
||||
|
||||
<ul>
|
||||
<li>$ r_0 $ is a seed.</li>
|
||||
<li>$r_1$, $r_2$, $r_3$, ..., are the random numbers.</li>
|
||||
<li>$a$, $c$, $m$ are constants.</li>
|
||||
<li>$ r_0 $ é uma seed.</li>
|
||||
<li>$r_1$, $r_2$, $r_3$, ..., são os números aleatórios.</li>
|
||||
<li>$a$, $c$, $m$ são constantes.</li>
|
||||
</ul>
|
||||
|
||||
If one chooses the values of $a$, $c$ and $m$ with care, then the generator produces a uniform distribution of integers from $0$ to $m - 1$.
|
||||
Se a escolha de $a$, $c$ e $m$ for feita com cuidado, o gerador produzirá uma distribuição uniforme de números inteiros de $0$ a $m - 1$.
|
||||
|
||||
LCG numbers have poor quality. $r_n$ and $r\_{n + 1}$ are not independent, as true random numbers would be. Anyone who knows $r_n$ can predict $r\_{n + 1}$, therefore LCG is not cryptographically secure. The LCG is still good enough for simple tasks like [Miller-Rabin primality test](http://rosettacode.org/wiki/Miller-Rabin primality test), or [FreeCell deals](http://rosettacode.org/wiki/deal cards for FreeCell). Among the benefits of the LCG, one can easily reproduce a sequence of numbers, from the same $r_0$. One can also reproduce such sequence with a different programming language, because the formula is so simple.
|
||||
Os números LCG são de má qualidade. $r_n$ e $r\_{n + 1}$ não são independentes como os números verdadeiramente aleatórios seriam. Qualquer um que conheça $r_n$ pode prever $r\_{n + 1}$. Assim, o LCG não é criptograficamente seguro. O LCG, ainda assim, é bom o suficiente para tarefas simples como [o teste de primalidade de Miller-Rabin ](http://rosettacode.org/wiki/Miller-Rabin primality test) ou [dar as cartas no FreeCell](http://rosettacode.org/wiki/deal cards for FreeCell). Entre os benefícios do LCG, pode-se facilmente reproduzir uma sequência de números, a partir da mesma $r_0$. Também é possível reproduzir essa sequência com uma linguagem de programação diferente, porque a fórmula é muito simples.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes $r_0,a,c,m,n$ as parameters and returns $r_n$.
|
||||
Escreva uma função que receba $r_0,a,c,m,n$ como parâmetros e retorne $r_n$.
|
||||
|
||||
# --hints--
|
||||
|
||||
`linearCongGenerator` should be a function.
|
||||
`linearCongGenerator` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof linearCongGenerator == 'function');
|
||||
```
|
||||
|
||||
`linearCongGenerator(324, 1145, 177, 2148, 3)` should return a number.
|
||||
`linearCongGenerator(324, 1145, 177, 2148, 3)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof linearCongGenerator(324, 1145, 177, 2148, 3) == 'number');
|
||||
```
|
||||
|
||||
`linearCongGenerator(324, 1145, 177, 2148, 3)` should return `855`.
|
||||
`linearCongGenerator(324, 1145, 177, 2148, 3)` deve retornar `855`.
|
||||
|
||||
```js
|
||||
assert.equal(linearCongGenerator(324, 1145, 177, 2148, 3), 855);
|
||||
```
|
||||
|
||||
`linearCongGenerator(234, 11245, 145, 83648, 4)` should return `1110`.
|
||||
`linearCongGenerator(234, 11245, 145, 83648, 4)` deve retornar `1110`.
|
||||
|
||||
```js
|
||||
assert.equal(linearCongGenerator(234, 11245, 145, 83648, 4), 1110);
|
||||
```
|
||||
|
||||
`linearCongGenerator(85, 11, 1234, 214748, 5)` should return `62217`.
|
||||
`linearCongGenerator(85, 11, 1234, 214748, 5)` deve retornar `62217`.
|
||||
|
||||
```js
|
||||
assert.equal(linearCongGenerator(85, 11, 1234, 214748, 5), 62217);
|
||||
```
|
||||
|
||||
`linearCongGenerator(0, 1103515245, 12345, 2147483648, 1)` should return `12345`.
|
||||
`linearCongGenerator(0, 1103515245, 12345, 2147483648, 1)` deve retornar `12345`.
|
||||
|
||||
```js
|
||||
assert.equal(linearCongGenerator(0, 1103515245, 12345, 2147483648, 1), 12345);
|
||||
```
|
||||
|
||||
`linearCongGenerator(0, 1103515245, 12345, 2147483648, 2)` should return `1406932606`.
|
||||
`linearCongGenerator(0, 1103515245, 12345, 2147483648, 2)` deve retornar `1406932606`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e4ce2a1ac708cc68c1df25d
|
||||
title: Long multiplication
|
||||
title: Multiplicação de números grandes
|
||||
challengeType: 5
|
||||
forumTopicId: 385269
|
||||
dashedName: long-multiplication
|
||||
@ -8,31 +8,31 @@ dashedName: long-multiplication
|
||||
|
||||
# --description--
|
||||
|
||||
Explicitly implement [long multiplication](https://en.wikipedia.org/wiki/long multiplication).
|
||||
Implemente explicitamente a [multiplicação de números grandes](https://en.wikipedia.org/wiki/long multiplication).
|
||||
|
||||
This is one possible approach to arbitrary-precision integer algebra.
|
||||
Esta é uma abordagem possível para a álgebra de números inteiros de precisão arbitrária.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes two strings of large numbers as parameters. Your function should return the product of these two large numbers as a string.
|
||||
Escreva uma função que receba duas strings de números grandes como parâmetros. A função deve devolver o produto desses dois números grandes como uma string.
|
||||
|
||||
**Note:** In JavaScript, arithmetic operations are inaccurate with large numbers, so you will have to implement precise multiplication yourself.
|
||||
**Observação:** em JavaScript, as operações aritméticas são imprecisas com números grandes, então você mesmo terá que implementar uma multiplicação exata.
|
||||
|
||||
# --hints--
|
||||
|
||||
`mult` should be a function.
|
||||
`mult` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof mult == 'function');
|
||||
```
|
||||
|
||||
`mult("18446744073709551616", "18446744073709551616")` should return a string.
|
||||
`mult("18446744073709551616", "18446744073709551616")` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(typeof mult('18446744073709551616', '18446744073709551616') == 'string');
|
||||
```
|
||||
|
||||
`mult("18446744073709551616", "18446744073709551616")` should return `"340282366920938463463374607431768211456"`.
|
||||
`mult("18446744073709551616", "18446744073709551616")` deve retornar `"340282366920938463463374607431768211456"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -41,7 +41,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`mult("31844674073709551616", "1844674407309551616")` should return `"58743055272886011737990786529368211456"`.
|
||||
`mult("31844674073709551616", "1844674407309551616")` deve retornar `"58743055272886011737990786529368211456"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -50,7 +50,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`mult("1846744073709551616", "44844644073709551616")` should return `"82816580680737279241781007431768211456"`.
|
||||
`mult("1846744073709551616", "44844644073709551616")` deve retornar `"82816580680737279241781007431768211456"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -59,7 +59,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`mult("1844674407370951616", "1844674407709551616")` should return `"3402823669833978308014392742590611456"`.
|
||||
`mult("1844674407370951616", "1844674407709551616")` deve retornar `"3402823669833978308014392742590611456"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -68,7 +68,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`mult("2844674407370951616", "1844674407370955616")` should return `"5247498076580334548376218009219475456"`.
|
||||
`mult("2844674407370951616", "1844674407370955616")` deve retornar `"5247498076580334548376218009219475456"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e6dd1278e6ca105cde40ea9
|
||||
title: Longest common subsequence
|
||||
title: Maior subsequência comum
|
||||
challengeType: 5
|
||||
forumTopicId: 385271
|
||||
dashedName: longest-common-subsequence
|
||||
@ -8,65 +8,65 @@ dashedName: longest-common-subsequence
|
||||
|
||||
# --description--
|
||||
|
||||
The **longest common subsequence** (or [**LCS**](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem)) of groups A and B is the longest group of elements from A and B that are common between the two groups and in the same order in each group. For example, the sequences "1234" and "1224533324" have an LCS of "1234":
|
||||
A **maior subsequência comum** (ou [**LCS**](http://en.wikipedia.org/wiki/Longest_common_subsequence_problem)) dos grupos A e B é o maior grupo de elementos de A e de B que são comuns entre os dois grupos e na mesma ordem em cada grupo. Por exemplo, as sequências "1234" e "1224533324" têm um LCS de "1234":
|
||||
|
||||
***1234***
|
||||
|
||||
***12***245***3***332***4***
|
||||
|
||||
For a string example, consider the sequences "thisisatest" and "testing123testing". An LCS would be "tsitest":
|
||||
Para um exemplo em string, considere as sequências "thisisatest" e "testing123testing". Uma LCS seria "tsitest":
|
||||
|
||||
***t***hi***si***sa***test***
|
||||
|
||||
***t***e***s***t***i***ng123***test***ing.
|
||||
|
||||
Your code only needs to deal with strings.
|
||||
O código só precisa lidar com strings.
|
||||
|
||||
For more information on this problem please see [Wikipedia](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
|
||||
Para obter mais informações sobre esse problema, consulte a [Wikipedia](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a case-sensitive function that returns the LCS of two strings. You don't need to show multiple LCS's.
|
||||
Escreva uma função que diferencie maiúsculas de minúsculas e que retorne o LCS de duas strings. Você não precisa mostrar diversos LCS.
|
||||
|
||||
# --hints--
|
||||
|
||||
`lcs` should be a function.
|
||||
`lcs` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof lcs == 'function');
|
||||
```
|
||||
|
||||
`lcs("thisisatest", "testing123testing")` should return a string.
|
||||
`lcs("thisisatest", "testing123testing")` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(typeof lcs('thisisatest', 'testing123testing') == 'string');
|
||||
```
|
||||
|
||||
`lcs("thisisatest", "testing123testing")` should return `"tsitest"`.
|
||||
`lcs("thisisatest", "testing123testing")` deve retornar `"tsitest"`.
|
||||
|
||||
```js
|
||||
assert.equal(lcs('thisisatest', 'testing123testing'), 'tsitest');
|
||||
```
|
||||
|
||||
`lcs("ABCDGH", "AEDFHR")` should return `"ADH"`.
|
||||
`lcs("ABCDGH", "AEDFHR")` deve retornar `"ADH"`.
|
||||
|
||||
```js
|
||||
assert.equal(lcs('ABCDGH', 'AEDFHR'), 'ADH');
|
||||
```
|
||||
|
||||
`lcs("AGGTAB", "GXTXAYB")` should return `"GTAB"`.
|
||||
`lcs("AGGTAB", "GXTXAYB")` deve retornar `"GTAB"`.
|
||||
|
||||
```js
|
||||
assert.equal(lcs('AGGTAB', 'GXTXAYB'), 'GTAB');
|
||||
```
|
||||
|
||||
`lcs("BDACDB", "BDCB")` should return `"BDCB"`.
|
||||
`lcs("BDACDB", "BDCB")` deve retornar `"BDCB"`.
|
||||
|
||||
```js
|
||||
assert.equal(lcs('BDACDB', 'BDCB'), 'BDCB');
|
||||
```
|
||||
|
||||
`lcs("ABAZDC", "BACBAD")` should return `"ABAD"`.
|
||||
`lcs("ABAZDC", "BACBAD")` deve retornar `"ABAD"`.
|
||||
|
||||
```js
|
||||
assert.equal(lcs('ABAZDC', 'BACBAD'), 'ABAD');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e6dd139859c290b6ab80292
|
||||
title: Longest increasing subsequence
|
||||
title: Maior subsequência crescente
|
||||
challengeType: 5
|
||||
forumTopicId: 385272
|
||||
dashedName: longest-increasing-subsequence
|
||||
@ -8,57 +8,57 @@ dashedName: longest-increasing-subsequence
|
||||
|
||||
# --description--
|
||||
|
||||
The longest increasing subsequence problem is to find a subsequence of a given sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. An example:
|
||||
O problema da maior subsequência crescente é encontrar uma subsequência de uma determinada sequência em que os elementos da subsequência estejam em ordem classificada, do mais baixo para mais alto, e em que a subsequência seja a mais longa possível. Exemplo:
|
||||
|
||||
For the following array:
|
||||
Para o seguinte array:
|
||||
|
||||
$\\{3, 10, 2, 1, 20\\}$
|
||||
|
||||
Longest increasing sequence is:
|
||||
A maior subsequência crescente é:
|
||||
|
||||
$\\{3, 10, 20\\}$
|
||||
|
||||
For more information on this problem please see [Wikipedia](https://en.wikipedia.org/wiki/Longest increasing subsequence).
|
||||
Para obter mais informações sobre esse problema, consulte a [Wikipedia](https://en.wikipedia.org/wiki/Longest increasing subsequence).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes an array of numbers as a parameter and returns the longest increasing subsequence.
|
||||
Escreva uma função que receba um array de números como parâmetro e retorne a maior subsequência crescente.
|
||||
|
||||
It is guaranteed that every array will have a longest increasing subsequence.
|
||||
É garantido que cada array terá uma subsequência crescente maior.
|
||||
|
||||
# --hints--
|
||||
|
||||
`findSequence` should be a function.
|
||||
`findSequence` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof findSequence == 'function');
|
||||
```
|
||||
|
||||
`findSequence([3, 10, 2, 1, 20])` should return a array.
|
||||
`findSequence([3, 10, 2, 1, 20])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(findSequence([3, 10, 2, 1, 20])));
|
||||
```
|
||||
|
||||
`findSequence([3, 10, 2, 1, 20])` should return `[3, 10, 20]`.
|
||||
`findSequence([3, 10, 2, 1, 20])` deve retornar `[3, 10, 20]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findSequence([3, 10, 2, 1, 20]), [3, 10, 20]);
|
||||
```
|
||||
|
||||
`findSequence([2, 7, 3, 5, 8])` should return `[2, 3, 5, 8]`.
|
||||
`findSequence([2, 7, 3, 5, 8])` deve retornar `[2, 3, 5, 8]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findSequence([2, 7, 3, 5, 8]), [2, 3, 5, 8]);
|
||||
```
|
||||
|
||||
`findSequence([2, 6, 4, 5, 1])` should return `[2, 4, 5]`.
|
||||
`findSequence([2, 6, 4, 5, 1])` deve retornar `[2, 4, 5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findSequence([2, 6, 4, 5, 1]), [2, 4, 5]);
|
||||
```
|
||||
|
||||
`findSequence([10, 22, 9, 33, 21, 50, 60, 80])` should return `[10, 22, 33, 50, 60, 80]`.
|
||||
`findSequence([10, 22, 9, 33, 21, 50, 60, 80])` deve retornar `[10, 22, 33, 50, 60, 80]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(findSequence([10, 22, 9, 33, 21, 50, 60, 80]), [
|
||||
@ -71,7 +71,7 @@ assert.deepEqual(findSequence([10, 22, 9, 33, 21, 50, 60, 80]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`findSequence([0, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15])` should return `[0, 2, 6, 9, 11, 15`.
|
||||
`findSequence([0, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15])` deve retornar `[0, 2, 6, 9, 11, 15`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e6dd14192286d95fc43046e
|
||||
title: Longest string challenge
|
||||
title: Desafio da string mais longa
|
||||
challengeType: 5
|
||||
forumTopicId: 385275
|
||||
dashedName: longest-string-challenge
|
||||
@ -8,27 +8,27 @@ dashedName: longest-string-challenge
|
||||
|
||||
# --description--
|
||||
|
||||
In this challenge, you have to find the strings that are the longest among the given strings.
|
||||
Nesse desafio, você precisa encontrar as strings que são as mais longas entre as strings fornecidas.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes an array of strings and returns the strings that have a length equal to the longest length.
|
||||
Escreva uma função que receba um array de strings e retorne as strings que têm um comprimento igual ao comprimento mais longo.
|
||||
|
||||
# --hints--
|
||||
|
||||
`longestString` should be a function.
|
||||
`longestString` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof longestString == 'function');
|
||||
```
|
||||
|
||||
`longestString(["a", "bb", "ccc", "ee", "f", "ggg"])` should return a array.
|
||||
`longestString(["a", "bb", "ccc", "ee", "f", "ggg"])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(longestString(['a', 'bb', 'ccc', 'ee', 'f', 'ggg'])));
|
||||
```
|
||||
|
||||
`longestString(["a", "bb", "ccc", "ee", "f", "ggg"])` should return `["ccc", "ggg"]'`.
|
||||
`longestString(["a", "bb", "ccc", "ee", "f", "ggg"])` deve retornar `["ccc", "ggg"]'`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(longestString(['a', 'bb', 'ccc', 'ee', 'f', 'ggg']), [
|
||||
@ -37,7 +37,7 @@ assert.deepEqual(longestString(['a', 'bb', 'ccc', 'ee', 'f', 'ggg']), [
|
||||
]);
|
||||
```
|
||||
|
||||
`longestString(["afedg", "bb", "sdccc", "efdee", "f", "geegg"])` should return `["afedg", "sdccc", "efdee", "geegg"]`.
|
||||
`longestString(["afedg", "bb", "sdccc", "efdee", "f", "geegg"])` deve retornar `["afedg", "sdccc", "efdee", "geegg"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -46,7 +46,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`longestString(["a", "bhghgb", "ccc", "efde", "fssdrr", "ggg"])` should return `["bhghgb", "fssdrr"]`.
|
||||
`longestString(["a", "bhghgb", "ccc", "efde", "fssdrr", "ggg"])` deve retornar `["bhghgb", "fssdrr"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -55,7 +55,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`longestString(["ahgfhg", "bdsfsb", "ccc", "ee", "f", "ggdsfg"])` should return `["ahgfhg", "bdsfsb", "ggdsfg"]`.
|
||||
`longestString(["ahgfhg", "bdsfsb", "ccc", "ee", "f", "ggdsfg"])` deve retornar `["ahgfhg", "bdsfsb", "ggdsfg"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -64,7 +64,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`longestString(["a", "bbdsf", "ccc", "edfe", "gzzzgg"])` should return `["gzzzgg"]`.
|
||||
`longestString(["a", "bbdsf", "ccc", "edfe", "gzzzgg"])` deve retornar `["gzzzgg"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(longestString(['a', 'bbdsf', 'ccc', 'edfe', 'gzzzgg']), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e6dd14797f5ce267c2f19d0
|
||||
title: Look-and-say sequence
|
||||
title: Sequência para olhar e dizer
|
||||
challengeType: 5
|
||||
forumTopicId: 385277
|
||||
dashedName: look-and-say-sequence
|
||||
@ -8,64 +8,64 @@ dashedName: look-and-say-sequence
|
||||
|
||||
# --description--
|
||||
|
||||
The [Look and say sequence](https://en.wikipedia.org/wiki/Look and say sequence) is a recursively defined sequence of numbers.
|
||||
A [sequência de olhar e dizer](https://en.wikipedia.org/wiki/Look and say sequence) é uma sequência de números definida recursivamente.
|
||||
|
||||
Sequence Definition
|
||||
Definição da sequência
|
||||
|
||||
<ul><li>Take a decimal number</li>
|
||||
<li><span>Look</span> at the number, visually grouping consecutive runs of the same digit.</li>
|
||||
<li><span>Say</span> the number, from left to right, group by group; as how many of that digit there are - followed by the digit grouped.</li></ul><span> This becomes the next number of the sequence.</span>
|
||||
<ul><li>Recebe um número decimal</li>
|
||||
<li><span>Olha</span> para o número, agrupando visualmente sequências consecutivas do mesmo dígito.</li>
|
||||
<li><span>Diz</span> o número, da esquerda para a direita, grupo após grupo, descrevendo quantos daquele dígito há na sequência, e, logo após, os dígitos agrupados.</li></ul><span> Esse se torna o próximo número da sequência.</span>
|
||||
|
||||
An example:
|
||||
Exemplo:
|
||||
|
||||
<ul><li>Starting with the number 1, you have <span>one</span> 1 which produces 11</li>
|
||||
<li>Starting with 11, you have <span>two</span> 1's. I.E.: 21</li>
|
||||
<li>Starting with 21, you have <span>one</span> 2, then <span>one</span> 1. I.E.: (12)(11) which becomes 1211</li>
|
||||
<li>Starting with 1211, you have <span>one</span> 1, <span>one</span> 2, then <span>two</span> 1's. I.E.: (11)(12)(21) which becomes 111221</li></ul>
|
||||
<ul><li>Começando pelo número 1, você tem <span>um</span> 1, o que gera o número 11</li>
|
||||
<li>Começando com 11, você tem <span>dois</span> 1s. Ou seja, 21</li>
|
||||
<li>Começando com 21, você tem <span>um</span> 2 e depois <span>um</span> 1. Ou seja: (12)(11), que depois se torna 1211</li>
|
||||
<li>Começando com 1211, você tem <span>um</span> 1, <span>um</span> 2 e <span>dois</span> 1s. Ou seja: (11)(12)(21), que depois se torna 111221</li></ul>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that accepts a string as a parameter, processes it, and returns the resultant string.
|
||||
Escreva uma função que aceita uma string como parâmetro, faz seu processamento e retorna a string resultante.
|
||||
|
||||
# --hints--
|
||||
|
||||
`lookAndSay` should be a function.
|
||||
`lookAndSay` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof lookAndSay == 'function');
|
||||
```
|
||||
|
||||
`lookAndSay("1")` should return a string.
|
||||
`lookAndSay("1")` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(typeof lookAndSay('1') == 'string');
|
||||
```
|
||||
|
||||
`lookAndSay("1")` should return `"11"`.
|
||||
`lookAndSay("1")` deve retornar `"11"`.
|
||||
|
||||
```js
|
||||
assert.equal(lookAndSay('1'), '11');
|
||||
```
|
||||
|
||||
`lookAndSay("11")` should return `"21"`.
|
||||
`lookAndSay("11")` deve retornar `"21"`.
|
||||
|
||||
```js
|
||||
assert.equal(lookAndSay('11'), '21');
|
||||
```
|
||||
|
||||
`lookAndSay("21")` should return `"1211"`.
|
||||
`lookAndSay("21")` deve retornar `"1211"`.
|
||||
|
||||
```js
|
||||
assert.equal(lookAndSay('21'), '1211');
|
||||
```
|
||||
|
||||
`lookAndSay("1211")` should return `"111221"`.
|
||||
`lookAndSay("1211")` deve retornar `"111221"`.
|
||||
|
||||
```js
|
||||
assert.equal(lookAndSay('1211'), '111221');
|
||||
```
|
||||
|
||||
`lookAndSay("3542")` should return `"13151412"`.
|
||||
`lookAndSay("3542")` deve retornar `"13151412"`.
|
||||
|
||||
```js
|
||||
assert.equal(lookAndSay('3542'), '13151412');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e6dd15004c88cf00d2a78b3
|
||||
title: Loop over multiple arrays simultaneously
|
||||
title: Percorrer vários arrays simultaneamente
|
||||
challengeType: 5
|
||||
forumTopicId: 385279
|
||||
dashedName: loop-over-multiple-arrays-simultaneously
|
||||
@ -8,15 +8,15 @@ dashedName: loop-over-multiple-arrays-simultaneously
|
||||
|
||||
# --description--
|
||||
|
||||
Loop over multiple arrays and create a new array whose $i^{th}$ element is the concatenation of $i^{th}$ element of each of the given.
|
||||
Percorra diversos arrays e crie um novo array, cujo $i^{o}$ elemento seja a concatenação do $i^{o}$ elemento de cada um dos arrays fornecidos.
|
||||
|
||||
For this example, if you are given this array of arrays:
|
||||
Para este exemplo, se você receber este array de arrays:
|
||||
|
||||
```js
|
||||
[ ["a", "b", "c"], ["A", "B", "C"], [1, 2, 3] ]
|
||||
```
|
||||
|
||||
the output should be:
|
||||
o resultado deve ser:
|
||||
|
||||
```js
|
||||
["aA1","bB2","cC3"]
|
||||
@ -24,17 +24,17 @@ the output should be:
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes an array of arrays as a parameter and returns an array of strings satisfying the given description.
|
||||
Escreva uma função que receba um array de arrays como parâmetro e retorne um array de strings que satisfaçam a descrição dada.
|
||||
|
||||
# --hints--
|
||||
|
||||
`loopSimult` should be a function.
|
||||
`loopSimult` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof loopSimult == 'function');
|
||||
```
|
||||
|
||||
`loopSimult([["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]])` should return a array.
|
||||
`loopSimult([["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -48,7 +48,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`loopSimult([["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]])` should return `["aA1", "bB2", "cC3"]`.
|
||||
`loopSimult([["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]])` deve retornar `["aA1", "bB2", "cC3"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -61,7 +61,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`loopSimult([["c", "b", "c"], ["4", "5", "C"], [7, 7, 3]])` should return `["c47", "b57", "cC3"]`.
|
||||
`loopSimult([["c", "b", "c"], ["4", "5", "C"], [7, 7, 3]])` deve retornar `["c47", "b57", "cC3"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -74,7 +74,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`loopSimult([["a", "b", "c", "d"], ["A", "B", "C", "d"], [1, 2, 3, 4]])` should return `["aA1", "bB2", "cC3", "dd4"]`.
|
||||
`loopSimult([["a", "b", "c", "d"], ["A", "B", "C", "d"], [1, 2, 3, 4]])` deve retornar `["aA1", "bB2", "cC3", "dd4"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -87,7 +87,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`loopSimult([["a", "b"], ["A", "B"], [1, 2]])` should return `["aA1", "bB2"]`.
|
||||
`loopSimult([["a", "b"], ["A", "B"], [1, 2]])` deve retornar `["aA1", "bB2"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -100,7 +100,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`loopSimult([["b", "c"], ["B", "C"], [2, 3]])` should return `["bB2", "cC3"]`.
|
||||
`loopSimult([["b", "c"], ["B", "C"], [2, 3]])` deve retornar `["bB2", "cC3"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e6decd8ec8d7db960950d1c
|
||||
title: LU decomposition
|
||||
title: Decomposição de LU
|
||||
challengeType: 5
|
||||
forumTopicId: 385280
|
||||
dashedName: lu-decomposition
|
||||
@ -8,21 +8,21 @@ dashedName: lu-decomposition
|
||||
|
||||
# --description--
|
||||
|
||||
Every square matrix $A$ can be decomposed into a product of a lower triangular matrix $L$ and a upper triangular matrix $U$, as described in [LU decomposition](https://en.wikipedia.org/wiki/LU decomposition).
|
||||
Toda matriz quadrada $A$ pode ser decomposta em um produto de uma matriz triangular inferior $L$ e uma matriz triangular superior $U$, conforme descrito em [Decomposição de LU](https://en.wikipedia.org/wiki/LU decomposition).
|
||||
|
||||
$A = LU$
|
||||
|
||||
It is a modified form of Gaussian elimination.
|
||||
Ela é uma forma modificada da eliminação de Gauss.
|
||||
|
||||
While the [Cholesky decomposition](http://rosettacode.org/wiki/Cholesky decomposition) only works for symmetric, positive definite matrices, the more general LU decomposition works for any square matrix.
|
||||
Enquanto a [Decomposição do Cholesky](http://rosettacode.org/wiki/Cholesky decomposition) funciona somente para matrizes simétricas, definidas e positivas, a decomposição da LU é mais geral e funciona para qualquer matriz quadrada.
|
||||
|
||||
There are several algorithms for calculating $L$ and $U$.
|
||||
Existem vários algoritmos para calcular $L$ e $U$.
|
||||
|
||||
To derive *Crout's algorithm* for a 3x3 example, we have to solve the following system:
|
||||
Para derivar o *algoritmo de Crout* para um exemplo de 3x3, temos de resolver o seguinte sistema:
|
||||
|
||||
\\begin{align}A = \\begin{pmatrix} a\_{11} & a\_{12} & a\_{13}\\\\ a\_{21} & a\_{22} & a\_{23}\\\\ a\_{31} & a\_{32} & a\_{33}\\\\ \\end{pmatrix}= \\begin{pmatrix} l\_{11} & 0 & 0 \\\\ l\_{21} & l\_{22} & 0 \\\\ l\_{31} & l\_{32} & l\_{33}\\\\ \\end{pmatrix} \\begin{pmatrix} u\_{11} & u\_{12} & u\_{13} \\\\ 0 & u\_{22} & u\_{23} \\\\ 0 & 0 & u\_{33} \\end{pmatrix} = LU\\end{align}
|
||||
|
||||
We now would have to solve 9 equations with 12 unknowns. To make the system uniquely solvable, usually the diagonal elements of $L$ are set to 1
|
||||
Agora, teríamos de resolver 9 equações com 12 incógnitas. Para tornar o sistema resolvível de forma única, geralmente os elementos diagonais de $L$ estão definidos como 1
|
||||
|
||||
$l\_{11}=1$
|
||||
|
||||
@ -30,11 +30,11 @@ $l\_{22}=1$
|
||||
|
||||
$l\_{33}=1$
|
||||
|
||||
so we get a solvable system of 9 unknowns and 9 equations.
|
||||
portanto, obtemos um sistema resolvível de 9 incógnitas e 9 equações.
|
||||
|
||||
\\begin{align}A = \\begin{pmatrix} a\_{11} & a\_{12} & a\_{13}\\\\ a\_{21} & a\_{22} & a\_{23}\\\\ a\_{31} & a\_{32} & a\_{33}\\\\ \\end{pmatrix} = \\begin{pmatrix} 1 & 0 & 0 \\\\ l\_{21} & 1 & 0 \\\\ l\_{31} & l\_{32} & 1\\\\ \\end{pmatrix} \\begin{pmatrix} u\_{11} & u\_{12} & u\_{13} \\\\ 0 & u\_{22} & u\_{23} \\\\ 0 & 0 & u\_{33} \\end{pmatrix} = \\begin{pmatrix} u\_{11} & u\_{12} & u\_{13} \\\\ u\_{11}l\_{21} & u\_{12}l\_{21}+u\_{22} & u\_{13}l\_{21}+u\_{23} \\\\ u\_{11}l\_{31} & u\_{12}l\_{31}+u\_{22}l\_{32} & u\_{13}l\_{31} + u\_{23}l\_{32}+u\_{33} \\end{pmatrix} = LU\\end{align}
|
||||
|
||||
Solving for the other $l$ and $u$, we get the following equations:
|
||||
Ao solucionar para os outros $l$ e $u$, recebemos as seguintes equações:
|
||||
|
||||
$u\_{11}=a\_{11}$
|
||||
|
||||
@ -48,7 +48,7 @@ $u\_{23}=a\_{23} - u\_{13}l\_{21}$
|
||||
|
||||
$u\_{33}=a\_{33} - (u\_{13}l\_{31} + u\_{23}l\_{32})$
|
||||
|
||||
and for $l$:
|
||||
e para $l$:
|
||||
|
||||
$l\_{21}=\\frac{1}{u\_{11}} a\_{21}$
|
||||
|
||||
@ -56,41 +56,41 @@ $l\_{31}=\\frac{1}{u\_{11}} a\_{31}$
|
||||
|
||||
$l\_{32}=\\frac{1}{u\_{22}} (a\_{32} - u\_{12}l\_{31})$
|
||||
|
||||
We see that there is a calculation pattern, which can be expressed as the following formulas, first for $U$
|
||||
Vemos que há um padrão de cálculo, que pode ser expresso com as seguintes fórmulas, primeiro para $U$
|
||||
|
||||
$u\_{ij} = a\_{ij} - \\sum\_{k=1}^{i-1} u\_{kj}l\_{ik}$
|
||||
|
||||
and then for $L$
|
||||
e depois para $L$
|
||||
|
||||
$l\_{ij} = \\frac{1}{u\_{jj}} (a\_{ij} - \\sum\_{k=1}^{j-1} u\_{kj}l\_{ik})$
|
||||
|
||||
We see in the second formula that to get the $l\_{ij}$ below the diagonal, we have to divide by the diagonal element (pivot) $u\_{jj}$, so we get problems when $u\_{jj}$ is either 0 or very small, which leads to numerical instability.
|
||||
Vemos na segunda fórmula que, para obter o $l\_{ij}$ abaixo da diagonal, temos de dividir pelo elemento da diagonal (pivô) $u\_{jj}$, de modo que temos problemas quando $u\_{jj}$ é 0 ou muito pequeno, o que gera uma instabilidade numérica.
|
||||
|
||||
The solution to this problem is *pivoting* $A$, which means rearranging the rows of $A$, prior to the $LU$ decomposition, in a way that the largest element of each column gets onto the diagonal of $A$. Rearranging the rows means to multiply $A$ by a permutation matrix $P$:
|
||||
A solução para este problema é *rotar* $A$, o que significa reorganizar as linhas de $A$, antes da decomposição de $LU$, de modo que o maior elemento de cada coluna fique na diagonal de $A$. Reordenar as linhas significa multiplicar $A$ por uma matriz de permutação $P$:
|
||||
|
||||
$PA \\Rightarrow A'$
|
||||
|
||||
Example:
|
||||
Exemplo:
|
||||
|
||||
\\begin{align} \\begin{pmatrix} 0 & 1 \\\\ 1 & 0 \\end{pmatrix} \\begin{pmatrix} 1 & 4 \\\\ 2 & 3 \\end{pmatrix} \\Rightarrow \\begin{pmatrix} 2 & 3 \\\\ 1 & 4 \\end{pmatrix} \\end{align}
|
||||
|
||||
The decomposition algorithm is then applied on the rearranged matrix so that
|
||||
O algoritmo de decomposição será então aplicado na matriz reorganizada para que
|
||||
|
||||
$PA = LU$
|
||||
|
||||
# --instructions--
|
||||
|
||||
The task is to implement a routine which will take a square nxn matrix $A$ and return a lower triangular matrix $L$, a upper triangular matrix $U$ and a permutation matrix $P$, so that the above equation is fullfilled. The returned value should be in the form `[L, U, P]`.
|
||||
A tarefa é implementar uma rotina que receba uma matriz quadrada $A$ nxn e retornar uma matriz triangular inferior $L$, uma matriz triangular superior $U$ e uma matriz de permutação $P$, para que a equação acima seja resolvida. O valor retornado deve estar na forma `[L, U, P]`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`luDecomposition` should be a function.
|
||||
`luDecomposition` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof luDecomposition == 'function');
|
||||
```
|
||||
|
||||
`luDecomposition([[1, 3, 5], [2, 4, 7], [1, 1, 0]])` should return a array.
|
||||
`luDecomposition([[1, 3, 5], [2, 4, 7], [1, 1, 0]])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -104,7 +104,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`luDecomposition([[1, 3, 5], [2, 4, 7], [1, 1, 0]])` should return `[[[1, 0, 0], [0.5, 1, 0], [0.5, -1, 1]], [[2, 4, 7], [0, 1, 1.5], [0, 0, -2]], [[0, 1, 0], [1, 0, 0], [0, 0, 1]]]`.
|
||||
`luDecomposition([[1, 3, 5], [2, 4, 7], [1, 1, 0]])` deve retornar `[[[1, 0, 0], [0.5, 1, 0], [0.5, -1, 1]], [[2, 4, 7], [0, 1, 1.5], [0, 0, -2]], [[0, 1, 0], [1, 0, 0], [0, 0, 1]]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -133,7 +133,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`luDecomposition([[11, 9, 24, 2], [1, 5, 2, 6], [3, 17, 18, 1], [2, 5, 7, 1]])` should return `[[[1, 0, 0, 0], [0.2727272727272727, 1, 0, 0], [0.09090909090909091, 0.2875, 1, 0], [0.18181818181818182, 0.23124999999999996, 0.0035971223021580693, 1]], [[11, 9, 24, 2], [0, 14.545454545454547, 11.454545454545455, 0.4545454545454546], [0, 0, -3.4749999999999996, 5.6875], [0, 0, 0, 0.510791366906476]], [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]]`.
|
||||
`luDecomposition([[11, 9, 24, 2], [1, 5, 2, 6], [3, 17, 18, 1], [2, 5, 7, 1]])` deve retornar `[[[1, 0, 0, 0], [0.2727272727272727, 1, 0, 0], [0.09090909090909091, 0.2875, 1, 0], [0.18181818181818182, 0.23124999999999996, 0.0035971223021580693, 1]], [[11, 9, 24, 2], [0, 14.545454545454547, 11.454545454545455, 0.4545454545454546], [0, 0, -3.4749999999999996, 5.6875], [0, 0, 0, 0.510791366906476]], [[1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 0, 0, 1]]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -166,7 +166,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`luDecomposition([[1, 1, 1], [4, 3, -1], [3, 5, 3]])` should return `[[[1, 0, 0], [0.75, 1, 0], [0.25, 0.09090909090909091, 1]], [[4, 3, -1], [0, 2.75, 3.75], [0, 0, 0.9090909090909091]], [[0, 1, 0], [0, 0, 1], [1, 0, 0]]]`.
|
||||
`luDecomposition([[1, 1, 1], [4, 3, -1], [3, 5, 3]])` deve retornar `[[[1, 0, 0], [0.75, 1, 0], [0.25, 0.09090909090909091, 1]], [[4, 3, -1], [0, 2.75, 3.75], [0, 0, 0.9090909090909091]], [[0, 1, 0], [0, 0, 1], [1, 0, 0]]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -195,7 +195,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`luDecomposition([[1, -2, 3], [2, -5, 12], [0, 2, -10]])` should return `[[[1, 0, 0], [0, 1, 0], [0.5, 0.25, 1]], [[2, -5, 12], [0, 2, -10], [0, 0, -0.5]], [[0, 1, 0], [0, 0, 1], [1, 0, 0]]]`.
|
||||
`luDecomposition([[1, -2, 3], [2, -5, 12], [0, 2, -10]])` deve retornar `[[[1, 0, 0], [0, 1, 0], [0.5, 0.25, 1]], [[2, -5, 12], [0, 2, -10], [0, 0, -0.5]], [[0, 1, 0], [0, 0, 1], [1, 0, 0]]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5e6dee7749a0b85a3f1fc7d5
|
||||
title: Lucas-Lehmer test
|
||||
title: Teste de Lucas-Lehmer
|
||||
challengeType: 5
|
||||
forumTopicId: 385281
|
||||
dashedName: lucas-lehmer-test
|
||||
@ -8,57 +8,57 @@ dashedName: lucas-lehmer-test
|
||||
|
||||
# --description--
|
||||
|
||||
Lucas-Lehmer Test: for $p$ an odd prime, the Mersenne number $2^p-1$ is prime if and only if $2^p-1$ divides $S(p-1)$ where $S(n+1)=(S(n))^2-2$, and $S(1)=4$.
|
||||
Teste de Lucas-Lehmer: para um primo ímpar $p$, o número de Mersenne $2^p-1$ é primo se e somente se $2^p-1$ puder dividir $S(p-1)$, onde $S(n+1)=(S(n))^2-2$ e $S(1)=4$.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that returns whether the given Mersenne number is prime or not.
|
||||
Escreva uma função que retorne se o número de Mersenne dado é primo ou não.
|
||||
|
||||
# --hints--
|
||||
|
||||
`lucasLehmer` should be a function.
|
||||
`lucasLehmer` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof lucasLehmer == 'function');
|
||||
```
|
||||
|
||||
`lucasLehmer(11)` should return a boolean.
|
||||
`lucasLehmer(11)` deve retornar um booleano.
|
||||
|
||||
```js
|
||||
assert(typeof lucasLehmer(11) == 'boolean');
|
||||
```
|
||||
|
||||
`lucasLehmer(11)` should return `false`.
|
||||
`lucasLehmer(11)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(lucasLehmer(11), false);
|
||||
```
|
||||
|
||||
`lucasLehmer(15)` should return `false`.
|
||||
`lucasLehmer(15)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(lucasLehmer(15), false);
|
||||
```
|
||||
|
||||
`lucasLehmer(13)` should return `true`.
|
||||
`lucasLehmer(13)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(lucasLehmer(13), true);
|
||||
```
|
||||
|
||||
`lucasLehmer(17)` should return `true`.
|
||||
`lucasLehmer(17)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(lucasLehmer(17), true);
|
||||
```
|
||||
|
||||
`lucasLehmer(19)` should return `true`.
|
||||
`lucasLehmer(19)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(lucasLehmer(19), true);
|
||||
```
|
||||
|
||||
`lucasLehmer(21)` should return `false`.
|
||||
`lucasLehmer(21)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(lucasLehmer(21), false);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5ea281203167d2b0bdefca00
|
||||
title: Ludic numbers
|
||||
title: Números lúdicos
|
||||
challengeType: 5
|
||||
forumTopicId: 385282
|
||||
dashedName: ludic-numbers
|
||||
@ -8,91 +8,91 @@ dashedName: ludic-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
[Ludic numbers](https://oeis.org/wiki/Ludic_numbers) are related to prime numbers as they are generated by a sieve quite like the [Sieve of Eratosthenes](https://rosettacode.org/wiki/Sieve_of_Eratosthenes) is used to generate prime numbers.
|
||||
[Números lúdicos](https://oeis.org/wiki/Ludic_numbers) têm a ver com números primos conforme eles são gerados por uma peneira, do mesmo modo como a [Peneira de Eratóstenes](https://rosettacode.org/wiki/Sieve_of_Eratosthenes) é usada para gerar números primos.
|
||||
|
||||
The first ludic number is 1.
|
||||
O primeiro número lúdico é 1.
|
||||
|
||||
To generate succeeding ludic numbers create an array of increasing integers starting from 2.
|
||||
Para gerar os próximos números lúdicos, crie um array de números inteiros crescentes a partir do 2.
|
||||
|
||||
<code style='margin-left: 2em;'><span style='color:blue;font-weight:bold'>2</span> 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ...</code>
|
||||
|
||||
(Loop)
|
||||
(Gere o laço)
|
||||
|
||||
<ul>
|
||||
<li>Take the first member of the resultant array as the next ludic number <span style='color:blue;font-weight:bold'>2</span>.</li>
|
||||
<li>Remove every <strong>2<sup>nd</sup></strong> indexed item from the array (including the first).</li>
|
||||
<li>Pegue o primeiro elemento do array resultante como sendo o próximo número lúdico <span style='color:blue;font-weight:bold'>2</span>.</li>
|
||||
<li>Remova cada <strong>2<sup>o</sup></strong> item indexado do array (incluindo o primeiro array).</li>
|
||||
<code style='margin-left: 2em;'><span style='color:blue;font-weight:bold;'><s>2</s></span> 3 <s>4</s> 5 <s>6</s> 7 <s>8</s> 9 <s>10</s> 11 <s>12</s> 13 <s>14</s> 15 <s>16</s> 17 <s>18</s> 19 <s>20</s> 21 <s>22</s> 23 <s>24</s> 25 <s>26</s> ...</code>
|
||||
</ul>
|
||||
|
||||
<ul>
|
||||
<li>(Unrolling a few loops...)</li>
|
||||
<li>Take the first member of the resultant array as the next ludic number <span style='color:blue;font-weight:bold'>3</span>.</li>
|
||||
<li>Remove every <strong>3<sup>rd</sup></strong> indexed item from the array (including the first).</li>
|
||||
<li>(Após alguns laços...)</li>
|
||||
<li>Pegue o primeiro elemento do array resultante como sendo o próximo número lúdico <span style='color:blue;font-weight:bold'>3</span>.</li>
|
||||
<li>Remova cada <strong>3<sup>o</sup></strong> item indexado do array (incluindo o primeiro array).</li>
|
||||
<code style='margin-left: 2em;'><span style='color:blue;font-weight:bold'><s>3</s></span> 5 7 <s>9</s> 11 13 <s>15</s> 17 19 <s>21</s> 23 25 <s>27</s> 29 31 <s>33</s> 35 37 <s>39</s> 41 43 <s>45</s> 47 49 <s>51</s> ...</code>
|
||||
</ul>
|
||||
|
||||
<ul>
|
||||
<li>Take the first member of the resultant array as the next ludic number <span style='color:blue;font-weight:bold'>5</span>.</li>
|
||||
<li>Remove every <strong>5<sup>th</sup></strong> indexed item from the array (including the first).</li>
|
||||
<li>Pegue o primeiro elemento do array resultante como sendo o próximo número lúdico <span style='color:blue;font-weight:bold'>5</span>.</li>
|
||||
<li>Remova cada <strong>5<sup>o</sup></strong> item indexado do array (incluindo o primeiro array).</li>
|
||||
<code style='margin-left: 2em;'><span style='color:blue;font-weight:bold'><s>5</s></span> 7 11 13 17 <s>19</s> 23 25 29 31 <s>35</s> 37 41 43 47 <s>49</s> 53 55 59 61 <s>65</s> 67 71 73 77 ...</code>
|
||||
</ul>
|
||||
|
||||
<ul>
|
||||
<li>Take the first member of the resultant array as the next ludic number <span style='color:blue;font-weight:bold'>7</span>.</li>
|
||||
<li>Remove every <strong>7<sup>th</sup></strong> indexed item from the array (including the first).</li>
|
||||
<li>Pegue o primeiro elemento do array resultante como sendo o próximo número lúdico <span style='color:blue;font-weight:bold'>7</span>.</li>
|
||||
<li>Remova cada <strong>7<sup>o</sup></strong> item indexado do array (incluindo o primeiro array).</li>
|
||||
<code style='margin-left: 2em;'><span style='color:blue;font-weight:bold'><s>7</s></span> 11 13 17 23 25 29 <s>31</s> 37 41 43 47 53 55 <s>59</s> 61 67 71 73 77 83 <s>85</s> 89 91 97 ...</code>
|
||||
</ul>
|
||||
|
||||
<ul>
|
||||
<li><big><b> ... </b></big></li>
|
||||
<li>Take the first member of the current array as the next ludic number <span style='color:blue;font-weight:bold'>L</span>.</li>
|
||||
<li>Remove every <strong>L<sup>th</sup></strong> indexed item from the array (including the first).</li>
|
||||
<li>Pegue o primeiro elemento do array atual como sendo o próximo número lúdico <span style='color:blue;font-weight:bold'>L</span>.</li>
|
||||
<li>Remova cada <strong>L<sup></sup>-ésimo</strong> item indexado do array (incluindo o primeiro array).</li>
|
||||
<li><big><b> ... </b></big></li>
|
||||
</ul>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that returns all the ludic numbers less than or equal to the given number.
|
||||
Escreva uma função que retorne todos os números lúdicos menores do que ou iguais ao número fornecido.
|
||||
|
||||
# --hints--
|
||||
|
||||
`ludic` should be a function.
|
||||
`ludic` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof ludic === 'function', '<code>ludic</code> should be a function.');
|
||||
```
|
||||
|
||||
`ludic(2)` should return a array.
|
||||
`ludic(2)` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(ludic(2)));
|
||||
```
|
||||
|
||||
`ludic(2)` should return `[1, 2]`.
|
||||
`ludic(2)` deve retornar `[1, 2]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(ludic(2), [1, 2]);
|
||||
```
|
||||
|
||||
`ludic(3)` should return `[1, 2, 3]`.
|
||||
`ludic(3)` deve retornar `[1, 2, 3]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(ludic(3), [1, 2, 3]);
|
||||
```
|
||||
|
||||
`ludic(5)` should return `[1, 2, 3, 5]`.
|
||||
`ludic(5)` deve retornar `[1, 2, 3, 5]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(ludic(5), [1, 2, 3, 5]);
|
||||
```
|
||||
|
||||
`ludic(20)` should return `[1, 2, 3, 5, 7, 11, 13, 17]`.
|
||||
`ludic(20)` deve retornar `[1, 2, 3, 5, 7, 11, 13, 17]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(ludic(20), [1, 2, 3, 5, 7, 11, 13, 17]);
|
||||
```
|
||||
|
||||
`ludic(26)` should return `[1, 2, 3, 5, 7, 11, 13, 17, 23, 25]`.
|
||||
`ludic(26)` deve retornar `[1, 2, 3, 5, 7, 11, 13, 17, 23, 25]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(ludic(26), [1, 2, 3, 5, 7, 11, 13, 17, 23, 25]);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5ea28156e79528a9ab248f27
|
||||
title: Luhn test of credit card numbers
|
||||
title: Teste de Luhn de números de cartão de crédito
|
||||
challengeType: 5
|
||||
forumTopicId: 385284
|
||||
dashedName: luhn-test-of-credit-card-numbers
|
||||
@ -8,22 +8,22 @@ dashedName: luhn-test-of-credit-card-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
The [Luhn test](https://en.wikipedia.org/wiki/Luhn algorithm) is used by some credit card companies to distinguish valid credit card numbers from what could be a random selection of digits.
|
||||
O [teste de Luhn](https://en.wikipedia.org/wiki/Luhn algorithm) é usado por algumas empresas de cartões de crédito para distinguir números válidos de cartão de crédito do que poderia ser uma seleção aleatória de dígitos.
|
||||
|
||||
Those companies using credit card numbers that can be validated by the Luhn test have numbers that pass the following test:
|
||||
Essas empresas que usam números de cartão de crédito que podem ser validados pelo teste de Luhn têm números que passam no teste a seguir:
|
||||
|
||||
<ol>
|
||||
<li> Reverse the order of the digits in the number.</li>
|
||||
<li> Take the first, third, ... and every other odd digit in the reversed digits and sum them to form the partial sum s1</li>
|
||||
<li> Taking the second, fourth ... and every other even digit in the reversed digits:</li>
|
||||
<li> Inverter a ordem dos dígitos no número.</li>
|
||||
<li> Pegar o primeiro, o terceiro, ... e qualquer outro dígito ímpar nos dígitos invertidos e somá-los para formar a soma parcial s1</li>
|
||||
<li> Tomando o segundo, o quarto ... e todos os outros dígitos pares nos dígitos invertidos:</li>
|
||||
<ol>
|
||||
<li>Multiply each digit by two and sum the digits if the answer is greater than nine to form partial sums for the even digits.</li>
|
||||
<li>Sum the partial sums of the even digits to form s2.</li>
|
||||
<li>Multiplicar cada algarismo por dois e somar os dígitos se a resposta for maior que nove para formar somas parciais para os dígitos pares.</li>
|
||||
<li>Somar as somas parciais dos dígitos pares para formar s2.</li>
|
||||
</ol>
|
||||
<li>If s1 + s2 ends in zero then the original number is in the form of a valid credit card number as verified by the Luhn test.</li>
|
||||
<li>Se s1 + s2 terminar em zero, então o número original está na forma de um número de cartão de crédito válido, conforme verificado pelo teste de Luhn.</li>
|
||||
</ol>
|
||||
|
||||
For example, if the trial number is 49927398716:
|
||||
Por exemplo, se o número avaliado for 49927398716:
|
||||
|
||||
```bash
|
||||
Reverse the digits:
|
||||
@ -44,53 +44,53 @@ s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn tes
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that will validate a number with the Luhn test. Return true if it's a valid number. Otherwise, return false.
|
||||
Escreva uma função que valide um número com o teste de Luhn. Retorne true se for um número válido. Caso contrário, retorne false.
|
||||
|
||||
# --hints--
|
||||
|
||||
`luhnTest` should be a function.
|
||||
`luhnTest` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof luhnTest === 'function');
|
||||
```
|
||||
|
||||
`luhnTest("4111111111111111")` should return a boolean.
|
||||
`luhnTest("4111111111111111")` deve retornar um booleano.
|
||||
|
||||
```js
|
||||
assert(typeof luhnTest('4111111111111111') === 'boolean');
|
||||
```
|
||||
|
||||
`luhnTest("4111111111111111")` should return `true`.
|
||||
`luhnTest("4111111111111111")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(luhnTest('4111111111111111'), true);
|
||||
```
|
||||
|
||||
`luhnTest("4111111111111112")` should return `false`.
|
||||
`luhnTest("4111111111111112")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(luhnTest('4111111111111112'), false);
|
||||
```
|
||||
|
||||
`luhnTest("49927398716")` should return `true`.
|
||||
`luhnTest("49927398716")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(luhnTest('49927398716'), true);
|
||||
```
|
||||
|
||||
`luhnTest("49927398717")` should return `false`.
|
||||
`luhnTest("49927398717")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(luhnTest('49927398717'), false);
|
||||
```
|
||||
|
||||
`luhnTest("1234567812345678")` should return `false`.
|
||||
`luhnTest("1234567812345678")` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(luhnTest('1234567812345678'), false);
|
||||
```
|
||||
|
||||
`luhnTest("1234567812345670")` should return `true`.
|
||||
`luhnTest("1234567812345670")` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(luhnTest('1234567812345670'), true);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5ea2815a8640bcc6cb7dab3c
|
||||
title: Lychrel numbers
|
||||
title: Números de Lychrel
|
||||
challengeType: 5
|
||||
forumTopicId: 385287
|
||||
dashedName: lychrel-numbers
|
||||
@ -9,21 +9,21 @@ dashedName: lychrel-numbers
|
||||
# --description--
|
||||
|
||||
<ol>
|
||||
<li>Take an integer <code>n₀</code>, greater than zero.</li>
|
||||
<li>Form the next number <code>n</code> of the series by reversing <code>n₀</code> and adding it to <code>n₀</code></li>
|
||||
<li>Stop when <code>n</code> becomes palindromic - i.e. the digits of <code>n</code> in reverse order == <code>n</code>.</li>
|
||||
<li>Receba um número inteiro <code>n₀</code>, maior que zero.</li>
|
||||
<li>Forme o próximo número <code>n</code> da série invertendo <code>n₀</code> e adicionando-a a <code>n₀</code></li>
|
||||
<li>Pare quando <code>n</code> se tornar palindrômico - ou seja, os dígitos de <code>n</code> na ordem inversa == <code>n</code>.</li>
|
||||
</ol>
|
||||
|
||||
The above recurrence relation when applied to most starting numbers `n` = 1, 2, ... terminates in a palindrome quite quickly.
|
||||
A relação de recorrência acima, quando aplicada à maioria dos números iniciais `n` = 1, 2, ... termina rapidamente em um palíndromo.
|
||||
|
||||
For example if `n₀` = 12 we get:
|
||||
Por exemplo, se `n₀` = 12, temos we get:
|
||||
|
||||
```bash
|
||||
12
|
||||
12 + 21 = 33, a palindrome!
|
||||
```
|
||||
|
||||
And if `n₀` = 55 we get:
|
||||
E se `n₀` = 55, temos:
|
||||
|
||||
```bash
|
||||
55
|
||||
@ -31,17 +31,17 @@ And if `n₀` = 55 we get:
|
||||
110 + 011 = 121, a palindrome!
|
||||
```
|
||||
|
||||
Notice that the check for a palindrome happens *after* an addition.
|
||||
Observe que a verificação de um palíndromo acontece *após* uma adição.
|
||||
|
||||
Some starting numbers seem to go on forever; the recurrence relation for 196 has been calculated for millions of repetitions forming numbers with millions of digits, without forming a palindrome. These numbers that do not end in a palindrome are called **Lychrel numbers**.
|
||||
Alguns números iniciais parecem demorar para sempre. A relação de recorrência para 196 foi calculada por milhões e milhões de repetições formando números com milhões de dígitos, sem formar um palíndromo. Esses números que não terminam em um palíndromo são chamados de **números de Lychrel**.
|
||||
|
||||
For the purposes of this task a Lychrel number is any starting number that does not form a palindrome within 500 (or more) iterations.
|
||||
Para fins desta tarefa, um número de Lychrel é qualquer número inicial que não forme um palíndromo em 500 (ou mais) iterações.
|
||||
|
||||
**Seed and related Lychrel numbers:**
|
||||
**Seed e os números de Lychrel relacionados:**
|
||||
|
||||
Any integer produced in the sequence of a Lychrel number is also a Lychrel number.
|
||||
Qualquer inteiro produzido na sequência de um número de Lychrel também é um número de Lychrel.
|
||||
|
||||
In general, any sequence from one Lychrel number *might* converge to join the sequence from a prior Lychrel number candidate; for example the sequences for the numbers 196 and then 689 begin:
|
||||
Em geral, qualquer sequência a partir de um número de Lychrel *pode* convergir para se juntar à sequência de um candidato a número de Lychrel anterior. Por exemplo, as sequências para os números 196 e depois 689 começam:
|
||||
|
||||
```bash
|
||||
196
|
||||
@ -58,59 +58,59 @@ In general, any sequence from one Lychrel number *might* converge to join the se
|
||||
...
|
||||
```
|
||||
|
||||
So we see that the sequence starting with 689 converges to, and continues with the same numbers as that for 196.
|
||||
Vemos, portanto, que a sequência que começa com 689 converge e continua com os mesmos números que para 196.
|
||||
|
||||
Because of this we can further split the Lychrel numbers into true **Seed** Lychrel number candidates, and **Related** numbers that produce no palindromes but have integers in their sequence seen as part of the sequence generated from a lower Lychrel number.
|
||||
Por isso, podemos dividir ainda mais os números de Lychrel em verdadeiros **seeds** candidatas a números de Lychrel, e números **relacionados** que não produzem palíndromos, mas têm números inteiros em sua sequência que são vistos como parte da sequência gerada de um número de Lychrel inferior.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes a number as a parameter. Return true if the number is a Lynchrel number. Otherwise, return false. Remember that the iteration limit is 500.
|
||||
Escreva uma função que recebe um número como parâmetro. Retorne true se o número for um número de Lynchrel. Caso contrário, retorne false. Lembre-se de que o limite de iterações é de 500.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isLychrel` should be a function.
|
||||
`isLychrel` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof isLychrel === 'function');
|
||||
```
|
||||
|
||||
`isLychrel(12)` should return a boolean.
|
||||
`isLychrel(12)` deve retornar um booleano.
|
||||
|
||||
```js
|
||||
assert(typeof isLychrel(12) === 'boolean');
|
||||
```
|
||||
|
||||
`isLychrel(12)` should return `false`.
|
||||
`isLychrel(12)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isLychrel(12), false);
|
||||
```
|
||||
|
||||
`isLychrel(55)` should return `false`.
|
||||
`isLychrel(55)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isLychrel(55), false);
|
||||
```
|
||||
|
||||
`isLychrel(196)` should return `true`.
|
||||
`isLychrel(196)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isLychrel(196), true);
|
||||
```
|
||||
|
||||
`isLychrel(879)` should return `true`.
|
||||
`isLychrel(879)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isLychrel(879), true);
|
||||
```
|
||||
|
||||
`isLychrel(44987)` should return `false`.
|
||||
`isLychrel(44987)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isLychrel(44987), false);
|
||||
```
|
||||
|
||||
`isLychrel(7059)` should return `true`.
|
||||
`isLychrel(7059)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isLychrel(7059), true);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5ea2815e364d9a2222ea55f8
|
||||
title: LZW compression
|
||||
title: Compressão LZW
|
||||
challengeType: 5
|
||||
forumTopicId: 385288
|
||||
dashedName: lzw-compression
|
||||
@ -8,29 +8,29 @@ dashedName: lzw-compression
|
||||
|
||||
# --description--
|
||||
|
||||
The Lempel-Ziv-Welch (LZW) algorithm provides loss-less data compression.
|
||||
O algoritmo de Lempel-Ziv-Welch (LZW) fornece compressão de dados sem perda.
|
||||
|
||||
You can read a complete description of it in the [Wikipedia article](https://en.wikipedia.org/wiki/Lempel-Ziv-Welch) on the subject.
|
||||
Você pode ler uma descrição completa dele no [artigo da Wikipédia](https://en.wikipedia.org/wiki/Lempel-Ziv-Welch) sobre o assunto.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes two parameters. The first parameter is a boolean where `true` indicates compress and `false` indicates decompress. The second parameter is either a string or an array to be processed. If it is a string to be compressed, return an array of numbers. If it's an array of numbers to be decompressed, return a string.
|
||||
Escreva uma função que receba dois parâmetros. O primeiro parâmetro é um booleano onde `true` indica compressão e `false` indica descompactação. O segundo parâmetro é uma string ou um array a ser processado. Se é uma string que deve ser comprimida, retorne um array de números. Se for um array de números a serem descompactados, retorne uma string.
|
||||
|
||||
# --hints--
|
||||
|
||||
`LZW` should be a function.
|
||||
`LZW` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof LZW === 'function');
|
||||
```
|
||||
|
||||
`LZW(true, "TOBEORNOTTOBEORTOBEORNOT")` should return a array.
|
||||
`LZW(true, "TOBEORNOTTOBEORTOBEORNOT")` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(LZW(true, 'TOBEORNOTTOBEORTOBEORNOT')));
|
||||
```
|
||||
|
||||
`LZW(false, [84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263])` should return a string.
|
||||
`LZW(false, [84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263])` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -55,7 +55,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`LZW(true, "TOBEORNOTTOBEORTOBEORNOT")` should return `[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]`.
|
||||
`LZW(true, "TOBEORNOTTOBEORTOBEORNOT")` deve retornar `[84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(LZW(true, 'TOBEORNOTTOBEORTOBEORNOT'), [
|
||||
@ -78,7 +78,7 @@ assert.deepEqual(LZW(true, 'TOBEORNOTTOBEORTOBEORNOT'), [
|
||||
]);
|
||||
```
|
||||
|
||||
`LZW(false, [84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263])` should return `"TOBEORNOTTOBEORTOBEORNOT"`.
|
||||
`LZW(false, [84, 79, 66, 69, 79, 82, 78, 79, 84, 256, 258, 260, 265, 259, 261, 263])` deve retornar `"TOBEORNOTTOBEORTOBEORNOT"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -104,7 +104,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`LZW(true, "0123456789")` should return `[48, 49, 50, 51, 52, 53, 54, 55, 56, 57]`.
|
||||
`LZW(true, "0123456789")` deve retornar `[48, 49, 50, 51, 52, 53, 54, 55, 56, 57]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(LZW(true, '0123456789'), [
|
||||
@ -121,7 +121,7 @@ assert.deepEqual(LZW(true, '0123456789'), [
|
||||
]);
|
||||
```
|
||||
|
||||
`LZW(false, [48, 49, 50, 51, 52, 53, 54, 55, 56, 57])` should return `"0123456789"`.
|
||||
`LZW(false, [48, 49, 50, 51, 52, 53, 54, 55, 56, 57])` deve retornar `"0123456789"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -130,13 +130,13 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`LZW(true, "BABAABAAA")` should return `[66, 65, 256, 257, 65, 260]`.
|
||||
`LZW(true, "BABAABAAA")` deve retornar `[66, 65, 256, 257, 65, 260]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(LZW(true, 'BABAABAAA'), [66, 65, 256, 257, 65, 260]);
|
||||
```
|
||||
|
||||
`LZW(false, [66, 65, 256, 257, 65, 260])` should return `"BABAABAAA"`.
|
||||
`LZW(false, [66, 65, 256, 257, 65, 260])` deve retornar `"BABAABAAA"`.
|
||||
|
||||
```js
|
||||
assert.equal(LZW(false, [66, 65, 256, 257, 65, 260]), 'BABAABAAA');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 59667989bf71cf555dd5d2ff
|
||||
title: S-Expressions
|
||||
title: Expressões S
|
||||
challengeType: 5
|
||||
forumTopicId: 302303
|
||||
dashedName: s-expressions
|
||||
@ -8,47 +8,47 @@ dashedName: s-expressions
|
||||
|
||||
# --description--
|
||||
|
||||
[S-Expressions](https://en.wikipedia.org/wiki/S-Expression "wp: S-Expression") are one convenient way to parse and store data.
|
||||
[Expressões S](https://en.wikipedia.org/wiki/S-Expression "wp: S-Expression") são uma maneira conveniente de analisar e armazenar dados.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a simple reader/parser for S-Expressions that handles quoted and unquoted strings, integers and floats.
|
||||
Escreva um leitor/analisador simples para Expressões S que lide com strings entre aspas ou não, números inteiros e flutuantes (decimais).
|
||||
|
||||
The function should read a single but nested S-Expression from a string and return it as a (nested) array.
|
||||
A função deve ler uma única Expressão S, porém aninhada, de uma string e retorná-la como um array (aninhado).
|
||||
|
||||
Newlines and other whitespace may be ignored unless contained within a quoted string.
|
||||
Novas linhas e outros tipos de espaço em branco devem ser ignorados a menos que estejam contidos em uma string entre aspas.
|
||||
|
||||
"`()`" inside quoted strings are not interpreted, but treated as part of the string.
|
||||
"`()`" em strings entre aspas não são interpretados, mas tratados como parte da string.
|
||||
|
||||
Handling escaped quotes inside a string is optional; thus "`(foo"bar)`" may be treated as a string "`foo"bar`", or as an error.
|
||||
Tratar de aspas com escape dentro de uma string é opcional. Assim, "`(foo"bar)`" pode ser tratado como uma string "`foo"bar`" ou como um erro.
|
||||
|
||||
For this, the reader need not recognize `\` for escaping, but should, in addition, recognize numbers if the language has appropriate data types.
|
||||
Para isso, o leitor não precisa reconhecer `\` para escape, mas deve, além disso, reconhecer números se a linguagem tiver tipos de dados apropriados.
|
||||
|
||||
Note that with the exception of `()"` (`\` if escaping is supported) and whitespace, there are no special characters. Anything else is allowed without quotes.
|
||||
Observe que, com a exceção de `()"` (`\`, se houver suporte a escape) e do espaço em branco, não há caracteres especiais. Todo o resto é permitido sem aspas.
|
||||
|
||||
The reader should be able to read the following input
|
||||
O leitor deve poder ler a entrada a seguir
|
||||
|
||||
<pre>((data "quoted data" 123 4.5)
|
||||
(data (!@# (4.5) "(more" "data)")))
|
||||
</pre>
|
||||
|
||||
and turn it into a native data structure. (See the [Pike](https://rosettacode.org/wiki/S-Expressions#Pike "\#Pike"), [Python](https://rosettacode.org/wiki/S-Expressions#Python "\#Python") and [Ruby](https://rosettacode.org/wiki/S-Expressions#Ruby "\#Ruby") implementations for examples of native data structures.)
|
||||
e transformá-la em uma estrutura de dados nativa. (veja as implementações em [Pike](https://rosettacode.org/wiki/S-Expressions#Pike "\#Pike"), [Python](https://rosettacode.org/wiki/S-Expressions#Python "\#Python") e [Ruby](https://rosettacode.org/wiki/S-Expressions#Ruby "\#Ruby") para obter exemplos de estruturas de dados nativas.)
|
||||
|
||||
# --hints--
|
||||
|
||||
`parseSexpr` should be a function.
|
||||
`parseSexpr` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof parseSexpr === 'function');
|
||||
```
|
||||
|
||||
`parseSexpr('(data1 data2 data3)')` should return `['data1', 'data2', 'data3']`
|
||||
`parseSexpr('(data1 data2 data3)')` deve retornar `['data1', 'data2', 'data3']`
|
||||
|
||||
```js
|
||||
assert.deepEqual(parseSexpr(simpleSExpr), simpleSolution);
|
||||
```
|
||||
|
||||
`parseSexpr('((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))')` should return `[['data', '"quoted data"', 123, 4.5], ['data', ['!@#', [4.5], '"(more"', '"data)"']]]`.
|
||||
`parseSexpr('((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))')` deve retornar `[['data', '"quoted data"', 123, 4.5], ['data', ['!@#', [4.5], '"(more"', '"data)"']]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(parseSexpr(basicSExpr), basicSolution);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 59da22823d04c95919d46269
|
||||
title: 'Sailors, coconuts and a monkey problem'
|
||||
title: 'Problema dos marinheiros, dos cocos e do macaco'
|
||||
challengeType: 5
|
||||
forumTopicId: 302304
|
||||
dashedName: sailors-coconuts-and-a-monkey-problem
|
||||
@ -8,38 +8,38 @@ dashedName: sailors-coconuts-and-a-monkey-problem
|
||||
|
||||
# --description--
|
||||
|
||||
Five sailors are shipwrecked on an island and collect a large pile of coconuts during the day. That night the first sailor wakes up and decides to take his first share early so tries to divide the pile of coconuts equally into five piles but finds that there is one coconut left over, so he tosses it to a monkey and then hides "his" one of the five equally sized piles of coconuts and pushes the other four piles together to form a single visible pile of coconuts again and goes to bed. To cut a long story short, each of the sailors in turn gets up once during the night and performs the same actions of dividing the coconut pile into five, finding that one coconut is left over and giving that single remainder coconut to the monkey. In the morning (after the surreptitious and separate action of each of the five sailors during the night), the remaining coconuts are divided into five equal piles for each of the sailors, whereupon it is found that the pile of coconuts divides equally amongst the sailors with no remainder. (Nothing for the monkey in the morning.)
|
||||
Cinco marinheiros são náufragos em uma ilha e coletam muitos cocos durante o dia. Naquela noite, o primeiro marinheiro acorda e decide tomar a sua parte dos cocos mais cedo, então tenta dividir o monte de cocos igualmente em cinco pilhas, mas descobre que ainda há um coco sobrando. Então, ele o joga para um macaco e então esconde "sua" pilha, uma das cinco pilhas de cocos de tamanho igual, e empurra os outros quatro montes para formar um único monte visível de cocos novamente e vai para a cama. Resumindo uma longa história, cada marinheiro por sua vez se levanta uma vez durante a noite e executa as mesmas ações de dividir a pilha de cocos em cinco, descobrindo que sobra um coco e deixando o coco que resta para o macaco. De manhã (depois da ação às escondidas e separada de cada um dos cinco marinheiros durante a noite), os cocos restantes são divididos em cinco pilhas iguais para cada um dos marinheiros, onde se descobre que a pilha de cocos pode ser dividida igualmente entre os marinheiros, sem sobrar nenhum. (Nada é dado para o macaco da manhã.)
|
||||
|
||||
# --instructions--
|
||||
|
||||
Create a function that returns the minimum possible size of the initial pile of coconuts collected during the day for `N` sailors. **Note:** Of course the tale is told in a world where the collection of any amount of coconuts in a day and multiple divisions of the pile, etc. can occur in time fitting the story line, so as not to affect the mathematics. **C.f:**
|
||||
Crie uma função que retorne o tamanho mínimo possível para a pilha inicial de cocos coletados durante o dia para `N` marinheiros. **Observação:** logicamente, a história é contada em um mundo onde a coleção de qualquer quantidade de cocos em um dia e múltiplas divisões do monte pode ocorrer em tempo ajustando a linha da história, de modo a não afetar a matemática. **De acordo com:**
|
||||
|
||||
<ul>
|
||||
<li><a href="https://www.youtube.com/watch?v=U9qU20VmvaU" target="_blank"> Monkeys and Coconuts - Numberphile</a> (Video) Analytical solution.</li>
|
||||
<li><a href="https://oeis.org/A002021" target="_blank">A002021 Pile of coconuts problem</a> The On-Line Encyclopedia of Integer Sequences. (Although some of its references may use the alternate form of the tale).</li>
|
||||
<li><a href="https://www.youtube.com/watch?v=U9qU20VmvaU" target="_blank"> Monkeys and Coconuts - Numberphile</a> (Vídeo) Solução analítica.</li>
|
||||
<li><a href="https://oeis.org/A002021" target="_blank">A002021 Pile of coconuts problem</a> The On-Line Encyclopedia of Integer Sequences. (Embora algumas das referências possam usar a forma alternativa de conto).</li>
|
||||
</ul>
|
||||
|
||||
# --hints--
|
||||
|
||||
`splitCoconuts` should be a function.
|
||||
`splitCoconuts` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof splitCoconuts === 'function');
|
||||
```
|
||||
|
||||
`splitCoconuts(5)` should return 3121.
|
||||
`splitCoconuts(5)` deve retornar 3121.
|
||||
|
||||
```js
|
||||
assert(splitCoconuts(5) === 3121);
|
||||
```
|
||||
|
||||
`splitCoconuts(6)` should return 233275.
|
||||
`splitCoconuts(6)` deve retornar 233275.
|
||||
|
||||
```js
|
||||
assert(splitCoconuts(6) === 233275);
|
||||
```
|
||||
|
||||
`splitCoconuts(7)` should return 823537.
|
||||
`splitCoconuts(7)` deve retornar 823537.
|
||||
|
||||
```js
|
||||
assert(splitCoconuts(7) === 823537);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5eb3e497b8d6d7f63c5517ea
|
||||
title: Search a list of records
|
||||
title: Procurar em uma lista de registros
|
||||
challengeType: 5
|
||||
forumTopicId: 385315
|
||||
dashedName: search-a-list-of-records
|
||||
@ -8,51 +8,51 @@ dashedName: search-a-list-of-records
|
||||
|
||||
# --description--
|
||||
|
||||
A record consists of attributes that describe an entity. Each attribute has a name and a value. For example, a person can have an attribute `age` with a value of 25. An important operation on a list of records is to find a record with a particular attribute value.
|
||||
Um registro é composto de atributos que descrevem uma entidade. Cada atributo tem um nome e um valor. Por exemplo, uma pessoa pode ter um atributo `age` (idade) com um valor de 25. Uma operação importante em uma lista de registros é encontrar um registro com um valor de atributo específico.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes a string as a parameter. The function should return the index of the item in `list` for which the value of the `name` attribute matches the given string.
|
||||
Escreva uma função que receba uma string como parâmetro. A função deve retornar o índice do item na `list` para o qual o valor do atributo `name` corresponde à string fornecida.
|
||||
|
||||
# --hints--
|
||||
|
||||
`searchCity` should be a function.
|
||||
`searchCity` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof searchCity === 'function');
|
||||
```
|
||||
|
||||
`searchCity("Dar Es Salaam")` should return a number.
|
||||
`searchCity("Dar Es Salaam")` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof searchCity('Dar Es Salaam') === 'number');
|
||||
```
|
||||
|
||||
`searchCity("Dar Es Salaam")` should return `6`.
|
||||
`searchCity("Dar Es Salaam")` deve retornar `6`.
|
||||
|
||||
```js
|
||||
assert.equal(searchCity('Dar Es Salaam'), 6);
|
||||
```
|
||||
|
||||
`searchCity("Casablanca")` should return `9`.
|
||||
`searchCity("Casablanca")` deve retornar `9`.
|
||||
|
||||
```js
|
||||
assert.equal(searchCity('Casablanca'), 9);
|
||||
```
|
||||
|
||||
`searchCity("Cairo")` should return `1`.
|
||||
`searchCity("Cairo")` deve retornar `1`.
|
||||
|
||||
```js
|
||||
assert.equal(searchCity('Cairo'), 1);
|
||||
```
|
||||
|
||||
`searchCity("Mogadishu")` should return `4`.
|
||||
`searchCity("Mogadishu")` deve retornar `4`.
|
||||
|
||||
```js
|
||||
assert.equal(searchCity('Mogadishu'), 4);
|
||||
```
|
||||
|
||||
`searchCity("Lagos")` should return `0`.
|
||||
`searchCity("Lagos")` deve retornar `0`.
|
||||
|
||||
```js
|
||||
assert.equal(searchCity('Lagos'), 0);
|
||||
|
@ -8,7 +8,7 @@ dashedName: sedols
|
||||
|
||||
# --description--
|
||||
|
||||
For each number list of 6-digit [SEDOL](https://en.wikipedia.org/wiki/SEDOL "wp: SEDOL")s, calculate and append the checksum digit. That is, given the input string on the left, your function should return the corresponding string on the right:
|
||||
Para cada lista de números de 6 algarismos [SEDOL](https://en.wikipedia.org/wiki/SEDOL "wp: SEDOL"), calcule e acrescente o algarismo da soma de verificação. Ou seja, dada a string de entrada à esquerda, sua função deve retornar a string correspondente à direita:
|
||||
|
||||
<pre>
|
||||
710889 => 7108899
|
||||
@ -24,35 +24,35 @@ B0YBKT => B0YBKT7
|
||||
B00030 => B000300
|
||||
</pre>
|
||||
|
||||
Check that each input is correctly formed, especially with respect to valid characters allowed in a SEDOL string. Your function should return `null` on an invalid input.
|
||||
Verifique se cada entrada é formada corretamente, especialmente em relação a caracteres válidos permitidos em uma string SEDOL. A função deve retornar `null` quando a entrada for inválida.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sedol` should be a function.
|
||||
`sedol` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof sedol === 'function');
|
||||
```
|
||||
|
||||
`sedol('a')` should return null.
|
||||
`sedol('a')` deve retornar null.
|
||||
|
||||
```js
|
||||
assert(sedol('a') === null);
|
||||
```
|
||||
|
||||
`sedol('710889')` should return '7108899'.
|
||||
`sedol('710889')` deve retornar '7108899'.
|
||||
|
||||
```js
|
||||
assert(sedol('710889') === '7108899');
|
||||
```
|
||||
|
||||
`sedol('BOATER')` should return null.
|
||||
`sedol('BOATER')` deve retornar null.
|
||||
|
||||
```js
|
||||
assert(sedol('BOATER') === null);
|
||||
```
|
||||
|
||||
`sedol('228276')` should return '2282765'.
|
||||
`sedol('228276')` deve retornar '2282765'.
|
||||
|
||||
```js
|
||||
assert(sedol('228276') === '2282765');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5eaf48389ee512d4d103684b
|
||||
title: Self Describing Numbers
|
||||
title: Números autodescritivos
|
||||
challengeType: 5
|
||||
forumTopicId: 385289
|
||||
dashedName: self-describing-numbers
|
||||
@ -8,52 +8,52 @@ dashedName: self-describing-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
There are several so-called "self describing" or ["self-descriptive"](https://en.wikipedia.org/wiki/Self-descriptive_number) integers.
|
||||
Há vários números inteiros chamados de ["autodescritivos"](https://en.wikipedia.org/wiki/Self-descriptive_number).
|
||||
|
||||
An integer is said to be "self-describing" if it has the property that, when digit positions are labeled 0 to N-1, the digit in each position is equal to the number of times that digit appears in the number.
|
||||
Diz-se que um número inteiro é "autodescritivo" quando ele tem uma propriedade que, quando as posições dos dígitos são rotuladas de 0 a N-1, o algarismo em cada posição é igual ao número de vezes em que o algarismo aparece no número.
|
||||
|
||||
For example, **2020** is a four-digit self describing number:
|
||||
Por exemplo, **2020** é um número autodescritivo de quatro dígitos:
|
||||
|
||||
<ul>
|
||||
<li> position 0 has value 2 and there are two 0s in the number; </li>
|
||||
<li> position 1 has value 0 and there are no 1s in the number; </li>
|
||||
<li> position 2 has value 2 and there are two 2s; </li>
|
||||
<li> position 3 has value 0 and there are zero 3s; </li>
|
||||
<li> a posição 0 tem o valor 2 e há dois 0s no número; </li>
|
||||
<li> a posição 1 tem valor 0 e o número 1 não é encontrado no número; </li>
|
||||
<li> a posição 2 tem o valor 2 e há dois 2s no número; </li>
|
||||
<li> a posição 3 tem o valor 0 e o número 3 não é encontrado no número; </li>
|
||||
</ul>
|
||||
|
||||
Self-describing numbers < 100,000,000 are: 1210, 2020, 21200, 3211000, 42101000.
|
||||
Os números autodescritivos < 100.000.000 são: 1210, 2020, 21200, 3211000, 42101000.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes a positive integer as a parameter. If it is self-describing return true. Otherwise, return false.
|
||||
Escreva uma função que receba um número inteiro positivo como parâmetro. Se ele for autodescritivo, retorne true. Caso contrário, retorne false.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isSelfDescribing` should be a function.
|
||||
`isSelfDescribing` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof isSelfDescribing == 'function');
|
||||
```
|
||||
|
||||
`isSelfDescribing()` should return a boolean.
|
||||
`isSelfDescribing()` deve retornar um booleano.
|
||||
|
||||
```js
|
||||
assert(typeof isSelfDescribing(2020) == 'boolean');
|
||||
```
|
||||
|
||||
`isSelfDescribing(2020)` should return `true`.
|
||||
`isSelfDescribing(2020)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isSelfDescribing(2020), true);
|
||||
```
|
||||
|
||||
`isSelfDescribing(3021)` should return `false`.
|
||||
`isSelfDescribing(3021)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isSelfDescribing(3021), false);
|
||||
```
|
||||
|
||||
`isSelfDescribing(3211000)` should return `true`.
|
||||
`isSelfDescribing(3211000)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isSelfDescribing(3211000), true);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5eb3e4a21f462f409d656c73
|
||||
title: Self-referential sequence
|
||||
title: Sequência autorreferencial
|
||||
challengeType: 5
|
||||
forumTopicId: 385317
|
||||
dashedName: self-referential-sequence
|
||||
@ -8,41 +8,41 @@ dashedName: self-referential-sequence
|
||||
|
||||
# --description--
|
||||
|
||||
There are several ways to generate a self-referential sequence. One very common one (the [Look-and-say sequence](https://rosettacode.org/wiki/Look-and-say sequence)) is to start with a positive integer, then generate the next term by concatenating enumerated groups of adjacent alike digits:
|
||||
Existem várias maneiras de gerar uma sequência autorreferencial. Uma maneira muito comum (a [Sequência de olhar e dizer](https://rosettacode.org/wiki/Look-and-say sequence)) é começar com um número inteiro positivo e gerar o próximo termo concatenando grupos enumerados de dígitos adjacentes semelhantes:
|
||||
|
||||
<pre>0, 10, 1110, 3110, 132110, 1113122110, 311311222110 ...</pre>
|
||||
|
||||
The terms generated grow in length geometrically and never converge.
|
||||
Os termos gerados crescem em extensão geometricamente e nunca convergem.
|
||||
|
||||
Another way to generate a self-referential sequence is to summarize the previous term.
|
||||
Outra maneira de gerar uma sequência autorreferencial é resumir o termo anterior.
|
||||
|
||||
Count how many of each alike digit there is, then concatenate the sum and digit for each of the sorted enumerated digits. Note that the first five terms are the same as for the previous sequence.
|
||||
Conte quantos algarismos semelhantes existem de cada um dos algarismos, então concatene a soma e o algarismo de cada um dos dígitos enumerados ordenados. Observe que os primeiros cinco termos são os mesmos que para a sequência anterior.
|
||||
|
||||
<pre>0, 10, 1110, 3110, 132110, 13123110, 23124110 ...</pre>
|
||||
|
||||
Sort the digits largest to smallest. Do not include counts of digits that do not appear in the previous term.
|
||||
Ordene os dígitos dos maiores para os menores. Não inclua contagens de dígitos que não apareçam no termo anterior.
|
||||
|
||||
Depending on the seed value, series generated this way always either converge to a stable value or to a short cyclical pattern. (For our purposes, converge means that an element matches a previously seen element.) The sequence shown, with a seed value of 0, converges to a stable value of 1433223110 after 11 iterations. The seed value that converges most quickly is 22. It goes stable after the first element. (The next element is 22, which has been seen before.)
|
||||
Dependendo do valor da seed, a série gerada dessa forma sempre levará para um valor estável ou para um padrão cíclico curto. (Para nossos fins, essa conversão significa que um elemento corresponde a um elemento visto anteriormente.) A sequência mostrada, com um valor de seed de 0, converte para um valor estável de 1433223110 após 11 iterações. O valor de seed que tem a conversão mais rápida é 22. Ela torna a sequência estável após o primeiro elemento. (O próximo elemento é 22, que já foi visto antes)
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes the seed value as parameter, generates a self referential sequence until it converges, and returns it as an array.
|
||||
Escreva uma função que receba o valor de seed como parâmetro, gere uma sequência autorreferencial até convergir, e a retorne como um array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`selfReferential` should be a function.
|
||||
`selfReferential` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof selfReferential === 'function');
|
||||
```
|
||||
|
||||
`selfReferential(40)` should return a array.
|
||||
`selfReferential(40)` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(selfReferential(40)));
|
||||
```
|
||||
|
||||
`selfReferential(40)` should return `["40", "1410", "142110", "14123110", "1413124110", "2413125110", "151413224110", "152413225110", "251413324110", "152423224110", "152413423110"]`.
|
||||
`selfReferential(40)` deve retornar `["40", "1410", "142110", "14123110", "1413124110", "2413125110", "151413224110", "152413225110", "251413324110", "152423224110", "152413423110"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(selfReferential(40), [
|
||||
@ -60,7 +60,7 @@ assert.deepEqual(selfReferential(40), [
|
||||
]);
|
||||
```
|
||||
|
||||
`selfReferential(132110)` should return `["132110", "13123110", "23124110", "1413223110", "1423224110", "2413323110", "1433223110"]`.
|
||||
`selfReferential(132110)` deve retornar `["132110", "13123110", "23124110", "1413223110", "1423224110", "2413323110", "1433223110"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(selfReferential(132110), [
|
||||
@ -74,7 +74,7 @@ assert.deepEqual(selfReferential(132110), [
|
||||
]);
|
||||
```
|
||||
|
||||
`selfReferential(132211)` should return `["132211", "132231", "232221", "134211", "14131231", "14231241", "24132231", "14233221"]`.
|
||||
`selfReferential(132211)` deve retornar `["132211", "132231", "232221", "134211", "14131231", "14231241", "24132231", "14233221"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(selfReferential(132211), [
|
||||
@ -89,7 +89,7 @@ assert.deepEqual(selfReferential(132211), [
|
||||
]);
|
||||
```
|
||||
|
||||
`selfReferential(1413223110)` should return `["1413223110", "1423224110", "2413323110", "1433223110"]`.
|
||||
`selfReferential(1413223110)` deve retornar `["1413223110", "1423224110", "2413323110", "1433223110"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(selfReferential(1413223110), [
|
||||
@ -100,7 +100,7 @@ assert.deepEqual(selfReferential(1413223110), [
|
||||
]);
|
||||
```
|
||||
|
||||
`selfReferential(251413126110)` should return `["251413126110", "16151413225110", "16251413226110", "26151413325110", "16251423225110", "16251413424110", "16153413225110"]`.
|
||||
`selfReferential(251413126110)` deve retornar `["251413126110", "16151413225110", "16251413226110", "26151413325110", "16251423225110", "16251413424110", "16153413225110"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(selfReferential(251413126110), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5eb3e4aa847216613aa81983
|
||||
title: Semiprime
|
||||
title: Semiprimo
|
||||
challengeType: 5
|
||||
forumTopicId: 385318
|
||||
dashedName: semiprime
|
||||
@ -8,83 +8,83 @@ dashedName: semiprime
|
||||
|
||||
# --description--
|
||||
|
||||
Semiprime numbers are natural numbers that are products of exactly two (possibly equal) [prime numbers](https://rosettacode.org/wiki/prime_number).
|
||||
Números semiprimos são números naturais que são produtos de dois [números primos](https://rosettacode.org/wiki/prime_number) (que podem ser iguais).
|
||||
|
||||
<pre>1679 = 23 x 73</pre>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that returns true if a number is semiprime, or false if it is not.
|
||||
Escreva uma função que retorne true se um número for semiprimo, ou false se não for.
|
||||
|
||||
# --hints--
|
||||
|
||||
`isSemiPrime` should be a function.
|
||||
`isSemiPrime` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof isSemiPrime === 'function');
|
||||
```
|
||||
|
||||
`isSemiPrime(100)` should return a boolean.
|
||||
`isSemiPrime(100)` deve retornar um booleano.
|
||||
|
||||
```js
|
||||
assert(typeof isSemiPrime(100) === 'boolean');
|
||||
```
|
||||
|
||||
`isSemiPrime(100)` should return `false`.
|
||||
`isSemiPrime(100)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isSemiPrime(100), false);
|
||||
```
|
||||
|
||||
`isSemiPrime(504)` should return `false`.
|
||||
`isSemiPrime(504)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isSemiPrime(504), false);
|
||||
```
|
||||
|
||||
`isSemiPrime(4)` should return `true`.
|
||||
`isSemiPrime(4)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isSemiPrime(4), true);
|
||||
```
|
||||
|
||||
`isSemiPrime(46)` should return `true`.
|
||||
`isSemiPrime(46)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isSemiPrime(46), true);
|
||||
```
|
||||
|
||||
`isSemiPrime(13)` should return `false`.
|
||||
`isSemiPrime(13)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isSemiPrime(13), false);
|
||||
```
|
||||
|
||||
`isSemiPrime(74)` should return `true`.
|
||||
`isSemiPrime(74)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isSemiPrime(74), true);
|
||||
```
|
||||
|
||||
`isSemiPrime(1679)` should return `true`.
|
||||
`isSemiPrime(1679)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isSemiPrime(1679), true);
|
||||
```
|
||||
|
||||
`isSemiPrime(2)` should return `false`.
|
||||
`isSemiPrime(2)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isSemiPrime(2), false);
|
||||
```
|
||||
|
||||
`isSemiPrime(95)` should return `true`.
|
||||
`isSemiPrime(95)` deve retornar `true`.
|
||||
|
||||
```js
|
||||
assert.equal(isSemiPrime(95), true);
|
||||
```
|
||||
|
||||
`isSemiPrime(124)` should return `false`.
|
||||
`isSemiPrime(124)` deve retornar `false`.
|
||||
|
||||
```js
|
||||
assert.equal(isSemiPrime(124), false);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5eb3e4b20aa93c437f9e9717
|
||||
title: Set of real numbers
|
||||
title: Conjunto de números reais
|
||||
challengeType: 5
|
||||
forumTopicId: 385322
|
||||
dashedName: set-of-real-numbers
|
||||
@ -8,61 +8,61 @@ dashedName: set-of-real-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
All real numbers form the uncountable set ℝ. Among its subsets, relatively simple are the convex sets, each expressed as a range between two real numbers *a* and *b* where *a* ≤ *b*. There are actually four cases for the meaning of "between", depending on open or closed boundary:
|
||||
Todos os números reais formam o conjunto incontável ℝ. Entre seus subconjuntos, são conjuntos relativamente simples os conjuntos convexos, cada um deles expressando um intervalo entre dois números reais *a* e *b*, onde *a* ≤ *b*. Na verdade, há quatro casos para o significado de "entre", dependendo dos limites abertos ou fechados:
|
||||
|
||||
<ul>
|
||||
<li>[<i>a</i>, <i>b</i>]: {<i>x</i> | <i>a</i> ≤ <i>x</i> and <i>x</i> ≤ <i>b</i> }</li>
|
||||
<li>(<i>a</i>, <i>b</i>): {<i>x</i> | <i>a</i> < <i>x</i> and <i>x</i> < <i>b</i> }</li>
|
||||
<li>[<i>a</i>, <i>b</i>): {<i>x</i> | <i>a</i> ≤ <i>x</i> and <i>x</i> < <i>b</i> }</li>
|
||||
<li>(<i>a</i>, <i>b</i>]: {<i>x</i> | <i>a</i> < <i>x</i> and <i>x</i> ≤ <i>b</i> }</li>
|
||||
<li>[<i>a</i>, <i>b</i>]: {<i>x</i> | <i>a</i> ≤ <i>x</i> e <i>x</i> ≤ <i>b</i> }</li>
|
||||
<li>(<i>a</i>, <i>b</i>): {<i>x</i> | <i>a</i> < <i>x</i> e <i>x</i> < <i>b</i> }</li>
|
||||
<li>[<i>a</i>, <i>b</i>): {<i>x</i> | <i>a</i> ≤ <i>x</i> e <i>x</i> < <i>b</i> }</li>
|
||||
<li>(<i>a</i>, <i>b</i>]: {<i>x</i> | <i>a</i> < <i>x</i> e <i>x</i> ≤ <i>b</i> }</li>
|
||||
</ul>
|
||||
|
||||
Note that if *a* = *b*, of the four only \[*a*, *a*] would be non-empty.
|
||||
Observe que, se *a* = *b*, dos quatro, apenas \[*a*, *a*] não seria vazio.
|
||||
|
||||
**Task**
|
||||
**Tarefa**
|
||||
|
||||
<ul>
|
||||
<li>Devise a way to represent any set of real numbers, for the definition of "any" in the implementation notes below.</li>
|
||||
<li>Provide methods for these common set operations (<i>x</i> is a real number; <i>A</i> and <i>B</i> are sets):</li>
|
||||
<li>Elabore uma forma de representar qualquer conjunto de números reais, para a definição de "qualquer" nas notas de implementação abaixo.</li>
|
||||
<li>Forneça métodos para estas operações com conjuntos comuns (<i>x</i> é um número real; <i>A</i> e <i>B</i> são conjuntos):</li>
|
||||
<ul>
|
||||
<li>
|
||||
<i>x</i> ∈ <i>A</i>: determine if <i>x</i> is an element of <i>A</i><br>
|
||||
example: 1 is in [1, 2), while 2, 3, ... are not.
|
||||
<i>x</i> ∈ <i>A</i>: determine se <i>x</i> é um elemento de <i>A</i><br>
|
||||
exemplo: 1 está em [1, 2), enquanto 2, 3, ... não estão.
|
||||
</li>
|
||||
<li>
|
||||
<i>A</i> ∪ <i>B</i>: union of <i>A</i> and <i>B</i>, i.e. {<i>x</i> | <i>x</i> ∈ <i>A</i> or <i>x</i> ∈ <i>B</i>}<br>
|
||||
example: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = well, [0, 1) ∪ (2, 3]
|
||||
<i>A</i> ∪ <i>B</i>: união de <i>A</i> e <i>B</i>, ou seja, {<i>x</i> | <i>x</i> ∈ <i>A</i> ou <i>x</i> ∈ <i>B</i>}<br>
|
||||
exemplo: [0, 2) ∪ (1, 3) = [0, 3); [0, 1) ∪ (2, 3] = assim, [0, 1) ∪ (2, 3]
|
||||
</li>
|
||||
<li>
|
||||
<i>A</i> ∩ <i>B</i>: intersection of <i>A</i> and <i>B</i>, i.e. {<i>x</i> | <i>x</i> ∈ <i>A</i> and <i>x</i> ∈ <i>B</i>}<br>
|
||||
example: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = empty set
|
||||
<i>A</i> ∩ <i>B</i>: intersecção de <i>A</i> e <i>B</i>, ou seja, {<i>x</i> | <i>x</i> ∈ <i>A</i> e <i>x</i> ∈ <i>B</i>}<br>
|
||||
exemplo: [0, 2) ∩ (1, 3) = (1, 2); [0, 1) ∩ (2, 3] = conjunto vazio
|
||||
</li>
|
||||
<li>
|
||||
<i>A</i> - <i>B</i>: difference between <i>A</i> and <i>B</i>, also written as <i>A</i> \ <i>B</i>, i.e. {<i>x</i> | <i>x</i> ∈ <i>A</i> and <i>x</i> ∉ <i>B</i>}<br>
|
||||
example: [0, 2) − (1, 3) = [0, 1]
|
||||
<i>A</i> - <i>B</i>: diferença entre <i>A</i> e <i>B</i>, também escrito <i>A</i> \ <i>B</i>, ou seja, {<i>x</i> | <i>x</i> ∈ <i>A</i> e <i>x</i> ∉ <i>B</i>}<br>
|
||||
exemplo: [0, 2) − (1, 3) = [0, 1]
|
||||
</li>
|
||||
</ul>
|
||||
</ul>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes 2 objects, a string and an array as parameters. The objects represents the set and have attributes: `low`, `high` and `rangeType`.
|
||||
Escreva uma função que receba 2 objetos, uma string e um array, como parâmetros. Os objetos representam o conjunto e têm atributos: `low`, `high` e `rangeType`.
|
||||
|
||||
The `rangeType` can have values 0, 1, 2 and 3 for `CLOSED`, `BOTH_OPEN`, `LEFT_OPEN` and `RIGHT_OPEN`, respectively. The function should implement a set using this information.
|
||||
O atributo `rangeType` pode ter os valores 0, 1, 2 e 3 para `CLOSED`, `BOTH_OPEN`, `LEFT_OPEN` e `RIGHT_OPEN` (fechado, aberto dos dois lados, aberto à esquerda e aberto à direita), respectivamente. A função deve implementar um conjunto usando esta informação.
|
||||
|
||||
The string represents the operation to be performed on the sets. It can be: `"union"`, `"intersect"` and `"subtract"` (difference).
|
||||
A string representa a operação a ser realizada nos conjuntos. Ela pode ser: `"union"`, `"intersect"` e `"subtract"` (diferença).
|
||||
|
||||
After performing the operation, the function should check if the values in the array are present in the resultant set and store a corresponding boolean value to an array. The function should return this array.
|
||||
Após executar a operação, a função deve verificar se os valores no array estão presentes no conjunto resultante e armazenar um valor booleano correspondente em um array. A função deve retornar esse array.
|
||||
|
||||
# --hints--
|
||||
|
||||
`realSet` should be a function.
|
||||
`realSet` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof realSet == 'function');
|
||||
```
|
||||
|
||||
`realSet({"low":0, "high":1, "rangeType":2}, {"low":0, "high":2, "rangeType":3}, "union", [1, 2, 3])` should return a array.
|
||||
`realSet({"low":0, "high":1, "rangeType":2}, {"low":0, "high":2, "rangeType":3}, "union", [1, 2, 3])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -77,7 +77,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`realSet({"low":0, "high":1, "rangeType":2}, {"low":0, "high":2, "rangeType":3}, "union", [1, 2, 3])` should return `[true, false, false]`.
|
||||
`realSet({"low":0, "high":1, "rangeType":2}, {"low":0, "high":2, "rangeType":3}, "union", [1, 2, 3])` deve retornar `[true, false, false]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -91,7 +91,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`realSet({"low":0, "high":2, "rangeType":3}, {"low":1, "high":2, "rangeType":2}, "intersect", [0, 1, 2])` should return `[false, false, false]`.
|
||||
`realSet({"low":0, "high":2, "rangeType":3}, {"low":1, "high":2, "rangeType":2}, "intersect", [0, 1, 2])` deve retornar `[false, false, false]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -105,7 +105,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`realSet({"low":0, "high":3, "rangeType":3}, {"low":0, "high":1, "rangeType":1}, "subtract", [0, 1, 2])` should return `[true, true, true]`.
|
||||
`realSet({"low":0, "high":3, "rangeType":3}, {"low":0, "high":1, "rangeType":1}, "subtract", [0, 1, 2])` deve retornar `[true, true, true]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -119,7 +119,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`realSet({"low":0, "high":3, "rangeType":3}, {"low":0, "high":1, "rangeType":0}, "subtract", [0, 1, 2])` should return `[false, false, true]`.
|
||||
`realSet({"low":0, "high":3, "rangeType":3}, {"low":0, "high":1, "rangeType":0}, "subtract", [0, 1, 2])` deve retornar `[false, false, true]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -133,7 +133,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`realSet({"low":0, "high":33, "rangeType":1}, {"low":30, "high":31, "rangeType":0}, "intersect", [30, 31, 32])` should return `[true, true, false]`.
|
||||
`realSet({"low":0, "high":33, "rangeType":1}, {"low":30, "high":31, "rangeType":0}, "intersect", [30, 31, 32])` deve retornar `[true, true, false]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8028
|
||||
title: Stern-Brocot sequence
|
||||
title: Sequência de Stern-Brocot
|
||||
challengeType: 5
|
||||
forumTopicId: 302324
|
||||
dashedName: stern-brocot-sequence
|
||||
@ -8,75 +8,73 @@ 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 tarefa, a sequência Stern-Brocot deve ser gerada por um algoritmo semelhante ao empregado na geração da [sequência de Fibonacci](https://rosettacode.org/wiki/Fibonacci sequence).
|
||||
|
||||
<ol>
|
||||
<li>The first and second members of the sequence are both 1:</li>
|
||||
<li>O primeiro e o segundo membros da sequência são ambos 1:</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>Comece considerando o segundo membro da sequência</li>
|
||||
<li>Some o membro considerado da sequência e seu precedente, (1 + 1) = 2, e acrescente-o ao final da sequência:</li>
|
||||
<ul><li>1, 1, 2</li></ul>
|
||||
<li>Append the considered member of the sequence to the end of the sequence:</li>
|
||||
<li>Acrescente o membro considerado da sequência ao final da sequência:</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>GOTO 3 </li>
|
||||
<li>Considere o próximo membro da série (o terceiro membro, ou seja, 2)</li>
|
||||
<li>IR PARA 3 </li>
|
||||
<ul>
|
||||
<li></li>
|
||||
<li> ─── Expanding another loop we get: ───</li>
|
||||
<li> ─── Expandindo outro laço, obtemos agora: ───</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>Some o membro considerado da sequência e seu precedente, (2 + 1) = 3, e acrescente-o ao final da sequência:</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>
|
||||
<li>Acrescente o membro considerado da sequência ao final da sequência:</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>Considere o próximo membro da série (o quarto membro, ou seja, 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.
|
||||
Crie uma função que retorne a posição na sequência Stern-Brocot em que $ n $ é encontrado pela primeira vez, onde a sequência é gerada com o método descrito acima. Observe que essa sequência usa uma indexação baseada em 1.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sternBrocot` should be a function.
|
||||
`sternBrocot` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof sternBrocot == 'function');
|
||||
```
|
||||
|
||||
`sternBrocot(2)` should return a number.
|
||||
`sternBrocot(2)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof sternBrocot(2) == 'number');
|
||||
```
|
||||
|
||||
`sternBrocot(2)` should return `3`.
|
||||
`sternBrocot(2)` deve retornar `3`.
|
||||
|
||||
```js
|
||||
assert.equal(sternBrocot(2), 3);
|
||||
```
|
||||
|
||||
`sternBrocot(3)` should return `5`.
|
||||
`sternBrocot(3)` deve retornar `5`.
|
||||
|
||||
```js
|
||||
assert.equal(sternBrocot(3), 5);
|
||||
```
|
||||
|
||||
`sternBrocot(5)` should return `11`.
|
||||
`sternBrocot(5)` deve retornar `11`.
|
||||
|
||||
```js
|
||||
assert.equal(sternBrocot(5), 11);
|
||||
```
|
||||
|
||||
`sternBrocot(7)` should return `19`.
|
||||
`sternBrocot(7)` deve retornar `19`.
|
||||
|
||||
```js
|
||||
assert.equal(sternBrocot(7), 19);
|
||||
```
|
||||
|
||||
`sternBrocot(10)` should return `39`.
|
||||
`sternBrocot(10)` deve retornar `39`.
|
||||
|
||||
```js
|
||||
assert.equal(sternBrocot(10), 39);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 595011cba5a81735713873bd
|
||||
title: Top rank per group
|
||||
title: Melhores classificações por grupo
|
||||
challengeType: 5
|
||||
forumTopicId: 302339
|
||||
dashedName: top-rank-per-group
|
||||
@ -8,9 +8,9 @@ dashedName: top-rank-per-group
|
||||
|
||||
# --description--
|
||||
|
||||
Find the top `n` ranked data in each group, where `n` is provided as a parameter. Name of the rank and the group are also provided as parameter.
|
||||
Encontre os melhores `n` dados classificados em cada grupo, onde `n` é fornecido como um parâmetro. O nome da classificação e o grupo também são fornecidos como parâmetro.
|
||||
|
||||
Given the following data:
|
||||
Considerando os dados a seguir:
|
||||
|
||||
```js
|
||||
testData1 = [
|
||||
@ -30,13 +30,13 @@ testData1 = [
|
||||
];
|
||||
```
|
||||
|
||||
One could rank top 10 employees in each department by calling:
|
||||
É possível classificar os 10 melhores funcionários em cada departamento chamando:
|
||||
|
||||
```js
|
||||
topRankPerGroup(10, testData1, 'dept', 'salary')
|
||||
```
|
||||
|
||||
Given the following data:
|
||||
Considerando os dados a seguir:
|
||||
|
||||
```js
|
||||
testData2 = [
|
||||
@ -48,15 +48,15 @@ testData2 = [
|
||||
];
|
||||
```
|
||||
|
||||
One could rank the top-rated movie in each genre by calling:
|
||||
É possível classificar o filme melhor classificado em cada gênero chamando:
|
||||
|
||||
```js
|
||||
topRankPerGroup(1, testData2, 'genre', 'rating')
|
||||
```
|
||||
|
||||
The function should return an array with an array for each group containing the top `n` objects.
|
||||
A função deve retornar um array com um array para cada grupo contendo os melhores objetos `n`.
|
||||
|
||||
For example, given data:
|
||||
Por exemplo, considerando os dados:
|
||||
|
||||
```js
|
||||
[
|
||||
@ -69,7 +69,7 @@ For example, given data:
|
||||
];
|
||||
```
|
||||
|
||||
Top two ranking employees in each department by salary would be:
|
||||
Os dois maiores funcionários classificados em cada departamento, por salário, são:
|
||||
|
||||
```js
|
||||
[ [ { name: 'Kim Arlich', id: 'E10001', salary: 57000, dept: 'D050' },
|
||||
@ -80,37 +80,37 @@ Top two ranking employees in each department by salary would be:
|
||||
|
||||
# --hints--
|
||||
|
||||
`topRankPerGroup` should be a function.
|
||||
`topRankPerGroup` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof topRankPerGroup === 'function');
|
||||
```
|
||||
|
||||
`topRankPerGroup` should return undefined on negative n values.
|
||||
`topRankPerGroup` deve retornar undefined para valores de n negativos.
|
||||
|
||||
```js
|
||||
assert(typeof topRankPerGroup(-1, []) === 'undefined');
|
||||
```
|
||||
|
||||
For `topRankPerGroup(10, testData1, 'dept', 'salary')`, the first result in the first group should be `{ name: 'John Rappl', id: 'E21437', salary: 47000, dept: 'D050'}`.
|
||||
Para `topRankPerGroup(10, testData1, 'dept', 'salary')`, o primeiro resultado no primeiro grupo deve ser `{ name: 'John Rappl', id: 'E21437', salary: 47000, dept: 'D050'}`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(res1[0][0], { name: 'John Rappl', id: 'E21437', salary: 47000, dept: 'D050'});
|
||||
```
|
||||
|
||||
For `topRankPerGroup(10, testData1, 'dept', 'salary')`, the last result in the last group should be `{ name: 'Adam Smith', id: 'E63535', salary: 18000, dept: 'D202' }`.
|
||||
Para `topRankPerGroup(10, testData1, 'dept', 'salary')`, o último resultado no último grupo deve ser `{ name: 'Adam Smith', id: 'E63535', salary: 18000, dept: 'D202' }`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(res1[3][3], { name: 'Adam Smith', id: 'E63535', salary: 18000, dept: 'D202' });
|
||||
```
|
||||
|
||||
`topRankPerGroup(1, ...)` should return only top ranking result per group.
|
||||
`topRankPerGroup(1, ...)` deve retornar apenas o maior resultado do ranking por grupo.
|
||||
|
||||
```js
|
||||
assert.equal(res2[2].length, 1);
|
||||
```
|
||||
|
||||
`topRankPerGroup(2, ...)` should return two ranking results per group.
|
||||
`topRankPerGroup(2, ...)` deve retornar dois resultados do ranking por grupo.
|
||||
|
||||
```js
|
||||
assert.equal(res3[2][1].name, 'Maze Runner');
|
||||
|
Reference in New Issue
Block a user