| Bytes | Lang | Time | Link |
|---|---|---|---|
| 034 | Juby | 250519T181257Z | Jordan |
| 004 | Thunno 2 | 230714T084238Z | The Thon |
| 004 | MATL | 190108T112011Z | Suever |
| 021 | Wolfram Language Mathematica | 190114T072617Z | alephalp |
| 013 | [APL Dyalog Unicode] | 220126T062334Z | Jayant C |
| 085 | Go | 220126T044833Z | cure |
| 025 | PowerShell Core | 220126T033647Z | Julian |
| 004 | Husk | 220104T174932Z | Natte |
| 001 | BQN | 220104T013151Z | lynn |
| 048 | Factor | 220104T012805Z | chunes |
| 004 | Vyxal | 220104T010039Z | lyxal |
| 122 | C++ gcc | 190113T093048Z | AZTECCO |
| 032 | Gema | 190830T121350Z | manatwor |
| 018 | K ngn/k | 190822T104532Z | scrawl |
| 174 | SAP ABAP | 190822T135752Z | Maz |
| 007 | Pyth | 190822T074150Z | ar4093 |
| 007 | J | 190108T101043Z | Galen Iv |
| 062 | C gcc | 190114T045139Z | att |
| 172 | C# .NET Core | 190114T165303Z | Destroig |
| 023 | Attache | 190114T125146Z | Conor O& |
| 032 | Pari/GP | 190114T065032Z | alephalp |
| 027 | R | 190112T140152Z | digEmAll |
| 014 | AWK | 190108T200112Z | Digital |
| 011 | Perl 5 | 190111T081826Z | Nahuel F |
| 024 | bash | 190108T151846Z | Nahuel F |
| 031 | awk | 190108T120134Z | Nahuel F |
| 063 | SNOBOL4 CSNOBOL4 | 190111T003756Z | Giuseppe |
| 017 | Reticular | 190111T002029Z | Wisław |
| 046 | Haskell | 190110T194518Z | Laikoni |
| 044 | Python 2 | 190110T001536Z | lynn |
| 015 | Perl 6 | 190108T094553Z | Jo King |
| 121 | GO 121 Bytes Not included new lines and tabs | 190109T053643Z | the ulti |
| 058 | Haxe | 190108T210929Z | Aurel |
| 034 | Ruby | 190108T205801Z | G B |
| 044 | Haskell | 190108T205358Z | ბიმო |
| 043 | R | 190108T174458Z | Sumner18 |
| 008 | Japt | 190108T101539Z | Shaggy |
| 035 | Ruby | 190108T173910Z | DaveMong |
| 048 | Tcl | 190108T153215Z | sergiol |
| 076 | Java JDK | 190108T150045Z | Olivier |
| 044 | C# Visual C# Interactive Compiler | 190108T122752Z | dana |
| 041 | R | 190108T154246Z | Giuseppe |
| 007 | APL Dyalog Unicode | 190108T142809Z | Sherlock |
| 004 | Jelly | 190108T102352Z | Mr. Xcod |
| 061 | Batch | 190108T100808Z | Neil |
| 043 | Python 2 | 190108T095238Z | Chas Bro |
| 004 | 05AB1E | 190108T094831Z | Emigna |
| 030 | Retina 0.8.2 | 190108T094505Z | Neil |
| 026 | JavaScript ES6 | 190108T093200Z | Arnauld |
| 048 | Python 2 | 190108T093635Z | TFeld |
Thunno 2, 4 bytes
ƒıṪc
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[#]&/@#)&
Wolfram Language (Mathematica), 28 bytes
(Clear@g;g@a_=0;++g[#]&/@#)&
Based on @att's answer to another challenge.
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}\$.
[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.
Husk, 4 bytes
z#ḣ¹
Explanation
one-indexed
z#ḣ¹ transforms to z#ḣ⁰⁰
z zip
ḣ⁰ prefixes of input
⁰ and input
# with count
Vyxal, 4 bytes
KƛtO
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;}
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]
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]
K (ngn/k), 18 bytes
(,/.!'#'=x)@<,/.=x
OLD APPROACH
K (ngn/k), 27 23 22 bytes
{x[,/.=x]:,/.!'#'=x;x}
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:
=xreturns a dict where keys are items of x and values are their indices (3 1 4 5 9 2 6!(0 9;1 3;,2;4 8 10;5 11;,6;,7))i:assign dict toi#:'count values for each key (3 1 4 5 9 2 6!2 2 1 3 2 1 1)!:'enumerate each value (3 1 4 5 9 2 6!(0 1;0 1;,0;0 1 2;0 1;,0;,0)),/.:extract values and flatten list (0 1 0 1 0 0 1 2 0 1 0 0)x[,/.:i]:extract indices from i, flatten, and assign each value from the right-side list at these indices
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:

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
.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._
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#.]=]\
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}
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]);}
-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;}
Attache, 23 bytes
{`~&>Zip[_,_[0:#_::0]]}
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}\$.
R, 27 bytes
function(x)ave(x,x,FUN=seq)
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
- 1 byte saved thanks to @NahuelFouilleul
{print++a[$1]}
The above does one-based indexing. If you prefer zero-based indexing, its an extra byte:
{print a[$1]++}
Perl 5, 11 bytes
$_=$h{$_}++
explanations following comment
$_perl's special variable containing current line when looping over input (-por-nswitches)$h{$_}++autovivifies the map%hand creates an entry with key$_and increments and gives the value before increment- the special variable is printed because of
-pswitch,-lswitch removes end of line on input and adds end of line on output
bash, 37 24 bytes
f()(for x;{ r+=$[a[x]++]\ ;};echo $r)
if valid, there is also this variation, as suggested by DigitalTrauma
for x;{ echo $[a[x]++];}
SNOBOL4 (CSNOBOL4), 63 bytes
T =TABLE()
R I =INPUT :F(END)
T<I> =OUTPUT =T<I> + 1 :(R)
END
Reticular, 17 bytes
L[ddc@c~]~*$qlbo;
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
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,
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
*>>.&{%.{$_}++}
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]);};
Haskell, 44 bytes
([]#)
x#(y:z)=sum[1|a<-x,a==y]:(y:x)#z
_#e=e
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)
Japt, 8 bytes
£¯YÄ è¶X
£¯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
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;}
Credits
- -2 bytes thanks to Kevin Cruijssen
C# (Visual C# Interactive Compiler), 44 bytes
x=>x.Select((y,i)=>x.Take(i).Count(z=>z==y))
R, 41 bytes
function(x)diag(diffinv(outer(x,x,"==")))
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.
+/¨⊢=,\
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
- First, it removes the instance of
⍵used in,\⍵as,\on the right by itself can implicitly figure out that it's supposed to operate on the right argument. - Second, for
⍵=, we replace the⍵with⊢, which stands for right argument - Third, now that we have no explicit arguments (in this case,
⍵), we can remove the braces{}as tacit functions do not use them
Jelly, 4 bytes
ċṪ$Ƥ
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).
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])
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()