chore(i18n,curriculum): processed translations (#43390)
This commit is contained in:
@ -10,9 +10,9 @@ dashedName: build-a-25--5-clock
|
||||
|
||||
**Objetivo:** Construye una aplicación funcional [CodePen.io](https://codepen.io) similar a esta: <https://codepen.io/freeCodeCamp/full/XpKrrW>.
|
||||
|
||||
Completa las siguientes [historias de usuario](https://en.wikipedia.org/wiki/User_story) y consigue pasar todas las pruebas. Dale tu propio estilo personal.
|
||||
Completa las siguientes [historias de usuario](https://en.wikipedia.org/wiki/User_story) y consigue que pasen todas las pruebas. Dale tu propio estilo personal.
|
||||
|
||||
Puedes utilizar una combinación de HTML, JavaScript, CSS, Bootstrap, SASS, React, Redux y jQuery para completar este proyecto. Deberías utilizar un framework frontend (como React por ejemplo) porque esta sección trata sobre el aprendizaje de frameworks frontend. No se recomienda utilizar tecnologías adicionales a las indicadas anteriormente, su utilización corre bajo su propio riesgo. Estamos considerando apoyar otros frameworks frontend como Angular y Vue, pero actualmente no están soportados. Aceptaremos e intentaremos solucionar todos los informes de incidencias que utilicen el conjunto de tecnologías sugeridas para este proyecto. ¡Feliz programación!
|
||||
Puedes utilizar una combinación de HTML, JavaScript, CSS, Bootstrap, SASS, React, Redux y jQuery para completar este proyecto. Debes usar un framework frontend (como React por ejemplo), ya que esta sección trata sobre el aprendizaje de frameworks frontend. No se recomienda utilizar tecnologías adicionales que no estén enlistadas, su utilización corre bajo tu propio riesgo. Estamos buscando apoyar otros frameworks de frontend como Angular y Vue, pero actualmente no están soportados. Aceptaremos e intentaremos arreglar todos los informes de incidencias que utilicen el stack de tecnologías sugeridas para este proyecto. ¡Feliz día programando!
|
||||
|
||||
**Historia de usuario #1:** Puedo ver un elemento con `id="break-label"` que contiene una cadena (por ejemplo: "Break Length").
|
||||
|
||||
@ -46,25 +46,25 @@ Puedes utilizar una combinación de HTML, JavaScript, CSS, Bootstrap, SASS, Reac
|
||||
|
||||
**Historia de usuario #16:** No debo ser capaz de establecer una duración de la sesión o pausa <= 0.
|
||||
|
||||
**Historia de usuario #17:** No debería poder establecer una duración de la sesión o pausa > 60.
|
||||
**Historia de usuario #17:** No debo poder establecer una duración de la sesión o pausa > 60.
|
||||
|
||||
**Historia de usuario #18:** Cuando hago clic por primera vez en el elemento con el correspondiente `id="start_stop"`, el temporizador debe comenzar a correr desde el valor mostrado actualmente en `id="session-length"`, incluso si el valor se incrementó o se redujo respecto al valor original 25.
|
||||
|
||||
**Historia de usuario #19:** Si el temporizador se está ejecutando, el elemento con el id: `time-left` debería mostrar el tiempo restante en formato `mm:ss` (reduciendo 1 y actualizando el valor mostrado cada 1000ms).
|
||||
**Historia de usuario #19:** Si el temporizador se está ejecutando, el elemento con el id: `time-left` debe mostrar el tiempo restante en formato `mm:ss` (reduciendo 1 y actualizando el valor mostrado cada 1000ms).
|
||||
|
||||
**Historia de usuario #20:** Si el temporizador se está ejecutando y hago clic en el elemento `id="start_stop"`, la cuenta atrás debería pausarse.
|
||||
**Historia de usuario #20:** Si el temporizador se está ejecutando y hago clic en el elemento `id="start_stop"`, la cuenta atrás debe pausarse.
|
||||
|
||||
**Historia de usuario #21:** Si el temporizador está pausado y hago clic en el elemento `id="start_stop"`, la cuenta atrás debe reanudarse desde el punto en el que fue pausada.
|
||||
|
||||
**Historia de usuario #22:** Cuando la cuenta atrás de la sesión llega a cero (NOTA: temporizador DEBE llegar a 00:00) y una nueva cuenta atrás comienza, el elemento cuyo id es `timer-label` debería mostrar una cadena en la que se indica que el descanso (break) ha comenzado.
|
||||
**Historia de usuario #22:** Cuando la cuenta atrás de la sesión llega a cero (NOTA: el temporizador DEBE llegar a 00:00) y una nueva cuenta atrás comienza, el elemento cuyo id es `timer-label` debería mostrar una cadena en la que se indica que el descanso (break) ha comenzado.
|
||||
|
||||
**Historia de usuario #23:** Cuando la cuenta atrás de la sesión llega a cero (NOTA: temporizador DEBE llegar a 00:00), una nueva cuenta atrás comienza para el periodo de descanso (break) y se inicia desde el valor mostrado actualmente por el elemento `id="break-length"`.
|
||||
**Historia de usuario #23:** Cuando la cuenta atrás de la sesión llega a cero (NOTA: el temporizador DEBE llegar a 00:00), una nueva cuenta atrás comienza para el periodo de descanso (break) y se inicia desde el valor mostrado actualmente por el elemento `id="break-length"`.
|
||||
|
||||
**Historia de usuario #24:** Cuando la cuenta atrás en el periodo de descanso (break) llega a cero (NOTA: temporizador DEBE llegar a 00:00) y una nueva cuenta atrás debe comenzar, el elemento cuyo id es `timer-label` debe mostrar una cadena en la que se indica que la sesión ha comenzado.
|
||||
**Historia de usuario #24:** Cuando la cuenta atrás en el periodo de descanso (break) llega a cero (NOTA: el temporizador DEBE llegar a 00:00) y una nueva cuenta atrás debe comenzar, el elemento cuyo id es `timer-label` debe mostrar una cadena en la que se indica que la sesión ha comenzado.
|
||||
|
||||
**Historia de usuario #25:** Cuando la cuenta atrás en el periodo de descanso (break) llega a cero (NOTA: temporizador DEBE llegar a 00:00), una nueva cuenta atrás debe comenzar para la sesión, la cual se inicia desde el valor mostrado actualmente por el elemento `id="session-length"`.
|
||||
**Historia de usuario #25:** Cuando la cuenta atrás en el periodo de descanso (break) llega a cero (NOTA: el temporizador DEBE llegar a 00:00), una nueva cuenta atrás debe comenzar para la sesión, la cual se inicia desde el valor mostrado actualmente por el elemento `id="session-length"`.
|
||||
|
||||
**Historia de usuario #26:** Cuando una cuenta atrás llega a cero (NOTA: temporizador DEBE llegar a 00:00), debe reproducirse un sonido que indica que el tiempo se ha agotado. Se debe utilizar una etiqueta HTML5 `audio` y tener un `id="beep"`.
|
||||
**Historia de usuario #26:** Cuando una cuenta atrás llega a cero (NOTA: el temporizador DEBE llegar a 00:00), debe reproducirse un sonido que indica que el tiempo se ha agotado. Se debe utilizar una etiqueta HTML5 `audio` y tener un `id="beep"`.
|
||||
|
||||
**Historia de usuario #27:** El elemento de audio `id="beep"` debe ser de 1 segundo o mayor.
|
||||
|
||||
|
@ -8,27 +8,27 @@ dashedName: change-text-inside-an-element-using-jquery
|
||||
|
||||
# --description--
|
||||
|
||||
Usando jQuery, puedes cambiar el texto entre las etiquetas de inicio y fin de un elemento. Puedes incluso cambiar el código HTML.
|
||||
Con jQuery, puedes cambiar el texto entre las etiquetas de abertura y cierre de un elemento. Puedes incluso cambiar el código HTML.
|
||||
|
||||
jQuery tiene una función llamada `.html()` que te permite añadir etiquetas HTML y texto dentro de un elemento. Cualquier contenido anterior dentro del elemento será completamente reemplazado con el contenido que proporciones usando esta función.
|
||||
jQuery tiene una función llamada `.html()` que te permite agregar etiquetas HTML y texto dentro de un elemento. Cualquier contenido anterior dentro del elemento será completamente reemplazado con el contenido que proporciones usando esta función.
|
||||
|
||||
Así es como se reescribiría y enfatizaría el texto de nuestro título:
|
||||
Así es como reescribirías y enfatizarías el texto de nuestro título:
|
||||
|
||||
```js
|
||||
$("h3").html("<em>jQuery Playground</em>");
|
||||
```
|
||||
|
||||
jQuery también tiene una función similar llamada `.text()` que solo altera el texto sin añadir etiquetas. En otras palabras, esta función no evaluará las etiquetas HTML que se le pasen. En cambio, lo tomará como el texto con el que quieres reemplazar el contenido existente.
|
||||
jQuery también tiene una función similar llamada `.text()` que solamente altera el texto sin agregar etiquetas. En otras palabras, esta función no evaluará ninguna etiqueta HTML que le pasemos, pero en cambio, la tratará como el texto por el que quieres reemplazar el contenido existente.
|
||||
|
||||
Cambia el botón con id `target4`, enfatizando su texto.
|
||||
Cambia el botón con id `target4` enfatizando su texto.
|
||||
|
||||
[ Ve a nuestro artículo sobre <em>](https://www.freecodecamp.org/news/html-elements-explained-what-are-html-tags/#em-element) para aprender la diferencia entre `<i>` y `<em>` y sus usos.
|
||||
|
||||
Ten en cuenta que, aunque la etiqueta `<i>` se ha utilizado tradicionalmente para enfatizar texto, se ha adoptado su uso desde entonces como etiqueta para íconos. La etiqueta `<em>` es ahora ampliamente aceptada como la etiqueta de énfasis. Cualquiera de las dos servirá para este desafío.
|
||||
Ten en cuenta que mientras la etiqueta `<i>` tradicionalmente se usaba para enfatizar texto, fue adaptada para ser usada como etiqueta para iconos. La etiqueta `<em>` ahora es ampliamente aceptada como la etiqueta de énfasis. Cualquiera de las dos servirá para este desafío.
|
||||
|
||||
# --hints--
|
||||
|
||||
Debes enfatizar el texto en el botón `target4` añadiendo etiquetas HTML.
|
||||
Debes enfatizar el texto en tu botón `target4` añadiendo etiquetas HTML.
|
||||
|
||||
```js
|
||||
assert.isTrue(
|
||||
@ -36,7 +36,7 @@ assert.isTrue(
|
||||
);
|
||||
```
|
||||
|
||||
De lo contrario, el texto debe permanecer inalterado.
|
||||
De lo contrario, el texto no debe modificarse.
|
||||
|
||||
```js
|
||||
assert($('#target4') && $('#target4').text().trim() === '#target4');
|
||||
|
@ -11,7 +11,7 @@ dashedName: change-the-css-of-an-element-using-jquery
|
||||
|
||||
# --description--
|
||||
|
||||
Podemos cambiar también el CSS de un elemento HTML directamente con jQuery.
|
||||
También podemos cambiar el CSS de un elemento HTML utilizando directamente jQuery.
|
||||
|
||||
jQuery tiene una función llamada `.css()` que te permite cambiar el CSS de un elemento.
|
||||
|
||||
@ -21,9 +21,9 @@ Así es como cambiaríamos su color a azul:
|
||||
$("#target1").css("color", "blue");
|
||||
```
|
||||
|
||||
Esto es ligeramente diferente de una declaración CSS normal, porque la propiedad CSS y su valor están entre comillas y separados con coma en lugar de con dos puntos.
|
||||
Esto es ligeramente diferente a una declaración CSS normal, porque la propiedad CSS y su valor están entre comillas y separados con coma en lugar de con dos puntos.
|
||||
|
||||
Elimina tus selectores de jQuery, dejando `document ready function` vacía.
|
||||
Elimina tus selectores de jQuery, dejando `document ready function` vacío.
|
||||
|
||||
Selecciona `target1` y cambia su color a rojo.
|
||||
|
||||
@ -35,7 +35,7 @@ Tu elemento `target1` debe tener texto rojo.
|
||||
assert($('#target1').css('color') === 'rgb(255, 0, 0)');
|
||||
```
|
||||
|
||||
Debes usar solo jQuery para añadir estas clases al elemento.
|
||||
Solo debes usar jQuery para agregar estas clases al elemento.
|
||||
|
||||
```js
|
||||
assert(!code.match(/class.*animated/g));
|
||||
|
@ -12,31 +12,31 @@ Además de mover elementos, también puedes copiarlos de un lugar a otro.
|
||||
|
||||
jQuery tiene una función llamada `clone()` que hace una copia de un elemento.
|
||||
|
||||
Por ejemplo, si quisiéramos copìar `target2` de nuestro `left-well` a nuestro `right-well`, usaríamos:
|
||||
Por ejemplo, si quisiéramos copiar `target2` de nuestro `left-well` a nuestro `right-well`, usaríamos:
|
||||
|
||||
```js
|
||||
$("#target2").clone().appendTo("#right-well");
|
||||
```
|
||||
|
||||
¿Notaste que esto implica usar dos funciones jQuery juntas? Esto es llamado <dfn>function chaining</dfn> (encadenamiento de funciones) y es una forma conveniente de hacer cosas con jQuery.
|
||||
¿Notaste que esto implica pegar dos funciones jQuery juntas? Esto es llamado <dfn>function chaining</dfn> (encadenamiento de funciones) y es una forma conveniente de lograr cosas con jQuery.
|
||||
|
||||
Clona tu elemento `target5` y añadelo a tu `left-well`.
|
||||
Clona tu elemento `target5` y agrégalo a tu `left-well`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Tu elemento `target5` debe estar dentro de `right-well`.
|
||||
Tu elemento `target5` debe estar dentro de tu `right-well`.
|
||||
|
||||
```js
|
||||
assert($('#right-well').children('#target5').length > 0);
|
||||
```
|
||||
|
||||
Una copia de tu elemento `target5` también debe estar dentro de `left-well`.
|
||||
Una copia de tu elemento `target5` debe estar también dentro de `left-well`.
|
||||
|
||||
```js
|
||||
assert($('#left-well').children('#target5').length > 0);
|
||||
```
|
||||
|
||||
Sólo debes usar jQuery para mover estos elementos.
|
||||
Debes usar solamente jQuery para mover estos elementos.
|
||||
|
||||
```js
|
||||
assert(!code.match(/class.*animated/g));
|
||||
|
@ -13,7 +13,7 @@ dashedName: delete-your-jquery-functions
|
||||
|
||||
Estas animaciones fueron geniales al principio, pero ahora distraen un poco.
|
||||
|
||||
Elimina las tres funciones de jQuery dentro de tu `document ready function`, pero deja intacta tu función `document ready function` en sí.
|
||||
Elimina las tres funciones de jQuery que están dentro de tu `document ready function`, pero deja intacta tu función `document ready function` en sí.
|
||||
|
||||
# --hints--
|
||||
|
||||
|
@ -8,7 +8,7 @@ dashedName: disable-an-element-using-jquery
|
||||
|
||||
# --description--
|
||||
|
||||
También puedes cambiar las demás propiedades (además de las propiedades CSS) de los elementos HTML con jQuery. Por ejemplo, puedes deshabilitar botones.
|
||||
También puedes cambiar las propiedades que no son CSS de tus elementos HTML con jQuery. Por ejemplo, puedes desactivar botones.
|
||||
|
||||
Cuando deshabilitas un botón, se mostrará en gris y no se podrá hacer clic sobre este.
|
||||
|
||||
@ -24,7 +24,7 @@ Deshabilita solo el botón `target1`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Tu botón `target1` debe ser deshabilitado.
|
||||
Your `target1` button should be disabled.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -40,7 +40,7 @@ Ningún otro botón debe estar deshabilitado.
|
||||
assert($('#target2') && !$('#target2').prop('disabled'));
|
||||
```
|
||||
|
||||
Solo debes usar jQuery para añadir estas clases al elemento.
|
||||
Debes usar solo jQuery para agregar estas clases al elemento.
|
||||
|
||||
```js
|
||||
assert(!code.match(/disabled[^<]*>/g));
|
||||
|
@ -10,13 +10,13 @@ dashedName: learn-how-script-tags-and-document-ready-work
|
||||
|
||||
Ahora estamos listos para aprender jQuery, la herramienta de JavaScript más popular de todos los tiempos.
|
||||
|
||||
Antes de empezar a usar jQuery, necesitamos añadir algunas cosas a nuestro HTML.
|
||||
Antes de empezar a usar jQuery, necesitamos agregar algunas cosas a nuestro HTML.
|
||||
|
||||
Primero, añade un elemento `script` en la parte superior de tu página. Asegúrate de cerrarlo en la siguiente línea.
|
||||
Primero, agrega un elemento `script` en la parte superior de tu página. Asegúrate de cerrarlo en la siguiente línea.
|
||||
|
||||
Tu navegador ejecutará cualquier JavaScript dentro de un elemento `script`, incluyendo jQuery.
|
||||
|
||||
Dentro de tu elemento `script`, añade este código: `$(document).ready(function() {` a tu `script`. Luego ciérralo en la siguiente línea (todavía dentro de tu elemento `script`) con: `});`
|
||||
Dentro de tu elemento `script`, agrega este código: `$(document).ready(function() {` a tu `script`. Luego ciérralo en la siguiente línea (todavía dentro de tu elemento `script`) con: `});`
|
||||
|
||||
Aprenderemos más sobre `functions` más tarde. Lo importante a saber es que el código que pongas dentro de esta `function` (función) se ejecutará tan pronto como tu navegador haya cargado tu página.
|
||||
|
||||
@ -39,7 +39,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Debes añadir `$(document).ready(function() {` al principio de tu elemento `script`.
|
||||
Debes agregar `$(document).ready(function() {` al principio de tu elemento `script`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -24,7 +24,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Sólo debes utilizar jQuery para remover este elemento.
|
||||
Solo debes utilizar jQuery para remover este elemento.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -29,7 +29,7 @@ La clase `btn-default` debe ser eliminada de todos los elementos `button`.
|
||||
assert($('.btn-default').length === 0);
|
||||
```
|
||||
|
||||
Sólo debes usar jQuery para eliminar esta clase del elemento.
|
||||
Solo debes usar jQuery para eliminar esta clase del elemento.
|
||||
|
||||
```js
|
||||
assert(code.match(/btn btn-default/g));
|
||||
|
@ -17,13 +17,13 @@ Afortunadamente, jQuery tiene algunos otros trucos para apuntar a los elementos
|
||||
|
||||
jQuery usa selectores de CSS para apuntar elementos. El selector `target:nth-child(n)` de CSS, te permite seleccionar todos los enésimos elementos con el tipo de elemento o la clase apuntada.
|
||||
|
||||
Así es como le darías al tercer elemento en cada pozo la clase de rebote:
|
||||
Así es como le darías al tercer elemento en cada "well" la clase de rebote:
|
||||
|
||||
```js
|
||||
$(".target:nth-child(3)").addClass("animated bounce");
|
||||
```
|
||||
|
||||
Has que el segundo niño en cada uno de sus elementos de pozo rebote. Debes seleccionar los hijos de los elementos con la clase `target`.
|
||||
Haz que el segundo niño en cada uno de sus elementos de "well" rebote. Debes seleccionar los hijos de los elementos con la clase `target`.
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -48,7 +48,7 @@ Debes usar el selector `:nth-child()` para modificar estos elementos.
|
||||
assert(code.match(/\:nth-child\(/g));
|
||||
```
|
||||
|
||||
Solo debes usar jQuery para añadir estas clases al elemento.
|
||||
Solo debes usar jQuery para agregar estas clases al elemento.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -11,15 +11,15 @@ dashedName: target-elements-by-class-using-jquery
|
||||
|
||||
# --description--
|
||||
|
||||
¿Ves como hicimos que todos tus elementos `button` reboten? Los seleccionamos con `$("button")`, luego agregamos algo de clases CSS a ellos con `.addClass("animated bounce");`.
|
||||
¿Ves cómo hemos hecho que todos tus elementos `button` reboten? Los seleccionamos con `$("button")`, luego agregamos algo de clases CSS a ellos con `.addClass("animated bounce");`.
|
||||
|
||||
Acabas de usar la función `.addClass()` de jQuery, que te permite añadir clases a los elementos.
|
||||
Acabas de usar la función `.addClass()` de jQuery, que te permite agregar clases a los elementos.
|
||||
|
||||
Primero, apuntemos tus elementos `div` con la clase `well` usando el selector `$(".well")`.
|
||||
|
||||
Ten en cuenta que, al igual que con las declaraciones CSS, escribes un `.` antes del nombre de la clase.
|
||||
|
||||
Luego usa la función `.addClass()` de jQuery para añadir las clases `animated` y `shake`.
|
||||
Luego usa la función `.addClass()` de jQuery para agregar las clases `animated` y `shake`.
|
||||
|
||||
Por ejemplo, puedes hacer que todos los elementos con la clase `text-primary` se agiten agregando lo siguiente a tu función `document ready function`:
|
||||
|
||||
@ -35,7 +35,7 @@ Debes usar la función jQuery `addClass()` para dar las clases `animated` y `sha
|
||||
assert($('.well').hasClass('animated') && $('.well').hasClass('shake'));
|
||||
```
|
||||
|
||||
Solo debes usar jQuery para añadir estas clases al elemento.
|
||||
Debes usar solo jQuery para agregar estas clases al elemento.
|
||||
|
||||
```js
|
||||
assert(!code.match(/class\.\*animated/g));
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: bad87fee1348bd9aeda08826
|
||||
title: Apunta a elementos por clase usando jQuery
|
||||
title: Apunta a elementos por id usando jQuery
|
||||
challengeType: 6
|
||||
forumTopicId: 18317
|
||||
required:
|
||||
@ -17,7 +17,7 @@ Primero apunta a tu elemento `button` con el id `target3` usando el selector `$(
|
||||
|
||||
Ten en cuenta que, al igual que con las declaraciones CSS, escribes un `#` antes del nombre del id.
|
||||
|
||||
Luego usa la función `.addClass()` de jQuery para añadir las clases `animated` y `fadeOut`.
|
||||
Luego usa la función `.addClass()` de jQuery para agregar las clases `animated` y `fadeOut`.
|
||||
|
||||
Así es como harás que el elemento `button` con el id `target6` se desvanezca:
|
||||
|
||||
@ -42,7 +42,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Solo debes usar jQuery para agregar estas clases al elemento.
|
||||
Debes usar solo jQuery para agregar estas clases al elemento.
|
||||
|
||||
```js
|
||||
assert(!code.match(/class.*animated/g));
|
||||
|
@ -39,7 +39,7 @@ Debes usar el selector `:even` para modificar estos elementos.
|
||||
assert(code.match(/\:even/g));
|
||||
```
|
||||
|
||||
Solo debes usar jQuery para añadir estas clases al elemento.
|
||||
Solo debes usar jQuery para agregar estas clases al elemento.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -17,7 +17,7 @@ Ahora vamos a escribir nuestra primera declaración de jQuery. Todas las funcion
|
||||
|
||||
jQuery a menudo selecciona un elemento HTML con un <dfn>selector</dfn>, y luego le hace algo a ese elemento.
|
||||
|
||||
Por ejemplo, hagamos que todos tus elementos `button` reboten. Simplemente añade este código dentro de tu función de documento listo (document ready):
|
||||
Por ejemplo, hagamos que todos tus elementos `button` reboten. Simplemente agrega este código dentro de tu función document ready:
|
||||
|
||||
```js
|
||||
$("button").addClass("animated bounce");
|
||||
@ -33,13 +33,13 @@ Debes usar la función de jQuery `addClass()` para dar las clases `animated` y `
|
||||
assert($('button').hasClass('animated') && $('button').hasClass('bounce'));
|
||||
```
|
||||
|
||||
Solo debes usar jQuery para añadir estas clases al elemento.
|
||||
Solo debes usar jQuery para agregar estas clases al elemento.
|
||||
|
||||
```js
|
||||
assert(!code.match(/class.*animated/g));
|
||||
```
|
||||
|
||||
Tu código de jQuery debería estar dentro de la función `$(document).ready();`.
|
||||
Tu código de jQuery debe estar dentro de la función `$(document).ready();`.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -49,7 +49,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
Solo debes usar jQuery para añadir estas clases al elemento.
|
||||
Solo debes usar jQuery para agregar estas clases al elemento.
|
||||
|
||||
```js
|
||||
assert(code.match(/<div class="well" id="left-well">/g));
|
||||
|
@ -13,17 +13,17 @@ dashedName: target-the-same-element-with-multiple-jquery-selectors
|
||||
|
||||
Ahora conoces tres maneras de seleccionar elementos: por tipo: `$("button")`, por clase: `$(".btn")`, y por id `$("#target1")`.
|
||||
|
||||
Aunque es posible añadir múltiples clases en una sola llamada `.addClass()`, vamos a añadirlos al mismo elemento en *tres maneras diferentes*.
|
||||
Aunque es posible agregar múltiples clases en una sola llamada `.addClass()`, vamos a agregarlos al mismo elemento de *tres maneras diferentes*.
|
||||
|
||||
Usando `.addClass()`, añade solo una clase a la vez al mismo elemento, de tres maneras diferentes:
|
||||
Usando `.addClass()`, agrega solo una clase a la vez al mismo elemento, de tres maneras diferentes:
|
||||
|
||||
Añade la clase `animated` a todos los elementos con el tipo `button`.
|
||||
Agrega la clase `animated` a todos los elementos con el tipo `button`.
|
||||
|
||||
Añade la clase `shake` a todos los botones con la clase `.btn`.
|
||||
Agrega la clase `shake` a todos los botones con la clase `.btn`.
|
||||
|
||||
Añade la clase `btn-primary` al botón con id `#target1`.
|
||||
Agrega la clase `btn-primary` al botón con id `#target1`.
|
||||
|
||||
**Nota:** Solo debes apuntar a un elemento y añadir solo una clase a la vez. En total, tus tres selectores individuales terminarán agregando las tres clases `shake`, `animated`, y `btn-primary` a `#target1`.
|
||||
**Nota:** Solo debes apuntar a un elemento y agregar solo una clase a la vez. En total, tus tres selectores individuales terminarán agregando las tres clases `shake`, `animated`, y `btn-primary` a `#target1`.
|
||||
|
||||
# --hints--
|
||||
|
||||
@ -45,7 +45,7 @@ Tu código debe usar el selector `$("#target1")`.
|
||||
assert(code.match(/\$\s*?\(\s*?(?:'|")\s*?#target1\s*?(?:'|")/gi));
|
||||
```
|
||||
|
||||
Solo debes añadir una clase con cada uno de tus tres selectores.
|
||||
Solo debes agregar una clase con cada uno de tus tres selectores.
|
||||
|
||||
```js
|
||||
assert(
|
||||
|
@ -10,7 +10,7 @@ dashedName: use-appendto-to-move-elements-with-jquery
|
||||
|
||||
Ahora intentemos mover elementos de un `div` a otro.
|
||||
|
||||
jQuery tiene una función llamada `appendTo()` que te permite seleccionar elementos HTML y añadirlos a otro elemento.
|
||||
jQuery tiene una función llamada `appendTo()` que te permite seleccionar elementos HTML y agregarlos a otro elemento.
|
||||
|
||||
Por ejemplo, si quisiéramos mover `target4` desde nuestro "right well" a nuestro "left well", usaríamos:
|
||||
|
||||
@ -34,7 +34,7 @@ Tu elemento `target2` debe estar dentro de `right-well`.
|
||||
assert($('#right-well').children('#target2').length > 0);
|
||||
```
|
||||
|
||||
Sólo debes usar jQuery para mover estos elementos.
|
||||
Solo debes usar jQuery para mover estos elementos.
|
||||
|
||||
```js
|
||||
assert(!code.match(/class.*animated/g));
|
||||
|
@ -17,11 +17,11 @@ jQuery también puede seleccionar al elemento `body`.
|
||||
|
||||
Así es como haríamos que el cuerpo entero se desvaneciera: `$("body").addClass("animated fadeOut");`
|
||||
|
||||
Pero hagamos algo más dramático. Añade las clases `animated` y `hinge` a tu elemento `body`.
|
||||
Pero hagamos algo más dramático. Agrega las clases `animated` y `hinge` a tu elemento `body`.
|
||||
|
||||
# --hints--
|
||||
|
||||
Debes añadir las clases `animated` y `hinge` a tu elemento `body`.
|
||||
Debes agregar las clases `animated` y `hinge` a tu elemento `body`.
|
||||
|
||||
```js
|
||||
assert($('body').hasClass('animated') && $('body').hasClass('hinge'));
|
||||
|
@ -10,7 +10,7 @@ dashedName: create-reusable-css-with-mixins
|
||||
|
||||
En Sass, un <dfn>mixin</dfn> es un grupo de declaraciones de CSS que pueden reutilizarse a través de la hoja de estilo.
|
||||
|
||||
Las nuevas funciones de CSS tardan en ser adoptadas por completo y estar listas para su uso en todos los navegadores. A medida que se añaden funciones a los navegadores, las reglas CSS que las utilizan pueden necesitar prefijos de proveedor. Consideremos `box-shadow`:
|
||||
Las nuevas funciones de CSS tardan en ser adoptadas por completo y estar listas para su uso en todos los navegadores. A medida que se agregan funciones a los navegadores, las reglas CSS que las utilizan pueden necesitar prefijos de proveedor. Consideremos `box-shadow`:
|
||||
|
||||
```scss
|
||||
div {
|
||||
|
@ -16,7 +16,7 @@ El último desafío mostró cómo la directiva `@for` utiliza un valor inicial y
|
||||
}
|
||||
```
|
||||
|
||||
Un mapa tiene una sintaxis ligeramente diferente. Aquí hay un ejemplo:
|
||||
Un mapa tiene una sintaxis ligeramente diferente. He aquí un ejemplo:
|
||||
|
||||
```scss
|
||||
$colors: (color1: blue, color2: red, color3: green);
|
||||
|
@ -8,7 +8,7 @@ dashedName: use-for-to-create-a-sass-loop
|
||||
|
||||
# --description--
|
||||
|
||||
La directiva `@for` añade estilos en un bucle, muy similar a un bucle `for` en JavaScript.
|
||||
La directiva `@for` agrega estilos en un bucle, muy similar a un bucle `for` en JavaScript.
|
||||
|
||||
`@for` se utiliza de dos maneras: "de principio hasta el fin" o "de principio a fin". La principal diferencia es que el "de principio **a** fin" *excluye* el número final como parte de la cuenta, y "de principio **hasta** el fin" *incluye* el número final como parte de la cuenta.
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 587d7dbe367417b2b2512bb8
|
||||
title: Usa @if y @else para añadir lógica a tus estilos
|
||||
title: Usa @if y @else para agregar lógica a tus estilos
|
||||
challengeType: 0
|
||||
forumTopicId: 301463
|
||||
dashedName: use-if-and-else-to-add-logic-to-your-styles
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f40e1000cf542c50ff21
|
||||
title: 'Problem 162: Hexadecimal numbers'
|
||||
title: 'Problema 162: Números hexadecimais'
|
||||
challengeType: 5
|
||||
forumTopicId: 301796
|
||||
dashedName: problem-162-hexadecimal-numbers
|
||||
@ -8,28 +8,34 @@ dashedName: problem-162-hexadecimal-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
In the hexadecimal number system numbers are represented using 16 different digits:
|
||||
Os números do sistema de números hexadecimais são representados usando 16 dígitos diferentes:
|
||||
|
||||
0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
|
||||
$$0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F$$
|
||||
|
||||
The hexadecimal number AF when written in the decimal number system equals 10x16+15=175.
|
||||
O número hexadecimal AF quando escrito no sistema de números decimais é igual a $10 \times 16 + 15 = 175$.
|
||||
|
||||
In the 3-digit hexadecimal numbers 10A, 1A0, A10, and A01 the digits 0,1 and A are all present.
|
||||
Nos números hexadecimais de 3 dígitos 10A, 1A0, A10 e A01 os algarismos 0,1 e A estão todos presentes.
|
||||
|
||||
Like numbers written in base ten we write hexadecimal numbers without leading zeroes.
|
||||
Como números escritos na base dez, escrevemos números hexadecimais sem zeros à frente.
|
||||
|
||||
How many hexadecimal numbers containing at most sixteen hexadecimal digits exist with all of the digits 0,1, and A present at least once?
|
||||
Quantos números hexadecimais, contendo no máximo dezesseis dígitos hexadecimais, existem com os dígitos 0,1 e A presentes pelo menos uma vez?
|
||||
|
||||
Give your answer as a hexadecimal number.
|
||||
Dê sua resposta com um número hexadecimal como uma string.
|
||||
|
||||
(A,B,C,D,E and F in upper case, without any leading or trailing code that marks the number as hexadecimal and without leading zeroes , e.g. 1A3F and not: 1a3f and not 0x1a3f and not $1A3F and not #1A3F and not 0000001A3F)
|
||||
**Observação:** deixe A,B,C,D,E e F em maiúsculas, sem qualquer código anterior ou posterior que marque o número como hexadecimal e sem zeros à direita, por exemplo: 1A3F e não: 1a3f, 0x1a3f, $1A3F, #1A3F ou 0000001A3F.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler162()` should return 3D58725572C62302.
|
||||
`hexadecimalNumbers()` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler162(), '3D58725572C62302');
|
||||
assert(typeof hexadecimalNumbers() === 'string');
|
||||
```
|
||||
|
||||
`hexadecimalNumbers()` deve retornar a string `3D58725572C62302`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(hexadecimalNumbers(), '3D58725572C62302');
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -37,12 +43,12 @@ assert.strictEqual(euler162(), '3D58725572C62302');
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler162() {
|
||||
function hexadecimalNumbers() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler162();
|
||||
hexadecimalNumbers();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f4f91000cf542c51000c
|
||||
title: 'Problem 397: Triangle on parabola'
|
||||
title: 'Problema 397: Triângulo na parábola'
|
||||
challengeType: 5
|
||||
forumTopicId: 302062
|
||||
dashedName: problem-397-triangle-on-parabola
|
||||
@ -8,18 +8,20 @@ dashedName: problem-397-triangle-on-parabola
|
||||
|
||||
# --description--
|
||||
|
||||
On the parabola y = x2/k, three points A(a, a2/k), B(b, b2/k) and C(c, c2/k) are chosen.
|
||||
Na parábola $y = \frac{x^2}{k}$, três pontos $A(a, \frac{a^2}{k})$, $B(b, \frac{b^2}{k})$ e $C(c, \frac{c^2}{k})$ são escolhidos.
|
||||
|
||||
Let F(K, X) be the number of the integer quadruplets (k, a, b, c) such that at least one angle of the triangle ABC is 45-degree, with 1 ≤ k ≤ K and -X ≤ a < b < c ≤ X.
|
||||
Considere que $F(K, X)$ é o número de quadras de inteiros $(k, a, b, c)$, de tal forma que pelo menos um ângulo do triângulo $ABC$ é 45°, com $1 ≤ k ≤ K$ e $-X ≤ a < b < c ≤ X$.
|
||||
|
||||
For example, F(1, 10) = 41 and F(10, 100) = 12492. Find F(106, 109).
|
||||
Por exemplo, $F(1, 10) = 41$ e $F(10, 100) = 12\\,492$.
|
||||
|
||||
Encontre $F({10}^6, {10}^9)$.
|
||||
|
||||
# --hints--
|
||||
|
||||
`euler397()` should return 141630459461893730.
|
||||
`triangleOnParabola()` deve retornar `141630459461893730`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(euler397(), 141630459461893730);
|
||||
assert.strictEqual(triangleOnParabola(), 141630459461893730);
|
||||
```
|
||||
|
||||
# --seed--
|
||||
@ -27,12 +29,12 @@ assert.strictEqual(euler397(), 141630459461893730);
|
||||
## --seed-contents--
|
||||
|
||||
```js
|
||||
function euler397() {
|
||||
function triangleOnParabola() {
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
euler397();
|
||||
triangleOnParabola();
|
||||
```
|
||||
|
||||
# --solutions--
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5900f3cc1000cf542c50fedf
|
||||
title: 'Problem 96: Su Doku'
|
||||
title: 'Problema 96: Sudoku'
|
||||
challengeType: 5
|
||||
forumTopicId: 302213
|
||||
dashedName: problem-96-su-doku
|
||||
@ -8,7 +8,7 @@ dashedName: problem-96-su-doku
|
||||
|
||||
# --description--
|
||||
|
||||
Su Doku (Japanese meaning *number place*) is the name given to a popular puzzle concept. Its origin is unclear, but credit must be attributed to Leonhard Euler who invented a similar, and much more difficult, puzzle idea called Latin Squares. The objective of Su Doku puzzles, however, is to replace the blanks (or zeros) in a 9 by 9 grid in such that each row, column, and 3 by 3 box contains each of the digits 1 to 9. Below is an example of a typical starting puzzle grid and its solution grid.
|
||||
Sudoku (do japonês, *lugar do número*) é o nome dado a um conceito de desafio popular. A sua origem não é clara, mas o mérito deve ser atribuído a Leonhard Euler, que inventou uma ideia de quebra-cabeça semelhante e muito mais difícil, chamada de Quadrados Latinos. No entanto, o objetivo dos quebra-cabeças de sudoku é substituir as lacunas (ou zeros) em um tabuleiro de 9 por 9, de tal forma que cada linha, coluna e caixa de 3 por 3 contenha cada um dos dígitos de 1 a 9. Abaixo, vemos um exemplo típico de tabuleiro inicial e o tabuleiro solucionado.
|
||||
|
||||
<div style="margin: auto; background-color: white; padding: 10px; width: 80%; text-align: center;">
|
||||
<table border="0" cellpadding="0" cellspacing="0" align="center">
|
||||
@ -100,27 +100,27 @@ Su Doku (Japanese meaning *number place*) is the name given to a popular puzzle
|
||||
</table>
|
||||
</div>
|
||||
|
||||
A well constructed Su Doku puzzle has a unique solution and can be solved by logic, although it may be necessary to employ "guess and test" methods in order to eliminate options (there is much contested opinion over this). The complexity of the search determines the difficulty of the puzzle; the example above is considered easy because it can be solved by straight forward direct deduction.
|
||||
Um quebra-cabeças de sudoku bem construído tem uma solução única e pode ser resolvida por lógica, embora possa ser necessário utilizar métodos de "adivinhação e teste" a fim de eliminar opções (há opiniões bastante contestadas a esse respeito). A complexidade da busca determina a dificuldade do quebra-cabeça. O exemplo acima é considerado fácil, pois pode ser resolvido através de dedução direta.
|
||||
|
||||
The `puzzlesArr` array contains different Su Doku puzzle strings ranging in difficulty, but all with unique solutions.
|
||||
O array `puzzlesArr` contém cadeias de quebra-cabeças de sudoku de várias dificuldades, mas com soluções únicas.
|
||||
|
||||
By solving all puzzles in `puzzlesArr`, find the sum of the 3-digit numbers found in the top left corner of each solution grid; for example, 483 is the 3-digit number found in the top left corner of the solution grid above.
|
||||
Resolvendo todos os quebra-cabeças de `puzzlesArr`, encontre a soma dos números de 3 algarismos encontrados no canto superior esquerdo de cada tabuleiro solucionado. Por exemplo, 483 é o número de 3 dígitos encontrado no canto superior esquerdo do tabuleiro solucionado acima.
|
||||
|
||||
# --hints--
|
||||
|
||||
`suDoku(testPuzzles1)` should return a number.
|
||||
`suDoku(testPuzzles1)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof suDoku(_testPuzzles1) === 'number');
|
||||
```
|
||||
|
||||
`suDoku(testPuzzles1)` should return `1190`.
|
||||
`suDoku(testPuzzles1)` deve retornar `1190`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(suDoku(_testPuzzles1), 1190);
|
||||
```
|
||||
|
||||
`suDoku(testPuzzles2)` should return `24702`.
|
||||
`suDoku(testPuzzles2)` deve retornar `24702`.
|
||||
|
||||
```js
|
||||
assert.strictEqual(suDoku(_testPuzzles2), 24702);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5eb3e4af7d0e7b760b46cedc
|
||||
title: Set consolidation
|
||||
title: Definir consolidação
|
||||
challengeType: 5
|
||||
forumTopicId: 385319
|
||||
dashedName: set-consolidation
|
||||
@ -8,58 +8,58 @@ dashedName: set-consolidation
|
||||
|
||||
# --description--
|
||||
|
||||
Given two sets of items then if any item is common to any set then the result of applying *consolidation* to those sets is a set of sets whose contents is:
|
||||
Dados dois conjuntos de itens, se qualquer item for comum a qualquer dos conjuntos, o resultado de aplicar a *consolidação* àqueles conjuntos é um conjunto de conjuntos, cujo conteúdo é:
|
||||
|
||||
<ul>
|
||||
<li>The two input sets if no common item exists between the two input sets of items.</li>
|
||||
<li>The single set that is the union of the two input sets if they share a common item.</li>
|
||||
<li>Os dois conjuntos de entrada, se não existir nenhum item comum entre os dois conjuntos de itens de entrada.</li>
|
||||
<li>O conjunto único que é a união dos dois conjuntos de entrada define se partilham um item em comum.</li>
|
||||
</ul>
|
||||
|
||||
Given N sets of items where N > 2 then the result is the same as repeatedly replacing all combinations of two sets by their consolidation until no further consolidation between set pairs is possible. If N < 2 then consolidation has no strict meaning and the input can be returned.
|
||||
Dados N conjuntos de itens em que N > 2, o resultado é o mesmo que substituir repetidamente todas as combinações de dois conjuntos por sua consolidação até que nenhuma consolidação adicional entre os pares de conjuntos seja possível. Se N < 2, a consolidação não terá nenhum significado estrito e a entrada pode ser retornada.
|
||||
|
||||
Here are some examples:
|
||||
Aqui estão alguns exemplos:
|
||||
|
||||
**Example 1:**
|
||||
**Exemplo 1:**
|
||||
|
||||
Given the two sets `{A,B}` and `{C,D}` then there is no common element between the sets and the result is the same as the input.
|
||||
Dados os dois conjuntos `{A,B}` e `{C,D}`, não há elemento comum entre os conjuntos e o resultado é o mesmo que a entrada.
|
||||
|
||||
**Example 2:**
|
||||
**Exemplo 2:**
|
||||
|
||||
Given the two sets `{A,B}` and `{B,D}` then there is a common element `B` between the sets and the result is the single set `{B,D,A}`. (Note that order of items in a set is immaterial: `{A,B,D}` is the same as `{B,D,A}` and `{D,A,B}`, etc).
|
||||
Dados os dois conjuntos `{A,B}` e `{B,D}`, há um elemento comum `B` entre os conjuntos. O resultado é um conjunto único `{B,D,A}`. (Observe que a ordem dos itens em um conjunto não tem importância: `{A,B,D}` é o mesmo que `{B,D,A}`, `{D,A,B}` e assim por diante).
|
||||
|
||||
**Example 3:**
|
||||
**Exemplo 3:**
|
||||
|
||||
Given the three sets `{A,B}` and `{C,D}` and `{D,B}` then there is no common element between the sets `{A,B}` and `{C,D}` but the sets `{A,B}` and `{D,B}` do share a common element that consolidates to produce the result `{B,D,A}`. On examining this result with the remaining set, `{C,D}`, they share a common element and so consolidate to the final output of the single set `{A,B,C,D}`
|
||||
Dados os três conjuntos `{A,B}`, `{C,D}` e `{D,B}` não há elemento comum entre os conjuntos `{A,B}` e `{C,D}`, mas os conjuntos `{A,B}` e `{D,B}` compartilham um elemento comum que é consolidado, produzindo o resultado `{B,D,A}`. Ao analisar este resultado com o conjunto restante, `{C,D}`, eles compartilham um elemento comum e assim são consolidados na saída final do conjunto único `{A,B,C,D}`
|
||||
|
||||
**Example 4:**
|
||||
**Exemplo 4:**
|
||||
|
||||
The consolidation of the five sets:
|
||||
A consolidação dos cinco conjuntos:
|
||||
|
||||
`{H,I,K}`, `{A,B}`, `{C,D}`, `{D,B}`, and `{F,G,H}`
|
||||
`{H,I,K}`, `{A,B}`, `{C,D}`, `{D,B}` e `{F,G,H}`
|
||||
|
||||
Is the two sets:
|
||||
São os dois conjuntos:
|
||||
|
||||
`{A, C, B, D}`, and `{G, F, I, H, K}`
|
||||
`{A, C, B, D}` e `{G, F, I, H, K}`
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes an array of strings as a parameter. Each string is represents a set with the characters representing the set elements. The function should return a 2D array containing the consolidated sets. Note: Each set should be sorted.
|
||||
Escreva uma função que receba um array de strings como parâmetro. Cada string representa um conjunto com os caracteres que representam os elementos do conjunto. A função deve retornar um array 2D contendo os conjuntos consolidados. Observação: cada conjunto deve ser ordenado.
|
||||
|
||||
# --hints--
|
||||
|
||||
`setConsolidation` should be a function.
|
||||
`setConsolidation` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof setConsolidation === 'function');
|
||||
```
|
||||
|
||||
`setConsolidation(["AB", "CD"])` should return a array.
|
||||
`setConsolidation(["AB", "CD"])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(setConsolidation(['AB', 'CD'])));
|
||||
```
|
||||
|
||||
`setConsolidation(["AB", "CD"])` should return `[["C", "D"], ["A", "B"]]`.
|
||||
`setConsolidation(["AB", "CD"])` deve retornar `[["C", "D"], ["A", "B"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(setConsolidation(['AB', 'CD']), [
|
||||
@ -68,19 +68,19 @@ assert.deepEqual(setConsolidation(['AB', 'CD']), [
|
||||
]);
|
||||
```
|
||||
|
||||
`setConsolidation(["AB", "BD"])` should return `[["A", "B", "D"]]`.
|
||||
`setConsolidation(["AB", "BD"])` deve retornar `[["A", "B", "D"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(setConsolidation(['AB', 'BD']), [['A', 'B', 'D']]);
|
||||
```
|
||||
|
||||
`setConsolidation(["AB", "CD", "DB"])` should return `[["A", "B", "C", "D"]]`.
|
||||
`setConsolidation(["AB", "CD", "DB"])` deve retornar `[["A", "B", "C", "D"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(setConsolidation(['AB', 'CD', 'DB']), [['A', 'B', 'C', 'D']]);
|
||||
```
|
||||
|
||||
`setConsolidation(["HIK", "AB", "CD", "DB", "FGH"])` should return `[["F", "G", "H", "I", "K"], ["A", "B", "C", "D"]]`.
|
||||
`setConsolidation(["HIK", "AB", "CD", "DB", "FGH"])` deve retornar `[["F", "G", "H", "I", "K"], ["A", "B", "C", "D"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(setConsolidation(['HIK', 'AB', 'CD', 'DB', 'FGH']), [
|
||||
|
@ -8,59 +8,59 @@ dashedName: sha-1
|
||||
|
||||
# --description--
|
||||
|
||||
**SHA-1** or **SHA1** is a one-way hash function; it computes a 160-bit message digest.
|
||||
**SHA-1** ou **SHA1** é uma função hash de mão única; ela calcula um message digest de 160-bit.
|
||||
|
||||
SHA-1 often appears in security protocols; for example, many HTTPS websites use RSA with SHA-1 to secure their connections.
|
||||
O SHA-1 aparece frequentemente em protocolos de segurança; por exemplo, muitos sites HTTPS usam RSA com SHA-1 para proteger suas conexões.
|
||||
|
||||
BitTorrent uses SHA-1 to verify downloads.
|
||||
O BitTorrent usa SHA-1 para verificar downloads.
|
||||
|
||||
Git and Mercurial use SHA-1 digests to identify commits.
|
||||
O Git e o Mercurial usam SHA-1 digests para identificar commits.
|
||||
|
||||
A US government standard, [FIPS 180-1](https://rosettacode.org/wiki/SHA-1/FIPS-180-1), defines SHA-1.
|
||||
Um padrão do governo dos EUA, [FIPS 180-1](https://rosettacode.org/wiki/SHA-1/FIPS-180-1), define o SHA-1.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that returns the SHA-1 message digest for a given string.
|
||||
Escreva uma função que retorne o SHA-1 message digest para uma determinada string.
|
||||
|
||||
# --hints--
|
||||
|
||||
`SHA1` should be a function.
|
||||
`SHA1` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof SHA1 === 'function');
|
||||
```
|
||||
|
||||
`SHA1("abc")` should return a string.
|
||||
`SHA1("abc")` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(typeof SHA1('abc') === 'string');
|
||||
```
|
||||
|
||||
`SHA1("abc")` should return `"a9993e364706816aba3e25717850c26c9cd0d89d"`.
|
||||
`SHA1("abc")` deve retornar `"a9993e364706816aba3e25717850c26c9cd0d89d"`.
|
||||
|
||||
```js
|
||||
assert.equal(SHA1('abc'), 'a9993e364706816aba3e25717850c26c9cd0d89d');
|
||||
```
|
||||
|
||||
`SHA1("Rosetta Code")` should return `"48c98f7e5a6e736d790ab740dfc3f51a61abe2b5"`.
|
||||
`SHA1("Rosetta Code")` deve retornar `"48c98f7e5a6e736d790ab740dfc3f51a61abe2b5"`.
|
||||
|
||||
```js
|
||||
assert.equal(SHA1('Rosetta Code'), '48c98f7e5a6e736d790ab740dfc3f51a61abe2b5');
|
||||
```
|
||||
|
||||
`SHA1("Hello world")` should return `"7b502c3a1f48c8609ae212cdfb639dee39673f5e"`.
|
||||
`SHA1("Hello world")` deve retornar `"7b502c3a1f48c8609ae212cdfb639dee39673f5e"`.
|
||||
|
||||
```js
|
||||
assert.equal(SHA1('Hello world'), '7b502c3a1f48c8609ae212cdfb639dee39673f5e');
|
||||
```
|
||||
|
||||
`SHA1("Programming")` should return `"d1a946bf8b2f2a7292c250063ee28989d742cd4b"`.
|
||||
`SHA1("Programming")` deve retornar `"d1a946bf8b2f2a7292c250063ee28989d742cd4b"`.
|
||||
|
||||
```js
|
||||
assert.equal(SHA1('Programming'), 'd1a946bf8b2f2a7292c250063ee28989d742cd4b');
|
||||
```
|
||||
|
||||
`SHA1("is Awesome")` should return `"6537205da59c72b57ed3881843c2d24103d683a3"`.
|
||||
`SHA1("is Awesome")` deve retornar `"6537205da59c72b57ed3881843c2d24103d683a3"`.
|
||||
|
||||
```js
|
||||
assert.equal(SHA1('is Awesome'), '6537205da59c72b57ed3881843c2d24103d683a3');
|
||||
|
@ -8,27 +8,27 @@ dashedName: sha-256
|
||||
|
||||
# --description--
|
||||
|
||||
The `SHA-2` family is a stronger alternative to `SHA-1`. The main difference between them is the length of the hash. Meaning `SHA-1` provides a shorter code with fewer possibilities for unique combinations. `SHA-2` or `SHA-256` creates a longer and thus more complex hash with more possibilities.
|
||||
A família `SHA-2` é uma alternativa mais forte a `SHA-1`. A principal diferença entre elas é o comprimento do hash. Significa que a `SHA-1` fornece um código mais curto com menos possibilidades para combinações únicas. `SHA-2` ou `SHA-256` cria um hash mais longo e, portanto, mais complexo com mais possibilidades.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Research implemenation details and write a function that takes a string as the parameter and returns a hash using `SHA-256`
|
||||
Pesquise os detalhes de implementação e escreva uma função que receba uma string como parâmetro e retorna um hash usando `SHA-256`
|
||||
|
||||
# --hints--
|
||||
|
||||
`SHA256` should be a function.
|
||||
`SHA256` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof SHA256 === 'function');
|
||||
```
|
||||
|
||||
`SHA256("Rosetta code")` should return a string.
|
||||
`SHA256("Rosetta code")` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(typeof SHA256('Rosetta code') === 'string');
|
||||
```
|
||||
|
||||
`SHA256("Rosetta code")` should return `"764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"`.
|
||||
`SHA256("Rosetta code")` deve retornar `"764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -37,7 +37,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`SHA256("SHA-256 Hash")` should return `"bee8c0cabdcf8c7835f40217dd35a8b0dba9134520e633f1c57285f35ca7ee3e"`.
|
||||
`SHA256("SHA-256 Hash")` deve retornar `"bee8c0cabdcf8c7835f40217dd35a8b0dba9134520e633f1c57285f35ca7ee3e"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -46,7 +46,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`SHA256("implementation")` should return `"da31012c40330e7e21538e7dd57503b16e8a0839159e96137090cccc9910b171"`.
|
||||
`SHA256("implementation")` deve retornar `"da31012c40330e7e21538e7dd57503b16e8a0839159e96137090cccc9910b171"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -55,7 +55,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`SHA256("algorithm")` should return `"b1eb2ec8ac9f31ff7918231e67f96e6deda83a9ff33ed2c67443f1df81e5ed14"`.
|
||||
`SHA256("algorithm")` deve retornar `"b1eb2ec8ac9f31ff7918231e67f96e6deda83a9ff33ed2c67443f1df81e5ed14"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -64,7 +64,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`SHA256("language")` should return `"a4ef304ba42a200bafd78b046e0869af9183f6eee5524aead5dcb3a5ab5f8f3f"`.
|
||||
`SHA256("language")` deve retornar `"a4ef304ba42a200bafd78b046e0869af9183f6eee5524aead5dcb3a5ab5f8f3f"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc7ffe
|
||||
title: Sort an array of composite structures
|
||||
title: Ordenar um array de estruturas compostas
|
||||
challengeType: 5
|
||||
forumTopicId: 302306
|
||||
dashedName: sort-an-array-of-composite-structures
|
||||
@ -8,17 +8,17 @@ dashedName: sort-an-array-of-composite-structures
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function that takes an array of objects as a parameter. The function should sort the array according to the 'key' attribute of the objects and return the sorted array.
|
||||
Escreva uma função que receba um array de objetos como parâmetro. A função deve ordenar o array de acordo com o atributo 'key' dos objetos e retornar o array ordenado.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sortByKey` should be a function.
|
||||
`sortByKey` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof sortByKey == 'function');
|
||||
```
|
||||
|
||||
`sortByKey([{key: 3, value: "foo"}, {key: 2, value: "bar"}, {key: 4, value: "baz"}, {key: 1, value: 42}, {key: 5, value: "another string"}])` should return an array.
|
||||
`sortByKey([{key: 3, value: "foo"}, {key: 2, value: "bar"}, {key: 4, value: "baz"}, {key: 1, value: 42}, {key: 5, value: "another string"}])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -34,7 +34,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`sortByKey([{key: 3, value: "foo"}, {key: 2, value: "bar"}, {key: 4, value: "baz"}, {key: 1, value: 42}, {key: 5, value: "another string"}])` should return `[{key: 1, value: 42}, {key: 2, value: "bar"}, {key: 3, value: "foo"}, {key: 4, value: "baz"}, {key: 5, value: "another string"}]`.
|
||||
`sortByKey([{key: 3, value: "foo"}, {key: 2, value: "bar"}, {key: 4, value: "baz"}, {key: 1, value: 42}, {key: 5, value: "another string"}])` deve retornar `[{key: 1, value: 42}, {key: 2, value: "bar"}, {key: 3, value: "foo"}, {key: 4, value: "baz"}, {key: 5, value: "another string"}]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -55,7 +55,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`sortByKey([{key: 3, name: "Joe"}, {key: 4, name: "Bill"}, {key: 20, name: "Alice"}, {key: 5, name: "Harry"}])` should return `[{key: 3, name: "Joe"}, {key: 4, name: "Bill"}, {key: 5, name: "Harry"}, {key: 20, name: "Alice"}]`.
|
||||
`sortByKey([{key: 3, name: "Joe"}, {key: 4, name: "Bill"}, {key: 20, name: "Alice"}, {key: 5, name: "Harry"}])` deve retornar `[{key: 3, name: "Joe"}, {key: 4, name: "Bill"}, {key: 5, name: "Harry"}, {key: 20, name: "Alice"}]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -74,7 +74,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`sortByKey([{key: 2341, name: "Adam"}, {key: 122, name: "Bernie"}, {key: 19, name: "David"}, {key: 5531, name: "Joe"}, {key: 1234, name: "Walter"}])` should return `[{key: 19, name: "David"}, {key: 122, name: "Bernie"}, {key: 1234, name: "Walter"}, {key: 2341, name: "Adam"}, {key: 5531, name: "Joe"}]`.
|
||||
`sortByKey([{key: 2341, name: "Adam"}, {key: 122, name: "Bernie"}, {key: 19, name: "David"}, {key: 5531, name: "Joe"}, {key: 1234, name: "Walter"}])` deve retornar `[{key: 19, name: "David"}, {key: 122, name: "Bernie"}, {key: 1234, name: "Walter"}, {key: 2341, name: "Adam"}, {key: 5531, name: "Joe"}]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8000
|
||||
title: Sort disjoint sublist
|
||||
title: Ordenar sublista desarticulada
|
||||
challengeType: 5
|
||||
forumTopicId: 302307
|
||||
dashedName: sort-disjoint-sublist
|
||||
@ -8,9 +8,9 @@ dashedName: sort-disjoint-sublist
|
||||
|
||||
# --description--
|
||||
|
||||
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, but preserving the values at indices outside the set of those to be sorted.
|
||||
Dada uma lista de valores e um conjunto de índices inteiros nessa lista de valores a tarefa é ordenar os valores nos índices indicados, mas preservando os valores nos índices exteriores ao conjunto dos que devem ser ordenados.
|
||||
|
||||
Make your function work with the following list of values and set of indices:
|
||||
Faça a função funcionar com a seguinte lista de valores e conjunto de índices:
|
||||
|
||||
<code>values: [7, <b>6</b>, 5, 4, 3, 2, <b>1</b>, <b>0</b>]</code>
|
||||
|
||||
@ -18,25 +18,25 @@ Make your function work with the following list of values and set of indices:
|
||||
indices(0-based): {6, 1, 7}
|
||||
```
|
||||
|
||||
Where the correct result would be:
|
||||
Onde o resultado correto seria:
|
||||
|
||||
<code>[7, <b>0</b>, 5, 4, 3, 2, <b>1</b>, <b>6</b>]</code>.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sortDisjoint` should be a function.
|
||||
`sortDisjoint` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof sortDisjoint == 'function');
|
||||
```
|
||||
|
||||
`sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7])` should return an array.
|
||||
`sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7])));
|
||||
```
|
||||
|
||||
`sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7])` should return `[7, 0, 5, 4, 3, 2, 1, 6]`.
|
||||
`sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7])` deve retornar `[7, 0, 5, 4, 3, 2, 1, 6]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7]), [
|
||||
@ -51,7 +51,7 @@ assert.deepEqual(sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [6, 1, 7]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [1, 2, 5, 6])` should return `[7, 1, 2, 4, 3, 5, 6, 0]`.
|
||||
`sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [1, 2, 5, 6])` deve retornar `[7, 1, 2, 4, 3, 5, 6, 0]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [1, 2, 5, 6]), [
|
||||
@ -66,7 +66,7 @@ assert.deepEqual(sortDisjoint([7, 6, 5, 4, 3, 2, 1, 0], [1, 2, 5, 6]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [6, 1, 7])` should return `[8, 1, 6, 5, 4, 3, 2, 7]`.
|
||||
`sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [6, 1, 7])` deve retornar `[8, 1, 6, 5, 4, 3, 2, 7]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [6, 1, 7]), [
|
||||
@ -81,7 +81,7 @@ assert.deepEqual(sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [6, 1, 7]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [1, 3, 5, 6])` should return `[8, 2, 6, 3, 4, 5, 7, 1]`.
|
||||
`sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [1, 3, 5, 6])` deve retornar `[8, 2, 6, 3, 4, 5, 7, 1]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [1, 3, 5, 6]), [
|
||||
@ -96,7 +96,7 @@ assert.deepEqual(sortDisjoint([8, 7, 6, 5, 4, 3, 2, 1], [1, 3, 5, 6]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`sortDisjoint([6, 1, 7, 1, 3, 5, 6], [6, 1, 5, 4])` should return `[6, 1, 7, 1, 3, 5, 6]`.
|
||||
`sortDisjoint([6, 1, 7, 1, 3, 5, 6], [6, 1, 5, 4])` deve retornar `[6, 1, 7, 1, 3, 5, 6]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sortDisjoint([6, 1, 7, 1, 3, 5, 6], [6, 1, 5, 4]), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8014
|
||||
title: Sort stability
|
||||
title: Estabilidade de ordenação
|
||||
challengeType: 5
|
||||
forumTopicId: 302308
|
||||
dashedName: sort-stability
|
||||
@ -8,9 +8,9 @@ dashedName: sort-stability
|
||||
|
||||
# --description--
|
||||
|
||||
When sorting records in a table by a particular column or field, a [stable sort](https://en.wikipedia.org/wiki/Stable_sort#Stability) will always retain the relative order of records that have the same key.
|
||||
Ao ordenar registros em uma tabela por uma coluna ou campo específico, uma [ordenação estável](https://en.wikipedia.org/wiki/Stable_sort#Stability) sempre manterá a ordem relativa dos registros que têm a mesma chave.
|
||||
|
||||
For example, in this table of countries and cities, a stable sort on the **second** column, the cities, would keep the US Birmingham above the UK Birmingham. (Although an unstable sort *might*, in this case, place the US Birmingham above the UK Birmingham, a stable sort routine would *guarantee* it).
|
||||
Por exemplo, nesta tabela de países e cidades, uma organização estável na **segunda** coluna, a das cidades, manteria US Birmingham acima de UK Birmingham. (Embora uma ordenação instável *possa*, neste caso, colocar US Birmingham acima de UK Birmingham, uma ordenação estável *garantiria* que isso ocorresse).
|
||||
|
||||
<pre>UK London
|
||||
US New York
|
||||
@ -18,21 +18,21 @@ US Birmingham
|
||||
UK Birmingham
|
||||
</pre>
|
||||
|
||||
Similarly, stable sorting on just the first column would generate "UK London" as the first item and "US Birmingham" as the last item (since the order of the elements having the same first word – "UK" or "US" – would be maintained).
|
||||
Da mesma forma, uma ordenação estável na primeira coluna geraria "UK London" como o primeiro item e "US Birmingham" como o último (já que a ordem dos elementos que têm a mesma palavra – "UK" ou "US" – seria mantida).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes a 2D array as a parameter. Each element has 2 elements similar to the above example. The function should sort the array as mentioned previously and return the sorted array.
|
||||
Escreva uma função que receba um array bidimensional como parâmetro. Cada elemento tem 2 elementos semelhantes ao exemplo acima. A função deve ordenar o array conforme mencionado anteriormente e retornar o array ordenado.
|
||||
|
||||
# --hints--
|
||||
|
||||
`stableSort` should be a function.
|
||||
`stableSort` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof stableSort == 'function');
|
||||
```
|
||||
|
||||
`stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]])` should return an array.
|
||||
`stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -47,7 +47,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]])` should return `[["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]`.
|
||||
`stableSort([["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]])` deve retornar `[["US", "Birmingham"], ["UK", "Birmingham"], ["UK", "London"], ["US", "New York"]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -66,7 +66,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`stableSort([[2, 2], [1, 2], [1, 4], [1, 5]])` should return `[[2, 2], [1, 2], [1, 4], [1, 5]]`.
|
||||
`stableSort([[2, 2], [1, 2], [1, 4], [1, 5]])` deve retornar `[[2, 2], [1, 2], [1, 4], [1, 5]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -85,7 +85,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`stableSort([[11, 55], [12, 45], [11, 45], [32, 45]])` should return `[[12, 45], [11, 45], [32, 45], [11, 55]]`.
|
||||
`stableSort([[11, 55], [12, 45], [11, 45], [32, 45]])` deve retornar `[[12, 45], [11, 45], [32, 45], [11, 55]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -104,7 +104,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`stableSort([[10, 22], [1, 2], [1, 4], [1, 5], [10, 9]])` should return `[[1, 2], [1, 4], [1, 5], [10, 9], [10, 22]]`.
|
||||
`stableSort([[10, 22], [1, 2], [1, 4], [1, 5], [10, 9]])` deve retornar `[[1, 2], [1, 4], [1, 5], [10, 9], [10, 22]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -125,7 +125,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`stableSort([[55, 54], [12, 22], [31, 43], [31, 54], [10, 49]])` should return `[[12, 22], [31, 43], [10, 49], [55, 54], [31, 54]]`.
|
||||
`stableSort([[55, 54], [12, 22], [31, 43], [31, 54], [10, 49]])` deve retornar `[[12, 22], [31, 43], [10, 49], [55, 54], [31, 54]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8016
|
||||
title: Sort using a custom comparator
|
||||
title: Ordenar usando um comparador personalizado
|
||||
challengeType: 5
|
||||
forumTopicId: 302309
|
||||
dashedName: sort-using-a-custom-comparator
|
||||
@ -8,17 +8,17 @@ dashedName: sort-using-a-custom-comparator
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function to sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
|
||||
Escrever uma função para ordenar um array (ou lista) de strings em ordem de tamanho decrescente, e em ordem lexicográfica crescente strings de mesmo tamanho.
|
||||
|
||||
# --hints--
|
||||
|
||||
`lengthSorter` should be a function.
|
||||
`lengthSorter` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof lengthSorter == 'function');
|
||||
```
|
||||
|
||||
`lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"])` should return an array.
|
||||
`lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -37,7 +37,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"])` should return `["strings", "sample", "sorted", "Here", "some", "are", "be", "to"]`.
|
||||
`lengthSorter(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"])` deve retornar`["strings", "sample", "sorted", "Here", "some", "are", "be", "to"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -55,7 +55,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`lengthSorter(["I", "hope", "your", "day", "is", "going", "good", "?"])` should return `["going", "good", "hope", "your", "day", "is", "?","I"]`.
|
||||
`lengthSorter(["I", "hope", "your", "day", "is", "going", "good", "?"])` deve retornar `["going", "good", "hope", "your", "day", "is", "?","I"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -64,7 +64,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`lengthSorter(["Mine", "is", "going", "great"])` should return `["going", "great", "Mine", "is"]`.
|
||||
`lengthSorter(["Mine", "is", "going", "great"])` deve retornar `["going", "great", "Mine", "is"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(lengthSorter(['Mine', 'is', 'going', 'great']), [
|
||||
@ -75,7 +75,7 @@ assert.deepEqual(lengthSorter(['Mine', 'is', 'going', 'great']), [
|
||||
]);
|
||||
```
|
||||
|
||||
`lengthSorter(["Have", "fun", "sorting", "!!"])` should return `["sorting", "Have", "fun", "!!"]`.
|
||||
`lengthSorter(["Have", "fun", "sorting", "!!"])` deve retornar `["sorting", "Have", "fun", "!!"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(lengthSorter(['Have', 'fun', 'sorting', '!!']), [
|
||||
@ -86,7 +86,7 @@ assert.deepEqual(lengthSorter(['Have', 'fun', 'sorting', '!!']), [
|
||||
]);
|
||||
```
|
||||
|
||||
`lengthSorter(["Everything", "is", "good", "!!"])` should return `["Everything", "good", "!!", "is"]`.
|
||||
`lengthSorter(["Everything", "is", "good", "!!"])` deve retornar `["Everything", "good", "!!", "is"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(lengthSorter(['Everything', 'is', 'good', '!!']), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8001
|
||||
title: Sorting algorithms/Bead sort
|
||||
title: Ordenar algoritmos/ordenação de contas
|
||||
challengeType: 5
|
||||
forumTopicId: 302310
|
||||
dashedName: sorting-algorithmsbead-sort
|
||||
@ -8,47 +8,47 @@ dashedName: sorting-algorithmsbead-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Sort an array of positive integers using the [Bead Sort Algorithm](https://en.wikipedia.org/wiki/Bead_sort).
|
||||
Ordene um array de números inteiros positivos usando o [Algoritmo de ordenação de contas](https://en.wikipedia.org/wiki/Bead_sort).
|
||||
|
||||
A *bead sort* is also known as a *gravity sort*.
|
||||
Uma *ordenação de contas* também é conhecida como *ordenação por gravidade*.
|
||||
|
||||
The algorithm has O(S), where S is the sum of the integers in the input set: Each bead is moved individually.
|
||||
O algoritmo tem O(S), onde S é a soma dos inteiros no conjunto de entrada: cada conta é movida individualmente.
|
||||
|
||||
This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
|
||||
Esse é o caso quando a ordenação de contas é implementada sem um mecanismo para ajudar a encontrar espaços vazios abaixo das contas, como em implementações de software.
|
||||
|
||||
# --hints--
|
||||
|
||||
`beadSort` should be a function.
|
||||
`beadSort` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof beadSort == 'function');
|
||||
```
|
||||
|
||||
`beadSort([25, 32, 12, 7, 20])` should return an array.
|
||||
`beadSort([25, 32, 12, 7, 20])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(beadSort([25, 32, 12, 7, 20])));
|
||||
```
|
||||
|
||||
`beadSort([25, 32, 12, 7, 20])` should return `[7, 12, 20, 25, 32]`.
|
||||
`beadSort([25, 32, 12, 7, 20])` deve retornar `[7, 12, 20, 25, 32]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(beadSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
|
||||
```
|
||||
|
||||
`beadSort([38, 45, 35, 8, 13])` should return `[8, 13, 35, 38, 45]`.
|
||||
`beadSort([38, 45, 35, 8, 13])` deve retornar `[8, 13, 35, 38, 45]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(beadSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
|
||||
```
|
||||
|
||||
`beadSort([43, 36, 20, 34, 24])` should return `[20, 24, 34, 36, 43]`.
|
||||
`beadSort([43, 36, 20, 34, 24])` deve retornar `[20, 24, 34, 36, 43]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(beadSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
|
||||
```
|
||||
|
||||
`beadSort([12, 33, 26, 18, 1, 16, 38])` should return `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
`beadSort([12, 33, 26, 18, 1, 16, 38])` deve retornar `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(beadSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
@ -62,7 +62,7 @@ assert.deepEqual(beadSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`beadSort([3, 39, 48, 16, 1, 4, 29])` should return `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
`beadSort([3, 39, 48, 16, 1, 4, 29])` deve retornar `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(beadSort([3, 39, 48, 16, 1, 4, 29]), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8002
|
||||
title: Sorting algorithms/Bogosort
|
||||
title: Algoritmos de ordenação/Bogosort
|
||||
challengeType: 5
|
||||
forumTopicId: 302311
|
||||
dashedName: sorting-algorithmsbogosort
|
||||
@ -8,56 +8,56 @@ dashedName: sorting-algorithmsbogosort
|
||||
|
||||
# --description--
|
||||
|
||||
[Bogosort](https://en.wikipedia.org/wiki/Bogosort) a list of numbers.
|
||||
Faça o [Bogosort](https://en.wikipedia.org/wiki/Bogosort) de uma lista de números.
|
||||
|
||||
Bogosort simply shuffles a collection randomly until it is sorted.
|
||||
O Bogosort simplesmente embaralha uma coleção aleatoriamente até que ela fica ordenada.
|
||||
|
||||
"Bogosort" is a perversely inefficient algorithm only used as an in-joke.
|
||||
O "Bogosort" é um algoritmo perversamente ineficaz, que só é usado como uma piada interna.
|
||||
|
||||
Its average run-time is O(n!) because the chance that any given shuffle of a set will end up in sorted order is about one in *n* factorial, and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence.
|
||||
Seu tempo médio de execução é O(n!), pois a probabilidade de que qualquer embaralhamento dado de um conjunto acabe ordenado é equivalente ao fatorial de *n*. No pior dos casos, o tempo é infinito, já que não há garantias de que um embaralhamento aleatório produza uma sequência ordenada.
|
||||
|
||||
Its best case is O(n) since a single pass through the elements may suffice to order them.
|
||||
O melhor caso é O(n), uma vez que um único passo através dos elementos pode bastar para ordená-los.
|
||||
|
||||
Pseudocode:
|
||||
Pseudocódigo:
|
||||
|
||||
<pre><b>while not</b> InOrder(list) <b>do</b>
|
||||
Shuffle(list)
|
||||
<pre><b>while not</b> NaOrdem(lista) <b>do</b>
|
||||
Embaralhar(lista)
|
||||
<b>done</b>
|
||||
</pre>
|
||||
|
||||
# --hints--
|
||||
|
||||
`bogosort` should be a function.
|
||||
`bogosort` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof bogosort == 'function');
|
||||
```
|
||||
|
||||
`bogosort([25, 32, 12, 7, 20])` should return an array.
|
||||
`bogosort([25, 32, 12, 7, 20])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(bogosort([25, 32, 12, 7, 20])));
|
||||
```
|
||||
|
||||
`bogosort([25, 32, 12, 7, 20])` should return `[7, 12, 20, 25, 32]`.
|
||||
`bogosort([25, 32, 12, 7, 20])` deve retornar `[7, 12, 20, 25, 32]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bogosort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
|
||||
```
|
||||
|
||||
`bogosort([38, 45, 35, 8, 13])` should return `[8, 13, 35, 38, 45]`.
|
||||
`bogosort([38, 45, 35, 8, 13])` deve retornar `[8, 13, 35, 38, 45]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bogosort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
|
||||
```
|
||||
|
||||
`bogosort([43, 36, 20, 34, 24])` should return `[20, 24, 34, 36, 43]`.
|
||||
`bogosort([43, 36, 20, 34, 24])` deve retornar `[20, 24, 34, 36, 43]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bogosort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
|
||||
```
|
||||
|
||||
`bogosort([12, 33, 26, 18, 1, 16, 38])` should return `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
`bogosort([12, 33, 26, 18, 1, 16, 38])` deve retornar `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bogosort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
@ -71,7 +71,7 @@ assert.deepEqual(bogosort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`bogosort([3, 39, 48, 16, 1, 4, 29])` should return `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
`bogosort([3, 39, 48, 16, 1, 4, 29])` deve retornar `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(bogosort([3, 39, 48, 16, 1, 4, 29]), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8004
|
||||
title: Sorting algorithms/Cocktail sort
|
||||
title: Algoritmos de ordenação/ordenação de coquetel
|
||||
challengeType: 5
|
||||
forumTopicId: 302312
|
||||
dashedName: sorting-algorithmscocktail-sort
|
||||
@ -8,67 +8,67 @@ dashedName: sorting-algorithmscocktail-sort
|
||||
|
||||
# --description--
|
||||
|
||||
The cocktail shaker sort is an improvement on the [Bubble Sort](https://rosettacode.org/wiki/Bubble Sort). The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from [wikipedia](https://en.wikipedia.org/wiki/Cocktail sort)):
|
||||
A ordenação do shaker de coquetel é uma melhoria da [Ordenação de bolha](https://rosettacode.org/wiki/Bubble Sort). A melhoria consiste basicamente no fato de que os valores são levados como "bolhas" para ambas as direções através do array, porque, em cada iteração, o shaker de coquetel classifica uma vez para frente e uma vez para trás. Pseudocódigo para o algoritmo (da [Wikipédia](https://en.wikipedia.org/wiki/Cocktail sort)):
|
||||
|
||||
<pre><b>function</b> <i>cocktailSort</i>( A : list of sortable items )
|
||||
<pre><b>function</b> <i>cocktailSort</i>( A : lista de itens ordenáveis)
|
||||
<b>do</b>
|
||||
swapped := false
|
||||
<b>for each</b> i <b>in</b> 0 <b>to</b> length( A ) - 2 <b>do</b>
|
||||
<b>if</b> A[ i ] > A[ i+1 ] <b>then</b> <i>// test whether the two</i>
|
||||
<i>// elements are in the wrong</i>
|
||||
<i>// order</i>
|
||||
swap( A[ i ], A[ i+1 ] ) <i>// let the two elements</i>
|
||||
<i>// change places</i>
|
||||
<i>// elementos na ordem</i>
|
||||
<i>// incorreta</i>
|
||||
swap( A[ i ], A[ i+1 ] ) <i>// permitir que os elementos</i>
|
||||
<i>// troquem de lugar</i>
|
||||
swapped := true;
|
||||
<b>if</b> swapped = false <b>then</b>
|
||||
<i>// we can exit the outer loop here if no swaps occurred.</i>
|
||||
<i>// saímos do laço externo aqui se não houver trocas.</i>
|
||||
<b>break do-while loop</b>;
|
||||
swapped := false
|
||||
<b>for each</b> i <b>in</b> length( A ) - 2 <b>down to</b> 0 <b>do</b>
|
||||
<b>if</b> A[ i ] > A[ i+1 ] <b>then</b>
|
||||
swap( A[ i ], A[ i+1 ] )
|
||||
swapped := true;
|
||||
<b>while</b> swapped; <i>// if no elements have been swapped,</i>
|
||||
<i>// then the list is sorted</i>
|
||||
<b>while</b> swapped; <i>// se nenhum elemento for trocado,</i>
|
||||
<i>// a lista está ordenada</i>
|
||||
</pre>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that sorts a given array using cocktail sort.
|
||||
Escreva uma função que ordene um determinado array usando uma ordenação de coquetel.
|
||||
|
||||
# --hints--
|
||||
|
||||
`cocktailSort` should be a function.
|
||||
`cocktailSort` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof cocktailSort == 'function');
|
||||
```
|
||||
|
||||
`cocktailSort([25, 32, 12, 7, 20])` should return an array.
|
||||
`cocktailSort([25, 32, 12, 7, 20])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(cocktailSort([25, 32, 12, 7, 20])));
|
||||
```
|
||||
|
||||
`cocktailSort([25, 32, 12, 7, 20])` should return `[7, 12, 20, 25, 32]`.
|
||||
`cocktailSort([25, 32, 12, 7, 20])` deve retornar `[7, 12, 20, 25, 32]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(cocktailSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
|
||||
```
|
||||
|
||||
`cocktailSort([38, 45, 35, 8, 13])` should return `[8, 13, 35, 38, 45]`.
|
||||
`cocktailSort([38, 45, 35, 8, 13])` deve retornar `[8, 13, 35, 38, 45]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(cocktailSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
|
||||
```
|
||||
|
||||
`cocktailSort([43, 36, 20, 34, 24])` should return `[20, 24, 34, 36, 43]`.
|
||||
`cocktailSort([43, 36, 20, 34, 24])` deve retornar `[20, 24, 34, 36, 43]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(cocktailSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
|
||||
```
|
||||
|
||||
`cocktailSort([12, 33, 26, 18, 1, 16, 38])` should return `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
`cocktailSort([12, 33, 26, 18, 1, 16, 38])` deve retornar `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(cocktailSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
@ -82,7 +82,7 @@ assert.deepEqual(cocktailSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`cocktailSort([3, 39, 48, 16, 1, 4, 29])` should return `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
`cocktailSort([3, 39, 48, 16, 1, 4, 29])` deve retornar `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(cocktailSort([3, 39, 48, 16, 1, 4, 29]), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8005
|
||||
title: Sorting algorithms/Comb sort
|
||||
title: Algoritmos de ordenação/ordenação do pente
|
||||
challengeType: 5
|
||||
forumTopicId: 302313
|
||||
dashedName: sorting-algorithmscomb-sort
|
||||
@ -8,48 +8,48 @@ dashedName: sorting-algorithmscomb-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Implement a *comb sort*.
|
||||
Implemente uma *ordenação de pente*.
|
||||
|
||||
The **Comb Sort** is a variant of the [Bubble Sort](https://rosettacode.org/wiki/Bubble Sort).
|
||||
A **ordenação de pente** é uma variante da [ordenação de bolha](https://rosettacode.org/wiki/Bubble Sort).
|
||||
|
||||
Like the [Shell sort](https://rosettacode.org/wiki/Shell sort), the Comb Sort increases the gap used in comparisons and exchanges.
|
||||
Como a [ordenação de concha](https://rosettacode.org/wiki/Shell sort), a ordenação de pente aumenta o intervalo usado nas comparações e trocas.
|
||||
|
||||
Dividing the gap by $(1-e^{-\\varphi})^{-1} \\approx 1.247330950103979$ works best, but 1.3 may be more practical.
|
||||
Dividir a diferença por $(1-e^{-\\varphi})^{-1} \\approx 1,247330950103979$ funciona melhor, mas 1,3 pode ser mais prático.
|
||||
|
||||
Some implementations use the insertion sort once the gap is less than a certain amount.
|
||||
Algumas implementações usam a ordenação de inserção, já que a diferença é menor do que uma certa quantidade.
|
||||
|
||||
**Also see**
|
||||
**Veja também**
|
||||
|
||||
<ul>
|
||||
<li>the Wikipedia article: <a href='https://en.wikipedia.org/wiki/Comb sort' target='_blank'>Comb sort</a>.</li>
|
||||
<li>o artigo da Wikipédia: <a href='https://pt.wikipedia.org/wiki/Comb_sort' target='_blank'>Comb sort</a>.</li>
|
||||
</ul>
|
||||
|
||||
Variants:
|
||||
Variantes:
|
||||
|
||||
<ul>
|
||||
<li>Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings.</li>
|
||||
<li>Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small). Comb sort with a low gap isn't much better than the Bubble Sort.</li>
|
||||
<li>Combsort11 garante que a diferença termine em (11, 8, 6, 4, 3, 2, 1), o que é significativamente mais rápido do que as outras duas terminações possíveis.</li>
|
||||
<li>A ordenação de pente com terminações diferentes muda para uma ordenação mais eficiente quando os dados estão quase ordenados (quando a diferença é pequena). A ordenação de pente com diferença baixa não é muito melhor que a ordenação de bolha.</li>
|
||||
</ul>
|
||||
|
||||
Pseudocode:
|
||||
Pseudocódigo:
|
||||
|
||||
<pre><b>function</b> combsort(<b>array</b> input)
|
||||
gap := input<b>.size</b> <i>//initialize gap size</i>
|
||||
gap := input<b>.size</b> <i>//inicialize o tamanho da diferença</i>
|
||||
<b>loop until</b> gap = 1 <b>and</b> swaps = 0
|
||||
<i>//update the gap value for a next comb. Below is an example</i>
|
||||
<i>//atualize o valor da diferença para o próximo pente. Abaixo, vemos um exemplo</i>
|
||||
gap := int(gap / 1.25)
|
||||
<b>if</b> gap < 1
|
||||
<i>//minimum gap is 1</i>
|
||||
<i>//a diferença mínima é 1</i>
|
||||
gap := 1
|
||||
<b>end if</b>
|
||||
i := 0
|
||||
swaps := 0 <i>//see <a href='https://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort' target='_blank'>Bubble Sort</a> for an explanation</i>
|
||||
<i>//a single "comb" over the input list</i>
|
||||
<b>loop until</b> i + gap >= input<b>.size</b> <i>//see <a href='https://rosettacode.org/wiki/Sorting_algorithms/Shell_sort' target='_blank'>Shell sort</a> for similar idea</i>
|
||||
swaps := 0 <i>//veja <a href='https://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort' target='_blank'>ordenação de bolha</a> para uma explicação</i>
|
||||
<i>//um único "pente" sobre a lista de entradas</i>
|
||||
<b>loop until</b> i + gap >= input<b>.size</b> <i>//consulte a <a href='https://rosettacode.org/wiki/Sorting_algorithms/Shell_sort' target='_blank'>ordenação de concha</a> para ver uma ideia semelhante</i>
|
||||
<b>if</b> input[i] > input[i+gap]
|
||||
<b>swap</b>(input[i], input[i+gap])
|
||||
swaps := 1 <i>// Flag a swap has occurred, so the</i>
|
||||
<i>// list is not guaranteed sorted</i>
|
||||
swaps := 1 <i>// Marque uma troca que ocorreu, para que</i>
|
||||
<i>// a lista não esteja garantidamente ordenada</i>
|
||||
<b>end if</b>
|
||||
i := i + 1
|
||||
<b>end loop</b>
|
||||
@ -59,41 +59,41 @@ Pseudocode:
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that sorts a given array using Comb sort.
|
||||
Escreva uma função que ordene um determinado array usando uma ordenação de pente.
|
||||
|
||||
# --hints--
|
||||
|
||||
`combSort` should be a function.
|
||||
`combSort` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof combSort == 'function');
|
||||
```
|
||||
|
||||
`combSort([25, 32, 12, 7, 20])` should return an array.
|
||||
`combSort([25, 32, 12, 7, 20])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(combSort([25, 32, 12, 7, 20])));
|
||||
```
|
||||
|
||||
`combSort([25, 32, 12, 7, 20])` should return `[7, 12, 20, 25, 32]`.
|
||||
`combSort([25, 32, 12, 7, 20])` deve retornar `[7, 12, 20, 25, 32]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(combSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
|
||||
```
|
||||
|
||||
`combSort([38, 45, 35, 8, 13])` should return `[8, 13, 35, 38, 45]`.
|
||||
`combSort([38, 45, 35, 8, 13])` deve retornar `[8, 13, 35, 38, 45]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(combSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
|
||||
```
|
||||
|
||||
`combSort([43, 36, 20, 34, 24])` should return `[20, 24, 34, 36, 43]`.
|
||||
`combSort([43, 36, 20, 34, 24])` deve retornar `[20, 24, 34, 36, 43]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(combSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
|
||||
```
|
||||
|
||||
`combSort([12, 33, 26, 18, 1, 16, 38])` should return `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
`combSort([12, 33, 26, 18, 1, 16, 38])` deve retornar `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(combSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
@ -107,7 +107,7 @@ assert.deepEqual(combSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`combSort([3, 39, 48, 16, 1, 4, 29])` should return `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
`combSort([3, 39, 48, 16, 1, 4, 29])` deve retornar `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(combSort([3, 39, 48, 16, 1, 4, 29]), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8007
|
||||
title: Sorting algorithms/Gnome sort
|
||||
title: Algoritmos de ordenação/ordenação do gnomo
|
||||
challengeType: 5
|
||||
forumTopicId: 302314
|
||||
dashedName: sorting-algorithmsgnome-sort
|
||||
@ -8,16 +8,16 @@ dashedName: sorting-algorithmsgnome-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Gnome sort is a sorting algorithm which is similar to [Insertion sort](https://rosettacode.org/wiki/Insertion sort), except that moving an element to its proper place is accomplished by a series of swaps, as in [Bubble Sort](https://rosettacode.org/wiki/Bubble Sort).
|
||||
A ordenação do gnomo é um algoritmo de ordenação semelhante à [ordenação de inserção](https://rosettacode.org/wiki/Insertion sort), exceto pelo fato de que mover um elemento para o lugar adequado é realizado por uma série de trocas, como na [ordenação de bolha](https://rosettacode.org/wiki/Bubble Sort).
|
||||
|
||||
The pseudocode for the algorithm is:
|
||||
O pseudocódigo para o algoritmo é:
|
||||
|
||||
<pre><b>function</b> <i>gnomeSort</i>(a[0..size-1])
|
||||
i := 1
|
||||
j := 2
|
||||
<b>while</b> i < size <b>do</b>
|
||||
<b>if</b> a[i-1] <= a[i] <b>then</b>
|
||||
<i>/// for descending sort, use >= for comparison</i>
|
||||
<i>/// para a ordenação descendente, use >= para a comparação</i>
|
||||
i := j
|
||||
j := j + 1
|
||||
<b>else</b>
|
||||
@ -33,41 +33,41 @@ The pseudocode for the algorithm is:
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function to implement the above pseudo code. The function should return the sorted array.
|
||||
Escreva uma função para implementar o pseudocódigo acima. A função deve retornar o array ordenado.
|
||||
|
||||
# --hints--
|
||||
|
||||
`gnomeSort` should be a function.
|
||||
`gnomeSort` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof gnomeSort == 'function');
|
||||
```
|
||||
|
||||
`gnomeSort([25, 32, 12, 7, 20])` should return an array.
|
||||
`gnomeSort([25, 32, 12, 7, 20])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(gnomeSort([25, 32, 12, 7, 20])));
|
||||
```
|
||||
|
||||
`gnomeSort([25, 32, 12, 7, 20])` should return `[7, 12, 20, 25, 32]`.
|
||||
`gnomeSort([25, 32, 12, 7, 20])` deve retornar `[7, 12, 20, 25, 32]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(gnomeSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
|
||||
```
|
||||
|
||||
`gnomeSort([38, 45, 35, 8, 13])` should return `[8, 13, 35, 38, 45]`.
|
||||
`gnomeSort([38, 45, 35, 8, 13])` deve retornar `[8, 13, 35, 38, 45]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(gnomeSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
|
||||
```
|
||||
|
||||
`gnomeSort([43, 36, 20, 34, 24])` should return `[20, 24, 34, 36, 43]`.
|
||||
`gnomeSort([43, 36, 20, 34, 24])` deve retornar `[20, 24, 34, 36, 43]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(gnomeSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
|
||||
```
|
||||
|
||||
`gnomeSort([12, 33, 26, 18, 1, 16, 38])` should return `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
`gnomeSort([12, 33, 26, 18, 1, 16, 38])` deve retornar `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(gnomeSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
@ -81,7 +81,7 @@ assert.deepEqual(gnomeSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`gnomeSort([3, 39, 48, 16, 1, 4, 29])` should return `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
`gnomeSort([3, 39, 48, 16, 1, 4, 29])` deve retornar `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(gnomeSort([3, 39, 48, 16, 1, 4, 29]), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc800b
|
||||
title: Sorting algorithms/Pancake sort
|
||||
title: Algoritmos de ordenação/ordenação da panqueca
|
||||
challengeType: 5
|
||||
forumTopicId: 302315
|
||||
dashedName: sorting-algorithmspancake-sort
|
||||
@ -8,51 +8,51 @@ dashedName: sorting-algorithmspancake-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function to sort an array of integers (of any convenient size) into ascending order using [Pancake sorting](https://en.wikipedia.org/wiki/Pancake sorting). The function should return the sorted array.
|
||||
Escreva uma função para ordenar um array de inteiros (de qualquer tamanho conveniente) em ordem ascendente usando o método de ordenação [Pancake sorting](https://en.wikipedia.org/wiki/Pancake sorting). A função deve retornar o array ordenado.
|
||||
|
||||
In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so:
|
||||
Em resumo, em vez de serem ordenados elementos individuais, a única operação permitida é "virar" uma extremidade da lista, assim:
|
||||
|
||||
<pre>Before:
|
||||
<pre>Antes:
|
||||
<b>6 7 8 9</b> 2 5 3 4 1<br>
|
||||
After:
|
||||
Depois:
|
||||
<b>9 8 7 6</b> 2 5 3 4 1
|
||||
</pre>
|
||||
|
||||
Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it **must** be the same end for the entire solution. (The end flipped can't be arbitrarily changed.)
|
||||
Apenas uma extremidade da lista pode ser invertida. Esta deve ser a extremidade inferior, mas pode ser a extremidade superior se for mais fácil codificar ou se funcionar melhor. mas **deve** ser a mesma extremidade virada para toda a solução. (A extremidade virada não pode ser alterada arbitrariamente.)
|
||||
|
||||
# --hints--
|
||||
|
||||
`pancakeSort` should be a function.
|
||||
`pancakeSort` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof pancakeSort == 'function');
|
||||
```
|
||||
|
||||
`pancakeSort([25, 32, 12, 7, 20])` should return an array.
|
||||
`pancakeSort([25, 32, 12, 7, 20])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(pancakeSort([25, 32, 12, 7, 20])));
|
||||
```
|
||||
|
||||
`pancakeSort([25, 32, 12, 7, 20])` should return `[7, 12, 20, 25, 32]`.
|
||||
`pancakeSort([25, 32, 12, 7, 20])` deve retornar `[7, 12, 20, 25, 32]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(pancakeSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
|
||||
```
|
||||
|
||||
`pancakeSort([38, 45, 35, 8, 13])` should return `[8, 13, 35, 38, 45]`.
|
||||
`pancakeSort([38, 45, 35, 8, 13])` deve retornar `[8, 13, 35, 38, 45]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(pancakeSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
|
||||
```
|
||||
|
||||
`pancakeSort([43, 36, 20, 34, 24])` should return `[20, 24, 34, 36, 43]`.
|
||||
`pancakeSort([43, 36, 20, 34, 24])` deve retornar `[20, 24, 34, 36, 43]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(pancakeSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
|
||||
```
|
||||
|
||||
`pancakeSort([12, 33, 26, 18, 1, 16, 38])` should return `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
`pancakeSort([12, 33, 26, 18, 1, 16, 38])` deve retornar `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(pancakeSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
@ -66,7 +66,7 @@ assert.deepEqual(pancakeSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`pancakeSort([3, 39, 48, 16, 1, 4, 29])` should return `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
`pancakeSort([3, 39, 48, 16, 1, 4, 29])` deve retornar `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(pancakeSort([3, 39, 48, 16, 1, 4, 29]), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc800c
|
||||
title: Sorting algorithms/Permutation sort
|
||||
title: Algoritmos de ordenação/ordenação de permutação
|
||||
challengeType: 5
|
||||
forumTopicId: 302316
|
||||
dashedName: sorting-algorithmspermutation-sort
|
||||
@ -8,48 +8,48 @@ dashedName: sorting-algorithmspermutation-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function to implement a permutation sort, which proceeds by generating the possible permutations of the input array until discovering the sorted one. The function should return the sorted array.
|
||||
Escreva uma função para implementar uma ordenação de permutação, que gere as possíveis permutações do array de entrada até descobrir a forma ordenada. A função deve retornar o array ordenado.
|
||||
|
||||
Pseudocode:
|
||||
Pseudocódigo:
|
||||
|
||||
<pre><b>while not</b> InOrder(list) <b>do</b>
|
||||
nextPermutation(list)
|
||||
<pre><b>while not</b> NaOrdem(lista) <b>do</b>
|
||||
proximaPermutacao(lista)
|
||||
<b>done</b>
|
||||
</pre>
|
||||
|
||||
# --hints--
|
||||
|
||||
`permutationSort` should be a function.
|
||||
`permutationSort` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof permutationSort == 'function');
|
||||
```
|
||||
|
||||
`permutationSort([25, 32, 12, 7, 20])` should return an array.
|
||||
`permutationSort([25, 32, 12, 7, 20])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(permutationSort([25, 32, 12, 7, 20])));
|
||||
```
|
||||
|
||||
`permutationSort([25, 32, 12, 7, 20])` should return `[7, 12, 20, 25, 32]`.
|
||||
`permutationSort([25, 32, 12, 7, 20])` deve retornar `[7, 12, 20, 25, 32]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(permutationSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
|
||||
```
|
||||
|
||||
`permutationSort([38, 45, 35, 8, 13])` should return `[8, 13, 35, 38, 45]`.
|
||||
`permutationSort([38, 45, 35, 8, 13])` deve retornar `[8, 13, 35, 38, 45]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(permutationSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
|
||||
```
|
||||
|
||||
`permutationSort([43, 36, 20, 34, 24])` should return `[20, 24, 34, 36, 43]`.
|
||||
`permutationSort([43, 36, 20, 34, 24])` deve retornar `[20, 24, 34, 36, 43]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(permutationSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
|
||||
```
|
||||
|
||||
`permutationSort([12, 33, 26, 18, 1, 16, 38])` should return `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
`permutationSort([12, 33, 26, 18, 1, 16, 38])` deve retornar `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(permutationSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
@ -63,7 +63,7 @@ assert.deepEqual(permutationSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`permutationSort([3, 39, 48, 16, 1, 4, 29])` should return `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
`permutationSort([3, 39, 48, 16, 1, 4, 29])` deve retornar `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(permutationSort([3, 39, 48, 16, 1, 4, 29]), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8010
|
||||
title: Sorting algorithms/Shell sort
|
||||
title: Ordenar algoritmos/ordenação de concha
|
||||
challengeType: 5
|
||||
forumTopicId: 302317
|
||||
dashedName: sorting-algorithmsshell-sort
|
||||
@ -8,51 +8,51 @@ dashedName: sorting-algorithmsshell-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function to sort an array of elements using the [Shell sort](https://en.wikipedia.org/wiki/Shell sort) algorithm, a diminishing increment sort. The function should return the sorted array.
|
||||
Escreva uma função para classificar um array de elementos usando o algoritmo de [ordenação de concha](https://en.wikipedia.org/wiki/Shell sort), uma ordenação de incremento reduzido. A função deve retornar o array ordenado.
|
||||
|
||||
The Shell sort (also known as Shellsort or Shell's method) is named after its inventor, Donald Shell, who published the algorithm in 1959.
|
||||
A ordenação de concha (também conhecida como método de Shell ou shellsort) recebeu o nome em homenagem ao seu inventor, Donald Shell, que publicou o algoritmo em 1959.
|
||||
|
||||
Shell sort is a sequence of interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until the increment size is 1.
|
||||
A ordenação de concha é uma sequência de ordenações de inserção intercaladas baseadas em sequência de incremento. O tamanho do incremento é reduzido após cada passagem até que seu tamanho seja 1.
|
||||
|
||||
With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case".
|
||||
Com um tamanho de incremento de 1, a ordenação é de inserção básica, mas, desta vez, com a garantia de que os dados estarão quase classificados, o que é o "melhor caso" da ordenação de inserção.
|
||||
|
||||
Any sequence will sort the data as long as it ends in 1, but some work better than others.
|
||||
Qualquer sequência ordenará os dados desde que termine em 1, mas algumas funcionam melhor do que outras.
|
||||
|
||||
Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice.
|
||||
Estudos empíricos mostraram que uma sequência de incrementos geométricos com uma relação de cerca de 2,2 funcionam bem na prática.
|
||||
|
||||
# --hints--
|
||||
|
||||
`shellSort` should be a function.
|
||||
`shellSort` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof shellSort == 'function');
|
||||
```
|
||||
|
||||
`shellSort([25, 32, 12, 7, 20])` should return an array.
|
||||
`shellSort([25, 32, 12, 7, 20])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(shellSort([25, 32, 12, 7, 20])));
|
||||
```
|
||||
|
||||
`shellSort([25, 32, 12, 7, 20])` should return `[7, 12, 20, 25, 32]`.
|
||||
`shellSort([25, 32, 12, 7, 20])` deve retornar `[7, 12, 20, 25, 32]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(shellSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
|
||||
```
|
||||
|
||||
`shellSort([38, 45, 35, 8, 13])` should return `[8, 13, 35, 38, 45]`.
|
||||
`shellSort([38, 45, 35, 8, 13])` deve retornar `[8, 13, 35, 38, 45]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(shellSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
|
||||
```
|
||||
|
||||
`shellSort([43, 36, 20, 34, 24])` should return `[20, 24, 34, 36, 43]`.
|
||||
`shellSort([43, 36, 20, 34, 24])` deve retornar `[20, 24, 34, 36, 43]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(shellSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
|
||||
```
|
||||
|
||||
`shellSort([12, 33, 26, 18, 1, 16, 38])` should return `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
`shellSort([12, 33, 26, 18, 1, 16, 38])` deve retornar `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(shellSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
@ -66,7 +66,7 @@ assert.deepEqual(shellSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`shellSort([3, 39, 48, 16, 1, 4, 29])` should return `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
`shellSort([3, 39, 48, 16, 1, 4, 29])` deve retornar `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(shellSort([3, 39, 48, 16, 1, 4, 29]), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8012
|
||||
title: Sorting algorithms/Stooge sort
|
||||
title: Algoritmos de ordenação/ordenação fantoche
|
||||
challengeType: 5
|
||||
forumTopicId: 302318
|
||||
dashedName: sorting-algorithmsstooge-sort
|
||||
@ -8,11 +8,11 @@ dashedName: sorting-algorithmsstooge-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function to perform [Stooge Sort](https://en.wikipedia.org/wiki/Stooge sort) on an array of integers. The function should return a sorted array.
|
||||
Escreva uma função para executar a [ordenação fantoche](https://en.wikipedia.org/wiki/Stooge sort) em um array de números inteiros. A função deve retornar o array ordenado.
|
||||
|
||||
The Stooge Sort algorithm is as follows:
|
||||
O algoritmo de ordenação fantoche é o seguinte:
|
||||
|
||||
<pre><b>algorithm</b> stoogesort(<b>array</b> L, i = 0, j = <b>length</b>(L)-1)
|
||||
<pre><b>Algoritmo</b> stoogesort(<b>array</b> L, i = 0, j = <b>length</b>(L)-1)
|
||||
<b>if</b> L[j] < L[i] <b>then</b>
|
||||
L[i] <b>↔</b> L[j]
|
||||
<b>if</b> j - i > 1 <b>then</b>
|
||||
@ -25,37 +25,37 @@ The Stooge Sort algorithm is as follows:
|
||||
|
||||
# --hints--
|
||||
|
||||
`stoogeSort` should be a function.
|
||||
`stoogeSort` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof stoogeSort == 'function');
|
||||
```
|
||||
|
||||
`stoogeSort([25, 32, 12, 7, 20])` should return an array.
|
||||
`stoogeSort([25, 32, 12, 7, 20])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(stoogeSort([25, 32, 12, 7, 20])));
|
||||
```
|
||||
|
||||
`stoogeSort([25, 32, 12, 7, 20])` should return `[7, 12, 20, 25, 32]`.
|
||||
`stoogeSort([25, 32, 12, 7, 20])` deve retornar `[7, 12, 20, 25, 32]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(stoogeSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
|
||||
```
|
||||
|
||||
`stoogeSort([38, 45, 35, 8, 13])` should return `[8, 13, 35, 38, 45]`.
|
||||
`stoogeSort([38, 45, 35, 8, 13])` deve retornar `[8, 13, 35, 38, 45]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(stoogeSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
|
||||
```
|
||||
|
||||
`stoogeSort([43, 36, 20, 34, 24])` should return `[20, 24, 34, 36, 43]`.
|
||||
`stoogeSort([43, 36, 20, 34, 24])` deve retornar `[20, 24, 34, 36, 43]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(stoogeSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
|
||||
```
|
||||
|
||||
`stoogeSort([12, 33, 26, 18, 1, 16, 38])` should return `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
`stoogeSort([12, 33, 26, 18, 1, 16, 38])` deve retornar `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(stoogeSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
@ -69,7 +69,7 @@ assert.deepEqual(stoogeSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`stoogeSort([3, 39, 48, 16, 1, 4, 29])` should return `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
`stoogeSort([3, 39, 48, 16, 1, 4, 29])` deve retornar `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(stoogeSort([3, 39, 48, 16, 1, 4, 29]), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8013
|
||||
title: Sorting algorithms/Strand sort
|
||||
title: Algoritmos de ordenação/ordenação strand
|
||||
challengeType: 5
|
||||
forumTopicId: 302319
|
||||
dashedName: sorting-algorithmsstrand-sort
|
||||
@ -8,43 +8,43 @@ dashedName: sorting-algorithmsstrand-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function to sort an array using the [Strand sort](https://en.wikipedia.org/wiki/Strand sort). The function should return the sorted array.
|
||||
Escreva uma função para ordenar um array usando o algoritmo de ordenação [Strand sort](https://pt.wikipedia.org/wiki/Strand_sort). A função deve retornar o array ordenado.
|
||||
|
||||
This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
|
||||
Esta é uma forma de ordenar números extraindo sequências mais curtas de números já ordenados de uma lista não ordenada.
|
||||
|
||||
# --hints--
|
||||
|
||||
`strandSort` should be a function.
|
||||
`strandSort` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof strandSort == 'function');
|
||||
```
|
||||
|
||||
`strandSort([25, 32, 12, 7, 20])` should return an array.
|
||||
`strandSort([25, 32, 12, 7, 20])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(strandSort([25, 32, 12, 7, 20])));
|
||||
```
|
||||
|
||||
`strandSort([25, 32, 12, 7, 20])` should return `[7, 12, 20, 25, 32]`.
|
||||
`strandSort([25, 32, 12, 7, 20])` deve retornar `[7, 12, 20, 25, 32]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(strandSort([25, 32, 12, 7, 20]), [7, 12, 20, 25, 32]);
|
||||
```
|
||||
|
||||
`strandSort([38, 45, 35, 8, 13])` should return `[8, 13, 35, 38, 45]`.
|
||||
`strandSort([38, 45, 35, 8, 13])` deve retornar `[8, 13, 35, 38, 45]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(strandSort([38, 45, 35, 8, 13]), [8, 13, 35, 38, 45]);
|
||||
```
|
||||
|
||||
`strandSort([43, 36, 20, 34, 24])` should return `[20, 24, 34, 36, 43]`.
|
||||
`strandSort([43, 36, 20, 34, 24])` deve retornar `[20, 24, 34, 36, 43]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(strandSort([43, 36, 20, 34, 24]), [20, 24, 34, 36, 43]);
|
||||
```
|
||||
|
||||
`strandSort([12, 33, 26, 18, 1, 16, 38])` should return `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
`strandSort([12, 33, 26, 18, 1, 16, 38])` deve retornar `[1, 12, 16, 18, 26, 33, 38]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(strandSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
@ -58,7 +58,7 @@ assert.deepEqual(strandSort([12, 33, 26, 18, 1, 16, 38]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`strandSort([3, 39, 48, 16, 1, 4, 29])` should return `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
`strandSort([3, 39, 48, 16, 1, 4, 29])` deve retornar `[1, 3, 4, 16, 29, 39, 48]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(strandSort([3, 39, 48, 16, 1, 4, 29]), [
|
||||
|
@ -8,86 +8,86 @@ dashedName: soundex
|
||||
|
||||
# --description--
|
||||
|
||||
Soundex is an algorithm for creating indices for words based on their pronunciation. The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from [the WP article](https://en.wikipedia.org/wiki/soundex)). There is a major issue in many of the implementations concerning the separation of two consonants that have the same soundex code! According to the [official Rules](https://www.archives.gov/research/census/soundex.html). So check for instance if **Ashcraft** is coded to **A-261**.
|
||||
Soundex é um algoritmo para criar índices para palavras com base em sua pronúncia. O objetivo é que os homófonos sejam codificados para a mesma representação, para que eles possam ser combinados apesar das pequenas diferenças na ortografia (do [artigo da Wikipédia](https://en.wikipedia.org/wiki/soundex)). Há uma questão importante em muitas das implementações relativas à separação de duas consoantes que têm o mesmo código soundex! De acordo com as [regras oficiais](https://www.archives.gov/research/census/soundex.html). Então, verifique por exemplo se **Ashcraft** é codificado para **A-261**.
|
||||
|
||||
<ul>
|
||||
<li>If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded.</li>
|
||||
<li>If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right of the vowel is not coded. Example: Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 for the F). It is not coded A-226.</li>
|
||||
<li>Se uma vogal (A, E, I, O, U) separa duas consoantes que tenham o mesmo código soundex, a consoante à direita da vogal é codificada. Tymczak é codificado como T-522 (T, 5 para M, 2 para o C, Z ignorado – veja a regra "Lado a lado" acima –, 2 para o K). Uma vez que a vogal "A" separa Z e K, o K está codificado.</li>
|
||||
<li>Se "H" ou "W" separa duas consoantes que tenham o mesmo código soundex, a consoante à direita da vogal não é codificada. Exemplo: Ashcraft está codificado A-261 (A, 2 para o S, C ignorado, 6 para o R, 1 para o F). Ele não é codificado A-226.</li>
|
||||
</ul>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes a string as a parameter and returns the encoded string.
|
||||
Escreva uma função que receba uma string como parâmetro e retorne a string codificada.
|
||||
|
||||
# --hints--
|
||||
|
||||
`soundex` should be a function.
|
||||
`soundex` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof soundex == 'function');
|
||||
```
|
||||
|
||||
`soundex("Soundex")` should return a string.
|
||||
`soundex("Soundex")` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(typeof soundex('Soundex') == 'string');
|
||||
```
|
||||
|
||||
`soundex("Soundex")` should return `"S532"`.
|
||||
`soundex("Soundex")` deve retornar `"S532"`.
|
||||
|
||||
```js
|
||||
assert.equal(soundex('Soundex'), 'S532');
|
||||
```
|
||||
|
||||
`soundex("Example")` should return `"E251"`.
|
||||
`soundex("Example")` deve retornar `"E251"`.
|
||||
|
||||
```js
|
||||
assert.equal(soundex('Example'), 'E251');
|
||||
```
|
||||
|
||||
`soundex("Sownteks")` should return `"S532"`.
|
||||
`soundex("Sownteks")` deve retornar `"S532"`.
|
||||
|
||||
```js
|
||||
assert.equal(soundex('Sownteks'), 'S532');
|
||||
```
|
||||
|
||||
`soundex("Ekzampul")` should return `"E251"`.
|
||||
`soundex("Ekzampul")` deve retornar `"E251"`.
|
||||
|
||||
```js
|
||||
assert.equal(soundex('Ekzampul'), 'E251');
|
||||
```
|
||||
|
||||
`soundex("Euler")` should return `"E460"`.
|
||||
`soundex("Euler")` deve retornar `"E460"`.
|
||||
|
||||
```js
|
||||
assert.equal(soundex('Euler'), 'E460');
|
||||
```
|
||||
|
||||
`soundex("Gauss")` should return `"G200"`.
|
||||
`soundex("Gauss")` deve retornar `"G200"`.
|
||||
|
||||
```js
|
||||
assert.equal(soundex('Gauss'), 'G200');
|
||||
```
|
||||
|
||||
`soundex("Hilbert")` should return `"H416"`.
|
||||
`soundex("Hilbert")` deve retornar `"H416"`.
|
||||
|
||||
```js
|
||||
assert.equal(soundex('Hilbert'), 'H416');
|
||||
```
|
||||
|
||||
`soundex("Knuth")` should return `"K530"`.
|
||||
`soundex("Knuth")` deve retornar `"K530"`.
|
||||
|
||||
```js
|
||||
assert.equal(soundex('Knuth'), 'K530');
|
||||
```
|
||||
|
||||
`soundex("Lloyd")` should return `"L300"`.
|
||||
`soundex("Lloyd")` deve retornar `"L300"`.
|
||||
|
||||
```js
|
||||
assert.equal(soundex('Lloyd'), 'L300');
|
||||
```
|
||||
|
||||
`soundex("Lukasiewicz")` should return `"L222"`.
|
||||
`soundex("Lukasiewicz")` deve retornar `"L222"`.
|
||||
|
||||
```js
|
||||
assert.equal(soundex('Lukasiewicz'), 'L222');
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc801c
|
||||
title: Spiral matrix
|
||||
title: Matriz espiral
|
||||
challengeType: 5
|
||||
forumTopicId: 302321
|
||||
dashedName: spiral-matrix
|
||||
@ -8,7 +8,7 @@ dashedName: spiral-matrix
|
||||
|
||||
# --description--
|
||||
|
||||
Produce a spiral array. A *spiral array* is a square arrangement of the first N<sup>2</sup> natural numbers, where the numbers increase sequentially as you go around the edges of the array spiraling inwards. For example, given **5**, produce this array:
|
||||
Produza um array espiral. Um *array espiral* é um arranjo quadrado dos primeiros N<sup>2</sup> números naturais, onde os números aumentam sequencialmente à medida que você vai visitando as arestas do array em uma espiral para dentro. Por exemplo, dado **5**, produza este array:
|
||||
|
||||
<pre>
|
||||
0 1 2 3 4
|
||||
@ -20,19 +20,19 @@ Produce a spiral array. A *spiral array* is a square arrangement of the first N<
|
||||
|
||||
# --hints--
|
||||
|
||||
`spiralArray` should be a function.
|
||||
`spiralArray` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof spiralArray == 'function');
|
||||
```
|
||||
|
||||
`spiralArray(3)` should return an array.
|
||||
`spiralArray(3)` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(spiralArray(3)));
|
||||
```
|
||||
|
||||
`spiralArray(3)` should return `[[0, 1, 2],[7, 8, 3],[6, 5, 4]]`.
|
||||
`spiralArray(3)` deve retornar `[[0, 1, 2],[7, 8, 3],[6, 5, 4]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(spiralArray(3), [
|
||||
@ -42,7 +42,7 @@ assert.deepEqual(spiralArray(3), [
|
||||
]);
|
||||
```
|
||||
|
||||
`spiralArray(4)` should return `[[0, 1, 2, 3],[11, 12, 13, 4],[10, 15, 14, 5],[9, 8, 7, 6]]`.
|
||||
`spiralArray(4)` deve retornar `[[0, 1, 2, 3],[11, 12, 13, 4],[10, 15, 14, 5],[9, 8, 7, 6]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(spiralArray(4), [
|
||||
@ -53,7 +53,7 @@ assert.deepEqual(spiralArray(4), [
|
||||
]);
|
||||
```
|
||||
|
||||
`spiralArray(5)` should return `[[0, 1, 2, 3, 4],[15, 16, 17, 18, 5],[14, 23, 24, 19, 6],[13, 22, 21, 20, 7],[12, 11, 10, 9, 8]]`.
|
||||
`spiralArray(5)` deve retornar `[[0, 1, 2, 3, 4],[15, 16, 17, 18, 5],[14, 23, 24, 19, 6],[13, 22, 21, 20, 7],[12, 11, 10, 9, 8]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(spiralArray(5), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc801d
|
||||
title: Split a character string based on change of character
|
||||
title: Dividir a string de caracteres com base na mudança de caractere
|
||||
challengeType: 5
|
||||
forumTopicId: 302322
|
||||
dashedName: split-a-character-string-based-on-change-of-character
|
||||
@ -8,13 +8,13 @@ dashedName: split-a-character-string-based-on-change-of-character
|
||||
|
||||
# --description--
|
||||
|
||||
Split a (character) string into comma (plus a blank) delimited strings based on a change of character (left to right). Blanks should be treated as any other character (except they are problematic to display clearly). The same applies to commas. For instance, the string:
|
||||
Divida uma string (de caracteres) em vírgulas (mais um espaço em branco) com base em uma mudança de caractere (da esquerda para a direita). Os espaços em branco devem ser tratados como qualquer outro caractere (exceto pelo fato de que são problemáticos para exibir claramente). O mesmo se aplica às vírgulas. Por exemplo, a string:
|
||||
|
||||
<pre>
|
||||
"gHHH5YY++///\\"
|
||||
</pre>
|
||||
|
||||
should be split as:
|
||||
deve ser dividida como:
|
||||
|
||||
<pre>
|
||||
["g", "HHH", "5", "YY", "++", "///", "\\" ];
|
||||
@ -22,25 +22,25 @@ should be split as:
|
||||
|
||||
# --hints--
|
||||
|
||||
`split` should be a function.
|
||||
`split` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof split == 'function');
|
||||
```
|
||||
|
||||
`split("hello")` should return an array.
|
||||
`split("hello")` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(split('hello')));
|
||||
```
|
||||
|
||||
`split("hello")` should return `["h", "e", "ll", "o"]`.
|
||||
`split("hello")` deve retornar `["h", "e", "ll", "o"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(split('hello'), ['h', 'e', 'll', 'o']);
|
||||
```
|
||||
|
||||
`split("commission")` should return `["c", "o", "mm", "i", "ss", "i", "o", "n"]`.
|
||||
`split("commission")` deve retornar `["c", "o", "mm", "i", "ss", "i", "o", "n"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(split('commission'), [
|
||||
@ -55,7 +55,7 @@ assert.deepEqual(split('commission'), [
|
||||
]);
|
||||
```
|
||||
|
||||
`split("ssss----====llloooo")` should return `["ssss", "----", "====", "lll", "oooo"]`.
|
||||
`split("ssss----====llloooo")` deve retornar `["ssss", "----", "====", "lll", "oooo"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(split('ssss----====llloooo'), [
|
||||
@ -67,7 +67,7 @@ assert.deepEqual(split('ssss----====llloooo'), [
|
||||
]);
|
||||
```
|
||||
|
||||
`split("sssmmmaaammmaaat")` should return `["sss", "mmm", "aaa", "mmm", "aaa", "t"]`.
|
||||
`split("sssmmmaaammmaaat")` deve retornar `["sss", "mmm", "aaa", "mmm", "aaa", "t"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(split('sssmmmaaammmaaat'), [
|
||||
@ -80,7 +80,7 @@ assert.deepEqual(split('sssmmmaaammmaaat'), [
|
||||
]);
|
||||
```
|
||||
|
||||
`split("gHHH5YY++///\\")` should return `["g", "HHH", "5", "YY", "++", "///", "\\"]`.
|
||||
`split("gHHH5YY++///\\")` deve retornar `["g", "HHH", "5", "YY", "++", "///", "\\"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(split('gHHH5YY++///\\'), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8024
|
||||
title: State name puzzle
|
||||
title: Desafio do nome do estado
|
||||
challengeType: 5
|
||||
forumTopicId: 302323
|
||||
dashedName: state-name-puzzle
|
||||
@ -8,21 +8,21 @@ dashedName: state-name-puzzle
|
||||
|
||||
# --description--
|
||||
|
||||
This task is inspired by Mark Nelson's DDJ Column "Wordplay" and one of the weekly puzzle challenges from Will Shortz on NPR Weekend Edition [\[1\]](https://www.npr.org/templates/story/story.php?storyId=9264290) and originally attributed to David Edelheit. The challenge was to take the names of two U.S. States, mix them all together, then rearrange the letters to form the names of two *different* U.S. States (so that all four state names differ from one another). What states are these? The problem was reissued on [the Unicon Discussion Web](https://tapestry.tucson.az.us/twiki/bin/view/Main/StateNamesPuzzle) which includes several solutions with analysis. Several techniques may be helpful and you may wish to refer to [Gödel numbering](https://en.wikipedia.org/wiki/Goedel_numbering), [equivalence relations](https://en.wikipedia.org/wiki/Equivalence_relation), and [equivalence classes](https://en.wikipedia.org/wiki/Equivalence_classes). The basic merits of these were discussed in the Unicon Discussion Web. A second challenge in the form of a set of fictitious new states was also presented.
|
||||
Esta tarefa é inspirada na coluna "Wordplay", de Mark Nelson no DDJ e um dos desafios semanais de Will Shortz na edição de fim de semana da NPR [\[1\]](https://www.npr.org/templates/story/story.php?storyId=9264290), sendo originalmente atribuída a David Edelheit. O desafio era pegar os nomes de dois estados dos Estados Unidos misturá-los, e, então, reorganizar as letras para formar os nomes de dois estados *diferentes* (para que os quatro nomes de estados sejam diferentes um do outro). Que estados são esses? O problema foi publicado novamente na [Unicon Discussion Web](https://tapestry.tucson.az.us/twiki/bin/view/Main/StateNamesPuzzle), que inclui diversas soluções com a análise. Várias técnicas podem ser úteis caso você queira consultar, como: [a numeração de Gödel](https://en.wikipedia.org/wiki/Goedel_numbering), [as relações de equivalência](https://en.wikipedia.org/wiki/Equivalence_relation) e [as classes de equivalência](https://en.wikipedia.org/wiki/Equivalence_classes). Os méritos básicos destas técnicas foram discutidos na Unicon Discussion Web. Foi também apresentado um segundo desafio, sob a forma de um conjunto de novos estados fictícios.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function to solve the challenge for the given array of names of states. The function should return an array. Each element should be an object in this form: `{"from":[],"to":[]}`. The "from" array should contain the original names and the "to" array should contain the resultant names.
|
||||
Escreva uma função para resolver o desafio para o array de nomes de estados fornecido. A função deve retornar um array. Cada elemento deve ser um objeto neste formato: `{"from":[],"to":[]}`. O array "from" deve conter os nomes originais e o array "to" deve conter os nomes resultantes.
|
||||
|
||||
# --hints--
|
||||
|
||||
`solve` should be a function.
|
||||
`solve` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof solve == 'function');
|
||||
```
|
||||
|
||||
`solve(["New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota"])` should return an array.
|
||||
`solve(["New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota"])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -44,7 +44,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`solve(["New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota"])` should return `[{ from: ["North Carolina ", "South Dakota"], to: ["North Dakota", "South Carolina"] }]`.
|
||||
`solve(["New Mexico", "New York", "North Carolina ", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania", "Rhode Island", "South Carolina", "South Dakota"])` deve retornar `[{ from: ["North Carolina ", "South Dakota"], to: ["North Dakota", "South Carolina"] }]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -70,7 +70,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`solve(["New York", "New Kory", "Wen Kory", "York New", "Kory New", "New Kory"])` should return `[{ from: ["New Kory", "New York"], to: ["Wen Kory", "York New"] }, { from: ["New Kory", "New York"], to: ["Kory New", "Wen Kory"] }, { from: ["New Kory", "New York"], to: ["Kory New", "York New"] }, { from: ["New York", "Wen Kory"], to: ["New Kory", "York New"] }, { from: ["New York", "Wen Kory"], to: ["Kory New", "New Kory"] }, { from: ["New York", "Wen Kory"], to: ["Kory New", "York New"] }, { from: ["New York", "York New"], to: ["New Kory", "Wen Kory"] }, { from: ["New York", "York New"], to: ["Kory New", "New Kory"] }, { from: ["New York", "York New"], to: ["Kory New", "Wen Kory"] }, { from: ["Kory New", "New York"], to: ["New Kory", "Wen Kory"] }, { from: ["Kory New", "New York"], to: ["New Kory", "York New"] }, { from: ["Kory New", "New York"], to: ["Wen Kory", "York New"] }, { from: ["New Kory", "Wen Kory"], to: ["Kory New", "York New"] }, { from: ["New Kory", "York New"], to: ["Kory New", "Wen Kory"] }, { from: ["Kory New", "New Kory"], to: ["Wen Kory", "York New"] }]`.
|
||||
`solve(["New York", "New Kory", "Wen Kory", "York New", "Kory New", "New Kory"])` deve retornar `[{ from: ["New Kory", "New York"], to: ["Wen Kory", "York New"] }, { from: ["New Kory", "New York"], to: ["Kory New", "Wen Kory"] }, { from: ["New Kory", "New York"], to: ["Kory New", "York New"] }, { from: ["New York", "Wen Kory"], to: ["New Kory", "York New"] }, { from: ["New York", "Wen Kory"], to: ["Kory New", "New Kory"] }, { from: ["New York", "Wen Kory"], to: ["Kory New", "York New"] }, { from: ["New York", "York New"], to: ["New Kory", "Wen Kory"] }, { from: ["New York", "York New"], to: ["Kory New", "New Kory"] }, { from: ["New York", "York New"], to: ["Kory New", "Wen Kory"] }, { from: ["Kory New", "New York"], to: ["New Kory", "Wen Kory"] }, { from: ["Kory New", "New York"], to: ["New Kory", "York New"] }, { from: ["Kory New", "New York"], to: ["Wen Kory", "York New"] }, { from: ["New Kory", "Wen Kory"], to: ["Kory New", "York New"] }, { from: ["New Kory", "York New"], to: ["Kory New", "Wen Kory"] }, { from: ["Kory New", "New Kory"], to: ["Wen Kory", "York New"] }]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8029
|
||||
title: Straddling checkerboard
|
||||
title: Tabuleiro de damas escarranchado
|
||||
challengeType: 5
|
||||
forumTopicId: 302325
|
||||
dashedName: straddling-checkerboard
|
||||
@ -8,17 +8,17 @@ dashedName: straddling-checkerboard
|
||||
|
||||
# --description--
|
||||
|
||||
Implement functions to encrypt and decrypt a message using the [straddling checkerboard](https://en.wikipedia.org/wiki/Straddling_checkerboard) method. The functions will take a string and an array as parameters. The array has 3 strings representing the 3 rows of the checkerboard. The output will be a series of decimal digits. Numbers should be encrypted by inserting the escape character before each digit, then including the digit unencrypted. This should be reversed for decryption.
|
||||
Implemente funções para criptografar e descriptografar uma mensagem usando o método do [tabuleiro de damas escarranchado](https://en.wikipedia.org/wiki/Straddling_checkerboard). As funções receberão uma string e um array como parâmetros. O array tem 3 strings representando as 3 linhas do tabuleiro de damas. O resultado será uma série de dígitos decimais. Os números devem ser criptografados inserindo o caractere de escape antes de cada dígito e, em seguida, incluindo o dígito não criptografado. Isso deve ser revertido para descriptografia.
|
||||
|
||||
# --hints--
|
||||
|
||||
`straddle` should be a function.
|
||||
`straddle` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof straddle == 'function');
|
||||
```
|
||||
|
||||
`straddle("One night-it was on the twentieth of March, 1888-I was returning.",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])` should return a string.
|
||||
`straddle("One night-it was on the twentieth of March, 1888-I was returning.",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -29,7 +29,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`straddle("One night-it was on the twentieth of March, 1888-I was returning.",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])` should return `"34045747525284613427502840425027537379697175891898898898584619028294547488"`.
|
||||
`straddle("One night-it was on the twentieth of March, 1888-I was returning.",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])` deve retornar `"34045747525284613427502840425027537379697175891898898898584619028294547488"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -41,7 +41,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`straddle("One night-it was on the twentieth of March, 1888-I was returning",["HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./"])` should return `"139539363509369743061399059745399365901344308320791798798798367430685972839363935"`.
|
||||
`straddle("One night-it was on the twentieth of March, 1888-I was returning",["HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./"])` deve retornar `"139539363509369743061399059745399365901344308320791798798798367430685972839363935"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -54,7 +54,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`straddle("Thecheckerboardcakerecipespecifies3largeeggsand2.25cupsofflour.",["ET AON RIS", "BCDFGHJKLM", "PQ/UVWXYZ."])` should return `"125021250212707204372221327070218600960021823809623283724002424935226226962262521636094232328463769"`.
|
||||
`straddle("Thecheckerboardcakerecipespecifies3largeeggsand2.25cupsofflour.",["ET AON RIS", "BCDFGHJKLM", "PQ/UVWXYZ."])` deve retornar `"125021250212707204372221327070218600960021823809623283724002424935226226962262521636094232328463769"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -67,13 +67,13 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`unstraddle` should be a function.
|
||||
`unstraddle` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof unstraddle == 'function');
|
||||
```
|
||||
|
||||
`unstraddle("34045747525284613427502840425027537379697175891898898898584619028294547488",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])` should return a string.
|
||||
`unstraddle("34045747525284613427502840425027537379697175891898898898584619028294547488",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -84,7 +84,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`unstraddle("34045747525284613427502840425027537379697175891898898898584619028294547488",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])` should return `"ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING."`.
|
||||
`unstraddle("34045747525284613427502840425027537379697175891898898898584619028294547488",["ESTONIA R", "BCDFGHJKLM", "PQUVWXYZ./"])` deve retornar `"ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING."`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -96,7 +96,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`unstraddle("139539363509369743061399059745399365901344308320791798798798367430685972839363935",["HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./"])` should return `"ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING"`.
|
||||
`unstraddle("139539363509369743061399059745399365901344308320791798798798367430685972839363935",["HOL MES RT", "ABCDFGIJKN", "PQUVWXYZ./"])` deve retornar `"ONENIGHTITWASONTHETWENTIETHOFMARCH1888IWASRETURNING"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
@ -108,7 +108,7 @@ assert.equal(
|
||||
);
|
||||
```
|
||||
|
||||
`unstraddle("125021250212707204372221327070218600960021823809623283724002424935226226962262521636094232328463769",["ET AON RIS", "BCDFGHJKLM", "PQ/UVWXYZ."])` should return `"THECHECKERBOARDCAKERECIPESPECIFIES3LARGEEGGSAND2.25CUPSOFFLOUR."`.
|
||||
`unstraddle("125021250212707204372221327070218600960021823809623283724002424935226226962262521636094232328463769",["ET AON RIS", "BCDFGHJKLM", "PQ/UVWXYZ."])` deve retornar `"THECHECKERBOARDCAKERECIPESPECIFIES3LARGEEGGSAND2.25CUPSOFFLOUR."`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc802a
|
||||
title: Stream Merge
|
||||
title: Mesclar fluxos
|
||||
challengeType: 5
|
||||
forumTopicId: 302326
|
||||
dashedName: stream-merge
|
||||
@ -8,17 +8,17 @@ dashedName: stream-merge
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function that takes multiple sorted arrays of items, and returns one array of sorted items.
|
||||
Escreva uma função que receba vários arrays de itens ordenados e retorne um array de itens ordenados.
|
||||
|
||||
# --hints--
|
||||
|
||||
`mergeLists` should be a function.
|
||||
`mergeLists` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof mergeLists == 'function');
|
||||
```
|
||||
|
||||
`mergeLists([[1, 3, 5, 9, 10], [2, 4, 6, 7, 8]])` should return an array.
|
||||
`mergeLists([[1, 3, 5, 9, 10], [2, 4, 6, 7, 8]])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -31,7 +31,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`mergeLists([[1, 3, 5, 9, 10], [2, 4, 6, 7, 8]])` should return `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`.
|
||||
`mergeLists([[1, 3, 5, 9, 10], [2, 4, 6, 7, 8]])` deve retornar `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -43,7 +43,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`mergeLists([[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]])` should return `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]`.
|
||||
`mergeLists([[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]])` deve retornar `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -56,7 +56,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`mergeLists([[1, 3, 9, 14, 15, 17, 28], [7, 8, 14, 14, 23, 26, 28, 29, 30], [9, 23, 25, 29]])` should return `[1, 3, 7, 8, 9, 9, 14, 14, 14, 15, 17, 23, 23, 25, 26, 28, 28, 29, 29, 30]`.
|
||||
`mergeLists([[1, 3, 9, 14, 15, 17, 28], [7, 8, 14, 14, 23, 26, 28, 29, 30], [9, 23, 25, 29]])` deve retornar `[1, 3, 7, 8, 9, 9, 14, 14, 14, 15, 17, 23, 23, 25, 26, 28, 28, 29, 29, 30]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -69,7 +69,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`mergeLists([[3, 14, 15], [2, 17, 18], [], [2, 3, 5, 7]])` should return `[2, 2, 3, 3, 5, 7, 14, 15, 17, 18]`.
|
||||
`mergeLists([[3, 14, 15], [2, 17, 18], [], [2, 3, 5, 7]])` deve retornar `[2, 2, 3, 3, 5, 7, 14, 15, 17, 18]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(mergeLists([[3, 14, 15], [2, 17, 18], [], [2, 3, 5, 7]]), [
|
||||
@ -86,7 +86,7 @@ assert.deepEqual(mergeLists([[3, 14, 15], [2, 17, 18], [], [2, 3, 5, 7]]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`mergeLists([[1, 19, 1999], [17, 33, 2999, 3000], [8, 500, 3999]])` should return `[1, 8, 17, 19, 33, 500, 1999, 2999, 3000, 3999]`.
|
||||
`mergeLists([[1, 19, 1999], [17, 33, 2999, 3000], [8, 500, 3999]])` deve retornar `[1, 8, 17, 19, 33, 500, 1999, 2999, 3000, 3999]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8036
|
||||
title: Strip control codes and extended characters from a string
|
||||
title: Remover códigos de controle e caracteres estendidos a partir de uma string
|
||||
challengeType: 5
|
||||
forumTopicId: 302327
|
||||
dashedName: strip-control-codes-and-extended-characters-from-a-string
|
||||
@ -8,47 +8,47 @@ dashedName: strip-control-codes-and-extended-characters-from-a-string
|
||||
|
||||
# --description--
|
||||
|
||||
The task is to strip control codes and extended characters from a string. The solution should demonstrate how to achieve each of the following results: A string with control codes and extended characters stripped. In ASCII, the control codes have decimal codes 0 through to 31 and 127. On an ASCII based system, if the control codes are stripped, the resultant string would have all of its characters within the range of 32 to 126 decimal on the ASCII table. On a non-ASCII based system, we consider characters that do not have a corresponding glyph on the ASCII table (within the ASCII range of 32 to 126 decimal) to be an extended character for the purpose of this task.
|
||||
A tarefa é remover códigos de controle e caracteres estendidos de uma string. A solução deve demonstrar como alcançar cada um dos seguintes resultados: uma string com códigos de controle e caracteres estendidos removidos. Em ASCII, os códigos de controle têm códigos decimais 0 até 31 e 127. Em um sistema baseado em ASCII, se os códigos de controle forem removidos, a string resultante teria todos os seus caracteres dentro do intervalo de 32 a 126 decimal na tabela ASCII. Em um sistema não ASCII, consideramos que caracteres que não têm um glifo correspondente na tabela ASCII (dentro do intervalo ASCII de 32 a 126 decimal) são um caráter alargado para efeitos desta tarefa.
|
||||
|
||||
# --hints--
|
||||
|
||||
`strip` should be a function.
|
||||
`strip` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof strip == 'function');
|
||||
```
|
||||
|
||||
`strip("abc")` should return a string.
|
||||
`strip("abc")` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(typeof strip('abc') == 'string');
|
||||
```
|
||||
|
||||
`strip("\ba\x00b\n\rc\fd\xc3")` should return `"abcd"`.
|
||||
`strip("\ba\x00b\n\rc\fd\xc3")` deve retornar `"abcd"`.
|
||||
|
||||
```js
|
||||
assert.equal(strip('\ba\x00b\n\rc\fd\xc3'), 'abcd');
|
||||
```
|
||||
|
||||
`strip("\u0000\n abc\u00E9def\u007F")` should return `" abcdef"`.
|
||||
`strip("\u0000\n abc\u00E9def\u007F")` deve retornar `" abcdef"`.
|
||||
|
||||
```js
|
||||
assert.equal(strip('\u0000\n abc\u00E9def\u007F'), ' abcdef');
|
||||
```
|
||||
|
||||
`strip("a\n\tb\u2102d\u2147f")` should return `"abdf"`.
|
||||
`strip("a\n\tb\u2102d\u2147f")` deve retornar `"abdf"`.
|
||||
|
||||
```js
|
||||
assert.equal(strip('a\n\tb\u2102d\u2147f'), 'abdf');
|
||||
```
|
||||
|
||||
`strip("Français.")` should return `"Franais."`.
|
||||
`strip("Français.")` deve retornar `"Franais."`.
|
||||
|
||||
```js
|
||||
assert.equal(strip('Français.'), 'Franais.');
|
||||
```
|
||||
|
||||
`strip("123\tabc\u0007DEF\u007F+-*/€æŧðłþ")` should return `"123abcDEF+-*/"`.
|
||||
`strip("123\tabc\u0007DEF\u007F+-*/€æŧðłþ")` deve retornar `"123abcDEF+-*/"`.
|
||||
|
||||
```js
|
||||
assert.equal(strip('123\tabc\u0007DEF\u007F+-*/€æŧðłþ'), '123abcDEF+-*/');
|
||||
|
@ -8,50 +8,50 @@ dashedName: subleq
|
||||
|
||||
# --description--
|
||||
|
||||
[Subleq](https://rosettacode.org/wiki/eso:Subleq) is an example of a [One-Instruction Set Computer (OISC)](https://en.wikipedia.org/wiki/One_instruction_set_computer).
|
||||
O [Subleq](https://rosettacode.org/wiki/eso:Subleq) é um exemplo de um [One-Instruction Set Computer (OISC)](https://en.wikipedia.org/wiki/One_instruction_set_computer).
|
||||
|
||||
It is named after its only instruction, which is **SU**btract and **B**ranch if **L**ess than or **EQ**ual
|
||||
Seu nome vem de sua única instrução, que é **SU**btract and **B**ranch if **L**ess than or **EQ**ual (subtraia e ramifique se for menor ou igual)
|
||||
|
||||
to zero.
|
||||
a zero.
|
||||
|
||||
Your task is to create an interpreter which emulates such a machine.
|
||||
Sua tarefa é criar um interpretador que emule esse tipo de máquina.
|
||||
|
||||
The machine's memory consists of an array of signed integers. Any reasonable word size is fine, but the memory must be
|
||||
A memória da máquina consiste em um array de números inteiros com sinal. Qualquer tamanho razoável de palavra serve, mas a memória deve ser
|
||||
|
||||
able to hold negative as well as positive numbers.
|
||||
capaz de conter números negativos e positivos.
|
||||
|
||||
Execution begins with the instruction pointer aimed at the first word, which is address 0. It proceeds as follows:
|
||||
A execução começa com o ponteiro de instrução mirando a primeira palavra, que é o endereço 0. Ela prossegue da seguinte forma:
|
||||
|
||||
<ol>
|
||||
<li>Let A, B, and C be the value stored in the three consecutive words in memory starting at the instruction pointer.</li>
|
||||
<li>Advance the instruction pointer 3 words to point at the address after the one containing C.</li>
|
||||
<li>If A is -1, then a character is read from standard input and its code point stored in the address given by B. C
|
||||
is unused.</li>
|
||||
<li>If B is -1, then the number contained in the address given by A is interpreted as a code point and the
|
||||
corresponding character output. C is again unused.</li>
|
||||
<li>Otherwise, both A and B are treated as the addresses of memory locations. The number contained in the address
|
||||
given by A is subtracted from the number at the address given by B (and the result stored back in address B). If
|
||||
the result is zero or negative, the value C becomes the new instruction pointer.</li>
|
||||
<li>If the instruction pointer becomes negative, execution halts.</li>
|
||||
<li>Permita que A, B e C sejam valores armazenado nas três palavras consecutivas na memória, começando no ponteiro de instrução.</li>
|
||||
<li>Avance o ponteiro de instrução 3 palavras para apontar para o endereço após o que contém C.</li>
|
||||
<li>Se A é -1, então um caractere é lido a partir da entrada padrão e seu ponto de código armazenado no endereço fornecido por B. C
|
||||
não é usado.</li>
|
||||
<li>Se B é -1, então o número contido no endereço dado por A é interpretado como um ponto de código e a
|
||||
saída de caractere correspondente. C, mais uma vez, não é utilizado.</li>
|
||||
<li>Caso contrário, tanto A quanto B são tratados como endereços de locais de memória. O número contido no endereço
|
||||
fornecido por A é subtraído do número do endereço fornecido por B (e o resultado é armazenado de volta no endereço B). Se
|
||||
o resultado for zero ou negativo, o valor C se torna o novo ponteiro da instrução.</li>
|
||||
<li>Se o ponteiro da instrução se tornar negativo, a execução para.</li>
|
||||
</ol>
|
||||
|
||||
Other negative addresses besides -1 may be treated as equivalent to -1, or generate an error, as you see fit.
|
||||
Outros endereços negativos além de -1 podem ser tratados como equivalentes a -1 ou gerar um erro, como você achar adequado.
|
||||
|
||||
Your solution should accept a program to execute on the machine, separately from the input fed to the program itself.
|
||||
A solução deve aceitar um programa que será executado na máquina, separadamente da entrada alimentado no programa em si.
|
||||
|
||||
This program should be in raw subleq "machine code" - whitespace-separated decimal numbers, with no symbolic names or
|
||||
Este programa deve estar em "código de máquina" bruto de subleq - números decimais separados por espaços em branco, sem nomes simbólicos ou
|
||||
|
||||
other assembly-level extensions, to be loaded into memory starting at address 0. Show the output of your solution when
|
||||
outras extensões de nível de assembly, a serem carregadas na memória iniciando no endereço 0. Mostre a saída da solução quando
|
||||
|
||||
fed this "Hello, world!" program. (Note that the example assumes ASCII or a superset of it, such as any of the Latin-N
|
||||
recebe esse programa "Hello, world!". (Observe que o exemplo assume ASCII ou um superconjunto dele, como qualquer um dos conjuntos
|
||||
|
||||
character sets or Unicode. You may translate it into another character set if your implementation is on a
|
||||
de caracteres N-latinos ou Unicode. Você pode traduzi-lo para outro conjunto de caracteres se a implementação estiver em um
|
||||
|
||||
non-ASCiI-compatible environment.)
|
||||
ambiente não ASCII compatível.)
|
||||
|
||||
<pre>15 17 -1 17 -1 -1 16 1 -1 16 3 -1 15 15 0 0 -1 72 101 108 108 111 44 32 119 111 114 108 100 33 10 0</pre>
|
||||
|
||||
Which corresponds to something like this in a hypothetical assembler language:
|
||||
O que corresponde a algo assim em uma linguagem hipotética de assembler:
|
||||
|
||||
<pre>start:
|
||||
zero, message, -1
|
||||
@ -66,19 +66,19 @@ message: "Hello, world!\n\0"
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes an array of integers as a parameter. This represents the memory elements. The function
|
||||
Escreva uma função que receba um array de números inteiros como parâmetro. Ele representa os elementos da memória. A função
|
||||
|
||||
should interpret the sequence and return the output string. For this task, assume that there is no standard input.
|
||||
deve interpretar a sequência e retornar a string de saída. Para esta tarefa, considere que não há uma entrada padrão.
|
||||
|
||||
# --hints--
|
||||
|
||||
`Subleq` should be a function.
|
||||
`Subleq` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof Subleq == 'function');
|
||||
```
|
||||
|
||||
`Subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0])` should return a string.
|
||||
`Subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0])` deve retornar uma string.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -118,7 +118,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`Subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0])` should return `"Hello, world!"`.
|
||||
`Subleq([15, 17, -1, 17, -1, -1, 16, 1, -1, 16, 3, -1, 15, 15, 0, 0, -1, 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33, 0])` deve retornar `"Hello, world!"`.
|
||||
|
||||
```js
|
||||
assert.equal(
|
||||
|
@ -8,17 +8,17 @@ dashedName: sudoku
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function to solve a partially filled-in normal 9x9 [Sudoku](https://en.wikipedia.org/wiki/Sudoku) grid and return the result. The blank fields are represented by `-1`. [Algorithmics of Sudoku](https://en.wikipedia.org/wiki/Algorithmics_of_sudoku) may help implement this.
|
||||
Escreva uma função para resolver um tabuleiro 9x9 normal, parcialmente preenchido, de [Sudoku](https://pt.wikipedia.org/wiki/Sudoku) e retorne o resultado. Os campos em branco são representados por `-1`. O [Algoritmo de Sudoku](https://pt.wikipedia.org/wiki/Algoritmo_de_sudoku) pode ajudar a implementar isso.
|
||||
|
||||
# --hints--
|
||||
|
||||
`solveSudoku` should be a function.
|
||||
`solveSudoku` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof solveSudoku == 'function');
|
||||
```
|
||||
|
||||
`solveSudoku([[8, 1, 9, -1, -1, 5, -1, -1, -1],[-1, -1, 2, -1, -1, -1, 7, 5, -1],[-1, 3, 7, 1, -1, 4, -1, 6, -1],[4, -1, -1, 5, 9, -1, 1, -1, -1],[7, -1, -1, 3, -1, 8, -1, -1, 2],[-1, -1, 3, -1, 6, 2, -1, -1, 7],[-1, 5, -1, 7, -1, 9, 2, 1, -1],[-1, 6, 4, -1, -1, -1, 9, -1, -1],[-1, -1, -1, 2, -1, -1, 4, 3, 8]])` should return an array.
|
||||
`solveSudoku([[8, 1, 9, -1, -1, 5, -1, -1, -1],[-1, -1, 2, -1, -1, -1, 7, 5, -1],[-1, 3, 7, 1, -1, 4, -1, 6, -1],[4, -1, -1, 5, 9, -1, 1, -1, -1],[7, -1, -1, 3, -1, 8, -1, -1, 2],[-1, -1, 3, -1, 6, 2, -1, -1, 7],[-1, 5, -1, 7, -1, 9, 2, 1, -1],[-1, 6, 4, -1, -1, -1, 9, -1, -1],[-1, -1, -1, 2, -1, -1, 4, 3, 8]])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -38,7 +38,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`solveSudoku([[8, 1, 9, -1, -1, 5, -1, -1, -1],[-1, -1, 2, -1, -1, -1, 7, 5, -1],[-1, 3, 7, 1, -1, 4, -1, 6, -1],[4, -1, -1, 5, 9, -1, 1, -1, -1],[7, -1, -1, 3, -1, 8, -1, -1, 2],[-1, -1, 3, -1, 6, 2, -1, -1, 7],[-1, 5, -1, 7, -1, 9, 2, 1, -1],[-1, 6, 4, -1, -1, -1, 9, -1, -1],[-1, -1, -1, 2, -1, -1, 4, 3, 8]])` should return `[[8, 1, 9, 6, 7, 5, 3, 2, 4],[6, 4, 2, 9, 8, 3, 7, 5, 1],[5, 3, 7, 1, 2, 4, 8, 6, 9],[4, 2, 6, 5, 9, 7, 1, 8, 3],[7, 9, 5, 3, 1, 8, 6, 4, 2],[1, 8, 3, 4, 6, 2, 5, 9, 7],[3, 5, 8, 7, 4, 9, 2, 1, 6],[2, 6, 4, 8, 3, 1, 9, 7, 5],[9, 7, 1, 2, 5, 6, 4, 3, 8]]`.
|
||||
`solveSudoku([[8, 1, 9, -1, -1, 5, -1, -1, -1],[-1, -1, 2, -1, -1, -1, 7, 5, -1],[-1, 3, 7, 1, -1, 4, -1, 6, -1],[4, -1, -1, 5, 9, -1, 1, -1, -1],[7, -1, -1, 3, -1, 8, -1, -1, 2],[-1, -1, 3, -1, 6, 2, -1, -1, 7],[-1, 5, -1, 7, -1, 9, 2, 1, -1],[-1, 6, 4, -1, -1, -1, 9, -1, -1],[-1, -1, -1, 2, -1, -1, 4, 3, 8]])` deve retornar `[[8, 1, 9, 6, 7, 5, 3, 2, 4],[6, 4, 2, 9, 8, 3, 7, 5, 1],[5, 3, 7, 1, 2, 4, 8, 6, 9],[4, 2, 6, 5, 9, 7, 1, 8, 3],[7, 9, 5, 3, 1, 8, 6, 4, 2],[1, 8, 3, 4, 6, 2, 5, 9, 7],[3, 5, 8, 7, 4, 9, 2, 1, 6],[2, 6, 4, 8, 3, 1, 9, 7, 5],[9, 7, 1, 2, 5, 6, 4, 3, 8]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -67,7 +67,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`solveSudoku([[5, 3, -1, -1, 2, 4, 7, -1, -1],[-1, -1, 2, -1, -1, -1, 8, -1, -1],[1, -1, -1, 7, -1, 3, 9, -1, 2],[-1, -1, 8, -1, 7, 2, -1, 4, 9],[-1, 2, -1, 9, 8, -1, -1, 7, -1],[7, 9, -1, -1, -1, -1, -1, 8, -1],[-1, -1, -1, -1, 3, -1, 5, -1, 6],[9, 6, -1, -1, 1, -1, 3, -1, -1],[-1, 5, -1, 6, 9, -1, -1, 1, -1]])` should return `[[5, 3, 9, 8, 2, 4, 7, 6, 1],[6, 7, 2, 1, 5, 9, 8, 3, 4],[1, 8, 4, 7, 6, 3, 9, 5, 2],[3, 1, 8, 5, 7, 2, 6, 4, 9],[4, 2, 5, 9, 8, 6, 1, 7, 3],[7, 9, 6, 3, 4, 1, 2, 8, 5],[8, 4, 1, 2, 3, 7, 5, 9, 6],[9, 6, 7, 4, 1, 5, 3, 2, 8],[2, 5, 3, 6, 9, 8, 4, 1, 7]]`.
|
||||
`solveSudoku([[5, 3, -1, -1, 2, 4, 7, -1, -1],[-1, -1, 2, -1, -1, -1, 8, -1, -1],[1, -1, -1, 7, -1, 3, 9, -1, 2],[-1, -1, 8, -1, 7, 2, -1, 4, 9],[-1, 2, -1, 9, 8, -1, -1, 7, -1],[7, 9, -1, -1, -1, -1, -1, 8, -1],[-1, -1, -1, -1, 3, -1, 5, -1, 6],[9, 6, -1, -1, 1, -1, 3, -1, -1],[-1, 5, -1, 6, 9, -1, -1, 1, -1]])` deve retornar `[[5, 3, 9, 8, 2, 4, 7, 6, 1],[6, 7, 2, 1, 5, 9, 8, 3, 4],[1, 8, 4, 7, 6, 3, 9, 5, 2],[3, 1, 8, 5, 7, 2, 6, 4, 9],[4, 2, 5, 9, 8, 6, 1, 7, 3],[7, 9, 6, 3, 4, 1, 2, 8, 5],[8, 4, 1, 2, 3, 7, 5, 9, 6],[9, 6, 7, 4, 1, 5, 3, 2, 8],[2, 5, 3, 6, 9, 8, 4, 1, 7]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -96,7 +96,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`solveSudoku([[-1, -1, 3, -1, 2, -1, 6, -1, -1],[9, -1, -1, 3, -1, 5, -1, -1, 1],[-1, -1, 1, 8, -1, 6, 4, -1, -1],[-1, -1, 8, 1, -1, 2, 9, -1, -1],[7, -1, -1, -1, -1, -1, -1, -1, 8],[-1, -1, 6, 7, -1, 8, 2, -1, -1],[-1, -1, 2, 6, -1, 9, 5, -1, -1],[8, -1, -1, 2, -1, 3, -1, -1, 9],[-1, -1, 5, -1, 1, -1, 3, -1, -1]])` should return `[[4, 8, 3, 9, 2, 1, 6, 5, 7],[9, 6, 7, 3, 4, 5, 8, 2, 1],[2, 5, 1, 8, 7, 6, 4, 9, 3],[5, 4, 8, 1, 3, 2, 9, 7, 6],[7, 2, 9, 5, 6, 4, 1, 3, 8],[1, 3, 6, 7, 9, 8, 2, 4, 5],[3, 7, 2, 6, 8, 9, 5, 1, 4],[8, 1, 4, 2, 5, 3, 7, 6, 9],[6, 9, 5, 4, 1, 7, 3, 8, 2]]`.
|
||||
`solveSudoku([[-1, -1, 3, -1, 2, -1, 6, -1, -1],[9, -1, -1, 3, -1, 5, -1, -1, 1],[-1, -1, 1, 8, -1, 6, 4, -1, -1],[-1, -1, 8, 1, -1, 2, 9, -1, -1],[7, -1, -1, -1, -1, -1, -1, -1, 8],[-1, -1, 6, 7, -1, 8, 2, -1, -1],[-1, -1, 2, 6, -1, 9, 5, -1, -1],[8, -1, -1, 2, -1, 3, -1, -1, 9],[-1, -1, 5, -1, 1, -1, 3, -1, -1]])` deve retornar `[[4, 8, 3, 9, 2, 1, 6, 5, 7],[9, 6, 7, 3, 4, 5, 8, 2, 1],[2, 5, 1, 8, 7, 6, 4, 9, 3],[5, 4, 8, 1, 3, 2, 9, 7, 6],[7, 2, 9, 5, 6, 4, 1, 3, 8],[1, 3, 6, 7, 9, 8, 2, 4, 5],[3, 7, 2, 6, 8, 9, 5, 1, 4],[8, 1, 4, 2, 5, 3, 7, 6, 9],[6, 9, 5, 4, 1, 7, 3, 8, 2]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc803f
|
||||
title: Sum digits of an integer
|
||||
title: Soma dos dígitos de um inteiro
|
||||
challengeType: 5
|
||||
forumTopicId: 302331
|
||||
dashedName: sum-digits-of-an-integer
|
||||
@ -8,60 +8,60 @@ dashedName: sum-digits-of-an-integer
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function that takes a string as a parameter. This string represents a number that can be in any base (less than 37) and return the sum of its digits.
|
||||
Escreva uma função que receba uma string como parâmetro. Essa string representa um número que pode estar em qualquer base (inferior a 37) e que retorne a soma de seus dígitos.
|
||||
|
||||
<ul>
|
||||
<li><b>1</b><sub>10</sub> sums to <b>1</b></li>
|
||||
<li><b>1234</b><sub>10</sub> sums to <b>10</b></li>
|
||||
<li><b>fe</b><sub>16</sub> sums to <b>29</b></li>
|
||||
<li><b>f0e</b><sub>16</sub> sums to <b>29</b></li>
|
||||
<li><b>1</b><sub>10</sub> soma <b>1</b></li>
|
||||
<li><b>1234</b><sub>10</sub> soma <b>10</b></li>
|
||||
<li><b>fe</b><sub>16</sub> soma <b>29</b></li>
|
||||
<li><b>f0e</b><sub>16</sub> soma <b>29</b></li>
|
||||
</ul>
|
||||
|
||||
# --hints--
|
||||
|
||||
`sumDigits` should be a function.
|
||||
`sumDigits` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof sumDigits == 'function');
|
||||
```
|
||||
|
||||
`sumDigits("1")` should return a number.
|
||||
`sumDigits("1")` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof sumDigits('1') == 'number');
|
||||
```
|
||||
|
||||
`sumDigits("1")` should return `1`.
|
||||
`sumDigits("1")` deve retornar `1`.
|
||||
|
||||
```js
|
||||
assert.equal(sumDigits('1'), 1);
|
||||
```
|
||||
|
||||
`sumDigits("12345")` should return `15`.
|
||||
`sumDigits("12345")` deve retornar `15`.
|
||||
|
||||
```js
|
||||
assert.equal(sumDigits('12345'), 15);
|
||||
```
|
||||
|
||||
`sumDigits("254")` should return `11`.
|
||||
`sumDigits("254")` deve retornar `11`.
|
||||
|
||||
```js
|
||||
assert.equal(sumDigits('254'), 11);
|
||||
```
|
||||
|
||||
`sumDigits("fe")` should return `29`.
|
||||
`sumDigits("fe")` deve retornar `29`.
|
||||
|
||||
```js
|
||||
assert.equal(sumDigits('fe'), 29);
|
||||
```
|
||||
|
||||
`sumDigits("f0e")` should return `29`.
|
||||
`sumDigits("f0e")` deve retornar `29`.
|
||||
|
||||
```js
|
||||
assert.equal(sumDigits('f0e'), 29);
|
||||
```
|
||||
|
||||
`sumDigits("999ABCXYZ")` should return `162`.
|
||||
`sumDigits("999ABCXYZ")` deve retornar `162`.
|
||||
|
||||
```js
|
||||
assert.equal(sumDigits('999ABCXYZ'), 162);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8040
|
||||
title: Sum multiples of 3 and 5
|
||||
title: Soma dos múltiplos de 3 e 5
|
||||
challengeType: 5
|
||||
forumTopicId: 302332
|
||||
dashedName: sum-multiples-of-3-and-5
|
||||
@ -8,47 +8,47 @@ dashedName: sum-multiples-of-3-and-5
|
||||
|
||||
# --description--
|
||||
|
||||
The objective is to write a function that finds the sum of all positive multiples of 3 or 5 below *n*.
|
||||
O objetivo é escrever uma função que encontra a soma de todos os múltiplos positivos de 3 ou 5 abaixo de *n*.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sumMults` should be a function.
|
||||
`sumMults` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof sumMults == 'function');
|
||||
```
|
||||
|
||||
`sumMults(10)` should return a number.
|
||||
`sumMults(10)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof sumMults(10) == 'number');
|
||||
```
|
||||
|
||||
`sumMults(10)` should return `23`.
|
||||
`sumMults(10)` deve retornar `23`.
|
||||
|
||||
```js
|
||||
assert.equal(sumMults(10), 23);
|
||||
```
|
||||
|
||||
`sumMults(100)` should return `2318`.
|
||||
`sumMults(100)` deve retornar `2318`.
|
||||
|
||||
```js
|
||||
assert.equal(sumMults(100), 2318);
|
||||
```
|
||||
|
||||
`sumMults(1000)` should return `233168`.
|
||||
`sumMults(1000)` deve retornar `233168`.
|
||||
|
||||
```js
|
||||
assert.equal(sumMults(1000), 233168);
|
||||
```
|
||||
|
||||
`sumMults(10000)` should return `23331668`.
|
||||
`sumMults(10000)` deve retornar `23331668`.
|
||||
|
||||
```js
|
||||
assert.equal(sumMults(10000), 23331668);
|
||||
```
|
||||
|
||||
`sumMults(100000)` should return `2333316668`.
|
||||
`sumMults(100000)` deve retornar `2333316668`.
|
||||
|
||||
```js
|
||||
assert.equal(sumMults(100000), 2333316668);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8041
|
||||
title: Sum of a series
|
||||
title: Soma de uma série
|
||||
challengeType: 5
|
||||
forumTopicId: 302333
|
||||
dashedName: sum-of-a-series
|
||||
@ -8,51 +8,51 @@ dashedName: sum-of-a-series
|
||||
|
||||
# --description--
|
||||
|
||||
Compute the **n**<sup>th</sup> term of a [series](https://en.wikipedia.org/wiki/Series (mathematics)), i.e. the sum of the **n** first terms of the corresponding [sequence](https://en.wikipedia.org/wiki/sequence). Informally this value, or its limit when **n** tends to infinity, is also called the *sum of the series*, thus the title of this task. For this task, use: $S_n = \displaystyle\sum_{k=1}^n \frac{1}{k^2}$.
|
||||
Calcule o **n**<sup></sup>-ésimo termo de uma [série](https://en.wikipedia.org/wiki/Series (mathematics)), ou seja, a soma dos **n** primeiros termos da [sequência](https://en.wikipedia.org/wiki/sequence) correspondente. Informalmente, esse valor, ou seu limite quando **n** tende ao infinito, é também chamado de *soma da série*, razão do título desta tarefa. Para esta tarefa, use: $S_n = \displaystyle\sum_{k=1}^n \frac{1}{k^2}$.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that take $a$ and $b$ as parameters and returns the sum of $a^{th}$ to $b^{th}$ members of the sequence.
|
||||
Escreva uma função que receba $a$ e $b$ como parâmetros e retorne a soma do $a$-ésimo ao $b$-ésimo termos da sequência.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sum` should be a function.
|
||||
`sum` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof sum == 'function');
|
||||
```
|
||||
|
||||
`sum(1, 100)` should return a number.
|
||||
`sum(1, 100)` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof sum(1, 100) == 'number');
|
||||
```
|
||||
|
||||
`sum(1, 100)` should return `1.6349839001848923`.
|
||||
`sum(1, 100)` deve retornar `1.6349839001848923`.
|
||||
|
||||
```js
|
||||
assert.equal(sum(1, 100), 1.6349839001848923);
|
||||
```
|
||||
|
||||
`sum(33, 46)` should return `0.009262256361481223`.
|
||||
`sum(33, 46)` deve retornar `0.009262256361481223`.
|
||||
|
||||
```js
|
||||
assert.equal(sum(33, 46), 0.009262256361481223);
|
||||
```
|
||||
|
||||
`sum(21, 213)` should return `0.044086990748706555`.
|
||||
`sum(21, 213)` deve retornar `0.044086990748706555`.
|
||||
|
||||
```js
|
||||
assert.equal(sum(21, 213), 0.044086990748706555);
|
||||
```
|
||||
|
||||
`sum(11, 111)` should return `0.08619778593108679`.
|
||||
`sum(11, 111)` deve retornar `0.08619778593108679`.
|
||||
|
||||
```js
|
||||
assert.equal(sum(11, 111), 0.08619778593108679);
|
||||
```
|
||||
|
||||
`sum(1, 10)` should return `1.5497677311665408`.
|
||||
`sum(1, 10)` deve retornar `1.5497677311665408`.
|
||||
|
||||
```js
|
||||
assert.equal(sum(1, 10), 1.5497677311665408);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8042
|
||||
title: Sum of squares
|
||||
title: Soma dos quadrados
|
||||
challengeType: 5
|
||||
forumTopicId: 302334
|
||||
dashedName: sum-of-squares
|
||||
@ -8,47 +8,47 @@ dashedName: sum-of-squares
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function to find the sum of squares of an array of integers.
|
||||
Escreva uma função para encontrar a soma dos quadrados de um array de números inteiros.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sumsq` should be a function.
|
||||
`sumsq` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof sumsq == 'function');
|
||||
```
|
||||
|
||||
`sumsq([1, 2, 3, 4, 5])` should return a number.
|
||||
`sumsq([1, 2, 3, 4, 5])` deve retornar um número.
|
||||
|
||||
```js
|
||||
assert(typeof sumsq([1, 2, 3, 4, 5]) == 'number');
|
||||
```
|
||||
|
||||
`sumsq([1, 2, 3, 4, 5])` should return `55`.
|
||||
`sumsq([1, 2, 3, 4, 5])` deve retornar `55`.
|
||||
|
||||
```js
|
||||
assert.equal(sumsq([1, 2, 3, 4, 5]), 55);
|
||||
```
|
||||
|
||||
`sumsq([25, 32, 12, 7, 20])` should return `2242`.
|
||||
`sumsq([25, 32, 12, 7, 20])` deve retornar `2242`.
|
||||
|
||||
```js
|
||||
assert.equal(sumsq([25, 32, 12, 7, 20]), 2242);
|
||||
```
|
||||
|
||||
`sumsq([38, 45, 35, 8, 13])` should return `4927`.
|
||||
`sumsq([38, 45, 35, 8, 13])` deve retornar `4927`.
|
||||
|
||||
```js
|
||||
assert.equal(sumsq([38, 45, 35, 8, 13]), 4927);
|
||||
```
|
||||
|
||||
`sumsq([43, 36, 20, 34, 24])` should return `5277`.
|
||||
`sumsq([43, 36, 20, 34, 24])` deve retornar `5277`.
|
||||
|
||||
```js
|
||||
assert.equal(sumsq([43, 36, 20, 34, 24]), 5277);
|
||||
```
|
||||
|
||||
`sumsq([12, 33, 26, 18, 1, 16, 3])` should return `2499`.
|
||||
`sumsq([12, 33, 26, 18, 1, 16, 3])` deve retornar `2499`.
|
||||
|
||||
```js
|
||||
assert.equal(sumsq([12, 33, 26, 18, 1, 16, 3]), 2499);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8043
|
||||
title: Sum to 100
|
||||
title: Soma até 100
|
||||
challengeType: 5
|
||||
forumTopicId: 302335
|
||||
dashedName: sum-to-100
|
||||
@ -8,33 +8,33 @@ dashedName: sum-to-100
|
||||
|
||||
# --description--
|
||||
|
||||
Find solutions to the *sum to one hundred* puzzle.
|
||||
Encontre soluções para o desafio de *soma até cem*.
|
||||
|
||||
Add (insert) the mathematical operators **+** or **─** (plus or minus) before any of the digits in the decimal numeric string **123456789** such that the resulting mathematical expression adds up to a particular sum (in this iconic case, **100**).
|
||||
Adicione (insira) os operadores matemáticos **+** ou **─** (mais ou menos) antes de cada um dos dígitos na string numérica decimal **123456789**, de modo que a expressão matemática resultante chegue a uma soma específica (no caso conhecido, **100**).
|
||||
|
||||
Example:
|
||||
Exemplo:
|
||||
|
||||
<pre><b>123 + 4 - 5 + 67 - 89 = 100</b></pre>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes a number as parameter. The function should return an array containing all solutions for the given number. The solutions should be strings representing the expressions. For example: "1+23-456+78-9". Sort the array before returning it.
|
||||
Escreva uma função que receba um número como parâmetro. A função deve retornar um array contendo todas as soluções para o número fornecido. As soluções devem ser strings que representam as expressões. Por exemplo: "1+23-456+78-9". Ordene o array resultante antes de retorná-lo.
|
||||
|
||||
# --hints--
|
||||
|
||||
`sumTo100` should be a function.
|
||||
`sumTo100` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof sumTo100 == 'function');
|
||||
```
|
||||
|
||||
`sumTo100(199)` should return an array.
|
||||
`sumTo100(199)` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(sumTo100(199)));
|
||||
```
|
||||
|
||||
`sumTo100(199)` should return `["-1+2-3+45+67+89", "123-4+5+6+78-9", "123-4+56+7+8+9"]`.
|
||||
`sumTo100(199)` deve retornar `["-1+2-3+45+67+89", "123-4+5+6+78-9", "123-4+56+7+8+9"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sumTo100(199), [
|
||||
@ -44,13 +44,13 @@ assert.deepEqual(sumTo100(199), [
|
||||
]);
|
||||
```
|
||||
|
||||
`sumTo100(209)` should return `["1+234+56+7-89"]`.
|
||||
`sumTo100(209)` deve retornar `["1+234+56+7-89"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sumTo100(209), ['1+234+56+7-89']);
|
||||
```
|
||||
|
||||
`sumTo100(243)` should return `["-1-234+567-89", "-12+345+6-7-89", "123+45+6+78-9"]`.
|
||||
`sumTo100(243)` deve retornar `["-1-234+567-89", "-12+345+6-7-89", "123+45+6+78-9"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sumTo100(243), [
|
||||
@ -60,7 +60,7 @@ assert.deepEqual(sumTo100(243), [
|
||||
]);
|
||||
```
|
||||
|
||||
`sumTo100(197)` should return `["1-2-3+45+67+89", "12+34-5+67+89", "123+4-5+6+78-9"]`.
|
||||
`sumTo100(197)` deve retornar `["1-2-3+45+67+89", "12+34-5+67+89", "123+4-5+6+78-9"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(sumTo100(197), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8045
|
||||
title: Sutherland-Hodgman polygon clipping
|
||||
title: Recorte de polígonos de Sutherland-Hodgman
|
||||
challengeType: 5
|
||||
forumTopicId: 302336
|
||||
dashedName: sutherland-hodgman-polygon-clipping
|
||||
@ -8,27 +8,27 @@ dashedName: sutherland-hodgman-polygon-clipping
|
||||
|
||||
# --description--
|
||||
|
||||
The [Sutherland-Hodgman clipping algorithm](https://en.wikipedia.org/wiki/Sutherland-Hodgman clipping algorithm) finds the polygon that is the intersection between an arbitrary polygon (the "subject polygon") and a convex polygon (the "clip polygon"). It is used in computer graphics (especially 2D graphics) to reduce the complexity of a scene being displayed by eliminating parts of a polygon that do not need to be displayed. Take the closed polygon defined by the points:
|
||||
O [algoritmo de recorte de polígonos de Sutherland-Hodgman](https://en.wikipedia.org/wiki/Sutherland-Hodgman clipping algorithm) encontra o polígono que é a intersecção entre um polígono arbitrário (o "polígono sujeito") e um polígono convexo (o "polígono de recorte"). Ele é usado em gráficos de computador (especialmente gráficos 2D) para reduzir a complexidade de uma cena que está sendo exibida eliminando partes de um polígono que não precisam ser exibidas. Pegue o polígono que se fecha definido pelos pontos:
|
||||
|
||||
<pre>[(50, 150), (200, 50), (350, 150), (350, 300), (250, 300), (200, 250), (150, 350), (100, 250), (100, 200)]</pre>
|
||||
|
||||
and clip it by the rectangle defined by the points:
|
||||
e recorte-o pelo retângulo definido pelos pontos:
|
||||
|
||||
<pre>[(100, 100), (300, 100), (300, 300), (100, 300)]</pre>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes 2 arrays as parameters. The first array contains the points of the subject polygon and the second array contains the points of the clipping polygon. The function should return an array containing the points of the clipped polygon. Each number should be rounded to 3 decimal places.
|
||||
Escreva uma função que receba dois arrays como parâmetro. O primeiro array contém os pontos do polígono sujeito e o segundo array contém os pontos do polígono de recorte. A função deve retornar um array contendo os pontos do polígono recortado. Cada número deve ser arredondado para 3 casas decimais.
|
||||
|
||||
# --hints--
|
||||
|
||||
`clip` should be a function.
|
||||
`clip` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof clip == 'function');
|
||||
```
|
||||
|
||||
`clip([[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]], [[100, 100], [300, 100], [300, 300], [100, 300]])` should return an array.
|
||||
`clip([[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]], [[100, 100], [300, 100], [300, 300], [100, 300]])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -56,7 +56,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`clip([[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]], [[100, 100], [300, 100], [300, 300], [100, 300]])` should return `[[100, 116.667], [125, 100], [275, 100], [300, 116.667], [300, 300], [250, 300], [200, 250], [175, 300], [125, 300], [100, 250]]`.
|
||||
`clip([[50, 150], [200, 50], [350, 150], [350, 300], [250, 300], [200, 250], [150, 350], [100, 250], [100, 200]], [[100, 100], [300, 100], [300, 300], [100, 300]])` deve retornar `[[100, 116.667], [125, 100], [275, 100], [300, 116.667], [300, 300], [250, 300], [200, 250], [175, 300], [125, 300], [100, 250]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -94,7 +94,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`clip([[150, 200], [400, 450], [30, 50]], [[10, 10], [300, 200], [400, 600], [100, 300]])` should return `[[150, 200], [350, 400], [348.611, 394.444], [30, 50]]`.
|
||||
`clip([[150, 200], [400, 450], [30, 50]], [[10, 10], [300, 200], [400, 600], [100, 300]])` deve retornar `[[150, 200], [350, 400], [348.611, 394.444], [30, 50]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -120,7 +120,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`clip([[250, 200], [100, 450], [130, 250]], [[50, 60], [100, 230], [400, 600], [100, 300]])` should return `[[129.167, 329.167], [119.565, 319.565], [121.854, 304.305]]`.
|
||||
`clip([[250, 200], [100, 450], [130, 250]], [[50, 60], [100, 230], [400, 600], [100, 300]])` deve retornar `[[129.167, 329.167], [119.565, 319.565], [121.854, 304.305]]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 5a23c84252665b21eecc8046
|
||||
title: Symmetric difference
|
||||
title: Diferença simétrica
|
||||
challengeType: 5
|
||||
forumTopicId: 16086
|
||||
dashedName: symmetric-difference
|
||||
@ -8,21 +8,21 @@ dashedName: symmetric-difference
|
||||
|
||||
# --description--
|
||||
|
||||
Given two [set](https://rosettacode.org/wiki/set)s *A* and *B*, compute $(A \\setminus B) \\cup (B \\setminus A).$ That is, enumerate the items that are in *A* or *B* but not both. This set is called the [symmetric difference](https://en.wikipedia.org/wiki/Symmetric difference) of *A* and *B*. In other words: $(A \\cup B) \\setminus (A \\cap B)$ (the set of items that are in at least one of *A* or *B* minus the set of items that are in both *A* and *B*).
|
||||
Dados dois [conjuntos ](https://rosettacode.org/wiki/set)*A* e *B*, calcule $(A \\setminus B) \\cup (B \\setminus A). Ou seja, enumere os itens que estão em *A* ou *B* mas não em ambos. Este conjunto é chamado de [diferença simétrica](https://pt.wikipedia.org/wiki/Diferen%C3%A7a_sim%C3%A9trica) de *A* e *B*. Em outras palavras: $(A \\cup B) \\setminus (A \\cap B)$ (o conjunto de itens que estão em pelo menos um dos conjuntos, *A* ou *B*, menos o conjunto de itens que estão em ambos, *A* e *B*).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes two arrays as parameters and returns the symmetric difference. Sort the resultant array before returning it.
|
||||
Escreva uma função que receba dois arrays como parâmetros e retorne a diferença simétrica. Ordene o array resultante antes de retorná-lo.
|
||||
|
||||
# --hints--
|
||||
|
||||
`symmetricDifference` should be a function.
|
||||
`symmetricDifference` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof symmetricDifference == 'function');
|
||||
```
|
||||
|
||||
`symmetricDifference(["John", "Bob", "Mary", "Serena"], ["Jim", "Mary", "John", "Bob"])` should return an array.
|
||||
`symmetricDifference(["John", "Bob", "Mary", "Serena"], ["Jim", "Mary", "John", "Bob"])` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(
|
||||
@ -35,7 +35,7 @@ assert(
|
||||
);
|
||||
```
|
||||
|
||||
`symmetricDifference(["John", "Bob", "Mary", "Serena"], ["Jim", "Mary", "John", "Bob"])` should return `["Jim", "Serena"]`.
|
||||
`symmetricDifference(["John", "Bob", "Mary", "Serena"], ["Jim", "Mary", "John", "Bob"])` deve retornar `["Jim", "Serena"]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -47,13 +47,13 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`symmetricDifference([1, 2, 3], [3, 4])` should return `[1, 2, 4]`.
|
||||
`symmetricDifference([1, 2, 3], [3, 4])` deve retornar `[1, 2, 4]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(symmetricDifference([1, 2, 3], [3, 4]), [1, 2, 4]);
|
||||
```
|
||||
|
||||
`symmetricDifference([1, 2, 3, 4, 5], [3, 4, 8, 7])` should return `[1, 2, 5, 7, 8]`.
|
||||
`symmetricDifference([1, 2, 3, 4, 5], [3, 4, 8, 7])` deve retornar `[1, 2, 5, 7, 8]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(symmetricDifference([1, 2, 3, 4, 5], [3, 4, 8, 7]), [
|
||||
@ -65,7 +65,7 @@ assert.deepEqual(symmetricDifference([1, 2, 3, 4, 5], [3, 4, 8, 7]), [
|
||||
]);
|
||||
```
|
||||
|
||||
`symmetricDifference([1, 2, 3, 4, 5, 6, 7, 8], [1, 3, 5, 6, 7, 8, 9])` should return `[2, 4, 9]`.
|
||||
`symmetricDifference([1, 2, 3, 4, 5, 6, 7, 8], [1, 3, 5, 6, 7, 8, 9])` deve retornar `[2, 4, 9]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(
|
||||
@ -74,7 +74,7 @@ assert.deepEqual(
|
||||
);
|
||||
```
|
||||
|
||||
`symmetricDifference([1, 2, 4, 7, 9], [2, 3, 7, 8, 9])` should return `[1, 3, 4, 8]`.
|
||||
`symmetricDifference([1, 2, 4, 7, 9], [2, 3, 7, 8, 9])` deve retornar `[1, 3, 4, 8]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(symmetricDifference([1, 2, 4, 7, 9], [2, 3, 7, 8, 9]), [
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 594ecc0d9a8cf816e3340187
|
||||
title: Taxicab numbers
|
||||
title: Números taxicab
|
||||
challengeType: 5
|
||||
forumTopicId: 302337
|
||||
dashedName: taxicab-numbers
|
||||
@ -8,67 +8,67 @@ dashedName: taxicab-numbers
|
||||
|
||||
# --description--
|
||||
|
||||
A [taxicab number](https://en.wikipedia.org/wiki/Hardy–Ramanujan number "wp: Hardy–Ramanujan number") (the definition that is being used here) is a positive integer that can be expressed as the sum of two positive cubes in more than one way.
|
||||
Um [Número taxicab](https://pt.wikipedia.org/wiki/N%C3%Bamero_taxicab) (a definição que está sendo usada aqui) é um inteiro positivo que pode ser expressado como a soma de dois cubos positivos em mais de uma maneira.
|
||||
|
||||
The first taxicab number is `1729`, which is:
|
||||
O primeiro número taxicab é `1729`, que é:
|
||||
|
||||
1<sup>3</sup> + 12<sup>3</sup> and
|
||||
1<sup>3</sup> + 12<sup>3</sup> e
|
||||
|
||||
9<sup>3</sup> + 10<sup>3</sup>.
|
||||
|
||||
Taxicab numbers are also known as:
|
||||
Os números taxicab também são conhecidos como:
|
||||
|
||||
<ul>
|
||||
<li>taxi numbers</li>
|
||||
<li>taxi-cab numbers</li>
|
||||
<li>taxi cab numbers</li>
|
||||
<li>Hardy-Ramanujan numbers</li>
|
||||
<li>números taxi</li>
|
||||
<li>números taxi-cab</li>
|
||||
<li>números taxi cab</li>
|
||||
<li>Números de Hardy-Ramanujan</li>
|
||||
</ul>
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that returns the lowest `n` taxicab numbers. For each of the taxicab numbers, show the number as well as its constituent cubes.
|
||||
Escreva uma função que retorne o menor número taxicab de `n`. Para cada um dos números taxicab, mostre o número e os cubos que o constituem.
|
||||
|
||||
**See also:**
|
||||
**Veja também:**
|
||||
|
||||
<ul>
|
||||
<li><a href='https://oeis.org/A001235' target='_blank'>A001235 taxicab numbers</a> on The On-Line Encyclopedia of Integer Sequences.</li>
|
||||
<li><a href='https://en.wikipedia.org/wiki/Taxicab_number' target='_blank'>taxicab number</a> on Wikipedia.</li>
|
||||
<li><a href='https://oeis.org/A001235' target='_blank'>A001235 números taxicab</a> na The On-Line Encyclopedia of Integer Sequences.</li>
|
||||
<li><a href='https://pt.wikipedia.org/wiki/N%C3%Bamero_taxicab' target='_blank'>Número taxicab</a> na Wikipédia.</li>
|
||||
</ul>
|
||||
|
||||
# --hints--
|
||||
|
||||
`taxicabNumbers` should be a function.
|
||||
`taxicabNumbers` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof taxicabNumbers === 'function');
|
||||
```
|
||||
|
||||
`taxicabNumbers` should return an array.
|
||||
`taxicabNumbers` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(typeof taxicabNumbers(2) === 'object');
|
||||
```
|
||||
|
||||
`taxicabNumbers` should return an array of numbers.
|
||||
`taxicabNumbers` deve retornar um array de números.
|
||||
|
||||
```js
|
||||
assert(typeof taxicabNumbers(100)[0] === 'number');
|
||||
```
|
||||
|
||||
`taxicabNumbers(4)` should return [1729, 4104, 13832, 20683].
|
||||
`taxicabNumbers(4)` deve retornar [1729, 4104, 13832, 20683].
|
||||
|
||||
```js
|
||||
assert.deepEqual(taxicabNumbers(4), res4);
|
||||
```
|
||||
|
||||
`taxicabNumbers(25)` should return [1729, 4104, 13832, 20683, 32832, 39312, 40033, 46683, 64232, 65728, 110656, 110808, 134379, 149389, 165464, 171288, 195841, 216027, 216125, 262656, 314496, 320264, 327763, 373464, 402597]
|
||||
`taxicabNumbers(25)` deve retornar [1729, 4104, 13832, 20683, 32832, 39312, 40033, 46683, 64232, 65728, 110656, 110808, 134379, 149389, 165464, 171288, 195841, 216027, 216125, 2656, 314496, 320264, 327763, 373464, 402597]
|
||||
|
||||
```js
|
||||
assert.deepEqual(taxicabNumbers(25), res25);
|
||||
```
|
||||
|
||||
`taxicabNumbers(39)` resulting numbers from 20 - 29 should be [314496,320264,327763,373464,402597,439101,443889,513000,513856].
|
||||
`taxicabNumbers(39)` resultando números de 20 - 29 devem ser [314496,320264,327763,373464,402597,439101,443889,513000,513856].
|
||||
|
||||
```js
|
||||
assert.deepEqual(taxicabNumbers(39).slice(20, 29), res39From20To29);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 594faaab4e2a8626833e9c3d
|
||||
title: Tokenize a string with escaping
|
||||
title: Tokenizar uma string com escape
|
||||
challengeType: 5
|
||||
forumTopicId: 302338
|
||||
dashedName: tokenize-a-string-with-escaping
|
||||
@ -8,65 +8,65 @@ dashedName: tokenize-a-string-with-escaping
|
||||
|
||||
# --description--
|
||||
|
||||
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
|
||||
Escreva uma função ou programa que possa dividir uma string em cada ocorrência sem escape de um caractere separador.
|
||||
|
||||
It should accept three input parameters:
|
||||
Ela deve aceitar três parâmetros de entrada:
|
||||
|
||||
<ul>
|
||||
<li>The <strong>string</strong></li>
|
||||
<li>The <strong>separator character</strong></li>
|
||||
<li>The <strong>escape character</strong></li>
|
||||
<li>A <strong>string</strong></li>
|
||||
<li>O <strong>caractere separador</strong></li>
|
||||
<li>O <strong>caractere de escape</strong></li>
|
||||
</ul>
|
||||
|
||||
It should output a list of strings.
|
||||
Ela deve ter como saída uma lista de strings.
|
||||
|
||||
Rules for splitting:
|
||||
Regras para a divisão:
|
||||
|
||||
<ul>
|
||||
<li>The fields that were separated by the separators, become the elements of the output list.</li>
|
||||
<li>Empty fields should be preserved, even at the start and end.</li>
|
||||
<li>Os campos que foram separados pelos separadores se tornam os elementos da lista de saída.</li>
|
||||
<li>Campos vazios devem ser preservados, mesmo no início e no fim.</li>
|
||||
</ul>
|
||||
|
||||
Rules for escaping:
|
||||
Regras para o escape:
|
||||
|
||||
<ul>
|
||||
<li>"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.</li>
|
||||
<li>When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).</li>
|
||||
<li>Each occurrences of the escape character that was used to escape something, should not become part of the output.</li>
|
||||
<li>Com "escape" significa precedido por uma ocorrência do caractere de escape, que já não estiver escapado por si mesmo.</li>
|
||||
<li>Quando o caractere de escape preceder um caractere que não tem nenhum significado especial, ele ainda conta como um escape (mas não faz nada especial).</li>
|
||||
<li>Cada ocorrência do caractere de escape que for usada para fazer o escape de algo não deve se tornar parte do resultado.</li>
|
||||
</ul>
|
||||
|
||||
Demonstrate that your function satisfies the following test-case:
|
||||
Demonstre que sua função satisfaz o seguinte caso de teste:
|
||||
|
||||
Given the string
|
||||
Dada a string
|
||||
|
||||
<pre>one^|uno||three^^^^|four^^^|^cuatro|</pre>
|
||||
|
||||
and using `|` as a separator and `^` as escape character, your function should output the following array:
|
||||
e usando `|` como separador e `^` como caractere de escape, a função deve dar como resultado o seguinte array:
|
||||
|
||||
<pre> ['one|uno', '', 'three^^', 'four^|cuatro', '']
|
||||
</pre>
|
||||
|
||||
# --hints--
|
||||
|
||||
`tokenize` should be a function.
|
||||
`tokenize` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof tokenize === 'function');
|
||||
```
|
||||
|
||||
`tokenize` should return an array.
|
||||
`tokenize` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(typeof tokenize('a', 'b', 'c') === 'object');
|
||||
```
|
||||
|
||||
`tokenize('one^|uno||three^^^^|four^^^|^cuatro|', '|', '^')` should return `['one|uno', '', 'three^^', 'four^|cuatro', '']`
|
||||
`tokenize('one^|uno||three^^^^|four^^^|^cuatro|', '|', '^')` deve retornar `['one|uno', '', 'three^^', 'four^|cuatro', '']`
|
||||
|
||||
```js
|
||||
assert.deepEqual(tokenize(testStr1, '|', '^'), res1);
|
||||
```
|
||||
|
||||
`tokenize('a@&bcd&ef&&@@hi', '&', '@')` should return `['a&bcd', 'ef', '', '@hi']`
|
||||
`tokenize('a@&bcd&ef&&@@hi', '&', '@')` deve retornar `['a&bcd', 'ef', '', '@hi']`
|
||||
|
||||
```js
|
||||
assert.deepEqual(tokenize(testStr2, '&', '@'), res2);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 594fa2746886f41f7d8bf225
|
||||
title: Topological sort
|
||||
title: Ordenação topológica
|
||||
challengeType: 5
|
||||
forumTopicId: 302340
|
||||
dashedName: topological-sort
|
||||
@ -8,22 +8,22 @@ dashedName: topological-sort
|
||||
|
||||
# --description--
|
||||
|
||||
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon. There are two popular algorithms for topological sorting: Kahn's (1962) topological sort and depth-first search.
|
||||
Dado um mapeamento entre itens e itens dos quais eles dependem, uma ordenação topológica de itens faz com que nenhum item preceda um item do qual ele depende. Existem dois algoritmos populares para a ordenação topológica: a ordenação topológica de Kahn (1962) e a busca profunda.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that will return a list with valid compile order of libraries from their dependencies.
|
||||
Escreva uma função que retorne uma lista com ordem de compilação válida de bibliotecas a partir de suas dependências.
|
||||
|
||||
- Assume library names are single words.
|
||||
- Items mentioned as only dependents have no dependents of their own, but their order of compiling must be given.
|
||||
- Any self dependencies should be ignored.
|
||||
- Any un-orderable dependencies should be ignored.
|
||||
- Assuma que os nomes das bibliotecas são palavras únicas.
|
||||
- Itens mencionados apenas como dependentes não têm dependentes próprios, mas sua ordem de compilação deve ser dada.
|
||||
- Quaisquer autodependências devem ser ignoradas.
|
||||
- Quaisquer dependências não ordenáveis devem ser ignoradas.
|
||||
|
||||
Use the following data as an example:
|
||||
Use os seguintes dados como exemplo:
|
||||
|
||||
<pre>
|
||||
LIBRARY LIBRARY DEPENDENCIES
|
||||
======= ====================
|
||||
BIBLIOTECA DEPENDÊNCIAS
|
||||
========== ====================
|
||||
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
|
||||
dw01 ieee dw01 dware gtech
|
||||
dw02 ieee dw02 dware
|
||||
@ -39,11 +39,11 @@ std_cell_lib ieee std_cell_lib
|
||||
synopsys
|
||||
</pre>
|
||||
|
||||
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on. The above data would be un-orderable if, for example, `dw04` is added to the list of dependencies of `dw01`.
|
||||
A compilação de uma biblioteca na linguagem VHDL tem a restrição de que uma biblioteca deve ser compilada após qualquer biblioteca da qual ela dependa. Os dados acima seriam não ordenáveis se, por exemplo, `dw04` fosse adicionado à lista de dependências de `dw01`.
|
||||
|
||||
The input of the function will be a multiline string, each line will consist of the name of the library, followed by its dependencies (if exist).
|
||||
A entrada da função será uma string em várias linhas. Cada linha será composta pelo nome da biblioteca, seguida por suas dependências (se existirem).
|
||||
|
||||
For example:
|
||||
Por exemplo:
|
||||
|
||||
```js
|
||||
const libsSimple =
|
||||
@ -53,37 +53,37 @@ const libsSimple =
|
||||
|
||||
# --hints--
|
||||
|
||||
`topologicalSort` should be a function.
|
||||
`topologicalSort` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert(typeof topologicalSort === 'function');
|
||||
```
|
||||
|
||||
`topologicalSort(libsSimple)` should return an array.
|
||||
`topologicalSort(libsSimple)` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(topologicalSort(libsSimple)));
|
||||
```
|
||||
|
||||
`topologicalSort(libsSimple)` should return `['bbb', 'aaa']`.
|
||||
`topologicalSort(libsSimple)` deve retornar `['bbb', 'aaa']`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(topologicalSort(libsSimple), ['bbb', 'aaa']);
|
||||
```
|
||||
|
||||
`topologicalSort(libsVHDL)` should return `['ieee', 'std_cell_lib', 'gtech', 'dware', 'dw07', 'dw06', 'dw05', 'dw02', 'dw01', 'dw04', 'std', 'ramlib', 'synopsys', 'dw03', 'des_system_lib']`.
|
||||
`topologicalSort(libsVHDL)` deve retornar `['ieee', 'std_cell_lib', 'gtech', 'dware', 'dw07', 'dw06', 'dw05', 'dw02', 'dw01', 'dw04', 'std', 'ramlib', 'synopsys', 'dw03', 'des_system_lib']`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(topologicalSort(libsVHDL), ['ieee', 'std_cell_lib', 'gtech', 'dware', 'dw07', 'dw06', 'dw05', 'dw02', 'dw01', 'dw04', 'std', 'ramlib', 'synopsys', 'dw03', 'des_system_lib']);
|
||||
```
|
||||
|
||||
`topologicalSort(libsCustom)` should return `['base', 'c', 'd', 'b', 'a']`.
|
||||
`topologicalSort(libsCustom)` deve retornar `['base', 'c', 'd', 'b', 'a']`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(topologicalSort(libsCustom), ['base', 'c', 'd', 'b', 'a']);
|
||||
```
|
||||
|
||||
`topologicalSort` should ignore unorderable dependencies.
|
||||
`topologicalSort` deve ignorar dependências não ordenáveis.
|
||||
|
||||
```js
|
||||
assert.deepEqual(topologicalSort(libsUnorderable), ['Base']);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 594810f028c0303b75339ad2
|
||||
title: Vector cross product
|
||||
title: Produto cruzado de vetor
|
||||
challengeType: 5
|
||||
forumTopicId: 302342
|
||||
dashedName: vector-cross-product
|
||||
@ -8,27 +8,27 @@ dashedName: vector-cross-product
|
||||
|
||||
# --description--
|
||||
|
||||
A vector is defined as having three dimensions as being represented by an ordered collection of three numbers: (X, Y, Z).
|
||||
Um vetor é definido como tendo três dimensões e sendo representado por uma coleção ordenada de três números: (X, Y, Z).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes two vectors (arrays) as input and computes their cross product. Your function should return `null` on invalid inputs such as vectors of different lengths.
|
||||
Escreva uma função que receba dois vetores (arrays) como entrada e calcule seu produto cruzado. A função deve retornar `null` em entradas inválidas, como vetores de diferentes tamanhos.
|
||||
|
||||
# --hints--
|
||||
|
||||
`crossProduct` should be a function.
|
||||
`crossProduct` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert.equal(typeof crossProduct, 'function');
|
||||
```
|
||||
|
||||
`crossProduct()` should return null.
|
||||
`crossProduct()` deve retornar null.
|
||||
|
||||
```js
|
||||
assert.equal(crossProduct(), null);
|
||||
```
|
||||
|
||||
`crossProduct([1, 2, 3], [4, 5, 6])` should return `[-3, 6, -3]`.
|
||||
`crossProduct([1, 2, 3], [4, 5, 6])` deve retornar `[-3, 6, -3]`.
|
||||
|
||||
```js
|
||||
assert.deepEqual(res12, exp12);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 594810f028c0303b75339ad3
|
||||
title: Vector dot product
|
||||
title: Produto de ponto de vetor
|
||||
challengeType: 5
|
||||
forumTopicId: 302343
|
||||
dashedName: vector-dot-product
|
||||
@ -8,51 +8,51 @@ dashedName: vector-dot-product
|
||||
|
||||
# --description--
|
||||
|
||||
A vector can have one or more values represented by an ordered collection. Examples could be (x), (x, y), or (x, y, z).
|
||||
Um vetor pode ter um ou mais valores representados por uma coleção ordenada. Exemplos podem ser (x), (x, y), ou (x, y, z).
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes two vectors (represented as one-dimensional arrays) as input and computes their dot product. Your function should return `null` on invalid inputs such as vectors of different lengths or passing anything other than two vectors.
|
||||
Escreva uma função que receba dois vetores (representados como arrays unidimensionais) como entrada e calcule seu produto cruzado. A função deve retornar `null` para entradas inválidas como vetores de tamanhos diferentes ou que passem qualquer coisa que não seja dois vetores.
|
||||
|
||||
# --hints--
|
||||
|
||||
`dotProduct` should be a function.
|
||||
`dotProduct` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert.equal(typeof dotProduct, 'function');
|
||||
```
|
||||
|
||||
`dotProduct()` should return `null`.
|
||||
`dotProduct()` deve retornar `null`.
|
||||
|
||||
```js
|
||||
assert.equal(dotProduct(), null);
|
||||
```
|
||||
|
||||
`dotProduct([1], [1])` should return `1`.
|
||||
`dotProduct([1], [1])` deve retornar `1`.
|
||||
|
||||
```js
|
||||
assert.equal(dotProduct([1], [1]), 1);
|
||||
```
|
||||
|
||||
`dotProduct([1], [1, 2])` should return `null`.
|
||||
`dotProduct([1], [1, 2])` deve retornar `null`.
|
||||
|
||||
```js
|
||||
assert.equal(dotProduct([1], [1, 2]), null);
|
||||
```
|
||||
|
||||
`dotProduct([1, 3, -5], [4, -2, -1])` should return `3`.
|
||||
`dotProduct([1, 3, -5], [4, -2, -1])` deve retornar `3`.
|
||||
|
||||
```js
|
||||
assert.equal(dotProduct([1, 3, -5], [4, -2, -1]), 3);
|
||||
```
|
||||
|
||||
`dotProduct([3, 2, 1], [2, 4, 2], [5, 3, 1])` should return `null`.
|
||||
`dotProduct([3, 2, 1], [2, 4, 2], [5, 3, 1])` deve retornar `null`.
|
||||
|
||||
```js
|
||||
assert.equal(dotProduct([3, 2, 1], [2, 4, 2], [5, 3, 1]), null);
|
||||
```
|
||||
|
||||
`dotProduct([ 0, 3, 6, 9, 12 ], [ 0, 4, 8, 12, 16 ])` should return `360`.
|
||||
`dotProduct([ 0, 3, 6, 9, 12 ], [ 0, 4, 8, 12, 16 ])` deve retornar `360`.
|
||||
|
||||
```js
|
||||
assert.equal(dotProduct([ 0, 3, 6, 9, 12 ], [ 0, 4, 8, 12, 16 ]), 360);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 594810f028c0303b75339ad5
|
||||
title: Y combinator
|
||||
title: Combinador Y
|
||||
challengeType: 5
|
||||
forumTopicId: 302345
|
||||
dashedName: y-combinator
|
||||
@ -8,11 +8,11 @@ dashedName: y-combinator
|
||||
|
||||
# --description--
|
||||
|
||||
In strict [functional programming](https://en.wikipedia.org/wiki/Functional programming "wp: functional programming") and the [lambda calculus](https://en.wikipedia.org/wiki/lambda calculus "wp: lambda calculus"), functions (lambda expressions) don't have state and are only allowed to refer to arguments of enclosing functions. This rules out the usual definition of a recursive function wherein a function is associated with the state of a variable and this variable's state is used in the body of the function. The [Y combinator](https://mvanier.livejournal.com/2897.html) is itself a stateless function that, when applied to another stateless function, returns a recursive version of the function. The Y combinator is the simplest of the class of such functions, called [fixed-point combinators](https://en.wikipedia.org/wiki/Fixed-point combinator "wp: fixed-point combinator").
|
||||
Em [programação funcional](https://en.wikipedia.org/wiki/Functional programming "wp: functional programming") estrita e em [cálculo de lambda](https://en.wikipedia.org/wiki/lambda calculus "wp: lambda calculus"), funções (expressões lambda) não têm estado e é permitido apenas se referir a argumentos de funções encapsuladas. Isso exclui a definição habitual de uma função recursiva, na qual uma função é associada ao estado de uma variável e o estado dessa variável é usado no corpo da função. O [combinador Y](https://mvanier.livejournal.com/2897.html) é uma função sem estado que, ao ser aplicada a outra função sem estado, retorna uma versão recursiva da função. O combinador Y é a mais simples dessas classes de funções, chamada de [combinador de ponto fixo](https://en.wikipedia.org/wiki/Fixed-point combinator "wp: fixed-point combinator").
|
||||
|
||||
# --instructions--
|
||||
|
||||
Define the stateless Y combinator function and use it to compute [factorial](https://en.wikipedia.org/wiki/Factorial "wp: factorial"). The `factorial(N)` function is already given to you. **See also:**
|
||||
Defina a função de combinador Y sem estado e use-a para calcular o [fatorial](https://en.wikipedia.org/wiki/Factorial "wp: factorial"). A função de fatorial, `factorial(N)`, você já tem. **Consulte também:**
|
||||
|
||||
<ul>
|
||||
<li><a href="https://vimeo.com/45140590" target="_blank">Jim Weirich: Adventures in Functional Programming</a>.</li>
|
||||
@ -20,37 +20,37 @@ Define the stateless Y combinator function and use it to compute [factorial](htt
|
||||
|
||||
# --hints--
|
||||
|
||||
Y should return a function.
|
||||
Y deve retornar uma função.
|
||||
|
||||
```js
|
||||
assert.equal(typeof Y((f) => (n) => n), 'function');
|
||||
```
|
||||
|
||||
factorial(1) should return 1.
|
||||
factorial(1) deve retornar 1.
|
||||
|
||||
```js
|
||||
assert.equal(factorial(1), 1);
|
||||
```
|
||||
|
||||
factorial(2) should return 2.
|
||||
factorial(2) deve retornar 2.
|
||||
|
||||
```js
|
||||
assert.equal(factorial(2), 2);
|
||||
```
|
||||
|
||||
factorial(3) should return 6.
|
||||
factorial(3) deve retornar 6.
|
||||
|
||||
```js
|
||||
assert.equal(factorial(3), 6);
|
||||
```
|
||||
|
||||
factorial(4) should return 24.
|
||||
factorial(4) deve retornar 24.
|
||||
|
||||
```js
|
||||
assert.equal(factorial(4), 24);
|
||||
```
|
||||
|
||||
factorial(10) should return 3628800.
|
||||
factorial(10) deve retornar 3628800.
|
||||
|
||||
```js
|
||||
assert.equal(factorial(10), 3628800);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 594810f028c0303b75339ad6
|
||||
title: Zeckendorf number representation
|
||||
title: Representação do número de Zeckendorf
|
||||
challengeType: 5
|
||||
forumTopicId: 302346
|
||||
dashedName: zeckendorf-number-representation
|
||||
@ -8,144 +8,144 @@ dashedName: zeckendorf-number-representation
|
||||
|
||||
# --description--
|
||||
|
||||
Just as numbers can be represented in a positional notation as sums of multiples of the powers of ten (decimal) or two (binary); all the positive integers can be represented as the sum of one or zero times the distinct members of the Fibonacci series. Recall that the first six distinct Fibonacci numbers are: `1, 2, 3, 5, 8, 13`.
|
||||
Assim como os números podem ser representados em uma notação posicional como somas de múltiplos das potências de dez (decimal) ou de dois (binário), todos os números inteiros positivos podem ser representados como a soma de um ou zero vezes os diferentes membros da série Fibonacci. Lembre-se de que os primeiros seis números de Fibonacci distintos são: `1, 2, 3, 5, 8, 13`.
|
||||
|
||||
The decimal number eleven can be written as `0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1` or `010100` in positional notation where the columns represent multiplication by a particular member of the sequence. Leading zeroes are dropped so that 11 decimal becomes `10100`. 10100 is not the only way to make 11 from the Fibonacci numbers however `0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1` or 010011 would also represent decimal 11. For a true Zeckendorf number there is the added restriction that *no two consecutive Fibonacci numbers can be used* which leads to the former unique solution.
|
||||
O número decimal onze pode ser escrito como `0*13 + 1*8 + 0*5 + 1*3 + 0*2 + 0*1` ou `010100` na notação posicional, onde as colunas representam a multiplicação por um determinado membro da sequência. Zeros à esquerda são descartados para que o número 11 decimal se torne `10100`. Porém, 10100 não é a única maneira de representar 11 nos números de Fibonacci. `0*13 + 1*8 + 0*5 + 0*3 + 1*2 + 1*1` ou 010011 também representaria o 11 decimal. Para um número de Zeckendorf verdadeiro, há a restrição adicional de que *não sejam usados dois números de Fibonacci consecutivos*, o que leva à antiga solução única.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that generates and returns the Zeckendorf number representation of `n`.
|
||||
Escreva uma função que gere e retorne a representação do número de Zeckendorf de `n`.
|
||||
|
||||
# --hints--
|
||||
|
||||
`zeckendorf` should be a function.
|
||||
`zeckendorf` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert.equal(typeof zeckendorf, 'function');
|
||||
```
|
||||
|
||||
`zeckendorf(0)` should return `0`.
|
||||
`zeckendorf(0)` deve retornar `0`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(0), 0);
|
||||
|
||||
```
|
||||
|
||||
`zeckendorf(1)` should return `1`.
|
||||
`zeckendorf(1)` deve retornar `1`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(1), 1);
|
||||
```
|
||||
|
||||
`zeckendorf(2)` should return `10`.
|
||||
`zeckendorf(2)` deve retornar `10`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(2), 10);
|
||||
```
|
||||
|
||||
`zeckendorf(3)` should return `100`.
|
||||
`zeckendorf(3)` deve retornar `100`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(3), 100);
|
||||
```
|
||||
|
||||
`zeckendorf(4)` should return `101`.
|
||||
`zeckendorf(4)` deve retornar `101`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(4), 101);
|
||||
```
|
||||
|
||||
`zeckendorf(5)` should return `1000`.
|
||||
`zeckendorf(5)` deve retornar `1000`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(5), 1000);
|
||||
```
|
||||
|
||||
`zeckendorf(6)` should return `1001`.
|
||||
`zeckendorf(6)` deve retornar `1001`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(6), 1001);
|
||||
```
|
||||
|
||||
`zeckendorf(7)` should return `1010`.
|
||||
`zeckendorf(7)` deve retornar `1010`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(7), 1010);
|
||||
```
|
||||
|
||||
`zeckendorf(8)` should return `10000`.
|
||||
`zeckendorf(8)` deve retornar `10000`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(8), 10000);
|
||||
```
|
||||
|
||||
`zeckendorf(9)` should return `10001`.
|
||||
`zeckendorf(9)` deve retornar `10001`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(9), 10001);
|
||||
```
|
||||
|
||||
`zeckendorf(10)` should return `10010`.
|
||||
`zeckendorf(10)` deve retornar `10010`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(10), 10010);
|
||||
```
|
||||
|
||||
`zeckendorf(11)` should return `10100`.
|
||||
`zeckendorf(11)` deve retornar `10100`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(11), 10100);
|
||||
```
|
||||
|
||||
`zeckendorf(12)` should return `10101`.
|
||||
`zeckendorf(12)` deve retornar `10101`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(12), 10101);
|
||||
```
|
||||
|
||||
`zeckendorf(13)` should return `100000`.
|
||||
`zeckendorf(13)` deve retornar `100000`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(13), 100000);
|
||||
```
|
||||
|
||||
`zeckendorf(14)` should return `100001`.
|
||||
`zeckendorf(14)` deve retornar `100001`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(14), 100001);
|
||||
```
|
||||
|
||||
`zeckendorf(15)` should return `100010`.
|
||||
`zeckendorf(15)` deve retornar `100010`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(15), 100010);
|
||||
```
|
||||
|
||||
`zeckendorf(16)` should return `100100`.
|
||||
`zeckendorf(16)` deve retornar `100100`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(16), 100100);
|
||||
```
|
||||
|
||||
`zeckendorf(17)` should return `100101`.
|
||||
`zeckendorf(17)` deve retornar `100101`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(17), 100101);
|
||||
```
|
||||
|
||||
`zeckendorf(18)` should return `101000`.
|
||||
`zeckendorf(18)` deve retornar `101000`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(18), 101000);
|
||||
```
|
||||
|
||||
`zeckendorf(19)` should return `101001`.
|
||||
`zeckendorf(19)` deve retornar `101001`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(19), 101001);
|
||||
```
|
||||
|
||||
`zeckendorf(20)` should return `101010`.
|
||||
`zeckendorf(20)` deve retornar `101010`.
|
||||
|
||||
```js
|
||||
assert.equal(zeckendorf(20), 101010);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 594810f028c0303b75339ad7
|
||||
title: Zhang-Suen thinning algorithm
|
||||
title: Algoritmo de afinamento de Zhang-Suen
|
||||
challengeType: 5
|
||||
forumTopicId: 302347
|
||||
dashedName: zhang-suen-thinning-algorithm
|
||||
@ -8,7 +8,7 @@ dashedName: zhang-suen-thinning-algorithm
|
||||
|
||||
# --description--
|
||||
|
||||
This is an algorithm used to thin a black and white i.e. one bit per pixel images. For example, with an input image of:
|
||||
Este é um algoritmo usado para afinar imagens em preto e branco, ou seja, imagens de um bit por pixel. Por exemplo, com uma imagem de entrada de:
|
||||
|
||||
```js
|
||||
const testImage1 = [
|
||||
@ -25,7 +25,7 @@ const testImage1 = [
|
||||
];
|
||||
```
|
||||
|
||||
It produces the thinned output:
|
||||
Ele produz a saída fina:
|
||||
|
||||
```js
|
||||
[ ' ',
|
||||
@ -40,76 +40,76 @@ It produces the thinned output:
|
||||
' ' ];
|
||||
```
|
||||
|
||||
## Algorithm
|
||||
## Algoritmo
|
||||
|
||||
Assume black pixels are one and white pixels zero, and that the input image is a rectangular N by M array of ones and zeroes. The algorithm operates on all black pixels P1 that can have eight neighbours. The neighbours are, in order, arranged as:
|
||||
Suponha que os pixels pretos são um e os pixels brancos são zeros. Leve em conta também que a imagem de entrada é um array retangular, de N por M, de uns e zeros. O algoritmo opera em todos os pixels pretos P1 que podem ter oito vizinhos. Os vizinhos estão, por ordem, organizados como:
|
||||
|
||||
$$\begin{array}{|c|c|c|} \\hline P9 & P2 & P3\\\\ \\hline P8 & \boldsymbol{P1} & P4\\\\ \\hline P7 & P6 & P5\\\\ \\hline \end{array}$$
|
||||
|
||||
Obviously the boundary pixels of the image cannot have the full eight neighbours.
|
||||
Obviamente que os pixels da borda da imagem não podem ter todos os oito vizinhos.
|
||||
|
||||
- Define $A(P1)$ = the number of transitions from white to black, ($0 \to 1$) in the sequence P2, P3, P4, P5, P6, P7, P8, P9, P2. (Note the extra P2 at the end - it is circular).
|
||||
- Define $B(P1)$ = the number of black pixel neighbours of P1. ($= \\sum(P2 \ldots P9)$)
|
||||
- Defina $A(P1)$ = o número de transições de branco para preto, ($0 \to 1$) na sequência P2, P3, P4, P5, P6, P7, P8, P9, P2. (Observe o P2 adicional no final - é circular).
|
||||
- Defina $B(P1)$ = o número de vizinhos de P1 que são pixels pretos. ($= \\sum(P2 \ldots P9)$)
|
||||
|
||||
**Step 1:**
|
||||
**Passo 1:**
|
||||
|
||||
All pixels are tested and pixels satisfying all the following conditions (simultaneously) are just noted at this stage.
|
||||
Todos os pixels são testados e pixels satisfazendo todas as seguintes condições (simultaneamente) são apenas anotados nesta fase.
|
||||
|
||||
1. The pixel is black and has eight neighbours
|
||||
1. O pixel é preto e tem oito vizinhos
|
||||
2. $2 \le B(P1) \le 6$
|
||||
3. $A(P1) = 1$
|
||||
4. At least one of $P2$, $P4$ and $P6$ is white
|
||||
5. At least one of $P4$, $P6$ and $P8$ is white
|
||||
4. Pelo menos um dos pixels, entre $P2$, $P4$ e $P6$, é branco
|
||||
5. Pelo menos um dos pixels, entre $P4$, $P6$ e $P8$, é branco
|
||||
|
||||
After iterating over the image and collecting all the pixels satisfying all step 1 conditions, all these condition satisfying pixels are set to white.
|
||||
Depois de iterar sobre a imagem e coletar todos os pixels satisfazendo todas as condições do passo 1, todos estes pixels que satisfazem as condições são definidos como brancos.
|
||||
|
||||
**Step 2:**
|
||||
**Passo 2:**
|
||||
|
||||
All pixels are again tested and pixels satisfying all the following conditions are just noted at this stage.
|
||||
Todos os pixels são testados novamente e pixels satisfazendo todas as seguintes condições (simultaneamente) são apenas anotados nesta fase.
|
||||
|
||||
1. The pixel is black and has eight neighbours
|
||||
1. O pixel é preto e tem oito vizinhos
|
||||
2. $2 \le B(P1) \le 6$
|
||||
3. $A(P1) = 1$
|
||||
4. At least one of $P2$, $P4$ and $P8$ is white
|
||||
5. At least one of $P2$, $P6$ and $P8$ is white
|
||||
4. Pelo menos um dos pixels, entre $P2$, $P4$ e $P8$, é branco
|
||||
5. Pelo menos um dos pixels, entre $P2$, $P6$ e $P8$, é branco
|
||||
|
||||
After iterating over the image and collecting all the pixels satisfying all step 2 conditions, all these condition satisfying pixels are again set to white.
|
||||
Depois de iterar sobre a imagem e coletar todos os pixels satisfazendo todas as condições do passo 2, todos estes pixels que satisfazem as condições são definidos novamente como brancos.
|
||||
|
||||
**Iteration:**
|
||||
**Iteração:**
|
||||
|
||||
If any pixels were set in this round of either step 1 or step 2 then all steps are repeated until no image pixels are so changed.
|
||||
Se qualquer pixel for definido nessa rodada dos passos 1 ou 2, então todos os passos são repetidos até que nenhum pixels da imagem seja mudado.
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a routine to perform Zhang-Suen thinning on the provided `image`, an array of strings, where each string represents single line of the image. In the string, `#` represents black pixel, and whitespace represents white pixel. Function should return thinned image, using the same representation.
|
||||
Escreva uma rotina que realize o afinamento de Zhang-Suen na `image` fornecida, um array de strings, onde cada string representa uma única linha da imagem. Na string, `#` representa um pixel preto e espaço em branco representa um pixel branco. A função deve retornar a imagem fina, usando a mesma representação.
|
||||
|
||||
# --hints--
|
||||
|
||||
`thinImage` should be a function.
|
||||
`thinImage` deve ser uma função.
|
||||
|
||||
```js
|
||||
assert.equal(typeof thinImage, 'function');
|
||||
```
|
||||
|
||||
`thinImage` should return an array.
|
||||
`thinImage` deve retornar um array.
|
||||
|
||||
```js
|
||||
assert(Array.isArray(thinImage(_testImage1)));
|
||||
```
|
||||
|
||||
`thinImage` should return an array of strings.
|
||||
`thinImage` deve retornar um array de strings.
|
||||
|
||||
```js
|
||||
assert.equal(typeof thinImage(_testImage1)[0], 'string');
|
||||
```
|
||||
|
||||
`thinImage(testImage1)` should return a thinned image as in the example.
|
||||
`thinImage(testImage1)` deve retornar uma imagem fina como no exemplo.
|
||||
|
||||
```js
|
||||
assert.deepEqual(thinImage(_testImage1), expected1);
|
||||
```
|
||||
|
||||
`thinImage(testImage2)` should return a thinned image.
|
||||
`thinImage(testImage2)` deve retornar uma imagem fina.
|
||||
|
||||
```js
|
||||
assert.deepEqual(thinImage(_testImage2), expected2);
|
||||
|
@ -1,6 +1,6 @@
|
||||
---
|
||||
id: 594810f028c0303b75339ad8
|
||||
title: Zig-zag matrix
|
||||
title: Matriz de zigue-zague
|
||||
challengeType: 5
|
||||
forumTopicId: 302348
|
||||
dashedName: zig-zag-matrix
|
||||
@ -8,9 +8,9 @@ dashedName: zig-zag-matrix
|
||||
|
||||
# --description--
|
||||
|
||||
A 'zig-zag' array is a square arrangement of the first $N^2$ integers, where the numbers increase sequentially as you zig-zag along the array's [anti-diagonals](https://en.wiktionary.org/wiki/antidiagonal).
|
||||
Uma matriz 'zig-zag' é um arranjo quadrado dos primeiros $N^2$ inteiros, onde os números crescem sequencialmente à medida que você percorre em zigue-zague ao longo das [antidiagonais](https://en.wiktionary.org/wiki/antidiagonal) da matriz.
|
||||
|
||||
For example, for the input `5`, the following result should be produced:
|
||||
Por exemplo, para a entrada `5`, o seguinte resultado deve ser produzido:
|
||||
|
||||
<pre>
|
||||
0 1 5 6 14
|
||||
@ -22,41 +22,41 @@ For example, for the input `5`, the following result should be produced:
|
||||
|
||||
# --instructions--
|
||||
|
||||
Write a function that takes the size of the zig-zag matrix, and returns the corresponding matrix as two-dimensional array.
|
||||
Escreva uma função que receba o tamanho da matriz em zigue-zague, e retorne a matriz correspondente como matriz bidimensional.
|
||||
|
||||
# --hints--
|
||||
|
||||
ZigZagMatrix should be a function.
|
||||
ZigZagMatrix deve ser uma função.
|
||||
|
||||
```js
|
||||
assert.equal(typeof ZigZagMatrix, 'function');
|
||||
```
|
||||
|
||||
ZigZagMatrix should return array.
|
||||
ZigZagMatrix deve retornar matriz.
|
||||
|
||||
```js
|
||||
assert.equal(typeof ZigZagMatrix(1), 'object');
|
||||
```
|
||||
|
||||
ZigZagMatrix should return an array of nested arrays.
|
||||
ZigZagMatrix deve retornar uma matriz de matrizes aninhadas.
|
||||
|
||||
```js
|
||||
assert.equal(typeof ZigZagMatrix(1)[0], 'object');
|
||||
```
|
||||
|
||||
ZigZagMatrix(1) should return \[[0]].
|
||||
ZigZagMatrix(1) deve retornar \[[0]].
|
||||
|
||||
```js
|
||||
assert.deepEqual(ZigZagMatrix(1), zm1);
|
||||
```
|
||||
|
||||
ZigZagMatrix(2) should return \[[0, 1], [2, 3]].
|
||||
ZigZagMatrix(2) deve retornar \[[0, 1], [2, 3]].
|
||||
|
||||
```js
|
||||
assert.deepEqual(ZigZagMatrix(2), zm2);
|
||||
```
|
||||
|
||||
ZigZagMatrix(5) should return specified matrix.
|
||||
ZigZagMatrix(5) deve retornar a matriz especificada.
|
||||
|
||||
```js
|
||||
assert.deepEqual(ZigZagMatrix(5), zm5);
|
||||
|
Reference in New Issue
Block a user