Lossy Sorting (Implement Dropsort)

62

4

Dropsort, designed by David Morgan-Mar, is an example of a linear-time "sorting algorithm" that produces a list that is, in fact, sorted, but contains only some of the original elements. Any element that is not at least as large as the maximum of the elements preceding it is simply removed from the list and discarded.

In this task, you will be given a list of integers as input (STDIN or function argument, you are required to support at least the range of 8-bit signed integers.) Your task is to dropsort them and then output the remaining elements in order.

You may assume that the list is non-empty.

This is code golf, so the shortest program wins.

Test Cases

Input             Output
1 2 5 4 3 7       1 2 5 7
10 -1 12          10 12
-7 -8 -5 0 -1 1   -7 -5 0 1
9 8 7 6 5         9
10 13 17 21       10 13 17 21
10 10 10 9 10     10 10 10 10

Leaderboard

var QUESTION_ID=61808,OVERRIDE_USER=39022;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>

SuperJedi224

Posted 2015-10-26T13:16:14.860

Reputation: 11 342

1Is the check highest < current? Or highest <= current? – Morgan Thrapp – 2015-10-26T13:20:47.367

7Keep the current element if highest (so far)<=current. – SuperJedi224 – 2015-10-26T13:21:40.100

Can we assume that there will be at least one element in the list? – lirtosiast – 2015-10-26T20:44:21.263

@ThomasKwa: Yes. – SuperJedi224 – 2015-10-26T20:49:46.667

19Dropsorts improved efficiency could save a company a lot of money if utilized in the payroll system. – PyRulez – 2015-10-26T21:06:17.353

Just a reminder, this is [tag:code-golf], you havent picked a winner in more than a year, but there are clearly some codes to pick from. – devRicher – 2016-12-26T22:35:21.830

An O(1) sorting algorithm: always returns the empty list :) – Solomon Ucko – 2018-03-22T20:41:10.670

Answers

43

APL, 9 bytes

⊢(/⍨)⊢=⌈\

This is a monadic function train with diagram:

┌─┼───┐  
⊢ ⍨ ┌─┼─┐
┌─┘ ⊢ = \
/     ┌─┘
      ⌈  

The non-train version is

{⍵/⍨⍵=⌈\⍵}

This basically checks if each element is equal to the running maximum.

Note that Martin Büttner's J solution is the same length as this and was posted first.

lirtosiast

Posted 2015-10-26T13:16:14.860

Reputation: 20 331

42Bonus points because it looks cute. – Sammitch – 2015-10-26T18:02:33.370

23Code looks like a disgruntled dude shooting at a cat flap – slebetman – 2015-10-27T05:42:32.147

1If it looks better, the left tack also works for the first character: ⊣(/⍨)⊢=⌈\. – lirtosiast – 2015-10-28T03:57:57.500

2

I don't know much about byte counting and what encoding is intended to be used, but according to https://mothereff.in/byte-counter and http://meta.codegolf.stackexchange.com/questions/4944/byte-counter-snippet this is 17 bytes, and http://bytesizematters.com/ it's 13.

– DLeh – 2015-10-28T15:43:12.707

5@DLeh That's in UTF-8. APL has its own legacy encoding that is 1 byte per APL character, from before unicode existed. – isaacg – 2015-10-29T16:52:25.987

3@DLeh bytesizematters uses a made up algorithm to count the bytes, which does not (and cannot) correspond to an actual encoding. – Dennis – 2016-02-19T18:00:34.430

Huh, that's how you force / to be a function and not an operator! – Zacharý – 2017-08-30T21:31:16.813

21

J, 10 9 bytes

#~(=>./\)

Working version of my CJam idea (in fewer bytes). E.g.:

   f =: #~(=>./\)
   f 10 10 10 9 10
10 10 10 10
   f 1 2 5 4 3 7
1 2 5 7

Explanation

First, we get the maximum of each prefix, with:

    >./\

(Here, >. is the maximum operator, / folds that operator onto a list, and \ gets all the prefixes of the input.)

Then we compare the initial list with those maxima for equality:

  (=>./\)

And finally, we select all elements where this list of boolean results gave a 1:

#~(=>./\)

Martin Ender

Posted 2015-10-26T13:16:14.860

Reputation: 184 808

16

Haskell, 28

foldr(\x l->x:filter(x<)l)[] 

An anonymous function. Call it like

foldr(\x l->x:filter(x<)l)[] [-7, -8, -5, 0, -1, 1] 
[-7,-5,0,1]

Equivalent to the recursion

f[]=[]
f(x:l)=x:filter(x<)(f l)

Translated iteratively, we iterate over the elements, and for each one we see, we remove the ones smaller than it from the remainder of the list that we're iterating over. Thanks to Antisthenes for a byte saved with (x<).

xnor

Posted 2015-10-26T13:16:14.860

Reputation: 115 687

Why not curry the lambda? Should save a few characters... – MathematicalOrchid – 2015-10-29T12:47:05.640

@MathematicalOrchid If you mean foldr(\x->(x:).filter(>=x))[], that turns out to be the same length. – xnor – 2015-10-29T22:55:54.563

Ah. I just saw the filter at the end and thought "hey, you can curry that!" Didn't occur to me that the x: forces you to add the dot operator. Oh well... – MathematicalOrchid – 2015-10-30T08:10:17.707

1it's O(n^2) though. lots of unneeded comparisons. ;-( – proud haskeller – 2016-03-27T22:27:03.547

Why not change (>=x) to (x<)? It will save 1 byte – Antisthenes – 2017-06-16T20:02:03.613

@Antisthenes Thanks, that's a forehead slapper. – xnor – 2017-06-16T21:59:04.553

10

Python 2, 49

f=lambda a:a and f(a[:-1])+a[-1:]*(a[-1]==max(a))

feersum

Posted 2015-10-26T13:16:14.860

Reputation: 29 566

1This is amazing. – Morgan Thrapp – 2015-10-26T17:46:20.797

1@ThomasKwa The problem is how do you stop the recursive calls. You need the empty case even if the input excludes that case. – Bakuriu – 2015-10-27T12:39:57.893

problem with that is that it is not linear because of max(a) – njzk2 – 2015-10-28T20:31:54.927

1@njzk2 The challenge does not require the implementations to run in linear time. – feersum – 2015-10-28T20:50:24.587

@feersum no, but it would be nice, since the original algorithm is in linear time – njzk2 – 2015-10-28T20:53:52.147

3@njzk2 Nice codes finish last! – feersum – 2015-10-28T21:06:07.403

10

JavaScript (ES6), 29

Abusing of the standard type conversion in javascript, array to number:

  • array of just 1 number => that number
  • any other array => NaN

d=l=>l.filter(v=>l>v?0:[l=v])

// TEST
console.log=x=>O.innerHTML+=x+'\n'

;[
  [[1,2,5,4,3,7], [1,2,5,7]]
, [[10,-1,12], [10,12]]
, [[-7,-8,-5,0,-1,1], [-7,-5,0,1]]
, [[9,8,7,6,5], [9]]
, [[10,13,17,21], [10,13,17,21]]
, [[10,10,10,9,10], [10,10,10,10]]
].forEach(t=>( i=t[0],r=d(i),x=t[1],              
  console.log('Test '+i+' -> '+r+(r+''==x+''?' OK':' Fail (expected '+x+')')))
)
<pre id=O></pre>

edc65

Posted 2015-10-26T13:16:14.860

Reputation: 31 086

Wow. I thought 38 bytes was approximately the best possible; apparently I was very wrong. +1 – ETHproductions – 2015-10-26T15:45:56.043

Table driven tests. Nice! – slebetman – 2015-10-27T05:43:46.233

9

Brachylog, 5 bytes

⊇ᶠ↔ᵒt

Try it online!

Jelly, 5 bytes

ŒPUÞṪ

Try it online!

Explanation

⊇ᶠ↔ᵒt    ŒPUÞṪ
⊇ᶠ       ŒP       On all subsequences of {the input}
   ᵒ        Þ     sort by
  ↔        U      their reverse
    t        Ṫ    then take the last element (i.e. the maximum as given by the sort)

This is a rare situation: I get to use an algorithm which (as far as I could tell with a quick skim) nobody is using so far, and it somehow ends up the same length in two very different golfing languages with very different syntax and builtin sets, with a 1-to-1 correspondence between the programs (the commands are even in the same order!). So it seemed to make more sense to combine them – in a way, these are the same program, and I wrote it in both languages to see which was shorter – than to submit them separately.

The basic idea here is that the dropsort of a list is its subsequence with the lexicographically maximum reverse. Oddly, neither Brachylog nor Jelly has a builtin to find the maximum by a particular function (Jelly has a builtin to return all the maxima by a particular function, but that'd return a singleton list containing the result rather than the result itself, and also isn't even shorter than doing it this way). So instead, we generate all possible subsequences, sort by reverse, take the last.

The reason why "lexicographically maximum reverse" works is that the chosen output must end (thus its reverse must start) with the highest number in the input list (it's easy to see that the dropsort output will always end with that), and thus can't contain anything after that (because taking subsequences preserves order). Repeat inductively and we end up with the definition of dropsort.

ais523

Posted 2015-10-26T13:16:14.860

Reputation: 11

9

Octave, 27 19 bytes

@(a)a(cummax(a)==a)

alephalpha

Posted 2015-10-26T13:16:14.860

Reputation: 23 988

7

Pyth, 12 bytes

eMfqeTeST._Q

Verify all test cases at once.

How it works

         ._Q  Compute all prefixes of the input.
  f           Filter; for each T in the prefixes:
    eT          Retrieve the last element of T.
      eST       Sort T and retrieve its last element.
   q            Check for equality.
              Keep T if q returned True.
eM            Select the last element of each kept T.

Dennis

Posted 2015-10-26T13:16:14.860

Reputation: 196 637

6

Mathematica, 26 Bytes

DeleteDuplicates[#,#>#2&]&

celtschk

Posted 2015-10-26T13:16:14.860

Reputation: 4 650

2I don't know Mathematica, but something that calls DeleteDuplicates doesn't look like it would return {10, 10, 10, 10} for input {10, 10, 10, 9, 10} – Dennis – 2015-10-27T15:49:41.963

2@Dennis: It does, I tested it. The trick is that I pass "is greater than" as "equivalence" test. Yes, it's a misuse of that function, but it works, and code golf is not exactly about best programming practices anyway. – celtschk – 2015-10-27T19:02:37.917

2

OK, in spite of what the name suggests, DeleteDuplicates with two arguments seems to be a simple filter.

– Dennis – 2015-10-27T19:19:31.690

5

R, 29 26 bytes

function(x)x[x>=cummax(x)]

This creates a function object that accepts a vector x and returns x after removing all elements not at least as large as the cumulative maximum of x.

Saved 3 bytes thanks to flodel!

Alex A.

Posted 2015-10-26T13:16:14.860

Reputation: 23 761

The function form would be shorter. – flodel – 2015-10-26T23:10:34.590

@flodel You're absolutely right. Thanks! – Alex A. – 2015-10-26T23:19:13.303

4

K, 11 bytes

{x@&~x<|\x}

In action:

  f: {x@&~x<|\x}
  f'(1 2 5 4 3 7
     10 -1 12
     -7 -8 -5 0 -1 1
     9 8 7 6 5
     10 13 17 21
     10 10 10 9 10)

(1 2 5 7
 10 12
 -7 -5 0 1
 ,9
 10 13 17 21
 10 10 10 10)

JohnE

Posted 2015-10-26T13:16:14.860

Reputation: 4 632

{x@&~<':x} is a byte shorter. – kirbyfan64sos – 2015-10-26T16:04:09.870

@kirbyfan64sos: Using eachprior does not produce the correct result. Consider the input case 3 4 2 2 5. – JohnE – 2015-10-26T17:42:57.473

Ah, I see. A fix would be {x@&~<':x}/, but that's the same length. – kirbyfan64sos – 2015-10-26T19:59:28.110

3

PowerShell, 32 bytes

$args|?{$e-eq$p-or$_-ge$p;$p=$_}

Try it online!

Less golfed:

$args|?{
    $empty -eq $previous -or $_ -ge $previous
    $previous = $_
}

mazzy

Posted 2015-10-26T13:16:14.860

Reputation: 4 832

3

Python 3, 67

Pretty brute force. Changed it to a function, because I missed that it was a valid answer.

def f(i):
 s=[i[0]]
 for n in i[1:]:
  if s[-1]<=n:s+=[n]
 return s

Ungolfed version:

input_numbers = input().split()
sorted_numbers = []
previous_number = int(input_numbers[0])
for number in map(int, input_numbers):
    if previous_number <= number:
        sorted_numbers.append(number)
        previous_number = number
print(sorted_numbers)

Morgan Thrapp

Posted 2015-10-26T13:16:14.860

Reputation: 3 574

62 bytes – movatica – 2019-08-14T20:49:45.877

3

Java, 82 bytes

void f(int[]a){int m=a[0];for(int n:a){System.out.print(m>n?"":n+" ");m=n>m?n:m;}}

Here's a simple output loop. It just keeps the max in m and compares each element.

Geobits

Posted 2015-10-26T13:16:14.860

Reputation: 19 061

1You can shorten it by using a lambda: a->{int m=a[0]... – Daniel M. – 2015-10-27T17:14:44.253

Yea, you usually can. I don't lambda-ize java golfs, though. – Geobits – 2015-10-27T17:57:14.157

3

Perl, 33 bytes

32 bytes code + -p

$p=$_;s/\S+ ?/$&>=$p&&($p=$&)/ge

If additional spaces are acceptable in the output, can be 31 bytes by removing and ?. Accepts a string (or number of newline separated) strings via STDIN:

perl -pe'$p=$_;s/\S+ ?/$&>=$p&&($p=$&)/ge' <<< '-7 -8 -5 0 -1 1'
-7 -5 0 1
perl -pe'$p=$_;s/\S+ ?/$&>=$p&&($p=$&)/ge' <<< '10 10 10 9 10'
10 10 10 10

Dom Hastings

Posted 2015-10-26T13:16:14.860

Reputation: 16 415

3

Haskell, 38 37 bytes

Saved 1 byte thanks to JArkinstall.

f(x:y:s)|x>y=f$x:s|1>0=x:f(y:s)
f s=s

alephalpha

Posted 2015-10-26T13:16:14.860

Reputation: 23 988

1You can replace one of your sets of parentheses with a $ to cut down by one whole byte!

f(x:y:s)|x>y=f$x:s|1>0=x:f(y:s);f s=s

(Semi-colon used because comments don't allow newlines) – Jake – 2015-10-27T01:14:18.990

3

C# - 6864 or 132127 Characters

int[]f(int[]b){return b.Where((v,i)=>i<1||b[i-1]<=v).ToArray();}

Where in this case is iterating through the list, and for each element v at index i in the list, evaluates the boolean expression. If the expression evaluates to true, then the item is added to the result. The only real trick to the boolean expression is that C# short circuits or evaluation as soon as a condition evaluates to true. This prevents the IndexOutOfRangeException exception, and keeps the first element in the list.

If the input and output have to be strings (I couldn't tell for sure, so I'll leave it to the OP and the rest of you to decide.)

string t(string b){var c=b.Split(' ').Select(d=>int.Parse(d)).ToList();return String.Join(" ",c.Where((v,i)=>i<1||c[i-1]<=v));}

Decompressing that a bit gives:

string t(string b) 
{
    var c=b.Split(' ').Select(d=>int.Parse(d)).ToList();
    return String.Join(" ",c.Where((v, i)=>i<1||c[i-1]<=v));
}

In this case the second line of the function is using the exact same logic as above. The Select grabs the elements of the list and converts them to int. The call to ToList1 forces the select to be evaluated, and turns the var into a List<int> at compile time, so that the Where is operating on a collection of integers.

Try it on C# Pad

Thanks to VisualMelon for helping trim 4 bytes and 5 bytes respectively. :)

1 tutu list?

theB

Posted 2015-10-26T13:16:14.860

Reputation: 171

If I miscounted, or if my explanation needs some explaining, please let me know. :) – theB – 2015-10-27T02:58:54.450

1Nice work - you can save a few bytes by using some common tricks - you don't need the spaces after the array declarations int[]f(int[]b) is fine, and you can use i<1 rather than i==0 to shorten that check a bit. For the string version, you can also drop the brackets around a single-argument in a lambda (e.g. (d)=>int.Parse(d) can be d=>int.Parse(d). I also only count 67 bytes, not 68, in your orignal ;) – VisualMelon – 2015-10-27T09:13:22.227

@VisualMelon - Thanks! I figured that any miscounting would end up making the total bigger. ;) – theB – 2015-10-27T09:28:13.953

3

CJam, 15 bytes

q~{_2$<{;}&}*]p

Try it online in the CJam interpreter.

How it works

q~               Read an evaluate all input.
  {        }*    Reduce; push the first element; or each remaining element:
   _2$           Copy the topmost and second topmost element from the stack.
      <          Check if the topmost is smaller than the second topmost.
       {;}&      If it is, remove it from the stack.
             ]   Wrap the stack i an array.
              p  Print.

Dennis

Posted 2015-10-26T13:16:14.860

Reputation: 196 637

2

Python 2, 41 bytes

for n in input():
 if-n<=id:print n;id=-n

Try it online!

A nice to trick is to use id as the initial running maximum, since it's already initialized. Python 2 allows this weird comparison, but unfortunately functions are smaller than numbers, we instead store the running max negated.


Python 3.8 (pre-release), 41 bytes

lambda l,m=-128:[m:=n for n in l if n>=m]

Try it online!

A nice solution using the Python 3.8+ walrus operator. We use -128 as the initial minimum since the challenge specifies the code needs to work for signed 8-bit integers.

xnor

Posted 2015-10-26T13:16:14.860

Reputation: 115 687

If we were allowed to output lists of singleton lists, I could shave this down to 38 bytes: Try it online!

– isaacg – 2019-12-08T20:54:32.873

@isaacg The defaults on singletons mention it the output being a single value, so I think this isn't allowed by default. This is a nice idea with the walrus operator that I haven't seen before to avoid needing to initialize the mutable value

– xnor – 2019-12-08T21:26:29.403

Huh, I completely forgot that default. I've downvoted it, so I must have read it at some point. I'll go and post it as a separate answer, but I'm not going to claim the indefinite bounty because it's making use of looser I/O and therefore doesn't feel fair to me. – isaacg – 2019-12-08T21:29:16.540

2

Python 3.8 (pre-release), 38 bytes

lambda l:[l:=[n]for n in l if n>=l[0]]

Try it online!

This outputs in the format

[[-2], [0], [1], [2], [5], [5], [7]]

e.g. a list of lists containing one element each. According to this default for output, it is allowed to use a singleton list in place of a single value, so arguably this should be allowed as well.

isaacg

Posted 2015-10-26T13:16:14.860

Reputation: 39 268

2

><> with -v flag, 36 31 + 2 = 33 bytes

:&\o " "&n:~& <
~ >l?!;:&:&(?!^

Input the list on the stack with -v so that the first element of the list is at the top of the stack. It will print the dropsorted list with a trailing space.

Test run :

$ for input in "1 2 5 4 3 7" "10 -1 12" "-7 -8 -5 0 -1 1" "9 8 7 6 5" "10 13 17 21" "10 10 10 9 10"; do echo $input '-> ' $(python fish.py dropsort.fsh -v $(echo $input | tac -s ' ')); done

1 2 5 4 3 7 ->  1 2 5 7

10 -1 12 ->  10 12

-7 -8 -5 0 -1 1 ->  -7 -5 0 1

9 8 7 6 5 ->  9

10 13 17 21 ->  10 13 17 21

10 10 10 9 10 ->  10 10 10 10

Edit : saved 5 bytes thanks to Fongoid

Aaron

Posted 2015-10-26T13:16:14.860

Reputation: 3 689

You can save 5 bytes by refactoring line 1 as :&\o" "&n:~& < and line 2 as ~ >l?!;:&:&(?!^ – Fongoid – 2015-10-27T21:42:38.477

@Fongoid thanks, updated ! – Aaron – 2015-10-28T10:37:44.327

2

Burlesque, 13 bytes

11 byte solution that passes test-cases:

-.2CO:so)[~

Try online here.

Explanation:

-. -- prepend head of list to list
2CO -- n-grams (sliding window) of size 2
:so -- filter sorted lists
)[~ -- map last

However, this version only works by using the fact, that no two smaller numbers are in between two numbers. Otherwise use the version below (which is 13B):

Older versions:

J-]{cm-1.>}LO

Try online here. Explanation:

J -- duplicate
-] -- head
{
  cm -- compare (returning -1,0 or 1)
  -1.> -- greater than -1
}LO -- Loop

If you'd drop equal numbers as well you could go with just .> instead of using cm. Also, if lists only contain positive numbers you can use either 0 or -1 instead of J-].

mroman

Posted 2015-10-26T13:16:14.860

Reputation: 1 382

Yeah, but then I can't hyperlink it :). – mroman – 2015-10-26T16:44:26.183

fixed. I'll just add a "try online here" line. – mroman – 2015-10-26T16:46:08.390

2

C: 73 bytes

int i,j;i=j=INT_MIN;while(scanf("%d",&j)!=EOF)if(j>=i)printf("%d",j),i=j;

or

C: 49 bytes

(If customs header made for codegolf competitions is allowed)

I z,y;z=y=INT_MIN;w(s(D,&y)!=E)i(y>z)p(D,y),z=y;}

Still can't beat CJam, but at least this allow to beat few other languages.

CoffeDeveloper

Posted 2015-10-26T13:16:14.860

Reputation: 123

4Sorry, the custom header isn't allowed; it would count as a different language. – lirtosiast – 2015-10-26T17:07:13.260

4The primary problem with your custom headers is that you published them after this competition started. – Dennis – 2015-10-26T19:31:04.200

Sure I understand, but then I cannot use it neither in future competitions? – CoffeDeveloper – 2015-10-27T09:24:52.880

@DarioOO You can, but you'd be required to include the import statement towards your byte count. – SuperJedi224 – 2016-03-15T14:14:07.227

Or just call it a new language. – CalculatorFeline – 2016-03-22T04:07:04.023

2

Ruby, 32 characters

->a{m,=a;a.select{|n|m<=n&&m=n}}

Thanks to:

  • Value Ink for reminding that in Ruby all numbers are truthy, so && number assignment does not change the preceding boolean expression.

Try it online!

Ruby, 41 37 characters

->a{m=a[0];a.map{|n|m>n ?p: m=n}-[p]}

(My old attempt.)

Sample run:

2.1.5 :001 > [
2.1.5 :002 >     [1, 2, 5, 4, 3, 7],
2.1.5 :003 >     [10, -1, 12],
2.1.5 :004 >     [-7, -8, -5, 0, -1, 1],
2.1.5 :005 >     [9, 8, 7, 6, 5],
2.1.5 :006 >     [10, 13, 17, 21],
2.1.5 :007 >     [10, 10, 10, 9, 10],
2.1.5 :008 > ].each{ |test| p ->a{m=a[0];a.map{|n|m>n ?p: m=n}-[p]}[test] }
[1, 2, 5, 7]
[10, 12]
[-7, -5, 0, 1]
[9]
[10, 13, 17, 21]
[10, 10, 10, 10]

manatwork

Posted 2015-10-26T13:16:14.860

Reputation: 17 865

1-[p] is shorter than .compact – Not that Charles – 2015-10-27T17:49:17.333

Oops. Of course. Thank you. (Note to myself: is not enough to just upvote the [link http://codegolf.stackexchange.com/questions/363/tips-for-golfing-in-ruby]Tips for golfing in Ruby[/link], I should also memorize them.) – manatwork – 2015-10-27T18:02:06.713

1->a{m,=a;a.select{|n|m<=n&&m=n}} 32 bytes – Value Ink – 2019-12-09T00:32:12.277

2

Minkolang 0.9, 18 bytes

ndN(nd1R`2&dN$I$).

Try it here.

Explanation

ndN                Take first integer from input
(         $I$).    Repeat until the input is empty and then stop.
 nd1R`             Is the next integer less than the previous one?
      2&dN         If not (i.e., it's greater than or equal to), print it.

El'endia Starman

Posted 2015-10-26T13:16:14.860

Reputation: 14 504

2

Python, 102 99 94 + 5 6 non-file-final newlines = 107 105 100 bytes

(I used tabs for indentation)

def d(l):
    j=b=0;m=l[j];r=[]
    for i in l:
        (m,b)=[(m,0),(i,1)][i>=m]
        if b>0:r+=[i]
        j+=1
    l[:]=r

Not the best out there, but this is my first shot at code golf. Couldn't figure out a way to sort the list inline without running into removal-related bugs, so I moved the ordered elements to a temporary list.

EDIT: list.append() is shorter than doing it the ugly way

r+=[i] was shorter than list.append(); thanks njzk2!

James Murphy

Posted 2015-10-26T13:16:14.860

Reputation: 267

r+=[i] is shorted than r.append – njzk2 – 2015-10-28T20:44:11.343

I tried doing that before, but got an error because I didn't realize you have to do it with brackets. Thanks! – James Murphy – 2015-10-28T20:57:48.497

2

Scala: 232 126 120 bytes

def f(x:Int*)=(Seq[Int]()/:x)((r,y)=>r.headOption.filter(y>=).map(_=>y+:r).getOrElse(if(r.isEmpty) y+:r else r)).reverse

Martin Seeler

Posted 2015-10-26T13:16:14.860

Reputation: 151

2Adding an "extension method" for List[Int] does not meet requirements, you should get the input via STDIN or as an argument. Plus, it bloats your answer... Why not simply have def dropSort(s:Seq[Int]):Seq[Int]? – Jacob – 2015-10-27T15:47:50.057

I thought it would be fancy, but you're right, way too much bytes... – Martin Seeler – 2015-10-27T19:07:37.277

1Very nice improvement using fold! You can still shave off some spaces and also you can use y>= rather than _<=y which yields a compile warning without a proper import, but also demonstrates how awesome Scala is (oh, and shaves off another character). – Jacob – 2015-10-28T22:33:10.420

Thx for the tipp! – Martin Seeler – 2015-10-29T07:07:37.817

2

NARS2000 APL, 13 bytes

NARS2000 is a free APL interpreter for Windows; it includes multiset features accessed with the operator.

(+⍦∩⌈\)

This is a monadic fork that takes the multiset intersection (⍦∩) of the input (+)* and the list of running maximums (⌈\).

Since is not a standard APL character in the one-byte APL legacy encodings, we must use UTF-8, making the ⍦∩⌈ characters three bytes each. I chose + instead of to save two bytes.

NARS2000 supports forks, which can be built into trains without parentheses, but unlike Dyalog it doesn't allow assignment to a function without wrapping the function in parentheses.

*+ is technically complex conjugate, but the input is real.

lirtosiast

Posted 2015-10-26T13:16:14.860

Reputation: 20 331

So, why doesn't http://codegolf.stackexchange.com/questions/61808/lossy-sorting-implement-dropsort#comment149730_61831 apply here too?

– cat – 2016-03-21T20:02:05.323

NARS2000 can't use the legacy APL encodings--and even before the rule that encodings must be the ones actually used by interpreters, this couldn't be 7 bytes because psi isn't part of any legacy APL encoding. – lirtosiast – 2016-03-21T21:48:39.470

2

Scala, 54 bytes

def f(x:Int*)=(x:\Seq[Int]())((y,r)=>y+:r.filter(y<=))

Ungolfed:

def dropSort(xs: Seq[Int]): Seq[Int] =
  xs.foldRight(Seq.empty[Int]) { (x, result) =>
    x +: result.filter(r => r >= x)
  }

knutwalker

Posted 2015-10-26T13:16:14.860

Reputation: 121

2

Tiny Lisp, 107 bytes

(This language was only published after this question, so this answer runs out of competition. Not that it had any chance to win. The language later evolved further to have more buildins than the ones I used here, but I'm staying with the version I originally implemented in 2015. This answer still works with the newer official interpreter, though it gives some warnings because I define a parameter a which shadows the new buildin a (for adding).Thanks to DLosc for the TIO link.)

(d r(q((m a)(i a(i(l(h a)m)(r m(t a))(c(h a)(r(h a)(t a))))()))))(d ds(q((b)(i b(c(h b)(r(h b)(t b)))()))))

This defines a function ds (and its recursive helper function r) which sorts its argument, which must be a list of integers.

r is not a tail-recursive function, so for very long lists this might run into a stack overflow.

Ungolfed:

(d r
   (q((m a)
      (i a
         (i (l (h a) m)
            (r m (t a))
            (c (h a)
               (r (h a) (t a))
             )
          )
         ()
       )
   ) )
 )
(d ds
  (q(
      (b)
      (i b
        (c (h b)
           (r (h b) (t b))
         )
        ()
       )
   ) )
 )

Here are some examples how to use this (with the test cases from the question):

(d list (q (args args)))
(d -
   (q( (n)
       (s 0 n)
    ) )
 ) 

(ds (list 1 2 5 4 3 7))
(ds (list 10 (- 1) 12))
(ds (list (- 7) (- 8) (- 5) 0 (- 1) 1))
(ds (list 9 8 7 6 5))
(ds (list 10 13 17 21))
(ds (list 10 10 10 9 10))

(Yeah, -7 is not an integer literal, so we have to define a function to represent them.) Output:

list
-
(1 2 5 7)
(10 12)
(-7 -5 0 1)
(9)
(10 13 17 21)
(10 10 10 10)

Paŭlo Ebermann

Posted 2015-10-26T13:16:14.860

Reputation: 1 010

"-7 is not an integer literal" I'm still laughing, +1 – cat – 2016-03-21T19:58:31.607

Did you really use up every single character for builtins? (Except r, I guess..) – CalculatorFeline – 2016-03-22T14:35:53.263

@CatsAreFluffy sorry, I have problems understanding your comment. Tiny Lisp has 7 build-in functions and three build-in macros, all of them having single character-names (I guess to make the language easier to use for golfing), with parentheses and space being special syntax. Note that Tiny Lisp is not my invention. – Paŭlo Ebermann – 2016-04-02T15:02:37.253

Ah, I think I get it now ... you are proposing to use a single-character name instead of ds? I guess this could be done, would save another byte. I guess I selected ds as a abbreviation for drop sort. – Paŭlo Ebermann – 2016-04-02T15:03:57.650

Hey, I just noticed this. Nice job! According to meta consensus, unnamed lambda functions are a valid form of submission, so you can save 6 bytes by getting rid of (d ds and the matching ) at the end. Other golfs are possible if you want to use my current interpreter, but if you want to stick to the spec in the original question, that's fine too. :)

– DLosc – 2018-02-02T23:37:52.797

@DLosc thanks. I guess I'll let it stay the current way, as this way the examples are easier to read. (And I stay in the way I've implemented in my answer. back then in 2015). – Paŭlo Ebermann – 2018-02-02T23:48:09.693

Oh, and: you get a bunch of warnings now, but it does indeed work with the current interpreter.

– DLosc – 2018-02-03T01:16:15.970

2

Jelly, 5 bytes

=»\Tị

Note that the challenge predates the creation of Jelly.

Try it online!

How it works

=»\Tị  Main link. Argument: A (list)

 »\    Yield the cumulative maxima of A.
=      Perform element-by-element comparison.
       Yields 1 iff A[n] = max(A[1], ..., A[n]).
   T   Get all indices of truthy elements.
    ị  Retrieve the items of A at those indices.

Dennis

Posted 2015-10-26T13:16:14.860

Reputation: 196 637

1

MATL, 6 bytes

ttY>=)

Try it online!

Mr. Xcoder

Posted 2015-10-26T13:16:14.860

Reputation: 39 774

1

SWI-Prolog, 55 bytes

A/B:-append(C,[D,E|F],A),E<D,append(C,[D|F],G),G/B;A=B.

Usage: Call "List/X" where List is a bracket-enclosed, comma-separated list e.g. [1,4,5,1,11,6,7].

ashtraypettingzoo

Posted 2015-10-26T13:16:14.860

Reputation: 51

1

Japt, 8 bytes

f@¯Y e§X

Try it here

Shaggy

Posted 2015-10-26T13:16:14.860

Reputation: 24 623

This fails on some inputs where the original list goes down and then back up, though I don't see any test cases where that would be a problem. Here's an example.

– Kamil Drakari – 2018-10-29T20:47:26.050

Thanks, @KamilDrakari; I misread the spec. (Or, rather, I didn't read the spec at all, just based my solution on the test cases! :) – Shaggy – 2018-10-30T11:55:56.600

1

05AB1E, 8 6 bytes

vyMyQ—

Try it online!

v          # for each item of the input list
 y         # push it on the stack
  M        # push the maximum of the stack
   yQ      # is it equal to the maximum?
     —     # if yes, print it

Grimmy

Posted 2015-10-26T13:16:14.860

Reputation: 12 521

1

Python 3, 58 56 bytes

f=lambda x:[e for i,e in enumerate(x)if max(x[:i+1])==e]

Not sure if the input would be a string or a list, my code only would work in the second case.

Jose Alejandro Galisteo Callej

Posted 2015-10-26T13:16:14.860

Reputation: 11

Welcome to the site! I count 57, and you can get rid of the space before if. Try it online!

– Khuldraeseth na'Barya – 2019-08-09T17:44:39.890

Thank you! I've just made the corrections – Jose Alejandro Galisteo Callej – 2019-08-14T08:45:43.653

1

VBA, 173 133 bytes

Sub s(c)
d=UBound(c)
ReDim r(d)
r(i)=c(i)
For i=1To d
If r(j)<=c(i)Then j=j+1:r(j)=c(i)
Next
ReDim Preserve r(j)
c=r
End Sub

(after edits) The above code is shorter and expects the parameter c to be passed as a variant array of numbers. My original Test_Cases sub below uses the Split() function which returns an array of strings. You won't be able to use Test_Cases to test the above code. If you want to see the algorithm working you need to test with the function below.

148 bytes (as a function expecting a string array)

Function s(c)
d=UBound(c)
ReDim r(d)
r(i)=c(i)
For i=1To d
If Val(r(j))<=c(i)Then j=j+1:r(j)=c(i)
Next
ReDim Preserve r(j)
s=r
End Function

The following code use the function s() and sends all the test cases and shows the result.

Public Sub Test_Cases()

    Dim cases(5, 1) As String
    Dim i As Integer
    Dim match As Boolean

    ' Define space-delimited strings of numbers.
    ' The second array column shows the expected response.
    cases(0, 0) = "1 2 5 4 3 7":     cases(0, 1) = "1 2 5 7"
    cases(1, 0) = "10 -1 12":        cases(1, 1) = "10 12"
    cases(2, 0) = "-7 -8 -5 0 -1 1": cases(2, 1) = "-7 -5 0 1"
    cases(3, 0) = "9 8 7 6 5":       cases(3, 1) = "9"
    cases(4, 0) = "10 13 17 21":     cases(4, 1) = "10 13 17 21"
    cases(5, 0) = "10 10 10 9 10":   cases(5, 1) = "10 10 10 10"

    Debug.Print "Case Input"; Tab(25); "Output"; Tab(38); "Do they match?"
    For i = 0 To UBound(cases())
        Debug.Print i; Tab(6); cases(i, 0); Tab(25); cases(i, 1); Tab(42);
        ' When calling the sorting function, use Split() to convert the string to
        ' a character array and then use Join() to convert the sorted array back
        ' into a string.  Compare that to the expected response in the second column.
        match = cases(i, 1) = Join(s(Split(cases(i, 0), " ")), " ")
        Debug.Print match
    Next i
    Debug.Print

End Sub

Output should look like this in the Immediate window:

Case Input              Output       Do they match?
 0   1 2 5 4 3 7        1 2 5 7          True
 1   10 -1 12           10 12            True
 2   -7 -8 -5 0 -1 1    -7 -5 0 1        True
 3   9 8 7 6 5          9                True
 4   10 13 17 21        10 13 17 21      True
 5   10 10 10 9 10      10 10 10 10      True

This was a fun challenge. If you know of an online interpreter like TIO for VB6/VBScript/VBA please leave a comment.

If you want to test this code and have Microsoft Excel, Word, Access, or Outlook installed (Windows only), press Alt+F11 to open the VBA IDE. Insert a new code module (Alt+I,M) and clear out Option Explicit. Then paste in the code and press F5 to run it. The results should appear in the Immediate Window (press Ctrl+G if you don't see it).

Ben

Posted 2015-10-26T13:16:14.860

Reputation: 201

You can get your function based answer down to 139 bytes as Function s(c) d=UBound(c) ReDim r(d) r(i)=c(i) For i=1To d If Val(r(j))<=c(i)Then j=j+1:r(j)=c(i) Next ReDim Preserve r(j)s=rEnd Functionor if get it down to 129 bytes with a subroutine approach asSub s(c)d=UBound(c)ReDim r(d)r(i)=c(i)For i=1To dIf Val(r(j))<=c(i)Then j=j+1:r(j)=c(i)NextReDim Preserve r(j)c=rEnd sub` – Taylor Scott – 2019-08-11T14:20:38.560

There is no online IDE for any of the VB family at this time, but if you are interested in something similar, you may consider taking a look at Yabasic at TIO.

– Taylor Scott – 2019-08-11T14:27:36.903

@taylorscott, Good tips to tighten it up. I can't get your sub() method to work. The c=r line is giving the error Variable uses an Automation type not supported in Visual Basic. – Ben – 2019-08-12T02:32:58.870

1Ok. I got the sub() method to work (offline) by changing my test case to pass a variant array of long instead of a variant array of string. That involved writing a loop to convert the string array to a long array which makes the test code longer. It will allow the val() call to be removed which removes another 5 characters. I will add your suggestion in a formatted block but not rewrite the test case because it's late and I'm tired (or just lazy). – Ben – 2019-08-12T03:21:31.663

1

Mathematica, 27 bytes

Pick[#,#-Max~FoldList~#,0]&

alephalpha

Posted 2015-10-26T13:16:14.860

Reputation: 23 988

1

Haskell, 52 bytes

d(x:l)=x:e l x
e(x:l)m|x<m=e l m|0<1=x:e l x
e[]_=[]

d expects a list.

Leif Willerts

Posted 2015-10-26T13:16:14.860

Reputation: 1 060

d$x:l is shorter than x:e l x – Akangka – 2015-10-28T12:13:03.503

1

OCaml, 62

let rec f=function a::b::c when a>b->f(a::c)|a::t->a::f t|t->t

The idea is that if the second element is less than the first element, then we should discard the second element. Otherwise, the first element is kept and we move on to the rest of the list.

feersum

Posted 2015-10-26T13:16:14.860

Reputation: 29 566

1

Ruby, 45 bytes

->a{o=[];a.map{|n|o<<n if !o[0]||n>=o.max};o}

daniero

Posted 2015-10-26T13:16:14.860

Reputation: 17 193

1

Simplex v.0.7, 32 bytes

That was long. Sorry for the vague explanation.

u{viRux}ly^nR@^m^_R&>n?[L@o' s]]
u{viRux}                         ~~ take pseudo-tuple input
        ly                       ~~ converts to tuple
          ^nR@                   ~~ takes minimum and puts it into register
              ^m               ] ~~ map the tuple using inner function
                ^_               ~~ the current value
                  R&>n           ~~ checks if current value is not greater
                      ?[      ]  ~~ does inner if so
                        L@o' s   ~~ outputs the number and a space; stores as current min

Conor O'Brien

Posted 2015-10-26T13:16:14.860

Reputation: 36 228

1

Perl 5, (33 Bytes+2) = 35

A regex-less solution.

map{print$p=$_.$"if$_>=$p||!$p}@F

Test

Note that the @F array is populated because of the -a switch.

$ echo -7 -8 -5 0 -1 4 4 3 5|perl -na -e 'map{print$p=$_.$"if$_>=$p||!$p}@F'
-7 -5 0 4 4 5

LukStorms

Posted 2015-10-26T13:16:14.860

Reputation: 1 776

1Sorry to say, but this doesn't seem to work for the -7 -8 -5 0 -1 1 test case. :( – manatwork – 2015-10-29T16:36:38.080

@manatwork Thanks for noticing. :) The problem was that $p is undefined till a next higher number is found. Adding an additional check solved that problem. – LukStorms – 2015-10-29T22:14:18.507

0

PHP, 63 bytes

function d($l){$m=$l[0];foreach($l as$n)echo$n<$m?"":$m="$n ";}

Try it online!

Jo.

Posted 2015-10-26T13:16:14.860

Reputation: 974

0

SmileBASIC, 57 bytes

DEF D A
WHILE LEN(A)N=SHIFT(A)IF N>=M THEN M=N?N
WEND
END

12Me21

Posted 2015-10-26T13:16:14.860

Reputation: 6 110

0

Perl 5, 24 22 bytes

Includes +2 for -la

#!/usr/bin/perl -la
$_<"$o $_"||say$o=$_

Try it online!

Ton Hospel

Posted 2015-10-26T13:16:14.860

Reputation: 14 114

0

Bash, 63 bytes

echo $1;a=$1;while test $a -gt ${2:?};do shift;done;shift;$0 $@

Try it online! (+3 bytes since "$0 $@" doesn't work in TIO)

DarkHeart

Posted 2015-10-26T13:16:14.860

Reputation: 171

0

Perl 5.10.0 -n, 17 16 15 bytes

$m>$_||say$m=$_

Try it online!

-1 byte thanks to Xcali

wastl

Posted 2015-10-26T13:16:14.860

Reputation: 3 089

1

You can save a byte using || instead of ?:: Try it online!

– Xcali – 2019-08-10T03:46:58.417

0

K (oK), 11 bytes

Solution:

{x@&~<':x}/

Try it online!

Examples:

{x@&~<':x}/1 2 5 4 3 7
1 2 5 7
{x@&~<':x}/10 -1 12
10 12
{x@&~<':x}/-7 -8 -5 0 -1 1
-7 -5 0 1
{x@&~<':x}/9 8 7 6 5
,9
{x@&~<':x}/10 13 17 21
10 13 17 21
{x@&~<':x}/10 10 10 9 10
10 10 10 10

Explanation:

{x@&~<':x}/ / the solution
{        }/ / perform function {} until results converge
     <':x   / less-than (<) each-previous (':) input
    ~       / not
   &        / where, indices where true
 x@         / index back into input at these indices

streetster

Posted 2015-10-26T13:16:14.860

Reputation: 3 635

0

PowerShell, 59 bytes

param($a)$a[0];(1..$a.Count|?{$a[$_]-ge$a[$_-1]})|%{$a[$_]}

Try it online!

I will golf this further as soon as possible.

Gabriel Mills

Posted 2015-10-26T13:16:14.860

Reputation: 778

0

Perl 6, 35 bytes

{(grep {.[0]==.max},[\R,] $_)[*;0]}

Try it online!

bb94

Posted 2015-10-26T13:16:14.860

Reputation: 1 831

0

Clojure, 55 bytes

#(for[[i j](map list(reductions max %)%):when(= i j)]j)

One day I'm gonna do a "Golfure" or something of that short which will have one-symbol names for most handy functions, and even more generic macros.

NikoNyrh

Posted 2015-10-26T13:16:14.860

Reputation: 2 361

0

Python 3, 68 64 62 bytes

lambda L:[L[i]for i in range(len(L))if L[i]>=max(L[:1]+L[:i])]

Try it online!

movatica

Posted 2015-10-26T13:16:14.860

Reputation: 635

0

C++ (gcc), 122 119 bytes

-3 bytes thanx to ceilingcat

#include<list>
auto f(std::list<int>l){auto i=l.begin();for(int m=*i;i!=l.end();)i=*i>=m?m=*i,++i:l.erase(i);return l;}

Try it online!

movatica

Posted 2015-10-26T13:16:14.860

Reputation: 635

0

JavaScript, 7270 bytes

a=>{for(b=[a[l=i=0]];i<a.length;b[l]>=a[++i]?b[++l]=a[i]:0);return a}

72B->70B - -2B for removing assignment of the function.

Naruyoko

Posted 2015-10-26T13:16:14.860

Reputation: 459

Since you do not seem to recurse on f, you could spare yourself the first two bytes. – Jonathan Frech – 2019-04-28T21:04:10.427

@Jonathan Frech Oh ok – Naruyoko – 2019-04-28T21:11:21.307

I am possibly misunderstanding your implementation, but it does not seem to work properly.

– Jonathan Frech – 2019-04-28T22:21:50.510

0

MathGolf, 10 bytes

╓\ô`╙┼=╛o╘

Try it online!

This solution relies on stack manipulation. It could have been 2 bytes shorter if negative numbers are not included (skip the first two bytes). Basically a port of the 05AB1E answer, except there is more of a hassle to get the stack right.

Explanation

╓            minimum of two elements, min of list, minimum by filter
 \           swap top elements, pushing list to top
  ô          start block of length 6
   `         duplicate the top two items
    ╙        maximum of two elements, max of list, maximum by filter
     ┼       duplicate second item from top and push to top
      =      is equal (is the current element equal to the total maximum so far)
       ╛o    print without popping if equal
             loop ends here
         ╘   discard everything in stack

maxb

Posted 2015-10-26T13:16:14.860

Reputation: 5 754

0

Oracle SQL, 115 bytes (Version 12c+)

select x from t match_recognize(order by i all rows per match pattern((p|{-y-})+)define p as x>=nvl(last(p.x,1),x))

It works with an assumption that input data is stored in a table t(i,x) (i for order), e.g.

with t(i,x) as (select rownum,value(v) from table(sys.odcinumberlist(1,2,5,4,3,7))v)

Test in SQL*Plus.

SQL> with t(i,x) as (select rownum,value(v) from table(sys.odcinumberlist(1,2,5,4,3,7))v)
  2  select x from t match_recognize(order by i all rows per match pattern((p|{-y-})+)define p as x>=nvl(last(p.x,1),x))
  3  /

         X
----------
         1
         2
         5
         7

Dr Y Wit

Posted 2015-10-26T13:16:14.860

Reputation: 511

0

Pushy, 14 bytes

@vL:Ov2d>?.;;_

Try it online!

                     \ Implicit: input on main stack.
@                    \ Reverse stack.
 v                   \ Move top item to auxiliary stack.
  L:        ;        \ length(main stack) times do:
    Ov               \   Move top item from main stack to auxiliary stack.
      2d>? ;         \   If top element > second element:
          .          \       Pop the main stack element.
             _       \ Output stack.

FlipTack

Posted 2015-10-26T13:16:14.860

Reputation: 13 242

0

rs, 121 109 bytes

(\d+)/(_)^^(\1)
-/n
+\b((_+) n_+|(n_+) \3_+|(_+)(_+) \4|(_+ ) |( ) n_+)\b/\2\3\4\5\6\7
n/-
(_+)/(^^\1)
  / 0 

The magic line is 3, which basically continuously deletes elements that aren't sorted.

Live demo and test cases.

121-byte version

(\d+)/(_)^^(\1)
-/n
+\b(((_+) n_+)|((n_+) \5_+)|((_+)(_+) \7)|((_+ ) )|(( ) n_+))\b/\3\5\7\8\10\12
n/-
(_+)/(^^\1)
  / 0 

Dang...12 groups...

Live demo and test cases.

kirbyfan64sos

Posted 2015-10-26T13:16:14.860

Reputation: 8 730

0

Ceylon, 73

Integer[]d(Integer[]l)=>[for(i->x in l.indexed)if(x==max{x,*l[0:i]})x];

Formatted and commented:

// dropsort: "sorts" a sequence of integers by dropping all elements which don't fit.
// input and output are (possible empty) sequences of integers.
Integer[] d(Integer[] l) =>
// construct a sequence with a comprehension
        [
    // iterate over the input sequence, with indexes.
    for (i->x in l.indexed)
        // only if x it is the maximum of ...
        if (x == max
            // .. an iterable made from x and the part of the input sequence just before the current index ...
                { x, *l[0:i] })
            // ... include x in the iteration.
            x];

This features an sequence comprehension (with for and if clause) for the return value, the => function defintion, the shortcut syntax X[] for Sequential<X> (i.e. a possibly empty sequence), a named argument list for max, in which we have actually no named arguments, but the contents for an iterable argument, given by a single entry and a spread argument made from a measured subsequence, to make it (the argument) non-empty (otherwise max could possibly return null, which can't be compared to x).

Paŭlo Ebermann

Posted 2015-10-26T13:16:14.860

Reputation: 1 010

0

Python 2 59 bytes

f=lambda a: reduce(lambda x,y:x+([],[y])[y>x[-1]],a,[a[0]])

Assumes the list is not empty, as stated in the description. Simple.

njzk2

Posted 2015-10-26T13:16:14.860

Reputation: 121

0

RETURN, 29 bytes (noncompetitive)

[␃$a:␌[$¥][$a;-<[%][$a:␌]?]#]

Try it here.

Anonymous lambda that leaves result on Stack2. Usage:

1 2 5 4 3 7[␃$a:␌[$¥][$a;-<[%][$a:␌]?]#]!

NOTE: Make sure to paste this string using the Insert String button, which will transform the control pictures into their respective unprintables.

Explanation

[                            ]  lambda
 ␃$a:␌                         reverse stack, set TOS to a and push to Stack2
       [  ][               ]#   while loop
        $¥                        check if TOS is integer
            $a;-<                 if so, check if TOS < a
                 [ ][    ]?       conditional
                  %                 if so, drop TOS
                     $a:␌           otherwise, set TOS to a and push to Stack2

Mama Fun Roll

Posted 2015-10-26T13:16:14.860

Reputation: 7 234