| Bytes | Lang | Time | Link |
|---|---|---|---|
| 096 | Type | 250828T154500Z | General |
| 003 | Vyxal 3 | 250827T080819Z | Themooni |
| 006 | tinylisp 2 | 230111T002009Z | DLosc |
| 9110 | Perl 5 p | 231106T172818Z | Xcali |
| 002 | Japt g | 230111T092857Z | Shaggy |
| 043 | C GCC | 231105T161325Z | Kamila S |
| 022 | Julia 0.6 | 231104T162749Z | MarcMush |
| 024 | Julia 0.6 | 160706T035941Z | Dennis |
| 007 | K ngn/k | 231104T131607Z | coltim |
| 007 | Uiua | 231104T114429Z | chunes |
| 005 | Nekomata | 230916T003422Z | alephalp |
| 005 | Thunno 2 | 230608T134856Z | The Thon |
| 024 | ReRegex | 230220T040711Z | ATaco |
| 025 | Rust | 230220T022750Z | user1169 |
| 020 | Arturo | 221109T193206Z | chunes |
| 016 | Ly | 230117T075510Z | cnamejj |
| 023 | PARI/GP | 230111T070557Z | alephalp |
| nan | 230110T194457Z | The Thon | |
| nan | 221105T235620Z | bigyihsu | |
| 087 | Nim | 221111T024506Z | Qaziquza |
| nan | Fig | 221109T214110Z | Seggan |
| 020 | jq | 221108T032253Z | pmf |
| 012 | ARM Thumb2 machine code | 221105T223635Z | EasyasPi |
| 059 | Prolog SWI | 221106T010405Z | hakr14 |
| 018 | Juby | 221012T031003Z | Jordan |
| 025 | Ruby | 221012T030709Z | Jordan |
| 024 | Factor | 221012T023422Z | chunes |
| 007 | Vyxal | 221012T022603Z | DialFros |
| 058 | Java JDK | 190405T005037Z | Sara J |
| 014 | Perl 6 | 190404T232506Z | Jo King |
| 003 | Husk | 190404T224958Z | Unrelate |
| 042 | Javascript ES2015 | 180312T053455Z | Sebasti& |
| 014 | Add++ | 180311T125342Z | caird co |
| 009 | Stax | 180311T012518Z | Weijun Z |
| nan | Perl 5 | 180310T233454Z | msh210 |
| 030 | JavaScript Firefox 3057 | 160705T212012Z | Neil |
| 044 | Common Lisp | 171108T080823Z | Renzo |
| 071 | Java 8 | 171108T075953Z | Kevin Cr |
| 061 | tinylisp repl | 171108T054017Z | DLosc |
| 020 | GNU sed | 171108T034233Z | Justin M |
| 044 | Funky | 171107T033218Z | ATaco |
| 044 | Tcl | 171106T225634Z | sergiol |
| 042 | Javascript using external library Enumerable | 160810T153848Z | applejac |
| 070 | ><> | 160809T211227Z | owacoder |
| 044 | SML | 160722T165634Z | Laikoni |
| 072 | Python 3 | 160717T221111Z | TheBikin |
| 025 | JavaScript | 160707T174122Z | apsiller |
| 263 | Brainf*** | 160708T203039Z | anOKsqui |
| 173 | Perl 5 + Perligata | 160708T154327Z | msh210 |
| 026 | PowerShell | 160708T164754Z | ThePoShW |
| 006 | MATL | 160705T184632Z | Luis Men |
| 055 | PHP | 160707T140055Z | Business |
| 019 | Hexagony | 160705T212703Z | FryAmThe |
| 042 | C | 160706T154706Z | owacoder |
| 017 | Retina | 160705T190539Z | Martin E |
| 098 | Java | 160707T105908Z | Leaky Nu |
| 059 | Python 3 | 160705T192957Z | TuxCraft |
| 021 | Perl | 160706T165554Z | Jarmex |
| 014 | 32bit x86 machine code | 160707T075657Z | meden |
| 036 | Perl 5.10 | 160707T072855Z | Sake |
| 011 | CJam | 160705T210213Z | Luis Men |
| 055 | Factor | 160706T203203Z | cat |
| 035 | Befunge | 160706T122217Z | Maliafo |
| 114 | Forth | 160705T205720Z | mbomb007 |
| 056 | Python 2 | 160705T192933Z | mbomb007 |
| 011 | GolfScript | 160705T232028Z | Ilmari K |
| 050 | C# | 160706T105528Z | ScifiDea |
| 067 | TSQL | 160706T103823Z | t-clause |
| 014 | Labyrinth | 160705T191911Z | Martin E |
| 067 | Lua | 160706T075106Z | Katenkyo |
| 007 | 05AB1E | 160705T190142Z | Emigna |
| 041 | Python | 160706T033938Z | xnor |
| 043 | Python | 160706T032445Z | xnor |
| 013 | ed | 160706T012552Z | Doorknob |
| 029 | JavaScript | 160706T004019Z | jrich |
| 040 | JavaScript | 160705T194020Z | jrich |
| 012 | Minkolang 0.15 | 160706T004754Z | El'e |
| 042 | Python 2 | 160705T211824Z | Dennis |
| 007 | Pyth | 160705T185512Z | busukxua |
| 013 | Haskell | 160705T191809Z | nimi |
| 022 | Racket | 160705T204427Z | Steven H |
| nan | Perl | 160705T200641Z | kirbyfan |
| 044 | Python | 160705T195033Z | Dennis |
| 025 | R | 160705T195642Z | pajonk |
| 055 | Python | 160705T194806Z | shooqie |
| 010 | J | 160705T194857Z | miles |
| 008 | Pyke | 160705T190600Z | Blue |
| 012 | K | 160705T192635Z | kirbyfan |
| 005 | Jelly | 160705T191346Z | Dennis |
| 025 | Ruby | 160705T190907Z | MegaTom |
| 016 | Brachylog | 160705T185915Z | Fatalize |
| 011 | Dyalog APL | 160705T191144Z | Adá |
| 007 | Pyth | 160705T191028Z | Blue |
| 021 | Clojure | 160705T190852Z | cliffroo |
| 013 | V | 160705T185953Z | DJMcMayh |
| 018 | Mathematica | 160705T185749Z | Martin E |
TypeScript (TS Type System), 100 96
type W<T,B=[]>=T extends[infer H,...infer R]?`${H}`extends`${any}${2|4|6|8|0}`?W<R,[...B,H]>:B:B
Input is standard decimal numbers. I wasn't sure if inlining the predicate was allowed based on others' submissions. In case that matters, the even-check can be easily extracted into its own type: type M=${H}`extends`${infer S}${2|4|6|8|0}?1:0.
Since basic arithmetic is really difficult in TS, we have to take whatever exploits we can get. In this case, it's the fact that all even numbers end with [24680].
Type safe version:
type W2<T extends number[],B extends any[]=[]>=
T extends [infer H, ...infer R]
? (H extends number ?
(`${H}` extends `${any}${2 | 4 | 6 | 8 | 0}`
? W<R, [...B, H]>
: B)
: never)
: B;
Vyxal 3, 3 bytes
⑴e⊖
⑴e⊖
⑴ # next element as lambda:
e # is-even?
⊖ # take from implicit input while function is true
💎
Created with the help of Luminespire.
<script type="vyxal3">
⑴e⊖
</script>
<script>
args=[["[14, 42, 2324, 97090, 4080622, 171480372]"],["[42, 14, 42, 2324]"],["[7,14,42]"],["[]"],["[171480372, 13, 14, 42]"],["[42, 14, 42, 43, 41, 4080622, 171480372]"]]
</script>
<script src="https://themoonisacheese.github.io/snippeterpreter/snippet.js" type="module"/>
tinylisp 2, 6 bytes
(p ] e
Explanation
Uses (abbreviated aliases for) the library functions take-while and even?:
(p ] e)
(p ) ; Partially apply
] ; the take-while function
e ; to the even? function
Without using the library's take-while function, I found a rather elegant solution using foldr which is 26 bytes:
(p {(\(N A)(?(e N)(c N A)(
That is, partially apply the { (foldr) function to the following argument:
(\(N A)(?(e N)(c N A)()))
(\ ) ; Lambda function
(N A) ; that takes a number N and a list A:
(? ) ; If
(e N) ; N is even
(c N A) ; cons N to A
() ; Else return empty list
So we end up with a function that takes a list and right-folds it on the above function, with a default starting accumulator value of nil (empty list). This starts from the right end of the list, collecting values as long as they are even, but whenever it encounters an odd value it discards all previous values and starts over.
Perl 5 -p, 9+1 = 10 bytes
(Scored under the system in place at the time of the question.)
$_%2&&die
Input and output both have the entries line separated.
C (GCC), 43 bytes
i;f(a,n)int*a;{for(;i<n&&~a[i]%2;i++);a=i;}
I/O format: Takes a list and its length, returns the length to which the input list needs chopped. Tricks: ~a[i]%2 checks if a[i] is even, a=i; loads i to rax with -O0, hence avoiding a return. Also uses K&R function declaration and implicit int.
Julia 0.6, 22 bytes
!x=x[cumprod(@.x%2<1)]
also works in julia 1.x
there is Iterators.takewhile but it is way too long
K (ngn/k), 7 bytes
(|\2!)_
(...)_set up a weed-out; drop elements from the (implicit) right argument where the code in(...)returns a positive integer (for each item of the input)|\2!do a max-scan on the input mod'ed by 2
Uiua, 7 bytes
▽\׬◿2.
▽\׬◿2.
. # duplicate
◿2 # modulo two
¬ # not
\× # scan by multiplication
▽ # keep input elements indicated by mask
Nekomata, 5 bytes
Ö∫¬∑T
Ö∫¬∑T
Ö Modulo 2
∫ Cumulative sum
¬ Logical NOT
∑ Sum
T Take; get the prefix with the given length
Nekomata, 5 bytes
pᵖ½al
pᵖ½al
p Non-deterministically choose a prefix
ᵖ½ Check that all elements are even
al Get the last possible value
Thunno 2, 5 bytes
(ɗS;ṫ
Explanation
(ɗS;ṫ # Implicit input
( ; # while loop
ɗS # (condition) at least one odd number in the list
ṫ # (body) remove the last item
# Implicit output
ReRegex, 24 bytes
,?\d*[13579]\b.*//#input
Takes input as a line of comma deliminated Integers. Matches any odd number, and replaces it and the rest of the line with nothing.
Rust, 25 bytes
|x|x.take_while(|x|x%2<1)
Ly, 16 bytes
&nr[:2%[;]pu9`o]
Pretty brute force, but it's relatively short too. :)
&nr - Read in list of numbers, reverse stack
[ ] - Loop until the stack is empty
:2% - Dup next number, compute 1|0 if odd/even
[;] - If odd, exit the program
p - Delete if/then boolean
u - Print the number, since it's even
9`o - Push 10 (LF) and print as character
Thunno X, \$ 11 \log_{256}(96) \approx \$ 9.05 bytes
lX{D2%)xsTX
Explanation
lX{D2%)xsTX # Implicit input
lX # Store [] in x
{ # Loop through the input list:
D # Duplicate
2%) # If it's odd, break
xsT # Otherwise, append to x
X # And store the result in x
# The X flag pushes x at the end
# Implicit output
Screenshot
Go, 78 64 bytes
func(s[]int,c func(int)){for _,x:=range s{if x%2>0{break}
c(x)}}
- -14 bytes by @Steffan
Go, generic with predicate, 96 bytes
func f[T any](s[]T,b func(T)bool)(o[]T){for i:=0;i<len(s)&&b(s[i]);i++{o=append(o,s[i])}
return}
Nim, 87 bytes
proc t(a:seq[int]):seq[int]=
var i=0;while i<a.len and a[i]mod 2==0:inc i
a[0..i-1]
Fig, \$3\log_{256}(96)\approx\$ 2.469 bytes
t@E
Builtin. Can't have a functional language without one.
t@E
t@ # Take while
E # Even
jq, 20 bytes
.[:map(.%2)[[1]][0]]
Explanation:
map(.%2) Maps the array items to their remainders when divided by 2
[[1]] Returns an array of indices where those items equal 1 (odds)
[0] Returns the first item of that array of indices
.[: ] Returns the original array up until that index
ARM Thumb-2 machine code, 12 bytes
00000000: 04 c8 52 ea c2 72 04 c1 fa d5 70 47 ..R..r....pG
Assembly:
.syntax unified
.arch armv7-a
.thumb
.globl takewhile
.thumb_func
// input: int *, r0
// output: int *, r1
// lists are terminated with a negative number
takewhile:
.Lloop:
// Load number into r2, increment r0
ldmia r0!, {r2}
// 1. shift the LSB of r0 into the MSB
// 2. Logical OR
// 3. Set flags on the result
// On either a terminator or an odd number, the MSB
// will be set, which sets the N flag. Additionally,
// this will terminate the list when stored.
// r2 = r2 | (r2 << 31);
// NF = r2 & 0x80000000;
orrs.w r2, r2, r2, lsl #31
// Store r2 into r1, increment r1
stmia r1!, {r2}
// Loop if MSB was not set (N flag not set)
bpl .Lloop
// Return
bx lr
This function requires and outputs an array of positive int32_ts terminated with any negative int32_t. It follows standard C calling convention:
#include <stdint.h>
#include <stdio.h>
void takewhile(const int32_t *input /* r0 */, int32_t *output /* r1 */);
int main(void)
{
const int32_t input[5] = { 171480372, 13, 14, 42, -1 };
int32_t output[5];
takewhile(input, output);
for (int i = 0; output[i] >= 0; i++) {
printf("%d, ", output[i]);
}
putchar('\n');
}
This takes advantage of the "numbers are positive" condition, and how ARM lets me set the condition codes for free.
I repeatedly logical OR the lowest bit of the values with the highest bit, and test the result. If the result is negative, one of the following is true:
- The end of the list was reached (the upper bit was already set)
- The number was odd (the lowest bit was set, which when shifted sets the upper bit).
With the example above, the outputted values will be this:
{ 171480372, /* -2147483635 */ 13 | 0x80000000 }
Vyxal, 7 bytes
⁽₂Ḋ¾wJh
Explained
⁽₂Ḋ¾wJh
⁽ # 1-element lambda
₂ # check if even
Ḋ # group if true
¾wJ # add empty list to end
h # get head of the list
Java (JDK), 58 bytes
a->a.stream().mapToInt(i->i).takeWhile(i->i%2<1).toArray()
Takes a List<Integer> and outputs an int[].
Perl 6, 14 bytes
{|$_,1...^*%2}
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
Husk, 3 bytes
↑¦2
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.
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
Add++, 14 bytes
L*,bU1€+2↑%1€_
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]
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.
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
Perl 5, 18 + 1 (for a) = 19 bytes
Uses -aE instead of -ae.
$_%2?die:say for@F
JavaScript (Firefox 30-57), 30 bytes
a=>[for(x of a)if(!(a|=x&1))x]
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:
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
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...)
GNU sed, 20 bytes
s/[^ ]*[13579]\b.*//
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.
Tcl, 44 bytes
proc T L {lmap e $L {if $e%2 {break}
set e}}
Tcl, 64 bytes
proc T L {set M {}
lmap e $L {if $e%2 break
lappend M $e}
set M}
Javascript (using external library - Enumerable) (42 bytes)
n=>_.From(n).TakeWhile(y=>y%2<1).ToArray()
Code explanation: Library built in implementation...
><>, 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&::&~<
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[])[]
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.
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.
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)
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 ofsi 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,)
scindedoesn't need a second argument, and useshoc. Alas,exineeds 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 givesThis 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..
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
MATL, 6 bytes
toYs~)
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
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.
Hexagony, 19
2.}<@>%?<{>$"/\M!8;
Readable:
2 . }
< @ > %
? < { > $
" / \ M
! 8 ;
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 (/"%>).
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.
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.
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.
Retina, 17 bytes
?\d*[13579]\b.*
The trailing linefeed is significant. Input and output are space-separated lists.
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.*
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);}
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
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.*//"
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
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"
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.
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
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.
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:
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
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 ;
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
Python 2, 59 57 56 bytes
def f(L,E=[]):
while L and~L[0]%2:E+=L.pop(0),
print E
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
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.
C#, 50 bytes
int[]f(int[]a)=>(a.TakeWhile(x=>x%2<1).ToArray());
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
Labyrinth, 14 bytes
?:
"`#
"@%
\!;
Input and output are linefeed-separated lists (although in principle, the input could use any non-digit separator).
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 % 2is0(as opposed to1), which means instead of conditional control flow we can simply divide the other copyNbyN % 2: if the input is odd, that just leavesNand we even got rid of theN % 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.
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
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
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
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.
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.
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.
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.
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)
Minkolang 0.15, 12 bytes
nd2%,5&xr$N.
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.
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.
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
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.
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!
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.
R, 25 bytes
x=scan()
x[!cumsum(x%%2)]
Or equivalently
(y=scan())[!cumsum(y%%2)]
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]))
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
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@<
2L% - map(%2, input)
1R@ - ^.index(1)
< - input[:^]
Or after 2nd bugfix, 6 bytes
2L%fhO
Explanation:
2L% - map(%2, input)
f - split_at(input, ^)
hO - ^[0][:-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.
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.
Ruby, 25 bytes
->a{a.take_while &:even?}
I think I lose...
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]".
Dyalog APL, 11 bytes
{⍵/⍨∧\~2|⍵}
2| division remainder from dividing with 2
~ negate
∧\ AND-scan (turns off from first 0)
/⍨ select where
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
V, 13 bytes
íä*[13579]¾.*
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.
Mathematica, 18 bytes
#~TakeWhile~EvenQ&
Another glorious built-in that is beaten by a factor of 3 by golfing languages without the built-in...



