44
\$\begingroup\$

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.

Example

Consider the input list

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

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

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

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]

Leaderboard

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:

## [><>](http://esolangs.org/wiki/Fish), 121 bytes

var QUESTION_ID=70091,OVERRIDE_USER=32014;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+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}}",e.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,link:e.link}});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}}",o.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="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <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>

\$\endgroup\$
0

26 Answers 26

35
\$\begingroup\$

awk, 10 bytes

Input is expected on STDIN, one number per line.

++a[$1]%$1

Explanation

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

Pyth, 18 15 14 10 9 bytes

f%/aYTTTQ

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.

\$\endgroup\$
0
16
\$\begingroup\$

Jelly, 10 8 bytes

=;\S€%af

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.
\$\endgroup\$
3
  • \$\begingroup\$ 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]]? \$\endgroup\$
    – quintopia
    Jan 27, 2016 at 8:43
  • \$\begingroup\$ @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]]. \$\endgroup\$
    – Dennis
    Jan 27, 2016 at 15:07
  • \$\begingroup\$ Ah I was missing that it was comparing a list to a list element-by-list. \$\endgroup\$
    – quintopia
    Jan 27, 2016 at 16:01
10
\$\begingroup\$

Python, 57 bytes

lambda l:[n for i,n in enumerate(l)if l[:i+1].count(n)%n]
\$\endgroup\$
8
\$\begingroup\$

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
}

Usage:

# 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 ) { IntStr.new: $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)
\$\endgroup\$
6
\$\begingroup\$

JavaScript ES6, 34 bytes

a=>a.filter(v=>f[v]=-~f[v]%v,f=[])

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

Edit: Saved 2 bytes thanks to @edc65.

\$\endgroup\$
1
  • \$\begingroup\$ Good! save 2 bytes removing the inner parentheses a=>a.filter(v=>f[v]=-~f[v]%v,f=[]) \$\endgroup\$
    – edc65
    Jan 25, 2016 at 9:46
6
\$\begingroup\$

Seriously, 22 17 bytes

k╗,;`;;╜o;╗c%`M@░

Hex Dump:

6bbb2c3b603b3bbd6f3bbb6325604d40b0

Try It Online

Explanation:

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
\$\endgroup\$
1
  • 10
    \$\begingroup\$ This language... \$\endgroup\$
    – Nico
    Jan 25, 2016 at 9:44
5
\$\begingroup\$

Mathematica, 40 38 36 bytes

Select[(f@#=#)&/@#,++f[#]~Mod~#>0&]&

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.

Explanation

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_] := (
  Map[
    (f[#] = #) &,
    list
  ];
  Select[
    list,
    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.

\$\endgroup\$
5
\$\begingroup\$

CJam, 17 bytes

Lq~{:X+_Xe=X%},p;

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)

Explanation

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

J, 18 bytes

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

Usage:

   (#~((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.

\$\endgroup\$
4
\$\begingroup\$

JavaScript ES6, 55 bytes

a=>a.filter((v,i)=>a.filter((w,j)=>j<=i&v==w).length%v)

Explanation

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

PowerShell, 56 bytes

param($a)$b=,0*($a|sort)[-1];$a|%{if(++$b[$_-1]%$_){$_}}

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
2
2

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

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------             
True     True     Object[]                                 System.Array
\$\endgroup\$
1
\$\begingroup\$

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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]} \$\endgroup\$
    – Alex A.
    Jan 25, 2016 at 5:52
1
\$\begingroup\$

MATL, 20 bytes

tu"t@=f@@h0h)0w(]tg)

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

Try it online!

Explanation

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

R, 63 bytes

f=function(z){n=seq(z);for(i in n)z[which(z==i)[n*i]]=0;z[z>0]}
\$\endgroup\$
1
\$\begingroup\$

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);
}
\$\endgroup\$
5
  • \$\begingroup\$ 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; \$\endgroup\$ Jan 25, 2016 at 14:41
  • \$\begingroup\$ @peter-taylor, you're right, thanks. Also, had to add some code to fixed a bug. \$\endgroup\$
    – Dmitry S
    Jan 25, 2016 at 15:35
  • \$\begingroup\$ If you've imported System.Linq then !l.Any() is shorter than l.Count<1, which is shorter than l.Count==0. \$\endgroup\$ Jan 25, 2016 at 16:11
  • \$\begingroup\$ @peter-taylor thanks, I also replaced w != 0 && w !=1 with w > 1. \$\endgroup\$
    – Dmitry S
    Jan 25, 2016 at 17:04
  • \$\begingroup\$ arrays should be good too and they would be a bit shorter int[] R(int[] l, int n = 1) \$\endgroup\$
    – raggy
    Jun 27, 2016 at 15:23
1
\$\begingroup\$

Haskell, 78 bytes

f l=[l!!n|n<-[0..length l-1],0/=mod(1+(length.filter(==l!!n)$take n l))(l!!n)]

Try it Online!

\$\endgroup\$
1
\$\begingroup\$

Haskell, 58 56 bytes

2 bytes saved by xnor

q w=[x|(n,x)<-zip[1..]w,0<mod(sum[1|u<-take n w,u==x])x]

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ IF you do zip[1..], you no longer have to add 1 to n: 56 bytes \$\endgroup\$
    – xnor
    Jan 10, 2022 at 7:03
0
\$\begingroup\$

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));}

Ungolfed

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));
}
\$\endgroup\$
1
  • 4
    \$\begingroup\$ I believe you would have to count the using statements, in which case this would be 241 bytes long. \$\endgroup\$ Jan 25, 2016 at 12:02
0
\$\begingroup\$

Mathematica, 63 bytes

Fold[Delete[#,Position[#,#2][[#2;;;;#2]]~Check~{}]&,#,Union@#]&

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

\$\endgroup\$
0
\$\begingroup\$

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]}};a.select{|i|i!=''}}
\$\endgroup\$
0
\$\begingroup\$

TI-BASIC, 47 bytes

Input X
For(I,1,dim(∟X
∟X(I
If fPart(sum(∟X=Ans),1,I)/Ans
Ans→L₁(1+dim(L₁
End
L₁

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.

\$\endgroup\$
0
\$\begingroup\$

APL, 16 chars

{⍵/⍨×⍵|+/¨⍵=,\⍵}

In English:

  • ,\⍵: vector of the vector prefixes up to the nth-element of the argument
  • +/¨⍵=: per prefix vector, count how many are equal to the n-th element itself
  • ×⍵|: signs of the mod's (that is: 0 if the remainder of the division is 0, 1 otherwise)
  • ⍵/⍨: of the argument keep only the element where the mod is 0
\$\endgroup\$
0
0
\$\begingroup\$

Racket 179 bytes

(λ(l)(define m(apply max l))(let g((n 1)(c 0))(set! l(for/list((i l))(if(= i n)(begin 
(set! c(+ 1 c))(if(= 0(modulo c n))0 i))i)))(if(< n m)(g(+ 1 n)0)(filter(λ(x)(> x 0))l))))

Ungolfed:

(define f
  (λ(l)
    (define m (apply max l))
    (let loop ((n 1) (c 0))
      (set! l (for/list ((i l))
                (if (= i n)
                    (begin
                      (set! c (+ 1 c))
                      (if (= 0 (modulo c n))
                          0 i ))                  ; replace by 0
                    i )))
      (if (< n m)
          (loop (+ 1 n) 0)
          (filter (λ(x)(> x 0)) l)                ; remove all 0s
          ))))

Testing:

(f '[1]) 
(f '[2]) 
(f '[1 1 1]) 
(f '[2 2 2]) 
(f '[1 1 2 2 2 3 3 3 3])
(f '[1 2 3 1 2 3 1 2 3 1 2 3]) 
(f '[3 2 6 1 1 6 2 3 2 6 6 6 6 1 6 6 3 3 7 2])

Output:

'()
'(2)
'()
'(2 2)
'(2 2 3 3 3)
'(2 3 3 2 3)
'(3 2 6 6 3 2 6 6 6 6 6 3 7)
\$\endgroup\$
0
\$\begingroup\$

Factor, 61 bytes

[ H{ } clone '[ _ 2dup inc-at over of swap mod 0 > ] filter ]

Try it online!

The idea is to have a hash table that keeps a running count of each element. Then we reject each element from the input that is divisible by its current count.

\$\endgroup\$
0
\$\begingroup\$

05AB1E, 8 bytes

ʒˆ¯y¢yÖ_

Inspired by @RainerP.'s awk answer.

Try it online or verify all test cases.

Explanation:

ʒ         # Filter the (implicit) input-list by:
 ˆ        #  Pop and add the current integer to the global array
    ¢     #  Count how many times
   y      #  the current integer
  ¯       #  occurs in the global array
       ≠  #  Check that this count is NOT
      Ö   #  evenly divisible
     y    #  by the current integer
          # (after which the filtered list is output implicitly as result)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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