32
\$\begingroup\$

Task:

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!

\$\endgroup\$
4
  • 2
    \$\begingroup\$ 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 \$\endgroup\$ Apr 21, 2021 at 23:37
  • \$\begingroup\$ Can the chosen subset be digits 0-9? \$\endgroup\$
    – Jonah
    Apr 22, 2021 at 13:31
  • \$\begingroup\$ @Jonah I'm going to say no, just since it's so narrow. \$\endgroup\$ Apr 22, 2021 at 14:18
  • \$\begingroup\$ 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 \$\endgroup\$ Jun 3, 2021 at 7:20

52 Answers 52

16
\$\begingroup\$

Python 2, 23 bytes

lambda l:map(l.count,l)

Try it online!

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

MATL, 3 bytes

&=s

Try it online! Or verify all test cases.

Explanation

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

JavaScript (ES6), 36 bytes

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

Try it online!

\$\endgroup\$
1
  • \$\begingroup\$ The one answer that doesn't use a counting builtin... \$\endgroup\$
    – emanresu A
    Apr 25, 2021 at 9:38
7
\$\begingroup\$

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
\$\endgroup\$
1
  • 3
    \$\begingroup\$ Another take +/¨⊢=⊂ \$\endgroup\$ Apr 22, 2021 at 4:16
7
\$\begingroup\$

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 }

\$\endgroup\$
5
\$\begingroup\$

Ruby, 27 bytes

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

Testing:

p f[4,3,4]  #=> [2, 1, 2]
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Welcome to Code Golf, and nice first answer! \$\endgroup\$ Apr 22, 2021 at 0:56
  • \$\begingroup\$ Similar to the other answer, you need to wrap this in a function or lambda. \$\endgroup\$
    – Razetime
    Apr 22, 2021 at 1:38
5
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$

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.
\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

Python 3, 26 bytes

lambda l:[*map(l.count,l)]

Try it online!

-5 bytes (indirectly) thanks to xnor!

\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
4
\$\begingroup\$

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]
\$\endgroup\$
4
\$\begingroup\$

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.

\$\endgroup\$
6
  • \$\begingroup\$ Is ||= a ES2021 feature? I don't remember seeing that before. \$\endgroup\$ Apr 22, 2021 at 2:29
  • \$\begingroup\$ @RedwolfPrograms Yes. ||=, &&= and ??= are ES2021 features. Logical ||= and &&= are also supported by ActionScript (ES4) long long ago. \$\endgroup\$
    – tsh
    Apr 22, 2021 at 2:34
  • 1
    \$\begingroup\$ Can't you use flatMap? \$\endgroup\$ Apr 22, 2021 at 3:43
  • 1
    \$\begingroup\$ @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> \$\endgroup\$
    – tsh
    Apr 22, 2021 at 3:46
  • \$\begingroup\$ a=>a.map(x=>a.filter(y=>x==y).length) (37 bytes) would be a better substitute for the second solution. \$\endgroup\$
    – kamoroso94
    Jan 18 at 4:45
4
\$\begingroup\$

Racket, 42 bytes

(λ(b)(map(λ(y)(count(λ(x)(= x y))b))b))

Try it online!

\$\endgroup\$
4
\$\begingroup\$

J, 6 bytes

1#.=/~

Try it online!

K (oK), 9 bytes

{+/x=\:x}

Try it online!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ An alternative 9-byte answer is possible in ngn/k: {(#'=x)x} \$\endgroup\$
    – coltim
    Apr 22, 2021 at 16:26
  • \$\begingroup\$ @coltim Thank you! So you make a dictionary with numbers/frequencies for keys/values and request the values according to the input keys? \$\endgroup\$ Apr 22, 2021 at 19:17
  • 1
    \$\begingroup\$ Yep, exactly! It's possible to implement it in oK as well, but you would need to use {(#:'=x)x}. \$\endgroup\$
    – coltim
    Apr 22, 2021 at 20:05
3
\$\begingroup\$

Haskell, 27 bytes

f a=[sum[1|y<-a,y==x]|x<-a]

Try it online!

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
3
\$\begingroup\$

Perl 5 -pa, 22 bytes

s/\S+/grep$_==$&,@F/ge

Try it online!

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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!

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Nice! I didn't see your answer before answering, but I came up with another 2 character solution: Dc. \$\endgroup\$
    – The Thonnu
    Jan 28 at 9:39
  • \$\begingroup\$ @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? \$\endgroup\$
    – noodle man
    Jan 28 at 14:01
  • \$\begingroup\$ Yeah, c will vectorise over a list. Your one isn't supposed to work, since e should pop the list, but somehow it does... \$\endgroup\$
    – The Thonnu
    Jan 28 at 17:35
3
\$\begingroup\$

Julia 1.0, 24 21 bytes

[email protected](==(a),[a])

Try it online!

-3 bytes thanks to MarcMush: replace Ref(a) with [a]

\$\endgroup\$
1
  • 1
    \$\begingroup\$ -3 bytes: [a] instead of Ref(a) \$\endgroup\$
    – MarcMush
    Sep 15 at 21:39
2
\$\begingroup\$

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)
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Great, and a nice showcase of a previously-unused-by-me R function \$\endgroup\$ Apr 22, 2021 at 7:50
2
\$\begingroup\$

Japt, 4 bytes

£è¥X

Try it

maps input by returning number of occurrence in input

\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

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

Nothing special

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

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Neim, 2 bytes

Right language, right time.

Ψ𝕠

Try it online!

Explanation:

Ψ  # Apply next token to all in list
 𝕠 # Count element in list
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
0
2
\$\begingroup\$

Zsh, 23 bytes

xargs -I. grep -c . f<f

Try it online!

\$\endgroup\$
2
\$\begingroup\$

Pyt, 2 bytes

Đɔ

Try it online!

Đ      implicit input; duplicate
 ɔ     for each item in input, count occurrences in input; implicit print
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.