# Replace all items with their counts

Given an array of numbers as input (you can choose what subset, such as integers or natural numbers), replace all items with the number of times they appear within the array. As an example, [1, 2, 2, 1, 4, 8, 1] would become [3, 2, 2, 3, 1, 1, 3].

You can take input/produce output as arrays, lists, tuples, or any other reasonable representation of some numbers.

Test cases:

[1]                     [1]
[1, 2]                  [1, 1]
[1, 1]                  [2, 2]
[1, 4, 4]               [1, 2, 2]
[4, 4, 2]               [2, 2, 1]
[4, 4, 4, 4]            [4, 4, 4, 4]
[10, 20, 10, 20]        [2, 2, 2, 2]
[1, 2, 2, 4, 4, 4, 4]   [1, 2, 2, 4, 4, 4, 4]
[1, 2, 2, 1, 4, 8, 1]   [3, 2, 2, 3, 1, 1, 3]


Other:

This is , shortest answer (in bytes) per language wins!

• I feel like this is a dupe of something but that's probably just because it's a convenient sub-problem of a bunch of other things Commented Apr 21, 2021 at 23:37
• Can the chosen subset be digits 0-9? Commented Apr 22, 2021 at 13:31
• @Jonah I'm going to say no, just since it's so narrow. Commented Apr 22, 2021 at 14:18
• A siller question on that same note, could the input be restricted to prime numbers? I don't see it being relevant to anything as it is, but if this exact question were posted in the dark days of Ð€, Jelly would still have had a 2-byter in Pọ :P Commented Jun 3, 2021 at 7:20

# Python 2, 23 bytes

lambda l:map(l.count,l)


Try it online!

• ...I forgot map was a thing, thanks for helping me save 5 bytes on my Python 3 answer! Commented Apr 21, 2021 at 23:50

# MATL, 3 bytes

&=s


### Explanation

     % Implicit input: numeric row vector
&=   % Matrix of all pairwise equality comparisons
s    % Sum of each column
% Implicit display


# JavaScript (ES6), 36 bytes

a=>a.map(x=>a.map(y=>t+=x==y,t=0)|t)


Try it online!

• The one answer that doesn't use a counting builtin... Commented Apr 25, 2021 at 9:38

# APL(Dyalog Unicode), 6 bytes SBCS

+/∘.=⍨


Try it on APLgolf!

+/∘.=⍨  dfn submission
∘.=   product table using equality
⍨  applied to the input on the left and the right
+/      reduce by addition / sum

• Another take +/¨⊢=⊂ Commented Apr 22, 2021 at 4:16

# Factor, 28 bytes

[ dup histogram substitute ]


Try it online!

It's a bit shorter than the version for squares:

[ dup [ '[ _ = ] count ] with map ]


## Explanation:

It's a quotation (anonymous function) that takes a sequence from the data stack as input and leaves a sequence on the data stack as output. Assuming { 1 4 4 } is on the data stack when this quotation is called...

• dup Duplicate an object.

Stack: { 1 4 4 } { 1 4 4 }

• histogram Create a histogram from a sequence.

Stack: { 1 4 4 } H{ { 1 1 } { 4 2 } }

• substitute Take a sequence and an associative array and substitute elements in the sequence that have keys in the assoc with their values.

Stack: { 1 2 2 }

# Ruby, 27 bytes

f=->*a{a.map{|e|a.count e}}


Testing:

p f[4,3,4]  #=> [2, 1, 2]

• Welcome to Code Golf, and nice first answer! Commented Apr 22, 2021 at 0:56
• Similar to the other answer, you need to wrap this in a function or lambda. Commented Apr 22, 2021 at 1:38

# Raku, 10 bytes

{.Bag{$_}}  Try it online! .Bag generates a Bag (a set with multiplicity) from the input argument $_. Then {$_} slices into that Bag with the original list, producing a list of the multiplicities of the elements of that list, in order. # Racket, 42 bytes (λ(b)(map(λ(y)(count(λ(x)(= x y))b))b))  Try it online! # Brachylog, 8 bytes ∋;?{∈ᵈ}ᶜ  Try it online! Generates the output through the output variable. ∋; Pair some element of the input with ? the input. { }ᶜ In how many ways is ∈ᵈ the element an element of the input?  Using ọ comes out one byte longer: # Brachylog, 9 bytes ⟨ọ⟨∋h⟩∋⟩t  Try it online! Also generates the output through the output variable.  ∋ Choose an element of the input. ⟨ h⟩ It is the first element of ∋ an element of ⟨ọ ⟩ the list of pairs [element of input, how many times it occurs in input] t the last element of which is the output.  # Jelly, 2 bytes ċⱮ  Try it online! ## How it works ċⱮ - Main link. Takes a list L on the left Ɱ - For each element in L ċ - Count the times it appears in L  # Python 3, 26 bytes lambda l:[*map(l.count,l)]  Try it online! -5 bytes (indirectly) thanks to xnor! # Pyth, 3 bytes /LQ  Test suite Explanation: /LQ | Full program /LQQ | with implicit variables -----+------------------------------------- L Q | replace each element d in input with / Q | the count of d in input  # Vyxal, 2 bytes vO  Try it Online! Wow y'all using unicode in your golfing languages while I'm chilling in the ASCII zone. ## Explained vO # vectorise count over the input # essentially, [input.count(n) for n in input]  # JavaScript (ES2021), 35 bytes (not quite reasonable I/O) a=>a.map(n=>a[++(a[n]||=[0])[0],n])  Accept an array of 1 element array of negative numbers. Return an array of 1 element array... f([-1, -2, -2, -1, -4, -8, -1]) // [[3], [2], [2], [3], [1], [1], [3]] f([[-1], [-2], [-2], [-1], [-4], [-8], [-1]]) // [[3], [2], [2], [3], [1], [1], [3]]  Just consider input / output as column vectors... # JavaScript (ES2021), 42 bytes Add an extra .flat() to make it reasonable would cost +7 bytes (42 bytes in total) a=>a.map(n=>a[++(a[n]||=[0])[0],n]).flat()  That's too long. • Is ||= a ES2021 feature? I don't remember seeing that before. Commented Apr 22, 2021 at 2:29 • @RedwolfPrograms Yes. ||=, &&= and ??= are ES2021 features. Logical ||= and &&= are also supported by ActionScript (ES4) long long ago. – tsh Commented Apr 22, 2021 at 2:34 • Can't you use flatMap? Commented Apr 22, 2021 at 3:43 • @RedwolfPrograms flatMap will flat as soon as the array returns, not flat after map. <del>maybe we need a proposal about Array#mapFlat API to JavaScript.</del> – tsh Commented Apr 22, 2021 at 3:46 • a=>a.map(x=>a.filter(y=>x==y).length) (37 bytes) would be a better substitute for the second solution. Commented Jan 18, 2023 at 4:45 # J, 6 bytes 1#.=/~  Try it online! # K (oK), 9 bytes {+/x=\:x}  Try it online! • An alternative 9-byte answer is possible in ngn/k: {(#'=x)x} Commented Apr 22, 2021 at 16:26 • @coltim Thank you! So you make a dictionary with numbers/frequencies for keys/values and request the values according to the input keys? Commented Apr 22, 2021 at 19:17 • Yep, exactly! It's possible to implement it in oK as well, but you would need to use {(#:'=x)x}. Commented Apr 22, 2021 at 20:05 # Haskell, 27 bytes f a=[sum[1|y<-a,y==x]|x<-a]  Try it online! # 05AB1E, 1 byte ¢  Try it online! Beats all other answers. ¢ # full program ¢ # number of times... # (implicit) each element in... # implicit input... ¢ # appears in... # implicit input # implicit output  # Perl 5-pa, 22 bytes s/\S+/grep$_==$&,@F/ge  Try it online! # Excel 17, bytes =COUNTIF(A1#,A1#)  Assuming A1 = { .... } then this works. It's a longer, less flexible formula if the data in entered in individual cells. # Java, 58 bytes l->l.stream().map(x->java.util.Collections.frequency(l,x))  Try it online! # Java, 56 bytes l->l.stream().map(x->l.stream().filter(y->y==x).count())  This only works for integers in the Integer Cache (-128 to 127, by default). Try it online! # Zsh, 23 bytes xargs -I. grep -c . f<f  Try it online! # Thunno, $$\ 2 \log_{256}(96) \approx \$$ 1.65 bytes ec  Attempt This Online! ec : implicit input array e : map the input to the following: c : count the occurrences of the number in the input : implicit output  Thought I'd try an easy and short problem for my first Thunno answer. • Nice! I didn't see your answer before answering, but I came up with another 2 character solution: Dc. Commented Jan 28, 2023 at 9:39 • @TheThonnu Can you explain how your version works? My understanding is: it duplicates the array. Then c automatically maps over both arrays at once. Is that correct? Commented Jan 28, 2023 at 14:01 • Yeah, c will vectorise over a list. Your one isn't supposed to work, since e should pop the list, but somehow it does... Commented Jan 28, 2023 at 17:35 # Go, 103 bytes func f(l[]int)[]int{m:=make(map[int]int) for _,e:=range l{m[e]++} for i,e:=range l{l[i]=m[e]} return l}  Attempt This Online! # Pip-p, 5 bytes _NgMg  Attempt This Online! ### Explanation  g ; List of command-line args M ; Map to each: _N ; Number of occurrences of that argument in... g ; ... the list of command-line args  # Julia 1.0, 19 bytes [email protected](==(a),[a])  Try it online! Saved 2 bytes by substituting sum for count. -3 bytes thanks to MarcMush: replace Ref(a) with [a] # R, 26 bytes ave(a,a<-scan(),FUN=table)  Try it online! ave takes a vector x, an arbitrary number of grouping variables ..., and a function FUN, and replaces each element of x with the result of applying FUN to the group containing that element. I've also found a number of 26 byte variants with FUN=sum; they differ only in the way they generate a vector of ones with length length(a). ave(a^0,a<-scan(),FUN=sum) ave(a,a<-scan(),FUN=sum)/a ave(a|1,a<-scan(),FUN=sum)  • Great, and a nice showcase of a previously-unused-by-me R function Commented Apr 22, 2021 at 7:50 # Japt, 4 bytes £è¥X  Try it maps input by returning number of occurrence in input # PHP, 56 bytes fn($a)=>array_map(fn($e)=>array_count_values($a)[$e],$a)


Try it online!

As usual, those "array_" PHP prefixes are ruining the golfing :P

# C# (Visual C# Interactive Compiler), 32 bytes

Nothing special

a=>a.Select(x=>a.Count(y=>x==y))


Try it online!

# Neim, 2 bytes

Right language, right time.

Ψ𝕠


Try it online!

Explanation:

Ψ  # Apply next token to all in list
𝕠 # Count element in list