# 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 – Unrelated String Apr 21 at 23:37
• Can the chosen subset be digits 0-9? – Jonah Apr 22 at 13:31
• @Jonah I'm going to say no, just since it's so narrow. – Redwolf Programs Apr 22 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 – Unrelated String Jun 3 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! – caird coinheringaahing Apr 21 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


# 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 +/¨⊢=⊂ – Andrew Ogden Apr 22 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 }

# 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... – A username Apr 25 at 9:38

# 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! – caird coinheringaahing Apr 22 at 0:56
• Similar to the other answer, you need to wrap this in a function or lambda. – Razetime Apr 22 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. # 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  # 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. – Redwolf Programs Apr 22 at 2:29 • @RedwolfPrograms Yes. ||=, &&= and ??= are ES2021 features. Logical ||= and &&= are also supported by ActionScript (ES4) long long ago. – tsh Apr 22 at 2:34 • Can't you use flatMap? – Redwolf Programs Apr 22 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 Apr 22 at 3:46 # Racket, 42 bytes (λ(b)(map(λ(y)(count(λ(x)(= x y))b))b))  Try it online! # 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} – coltim Apr 22 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? – Galen Ivanov Apr 22 at 19:17 • Yep, exactly! It's possible to implement it in oK as well, but you would need to use {(#:'=x)x}. – coltim Apr 22 at 20:05 # 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.  # Haskell, 27 bytes f a=[sum[1|y<-a,y==x]|x<-a]  Try it online! # 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]  # AWK, 47 bytes {c[$1]++;a[NR]=$0}END{for(i in a)print c[a[i]]}  Try it online! # 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. # 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 – Dominic van Essen Apr 22 at 7:50 # 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


# C (clang), 84 $$\\cdots\$$ 81 75 bytes

Saved 6 bytes thanks to AZTECCO!!!

b;i;j;f(*a,l){for(i=-1;++i<l;printf("%d ",b))for(b=j=l;j--;)b-=a[i]!=a[j];}


Try it online!

Inputs a pointer to an array and its length (because array pointers in C don't carry any length info) and prints the occurrence counts.

• @AZTECCO Very nice - thanks! :D – Noodle9 Apr 22 at 15:15

# 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!

# Charcoal, 6 bytes

ＩＥθ№θι


Try it online! Link is to verbose version of code. Explanation:

  θ     Input array
Ｅ      Map over elements
№    Count of
ι  Current element in
θ   Input arrray
Ｉ       Cast to string
Implicitly print


# 05AB1E, 2 bytes

€¢


Try it online!

## Explained

€¢   # [input.count(n) for n in input]

• you had the chance to (ab)use automatic vectorization – Makonede Apr 22 at 0:34
• @Makonede so why did you post as a separate answer instead of just leaving a golfing suggestion? Usually when someone has a similar method but shorter they leave a comment showing how to remove bytes. – lyxal Apr 22 at 0:49
• Actually, I had posted the answer before even seeing yours, so I would've left the suggestion but it was too late – Makonede Apr 22 at 1:48

# Scala, 22 bytes

a=>a.map(a count _.==)


Try it in Scastie!

# 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


# Wolfram Language (Mathematica), 12 bytes

Counts@#/@#&


Try it online!