Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

The task

In this challenge, your input is a non-empty list of positive integers, given in the native format of your language. Your output is that same list, in the same format, with some elements removed. You shall remove every occurrence of 1, every second occurrence of 2, every third occurrence 3, and so on. In general, for every positive integer N, you shall remove every Nth occurrence of N from the list, starting with the Nth occurrence.


Consider the input list


First, we remove every occurrence of 1:

[3,2,6,    6,2,3,2,6,6,6,6,  6,6,3,3,7,2]

Then every second occurrence of 2:

[3,2,6,    6,  3,2,6,6,6,6,  6,6,3,3,7  ]

Then every third occurrence of 3:

[3,2,6,    6,  3,2,6,6,6,6,  6,6,  3,7  ]

The numbers 4 and 5 don't occur in the input, so they can be skipped. Next, we remove every sixth occurrence of 6:

[3,2,6,    6,  3,2,6,6,6,    6,6,  3,7  ]

There's only one occurrence of 7, so that can be skipped as well. Thus the correct output is


Rules and scoring

You can write either a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

Test cases

[1] -> []
[2] -> [2]
[1,1,1] -> []
[2,2,2] -> [2,2]
[1,1,2,2,2,3,3,3,3] -> [2,2,3,3,3]
[1,2,3,1,2,3,1,2,3,1,2,3] -> [2,3,3,2,3]
[3,2,6,1,1,6,2,3,2,6,6,6,6,1,6,6,3,3,7,2] -> [3,2,6,6,3,2,6,6,6,6,6,3,7]
[5,4,5,4,3,5,4,5,4,5,4,3,5,4,5,3,3,3,4,5,4,5,4,5,4,3,3,3,5,4] -> [5,4,5,4,3,5,4,5,4,3,5,4,5,3,3,4,5,5,4,4,3,3,5,4]
[6,4,5,8,2,9,3,1,8,5,3,5,5,6,3,5,1,2,3,9,3,5,8,7,5,9,1,3,4,8,2,3,4,7,8,5,8,5,3,1] -> [6,4,5,8,2,9,3,8,5,3,5,5,6,3,9,3,5,8,7,5,9,4,8,2,3,4,7,8,5,8,5,3]
[4,4,9,12,9,4,4,4,12,9,12,9,12,4,12,4,4,9,4,9,12,4,12,4,4,12,4,4,9,12,9,12,9,4,9,12,4,9,12,9,12,9,4,9,12,12,4,4,12,4] -> [4,4,9,12,9,4,4,12,9,12,9,12,4,12,4,9,4,9,12,4,12,4,12,4,4,9,12,9,12,4,9,12,9,9,12,9,4,9,12,12,4,4,12]
[2,2,11,11,11,11,6,2,2,6,6,2,2,2,2,6,11,6,11,11,2,11,2,6,6,11,2,11,6,2,6,6,6,6,6,11,2,11,11,6,6,6,11,6,2,6,2,6,6,2,11,2,2,11,11,11,11,2,6,2] -> [2,11,11,11,11,6,2,6,6,2,2,6,11,6,11,11,2,11,6,11,2,11,6,6,6,6,6,2,11,11,6,6,6,11,6,2,6,6,11,2,11,11,11,11,2,6]
[20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102] -> [20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,21,22,100,101,102,20,22,100,101,102,20,21,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,21,22,100,101,102,20,21,22,100,101,102,20,22,100,101,102,20,21,22,100,101,102,20,21,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,21,22,101,102,20,21,22,100,102,20,21,22,100,101,20,21,22,100,101,102,20,21,22,100,101,102,20,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,22,100,101,102,20,21,100,101,102]


Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language. To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

## Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

## Ruby, <s>104</s> <s>101</s> 96 bytes

If you want to include multiple numbers in your header, make sure that the actual score is the last number in the header:

## Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:

## [><>](, 121 bytes

var QUESTION_ID=70091,OVERRIDE_USER=32014;function answersUrl(e){return""+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return""+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",,t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",,i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src=""></script> <link rel="stylesheet" type="text/css" href="//"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

share|improve this question

20 Answers 20

up vote 12 down vote accepted

Jelly, 10 8 bytes


Thanks to @Sp3000 for golfing off 2 bytes!

Try it online!

How it works

=;\S€%af    Main link. Input: A (list)

 ;\         Compute the cumulative concatenations of the elements of A, i.e., the
            list of A's prefixes.
=           Compare the elements of the nth prefix with the nth element of A.
   S€       Compute the sum of the resulting arrays.
     %      Take the nth sum modulo the nth element of A.
      a     Logical AND; replace the nth remainder with the nth element of A
            if the remainder is non-zero.
        f   Filter; remove the zeroes (which do not occur in A) from the result.
share|improve this answer
how does that comparison step work? and are the prefixes of [5,4,3,2,1] [[5],[5,4],[5,4,3],[5,4,3,2],[5,4,3,2,1]] or [[1],[2,1],[3,2,1],[4,3,2,1],[5,4,3,2,1]]? – quintopia Jan 27 at 8:43
@quintopia Jelly is left-to-right, so it is the first. = compares integers. For example, [3,2,1]=;\ compares 3 with the element of [3], 2 with the ones of [3, 2] and 1 with those of [3, 2, 1], giving [1, [0, 1], [0, 0, 1]]. – Dennis Jan 27 at 15:07
Ah I was missing that it was comparing a list to a list element-by-list. – quintopia Jan 27 at 16:01

awk, 10 bytes

Input is expected on STDIN, one number per line.



Keeps a counter for each number in an associative array, prints only if the counter value modulo n is not zero. Printing is implicit. Long version:

++a[$1]%$1{print $0}
share|improve this answer

Pyth, 18 15 14 10 9 bytes


I think this is the first code I've written that has five consecutive variable references in nine bytes.

I wish the array manipulation solution (u.DG%HgxHGH{QQ, 14 bytes) weren't so long.

f%/aYTTTQ       Implicit: Q=input
                 lambda T:
    Y              Variable: starts as empty list.
   a T             Append T to Y. Mutates Y.
  /   T           Number of elts of Y that equal T.
 %     T         Modulo by T
f       Q       Filter that lambda over Q.

Try it here.

share|improve this answer

Perl 6, 28 bytes

{$_=$;grep {++.{$^n}%$n},@_} # 28 bytes
  $_=$;        # put $_ in a clean state
  grep {
    ++.{$^n}   # increment $_{ $n } and declare $n as an argument
    % $n       # check if the count is not divisible by $n
  }, @_        # the input


# give it a lexical name for ease of use
my &code = {...}

sub check ( @a, @b ){
  say try { so all code(@a) »==« @b } // False

check [1], []; # True
check [2], [2]; # True
check [1,1,1], []; # True
check [2,2,2], [2,2]; # True
check [1,1,2,2,2,3,3,3,3], [2,2,3,3,3]; # True
check [1,2,3,1,2,3,1,2,3,1,2,3], [2,3,3,2,3]; # True
check [3,2,6,1,1,6,2,3,2,6,6,6,6,1,6,6,3,3,7,2], [3,2,6,6,3,2,6,6,6,6,6,3,7]; # True

Double check that the correct elements are being thrown out

# have to change it to a pure number
# when checking $_         V
my &code = {$_=$;grep {++.{+$^n}%$n},@_}
# only matters here because we are using
# a subclass of Int but want it to use
# the same key as a normal Int

sub F ( Int $v ) { $v, "Fail($v)" }
# prove that it passes through unchanged
say [F(2)];
# (Fail(2))

say code [3,2,6,F(1),F(1),6,F(2),3,2,6,6,6,F(6),F(1),6,6,F(3),3,7,F(2)];
# (3 2 6 6 3 2 6 6 6 6 6 3 7)
share|improve this answer

Python, 57 bytes

lambda l:[n for i,n in enumerate(l)if l[:i+1].count(n)%n]
share|improve this answer

Seriously, 22 17 bytes


Hex Dump:


Try It Online


k╗                                Put empty list in reg0
  ,;                              Two copies of input
    `        `M                   Map over the list
     ;;                           Make 2 extra copies of n
       ╜o                         Load reg0 and push the n onto it
         ;╗                       Put a copy back in reg0
           c                      Count the number of copies of n in the list
            %                     Take the result modulo n
               @░                 Filter the original list with the resulting list
share|improve this answer
This language... – Nico Jan 25 at 9:44

JavaScript ES6, 34 bytes


Turned out to be the same as Brad's Perl algorithm.

Edit: Saved 2 bytes thanks to @edc65.

share|improve this answer
Good! save 2 bytes removing the inner parentheses a=>a.filter(v=>f[v]=-~f[v]%v,f=[]) – edc65 Jan 25 at 9:46

Mathematica, 40 38 36 bytes


This is an unnamed function taking and returning a List. It defines a named function f when executed (to keep track of the numbers), but takes care of resetting the relevant definitions of f beforehand.


The way functions (or function definitions) work in Mathematica is really powerful. As in Haskell (for instance), functions cannot only be overloaded and defined for certain types, but also for individual values (or arbitrary patterns of arguments, actually). But it is even more powerful than Haskell in that a) these values can be defined as side effects during control flow and b) the values can also be redefined at any time. That means functions are actually pretty powerful lookup tables (that can optionally compute the looked-up value instead of just storing it).

If we remove the golfitude from the code it would look a bit like this:

g[list_] := (
    (f[#] = #) &,
    Mod[++f[#], #] > 0 &

So first, we loop over the input and define f[x] = x, for all x in the list. f will ultimately be used to keep track of how often each number has already appeared in the list. Why do we not count from 0? The loop over the list is a Map. The expression f[x] = y returns y (in addition to storing the function definition). So by setting f[x] to x, the map will evaluate to the input list itself. That saves two bytes because then we don't need to provide list again explicitly to Select. Starting from x instead of 0 doesn't affect the computation at all since we're only ever interested in Mod[f[x], x].

(Normally we could simply use something like f[_] = 0 as a fallback definition to avoid the Map, but we don't know if our function has been used before, which would leave some previous values defined that would mess with our counting.)

Then Select filters the list by keeping only those elements where the unnamed function passed as the second argument yields True. That function first increments the value of f[x] (where x is the current list element), in order to count the occurrences, and then it takes the resulting count modulo x. We want to discard all elements where this yields 0.

share|improve this answer

CJam, 17 bytes


Just beat... J? Not sure what my expectations are for this challenge, really. Note that "" is CJam's representation of an empty array.

Try it online | Test suite (the last case is too long for the permalink)


L                     Push empty array (let's call it L)
 q~                   Push input and evaluate

   {         },       Filter the array elements by...
    :X                   Save number to variable X
      +                  Append to L

       _                 Duplicate
        Xe=              Count occurences of X
           X%            Take modulo X

                      The top element is popped to determine whether or not to keep that
                      element, with the updated L kept on the stack for the next iteration

               p      Print the resulting filtered array
                ;     Pop L, which is now equal to the input array
share|improve this answer

JavaScript ES6, 55 bytes



a=>                            //a -> input array
 a.filter(                     //filter array. only keep elements if inside function returns truthy
      (v,i)=>                  //inside function to decide whether to keep items. v -> item; i -> index
           a.filter((w,j)=>    //get all ocurrences of v that occur before index i
                j<=i&v==w      //(this is done by keeping all items w at index j, if j <= i and v == w
           ).length%v          //get length (count ocurrences), and mod v.
                               //this will only be falsy if the number of ocurrences of v up to this index is divisible by v. (0 -> falsy, positive -> truthy) 
 )                             //so, we don't keep every second 2, every third 3, etc.
share|improve this answer

J, 18 bytes



   (#~((0<]|+/@:=){:)\) 1 2 3 1 2 3 1 2 3 1 2 3
2 3 3 2 3

Pretty straightforward method. We count the occurrences of a number up to it and select the number only if the number divides the count.

More explanation comes later.

Try it online here.

share|improve this answer

PowerShell, 56 bytes


Uses a similar helper-array-trick as Rainer P's answer, which I developed independently but I apparently got FGITW'd.

Takes input as an array with param($a). We then create our helper array $b as a populated-with-zeros array by using the comma operator coupled with the overloaded multiplication operator. This creates $b to be equal to @(0,0,0...0) with $b.length equal to the maximal number in $a.
(Quick plug for my "Showcase your language" answer where I describe this in detail)

Next is our output. We loop over every element of our input array $a|%{...} and each loop check an if statement. The conditional pre-increments the value in our helper array that corresponds with the current element, then checks whether it's a multiple of the current element with the modulo operator. If it is a multiple, the % will equal 0 which is falsey, so the if doesn't execute. Otherwise, we output the current element.

Takes advantage of implicit typecasting to save on output formatting. If a function or program returns multiple elements, and you save the results to a variable, PowerShell will dynamically create that variable as an array. Example:

PS C:\Tools\Scripts\golfing> $testc = .\remove-every-nth-n.ps1 @(2,2,2)

PS C:\Tools\Scripts\golfing> $testc

PS C:\Tools\Scripts\golfing> $testc.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------             
True     True     Object[]                                 System.Array
share|improve this answer

R, 110 98 99 92 Bytes

function(a){for(i in 1:max(a))for(j in seq_along(b<-which(a==i)))if(j%%i<1)a[b[j]]=0;a[a>0]}

Edit complete rewrite fixes bug with test case 2/3 Edit 2 Save 7 bytes thanks to @Alex-A

share|improve this answer
92 bytes: function(a){for(i in 1:max(a))for(j in seq_along(b<-which(a==i)))if(j%%i<1)a[b[j]]=0;a[a>0]} – Alex A. Jan 25 at 5:52

MATL, 20 bytes


This uses current release (10.2.1) of the language/compiler.

Try it online!


tu        % implicitly input array. Duplicate and get unique elements
"         % for each unique element, say "i"
  t       % duplicate
  @=f     % indices of occurrences of i
  @@h0h   % build index representing i-th occurrences (Matlab's i:i:end)
  )       % keep only indices of i-th occurrences
  0w(     % set those entries to 0
]         % end for loop
tg)       % keep nonzeros only. Implicit display
share|improve this answer

R, 63 bytes

f=function(z){n=seq(z);for(i in n)z[which(z==i)[n*i]]=0;z[z>0]}
share|improve this answer

C#, 224 bytes

List<int>R(List<int>l,int n=1){l=l.Where(w=>w!=0&&w!=1).ToList();for(int i=0,t=0;i<l.Count;i++){if(l[i]==n&&++t==n){l[i]=0;t=0;}}return !l.Any()||n>l.Max()?l:R(l,++n);}

This code uses recursion. With using statements that's 224 bytes (160 for the method code itself).

Try it online.

List <int> R(List <int> l, int n = 1)
    l = l.Where(w => w > 1).ToList();
    for (int i = 0, t = 0; i < l.Count; i++)
        if (l[i] == n && ++t == n)
            l[i] = 0;
            t = 0;
    return !l.Any() || n > l.Max() ? l : R(l, ++n);
share|improve this answer
You should be able to save a few chars by removing the continue statement. Something like (untested) for(int i=0,t=0;i<l.Count;i++)if(l[i]==n&&++t==n)l[i]=t=0; – Peter Taylor Jan 25 at 14:41
@peter-taylor, you're right, thanks. Also, had to add some code to fixed a bug. – Dmitry Stepanov Jan 25 at 15:35
If you've imported System.Linq then !l.Any() is shorter than l.Count<1, which is shorter than l.Count==0. – Peter Taylor Jan 25 at 16:11
@peter-taylor thanks, I also replaced w != 0 && w !=1 with w > 1. – Dmitry Stepanov Jan 25 at 17:04

C# - 177 Bytes

void r(List<int> i){for(int c=1,k=1,m=i.Max();k<=m;k++){var n=new List<int>();foreach(var o in i)if(o==k&&c++==k)c = 1;else n.Add(o);i=n;}Console.WriteLine(string.Join(" ",i));}


void r(List<int> i)
    for (int c = 1, k = 1, m = i.Max(); k <= m; k++)
        var n = new List<int>();
        foreach (var o in i)
            if (o == k && c++ == k)
                c = 1;
        i = n;
    Console.WriteLine(string.Join(" ", i));
share|improve this answer
I believe you would have to count the using statements, in which case this would be 241 bytes long. – LegionMammal978 Jan 25 at 12:02

Mathematica, 63 bytes


Quite interesting to golf! Ignore the occasional message that pops up.

share|improve this answer

Ruby, 120 bytes

->a{1.upto(a.max).each{|i|k=0;a.length.times.each{|j|k+=1if a[j]==i;a[j]=''if k%i==0&&a[j]==i;a[j]}};{|i|i!=''}}
share|improve this answer

TI-BASIC, 47 bytes

Input X
If fPart(sum(∟X=Ans),1,I)/Ans

This uses the fact that, on a fresh calculator, L₁ is initialized and cleared. Note that trying to display an empty list in TI-BASIC throws an error.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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