实施接单


30

介绍和信誉

今天没有花哨的前奏:请实施takewhile

这种变化(在非平凡的数据结构上)是我大学功能编程课程中的一项作业。这项作业现在已经关闭,并且已经在课堂上进行了讨论,我已经得到了我教授的允许在这里发布(我明确要求过)。

规格

输入值

输入将是一个正整数列表(或您的语言的等效概念)。

输出量

输出应为正整数列表(或您的语言的等效概念)。

该怎么办?

您的任务是使用要takewhile考虑的数字为偶数的谓词来实现(允许使用语言内置函数)(着重于获取时间)。

因此,您从头到尾遍历列表,并且在条件(为偶数)成立的情况下,将其复制到输出列表,并在遇到不符合条件的元素时立即中止操作并输出(下面是一个分步示例)。这种高阶功能也称为takeWhile(takewhile)。

潜在的极端情况

与输入列表相比,输出列表的顺序可能不会更改,例如[14,42,2]可能不会变为[42,14]

空列表是有效的输入和输出。

谁赢?

这是代码高尔夫球,因此最短的答案以字节为单位!

标准规则当然适用。

测试向量

[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]

分步示例

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]

2
如果返回迭代器而不是列表,可以吗?
DJMcMayhem

2
@DrGreenEg​​gsandIronMan我猜您的函数必须能够将其输出作为输入,保证它们的格式相同。
mbomb007 '16

@DrGreenEg​​gsandIronMan,我不认为返回子列表应该在此处以输出格式使用。(但是,如果您在代码中利用它,则仍然取决于您)。Mbomb的标准看起来最合适并且与当前挑战兼容,因此它将是“您的输出至少应该是有效输入”。
SEJPM'7

Answers:


28

Mathematica,18个字节

#~TakeWhile~EvenQ&

另一种出色的内置功能,在没有内置功能的情况下,被高尔夫语言打败了三倍。


3
Mathematica有多少个内置插件?似乎几乎所有东西都有它。
Emigna '16

35
@Emigna我还没有数过,但是互联网上的规则#110是:“如果存在,则内置Mathematica。”
Martin Ender

3
@MartinEnder互联网规则110.5太糟糕了,“如果它以任何方式涉及字符串,那么就规则110而言,它不存在。”
LegionMammal978 '16

@ LegionMammal978解决方法是使字符串成为表达式的
开头

26

Haskell,13个字节

fst.span even

span在谓词(-> even)为false 的第一个元素之前,将输入列表拆分为一对列表。fst接受一对中的第一个元素。

备用版本,13字节:

fst.break odd

break是与的相反span,即它在谓词为true的第一个元素处拆分列表。

当然也有

takeWhile even

但这是14个字节。


23

MATL,6个字节

toYs~)

在线尝试!

说明

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

22
代码在那儿微笑着说“玩具”是正常的吗?
SEJPM '16

3
@SEJPM to~Y<)也可以,但是我更喜欢这个:-)
Luis Mendo

13

六角形,19

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

可读性:

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

在线尝试!

可能需要打一两个字节,但这可能需要一些真正巧妙的布局,通过蛮力可以更容易找到它(即使找到它可能需要很长时间)。

高层次的解释

该程序主要遵循以下伪代码:

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

一旦STDIN为空(返回零),这会滥用Hexagony尝试读取数字的方式。非常感谢Martin为提出这种方法所提供的帮助。

完整说明

我仍然没有弄乱Mono来使Timwi的神奇而深奥的IDE运行,所以我选择Martin来为我提供一些有用的漂亮图片!

首先,简要介绍六角形中的基本控制流程。该程序中唯一使用的第一个指令指针(IP)从六角形源代码的左上方开始,然后开始向右移动。每当IP离开六边形的边缘时,它就会将side_length - 1行移向六边形的中间。由于此程序使用边长为三边形的六边形,因此发生这种情况时,IP始终将移动两行。唯一的例外是,如果它移出中间行,则有条件地移到六边形的顶部或底部,具体取决于当前内存边的值。

现在介绍一下条件句。六边形中用于控制流的唯一条件是><以及六边形的中间边缘。所有这些都遵循一个不变的规则:如果当前存储边上的值是零或负控制流向左移动,而如果是正则控制流向右移动。大于和小于括号以60度角重定向IP,而六边形的边缘控制IP跳转到哪一行。

六边形还具有特殊的内存模型,其中所有数据都存储在无限六边形网格的边缘。该程序仅使用三个边:一个用于存储两个,一个用于当前读取的数字,一个用于模2的数字。看起来像:

Mod  \ / Input
      |
      2

在解释程序的过程中,我不会在每个点上都仔细解释我们在内存中的位置,因此如果对我们在内存中的位置感到困惑,请回到此处。

有了所有这些,就可以开始实际的解释了。首先,我们用2填充内存中的“ 2”边,然后执行无操作并将内存指针移到右侧(2.})。

接下来,我们开始主程序循环。我们从STDIN中读取第一个数字,然后按条件(?<)。如果STDIN中没有剩余的数字@,则它将零读入当前的存储器边沿,因此我们左转到,结束程序。否则,我们将弹起一面镜子,向后和向左移动内存指针,环绕六边形以计算将输入除以2的余数,然后命中另一个条件(/"%>)。

Odd Path

如果余数是一个(即数字是奇数),则我们通过再次执行no-op从上面的蓝色路径右转,然后环绕到六边形的底部,将当前边乘以10,然后加八,跳出一对镜像,再次执行相同的乘法和加法运算,在当前边上获得188,绕回六边形的顶部,再次执行无操作,最后结束程序(.8/\8.@)。这个令人费解的结果是一个不幸的事故,我本来编写的逻辑要简单得多,但是注意到我可以删除它以支持no-op,我认为这更符合Hexagony的精神。

Even Path

如果余数为零,我们将按照上面的红色路径向左转。这使我们将内存指针移到左侧,然后在此处将值(输入值)打印为数字。由于我们移动的方向({/!),我们遇到的镜子充当无操作镜。然后,我们碰到六角形的边缘,该边缘仅产生一个结果,因为之前的输入值已被测试为正,因此我们总是向右移动(如果您想自己正朝IP的方向发展) 。然后,我们将输入乘以10并加两个,只不过是改变方向,用大写字母M的ascii值环绕并覆盖新值77,然后打一些镜子,并在中间的边缘处退出带有蹦床的六角形(2<M\>$)。由于77为正,因此我们向六边形的底部右移,由于蹦床而跳过了第一条指令(!)。然后,将当前内存边沿乘以10,然后加8,得到778。然后,将这个值mod 256(10)作为ASCII字符输出,恰好是换行符。最后,我们退出六边形,然后返回到第一个六边形,?后者用下一个输入值覆盖778。


8
对,没错
泰兰

10

Pyth,13 9 7个字节

uPWs%R2

感谢2个字节(非常棘手)的@FryAmTheEggman!

说明:

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

在这里测试


1
这不是一个正确的变量介绍描述。应该G引入两个s,一个用于条件s%R2G,一个作为函数的参数P
isaacg

9

果冻,5 个字节

Ḃœp⁸Ḣ

在线尝试!要么验证所有测试用例

怎么运行的

Ḃœ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.


8

ed,13

/[13579]$/,$d

因为真正的程序员使用标准文本编辑器

将输入作为每一行的一个整数;以相同格式输出。

这只是找到第一个奇数(以奇数结尾的数字)并从该行删除直到文件末尾。


嗯。这就是该程序的用途。


6

Python,45 44字节

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

Ideone上进行测试


噢,伙计。而且,我以为我有机会赢得赏金
DJMcMayhem

1
只有在2015年7月22日之前发布的无限制的纯代码高尔夫球问题才有资格。
丹尼斯

@DrGreenEg​​gsandIronMan 我的矿井一直比你的短。我先发布了我的。:P
mbomb007 '16

2
丹尼斯,谁曾想过:) Outgolfed
shooqie

@ mbomb007可以肯定吗?
DJMcMayhem


5

05AB1E,8 7字节

[DÉO_#¨

说明

[        # 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

在线尝试

以前的8字节解决方案

vyÈiyˆëq

说明

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

在线尝试


5

Brainf ***,263个字节

我从这里拿了一个小片段

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

我会给出一个解释,但是即使我也不知道它是如何工作的。

期望输入为空格分隔的数字(例如2 432 1


趁高炉._。+1
TuxCrafting's

您可能可以打高尔夫,+>使用一些逻辑?
Rɪᴋᴇʀ

@EᴀsᴛᴇʀʟʏIʀᴋ已经有很多链条被打高尔夫球了(否则会有很多排32'+的行),我可能可以提高其中一些的>效率,但是我现在对它们的理解还不够
ansquisrelr

这就是为什么在记事本中编写代码时应注释掉代码的原因。:P
mbomb007 '16


4

球拍,22字节

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

λ character is counted as 2 bytes.

在看过的任何代码打高尔夫球的答案中,我都从未见过Racket,所以我至少要做一次!


2
我曾经在球拍打高尔夫球,为球拍欢呼!

4

迷宫,14字节

?:
"`#
"@%
\!;

输入和输出是换行符分隔的列表(尽管原则上,输入可以使用任何非数字分隔符)。

在线尝试!

这可能是我编写过的最紧凑的迷宫程序。

有趣的takewhile(odd)是,要简单得多:

?:#
" %
\!/

说明

普通的迷宫底漆:

  • 内存模型是一个堆栈(实际上有两个,但对于该程序,我们只需要一个),它可以存储任意精度的整数,并且初始时可以存储(隐式)无限个零。
  • 没有控制流指令。而是,指令指针(IP)的移动由代码的布局确定(空格被视为“墙”,并且IP不能遍历)。通常,该代码应该类似于迷宫,在该迷宫中IP沿着笔直的走廊和弯道,但是无论何时到达交界处,这都是根据当前状态确定IP新方向的条件。选择方向的规则归结为:如果栈顶为零,则IP继续前进;如果栈顶为零,则IP继续前进。如果顶部为正,则IP向右转;如果顶部为负,则IP左移。如果这些方向之一被墙阻挡,则IP采取相反的方向。这意味着程序没有畅通无阻的走廊通常很难使用,因为每个单独的命令都会充当枢纽。在这种情况下解决问题的事实有点奇迹。
  • IP从阅读顺序的第一个非空格字符开始(?在这种情况下),向东移动。

程序的主要流程是围绕周边的单个循环:

>v
^>v
^@v
^<<

碰巧的是,我们知道栈顶在之后为零!"因此可以保证IP不会偏向中心。`%在另一方面,使用如条件在IP可能会向中心,使得移动@终止程序,或者它可能保持移动在周边。

让我们看一下循环中的代码:

?   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.

然后循环开始。

这就提出了一个问题,为什么takewhile(odd)如此简单。有两个原因:

  • 由于EOF返回为0(偶数),因此我们不需要单独的EOF检查。无论如何,该清单将被删除。
  • 现在我们要终止N % 2is是0(而不是1),这意味着可以代替条件控制流,而只需将另一个副本N除以N % 2:如果输入为奇数,则只剩下一个,N而我们甚至摆脱了N % 2(所以)不需要;),但如果输入为偶数,则仅会以(无声)除零错误终止程序。

因此,其他代码是一个简单的循环,根本不允许任何分支。


3

Brachylog19 16字节

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

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

说明

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

今天,我学到了一个巧妙的技巧(在19个字节的答案中使用了该技巧):~b.hH:[H]rc.在列表的开头添加元素要短 。第一个表示“输出是在开头有一个额外项目的结果H,而输出的第一项是,而另一个则直接是“输出是”的串联[[H], Result]


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

1{.2&|<;._2] is interesting (although longer)
Leaky Nun

Use $ instead of {.
FrownyFrog

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.



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

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.*


You can take the list in binary?
Leaky Nun

3

JavaScript (Firefox 30-57), 30 bytes

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

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.


2

Dyalog APL, 11 bytes

{⍵/⍨∧\~2|⍵}

2| division remainder from dividing with 2

~ negate

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

/⍨ select where


2

Ruby, 25 bytes

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

I think I lose...


Can you do ->a{a.take_while &:even?} or at least ->a{a.take_while(&:even?)}?
Martin Ender

@MartinEnder Thank you. I was looking for something like that, but I guess I am not well versed in ruby golfing syntax.
MegaTom

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]

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.


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


5
After finishing this, I realized my breakfast was cold. :(
mbomb007

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

@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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.