g | x | w | all
Bytes Lang Time Link
015K ngn/k210224T235024Zcoltim
005Vyxal240822T014640Zemanresu
005BQN240821T233006ZDLosc
048Arturo240821T122300Zchunes
057Desmos230110T034442ZAiden Ch
046Factor221230T201642Zchunes
00605AB1E210310T161332ZKevin Cr
101Java JDK210307T155222Zbranboye
114TSQL210225T043158ZDanielOn
008Japt210225T065230ZKamil Dr
066Python3210225T060300ZDanielOn
056C# Visual C# Interactive Compiler210225T100556Zpinkfloy
062R210224T001824ZDominic
028Wolfram Language Mathematica210224T194938Zatt
087SNOBOL4 CSNOBOL4210224T223638ZGiuseppe
048R210224T211038ZGiuseppe
009AWK vn=210224T010144ZDigital
157Java210224T184250ZUnmitiga
037PowerShell Core210224T041024ZJulian
076Clojure210224T152037ZKirill L
038Ruby210224T115240ZG B
035JavaScript ES6210224T011830ZArnauld
054Haskell210224T044353ZAZTECCO
028Perl 5 al210224T032616ZXcali
050Python 2210224T022009Zxnor
004Husk210224T024811ZLeo
044Haskell210224T024659Zxnor
005Stax210224T020617ZRazetime
013J210224T023108ZFrownyFr
005Jelly210224T020938ZUnrelate
062C clang210224T015708ZAZTECCO
043Julia 1.0210224T010834ZMarcMush
019APL Dyalog Unicode210224T005245Zuser
009MATL210224T004315ZLuis Men
057Python 3210224T010642ZNoodle9
017J210224T010426ZBubbler
009Husk210224T005247ZDominic
011Charcoal210224T004429ZNeil
052Retina 0.8.2210224T003921ZNeil

K (ngn/k), 18 16 15 bytes

-1 byte from @ovs's solution

{x(!#x)^/y_'=x}

Try it online!

Vyxal, 5 bytes

UẋfÞ∩

Try it Online!

   Þ∩ # Take the multiset intersection, preserving order, with
U     # All distinct elements of the input
 ẋf   # Repeated n times

BQN, 5 bytes

>⟜⊒/⊢

A dyadic function that takes the number on the left and the list on the right. Try it at BQN online!

Explanation

This is a direct translation of the procedure in the OP's worked example:

  ⊒     Occurrence count: for each element, how many times has it occurred before?
>⟜      1 if this is less than the cutoff, 0 otherwise
   /⊢   Repeat each element in the list that many times (i.e. remove the ones that
        correspond to 0s)

Arturo, 48 bytes

$[a,n][o:@.of:10 0filter a'x->n<o\[x]:<=o\[x]+1]

Try it!

Explanation

$[a,n][]         ; a function taking args a and n
o:               ; to o, assign
@.of:10 0        ; an array of ten zeros
filter a'x->     ; remove elts from a with func, current elt is x
n<               ; is n less than
o\[x]:<=o\[x]+1  ; increment and return o[x]

Desmos, 57 bytes

f(l,n)=l[[l[1...i][l=l[i]].lengthfori=[1...l.length]]<=n]

The double .length is really bugging me but I can't think of a way to circumvent that at the moment...

Try It On Desmos!

Try It On Desmos! - Prettified

Factor, 46 bytes

[ '[ [ dup inc get _ > ] reject ] with-scope ]

Attempt This Online!

05AB1E, 6 bytes

ʒˆ¯¤¢@

Try it online or verify all test cases.

Explanation:

ʒ       # Filter the (implicit) input-list by:
 ˆ      #  Pop and push the current value to the global array
  ¯     #  Push the global array
   ¤    #  Get its last item (without popping the list itself)
    ¢   #  Count how many times it occurs in the global array
     @  #  And check if the (implicit) input-integer is >= this count
        # (after which the filtered list is output implicitly)

Java (JDK), 101 bytes

l->n->{for(int i=0,j,c;i++<9;)for(j=c=0;j<l.size();)j+=l.get(j)==i?++c>n?l.remove(j)*0:1:1;return l;}

Try it online!

Input: ArrayList<Integer>

Output: ArrayList<Integer>

T-SQL, 114 bytes

SELECT C FROM (SELECT B,C,row_number() OVER (PARTITION BY C ORDER BY B) AS D FROM @A) E WHERE D <= @n ORDER BY B;

Example:

DECLARE @A TABLE(B INT IDENTITY(1,1), C INT);
DECLARE @n INT;
INSERT INTO @A SELECT * FROM (VALUES(1),(2),(3),(2),(3),(2),(4),(1),(2)) AS A(C);
SET @n = 2;

SELECT C --4.Finally select the filtered rows
FROM (SELECT B
            ,C
            ,row_number() OVER (PARTITION BY C ORDER BY B) AS D --1.Create an ordinal for each repetition that increments in ascending order of B
      FROM @A
      ) E 
WHERE D <= @n --2.Filter on the windowed function in subquery, removing rows with more than n repetitions
ORDER BY B; --3. Preserve original order of table variable @A (Can't order by in subquery)

Returns:

C
1 1
2 2
3 3
4 2
5 3
6 4
7 1

Only way I could simulate an 'array' was by making a table with an identity on insert to store the insertion order.

Japt, 8 bytes

fVÆâÃc 2

Try it online! or Check all test cases

Very similar to the Jelly, Stax, and Husk answers.

Explanation:

            # Implicitly store the input array as U and the input number as V
 VÆ         # Create an array of length V
   âà       #  Each item in the array is the unique elements of U
     c      # Flatten that array
f           # Only keep elements of U that are in that array...
       2    # ... up to the number of times it appears in that array

Python3, 66 Bytes

def f(A,n):[A.pop(-A[::-1].index(i)-1) for i in A if A.count(i)>n]

There are already superior Python answers to this, but thought it's worth a mention as it only uses list methods.

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

(a,n)=>{var b=new int[10];return a.Where(c=>b[c]++<n);} 

Try it online!

Or 66 bytes if output should explicitly be an array vs an enumerable:

(a,n)=>{var b=new int[10];return a.Where(c=>b[c]++<n).ToArray();} 

Try it online!

R, 62 bytes

function(x,n)x[sapply(seq(x),function(i)sum(x[1:i]==x[i]))<=n]

Try it online!


...although a port of Luis Mendo's answer is shorter at 59 58 bytes (Thanks to Giuseppe)

Wolfram Language (Mathematica), 31 28 bytes

nFold[#||Count@##<n&&#2&]

Try it online!

Returns an Or of digits. Input [n][A].

SNOBOL4 (CSNOBOL4), 87 bytes

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

Try it online!

Takes input as N, then A, each element separated by newlines.

	N =INPUT			;* Read in N, number to keep
	T =TABLE()			;* create an empty table
R	I =INPUT	:F(END)		;* read in the next input; if none exists, exit
	T<I> =T<I> + 1			;* increment the value at index I (initially 0)
	OUTPUT =I LE(T<I>,N)	:(R)	;* if T<I> is LEQ to N, then output I. Goto R.
END

R, 48 bytes

function(x,n)x[diag(diffinv(outer(x,x,"=="))<n)]

Try it online!

Test harness taken from Dominic's answer.

Closely related to Luis Mendo's answer, though implementing it in MATL is longer. Rather than zeroing out the lower triangle of the matrix and computing the column sums, this calculates the cumulative sum of each column, then takes the diagonal of the resulting matrix as the filtering criterion -- for some element \$a_i\$ this tells the number of occurrences of \$a_i\$ before index \$i\$.

So for instance, using [6,9,7,6,7,9,9]:

Pairwise equality check:
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    0    0    1    0    0    0
[2,]    0    1    0    0    0    1    1
[3,]    0    0    1    0    1    0    0
[4,]    1    0    0    1    0    0    0
[5,]    0    0    1    0    1    0    0
[6,]    0    1    0    0    0    1    1
[7,]    0    1    0    0    0    1    1

Column-wise cumulative sum (with an initial condition of 0):
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    0    0    0    0    0    0    0
[2,]    1    0    0    1    0    0    0
[3,]    1    1    0    1    0    1    1
[4,]    1    1    1    1    1    1    1
[5,]    2    1    1    2    1    1    1
[6,]    2    1    2    2    2    1    1
[7,]    2    2    2    2    2    2    2
[8,]    2    3    2    2    2    3    3
The diagonal:
[1] 0 0 0 1 1 1 2

AWK -vn=, 9

a[$1]++<n

This is so competitive with the golfing-language answers, I feel like I might have misunderstood the question - did I?

The limit n is passed as a variable at the command line with -vn=<value>. The array is read from STDIN.

Try it online!

Java, 157 bytes

l->n->java.util.stream.IntStream.range(0,l.length).filter(i->java.util.stream.IntStream.range(0,i+1).filter(j->l[j]==l[i]).count()<=n).map(i->l[i]).toArray()

Takes a int[] and the integer n as input and returns a int[].

Try it online!

PowerShell Core, 38 37 bytes

$a,$b=$args
$t=@{}
$a|?{++$t.$_-le$b}

-1 byte thanks to mazzy!

Try it online!

Clojure, 76 bytes

#(for[[i v](map vector(range)%1):when(<(count(filter #{v}(take i %1)))%2)]v)

Try it online!

Ruby, 38 bytes

->a,n{w=[0]*10;a.reject{|x|n<w[x]+=1}}

Try it online!

JavaScript (ES6), 35 bytes

Expects (A)(n), where A is an array of digit characters.

a=>n=>a.filter(v=>!(a[~v]+=v)[n+9])

Try it online!

How?

We use the underlying object of a[] to keep track of the number of times each digit has appeared in the string.

By using ~v, we make sure that we use a property of the object (a negative value as a string) rather than an index of the array (which is already filled with the input values).

The first time we append v to a[~v], we get undefined coerced to a string followed by the digit character. Because "undefined" is 9 characters long, we know that we've reached n+1 occurrences of v by testing a[~v][n+9].


JavaScript (ES6), 37 bytes

Expects (A)(n), where A is an array of integers.

a=>n=>a.filter(v=>(a[~v]=-~a[~v])<=n)

Try it online!

Haskell, 54 bytes

f n|let a?x|sum[1|y<-a,y==x]<n=a++[x]|1>0=a=foldl(?)[]

Try it online!

Perl 5 -al, 28 bytes

$l=<>;map$k{$_}++<$l&&say,@F

Try it online!

Python 2, 50 bytes

lambda s,n:reduce(lambda r,x:r+x*(r.count(x)<n),s)

Try it online!

-2 bytes from Leo by taking input and output as a string of digits, which is also used in the answers below


Python 3.8 (pre-release), 53 bytes

lambda s,n,r='':[x for x in s if(r:=r+x).count(x)<=n]

Try it online!

Input and output as list of characters.


55 bytes

f=lambda s,n:s and f(s[:-1],n)+s[-1][s.count(s[-1])>n:]

Try it online!

Repeatedly takes and removes the last element of the list, keeping it if it appears a maximum of n times in the current list.

It feels like there should be a better way to express this, but I'm not seeing it. Python is clumsy at dealing with the end of a list. While l[-k:] usually takes the last k elements from the end, for k=0 it instead takes the whole list. So, I didn't find a nice single slice that conditionally takes 0 or 1 elements from the end of a list. Also, doing l.pop() has the trouble that the recursive function call comes before the expression where we want the last element.

Husk, 4 bytes

n¹*u

Try it online!

I've tried a few different ways, but Razetime's approach turned out to be very concise in Husk.

Explanation

n¹*u    Function of two arguments: A=[6,9,7,6,7,9,9], n=2
   u    Unique values of A: [6,9,7]
  *     Repeated n times: [6,9,7,6,9,7]
n¹      Intersected with A: [6,9,7,6,7,9]

Haskell, 44 bytes

f n=foldl(\r x->r++[x|sum[1|y<-r,y==x]<n])[]

Try it online!

Stax, 6 5 bytes

°º☻¿_

Run and debug it

Output as a string of codepoints(since stax prints all numeric arrays as strings). Verifiable version

Explanation

cua*|b
c       copy the list
 u      uniquify
  a     bring the count to the top
   *    repeat the elements n times
    |b  multiset intersect

J, 13 bytes

(>:1#.]=]\)#]

Try it online!

Jelly, 5 bytes

œ&Qx¥

Try it online!

Accidental translation of Razetime's Stax answer based on his comment.

œ&       Multiset intersection of A with
  Q ¥    the unique elements of A
   x     repeated n times.

Jelly, 7 bytes

xċṪ$Ƥ<¥

Try it online!

I was going to hold off on posting until I tied caird's 6 bytes, but I feel like I'm so far off the mark that it's worth documenting anyhow.

x     ¥    Repeat each element of A by the corresponding elements of:
    Ƥ      for each prefix of A,
 ċ         how many times it contains
  Ṫ$       its last element (which is then not considered).
     <     Is each count less than n?

C (clang), 62 bytes

f(*l,n){for(int m[10]={0};*l;++l)m[*l]++<n&&printf("%d ",*l);}

Try it online!

If tacking a 0 filled array as an additional input is valid:

C (clang), 58 bytes

f(*l,n,*o){for(int m[10]={0};*l;++l)m[*l]++<n&&(*o++=*l);}

Try it online!

Julia 1.0, 46 43 bytes

l$n=(j=0;!i=sum(l[1:(j+=1)].==i)<=n;l[.!l])

Try it online!

APL (Dyalog Unicode), 23 19 bytes

Saved a couple bytes by looking at Bubbler how negated the mask in their answer.

{⍺/⍨(⊢∨(≠⍺×~))⍣⍵⊢0}

Don't try it online! because TIO has an older version of Dyalog APL without Unique Mask.

Takes the array on the left and n on the right.

This takes advantage of monadic , which gives a mask to obtain unique elements. While ≠A lets you keep unique elements in A, the mask 1-≠A inverts it and lets you keep only repeated elements in A. Then A×1-≠A replaces unique elements with zeroes (this is safe because as the question states, A only contains numbers 1-9). The mask ≠A×1-≠A gives us only unique elements from this new array, but since we replaced unique elements, it lets us keep duplicates (and the first element, but that is always kept no matter what anyway). (≠A)∨≠A×1-≠A now gives us a mask for unique elements and duplicates, but not triplicates, etc. By repeating this process n times, we get a mask for keeping only n-plicates, and then we just apply that mask to A to get the result.

MATL, 9 bytes

t&=Rsi>~)

Inputs A, then n. Try it online!

Or verify all test cases. For each case this takes a third input containing the desired output. The footer code checks if the program output equals the desired output, and prints Correct or Incorrect accordingly.

How it works

Consider inputs [1 2 3 2 3 2 4 1 2] and 2 as an example.

t    % Implicit input: array A. Duplicate
     % STACK: [1 2 3 2 3 2 4 1 2], [1 2 3 2 3 2 4 1 2]
&=   % Matrix of pairwise comparisons
     % STACK: [1 2 3 2 3 2 4 1 2], [1 0 0 0 0 0 0 1 0
                                    0 1 0 1 0 1 0 0 1;
                                    0 0 1 0 1 0 0 0 0;
                                    0 1 0 1 0 1 0 0 1;
                                    0 0 1 0 1 0 0 0 0;
                                    0 1 0 1 0 1 0 0 1;
                                    0 0 0 0 0 0 1 0 0;
                                    1 0 0 0 0 0 0 1 0;
                                    0 1 0 1 0 1 0 0 1]
R    % Upper triangular part: sets entries below the diagonal to 0
     % STACK: [1 2 3 2 3 2 4 1 2], [1 0 0 0 0 0 0 1 0;
                                    0 1 0 1 0 1 0 0 1;
                                    0 0 1 0 1 0 0 0 0;
                                    0 0 0 1 0 1 0 0 1;
                                    0 0 0 0 1 0 0 0 0;
                                    0 0 0 0 0 1 0 0 1;
                                    0 0 0 0 0 0 1 0 0;
                                    0 0 0 0 0 0 0 1 0;
                                    0 0 0 0 0 0 0 0 1]
s    % Sum of each column. For each entry of A this gives the number
     % of repetitions up to that point
     % STACK: [1 2 3 2 3 2 4 1 2], [1 1 1 2 2 3 1 2 4]
i    % Input: number a
     % STACK: [1 2 3 2 3 2 4 1 2], [1 1 1 2 2 3 1 2 4], 2
>~   % Less than or equal? Element-wise
     % STACK: [1 2 3 2 3 2 4 1 2], [1 1 1 1 1 0 1 1 0]
)    % Apply as an index (logical mask)
     % STACK: [1 2 3 2 3 4 1]
     % Implicit display

Python 3, 57 bytes

lambda a,n:[e for i,e in enumerate(a)if a[:i].count(e)<n]

Try it online!

J, 17 bytes

0-.~]-1&(]*(-~:))

Try it online!

Apparently, this is shorter than a solution using Self-classify = or self equality =/~.

How it works

0-.~]-1&(]*(-~:))  NB. left: n, right: A
      1&(       )  NB. Apply this function on A, n times...
      1    (-~:)   NB.   Negation of Nub Sieve (mark first occurrence of each number)
         ]*        NB.   Multiply to A so that each first occurrence becomes 0
    ]-             NB. Kill (change to 0) survivors of ^ from the original A
0-.~               NB. Erase zeros by set difference

Illustration:

n = 2, A = 2 3 8 1 6 4 8 2 8 3
First iteration:
Nub sieve of A = 1 1 1 1 1 1 0 0 0 0
Kill them      = 0 0 0 0 0 0 8 2 8 3

Second iteration:
Nub sieve of ^ = 1 0 0 0 0 0 1 1 0 1
Kill them      = 0 0 0 0 0 0 0 0 8 0

Kill the survivors of ^ = 2 3 8 1 6 4 8 2 0 3
Erase zeros by set diff = 2 3 8 1 6 4 8 2 3

Husk, 9 bytes

fm≤⁰Sz#ḣ³

Try it online!

f           # filter input to retain only elements at positions of truthy values of
 m≤⁰        # elements less-than-or-equal to arg 2 of
    Sz#     # count the occurrences of each element of arg1
       ḣ³   # in the list of prefixes of arg1

Charcoal, 11 bytes

NθΦη‹№…ηκιθ

Try it online! Link is to verbose version of code. Takes input n as an integer and A as a string of digits. Explanation:

Nθ          Input `n` as an integer
   η        Input `A`
  Φ         Filtered where
     №      Count of
         ι  Current character in
      …ηκ   Prefix so far
    ‹       Is less than
          θ Input `n`
            Implicitly print

Retina 0.8.2, 52 bytes

\d+$
$*
(.)(?=.*,(.)+)(?<=(?(2)$)(?<-2>\1.*)+.)|,.+

Try it online! Link includes test cases. Takes A as a string of digits and n as a positive integer separated by a comma. Explanation:

\d+$
$*

Convert n to unary.

(.)(?=.*,(.)+)(?<=(?(2)$)(?<-2>\1.*)+.)|,.+

Delete any digit of A that is preceded by at least n identical digits and also delete n from the result.