Make a frequency table (histogram)
Challenge
Given an array in any suitable format, create a frequency table for it. i.e: Pair each unique element with the number of times it appears in the array.
You can return the frequency table as a list of pairs, hashmap/dictionary, output the pairs directly, etc.
Tests
{ 1 1 2 3 5 6 6 } -> { { 1 2 } { 2 1 } { 3 1 } { 5 1 } { 6 2 } }
{ } -> { }
{ 1 6 7 1 2 6 6 1 53 4 10 } -> { { 1 3 } { 2 1 } { 4 1 } { 53 1 } { 6 3 } { 7 1 } { 10 1 } }
Factor, 46 bytes ``` USE: …
2y ago
J, 8 bytes ```J .,:#/. `` …
2y ago
Python 3, 38 36 33 bytes `` …
2y ago
Japt, 8 bytes ü ®â pZl …
2y ago
Ruby, 12 bytes ``` ->{1.tall …
2y ago
Vyxal, 1 byte ``` Ċ ``` Tr …
2y ago
Lua, 98 bytes ``` lua func …
2y ago
[C (gcc)], 45, 42 bytes …
2y ago
APL(Dyalog Unicode), 4 bytes S …
2y ago
[JavaScript (Node.js)], 38 32 …
2y ago
10 answers
J, 8 bytes
~.,:#/.~
Tacit function, this is the de facto method for this problem in J.
0 comment threads
Python 3, 38 36 33 bytes
lambda x:{n:x.count(n)for n in x}
-2 bytes thanks to @Razetime
Another -3 bytes thanks to @orthoplex
APL(Dyalog Unicode), 4 bytes SBCS
Anonymous tacit prefix function.
,∘≢⌸
…⌸
between each unique element and its indices, apply:
,∘≢
concatenate the unique element to the tally of indices
0 comment threads
JavaScript (Node.js), 38 32 bytes
-6 bytes thanks to Shaggy!
a=>a.map(v=>d[v]=-~d[v],d={})&&d
Basically just this but returning the result
1 comment thread
Lua, 98 bytes
function(t)r={}for k,v in pairs(t)do r[v]=0 end for k,v in pairs(t)do r[v]=r[v]+1 end return r end
C (gcc), 45, 42 bytes
t[9999];f(s,a)int*a;{for(;s;)t[a[--s]]++;}
Assumptions:
- Passing the array size to a function can be used as a means to deal with empty arrays (not supported in C).
- A table of integers can be regarded as a hashtable with an integer value as hash key and the value's frequency as data. Or if you will: a key-value pair.
- Maximum integer value 9999.
- The global variable
t
may have its contents printed outside the function.
1 comment thread