g | x | w | all
Bytes Lang Time Link
034Juby250519T181257ZJordan
004Thunno 2230714T084238ZThe Thon
004MATL190108T112011ZSuever
021Wolfram Language Mathematica190114T072617Zalephalp
013[APL Dyalog Unicode]220126T062334ZJayant C
085Go220126T044833Zcure
025PowerShell Core220126T033647ZJulian
004Husk220104T174932ZNatte
001BQN220104T013151Zlynn
048Factor220104T012805Zchunes
004Vyxal220104T010039Zlyxal
122C++ gcc190113T093048ZAZTECCO
032Gema190830T121350Zmanatwor
018K ngn/k190822T104532Zscrawl
174SAP ABAP190822T135752ZMaz
007Pyth190822T074150Zar4093
007J190108T101043ZGalen Iv
062C gcc190114T045139Zatt
172C# .NET Core190114T165303ZDestroig
023Attache190114T125146ZConor O&
032Pari/GP190114T065032Zalephalp
027R190112T140152ZdigEmAll
014AWK190108T200112ZDigital
011Perl 5190111T081826ZNahuel F
024bash190108T151846ZNahuel F
031awk190108T120134ZNahuel F
063SNOBOL4 CSNOBOL4190111T003756ZGiuseppe
017Reticular190111T002029ZWisław
046Haskell190110T194518ZLaikoni
044Python 2190110T001536Zlynn
015Perl 6190108T094553ZJo King
121GO 121 Bytes Not included new lines and tabs190109T053643Zthe ulti
058Haxe190108T210929ZAurel
034Ruby190108T205801ZG B
044Haskell190108T205358Zბიმო
043R190108T174458ZSumner18
008Japt190108T101539ZShaggy
035Ruby190108T173910ZDaveMong
048Tcl190108T153215Zsergiol
076Java JDK190108T150045ZOlivier
044C# Visual C# Interactive Compiler190108T122752Zdana
041R190108T154246ZGiuseppe
007APL Dyalog Unicode190108T142809ZSherlock
004Jelly190108T102352ZMr. Xcod
061Batch190108T100808ZNeil
043Python 2190108T095238ZChas Bro
00405AB1E190108T094831ZEmigna
030Retina 0.8.2190108T094505ZNeil
026JavaScript ES6190108T093200ZArnauld
048Python 2190108T093635ZTFeld

J-uby, 34 bytes

:*%[:& &:count%[:take,:[]],:+@|:*]

Attempt This Online!

Thunno 2, 4 bytes

ƒıṪc

Try it online!

Explanation

ƒıṪc­⁡​‎‎  # Implicit input⁡⁠⁡‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢‏⁠‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌­
ƒ     # ‎⁡Get the prefixes of the input list
 ı    # ‎⁢Map over this list of lists:
  Ṫ   # ‎⁣ Remove the last item and push it separately
   c  # ‎⁤ Count the occurrences of this letter
      # ‎⁢⁡Implicit output

MATL, 4 bytes

&=Rs

This solution is 1-based

Try it out at MATL Online!

Explanation

Uses [1,2,3,2] as an example

    # Implicitly grab the input array of length N
    #
    #   [1,2,3,2]
    #
&=  # Create an N x N boolean matrix by performing an element-wise comparison
    # between the original array and its transpose:
    #
    #     1 2 3 2
    #     -------
    # 1 | 1 0 0 0
    # 2 | 0 1 0 1
    # 3 | 0 0 1 0
    # 2 | 0 1 0 1
    #
R   # Take the upper-triangular portion of this matrix (sets below-diagonal to 0)
    #
    #   [1 0 0 0
    #    0 1 0 1
    #    0 0 1 0
    #    0 0 0 1]
    #
s   # Compute the sum down the columns
    #
    #   [1,1,1,2]
    #
    # Implicitly display the result

Wolfram Language (Mathematica), 21 bytes (@att)

_g=g/@#-(--g[#]&/@#)&

Try it online!


Wolfram Language (Mathematica), 28 bytes

(Clear@g;g@a_=0;++g[#]&/@#)&

Based on @att's answer to another challenge.

Try it online!


Wolfram Language (Mathematica), 32 bytes

-1 byte thanks to @att.

Accumulate[p=x^#]~Coefficient~p&

The \$k\$-th element in the answer is the coefficient of the \$x^{a_k}\$ term in the polynomial \$\sum_{i=1}^kx^{a_i}\$.

Try it online!

[APL (Dyalog Unicode)], 13 bytes

(+/⊃⍷⊢)⍤⌽¨,\⎕

Go, 85 bytes

package main
func main(){
m:=make(map[int]int)
for i,n:=range a{
a[i]=m[n]
m[n]++
}
}

Create a map to store the count, loop through input list (a), replacing each item with the count for that item before incrementing.

PowerShell Core, 25 bytes

$t=@{}
$args|%{(++$t.$_)}

Try it online!

Husk, 4 bytes

z#ḣ¹

Try it online!

Explanation

one-indexed

z#ḣ¹  transforms to z#ḣ⁰⁰
z     zip
  ḣ⁰  prefixes of input
    ⁰ and input
 #    with count

BQN, 1 byte

Try it here!, All tests

I don't know much about BQN, but I learned from this answer that this is a built-in.

Factor, 48 bytes

[ dup [ head [ = ] with count ] with map-index ]

Try it online!

Vyxal, 4 bytes

KƛtO

Try it Online!

KƛṫO is also valid for 4 bytes

Simply count the number of occurrences of the tail of each prefix in each prefix.

C++ (gcc), 122 bytes

#import<vector>
using V=std::vector<int>;V f(V x){for(int i,t,z=x.size();t=i=z--;x[z]=t)for(;i--;)t-=x[z]!=x[i];return x;}

Try it online!

Saved 2 more bytes thanks to @ceilingcat

Gema, 32 characters

<D>=@set{$1;@add{${$1;};1}}${$1}

Outputs 1 based indexes.

Sample run:

bash-5.0$ gema '<D>=@set{$1;@add{${$1;};1}}${$1}' <<< '[5,12,10,12,12,10]'
[1,1,1,2,3,2]

Try it online!

Gema, 34 characters

<D>=${$1;0}@set{$1;@add{${$1;};1}}

Outputs 0 based indexes.

Sample run:

bash-5.0$ gema '<D>=${$1;0}@set{$1;@add{${$1;};1}}' <<< '[5,12,10,12,12,10]'
[0,0,0,1,2,1]

Try it online!

K (ngn/k), 18 bytes

(,/.!'#'=x)@<,/.=x

Try it online!


OLD APPROACH

K (ngn/k), 27 23 22 bytes

{x[,/.=x]:,/.!'#'=x;x}

Try it online!


this is not pretty... quick and dirty solution, i will be refining this later when i get the chance to think of a better approach

explanation:

annoyingly, the list is updated but a null value is returned by the assignment, so i need to return the list after the semicolon (;x)

edit: removed extraneous colons

edit2: removed unnecessary assignment

SAP ABAP, 174 bytes

FORM f TABLES t.DATA r TYPE int_tab1.LOOP AT t.DATA(i) = 0.DATA(x) = sy-tabix.LOOP AT t.CHECK:sy-tabix < x,t = t[ x ].i = i + 1.ENDLOOP.APPEND i TO r.ENDLOOP.t[] = r.ENDFORM.

Subroutine which takes a table of integers and replaces all values with zero-based indices. ABAP has no array type, so a table of integers is the closest thing we have. It uses the builtin table type int_tab1 to save some bytes over declaring TYPE TABLE OF i and abuses obsolete (but still functional) internal tables with header lines, which allows us to use LOOP AT t and read t at the implicit index sy-tabix without declaring additional variables for keeping the value.


Full program with some test cases from OP can be found here. Output below: Results from the test cases

Forgot to add the two edge cases of [ ] and [42], but they work, too:
[ ] => An empty input table stays empty as the outer loop gets skipped completely
[42] => A single value in the table means table line 1 in the inner loop is skipped, since sy-tabix is equal to x - therefore i stays 0 and the output is [0].


Explanation:

FORM f TABLES t.              "Subroutine, TABLES parameters are references
  DATA r TYPE int_tab1.       "A temporary internal table for results
  LOOP AT t.                  "Go over each line in table t
    DATA(i) = 0.              "Set count to 0            (inline declaration)
    DATA(x) = sy-tabix.       "Set x to current index    (inline declaration)
    LOOP AT t.                "Go over each line in table t again
      CHECK:                  "Check whether... (works like a CONTINUE if not true)
        sy-tabix < x,         "1) ...inner LOOP index is smaller than outer index (= only check lines up to outer index - 1)
        t = t[ x ].           "2) ...value of t at inner index (implicit) is equal to value of t at outer index (x)
      i = i + 1.              "If both are true, increase the counter by 1
    ENDLOOP.                  
    APPEND i TO r.            "Add the count for this value to temporary results table
  ENDLOOP.                    
  t[] = r.                    "Fill referenced table t with the values in r.
ENDFORM.

Pyth, 7 bytes

.e/<Qkb

Try it online!

.e     Q # enumerated map over (implicit) Q (input): lambda k,b: (k=index, b=element)
  /   b  # number of occurences of b in
   <Qk   # Q[:k]

Alternative 1-based solution (7 bytes)

m/ded._

Try it online!

m    ._ # map over all prefixes of (implicit) Q (input): lambda d:
 / ed   # Number of occurences of d[-1] in
  d     #                                  d

J, 7 bytes

1#.]=]\

Try it online!

1-indexed.

Explanation:

]\ all the prefixes (filled with zeros, but there won't be any 0s in the input):
   ]\ 5 12 10 12 12 10
5  0  0  0  0  0
5 12  0  0  0  0
5 12 10  0  0  0
5 12 10 12  0  0
5 12 10 12 12  0
5 12 10 12 12 10

]= is each number from the input equal to the prefix:
   (]=]\) 5 12 10 12 12 10
1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 1 0 1 0 0
0 1 0 1 1 0
0 0 1 0 0 1

1#. sum each row:
   (1#.]=]\) 5 12 10 12 12 10
1 1 1 2 3 2

K (oK), 11 10 bytes

-1 byte thanks to ngn!

{+/'x=,\x}

Try it online!

C (gcc), 65 62 bytes

c,d;f(a,b)int*a;{for(;c=d=b--;a[b]=d)for(;c--;d-=a[c]!=a[b]);}

Try it online!

-2 bytes thanks to ASCII-only


This felt too straightforward, but I couldn't seem to get any shorter with a different approach.

C# (.NET Core), 172 bytes

Without LINQ. 0 indexed int[] arrays.

p=>{int h=0,m=0,l=p.Length,j;var k=new int[l];if(l>0){foreach(int z in p){h=z>h?z:h;m=z<m?z:m;}for(j=m;j<=h;j++,m=0)for(int z=0;z<l;z++)k[z]=p[z]==j?m++:k[z];}return k;}

Try it online!

Attache, 23 bytes

{`~&>Zip[_,_[0:#_::0]]}

Try it online!

Explanation

{`~&>Zip[_,_[0:#_::0]]}
{                     }    _: input (e.g., [5, 12, 10, 12, 12, 10])
             0:#_          range from 0 to length of input (inclusive)
                           e.g., [0, 1, 2, 3, 4, 5, 6]
                 ::0       descending range down to 0 for each element
                           e.g., [[0], [1, 0], [2, 1, 0], [3, 2, 1, 0], [4, 3, 2, 1, 0], [5, 4, 3, 2, 1, 0], [6, 5, 4, 3, 2, 1, 0]]
           _[       ]      get input elements at those indices
                           e.g., [[5], [12, 5], [10, 12, 5], [12, 10, 12, 5], [12, 12, 10, 12, 5], [10, 12, 12, 10, 12, 5], [nil, 10, 12, 12, 10, 12, 5]]
     Zip[_,          ]     concatenate each value with this array
                           e.g., [[5, [5]], [12, [12, 5]], [10, [10, 12, 5]], [12, [12, 10, 12, 5]], [12, [12, 12, 10, 12, 5]], [10, [10, 12, 12, 10, 12, 5]]]
   &>                      using each sub-array spread as arguments...
 `~                            count frequency
                               e.g. [12, [12, 10, 12, 5]] = 12 ~ [12, 10, 12, 5] = 2

Pari/GP, 32 bytes

a->p=0;[polcoeff(p+=x^t,t)|t<-a]

The \$k\$-th element in the answer is the coefficient of the \$x^{a_k}\$ term in the polynomial \$\sum_{i=1}^kx^{a_i}\$.

Try it online!

R, 27 bytes

function(x)ave(x,x,FUN=seq)

Try it online!

Explanation :

ave(x,x,FUN=seq) splits vector x into sub-vectors using values of x as grouping keys. Then seq function is called for each group and each result is re-arranged back in the original group position.

Better see an example :

x <- c(5,7,5,5,7,6)
ave(x, x, FUN=seq) # returns 1,1,2,3,2


 ┌───┬───┬───┬───┬───┐
 │ 5 │ 7 │ 5 │ 5 │ 7 │
 └───┴───┴───┴───┴───┘            
   |   |   |    |  |     
   ▼   |   ▼    ▼  |
 GROUP A : seq(c(5,5,5)) = c(1,2,3)
   |   |   |    |  |     
   ▼   |   ▼    ▼  |
 ┌───┐ | ┌───┬───┐ |
 │ 1 │ | │ 2 │ 3 │ |
 └───┘ | └───┴───┘ |
       ▼           ▼
 GROUP B : seq(c(7,7)) = c(1,2)
       |           |
       ▼           ▼
     ┌───┐       ┌───┐
     │ 1 │       │ 2 │
     └───┘       └───┘ 

   |   |   |   |   |
   ▼   ▼   ▼   ▼   ▼ 
 ┌───┬───┬───┬───┬───┐
 │ 1 │ 1 │ 2 │ 3 │ 2 │
 └───┴───┴───┴───┴───┘  

Note :

seq(y) function returns a sequence 1:length(y) in case y has length(y) > 1, but returns a sequence from 1:y[1] if y contains only one element.
This is fortunately not a problem because in that case R - complaining with a lot of warnings - selects only the first value which is incidentally what we want :)

AWK, 14

{print++a[$1]}

Try it online!

The above does one-based indexing. If you prefer zero-based indexing, its an extra byte:

{print a[$1]++}

Try it online!

Perl 5, 11 bytes

$_=$h{$_}++

TIO

explanations following comment

bash, 37 24 bytes

f()(for x;{ r+=$[a[x]++]\ ;};echo $r)

TIO

if valid, there is also this variation, as suggested by DigitalTrauma

for x;{ echo $[a[x]++];}

TIO

awk 46 31 bytes

-15 bytes thanks to @Dennis

{for(;i++<NF;)$i=a[$i]++;print}

TIO

SNOBOL4 (CSNOBOL4), 63 bytes

 T =TABLE()
R I =INPUT :F(END)
 T<I> =OUTPUT =T<I> + 1 :(R)
END

Try it online!

Reticular, 17 bytes

L[ddc@c~]~*$qlbo;

Try it online!

The input list of integers is assumed to already be pushed to the stack. Run the following code to test input:

'2''7''1''8''2''8''1''8''2''8'lbL[ddc@c~]~*$qlbo;

Explanation

The pop instruction c which is supposed to: pop a list from the stack, pop the last element from that list and push this element to the stack. However, if the list occurs at more than 1 place in the stack (if it has been duplicated for example), all of the duplicated lists in the stack will also have their last element popped contrary to what one might think will happen. This is fortunately used in our favor in this puzzle.

L                 # Push length of input list to the stack.
 [      ]         # Push the following function:
  dd              # Duplicate top of stack twice.
    c             # Pop the list at top of the stack,
                    pop the last element in the list (which will pop the element of every list!)
                    and finally push it to the stack.
     @c           # Pop two items at the top of the stack (list + last element in that list).
                    then push the number of occurrences of that element in the list.
       ~          # Swap top two items in the stack (so that the popped list is on top again).
         ~        # Swap top two items in the stack.
          *       # Call the above function the same number of times as length of the input list.
           $      # Remove the item at the top of the stack (which by now is an empty list).
            q     # Reverse stack.
             lb   # Push size of stack and put that many items from the stack into a list.
               o; # Output resulting list and exit.

Haskell, 47 46 bytes

(#(*0))
(x:r)#g=g x:r# \y->0^(y-x)^2+g y
e#g=e

Try it online!

A different approach than BMO's answer which turned out a bit longer. (And kindly borrows their nice test suit.)

The idea is to iterate over the input list and keep track of the number of times each element has occurred by updating a function g. Ungolfed:

f (const 0)
f g (x:r) = g x : f (\ y -> if x==y then 1 + g y else g y) r
f g []    = []

Two interesting golfing opportunities arose. First for the initial value of g, a constant function which disregards its argument and returns 0:

const 0  -- the idiomatic way
(\_->0)  -- can be shorter if parenthesis are not needed
min 0    -- only works as inputs are guaranteed to be non-negative
(0*)     -- obvious in hindsight but took me a while to think of

And secondly an expression over variables x and y which yields 1 if x equals y and 0 otherwise:

if x==y then 1else 0  -- yes you don't need a space after the 1
fromEnum$x==y         -- works because Bool is an instance of Enum
sum[1|x==y]           -- uses that the sum of an empty list is zero
0^abs(x-y)            -- uses that 0^0=1 and 0^x=0 for any positive x
0^(x-y)^2             -- Thanks to  Christian Sievers!

There still might be shorter ways. Anyone got an idea?

Python 2, 44 bytes

a=[]
for x in input():print a.count(x);a+=x,

Try it online!

The first thing I wrote tied Chas Brown's 43, so here's a different solution that's one byte longer.

Perl 6, 15 bytes

*>>.&{%.{$_}++}

Try it online!

You can move the ++ to before the % for a one based index.

Explanation:

*>>.&{        }  # Map the input to
      %          # An anonymous hash
       .{$_}     # The current element indexed
            ++   # Incremented

GO 121 Bytes (Not included new lines and tabs)

func cg(a []int) []int{
    var m = make(map[int]int)
    var r = make([]int, len(a))
    for i,v := range a{
        r[i] = m[v]
        m[v]++
    }
    return r
}

Accepts integer array and returns integer array.

Haxe, 58 bytes

l->{var x=[0=>0];l.map(e->++x[(x[e]==null?x[e]=0:0)+e]);};

(Requires arrow functions, so 4.0+)

var x=[0=>0] declares a new IntMap, with 0 as its only key (since the question say inputs are strictly positive). Unfortunately most targets throw when adding null to a number, hence the explicit check to make sure each key is in the map before incrementing.

Also a cheeky rip off based on the JS answer:

Haxe (JS target), 41 bytes

l->{var x=[0=>0];l.map(e->x[e]=-~x[e]);};

Try both online

Ruby, 34 bytes

->a{r=[];a.map{|x|(r<<x).count x}}

Try it online!

Haskell, 44 bytes

([]#)
x#(y:z)=sum[1|a<-x,a==y]:(y:x)#z
_#e=e

Try it online!

Explanation

Traverses the list from left to right keeping the list x of visited elements, initially []:

For every encounter of a y count all equal elements in the list x.

R, 62 43 bytes

x=z=scan();for(i in x)z[y]=1:sum(y<-x==i);z

-19 bytes thanks to Giuseppe, by removing which, and table, and only slight changes to the implementation

Original

x=z=scan();for(i in names(r<-table(x)))z[which(x==i)]=1:r[i];z

I can't compete with Giuseppe's knowledge, so my submission is somewhat longer than his, but using my basic knowledge, I felt that this solution was rather ingenious.

r<-table(x) counts the number of times each number appears and stores it in r, for future reference

names() gets the values of each unique entry in the table, and we iterate over these names with a for loop.

The remaining portion checks which entries are equal to the iterations and stores a sequence of values (from 1 to the number of entries of the iteration)

Try it online!

Japt, 8 bytes

£¯YÄ è¶X

Try it here

£¯YÄ è¶X
             :Implicit input of array U
£            :Map each X at 0-based index Y
 ¯           :  Slice U to index
  YÄ         :    Y+1
     è       :  Count the elements
      ¶X     :    Equal to X

Ruby, 35 bytes

->a{f=Hash.new 0;a.map{|v|f[v]+=1}}

It's pretty mundane, unfortunately - build a hash that stores the total for each entry encountered so far.

Some other, fun options that unfortunately weren't quite short enough:

->a{a.dup.map{a.count a.pop}.reverse}   # 37
->a{i=-1;a.map{|v|a[0..i+=1].count v}}  # 38

Tcl, 48 bytes

proc C L {lmap n $L {dict g [dict inc D $n] $n}}

Try it online!

Java (JDK), 76 bytes

a->{for(int l=a.length,i,c;l-->0;a[l]=c)for(c=i=0;i<l;)c+=a[l]==a[i++]?1:0;}

Try it online!

Credits

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

x=>x.Select((y,i)=>x.Take(i).Count(z=>z==y))

Try it online!

R, 41 bytes

function(x)diag(diffinv(outer(x,x,"==")))

Try it online!

Oddly, returning a zero-based index is shorter in R.

APL (Dyalog Unicode), 7 bytes

Many, many thanks to H.PWiz, Adám and dzaima for all their help in debugging and correcting this.

+/¨⊢=,\

Try it online!

Explanation

The 10-byte non-tacit version will be easier to explain first

{+/¨⍵=,\⍵}

{         } A user-defined function, a dfn
      ,\⍵  The list of prefixes of our input list ⍵
           (⍵ more generally means the right argument of a dfn)
           \ is 'scan' which both gives us our prefixes 
           and applies ,/ over each prefix, which keeps each prefix as-is
    ⍵=     Checks each element of ⍵ against its corresponding prefix
           This checks each prefix for occurrences of the last element of that prefix
           This gives us several lists of 0s and 1s
 +/¨       This sums over each list of 0s and 1s to give us the enumeration we are looking for

The tacit version does three things

Jelly, 4 bytes

ċṪ$Ƥ

Try it online!

For each prefix of the input list, it counts the number of occurrences of its last element in itself.

Batch, 61 bytes

@setlocal
@for %%n in (%*)do @set/ac=c%%n+=1&call echo %%c%%

1-indexed. Because variable substitution happens before parsing, the set/a command ends up incrementing the variable name given by concatenating the letter c with the integer from the list (numeric variables default to zero in Batch). The result is then copied to another integer for ease of output (more precisely, it saves a byte).

Python 2, 47 43 bytes

f=lambda a:a and f(a[:-1])+[a.count(a[-1])]

Try it online!

A recursive 'one-based' solution.

05AB1E, 4 bytes

ηε¤¢

Try it online! or as a Test Suite

Explanation

ηε     # apply to each prefix of the input list
  ¤¢   # count occurrences of the last element

Retina 0.8.2, 30 bytes

\b(\d+)\b(?<=(\b\1\b.*?)+)
$#2

Try it online! Link includes test cases. 1-indexed. Explanation: The first part of the regex matches each integer in the list in turn. The lookbehind's group matches each occurrence of that integer on that line up to and including the current integer. The integer is then substituted with the number of matches.

JavaScript (ES6), 26 bytes

1-indexed.

a=>a.map(o=x=>o[x]=-~o[x])

Try it online!

Commented

a =>                // a[] = input array
  a.map(o =         // assign the callback function of map() to the variable o, so that
                    // we have an object that can be used to store the counters
    x =>            // for each value x in a[]:
      o[x] = -~o[x] //   increment o[x] and yield the result
                    //   the '-~' syntax allows to go from undefined to 1
  )                 // end of map()

Python 2, 48 bytes

lambda a:[a[:i].count(v)for i,v in enumerate(a)]

Try it online!