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

37 Answers 37

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\$ – caird coinheringaahing Apr 21 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\$
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
  • 2
    \$\begingroup\$ Another take +/¨⊢=⊂ \$\endgroup\$ – Andrew Ogden Apr 22 at 4:16
6
\$\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\$

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\$ – A username Apr 25 at 9:38
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\$ – caird coinheringaahing Apr 22 at 0:56
  • \$\begingroup\$ Similar to the other answer, you need to wrap this in a function or lambda. \$\endgroup\$ – Razetime Apr 22 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\$
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\$

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\$
4
  • \$\begingroup\$ Is ||= a ES2021 feature? I don't remember seeing that before. \$\endgroup\$ – Redwolf Programs Apr 22 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 at 2:34
  • 1
    \$\begingroup\$ Can't you use flatMap? \$\endgroup\$ – Redwolf Programs Apr 22 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 at 3:46
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 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\$ – Galen Ivanov Apr 22 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 at 20:05
4
\$\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\$
3
\$\begingroup\$

Haskell, 27 bytes

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

Try it online!

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

AWK, 47 bytes

{c[$1]++;a[NR]=$0}END{for(i in a)print c[a[i]]}

Try it online!

\$\endgroup\$
0
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\$
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\$ – Dominic van Essen Apr 22 at 7:50
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\$
1
  • 1
    \$\begingroup\$ @AZTECCO Very nice - thanks! :D \$\endgroup\$ – Noodle9 Apr 22 at 15:15
2
\$\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\$
1
\$\begingroup\$

Charcoal, 6 bytes

IEθ№θι

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

  θ     Input array
 E      Map over elements
   №    Count of
     ι  Current element in
    θ   Input arrray
I       Cast to string
        Implicitly print
\$\endgroup\$
1
\$\begingroup\$

05AB1E, 2 bytes

€¢

Try it online!

Explained

€¢   # [input.count(n) for n in input]
\$\endgroup\$
3
  • \$\begingroup\$ you had the chance to (ab)use automatic vectorization \$\endgroup\$ – Makonede Apr 22 at 0:34
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ – lyxal Apr 22 at 0:49
  • 3
    \$\begingroup\$ Actually, I had posted the answer before even seeing yours, so I would've left the suggestion but it was too late \$\endgroup\$ – Makonede Apr 22 at 1:48
1
\$\begingroup\$

Scala, 22 bytes

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

Try it in Scastie!

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

Wolfram Language (Mathematica), 12 bytes

Counts@#/@#&

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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