答:
JavaScript, <s>66</s> <s>64</s> 61 chars

Heavily inspired by TwoScoopsofPig (PHP) and Joe Tuskan (JS).

<s>

for(a=[s=0];s!=72;)for(s=i=0;i<18;s+=a[i++]=Math.random()*3+3|0);a
```

<p></s>
<s></p>

<pre class="lang-js prettyprint-override"><code>for(a=[s=0];s-72;)for(s=i=0;i<18;s+=a[i++]=Math.random()*3+3|0)a
</code>```

</s>

for(a=s=[];s;)for(i=18,s=72;i;s-=a[--i]=Math.random()*3+3|0)a
```

Title: Can you Golf Golf?

Body:
JavaScript, <s>66</s> <s>64</s> 61 chars

Heavily inspired by TwoScoopsofPig (PHP) and Joe Tuskan (JS).

<s>

for(a=[s=0];s!=72;)for(s=i=0;i<18;s+=a[i++]=Math.random()*3+3|0);a

</s>
<s>

for(a=[s=0];s-72;)for(s=i=0;i<18;s+=a[i++]=Math.random()*3+3|0)a

</s>

for(a=s=[];s;)for(i=18,s=72;i;s-=a[--i]=Math.random()*3+3|0)a


问:
Integer square root of integer
Problem:

In your choice of language, write the shortest function that returns the floor of the square root of an unsigned 64-bit integer.

Test cases:

Your function must work correctly for all inputs, but here are a few which help illustrate the idea:

```<code>               INPUT ⟶ OUTPUT

                   0 ⟶  0
                   1 ⟶  1
                   2 ⟶  1
                   3 ⟶  1
                   4 ⟶  2
                   8 ⟶  2
                   9 ⟶  3
                  15 ⟶  3
                  16 ⟶  4
               65535 ⟶ 255
               65536 ⟶ 256
18446744073709551615 ⟶ 4294967295
</code>```

Rules:

You can name your function anything you like. (Unnamed, anonymous, or lambda functions are fine, as long as they are somehow callable.)

Character count is what matters most in this challenge, but runtime is also important. I'm sure you could scan upwards iteratively for the answer in O(√n) time with a very small character count, but O(log(n)) time would really be better (that is, assuming an input value of n, not a bit-length of n).

You will probably want to implement the function using purely integer and/or boolean artithmetic. However, if you really want to use floating-point calculations, then that is fine so long as you call no library functions. So, simply saying return (n>0)?(uint32_t)sqrtl(n):-1; in C is off limits even though it would produce the correct result. If you're using floating-point arithmetic, you may use *, /, +, -, and exponentiation (e.g., ** or ^ if it's a built-in operator in your language of choice, but only exponentiation of powers not less than 1). This restriction is to prevent "cheating" by calling sqrt() or a variant or raising a value to the ½ power.

If you're using floating-point operations (see #3), you aren't required that the return type be integer; only that that the return value is an integer, e.g., floor(sqrt(n)), and be able to hold any unsigned 32-bit value.

If you're using C/C++, you may assume the existence of unsigned 64-bit and 32-bit integer types, e.g., uint64_t and uint32_t as defined in stdint.h. Otherwise, just make sure your integer type is capable of holding any 64-bit unsigned integer.

If your langauge does not support 64-bit integers (for example, Brainfuck apparently only has 8-bit integer support), then do your best with that and state the limitation in your answer title. That said, if you can figure out how to encode a 64-bit integer and correctly obtain the square root of it using 8-bit primitive arithmetic, then more power to you!

Have fun and get creative!

ContentLicense: CC BY-SA 3.0

Title: Integer square root of integer

Body:
C++17, 80 bytes

auto f(auto n){auto x=1ul<<32,a=x-x;for(;x/=2;)a+=(a+x)*(a+x)<=n?x:0;return a;};

Explanation

This computes one bit per iteration, accumulating the result in a.

Tests

int main()
{
    return
        + (f(0) != 0)
        + (f(1) != 1)
        + (f(1) != 1)
        + (f(2) !=  1)
        + (f(3) !=  1)
        + (f(4) !=  2)
        + (f(8) !=  2)
        + (f(9) !=  3)
        + (f(15) !=  3)
        + (f(16) !=  4)
        + (f(65535) != 255)
        + (f(65536) != 256)
        + (f(18446744073709551615ul) != 4294967295)
        ;
}


问:
Was it Really Canada Day?
July 1st is Canada day (yay Canada)! Or is it?  It seems that the Wikipedia page for this day has a lot of Canada related content, but is there another day which is more Canadian?

Your task is to write a program or function which takes a date (month and day) as input and returns or outputs the number of mentions of "Canada" on the Wikipedia page for the inputed date.
Some rules:

Dates may be input in any reasonable format of your choice

Your submission must pull data from the url en.wikipedia.org/wiki/Month_Day.

Only "Canada" must be searched for and counted included substrings, and only in title case. "Canadian" does not count, however "Canada's" does count. As long as the exact, case-senstitive text "Canada" exists within a string, it is a match

Contents of the page are considered anything within the corresponding .html file (i.e. what shows up if you download as page as a .html and open it in Notepad)

Result may be output to STDOUT, returned, or displayed in any other reasonable manner

Test Cases:

```<code>July 1 => 34
May 14 => 1
Oct 31 => 2
July 4 => 2
</code>```

This is code golf, so shortest submission wins

(As an unrewarded bonus, I'm interested to see what the day with the highest count is)

答:
Perl 5, 39 bytes

38 bytes, plus 1 for -pe instead of -e

```<code>$_=()=`curl -L enwp.org/$_`=~/Canada/g
</code>```

Takes input like July_1.

Thanks to busukxuan for saving me seven bytes.

Title: Was it Really Canada Day?

Body:
Perl 5, 39 bytes

38 bytes, plus 1 for -pe instead of -e

$_=()=`curl -L enwp.org/$_`=~/Canada/g

Takes input like July_1.

Thanks to busukxuan for saving me seven bytes.


答:
Mathematica, 60 bytes

```<code>Import["http://enwp.org/"<>#,"Source"]~StringCount~"Canada"&
</code>```

Anonymous function. Similarly to the Perl 5 solution, takes input like July_1.

Title: Was it Really Canada Day?

Body:
July 1st is Canada day (yay Canada)! Or is it?  It seems that the Wikipedia page for this day has a lot of Canada related content, but is there another day which is more Canadian?

Your task is to write a program or function which takes a date (month and day) as input and returns or outputs the number of mentions of "Canada" on the Wikipedia page for the inputed date.
Some rules:

Dates may be input in any reasonable format of your choice

Your submission must pull data from the url en.wikipedia.org/wiki/Month_Day.

Only "Canada" must be searched for and counted included substrings, and only in title case. "Canadian" does not count, however "Canada's" does count. As long as the exact, case-senstitive text "Canada" exists within a string, it is a match

Contents of the page are considered anything within the corresponding .html file (i.e. what shows up if you download as page as a .html and open it in Notepad)

Result may be output to STDOUT, returned, or displayed in any other reasonable manner

Test Cases:

```<code>July 1 => 34
May 14 => 1
Oct 31 => 2
July 4 => 2
</code>```

This is code golf, so shortest submission wins

(As an unrewarded bonus, I'm interested to see what the day with the highest count is)

Body:
Mathematica, 60 bytes

Import["http://enwp.org/"<>#,"Source"]~StringCount~"Canada"&

Anonymous function. Similarly to the Perl 5 solution, takes input like July_1.


答:
Python 3.5, <s>117</s> <s>111</s> <s>98</s> 90 bytes

(-8 bytes (98 -> 90) thanks to alexwlchan)

```<code>from urllib.request import*
lambda i:urlopen('http://enwp.org/'+i).read().count(b"Canada")
</code>```

Simply uses Python's built-in "urllib" library to fetch HTML data and then counts the occurrences of the word "Canada" in that data. Will try and golf more over time where and when I can. Call it by renaming the lambda function to anything and then calling that name like a normal function wrapped in print(). For instance, if the function were named H, then you would call it like print(H(Month_Day)).

Title: Was it Really Canada Day?

Body:
Python 3.5, <s>117</s> <s>111</s> <s>98</s> 90 bytes

(-8 bytes (98 -> 90) thanks to alexwlchan)

from urllib.request import*
lambda i:urlopen('http://enwp.org/'+i).read().count(b"Canada")

Simply uses Python's built-in "urllib" library to fetch HTML data and then counts the occurrences of the word "Canada" in that data. Will try and golf more over time where and when I can. Call it by renaming the lambda function to anything and then calling that name like a normal function wrapped in print(). For instance, if the function were named H, then you would call it like print(H(Month_Day)).


答:
Bash, 43 42 40 bytes

```<code>curl -L enwp.org/$@|grep -o Canada|wc -l
</code>```

Uses curl, grep, and wc to count occurrences of "Canada" in specified webpage. Like the other answers, input is given in the format July_1. This is my first time posting on the Code Golf SE and I'm not quite familiar with all of the rules. Any feedback would be most welcome.

Didn't realize that output to STDERR is traditionally ignored. Thanks for the 3 bytes, Dennis!

Title: Was it Really Canada Day?

Body:
Bash, 43 42 40 bytes

curl -L enwp.org/$@|grep -o Canada|wc -l

Uses curl, grep, and wc to count occurrences of "Canada" in specified webpage. Like the other answers, input is given in the format July_1. This is my first time posting on the Code Golf SE and I'm not quite familiar with all of the rules. Any feedback would be most welcome.

Didn't realize that output to STDERR is traditionally ignored. Thanks for the 3 bytes, Dennis!


问:
Golf Down the PPCG Usernames
A comment I made in chat and the ensuing conversation inspired me to make this challenge.

Am I the only one referred to by initials around here? We are all about golfing things down. We can have MB and D-nob and ... O.

If I'm known as "CH" then I think everyone else ought to have an initial-based nickname as well.

Here's a list of the top 100 Programming Puzzles & Code Golf users by reputation to play with:

```<code>Martin Büttner
Doorknob
Peter Taylor
Howard
marinus
Dennis
DigitalTrauma
David Carraher
primo
squeamish ossifrage
Keith Randall
Ilmari Karonen
Quincunx
Optimizer
grc
Calvin's Hobbies
ugoren
Mig
gnibbler
Sp3000
aditsu
histocrat
Ventero
xnor
mniip
Geobits
J B
Joe Z.
Gareth
Jan Dvorak
isaacg
edc65
Victor
steveverrill
feersum
ace
Danko Durbić
xfix
PhiNotPi
user23013
manatwork
es1024
Joey
daniero
boothby
nneonneo
Joey Adams
Timwi
FireFly
dansalmo
grovesNL
breadbox
Timtech
Flonk
algorithmshark
Johannes Kuhn
Yimin Rong
copy
belisarius
professorfish
Ypnypn
trichoplax
Darren Stone
Riot
ProgramFOX
TheDoctor
swish
minitech
Jason C
Tobia
Falko
PleaseStand
VisioN
leftaroundabout
alephalpha
FUZxxl
Peter Olson
Eelvex
marcog
MichaelT
w0lf
Ell
Kyle Kanos
qwr
flawr
James_pic
MtnViewMark
cjfaure
hammar
bitpwner
Heiko Oberdiek
proud haskeller
dan04
plannapus
Mr Lister
randomra
AShelly
ɐɔıʇǝɥʇuʎs
Alexandru
user unknown
</code>```

(this is how I got it)

Challenge

Write a program or function that takes in a list of strings and outputs another list of strings of their minimal, unique, initial-based nicknames, giving preference to those closer to the start of the list.

Apply this method to each string S in the list in the order given to create the nicknames:

Split S up into words separated by spaces, removing all spaces in the process.

List the nonempty prefixes of the string of the first letters of the words in S, from shortest to longest.

    e.g. Just Some Name → J, JS, JSN

Choose the first item in this list that is not identical to an already chosen nickname as the nickname for S. Stop if a nickname was chosen, continue to step 4 otherwise.

    e.g. if Just Some Name was the first string then J is guaranteed to be the nickname.

List the prefixes again, but this time include the second letter of the first word in it's natural place.

    e.g. Just Some Name → Ju, JuS, JuSN

Do the same as in step 3 for this list, stopping if a unique nickname is found.

Repeat this process with the remaining letters of the first word, eventually inserting letters into the second word, then the third, and so on, until a unique nickname is found.

    e.g. The first unique string listed here will be the nickname:

    Jus, JusS, JusSN

    Just, JustS, JustSN

    Just, JustSo, JustSoN (note that o was not added after Just)

    Just, JustSom, JustSomN

    Just, JustSome, JustSomeN

    Just, JustSome, JustSomeNa

    Just, JustSome, JustSomeNam

    Just, JustSome, JustSomeName

In the end all the input strings should end up with a unique nickname (potentially identical to the string). You may assume that none of the input strings will map to the same nickname using this method.

Example

Updated to fix my mistake!

For the input

```<code>Martin Buttner
Doorknob
Peter Taylor
Howard
marinus
Dennis
DigitalTrauma
David Carraher
Martin Bitter
Martin Butter
Martin Battle
Martini Beer
Mart Beer
Mars Bar
Mars Barn
</code>```

the nicknames would be

```<code>M
D
P
H
m
De
Di
DC
MB
Ma
MaB
Mar
MarB
Mars
MarsB
</code>```

Details

Input can be from a file (one name per line), or one name at a time via stdin/command line, or as a function argument of a list of strings, or as a function arg of a single string with newlines between names.

Output should be printed to stdout (one nickname per line) or returned by the function as a list of strings, or as one string with newlines between nicknames.

Ideally programs will work for names that contain any characters except line terminators. However, you may assume that all the names only contain printable ASCII. (The PPCG names don't.)

Only the regular space character counts as a word separator. Leading and trailing spaces can be ignored.

Scoring

The shortest submission in bytes wins. Tiebreaker goes to the answer posted earliest.

答:
PHP, <s>327</s> <s>289</s> <s>275</s> <s>274</s> 270

There may still be a little golfing potential.

```<code>while($n=fgets(STDIN)){$c=count($w=preg_split('/\s+/',trim($n)));$p=[];for($k=0;$k<$c;$p[$k]++){for($t='',$j=0;$j<$c;$j++)$t.=substr($w[$j],0,$p[$j]+1);for($j=1;$j<=strlen($t);$j++)if(!in_array($v=substr($t,0,$j),$u))break 2;$k+=$p[$k]==strlen($w[$k]);}echo$u[]=$v,'
';}
</code>```

Program operates on stdin/stdout, works on ASCII, buggy on UTF

usage: php -d error_reporting=0 golfnicks.php < nicknames.txt

or cat <<EOF | php -d error_reporting=0 golfnicks.php + list of names + EOF

To test as function in web browser: fetch the breakdown, uncomment all lines marked with // FUNC and comment the one marked with //PROG.
Try f(array_fill(0,21,'Just Some Name'));

breakdown

```<code>#error_reporting(0);function f($a){echo'```'; // FUNC
#foreach($a as$n) // FUNC
while($n=fgets(STDIN)) // PROG
{
    $c=count($w=preg_split('/\s+/',trim($n)));     // split name to words, count them
    $p=[];                                         // initialize cursors
    for($k=0;$k<$c;$p[$k]++)
    {
        for($t='',$j=0;$j<$c;$j++)$t.=substr($w[$j],0,$p[$j]+1); // concatenate prefixes
        for($j=1;$j<=strlen($t);$j++)              // loop through possible nicks
            if(!in_array($v=substr($t,0,$j),$u))   // unused nick found
                break 2;                           // -> break cursor loop
        $k+=$p[$k]==strlen($w[$k]);                // if Cw exhausted -> next word
        // strlen()-1 would be correct; but this works too)
    }
    echo$u[]=$v,'
';
}
#echo '```';} // FUNC
</code>```

Title: Golf Down the PPCG Usernames

Body:
PHP, <s>327</s> <s>289</s> <s>275</s> <s>274</s> 270

There may still be a little golfing potential.

while($n=fgets(STDIN)){$c=count($w=preg_split('/\s+/',trim($n)));$p=[];for($k=0;$k<$c;$p[$k]++){for($t='',$j=0;$j<$c;$j++)$t.=substr($w[$j],0,$p[$j]+1);for($j=1;$j<=strlen($t);$j++)if(!in_array($v=substr($t,0,$j),$u))break 2;$k+=$p[$k]==strlen($w[$k]);}echo$u[]=$v,'
';}

Program operates on stdin/stdout, works on ASCII, buggy on UTF

usage: php -d error_reporting=0 golfnicks.php < nicknames.txt

or cat <<EOF | php -d error_reporting=0 golfnicks.php + list of names + EOF

To test as function in web browser: fetch the breakdown, uncomment all lines marked with // FUNC and comment the one marked with //PROG.
Try f(array_fill(0,21,'Just Some Name'));

breakdown

#error_reporting(0);function f($a){echo'<pre>'; // FUNC
#foreach($a as$n) // FUNC
while($n=fgets(STDIN)) // PROG
{
    $c=count($w=preg_split('/\s+/',trim($n)));     // split name to words, count them
    $p=[];                                         // initialize cursors
    for($k=0;$k<$c;$p[$k]++)
    {
        for($t='',$j=0;$j<$c;$j++)$t.=substr($w[$j],0,$p[$j]+1); // concatenate prefixes
        for($j=1;$j<=strlen($t);$j++)              // loop through possible nicks
            if(!in_array($v=substr($t,0,$j),$u))   // unused nick found
                break 2;                           // -> break cursor loop
        $k+=$p[$k]==strlen($w[$k]);                // if Cw exhausted -> next word
        // strlen()-1 would be correct; but this works too)
    }
    echo$u[]=$v,'
';
}
#echo '</pre>';} // FUNC


答:
Pyth, 31 bytes

```<code>/jk'+"http://enwp.org/"z"Canada
</code>```

Does not work on the online implementation, the server disables Internet access. I wanted to use http://wki.pe/July_1 but sadly it's a client-side redirect so it fetches the wrong page. The input format is July_1.

The code is basically just:

```<code>"".join(open("http://enwp.org/"+input())).count("Canada")
</code>```

Title: Was it Really Canada Day?

Body:
Pyth, 31 bytes

/jk'+"http://enwp.org/"z"Canada

Does not work on the online implementation, the server disables Internet access. I wanted to use http://wki.pe/July_1 but sadly it's a client-side redirect so it fetches the wrong page. The input format is July_1.

The code is basically just:

"".join(open("http://enwp.org/"+input())).count("Canada")


问:
Can you Golf Golf?
You are required to generate a random 18-hole golf course.

Example output:

```<code>[3 4 3 5 5 4 4 4 5 3 3 4 4 3 4 5 5 4]
</code>```

Rules:

Your program must output a list of hole lengths for exactly 18 holes

Each hole must have a length of 3, 4 or 5

The hole lengths must add up to 72 for the entire course

Your program must be able to produce every possible hole configuration with some non-zero-probability (the probabilities of each configuration need not be equal, but feel free to claim extra kudos if this is the case)

答:
GolfScript (26 chars)

```<code>{;0{3rand.3+@@+(}18*])}do`
</code>```

There are some obvious similarities with Ilmari's solution, but also some obvious differences. In particular, I'm exploiting the fact that the average par is 4.

Title: Can you Golf Golf?

Body:
GolfScript (26 chars)

{;0{3rand.3+@@+(}18*])}do`

There are some obvious similarities with Ilmari's solution, but also some obvious differences. In particular, I'm exploiting the fact that the average par is 4.


问:
Convert string to time
This challenge is inspired by this other.

The challenge

Write a program or a function in any programming language that given as input a string representing a time in English (see below, for further details) it outputs or prints the equivalent in the 24 hours "digital" format HH:MM.

Shortest code in bytes wins, standard loopholes are forbidden.

Input format

Your program should be able to handle all this kind of inputs:

```<code>one minute past 'HOUR'
'MINUTES' minutes past 'HOUR'
quarter past 'HOUR'
half past 'HOUR'
one minute to 'HOUR'
'MINUTES' minutes to 'HOUR'
quarter to 'HOUR'
'HOUR'
'HOUR12' 'MINUTES' AM
'HOUR12' 'MINUTES' PM
</code>```

where: MINUTES is a number from 1 to 59 written in English with hyphen; HOUR is the name of an hour in one of the formats:

```<code>midnight
noon
midday
'HOUR24' o'clock
'HOUR12' o'clock AM
'HOUR12' o'clock PM
</code>```

HOUR12 is a number from 1 to 12 written in English with hyphen; and HOUR24 is a number from 1 to 23 written in English with hyphen.

Some examples

```<code>midnight                                  ->   00:00
midday                                    ->   12:00
twelve o'clock                            ->   12:00
quarter to midnight                       ->   23:45
twenty-two minutes past eight o'clock PM  ->   20:22
thirty-four minutes to fifteen o'clock    ->   14:26
six o'clock AM                            ->   06:00
one minute to twenty-one o'clock          ->   20:59
seven thirteen AM                         ->   07:13
nine fourteen PM                          ->   21:14
</code>```

Good luck!

答:
Ruby, <s>653</s> 597 Bytes

```<code>P=/ past | to /;T=%w{q twen thirty fourty fifty sixty el twe thi fourte fifte sixt sevent eighte ninet o tw th fo fi si s e n t}.zip([15,*(2..6).map{|i|i*10},*11..19,*1..10]).to_h;D={'middnight'=>0,'midday'=>12,'noon'=>12};n=->s{s.split('-').reduce(0){|p,v|(Array(T.find{|k,_|v.start_with? k}).last||0)+p}};i=->s{m=0;s=s.gsub(/^\s+|\s+$/,'');c=s.split(P);(c.reverse! if s.match(P));h=D[c[0]]||n.(c[0].gsub(/ o\'clock (A|P)m/,''));h+=(s.end_with?('PM') ? 12 : 0);m=n.(c[1]||c[0].split(' ')[1]) if c[1]||c[0].match(/^\w+ (?!o'clock)/);(m=60-m;h=(h-1)%24)if s.match(/ to /);(sprintf '%02d:%02d',h,m)}
</code>```

Ungolfed:

```<code>P=/ past | to /
# configuration for translating english words to numbers
T=%w{q twen thirty fourty fifty sixty el twe thi fourte fifte sixt sevent eighte ninet o tw th fo fi si s e n t}.zip([15,*(2..6).map{|i|i*10},*11..19,*1..10]).to_h
D={'middnight'=>0,'midday'=>12,'noon'=>12}

# proc for translating english word groups to a number
n=-> s {
  s.split('-').reduce(0) { |p,v|
    (Array(T.find {|k,_| v.start_with? k}).last || 0) + p
  }
}

i=-> s {
  m=0
  s=s.gsub(/^\s+|\s+$/,'')
  c=s.split(P)
  (c.reverse! if s.match(P))

  # set the hour
  h=D[c[0]]||n.(c[0].gsub(/ o\'clock (A|P)m/,''))
  h+=(s.end_with?('PM') ? 12 : 0)

  # set the minute
  m=n.(c[1]||c[0].split(' ')[1]) if c[1]||c[0].match(/^\w+ (?!o'clock)/)

  # adjust for 'past'
  (m=60-m;h=(h-1)%24)if s.match(/ to /)

  sprintf '%02d:%02d',h,m
}
</code>```

Verification script used:

```<code>examples = <<EXAMPLES
midnight                                  ->   00:00
midday                                    ->   12:00
twelve o'clock                            ->   12:00
quarter to midnight                       ->   23:45
twenty-two minutes past eight o'clock PM  ->   20:22
thirty-four minutes to fifteen o'clock    ->   14:26
six o'clock AM                            ->   06:00
one minute to twenty-one o'clock          ->   20:59
seven thirteen AM                         ->   07:13
nine fourteen PM                          ->   21:14
EXAMPLES

examples.split("\n").each do |example|
  text, expected = example.split(/\s+->\s+/)
  r = i.(text)
  raise "Unexpected result for \"#{text}\". Got \"#{r}\", expected \"#{expected}\"" unless r == expected
  print "."
end
</code>```

Thank you to Kevin Lau for 47 bytes of optimization

Title: Convert string to time

Body:
Ruby, <s>653</s> 597 Bytes

P=/ past | to /;T=%w{q twen thirty fourty fifty sixty el twe thi fourte fifte sixt sevent eighte ninet o tw th fo fi si s e n t}.zip([15,*(2..6).map{|i|i*10},*11..19,*1..10]).to_h;D={'middnight'=>0,'midday'=>12,'noon'=>12};n=->s{s.split('-').reduce(0){|p,v|(Array(T.find{|k,_|v.start_with? k}).last||0)+p}};i=->s{m=0;s=s.gsub(/^\s+|\s+$/,'');c=s.split(P);(c.reverse! if s.match(P));h=D[c[0]]||n.(c[0].gsub(/ o\'clock (A|P)m/,''));h+=(s.end_with?('PM') ? 12 : 0);m=n.(c[1]||c[0].split(' ')[1]) if c[1]||c[0].match(/^\w+ (?!o'clock)/);(m=60-m;h=(h-1)%24)if s.match(/ to /);(sprintf '%02d:%02d',h,m)}

Ungolfed:

P=/ past | to /
# configuration for translating english words to numbers
T=%w{q twen thirty fourty fifty sixty el twe thi fourte fifte sixt sevent eighte ninet o tw th fo fi si s e n t}.zip([15,*(2..6).map{|i|i*10},*11..19,*1..10]).to_h
D={'middnight'=>0,'midday'=>12,'noon'=>12}

# proc for translating english word groups to a number
n=-> s {
  s.split('-').reduce(0) { |p,v|
    (Array(T.find {|k,_| v.start_with? k}).last || 0) + p
  }
}

i=-> s {
  m=0
  s=s.gsub(/^\s+|\s+$/,'')
  c=s.split(P)
  (c.reverse! if s.match(P))

  # set the hour
  h=D[c[0]]||n.(c[0].gsub(/ o\'clock (A|P)m/,''))
  h+=(s.end_with?('PM') ? 12 : 0)

  # set the minute
  m=n.(c[1]||c[0].split(' ')[1]) if c[1]||c[0].match(/^\w+ (?!o'clock)/)

  # adjust for 'past'
  (m=60-m;h=(h-1)%24)if s.match(/ to /)

  sprintf '%02d:%02d',h,m
}

Verification script used:

examples = <<EXAMPLES
midnight                                  ->   00:00
midday                                    ->   12:00
twelve o'clock                            ->   12:00
quarter to midnight                       ->   23:45
twenty-two minutes past eight o'clock PM  ->   20:22
thirty-four minutes to fifteen o'clock    ->   14:26
six o'clock AM                            ->   06:00
one minute to twenty-one o'clock          ->   20:59
seven thirteen AM                         ->   07:13
nine fourteen PM                          ->   21:14
EXAMPLES

examples.split("\n").each do |example|
  text, expected = example.split(/\s+->\s+/)
  r = i.(text)
  raise "Unexpected result for \"#{text}\". Got \"#{r}\", expected \"#{expected}\"" unless r == expected
  print "."
end

Thank you to Kevin Lau for 47 bytes of optimization


问:
Implement Takewhile

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

```<code>[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]
</code>```

Step-by-Step Example

```<code>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]
</code>```

答:
MATL, 6 bytes

```<code>toYs~)
</code>```

Try it online!

Explanation

```<code>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
</code>```

Title: Implement Takewhile

Body:
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


答:
Pyth, <s>13</s> <s>9</s> 7 bytes

```<code>uPWs%R2
</code>```

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

Explanation:

```<code>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
</code>```

Test it here.

Title: Implement Takewhile

Body:
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

```<code>[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]
</code>```

Step-by-Step Example

```<code>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]
</code>```

Body:
Pyth, <s>13</s> <s>9</s> 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.


答:
Mathematica, 18 bytes

```<code>#~TakeWhile~EvenQ&
</code>```

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

Title: Implement Takewhile

Body:
Mathematica, 18 bytes

#~TakeWhile~EvenQ&

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


答:
Brachylog, <s>19</s> 16 bytes

```
<s>hH:2%0,?b&~b.hH;[].</s>

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

Explanation

```<code>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
</code>```

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]".

Title: Implement Takewhile

Body:
Brachylog, <s>19</s> 16 bytes

<s>hH:2%0,?b&~b.hH;[].</s>

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]".


答:
V, 13 bytes

```<code>íä*[13579]¾.*
</code>```

Try it online!

Explanation:

```<code>í              "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.
</code>```

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

Title: Implement Takewhile

Body:
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.


答:
05AB1E, <s>8</s> 7 bytes

```<code>[DÉO_#¨
</code>```

Explanation

```<code>[        # 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
</code>```

Try it online

Previous 8 byte solution

```<code>vyÈiyˆëq
</code>```

Explanation

```<code>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
</code>```

Try it online

Title: Implement Takewhile

Body:
05AB1E, <s>8</s> 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


答:
Retina, 17 bytes

```<code> ?\d*[13579]\b.*

</code>```

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:

```<code> ?\d*1\b.*

</code>```

Title: Implement Takewhile

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


答:
Pyke, 8 bytes

```<code>0+2L%fhO
</code>```

Interpreter fixed, use other links

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

Or with bugfix, 7 bytes

```<code>2L%1R@<
</code>```

Try it here!

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

Or after 2nd bugfix, 6 bytes

```<code>2L%fhO
</code>```

Try it here!

Explanation:

```<code>2L%    -   map(%2, input)
   f   -  split_at(input, ^)
    hO - ^[0][:-1]
</code>```

Title: Implement Takewhile

Body:
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]


答:
Clojure, 21 bytes

```<code>#(take-while even? %)
</code>```

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

Title: Implement Takewhile

Body:
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


答:
Python 2, 70 bytes

from random import*
print sample(([3,5]*randint(0,9)+[4]*99)[:18],18)
```

edit:

<p>Here's another one, similar to the solution of sgrieve:</p>

<h1>Python 2, 73 bytes + equal probability</h1>

<pre class="lang-python prettyprint-override"><code>from random import*
a=[]
while sum(a)-72:a=sample([3,4,5]*18,18)
print a
</code>```

Title: Can you Golf Golf?

Body:
You are required to generate a random 18-hole golf course.

Example output:

```<code>[3 4 3 5 5 4 4 4 5 3 3 4 4 3 4 5 5 4]
</code>```

Rules:

Your program must output a list of hole lengths for exactly 18 holes

Each hole must have a length of 3, 4 or 5

The hole lengths must add up to 72 for the entire course

Your program must be able to produce every possible hole configuration with some non-zero-probability (the probabilities of each configuration need not be equal, but feel free to claim extra kudos if this is the case)

Body:
Python 2, 70 bytes

from random import*
print sample(([3,5]*randint(0,9)+[4]*99)[:18],18)

edit:

Here's another one, similar to the solution of sgrieve:

Python 2, 73 bytes + equal probability

from random import*
a=[]
while sum(a)-72:a=sample([3,4,5]*18,18)
print a


答:
Ruby, 25 bytes

```<code>->a{a.take_while &:even?}
</code>```

I think I lose...

Title: Implement Takewhile

Body:
Ruby, 25 bytes

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

I think I lose...


答:
Pyth, 7 bytes

```<code><x%R2Q1
</code>```

Try it here!

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

Title: Implement Takewhile

Body:
Pyth, 7 bytes

<x%R2Q1

Try it here!

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


答:
Dyalog APL, 11 bytes

```<code>{⍵/⍨∧\~2|⍵}
</code>```

2| division remainder from dividing with 2

~ negate

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

/⍨ select where

Title: Implement Takewhile

Body:
Dyalog APL, 11 bytes

{⍵/⍨∧\~2|⍵}

2| division remainder from dividing with 2

~ negate

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

/⍨ select where


答:
Jelly, 5 bytes

```<code>Ḃœp⁸Ḣ
</code>```

Try it online! or verify all test cases.

How it works

```<code>Ḃœ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.
</code>```

Title: Implement Takewhile

Body:
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.


答:
Haskell, 13 bytes

```<code>fst.span even
</code>```

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:

```<code>fst.break odd
</code>```

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

```<code>takeWhile even
</code>```

but that's 14 bytes.

Title: Implement Takewhile

Body:
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.


答:
Labyrinth, 14 bytes

```<code>?:
"`#
"@%
\!;
</code>```

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:

```<code>?:#
" %
\!/
</code>```

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:

```<code>>v
^>v
^@v
^<<
</code>```

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:

```<code>?   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.
</code>```

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.

Title: Implement Takewhile

Body:
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.


答:
K, 12 bytes

```<code>{x@&~|\2!'x}
</code>```

Explanation

```<code>{           } 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.
</code>```

Title: Implement Takewhile

Body:
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

```<code>[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]
</code>```

Step-by-Step Example

```<code>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]
</code>```

Body:
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.


答:
Python 2, <s>59</s> <s>57</s> 56 bytes

def f(L,E=[]):
 while L and~L[0]%2:E+=L.pop(0),
 print E
```
<p><strong>Try it online</strong></p>
<p>If printing rather than returning a list is allowed, <strong>44 bytes</strong>:</p>
<pre class="lang-python prettyprint-override"><code>L=input()
while L and~L[0]%2:print L.pop(0)
</code>```

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

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

Title: Implement Takewhile

Body:
Python 2, <s>59</s> <s>57</s> 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


答:
Python 3, 59 bytes

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

Can <s>surely</s> probably be golfed more.

Thanks to everyone who commented :D

Title: Implement Takewhile

Body:
Python 3, 59 bytes

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

Can <s>surely</s> probably be golfed more.

Thanks to everyone who commented :D


答:
C# (143 non-whitespace):

```<code>()=>{
  var n=new Math.Random().Next(10);
  Enumerable.Range(1,18)
    .Select((x,i)=>i<n?3:i>=18-n?5:4)
    .OrderBy(x=>Guid.NewGuid())
    .ForEach(Console.Write);
}
</code>```

Title: Can you Golf Golf?

Body:
C# (143 non-whitespace):

()=>{
  var n=new Math.Random().Next(10);
  Enumerable.Range(1,18)
    .Select((x,i)=>i<n?3:i>=18-n?5:4)
    .OrderBy(x=>Guid.NewGuid())
    .ForEach(Console.Write);
}


答:
R, 99 96 bytes

x=function(d){p=readLines(paste0("http://enwp.org/",d));sum(nchar(p)-nchar(gsub("Canada","",p)))/6}

```<code>d=scan(,"");p=readLines(paste0("http://enwp.org/",d));sum(nchar(p)-nchar(gsub("Canada","",p)))/6
</code>```

This takes input d in the form "July_1" and returns the count of Canadas. It counts the words by counting the number of characters on the page, then removes the word Canada from the page and counts the characters again. The number of times Canada shows up is the difference in these counts divided by the number of letters in Canada, 6.

edit: I appreciate the tip below about replacing my function with scan.

Title: Was it Really Canada Day?

Body:
July 1st is Canada day (yay Canada)! Or is it?  It seems that the Wikipedia page for this day has a lot of Canada related content, but is there another day which is more Canadian?

Your task is to write a program or function which takes a date (month and day) as input and returns or outputs the number of mentions of "Canada" on the Wikipedia page for the inputed date.
Some rules:

Dates may be input in any reasonable format of your choice

Your submission must pull data from the url en.wikipedia.org/wiki/Month_Day.

Only "Canada" must be searched for and counted included substrings, and only in title case. "Canadian" does not count, however "Canada's" does count. As long as the exact, case-senstitive text "Canada" exists within a string, it is a match

Contents of the page are considered anything within the corresponding .html file (i.e. what shows up if you download as page as a .html and open it in Notepad)

Result may be output to STDOUT, returned, or displayed in any other reasonable manner

Test Cases:

```<code>July 1 => 34
May 14 => 1
Oct 31 => 2
July 4 => 2
</code>```

This is code golf, so shortest submission wins

(As an unrewarded bonus, I'm interested to see what the day with the highest count is)

Body:
R, 99 96 bytes

x=function(d){p=readLines(paste0("http://enwp.org/",d));sum(nchar(p)-nchar(gsub("Canada","",p)))/6}

d=scan(,"");p=readLines(paste0("http://enwp.org/",d));sum(nchar(p)-nchar(gsub("Canada","",p)))/6

This takes input d in the form "July_1" and returns the count of Canadas. It counts the words by counting the number of characters on the page, then removes the word Canada from the page and counts the characters again. The number of times Canada shows up is the difference in these counts divided by the number of letters in Canada, 6.

edit: I appreciate the tip below about replacing my function with scan.


答:
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)

Title: Implement Takewhile


答:
Python, 55

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

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

```<code>def t(A):
 for a in A:
  if a%2:break
  else:yield a

# usage: list(t([2, 3, 4]))
</code>```

Title: Implement Takewhile

Body:
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

```<code>{.~2&|i.1:
</code>```

Explanation

```<code>{.~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
</code>```

Title: Implement Takewhile

Body:
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


答:
Python, <s>45</s> 44 bytes

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

Test it on Ideone.

Title: Implement Takewhile

Body:
Python, <s>45</s> 44 bytes

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

Test it on Ideone.


答:
R, 25 bytes

```<code>x=scan()
x[!cumsum(x%%2)]
</code>```

Or equivalently

```<code>(y=scan())[!cumsum(y%%2)]
</code>```

Title: Implement Takewhile

Body:
R, 25 bytes

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

Or equivalently

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


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

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

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.

Title: Implement Takewhile

Body:
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.


答:
Racket, 22 bytes

```<code>(λ(n)(takef n even?))
</code>```

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!

Title: Implement Takewhile

Body:
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!


答:
Clojure, 71 bytes

```<code>#(count(re-seq #"Canada"(slurp(str"https://en.wikipedia.org/wiki/"%))))
</code>```

Yeah, it would be nice to use http://enwp.org but I guess slurp does not handle redirects(?).  Anonymous function which take day in the format "July_1".

Title: Was it Really Canada Day?

Body:
Clojure, 71 bytes

#(count(re-seq #"Canada"(slurp(str"https://en.wikipedia.org/wiki/"%))))

Yeah, it would be nice to use http://enwp.org but I guess slurp does not handle redirects(?).  Anonymous function which take day in the format "July_1".


答:
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?

```<code>: 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 ;
</code>```

Try it online

Ungolfed, with comments:

```<code>: 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
;
</code>```

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

```<code>: f DEPTH IF BEGIN DUP 2 MOD DUP 1- IF SWAP . THEN UNTIL THEN ;
</code>```

Fails if only even integers

Title: Implement Takewhile

Body:
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


答:
CJam, 11 bytes

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

```<code>{1+_2f%1#<}
</code>```

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

```<code>{         }    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
</code>```

Title: Implement Takewhile

Body:
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


答:
Ruby + curl, 44 bytes

```<code>p`curl -L enwp.org/#$_`.scan(/Canada/).size
</code>```

ruby -n + 43 bytes. Takes input like July_1.

Title: Was it Really Canada Day?

Body:
Ruby + curl, 44 bytes

p`curl -L enwp.org/#$_`.scan(/Canada/).size

ruby -n + 43 bytes. Takes input like July_1.


答:
Python 2, <s>43</s> 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.

Title: Implement Takewhile

Body:
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

```<code>[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]
</code>```

Step-by-Step Example

```<code>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]
</code>```

Body:
Python 2, <s>43</s> 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.


答:
JavaScript (Firefox 30-57), 30 bytes

```<code>a=>[for(x of a)if(!(a|=x&1))x]
</code>```

Title: Implement Takewhile

Body:
JavaScript (Firefox 30-57), 30 bytes

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


答:
Hexagony, 19

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

Readable:

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

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:

```<code>while (read number is not zero)
{
    if (number is even)
        print number;
}
</code>```

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:

```<code>Mod  \ / Input
      |
      2
</code>```

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.

Title: Implement Takewhile

Body:
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 (/"%>).

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 (123 chars) - effort on efficiency

Pipe through wc and it will generate all 44152809 solutions within 10 seconds...

```<code>char s[19];g(d,t){int i;if(d--){for(i=51,t-=3;i<54;i++,t--)if(t>=3*d&&t<=5*d)s[d]=i,g(d,t);}else puts(s);}main(){g(18,72);}
</code>```

Oh, well - didn't read the question properly - but given we're generating all solutions then picking a random one with equal probability is a scripting exercise :P

Title: Can you Golf Golf?

Body:
You are required to generate a random 18-hole golf course.

Example output:

```<code>[3 4 3 5 5 4 4 4 5 3 3 4 4 3 4 5 5 4]
</code>```

Rules:

Your program must output a list of hole lengths for exactly 18 holes

Each hole must have a length of 3, 4 or 5

The hole lengths must add up to 72 for the entire course

Your program must be able to produce every possible hole configuration with some non-zero-probability (the probabilities of each configuration need not be equal, but feel free to claim extra kudos if this is the case)

Body:
C (123 chars) - effort on efficiency

Pipe through wc and it will generate all 44152809 solutions within 10 seconds...

char s[19];g(d,t){int i;if(d--){for(i=51,t-=3;i<54;i++,t--)if(t>=3*d&&t<=5*d)s[d]=i,g(d,t);}else puts(s);}main(){g(18,72);}

Oh, well - didn't read the question properly - but given we're generating all solutions then picking a random one with equal probability is a scripting exercise :P


问:
Dig to Australia - antipodes

Background

Countless generations of children have wondered where they would end up if they dug a hole directly downwards. It turns out that this would, unsurprisingly, be rather dangerous, but anyway...

Antipodes are points that are directly opposite each other on the Earth's surface. This means that if a line was drawn between the two points, it would pass through the centre of the Earth.

Challenge

Write a program or function that, given a point, finds its antipode.

In this challenge, points are represented using the longitude-latitude system and degrees, arc minutes and arc seconds. To find the antipode, swap the directions of each ordinate (N <-> S and W <-> E) and subtract the longitude ordinate from 180 degrees.

Example:

Take the point N 50 26 23 W 4 18 29. Swap the directions to give S 50 26 23 E 4 18 29. Subtract the longitude ordinate from 180 0 0 to give 175 41 31, leaving the antipode coordinates as S 50 26 23 E 175 41 31.

Rules

Input

A set of latitude-longitude coordinates, in any reasonable format, where each ordinate contains a direction, a number of degrees, a number of arc minutes, and a number of arc seconds.

Output

The latitude-longitude coordinates of the antipode, in any reasonable format, where each ordinate contains a direction, a number of degrees, a number of arc minutes, and a number of arc seconds.

Take reasonable to mean that each part of the coordinate can be distinguished unambiguously.

Specs

The direction for the latitude ordinate is N or S, and that for the longitude ordinate is W or E.

All coordinate values are integers. The degree value will be between 0 and 90 for latitude, and between 0 and 180 for longitude. The arc minute and arc second values for both ordinates will be between 0 and 59.

If all the values for an ordinate are 0, either direction is acceptable.

There is no need to zero-pad any values.

No latitude ordinate will ever  be larger than 90 degrees, and no longitude ordinate will ever be larger than 180 degrees.

Standard loopholes apply.

Test cases

```<code>N 50 26 23 W 4 18 29 -> S 50 26 23 E 175 41 31

S 43 9 9 E 0 0 5     -> N 43 9 9 W 179 59 55

N 0 0 0 E 0 0 0      -> S/N 0 0 0 W/E 180 0 0 (either direction fine in each case)

S 1 2 3 W 4 5 6      -> N 1 2 3 E 175 54 54

S 9 21 43 W 150 7 59 -> N 9 21 43 E 29 52 1

S 27 40 2 W 23 0 0   -> N 27 40 2 E 157 0 0

N 0 58 37 W 37 0 0   -> S 0 58 37 E 143 0 0
</code>```

Useful links

Latitude and longitude

Antipodes

Arc minutes and arc seconds

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

答:
MATL, 51 bytes

```<code>'NS'tPXEii'WE'tPXE648e3i60:qXJZA-JYAtn3-?2:&)wJZAwh
</code>```

Input format:

```<code>'N'
[50 26 23]
'W'
[4 18 29]
</code>```

Output format:

```<code>S
50 26 23
E
175  41  31
</code>```

Try it online!

Explanation

```<code>'NS'tPXE     % Take input (string) implicitly. Exchange 'N' and 'S'
i            % Take input (array)
i'WE'tPXE    % Take input (string). Exchange 'W' and 'E'
648e3        % Push 648000
i            % Take input (array)
60:qXJ       % Push [0 1 ... 59]. Copy into clipboard J
ZA           % Convert second input array from base 60 to decimal
-            % Subtract
JYA          % Convert to base 60
tn3-?        % If length exceeds 3
  2:&)       %   Split into first two elements and then the rest
  w          %   Swap
  JZA        %   Convert from base 60 to decimal
  wh         %   Swap, concatenate
</code>```

Title: Dig to Australia - antipodes

Body:
MATL, 51 bytes

'NS'tPXEii'WE'tPXE648e3i60:qXJZA-JYAtn3-?2:&)wJZAwh

Input format:

'N'
[50 26 23]
'W'
[4 18 29]

Output format:

S
50 26 23
E
175  41  31

Try it online!

Explanation

'NS'tPXE     % Take input (string) implicitly. Exchange 'N' and 'S'
i            % Take input (array)
i'WE'tPXE    % Take input (string). Exchange 'W' and 'E'
648e3        % Push 648000
i            % Take input (array)
60:qXJ       % Push [0 1 ... 59]. Copy into clipboard J
ZA           % Convert second input array from base 60 to decimal
-            % Subtract
JYA          % Convert to base 60
tn3-?        % If length exceeds 3
  2:&)       %   Split into first two elements and then the rest
  w          %   Swap
  JZA        %   Convert from base 60 to decimal
  wh         %   Swap, concatenate


答:
C#, <s>310</s> 269 bytes

```<code>float[]t(string[]a,int n)=>a.Skip(n).Take(3).Select(float.Parse).ToArray();string A(string i){var s=i.Split(' ');var w=t(s,5);float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60;return(s[0][0]>82?"N":"S")+$" {string.Join(" ",t(s,1))} {(s[4][0]<70?'W':'E')} {a} {b} "+b%1*60;}
</code>```

The input is one string. You can try it on .NetFiddle.

Code

```<code>float[]t(string[]a,int n)=>a.Skip(n).Take(3).Select(float.Parse).ToArray();
string A(string i) {
    var s=i.Split(' ');var w=t(s,5);float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60;
    return (s[0][0]>82?"N":"S")
        +$" {string.Join(" ",t(s,1))} {(s[4][0]<70?'W':'E')} {a} {b} "+b%1*60;
}
</code>```

If I don't take a string as input but a char, float[], char, float[], I can do:

C#, <s>167</s> <s>166</s> <s>165</s> <s>163</s> <s>152</s> <s>148</s> <s>147</s> 139 bytes

```<code>(s,n,e,w)=>{float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60;return(s>82?"N":"S")+$" {string.Join(" ",n)} {(e<70?'W':'E')} {a} {b} "+b%1*60;};
</code>```

Code

```<code>(s,n,e,w) => {
    float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60;
    return(s>82?"N":"S")+$" {string.Join(" ",n)} {(e<70?'W':'E')} {a} {b} "+b%1*60;
};
</code>```

Also I can remove the 3600 and use ฐ instead to move to 164 characters and 166 bytes. Should I use it?

C#, 150 bytes

```<code>(s,n,m,p,e,w,x,y)=>{var t=new TimeSpan(180,0,0)-new TimeSpan(w,x,y);return(s>82?"N":"S")+$" {n} {m} {p} {(e<70?'W':'E')} {t.TotalHours} {t:%m\\ s}";};
</code>```

Code

```<code>(s,n,m,p,e,w,x,y) => {
    var z=new TimeSpan(180,0,0)-new TimeSpan(w,x,y);
     return(s>82?"N":"S")+$" {n} {m} {p} {(e<70?'W':'E')} {z.TotalHours} {z:%m\\ s}";
};
</code>```

A more .NET way! I delegate all the logic to the .NET struct TimeSpan and I <s>ab</s>use the string formatting logic. Input is char, int, int, int, char, int, int, int. I share this one to give some ideas. Maybe someone will improve in a better way than me.

Title: Dig to Australia - antipodes

Body:
Background

Countless generations of children have wondered where they would end up if they dug a hole directly downwards. It turns out that this would, unsurprisingly, be rather dangerous, but anyway...

Antipodes are points that are directly opposite each other on the Earth's surface. This means that if a line was drawn between the two points, it would pass through the centre of the Earth.

Challenge

Write a program or function that, given a point, finds its antipode.

In this challenge, points are represented using the longitude-latitude system and degrees, arc minutes and arc seconds. To find the antipode, swap the directions of each ordinate (N <-> S and W <-> E) and subtract the longitude ordinate from 180 degrees.

Example:

Take the point N 50 26 23 W 4 18 29. Swap the directions to give S 50 26 23 E 4 18 29. Subtract the longitude ordinate from 180 0 0 to give 175 41 31, leaving the antipode coordinates as S 50 26 23 E 175 41 31.

Rules

Input

A set of latitude-longitude coordinates, in any reasonable format, where each ordinate contains a direction, a number of degrees, a number of arc minutes, and a number of arc seconds.

Output

The latitude-longitude coordinates of the antipode, in any reasonable format, where each ordinate contains a direction, a number of degrees, a number of arc minutes, and a number of arc seconds.

Take reasonable to mean that each part of the coordinate can be distinguished unambiguously.

Specs

The direction for the latitude ordinate is N or S, and that for the longitude ordinate is W or E.

All coordinate values are integers. The degree value will be between 0 and 90 for latitude, and between 0 and 180 for longitude. The arc minute and arc second values for both ordinates will be between 0 and 59.

If all the values for an ordinate are 0, either direction is acceptable.

There is no need to zero-pad any values.

No latitude ordinate will ever  be larger than 90 degrees, and no longitude ordinate will ever be larger than 180 degrees.

Standard loopholes apply.

Test cases

```<code>N 50 26 23 W 4 18 29 -> S 50 26 23 E 175 41 31

S 43 9 9 E 0 0 5     -> N 43 9 9 W 179 59 55

N 0 0 0 E 0 0 0      -> S/N 0 0 0 W/E 180 0 0 (either direction fine in each case)

S 1 2 3 W 4 5 6      -> N 1 2 3 E 175 54 54

S 9 21 43 W 150 7 59 -> N 9 21 43 E 29 52 1

S 27 40 2 W 23 0 0   -> N 27 40 2 E 157 0 0

N 0 58 37 W 37 0 0   -> S 0 58 37 E 143 0 0
</code>```

Useful links

Latitude and longitude

Antipodes

Arc minutes and arc seconds

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

Body:
C#, <s>310</s> 269 bytes

float[]t(string[]a,int n)=>a.Skip(n).Take(3).Select(float.Parse).ToArray();string A(string i){var s=i.Split(' ');var w=t(s,5);float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60;return(s[0][0]>82?"N":"S")+$" {string.Join(" ",t(s,1))} {(s[4][0]<70?'W':'E')} {a} {b} "+b%1*60;}

The input is one string. You can try it on .NetFiddle.

Code

float[]t(string[]a,int n)=>a.Skip(n).Take(3).Select(float.Parse).ToArray();
string A(string i) {
    var s=i.Split(' ');var w=t(s,5);float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60;
    return (s[0][0]>82?"N":"S")
        +$" {string.Join(" ",t(s,1))} {(s[4][0]<70?'W':'E')} {a} {b} "+b%1*60;
}

If I don't take a string as input but a char, float[], char, float[], I can do:

C#, <s>167</s> <s>166</s> <s>165</s> <s>163</s> <s>152</s> <s>148</s> <s>147</s> 139 bytes

(s,n,e,w)=>{float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60;return(s>82?"N":"S")+$" {string.Join(" ",n)} {(e<70?'W':'E')} {a} {b} "+b%1*60;};

Code

(s,n,e,w) => {
    float a=180-(w[0]+w[1]/60+w[2]/3600),b=a%1*60;
    return(s>82?"N":"S")+$" {string.Join(" ",n)} {(e<70?'W':'E')} {a} {b} "+b%1*60;
};

Also I can remove the 3600 and use ฐ instead to move to 164 characters and 166 bytes. Should I use it?

C#, 150 bytes

(s,n,m,p,e,w,x,y)=>{var t=new TimeSpan(180,0,0)-new TimeSpan(w,x,y);return(s>82?"N":"S")+$" {n} {m} {p} {(e<70?'W':'E')} {t.TotalHours} {t:%m\\ s}";};

Code

(s,n,m,p,e,w,x,y) => {
    var z=new TimeSpan(180,0,0)-new TimeSpan(w,x,y);
     return(s>82?"N":"S")+$" {n} {m} {p} {(e<70?'W':'E')} {z.TotalHours} {z:%m\\ s}";
};

A more .NET way! I delegate all the logic to the .NET struct TimeSpan and I <s>ab</s>use the string formatting logic. Input is char, int, int, int, char, int, int, int. I share this one to give some ideas. Maybe someone will improve in a better way than me.


答:
Racket, 199 bytes

```<code>(λ(l)(cons(cons(if(eq?(caar l)'n)'s'n)(cdar l))(cons(if(eq?(cadr l)'e)'w'e)(list (- 180(+(caddr l)(sgn(foldl + 0(cdddr l)))))(modulo(- 60(+(fourth l)(sgn(fifth l))))60)(modulo(- 60(fifth l))60)))))
</code>```

That's horribly long.  There's probably some things I could do to shorten it further, but shudders I'm completely done.

Takes a cons pair of two lists: one for the latitude and one for the longitude.  Each list has the direction (as a lowercase Racket symbol) as its first item and following it the degrees, arc-minutes, and arc-seconds.  Outputs in the same format

Racket will interpret this pair of two lists as a single list with another list as its first element.  This is perfectly fine, since you can still access both latitude and longitude as if they were two lists in a pair.

Usage:

```<code>>    (
     (λ(l)(cons(cons(if(eq?(caar l)'n)'s'n)(cdar l))(cons(if(eq?(cadr l)'e)'w'e)(list (- 180(+(caddr l)(sgn(foldl + 0(cdddr l)))))(modulo(- 60(+(fourth l)(sgn(fifth l))))60)(modulo(- 60(fifth l))60)))))
     (cons (list 's 43 9 9) (list 'e 0 0 5)))
'((n 43 9 9) w 179 59 55)
</code>```

Which can be interpreted by future code as '((n 43 9 9) (w 179 59 55)), two lists.

Title: Dig to Australia - antipodes

Body:
Racket, 199 bytes

(λ(l)(cons(cons(if(eq?(caar l)'n)'s'n)(cdar l))(cons(if(eq?(cadr l)'e)'w'e)(list (- 180(+(caddr l)(sgn(foldl + 0(cdddr l)))))(modulo(- 60(+(fourth l)(sgn(fifth l))))60)(modulo(- 60(fifth l))60)))))

That's horribly long.  There's probably some things I could do to shorten it further, but shudders I'm completely done.

Takes a cons pair of two lists: one for the latitude and one for the longitude.  Each list has the direction (as a lowercase Racket symbol) as its first item and following it the degrees, arc-minutes, and arc-seconds.  Outputs in the same format

Racket will interpret this pair of two lists as a single list with another list as its first element.  This is perfectly fine, since you can still access both latitude and longitude as if they were two lists in a pair.

Usage:

>    (
     (λ(l)(cons(cons(if(eq?(caar l)'n)'s'n)(cdar l))(cons(if(eq?(cadr l)'e)'w'e)(list (- 180(+(caddr l)(sgn(foldl + 0(cdddr l)))))(modulo(- 60(+(fourth l)(sgn(fifth l))))60)(modulo(- 60(fifth l))60)))))
     (cons (list 's 43 9 9) (list 'e 0 0 5)))
'((n 43 9 9) w 179 59 55)

Which can be interpreted by future code as '((n 43 9 9) (w 179 59 55)), two lists.


答:
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:

```<code>~1\{~&.},p;
</code>```

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

De-golfed version with comments:

```<code>~     # 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
</code>```

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.

Title: Implement Takewhile

Body:
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.


答:
Pyth, <s>41</s> <s>45</s> <s>43</s> 35 bytes

```<code>K60-"NS"ww-"EW"wA.D-*3^K3iEKK+.DGKH
</code>```

Uses base-60 conversion to turn degrees and minutes into seconds.

I/O format:

```<code>N
[1,2,3]
E
[4,5,6]
</code>```

It prints a line every time you input a line, so to have a good-looking format, you can either use the CLI and pipe the input, or more conveniently, use the online Pyth implementation.

In pseudocode:

```<code>K60                                              K = 60
   -"NS"w                                        "NS".remove(input())
         w                                       print(input())
          -"EW"w                                 "EW".remove(input())
                A.D                              G,H = divmod(
                   -*3^K3                          3*K**3 -
                         iEK                         baseToDec(input(),K)),
                            K                      K)
                             +.DGKH              divmod(G,K)+H
</code>```

Title: Dig to Australia - antipodes

Body:
Pyth, <s>41</s> <s>45</s> <s>43</s> 35 bytes

K60-"NS"ww-"EW"wA.D-*3^K3iEKK+.DGKH

Uses base-60 conversion to turn degrees and minutes into seconds.

I/O format:

N
[1,2,3]
E
[4,5,6]

It prints a line every time you input a line, so to have a good-looking format, you can either use the CLI and pipe the input, or more conveniently, <a href="http://pyth.herokuapp.com/?code=K60-%22NS%22ww-%22EW%22wA.D-%2a3%5EK3iEKK%2B.DGKH&input=N%0A%5B3%2C2%2C1%5D%0AE%0A%5B7%2C5%2C4%5D&test_suite=1&test_suite_input=N%0A%5B50%2C26%2C23%5D%0AW%0A%5B4%2C18%2C29%5D%0AS%0A%5B43%2C9%2C9%5D%0AE%0A%5B0%2C0%2C5%5D%0AN%0A%5B0%2C0%2C0%5D%0AE%0A%5B0%2C0%2C0%5D%0AS%0A%5B1%2C2%2C3%5D%0AW%0A%5B4%2C5%2C6%5D%0AS%0A%5B9%2C21%2C43%5D%0AW%0A%5B150%2C7%2C59%5D%0AS%0A%5B27%2C40%2C2%5D%0AW%0A%5B23%2C0%2C0%5D%0AN%0A%5B0%2C58%2C37%5D%0AW%0A%5B37%2C0%2C0%5D&debug=0&input_size=4" rel="nofollow">use the online Pyth implementation.

In pseudocode:

K60                                              K = 60
   -"NS"w                                        "NS".remove(input())
         w                                       print(input())
          -"EW"w                                 "EW".remove(input())
                A.D                              G,H = divmod(
                   -*3^K3                          3*K**3 -
                         iEK                         baseToDec(input(),K)),
                            K                      K)
                             +.DGKH              divmod(G,K)+H


答:
JavaScript (ES6), 88 bytes

```<code>(a,b,c,d,e,f,g,h)=>[a<'S'?'S':'N',b,c,d,e<'W'?'W':'E',!(g|h)+179-f,g|h&&!h+59-g,h&&60-h]
</code>```

Takes 8 parameters and returns an array as the result. Expects a to be one of N or S and similarly e to be one of W or E. Calculations:

f needs to be subtracted from 179 if either g or h is nonzero but 180 if both g and h are zero (because there is no borrow), thus !(g|h) is added to the 179.

g needs to be zero if both g and h are zero, thus g|h&&, otherwise it needs to be subtracted from 59 if h is nonzero but 60 if h is zero (because there is no borrow), thus !h is added to the 59.

h needs to be zero if it was already zero, otherwise it is simply subtracted from 60.

Another way to look at this is to notice that subtracting in binary is achieved by adding the 1s complement plus an additional 1. Translated to this problem, we take 179-f, 59-g and 59-h and add 1. 59-h + 1 is 60-h, but if this is 60 then it carries, so the desired result is zero if h was originally zero. We add 1 to 59-g if there's a carry from h, i.e. if h was originally zero. Again we have to allow for a carry, which this time happens if both g and h are zero, and we add 1 to 179-f in this case.

Title: Dig to Australia - antipodes

Body:
JavaScript (ES6), 88 bytes

(a,b,c,d,e,f,g,h)=>[a<'S'?'S':'N',b,c,d,e<'W'?'W':'E',!(g|h)+179-f,g|h&&!h+59-g,h&&60-h]

Takes 8 parameters and returns an array as the result. Expects a to be one of N or S and similarly e to be one of W or E. Calculations:

f needs to be subtracted from 179 if either g or h is nonzero but 180 if both g and h are zero (because there is no borrow), thus !(g|h) is added to the 179.

g needs to be zero if both g and h are zero, thus g|h&&, otherwise it needs to be subtracted from 59 if h is nonzero but 60 if h is zero (because there is no borrow), thus !h is added to the 59.

h needs to be zero if it was already zero, otherwise it is simply subtracted from 60.

Another way to look at this is to notice that subtracting in binary is achieved by adding the 1s complement plus an additional 1. Translated to this problem, we take 179-f, 59-g and 59-h and add 1. 59-h + 1 is 60-h, but if this is 60 then it carries, so the desired result is zero if h was originally zero. We add 1 to 59-g if there's a carry from h, i.e. if h was originally zero. Again we have to allow for a carry, which this time happens if both g and h are zero, and we add 1 to 179-f in this case.