7
Introduction and Credit
Imagine you're Amazon. Imagine you have a large number of products for which a lot of people have written reviews scoring 1-5 stars. Now you need to give your customers a summary for each product based on the simple product-scoring association. Because you're Amazon, time is money and as such you need to fit this into the smallest code possible because that's the code you can write the fastest.
Credit: This task appeared in 2014 in a programming mid-term exam in the functional programming course at my university and since then an example solution has been provided. I have the lecturer's and author's (same person) permission to post this question publicly.
Input
Your input will be a list of pairs of natural numbers, where the second value of each pair is always either 1, 2, 3, 4 or 5. Take the input using your preferred, generally accepted way.
Output
Your output will be a list of pairs of a number and a list of 5 numbers. Give the output using your preferred, generally accepted way.
What to do?
Given the (unsorted) list of product-id and scoring pairs, count for each product how often each score appears and return the amounts in the second list of the output pair at the appropriate position.
So for product #5 with 10x 1-star, 15x 2-star, 25x 3-star, 50x 4-star and 150x 5-star would result in the entry [5 [10 15 25 50 150]]
.
Potential Corner Cases
The input list may be empty in which case your output should be as well.
You don't need to consider the case where the input violates the above constraints.
You can safely assume all numbers to be representable by a signed 32-bit integer.
If you have no review(s) for a product (ie it doesn't appear in the output) it must not appear in the output either, i.e. 5x zeroes doesn't happen and can always be dropped.
Who wins?
This is code-golf so the shortest answer in bytes wins. Built-ins are allowed and standard rules apply.
Examples
Example input:
[(1,4),(2,5),(1,5),(1,1),(1,5),(1,4)]
Example corresponding output:
[
(1,[1, 0, 0, 2, 2]),
(2,[0, 0, 0, 0, 1])
]
Other test vectors:
[] -> []
[(1,1),(2,2),(3,3),(4,4),(5,5)] ->
[(1, [1,0,0,0,0]),(2, [0,1,0,0,0]),(3, [0,0,1,0,0]),(4, [0,0,0,1,0]),(5, [0,0,0,0,1])]
Can / must we output a list of
5
zeros for product2
if only products1
are given in the input? Or can we assume that will never happen? – Luis Mendo – 2016-12-05T22:53:40.207@LuisMendo if you have no reviews for a product "it doesn't exist". Or in another way: If you have no review then there's no way for you to tell product 2 or 3 or 4 is a thing and thus you can obviously leave it out. Also see the edit. – SEJPM – 2016-12-05T22:57:56.210
Would a JS object such as
{"1":[1,0,0,2,2],"2":[0,0,0,0,1]}
be a valid output? – Arnauld – 2016-12-06T00:15:22.323@Arnauld well, you pair the item number with a list so it's OK. – SEJPM – 2016-12-06T08:52:12.850