Code Lab

Mode entretien. Minuteur de 10 min, sans indices ni autocomplétion

Count balls by color

MoyenMap 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.

Exemples

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

Renvoie 'blue 2, red 1'

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

Renvoie 'red 3, green 1'

countColors([])

Renvoie ''

Posé chez emids · Source

Chargement de l'éditeur...
  1. EntréecountColors([ 'blue', 'red', 'indigo', 'red', 'blue', 'indigo', 'red', 'indigo', 'blue', 'indigo', 'red', 'indigo', 'red', 'indigo', 'indigo' ])
    Attendu'blue 3, red 5, indigo 7'
  2. EntréecountColors([ 'red', 'blue', 'red' ])
    Attendu'red 2, blue 1'

Les tests cachés se lancent à la soumission