Code Lab

Modo entrevista. Cronômetro de 10 min, sem dicas e sem autocompletar

Count balls by color

MédiaMap and Set10 min

Write a function countColors(balls) that counts the balls of each color and returns the result as one string.

  • balls is an array of color names, one per ball. Every name is in lower case. A name can have a space inside, for example 'light blue'.
  • For every color, write the name, one space and the count: 'blue 3'.
  • Join the parts with a comma and a space: 'blue 3, red 5, indigo 7'. There is no comma at the end.
  • Colors go in the order of their first appearance in balls. Do not sort them.
  • For an empty array return ''.

A map keeps keys in the order you add them, so it is a good place for the counts.

Exemplos

countColors(['blue', 'red', 'blue'])

Retorna 'blue 2, red 1'

countColors(['red', 'red', 'green', 'red'])

Retorna 'red 3, green 1'

countColors([])

Retorna ''

Cobrada em emids · Fonte

Carregando o editor...
  1. EntradacountColors([ 'blue', 'red', 'indigo', 'red', 'blue', 'indigo', 'red', 'indigo', 'blue', 'indigo', 'red', 'indigo', 'red', 'indigo', 'indigo' ])
    Esperado'blue 3, red 5, indigo 7'
  2. EntradacountColors([ 'red', 'blue', 'red' ])
    Esperado'red 2, blue 1'

Os testes ocultos rodam no envio