Implement Takewhile

30

3

Introduction and Credit

Today without a fancy prelude: Please implement takewhile.

A variation of this (on a non-trivial data structure) was an assignment at my university functional programming course. This assignment is now closed and has been discussed in class and I have my professor's permission to post it here (I asked explicitly).

Specification

Input

The input will be a list (or your language's equivalent concept) of positive integers.

Output

The output should be a list (or your language's equivalent concept) of positive integers.

What to do?

Your task is to implement takewhile (language built-ins are allowed) with the predicate that the number under consideration is even (to focus on takewhile).

So you iterate over the list from start to end and while the condition (is even) holds, you copy to the output-list and as soon as you hit an element that doesn't make the condition true, you abort the operation and output (a step-by-step example is below). This higher-order functionality is also called takeWhile (takewhile).

Potential corner cases

The order of the output list compared to the input list may not be changed, e.g. [14,42,2] may not become [42,14].

The empty list is a valid in- and output.

Who wins?

This is code-golf so the shortest answer in bytes wins!

Standard rules apply of course.

Test Vectors

[14, 42, 2324, 97090, 4080622, 171480372] -> [14, 42, 2324, 97090, 4080622, 171480372]
[42, 14, 42, 2324] -> [42, 14, 42, 2324]
[7,14,42] -> []
[] -> []
[171480372, 13, 14, 42] -> [171480372]
[42, 14, 42, 43, 41, 4080622, 171480372] -> [42, 14, 42]

Step-by-Step Example

Example Input: [42, 14, 42, 43, 41, 4080622, 171480372]

Consider first element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42]

Consider second element: 14
14 is even (7*2)
Put 14 into output list, output list is now [42,14]

Consider third element: 42
42 is even (21*2)
Put 42 into output list, output list is now [42,14,42]

Consider fourth element: 43
43 is not even (2*21+1)
Drop 43 and return the current output list

return [42,14,42]

SEJPM

Posted 2016-07-05T18:36:31.717

Reputation: 3 203

2Is it OK if I return an iterator, rather than a list? – James – 2016-07-05T19:45:47.770

2@DrGreenEggsandIronMan I'm guessing your function has to be able to take its output as its input, guaranteeing they are in the same format. – mbomb007 – 2016-07-05T19:47:53.213

@DrGreenEggsandIronMan, I don't think that returning a sublist should be exploited here in the output format. (It's still up to you if you exploit this in your code though). Mbomb's criterion looks most appropriate and compatible with the current challenge so it will be "your output should be a valid input at the very least". – SEJPM – 2016-07-05T20:00:31.360

Answers

28

Mathematica, 18 bytes

#~TakeWhile~EvenQ&

Another glorious built-in that is beaten by a factor of 3 by golfing languages without the built-in...

Martin Ender

Posted 2016-07-05T18:36:31.717

Reputation: 184 808

3How many built-ins does Mathematica have? Seems as if it has one for almost anything. – Emigna – 2016-07-05T19:06:35.087

35@Emigna I haven't counted, but Rule #110 of the internet is, "If it exists, there's a Mathematica built-in for it." – Martin Ender – 2016-07-05T19:07:26.550

3@MartinEnder Too bad that Rule #110.5 of the internet is, "If it involves strings in any way whatsoever, then it is not considered to exist for the purposes of Rule #110." – LegionMammal978 – 2016-07-06T11:26:10.897

@LegionMammal978 The workaround is to make strings heads of expressions :) – LLlAMnYP – 2016-07-07T11:03:55.803

26

Haskell, 13 bytes

fst.span even

span splits the input list into a pair of lists just before the first element where the predicate (-> even) is false. fst takes the first element of the pair.

Alternative version, 13 bytes:

fst.break odd

break is the opposite of span, i.e. it splits the list at the first element where the predicate is true.

Of course there's also

takeWhile even

but that's 14 bytes.

nimi

Posted 2016-07-05T18:36:31.717

Reputation: 34 639

23

MATL, 6 bytes

toYs~)

Try it online!

Explanation

t    % Input array implicitly. Duplicate
o    % Parity of each entry. Gives 0 for even entries, 1 for odd
Ys   % Cumulative sum
~    % Logical negate. Gives true for the first run of even entries, and then false
)    % Use this as logical index into the original array. Implicitly display

Luis Mendo

Posted 2016-07-05T18:36:31.717

Reputation: 87 464

22Is this normal, that the code says "toys" with a smile there? – SEJPM – 2016-07-05T18:56:09.913

3@SEJPM to~Y<) also works, but I like this one better :-) – Luis Mendo – 2016-07-05T18:56:53.193

13

Hexagony, 19

2.}<@>%?<{>$"/\M!8;

Readable:

  2 . }
 < @ > %
? < { > $
 " / \ M
  ! 8 ;

Try it online!

This can probably be golfed by a byte or two, but that might require some truly ingenious layout, that might be more easily found via brute force (even if it might take rather long to find it).

High level explanation

The program mostly follows this pseudocode:

while (read number is not zero) 
{
    if (number is even) 
        print number;
} 

Which abuses how Hexagony tries to read a number once STDIN is empty (it returns a zero). Big thanks to Martin for help with coming up with this approach.

Full Explanation

I still haven't fiddled around with Mono to get Timwi's fantastic esoteric IDE running, so I've leant on Martin to provide me with some helpful pretty pictures!

First, a little primer on basic control flow in Hexagony. The first instruction pointer (IP), which is the only one used in this program, starts at the top left of the hexagonal source code, and begins moving towards the right. Whenever the IP leaves the edge of the hexagon, it moves side_length - 1 rows towards the middle of the hexagon. Since this program uses a side length three hexagon, the IP will always be moving two rows when this happens. The only exception is if it moves off of the middle row, where it conditionally moves towards the top or bottom of the hexagon, depending on the value of the current memory edge.

Now a bit about conditionals. The only conditionals in Hexagony for control flow are >, < and the middle edge of the hexagon. These all follow a constant rule: if the value on the current memory edge is zero or negative control flow moves left and if is positive the control flows right. The greater than and less than brackets redirect the IP at sixty degree angles, while the edge of the hexagon controls to which row the IP jumps.

Hexagony also has a special memory model, where all data is stored on the edges of an infinite hexagonal grid. This program only uses three edges: one to store a two, one for the currently read number, and one for the number modulo two. It looks something like:

Mod  \ / Input
      |
      2

I'm not going to carefully explain where we are in memory at each point during the explanation of the program, so come back here if you get confused by where we are in memory.

With all of that out of the way, the actual explanation can begin. First, we populate the "2" edge in memory with a 2, then we execute a no-op and move the memory pointer to the right (2.}).

Next, we begin the main program loop. We read the first number from STDIN and then we hit a conditional (?<). If there are no numbers left in STDIN, this reads a zero into the current memory edge, so we turn left onto the @, which ends the program. Otherwise, we bounce off a mirror, move the memory pointer backwards and to the left, wrap around the hexagon to calculate the remainder of dividing the input by 2 and then hit another conditional (/"%>).

Odd Path

If the remainder was one (i.e. the number was odd), we turn right following the blue path above starting by executing the no-op again, then we wrap around to the bottom of the hexagon, multiply the current edge by 10 and then add eight, bounce off a couple mirrors, do the same multiplication and addition again, getting 188 on the current edge, wrapping back around to the top of the hexagon, executing the no-op again, and finally ending the program (.8/\8.@). This convoluted result was a happy accident, I originally had written a much simpler bit of logic, but noticed that I could remove it in favour of the no-op, which I thought was more in the spirit of Hexagony.

Even Path

If the remainder was zero we instead turn left following the red path, above. This causes us to move the memory pointer to the left, and then print the value there (the input value) as a number. The mirror we encounter acts as a no-op because of the direction we are moving ({/!). Then we hit the edge of the hexagon which acts a conditional with only one outcome, as the input value from before was already tested to be positive, so we always move towards the right (if you imagine yourself facing in the direction of the IP). We then multiple the input by 10 and add two, only to change direction, wrap around and overwite the new value with the ascii value of the capital letter M, 77. Then we hit some mirrors, and exit over the edge of the middle of the hexagon with a trampoline (2<M\>$). Since 77 is positive, we move right towards the bottom of the hexagon and because of the trampoline skip the first instruction (!). We then multiply the current memory edge by 10 and add 8, getting 778. We then output this value mod 256 (10) as an ASCII character, which happens to be newline. Finally we exit the hexagon and wrap back around to the first ? which overrides the 778 with the next input value.

FryAmTheEggman

Posted 2016-07-05T18:36:31.717

Reputation: 16 206

8Readable yeah right – Taylan – 2016-07-06T13:09:52.190

10

Pyth, 13 9 7 bytes

uPWs%R2

Credits to @FryAmTheEggman for 2 (quite tricky) bytes!

Explanation:

u       Q    keep applying to input until invariant:
 PW          drop last element if...
   s%R2G     ...any one is odd, G is the argument originally given the value of input

Test it here.

busukxuan

Posted 2016-07-05T18:36:31.717

Reputation: 2 728

1This is not quite a correct variable introduction description. There should be two Gs introduced, one for the condition s%R2G and one as the argument to the function P. – isaacg – 2017-11-07T04:48:32.683

9

Jelly, 5 bytes

Ḃœp⁸Ḣ

Try it online! or verify all test cases.

How it works

Ḃœp⁸Ḣ  Main link. Argument: A (array)

Ḃ      Bit; yield 1 for odd integers, 0 for even ones.
   ⁸   Yield A.
 œp    Partition A, splitting at 1's in the bit array.
       This yields a 2D array of runs of even integers.
    Ḣ  Head; extract the first chunk.

Dennis

Posted 2016-07-05T18:36:31.717

Reputation: 196 637

8

Python 2, 43 42 bytes

def f(x):
 while"1'"in`map(bin,x)`:x.pop()

The function modifies its argument in place.

Thanks to @xnor for golfing off a byte in a really clever way!

Test it on Ideone.

Dennis

Posted 2016-07-05T18:36:31.717

Reputation: 196 637

4This is crazy, but I think you can check for an odd element as "1'"in`map(bin,x)` for Python 2. – xnor – 2016-07-05T23:34:10.387

That's brilliant. Thanks! – Dennis – 2016-07-05T23:47:37.247

8

ed, 13

/[13579]$/,$d

Because real programmers use The Standard Text Editor.

Takes input as one integer on each line; outputs in the same format.

This simply finds the first odd number (number ending in an odd digit) and deletes from that line until the end of the file.

Doorknob

Posted 2016-07-05T18:36:31.717

Reputation: 68 138

uhhhhh. so that's what that program is for. – cat – 2016-07-06T02:32:36.230

7

Clojure, 21 bytes

#(take-while even? %)

Clojure is kinda nearly competing at last! (thanks to the task being a built-in) See it online https://ideone.com/BEKmez

cliffroot

Posted 2016-07-05T18:36:31.717

Reputation: 1 080

6

Python, 45 44 bytes

f=lambda x:x and~x[0]%2*x and x[:1]+f(x[1:])

Test it on Ideone.

Dennis

Posted 2016-07-05T18:36:31.717

Reputation: 196 637

Aww man.. And there goes any chance I thought I had at winning a bounty

– James – 2016-07-05T19:51:36.447

1Only pure code-golf questions with no restrictions posted before July 22, 2015 are eligible. – Dennis – 2016-07-05T19:52:05.500

@DrGreenEggsandIronMan Mine has been shorter than yours the entire time. I posted mine first. :P

– mbomb007 – 2016-07-05T19:53:22.740

2Outgolfed by Dennis, who would've thought :) – shooqie – 2016-07-05T19:53:40.840

@mbomb007 sure about that?

– James – 2016-07-05T19:54:22.520

@DrGreenEggsandIronMan Not a list. :P The question says "list" – mbomb007 – 2016-07-05T19:54:41.903

Honestly though, my secondary answer that prints would tie Dennis's answer, if that was allowed. So until Dennis shaves off one more byte, I'm an honorary Dennis-level golfer. :D – mbomb007 – 2016-07-05T19:59:35.320

5

05AB1E, 8 7 bytes

[DÉO_#¨

Explanation

[        # infinite loop start
 DÉO     # count odd numbers
    _    # push negative bool (turning 0->1, X->0)
     #   # if true (no odd numbers exist), break out of loop and implicitly print
      ¨  # else, remove last element from list

Try it online

Previous 8 byte solution

vyÈiyˆëq

Explanation

v         # for each y in input
 yÈi      # if y is even
    yˆ    # push y to global array
      ëq  # else terminate program
          # implicitly print global array

Try it online

Emigna

Posted 2016-07-05T18:36:31.717

Reputation: 50 798

5

R, 25 bytes

x=scan()
x[!cumsum(x%%2)]

Or equivalently

(y=scan())[!cumsum(y%%2)]

pajonk

Posted 2016-07-05T18:36:31.717

Reputation: 2 480

this is elegant. – user5957401 – 2016-08-10T15:58:46.180

5

Brainf***, 263 bytes

I took a little snippet from here

>>>>>>,[>>>>>>,]>++++[<++++++++>-]>>>>>+>>>>>>>++++[<++++++++>-]<<<<<<<[<<<<<<]>>>>>>[[>>>>>>>++++[<-------->-]<]<<<<<<[->>>+<<<]>>>[-<+<<+>>>]<>>+>+<<<[-[->]<]+>>>[>]<[-<]<[-]<-[<[<<<<<<]>>>>>>.>>>>>>[>[-]++++[<++++++++>-]<.>>>>>>]>++++[-<++++++++>]<.[-]]>>>>>>]

I'd give an explanation but even I don't have a clue how this works anymore.

Expects input as space-seperated numbers (eg 2 432 1)

anOKsquirrel

Posted 2016-07-05T18:36:31.717

Reputation: 361

Takewhile in BF ._. +1 – TuxCrafting – 2016-07-08T20:31:37.047

You can probably golf the chains of + and > using some logic? – Rɪᴋᴇʀ – 2016-07-08T20:33:01.920

@EᴀsᴛᴇʀʟʏIʀᴋ quite a few of the chains are already golfed (otherwise there would be a lot of rows of 32 '+'s), and I could probably make some of the >s more efficient but I don't understand them enough now – anOKsquirrel – 2016-07-08T20:35:17.477

That's why you should comment your code as you write it in Notepad. :P – mbomb007 – 2016-07-08T21:02:50.317

4

Pyth, 7 bytes

<x%R2Q1

Try it here!

What I attempted to do in Pyke but index is broken in that atm

Blue

Posted 2016-07-05T18:36:31.717

Reputation: 26 661

4

Labyrinth, 14 bytes

?:
"`#
"@%
\!;

Input and output are linefeed-separated lists (although in principle, the input could use any non-digit separator).

Try it online!

This is probably the most compact Labyrinth program I've ever written.

Interestingly, takewhile(odd) is lot simpler:

?:#
" %
\!/

Explanation

The usual Labyrinth primer:

  • The memory model is a stack (there's actually two, but we'll only need one for this program), which holds arbitrary-precision integers and initially holds an (implicit) infinite number of zeros.
  • There are no control flow instructions. Instead, the movement of the instruction pointer (IP) is determinated by the layout of the code (spaces are considered "walls" and cannot be traversed by the IP). Normally, the code is supposed to resemble a maze, where the IP follows straight corridors and bends, but whenever it reaches a junction, this acts as a conditional where the IP's new direction is determined based on the current state. The rules for choosing a direction boil down to this: if the top of the stack is zero, the IP keeps moving forward; if the top is positive, the IP turns right; if the top is negative the IP turns left. If one of these directions is blocked by a wall, the IP takes the opposite direction instead. This means that programs without clear corridors are usually incredibly tough to work with, because every single command would act as a junction. The fact that this worked out in this case is a bit of a miracle.
  • The IP starts at the first non-space character in reading order (? in this case), moving east.

The main flow through the program is a single loop around the perimeter:

>v
^>v
^@v
^<<

As it happens, we know that the top of the stack is zero after ! and " so that the IP is guaranteed not to turn towards the centre. ` and % on the other hand are used as conditionals where the IP might move towards the centre such that @ terminates the program, or it might keep moving around the perimeter.

Let's look at the code in the loop:

?   Read decimal integer N from STDIN, or 0 at EOF.
:   Duplicate. Since this is just a corner, the IP always turns south.
`   Negate the copy of the input (i.e. multiply by 1). At EOF, the result
    is still zero and the IP keeps moving south into the @. Otherwise, the
    top of the stack is now negative, and the IP turns east.
#   Push the stack depth (i.e. 2). Again, this is a corner, and the IP
    is forced to turn south.
%   Computer (-N % 2), which is identical to (N % 2) to determine the
    parity of the input. If input was odd, this gives 1, and the IP turns
    west into the @. Otherwise, the result is 0 and the IP keeps moving
    south, continuing the loop.
;   Discard the 0. This is a corner, so the IP is forced to turn west.
!   Print (and discard) N. The top of the stack is now one of the implicit
    zeros at the bottom, so the IP keeps moving west.
\   Print a linefeed. The IP is forced to turn north in the corner.
""  Two no-ops. The top of the stack is still zero, so the IP keeps moving north.

And then the loop starts over.

That raises the question why takewhile(odd) is so much simpler. There's two reasons:

  • Since EOF is returned as 0 (which is even), we don't need a separate EOF check. The list would be cut off at that point anyway.
  • Now we want to terminate when N % 2 is 0 (as opposed to 1), which means instead of conditional control flow we can simply divide the other copy N by N % 2: if the input is odd, that just leaves N and we even got rid of the N % 2 (so we don't need ;), but if the input is even, that simply terminates the program with a (silent) division-by-zero error.

Hence, the other code is a simple loop that doesn't allow for any branching at all.

Martin Ender

Posted 2016-07-05T18:36:31.717

Reputation: 184 808

4

Racket, 22 bytes

(λ(n)(takef n even?))

The λ character is counted as 2 bytes.

I haven't seen Racket used before in any of the code golfing answers I've seen, so I had to do it at least once!

Steven H.

Posted 2016-07-05T18:36:31.717

Reputation: 2 841

2I used to golf in Racket, hooray for Racket! – cat – 2016-07-06T01:17:33.563

3

Brachylog, 19 16 bytes

hH:2%0,?b&~b.hH;[].

s.:Mc?,.:{:2%0}a

Explanation

s.                 Output is an ordered subset of Input
  :Mc?,            The concatenation of Output with a list M is Input
       .:{:2%0}a   All elements of Output are even

Today I learnt a neat trick (which was used in the 19 bytes answer): ~b.hH is shorter than :[H]rc. to append an element at the beginning of a list. The first one means "Output is the result with an extra item at the beginning, and the first item of the Output is H", whereas the other one is straightforwardly "Output is the concatenation of [[H], Result]".

Fatalize

Posted 2016-07-05T18:36:31.717

Reputation: 32 976

3

Retina, 17 bytes

 ?\d*[13579]\b.*

The trailing linefeed is significant. Input and output are space-separated lists.

Try it online!

This is a simple regex substitution, it matches the first odd number (i.e. a number ending in an odd digit), and if possible the space preceding it as well as everything after it and replaces it with an empty string, i.e. all elements from there onward are removed from the input.

As Leaky Nun points out, taking the list in binary, we can save 6 bytes, but it seems a bit cheaty, so I'll probably continue counting the decimal version:

 ?\d*1\b.*

Martin Ender

Posted 2016-07-05T18:36:31.717

Reputation: 184 808

You can take the list in binary? – Leaky Nun – 2016-07-07T10:37:26.760

3

J, 10 bytes

{.~2&|i.1:

Explanation

{.~2&|i.1:  Input: s
   2&|      Take each value in s mod 2
      i.1:  Find the index of the first 1
{.~         Take that many values from s and return

miles

Posted 2016-07-05T18:36:31.717

Reputation: 15 654

1{.2&|<;._2] is interesting (although longer) – Leaky Nun – 2016-07-07T10:41:36.187

Use $ instead of {. – FrownyFrog – 2018-03-11T15:50:00.927

3

CJam, 11 bytes

Thanks to @Dennis for two corrections and one byte off!

{1+_2f%1#<}

This is a code block (equivalent to a function; allowed by default) that expects the input array on the stack, and leaves the output array on the stack.

Try it online!

Explanation

{         }    e# define code block
 1+            e# attach 1 at the end of the array
   _           e# duplicate
    2f%        e# modulo 2 of each entry
       1#      e# find index of first occurrence of 1
         <     e# slice before

Luis Mendo

Posted 2016-07-05T18:36:31.717

Reputation: 87 464

3

JavaScript (Firefox 30-57), 30 bytes

a=>[for(x of a)if(!(a|=x&1))x]

Neil

Posted 2016-07-05T18:36:31.717

Reputation: 95 035

3

Python, 41 bytes

lambda l:l[:[x%2for x in l+[1]].index(1)]

Truncates l up to the index of the first occurrence of an odd number. The index is found by looking for a 1 in the values modulo 2. To guard against no odd number being found, a 1 is put on the end.

xnor

Posted 2016-07-05T18:36:31.717

Reputation: 115 687

3

C#, 50 bytes

int[]f(int[]a)=>(a.TakeWhile(x=>x%2<1).ToArray());

ScifiDeath

Posted 2016-07-05T18:36:31.717

Reputation: 151

You can use a lambda directly. It is valid as far as I know. a=>a.TakeWhile(x=>x%2<1); – aloisdg moving to codidact.com – 2016-07-06T17:02:59.480

2

V, 13 bytes

íä*[13579]¾.*

Try it online!

Explanation:

í              "search for, on every line
 ä*            "Any number of digits
   [13579]     "Followed by an odd digit
          ¾    "Then the end of a word,
           .*  "Followed by anything
               "(implicit) and replace it with nothing.

Conveniently, the same code works to verify all test-cases simultaneously.

James

Posted 2016-07-05T18:36:31.717

Reputation: 54 537

2

Pyke, 8 bytes

0+2L%fhO

Interpreter fixed, use other links

Uses Dennis' method except my split_at function includes the change - probably a bug

Or with bugfix, 7 bytes

2L%1R@<

Try it here!

2L%     -   map(%2, input)
   1R@  -  ^.index(1)
      < - input[:^]

Or after 2nd bugfix, 6 bytes

2L%fhO

Try it here!

Explanation:

2L%    -   map(%2, input)
   f   -  split_at(input, ^)
    hO - ^[0][:-1]

Blue

Posted 2016-07-05T18:36:31.717

Reputation: 26 661

2

Ruby, 25 bytes

->a{a.take_while &:even?}

I think I lose...

MegaTom

Posted 2016-07-05T18:36:31.717

Reputation: 3 787

Can you do ->a{a.take_while &:even?} or at least ->a{a.take_while(&:even?)}? – Martin Ender – 2016-07-05T19:11:00.083

@MartinEnder Thank you. I was looking for something like that, but I guess I am not well versed in ruby golfing syntax. – MegaTom – 2016-07-05T19:13:40.980

2

Dyalog APL, 11 bytes

{⍵/⍨∧\~2|⍵}

2| division remainder from dividing with 2

~ negate

∧\ AND-scan (turns off from first 0)

/⍨ select where

Adám

Posted 2016-07-05T18:36:31.717

Reputation: 37 779

2

Python 3, 59 bytes

def f(l):
 L=[]
 for x in l:
  if x%2:break
  L+=x,
 return L

Can surely probably be golfed more.

Thanks to everyone who commented :D

TuxCrafting

Posted 2016-07-05T18:36:31.717

Reputation: 4 547

x%2<1 and x%2>0 are shorter – mbomb007 – 2016-07-05T19:30:31.950

just use x%2 - 0 is false. You can flip the condition to use it for the other one too. – Random832 – 2016-07-05T19:43:15.603

@mbomb007 I'd just flip the condition: []if x%2 else[x] – Random832 – 2016-07-05T19:44:41.503

wait a minute, why do you even need a condition after the break – Random832 – 2016-07-05T19:45:58.950

And with the condition gone, adding a tuple works and is one character shorter: L+=x, – Random832 – 2016-07-05T19:48:20.740

If you replace the if with if not, you can save 7-4=3 bytes (if not x%2>0:L+=x) – J F – 2016-07-06T12:45:10.830

if x%2>0: is equivalent with if x%2: – Leaky Nun – 2016-07-07T10:45:33.393

2

Forth, 114 bytes

Forth doesn't really have lists. The parameters must be pushed onto the stack in reverse order, as is typical in Forth. The result will be left on the stack in the same order. This doesn't work on Ideone for some reason, but it works on repl. The new line is required to remove ambiguity of some sort?

: D DEPTH ;
: f D IF 1 D 1 DO D 1- ROLL LOOP D 0 DO I PICK 2 MOD IF D I LEAVE THEN LOOP
DO I ROLL DROP LOOP THEN ;

Try it online

Ungolfed, with comments:

: f DEPTH IF                                ( if stack not empty )
        1 DEPTH 1 DO DEPTH 1- ROLL LOOP     ( put 1 on bottom of stack )
        DEPTH 0 DO                          ( loop over entire stack )
            I PICK 2 MOD IF                 ( if stack[i] is odd )
                DEPTH I LEAVE               ( put range and exit loop )
            THEN
        LOOP
        DO I ROLL                           ( roll eyes )
            DROP
        LOOP                                ( iterate that range and remove )
    THEN
;

This program (my previous attempt) prints the results until it hits an odd number. Everything remaining (not taken) will be left on the stack.

: f DEPTH IF BEGIN DUP 2 MOD DUP 1- IF SWAP . THEN UNTIL THEN ;

Fails if only even integers

mbomb007

Posted 2016-07-05T18:36:31.717

Reputation: 21 944

5After finishing this, I realized my breakfast was cold. :( – mbomb007 – 2016-07-06T14:54:44.243

Too often I find my dinner cold after golfing code at the table. Perhaps Factor will let you be more productive and golfier at the same time? :D

– cat – 2016-07-06T20:03:16.550

@c I do my code development for PPCG with online IDEs. But I use Forth because I already know it, it's just difficult to manage a stack in my head. I originally learned Forth because a Minecraft mod added redstone computers that ran a version of Forth entitled MineOS. – mbomb007 – 2016-07-06T20:13:06.207

2

GolfScript, 11 bytes

This is a full GolfScript program that reads a stringified GolfScript array literal (e.g. [28 14 7 0]) and prints out the same array with the first odd element and everything after it removed:

~1\{~&.},p;

Try it online. (Also: Extended version with test harness.)

De-golfed version with comments:

~     # evaluate input
1\    # push the number 1 onto the stack and move it under then input array
{     # start of loop body
  ~   #  bitwise negate the input number (making odd numbers even and vice versa)
  &   #  take bitwise AND of input and the saved number (0 or 1) on stack 
  .   #  duplicate result; filter loop will pop off the duplicate
},    # run loop above over input array, select elements for which it returns true
p     # stringify and print filtered array
;     # pop the number 0/1 off the stack

This solution is based on the GolfScript { }, filter operator, which runs the contents of the code block on each element of an array, and selects the elements of the array for which the code in the block returns a true (i.e. non-zero) value on top of the stack.

Thus, for example, {1&}, would select all odd numbers in an array, and {~1&}, would select all even numbers. The challenge, then, is to make a filter that selects even numbers until it finds the first odd one, and thereafter selects no numbers at all.

The solution I used is to replace the constant bit-mask 1 (used to extract the lowest bit of each input number) with a variable on the stack that stores the result (0 or 1) of the previous filter loop iteration (and is initialized to 1 before the loop). Thus, as soon as the filter returns 0 once, the bitmask also gets set to 0, preventing the filter from ever returning 1 again.

Ilmari Karonen

Posted 2016-07-05T18:36:31.717

Reputation: 19 513

2

Befunge, 35 Bytes

This code handles numbers between 0 and 65535

1&:v
v-1_@#:@#<
>\:&:2%|
 \+1p4\< ^

Input format :

number_of_values    values(separated by a space)

Here is a version that displays the values at the end of the process :

1&:v>::   v                >00g1+:4g.v
v-1_^#:>#<>$$\$1-:10p000p0-| -g01p00:<
>\:&:2%|                   @
 \+1p4\< ^

You may test the code here, but you will have to add a trailing line with trailing spaces, as this interpret specifies :

« The code torus is only as large as the initial program. Insert more lines or trailing space if data will be put beyond the end of code.»

I don't know if this is acceptable, as I didn't count this trailing in the byte count
nb: it seems that because I'm storing number in the code, the interpreter won't let this program run twice in the correct way. You'll have to reload it.


How does this work: how The interpreter follows the arrows and skip an instruction when crossing '#'

Grey dots are test, and the red line removes unneeded variables from the stack

Using the here in the above interpreter, the saved values are displayed in the code using their representations (I don't know the format). Yes, Befunge is a quite reflective language

Maliafo

Posted 2016-07-05T18:36:31.717

Reputation: 361

2

32-bit x86 machine code, 14 bytes

In hex:

31C9FCADD1E87203E0F941F7D9C3

The list of integers in machine code is something like C's "int a[]". Since the list contains positive integers let's assume the list is zero-terminated, i.e. the value zero marks the end of the array. It's also makes no sense to copy values to another buffer inside this function, that's what strncpy() is for.

The pointer to an array is passed via ESI register. Returns the number of elements comprising the resulting list in ECX.

Disassembly:

31 c9     xor    ecx,ecx  ;ECX=0
fc        cld
_loop:
ad        lodsd           ;Fetch a number to EAX
d1 e8     shr    eax,1    ;EAX=>>1
72 03     jc _end         ;If CF is set then the number is odd, break
e0 f9     loopne _loop    ;--ECX; if(CF==0&&ZF==0)continue
41        inc    ecx      ;Should not include the terminating 0 into the count
_end:
f7 d9     neg    ecx      ;Counting from 0 downward, so ECX=-ECX
c3        ret

meden

Posted 2016-07-05T18:36:31.717

Reputation: 711

2

JavaScript, 27 25 bytes

a=>a.filter(v=>a=a&&~v%2)

The filer expression repeatedly assigns to a and uses the value of a as a filter predicate. a holds either the initial array value (always truthy) or the boolean of whether only even values have been seen. When a turns false (i.e., an odd number appears), then subsequent runs of the a = a && ... logical AND operation short cirucits, and we use false for the rest of the run.

The bitwise NOT ~v turns even numbers to odd and vice versa, so ~v%2 returns a truthy value for even input and falsy values for odd input.

apsillers

Posted 2016-07-05T18:36:31.717

Reputation: 3 632

2

Perl 5 + Perligata, 173 bytes

145 bytes, plus 28 for -MLingua::Romana::Perligata

Use as perl -MLingua::Romana::Perligata foo.pl; input (from stdin) and output (to stdout) are underscore-separated strings of decimal integers. Tested on Strawberry 5.20.2 with version 0.6 of Perligata, released two days ago; I don't know whether it works with Perligata version 0.50.

huic vestibulo perlegementum da.his _ scindementa da.per in his fac sic
si recidementum hoc tum II fac sic I exi cis
hoc tum _ egresso scribe
cis

Obviously this is clear as a bell. In case it's not, run it with -MLingua::Romana::Perligata=converte instead of -MLingua::Romana::Perligata, and perl will, instead of running the script, output a translation into regular Perl:

 $_ = Lingua::Romana::Perligata::getline (*STDIN );
 @_ = split ( '_');
for $_ (@_) {if ( ($_ % 2)) {exit ( 1)}
;
print (STDOUT $_, '_')}

For a token-by-token analysis, use -MLingua::Romana::Perligata=discribe.


Golfing notes:

  • It seems from the documentation that ultimus si recidementum hoc tum II fac. would work instead of si recidementum hoc tum II fac sic ultimus cis, saving 7 bytes. But it doesn't (it gives a "iussa absentia" error).
  • Undocumented (but unsurprising), you don't need a space after ..
  • (Also unsurprising,) scinde doesn't need a second argument, and uses hoc. Alas, exi needs an argument.
  • Instead of huic vestibulo perlegementum da, I tried -pMLingua::Romana::Perligata, but couldn't get it to work.

Just for kicks (although this whole answer was just for kicks):

  • After cleaning it up to Huic vestibulo perlegementum da. His lacunam scindementa da. Per in his fac sic si recidementum hoc tum II fac sic I exi cis. Hoc tum lacunam egresso scribe cis., Google Translate gives This court perlegementum grant. His gap scindementa grant. 2 By that time, do so in the following 1, Go out and do so if recidementum on this side. This was the gap as soon as write on this side..

msh210

Posted 2016-07-05T18:36:31.717

Reputation: 3 094

what is this witchery – Addison Crump – 2016-07-08T15:57:31.933

2

SML, 44 bytes

an assignment at my university functional programming course

Yay, functional programming! So as an assignment solution, this would probably look like this:

(* 'a takeWhile : ('a -> bool) -> 'a list -> 'a list *)
fun takeWhile p nil     = nil
  | takeWhile p (x::xr) = if p x then x :: takeWhile p xr else nil

(* takeWhileEven : int list -> int list *) 
val takeWhileEven = takeWhile (fn x => x mod 2 = 0)

which can be golfed to

fun t[]=[]|t($ :: &)=if$mod 2=0then$ ::t&else[]

However using foldr is 3 bytes shorter:

foldr(fn($,r)=>if$mod 2=0then$ ::r else[])[]

Laikoni

Posted 2016-07-05T18:36:31.717

Reputation: 23 676

1

Perl 6, 14 bytes

{|$_,1...^*%2}

Try it online!

Finally, a use for a neat trick I found involving .... This is an anonymous code block that basically filters the list until it reaches an element that succeeds in the condition *%2 i.e. odd. Then we return the list excluding the last element. Since an element has to pass the condition at some point, otherwise it attempts to extrapolate off the end of the list, we append a 1 to the input list.

Note this isn't the intended use for the sequence operator ..., which is usually used to create sequences based off several parameters. We're using the behaviour that the end condition is checked against the starting elements as well, and will stop even before any new elements are generated.

Explanation:

{            }  # Anonymous code block
 |$_,1          # Using the input list appended with 1
      ...       # Take up to
          *%2   # The element that is odd
         ^      # And exclude the last element

Jo King

Posted 2016-07-05T18:36:31.717

Reputation: 38 234

:P i think a lot of people know about the trick – ASCII-only – 2019-04-04T23:28:59.527

@ASCII-only Really? I haven't seen it before in the wild, if you could point me to any solutions that use ... to filter a list like this, I'd be very interested to see them – Jo King – 2019-04-04T23:31:30.340

it's not really filtering though, i thought it's just the conventional use of creating a range until a predicate is satisfied? – ASCII-only – 2019-04-04T23:33:46.783

well, the other conventional use – ASCII-only – 2019-04-04T23:35:15.473

i mean, i guess the "checked against the starting elements" usually isn't taken advantage of – ASCII-only – 2019-04-05T09:57:08.317

1

K, 12 bytes

{x@&~|\2!'x}

Explanation

{           } Function definition.
         'x   For each item in the input list...
       2!     Modulo it with 2 (e.g. 1%2, 5%2, 2%2, etc.) to get a list of booleans.
     |\       Fold | over the list to figure out where the odd numbers begin.
    ~         Flip the values it to get the beginning even numbers (until they turn odd).
   &          Get the indices.
 x@           Index the original list.

kirbyfan64sos

Posted 2016-07-05T18:36:31.717

Reputation: 8 730

1

Python 2, 59 57 56 bytes

def f(L,E=[]):
 while L and~L[0]%2:E+=L.pop(0),
 print E

Try it online

If printing rather than returning a list is allowed, 44 bytes:

L=input()
while L and~L[0]%2:print L.pop(0)

And shorter by xnor, 34 bytes, exits with an error on encountering an odd number:

for x in input():
    0>>x%-2;print x

mbomb007

Posted 2016-07-05T18:36:31.717

Reputation: 21 944

If you replace E=[] with *E, [L.pop(0)] with L.pop(0), and add parens to print, you can get 55 bytes with Python 3.5. – Dennis – 2016-07-05T20:24:18.440

Nevermind. That returns tuples, which wouldn't work as input. – Dennis – 2016-07-05T20:29:04.263

Actually, += allows extending lists with tuples for some reason, so E+=L.pop(0), still works. – Dennis – 2016-07-05T21:05:05.013

With printing output, you can do much shorter with terminating with error: for x in input():0>>x%-2;print x – xnor – 2016-07-06T02:21:29.540

@Dennis And *E creates a tuple, so E+=L.pop(0), is extending a tuple, not a list. – mbomb007 – 2016-07-06T14:02:22.087

@xnor I had to add a newline or it wouldn't compile (the printing one) – mbomb007 – 2016-07-06T14:13:14.187

1

JavaScript, 40 bytes

a=>[...a,1].slice(0,a.findIndex(n=>n%2))

How it works

1) Take input array a and add a 1 to the end

2) Find the index of the first odd integer in the array

3) Return a subset of the array from index 0 (inclusive) to the odd integer's index (exclusive)

jrich

Posted 2016-07-05T18:36:31.717

Reputation: 3 898

1

Minkolang 0.15, 12 bytes

nd2%,5&xr$N.

Try it here!

Explanation

nd              Take number from input and duplicate
  2%            Modulo 2
    ,           Logical NOT
     5&         Pop top of stack and jump 5 spaces if truthy
       x        Dump top element
        r       Reverse stack
         $N.    Output whole stack as numbers and stop.

Minkolang's codebox is toroidal, so if the instruction pointer does not stop, then it loops around to the beginning again. Trying to take a number after all input has been exhausted pushes -1, which is very conveniently odd.

El'endia Starman

Posted 2016-07-05T18:36:31.717

Reputation: 14 504

1

Python, 43 bytes

lambda l:[x for x in l if l.__imul__(~x%2)]

Calling l.__imul__(n) does l*=n. For n=~x%2, it empties the list when x is even and otherwise leaves it unchanged. The list comprehension iterates and collect elements until it hits an odd number, which stops the iteration by emptying the list. Moreover, because it outputs the now-empty list, the if fails and the current odd value is not included.

xnor

Posted 2016-07-05T18:36:31.717

Reputation: 115 687

1

Lua, 67 Bytes

Simply iterate on each elements of the input using a repeat..until loop. The first iteration will use i=0, which isn't the first element of the input as Lua's tables are 1-indexed, resulting in r[0]=nil which won't do anything as r[0] is already nil.

function f(t)r={}i=0repeat r[i]=t[i]i=i+1until t[i]%2<1return r end

Katenkyo

Posted 2016-07-05T18:36:31.717

Reputation: 2 857

1

C, 73 69 63 60 54 45 42

This requires a NULL-terminated array of strings as input. It modifies the parameter by chopping the list down to only even entries.

f(char**v){for(;*v&&~atoi(*v++)&1;);*v=0;}

If printing is allowed (45 bytes, doesn't modify parameter):

f(char**v){for(;*v&&~atoi(*v)&1;puts(*v++));}

Here is the previous complete program version (63 bytes):

i;main(int c,char**v){for(;(++i<c)-(atoi(v[i])&1);puts(v[i]));}

Takes input as program arguments.

owacoder

Posted 2016-07-05T18:36:31.717

Reputation: 1 556

@cat - GCC complains when I don't have the int c,char**v. How do you get around that? – owacoder – 2016-07-06T20:03:40.520

Ehh, never mind, I can't get what I was after. Tips for golfing in C

– cat – 2016-07-06T20:26:08.230

1

Perl, 21 bytes

20 bytes code + 1 bytes command line (-p)

s/ ?\d*[13579]\b.*//

Usage example:

echo "20 4 6 5 3 4" | perl -pe "s/ ?\d*[13579]\b.*//"

Jarmex

Posted 2016-07-05T18:36:31.717

Reputation: 2 045

1

PowerShell 26 bytes

process{if($_%2){break}$_}

Explanation

process{if($_%2){break}$_}
process{                 } # runs the script block once per item in the passed parameter
        if($_%2){break}    # if odd, break out of process{}
                       $_  # implicit output

Testing (save as evenodd.ps1):

PS> 42,14,42,2324 | .\evenodd.ps1
42
14
42
2324
PS> 7,14,42 | .\evenodd.ps1
PS> 171480372,13,14,42 | .\evenodd.ps1
171480372

ThePoShWolf

Posted 2016-07-05T18:36:31.717

Reputation: 171

0

Tcl, 44 bytes

proc T L {lmap e $L {if $e%2 {break}
set e}}

Try it online!

Tcl, 64 bytes

proc T L {set M {}
lmap e $L {if $e%2 break
lappend M $e}
set M}

Try it online!

sergiol

Posted 2016-07-05T18:36:31.717

Reputation: 3 055

0

Funky, 44 bytes

t=>{z={}fori=0;(!t[i]&1)*i<#t;i++z[i]=t[i]z}

Try it online!

ATaco

Posted 2016-07-05T18:36:31.717

Reputation: 7 898

0

GNU sed, 20 bytes

s/[^ ]*[13579]\b.*//    

Try it online!

Input and output are space-separated numbers.

Alternate solution, 22 bytes (20 + -n)

s/[24680]$/&/p;t;q;:

Try it online! Uses newlines instead of spaces this time.

Justin Mariner

Posted 2016-07-05T18:36:31.717

Reputation: 4 746

0

tinylisp repl, 61 bytes

(load library)(d E(q((L)(i(i L(even?(h L))L)(c(h L)(E(t L)))(

Defines a function E (short for "take while Even"). Try it online!

Ungolfed

(load library)
(def takewhile-even
 (lambda (ls)
  (if
   (if ls (even? (head ls)) ls)
   (cons (head ls) (takewhile-even (tail ls)))
   nil))))

Recurse through the list, using cons to build the result list. If the list is empty or if even? returns false, return empty list.

Note #1: Your functional programming professor would not like this function. It's not tail-recursive, so it will hit the recursion limit for long lists. Tail-recursive version is 73 bytes:

(load library)(d E(q((L A)(i(i L(even?(h L))L)(E(t L)(c(h L)A))(reverse A

or ungolfed:

(load library)
(def takewhile-even
 (lambda (ls accum)
  (if
   (if ls (even? (head ls)) ls)
   (takewhile-even
    (tail ls)
    (cons (head ls) accum))
   (reverse accum))))

Note #2: The specification of "take while even" actually costs bytes in tinylisp: even? isn't built-in, so we have to load the library (which is expensive) or reimplement the function (which is worse). Generic takewhile with the predicate as a second argument is only 46 bytes:

(d T(q((L P)(i(i L(P(h L))L)(c(h L)(T(t L)P))(

or ungolfed:

(load library)
(def takewhile
 (lambda (ls predicate)
  (if
   (if ls (predicate (head ls)) ls)
   (takewhile (tail ls) predicate)
   nil)))

(I think I may have my next standard library function here...)

DLosc

Posted 2016-07-05T18:36:31.717

Reputation: 21 213

0

Java 8, 79 71 bytes

l->{int i=0;for(int n:l){if(n%2>0)return l.subList(0,i);i++;}return l;}

Explanation:

Try it here.

l->{             // Method with ArrayList<Integer> as parameter and List as return-type
  int i=0;       //  Index-integer
  for(int n:l){  //  Loop over the input-List
    if(n%2>0)    //   If the current item is odd:
      return l.subList(0,i);
                 //    Return a sub-List from 0 through index `i` (exclusive)
    i++;         //   At the end of every iteration: increase index `i` by 1
  }              //  End of loop
  return l;      //  If the input-List was empty or contained no odd values, return itself
}                // End of method

Kevin Cruijssen

Posted 2016-07-05T18:36:31.717

Reputation: 67 575

0

Common Lisp, 44 bytes

 (loop as x in(read)while(evenp x)collect x)

Try it online!

Renzo

Posted 2016-07-05T18:36:31.717

Reputation: 2 260

0

Perl 5, 18 + 1 (for a) = 19 bytes

Uses -aE instead of -ae.

$_%2?die:say for@F

msh210

Posted 2016-07-05T18:36:31.717

Reputation: 3 094

0

Stax, 9 bytes

{O{|e*cf}

This is a block (equivalent to a function) that takes a list and returns a list on the top of the stack. The link below attaches some footers to output the list.

Run and debug online!

Explanation

{O{|e*cf}
{       }    Define a block
 O           Put 1 under top of stack, used as an accumulator
  {    f     Filter array with accumulator
   |e        True if array element is even, false if odd
     *c      `And` with accumulator

Weijun Zhou

Posted 2016-07-05T18:36:31.717

Reputation: 3 396

Does packing not save any bytes? – caird coinheringaahing – 2018-03-11T11:18:13.053

Packed content cannot be directly copied to a program as a block that can be called. – Weijun Zhou – 2018-03-11T11:41:26.463

0

Add++, 14 bytes

L*,bU1€+2↑%1€_

Try it online!

How it works

L*,		; Declare 'lambda 1' that returns the stack
		; Example argument:		[[12 14 16 17 18 20]]
	bU	; Unpack;		STACK = [12 14 16 17 18 20]
	1€+	; Increment each;	STACK = [13 15 17 18 19 21]
	2↑%	; Takewhile odd;	STACK = [13 15 17]
	1€_	; Decrement each;	STACK = [12 14 16]

caird coinheringaahing

Posted 2016-07-05T18:36:31.717

Reputation: 13 702

2Why the downvote? Is there anything wrong with this answer? – caird coinheringaahing – 2018-03-11T17:51:27.393

1I don't see anything wrong with it, so I've upvoted to neutralize the unexplained downvote. – Kevin Cruijssen – 2018-03-12T15:59:43.980

0

Javascript (ES2015) , 42 Bytes

I wasn't sure if the expected implementation was of the actual higher order function or the special case of getting a list of all even numbers, so i did both. Byte count is for longest of the two (higher order)

Even numbers (39 bytes)

l=>(o=[],l.every(v=>~v%2&&o.push(v)),o)

Higher order function:

f=>l=>(o=[],l.every(v=>f(v)&&o.push(v)),o)

higher order function called using curry style syntax

f(predicate)(list) => list

Sebastián Mestre

Posted 2016-07-05T18:36:31.717

Reputation: 101

0

Husk, 3 bytes

↑¦2

Try it online!

After my adventures with using drop-while to set a default input value with Husk's type inference system, I jumped at the opportunity to use take-while for something normal.

↑      The largest prefix of
       the input
 ¦     in which each element is divisible by
  2    two.

Unrelated String

Posted 2016-07-05T18:36:31.717

Reputation: 5 300

0

Java (JDK), 58 bytes

a->a.stream().mapToInt(i->i).takeWhile(i->i%2<1).toArray()

Try it online!

Takes a List<Integer> and outputs an int[].

Sara J

Posted 2016-07-05T18:36:31.717

Reputation: 2 576

0

Python, 55

t=lambda A,i=0:i<len(A)and~A[i]%2and[A[i]]+t(A,i+1)or[]

The following one is a generator, so it doesn't return a list, 49 bytes:

def t(A):
 for a in A:
  if a%2:break
  else:yield a

# usage: list(t([2, 3, 4]))

shooqie

Posted 2016-07-05T18:36:31.717

Reputation: 5 032

"The output should be a list" – mbomb007 – 2016-07-05T19:49:13.923

@mbomb007: thanks for reformating, looks better now – shooqie – 2016-07-05T19:51:46.783

0

Perl, 29 + 1 (for -p) = 30 bytes

s/(\d+)/($1)[$o or$o=$1%2]/eg

Use like perl -p myfile.pl, where myfile.pl contains the above code, or just perl -pn 's/(\d+)/($1)[$o or$o=$1%2]/eg'. Takes input from standard input.

kirbyfan64sos

Posted 2016-07-05T18:36:31.717

Reputation: 8 730

s/-pn/-pe/. Also, I haven't tested, but I imagine you can omit the parens from the first argument to s and use $& instead of $1. – msh210 – 2016-07-07T22:40:23.017

0

JavaScript, 29 bytes

a=>a.filter(e=>!(s|=e%2),s=0)

or

a=>a.filter(e=>s&=!(e%2),s=1)

How it works (1st version)

1) Take input array a and return the result of calling filter on it. This will keep every element for which the function we pass into filter returns a truthy value.

2) Abuse the second parameter to filter (normally used to set the this value to the function, but we don't use this in the program) to initialize s to 0.

3) For the filter function, set s to s | (e % 2), which will evaluate s to 0 iff s was 0 before and the element e is even. So, s will be 0 up until the first odd value, after which it will never be 0 again. Then simply return the negation of s, keeping the first run of even values (!0 === true) and discarding the rest.

jrich

Posted 2016-07-05T18:36:31.717

Reputation: 3 898

0

Julia, 24 bytes

!x=1∈x%2?!x[1:end-1]:x

Try it online!

Dennis

Posted 2016-07-05T18:36:31.717

Reputation: 196 637

0

TSQL 67 bytes

DECLARE @ table(i INT identity, n INT)
INSERT @ values(14),(42),(2324),(97090),(4080622),(1),(171480372)

SELECT n FROM(SELECT n,sum(n%2)over(order by i)z FROM @)x WHERE z=0

Fiddle

t-clausen.dk

Posted 2016-07-05T18:36:31.717

Reputation: 2 874

0

Factor, 55 bytes

[ dup [ odd? ] find drop over length over swap ? head ]

Using the following substitution regexes, the test cases from the question can be turned into a Factor test suite.

s/\[((?:\d*(?: )?)*)\]\s+->\s+\[((?:\d*(?: )?)*)\]/{ { $2 } } [ { $1 } take-while-even ] unit-test/g
s/,//g

takewhile-even.factor

USING: kernel math sequences ;
IN: takewhile-even

: take-while-even ( seq -- newseq )
  dup [ odd? ] find drop over length over swap ? head ;

takewhile-even-tests.factor

USING: tools.test takewhile-even ;
IN: takewhile-even.tests

{ { 14 42 2324 97090 4080622 171480372 } } [ { 14 42 2324 97090 4080622 171480372 } take-while-even ] unit-test
{ { 42 14 42 2324 } } [ { 42 14 42 2324 } take-while-even ] unit-test
{ {  } } [ { 7 14 42 } take-while-even ] unit-test
{ {  } } [ {  } take-while-even ] unit-test
{ { 171480372 } } [ { 171480372 13 14 42 } take-while-even ] unit-test
{ { 42 14 42 } } [ { 42 14 42 43 41 4080622 171480372 } take-while-even ] unit-test

Run them with "takewhile-even" test.

cat

Posted 2016-07-05T18:36:31.717

Reputation: 4 989

0

Perl 5.10, 36 bytes

Different way of doing it when compared to the other Perl answers which are based on regexes. 35 bytes + 1 byte for -a flag.

for(@F){$_%2?last:push@a,$_}say"@a"

Try it here!

Paul Picard

Posted 2016-07-05T18:36:31.717

Reputation: 863

0

Java, 98 bytes

int[]f(int[]t){int i=0;for(;i<t.length&&t[i]%2<1;i++);return java.util.Arrays.copyOfRange(t,0,i);}

Ideone it!

Leaky Nun

Posted 2016-07-05T18:36:31.717

Reputation: 45 011

0

PHP, 57 55 bytes

function f($i){foreach($i as $n){if($n&1)die;echo $n;}}

Ungolfed:

function f($i){
    foreach($i as $n){
        if($n & 1) die;
        echo $n;
    }
}

The function takes an array $i as an input parameter.

$n & 1 will return 1 if $n is odd and 0 is $n is even.

Business Cat

Posted 2016-07-05T18:36:31.717

Reputation: 8 927

0

Python 3, 72 bytes

It's a bit of a boring answer, but itertools has a function for this...

from itertools import*
lambda x:[i for i in takewhile(lambda y:y%2+1,x)]

An anonymous function that takes input of the list x via argument and returns a list.

Try it on Ideone

TheBikingViking

Posted 2016-07-05T18:36:31.717

Reputation: 3 674

0

><>, 70 bytes

Takes input as any number of decimal integers separated by a single character (anything but a digit), and prints out the list newline-separated.

v;oan;?<
0!2&::&\%
&>i:0(?^'0'-::0($9)+?v&a*+&!
>^   oan&0~&;?%2&::&~<

Try it online!

owacoder

Posted 2016-07-05T18:36:31.717

Reputation: 1 556

0

Javascript (using external library - Enumerable) (42 bytes)

n=>_.From(n).TakeWhile(y=>y%2<1).ToArray()

Code explanation: Library built in implementation...

enter image description here

applejacks01

Posted 2016-07-05T18:36:31.717

Reputation: 989