答:
ES6, 89 bytes

```<code>d=>fetch('http://enwp.org/'+d).then(r=>r.text().then(t=>alert(t.split`Canada`.length-1)))
</code>```

Sadly Unwrapping all the promises penalises the size :/

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:
ES6, 89 bytes

d=>fetch('http://enwp.org/'+d).then(r=>r.text().then(t=>alert(t.split`Canada`.length-1)))

Sadly Unwrapping all the promises penalises the size :/


问:
Implement bag operations
A bag, also called a multiset, is an unordered collection. You can call it a set that allows duplicates, or a list (or an array) that is not ordered/indexed. In this challenge, you are asked to implement bag operations: addition, difference, multiplication, division, counting and equality test.

Operations

The specified operations may not be conventional.

addition combines two bags into one, conserving the total number of each value

[1,2,2,3] + [1,2,4] = [1,1,2,2,2,3,4]

difference removes from a bag each element of another bag, or does nothing if no such element

[1,2,2,4] - [1,2] = [2,4]  [1,2,3] - [2,4] = [1,3]

multiplication multiplies each element in the bag.

[1,2,3,3,4] * 3 = [1,1,1,2,2,2,3,3,3,3,3,3,4,4,4] 2 * [1,3] = [1,1,3,3]

division is an uncommon one: each n equal elements are put in n equal new bags, elements that cannot form an n-group remain in the bag. Return any one of the n new bags.

[1,1,2,2,2] / 2 = [1,2] [1,2,2,3,3,3] / 3 = [3]

counting counts how many divisor bags can be produced from the dividend bag

[1,1,2,2,2,2,3,3,3] c [1,2,3] = 2

equality test checks if two bags have the same numbers of each element

[1,2,2,3] == [3,2,1,2] = truthy [1,2,3] == [1,2,2,3] = falsy (can also use = for this)

If you are using your own symbols for the operators, please specify.

Formats

Bags will be displayed as lists of the form [1,1,2,3,4]. You can use any other bracket than square ones, or even use quotes, or nothing at all. The elements will be integers(mathematically, not necessarily int) for the purpose of this question. Bags do not have to be sorted.

The input format will be two bags or a bag and an integer, with an operator. You can specify your own format as long as it contains these three.

The output format should be a single bag of the same format.

Rules

you may not use built-in functions, operations or libraries (including the standard library) that already implement these; it's ok though to use list concatenation and multiplication since they are by definition list operations, not bag operations (which happen to basically do the same thing)

standard loopholes apply

shortest answer wins

Test cases

```<code>[1,2,2,3] + [1,2,4]
[1,1,2,2,2,3,4]

[1,2,2,4] - [1,2]
[2,4]

[1,2,3] - [2,4]
[1,3]

[1,2,3,3,4] * 3
[1,1,1,2,2,2,3,3,3,3,3,3,4,4,4]

2 * [1,3]
[1,1,3,3]

[1,1,2,2,2] / 2
[1,2]

[1,2,2,3,3,3] / 3
[3]

[1,1,2,2,2,2,3,3,3] c [1,2,3]
2

[3,2,1,2] == [1,2,2,3]
truthy

[1,2,3] == [1,2,2,3]
falsy
</code>```

答:
Ruby, 201 bytes

As promised in my other answer, here's one that uses functions instead of building a new class. I'm so close to breaching the 200 byte mark... Try it online

This uses the same opcodes as @Neil in his JavaScript answer, and the same order of arguments (lhs, opcode, rhs)

```<code>0: Addition
1: Difference
2: Multiplication
3: Division
4: Counting
5: Equality
</code>```

The code:

```<code>->x,o,y{[->{(x+y).sort},->r=[*x]{y.map{|i|r[r.index(i)||x.size]=p};r-[p]},->{(x==[*x]?x*y :y*x).sort},->{x.uniq.map{|i|[i]*(x.count(i)/y)}.flatten},->{y.map{|i|x.count i}.min},->{x.sort==y.sort}][o][]}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Implement bag operations

Body:
Ruby, 201 bytes

As promised in my other answer, here's one that uses functions instead of building a new class. I'm so close to breaching the 200 byte mark... Try it online

This uses the same opcodes as @Neil in his JavaScript answer, and the same order of arguments (lhs, opcode, rhs)

0: Addition
1: Difference
2: Multiplication
3: Division
4: Counting
5: Equality

The code:

->x,o,y{[->{(x+y).sort},->r=[*x]{y.map{|i|r[r.index(i)||x.size]=p};r-[p]},->{(x==[*x]?x*y :y*x).sort},->{x.uniq.map{|i|[i]*(x.count(i)/y)}.flatten},->{y.map{|i|x.count i}.min},->{x.sort==y.sort}][o][]}


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

答:
Clojure - 72 chars

(some #(if(=(apply +%)72)%)(partition 18(repeatedly #(+(rand-int 3)3))))

Would be much shorter if Clojure didn't have such flowery descriptive function names :-)

Title: Can you Golf Golf?


问:
Leave a Comment
Task:

Make a program that leaves a comment on this question. The content should be 1234567890123456.

Edits:

You may leave your usernames and passwords as U and P if you are
using username and password. (if applicable)

No URL Shorteners (if applicable)

You may not use the browser console.

答:
Python 3.5 with Selenium Webdriver, <s>485</s> <s>427</s> <s>469</s> <s>461</s> <s>449</s> <s>414</s> 403 bytes:

from selenium.webdriver import*;import time;D=Chrome();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit()
```
<p>A full program utilizing a simple Python selenium web driver solution. Works in Chrome, although it needs ChromeDriver installed to work. Works by renaming <code>U</code> and <code>P</code> to the user's Stack Exchange email and password, respectively. However, if there are any issues getting ChromeDriver installed, here is a FireFox solution that gets executed in the exact same manner as the above solution and does not need any drivers, although it is currently 1 byte longer at <strong><s>414</s> 404 bytes</strong>:</p>
<pre class="lang-python prettyprint-override"><code>from selenium.webdriver import*;import time;D=Firefox();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit()
</code>```

Also, if a function is wanted, here is a solution using an anonymous lambda function, currently standing at <s>513</s> <s>455</s> <s>497</s> <s>489</s> <s>477</s> <s>449</s> 431 bytes and using Chrome as the browser.

lambda U,P:exec("from selenium.webdriver import*;import time;D=Chrome();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit()",locals())
```
<p>However, if there are, again, any issues regarding ChromeDriver, here is the same type of solution but this time using Firefox, currently standing at <strong><s>442</s> 432 bytes</strong>:</p>
<pre class="lang-python prettyprint-override"><code>lambda U,P:exec("from selenium.webdriver import*;import time;D=Firefox();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit()",locals())
</code>```

You call these lambda functions by simply renaming the function as anything valid and then calling with your email and password like a normal function. For instance, if the function were named H, you would call it like H(Email, Password).

ContentLicense: CC BY-SA 4.0

Title: Leave a Comment

Body:
Python 3.5 with Selenium Webdriver, <s>485</s> <s>427</s> <s>469</s> <s>461</s> <s>449</s> <s>414</s> 403 bytes:

from selenium.webdriver import*;import time;D=Chrome();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit()

A full program utilizing a simple Python selenium web driver solution. Works in Chrome, although it needs ChromeDriver installed to work. Works by renaming U and P to the user's Stack Exchange email and password, respectively. However, if there are any issues getting ChromeDriver installed, here is a FireFox solution that gets executed in the exact same manner as the above solution and does not need any drivers, although it is currently 1 byte longer at <s>414</s> 404 bytes:

from selenium.webdriver import*;import time;D=Firefox();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit()

Also, if a function is wanted, here is a solution using an anonymous lambda function, currently standing at <s>513</s> <s>455</s> <s>497</s> <s>489</s> <s>477</s> <s>449</s> 431 bytes and using Chrome as the browser.

lambda U,P:exec("from selenium.webdriver import*;import time;D=Chrome();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit()",locals())

However, if there are, again, any issues regarding ChromeDriver, here is the same type of solution but this time using Firefox, currently standing at <s>442</s> 432 bytes:

lambda U,P:exec("from selenium.webdriver import*;import time;D=Firefox();I=lambda k:D.find_element_by_name(k);C='comment';D.get('http://www.codegolf.stackexchange.com/users/login');I('email').send_keys(U);Z=I('password');Z.send_keys(P);Z.submit();D.get('http://www.codegolf.stackexchange.com/questions/84546');D.find_element_by_link_text('add a '+C).click();E=I(C);E.send_keys('1234567890123456');time.sleep(1);E.submit()",locals())

You call these lambda functions by simply renaming the function as anything valid and then calling with your email and password like a normal function. For instance, if the function were named H, you would call it like H(Email, Password).


问:
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>```

答:
JavaScript, 29 bytes

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

or

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

How it works (1st version)

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

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

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

Title: Implement Takewhile


问:
Print a table of numbers in decimal and 2**i bases
Computers live by binary. All programmers know binary.

But the 2**x bases are often neglected as non-practical, while they have beautiful relations to binary.

To show you one example of such a beatiful relation, 19 will be my testimonial.

```<code>19 10011 103 23 13 j
</code>```

19 is decimal, included for clarity.

10011 is 19 in binary.

103, in base 4 is made starting from binary this way:

log2(4) == 2, let us remember two.

Pad 10011 so that it has a multiple of 2 length -> 010011

Take digits 2 by 2 from left to right and treat them as 2-digits binary numbers:

01 -> 1

00 -> 0

11 -> 3

Done, 10011 in base-4 is 103.

For base 8, do the same but 3-by-3 as log2(8) = 3.

Pad 010011

010 -> 2

011 -> 3

23, Done.

For base 16, do the same but 4-by-4 as log2(16) = 4.

Pad 00010011

0001 -> 1

0011 -> 3

13, Done.

Task

Given a max number as input, you shall output a table

```<code>base-ten-i base-two-i base-four-i base-eight-i base-sixteen-i base-thirtytwo-i
</code>```

for i that goes from 0 to n inclusive. Binary numbers are the epitome of the absolute minimum needed to work, so your code should be as short as possible.

Restrictions and bonuses

Base-ten -> binary and binary -> Base-ten built-ins are considered loopholes as Base-a -> Base-b are.

If you generate all the 2**i (for i > 2) bases by using the relations over mentioned you get a *0.6 bonus, but general base conversions (written by yourself) are allowed.

Example table

```<code>> 32
0 0 0 0 0 0
1 1 1 1 1 1
2 10 2 2 2 2
3 11 3 3 3 3
4 100 10 4 4 4
5 101 11 5 5 5
6 110 12 6 6 6
7 111 13 7 7 7
8 1000 20 10 8 8
9 1001 21 11 9 9
10 1010 22 12 a a
11 1011 23 13 b b
12 1100 30 14 c c
13 1101 31 15 d d
14 1110 32 16 e e
15 1111 33 17 f f
16 10000 100 20 10 g
17 10001 101 21 11 h
18 10010 102 22 12 i
19 10011 103 23 13 j
20 10100 110 24 14 k
21 10101 111 25 15 l
22 10110 112 26 16 m
23 10111 113 27 17 n
24 11000 120 30 18 o
25 11001 121 31 19 p
26 11010 122 32 1a q
27 11011 123 33 1b r
28 11100 130 34 1c s
29 11101 131 35 1d t
30 11110 132 36 1e u
31 11111 133 37 1f v
32 100000 200 40 20 10
</code>```

Body:
Ruby, 80 bytes (non-bonus version)

m=ARGV[0].to_i;(0..m).each{|n|puts [10,2,4,8,16,32].map{|b|n.to_s(b)}.join(' ')}


问:
Where should I put my mirror?
This is a mirror: |. I just found out that you can stick a mirror in the middle of a string if the string can be mirrored on itself! For example, the string abccba. If you cut it in half the two halves are mirror images of each other:

```<code>abc  <-->  cba
</code>```

So, we can stick a mirror in the middle of the string, and our new string is abc|cba. Sometimes, only part of the string can be mirrored on itself. For example, the string "mirror". The two r's are mirrored, but the rest of the string isn't. That's OK, we'll just remove the parts of the string that don't mirror each other, and we get the following string:

```<code>r|r
</code>```

Some strings could be mirrored in multiple places. For example, "Hello World, xyzzyx". I like having a lot of text reflected in my mirror, so you need to find the best place to put my mirror. In this case, you should output the longer mirrored string and just like our last example, remove everything else. This string becomes:

```<code>xyz|zyx
</code>```

Some strings look like they can be mirrored, but actually can not. If a string cannot be mirrored anywhere, you should output nothing.

The challenge:

Given a string containing only printable-ascii, find the best place to put my mirror. In other words,

Find the largest even-length palindromic substring, then output it with a pipe character '|' in the middle of it.

The input will be 1-50 characters long.

You can assume that the input will not contain mirrors | or newlines. Beyond that, all printable-ascii characters are fair game. If the longest mirrored substring is tied between two substrings, you can choose which one to output. For example, for the string "abba ollo", you must output "ab|ba" or "ol|lo", but it doesn't matter which one you output. Strings are case-sensitive, e.g. "ABba" should not output "AB|ba", it should output the empty string.

Sample IO:

```<code>"Hello World"     --> "l|l"
"Programming Puzzles and Code-Golf"     --> Either "m|m" or "z|z"
"abcba"           --> ""
"Hulluh"          --> "ul|lu"
"abcdefggfedcba"  --> "abcdefg|gfedcba"
"abcdefggfabc"    --> "fg|gf"
"AbbA"            --> "Ab|bA"
"This input is a lot like the last one, but with more characters that don't change the output. AbbA" --> "Ab|bA"
</code>```

As usual, this is code-golf, so standard loopholes apply, and the shortest answer in bytes wins!

答:
Python 2, 91 bytes

f=lambda s,p='':s and max((''<p<=s<p+'\x7f')*(p[::-1]+'|'+p),f(s[1:]),f(s[1:],s[0]+p),key=len)
```

Replace \x7f with the actual character DEL, which is ASCII 127 (credit to Dennis).

This follows a similar strategy to Dennis's answer of using max and recursively branching to find the longest palindrome interval. But, instead, it finds the left half, checking that the corresponding mirrored right half comes right after it with a self-made startswith.

The function guesses whether the first character is in the mirrored left half. If not, it just drops it and recurses on the remainder. If it is, it's added to to the stack p of reversed characters. If the string ever starts with the stack, the mirror string is generated and considered as a possible longest mirror. To avoid | as an output, only non-empty stacks are considered.

Title: Where should I put my mirror?

Body:
Python 2, 91 bytes

f=lambda s,p='':s and max((''<p<=s<p+'\x7f')*(p[::-1]+'|'+p),f(s[1:]),f(s[1:],s[0]+p),key=len)

Replace \x7f with the actual character DEL, which is ASCII 127 (credit to Dennis).

This follows a similar strategy to Dennis's answer of using max and recursively branching to find the longest palindrome interval. But, instead, it finds the left half, checking that the corresponding mirrored right half comes right after it with a self-made startswith.

The function guesses whether the first character is in the mirrored left half. If not, it just drops it and recurses on the remainder. If it is, it's added to to the stack p of reversed characters. If the string ever starts with the stack, the mirror string is generated and considered as a possible longest mirror. To avoid | as an output, only non-empty stacks are considered.


答:
Minkolang 0.15, 12 bytes

```<code>nd2%,5&xr$N.
</code>```

Try it here!

Explanation

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

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

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:
Minkolang 0.15, 12 bytes

nd2%,5&xr$N.

Try it here!

Explanation

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

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


问:
Print a Lego piece
This challenge is a simple ascii-art one. Given two inputs, describing the height and width of a Lego piece, you have print an ASCII art representation of it.

Here is how the Lego pieces are supposed to look:

```<code>(4, 2)

___________
| o o o o |
| o o o o |
-----------

(8, 2)

___________________
| o o o o o o o o |
| o o o o o o o o |
-------------------

(4, 4)

___________
| o o o o |
| o o o o |
| o o o o |
| o o o o |
-----------

(3, 2)

_________
| o o o |
| o o o |
---------

(1, 1)

o
</code>```

If you can't tell from the test-cases, the top and bottom are width*2+3 underscores and dashes, and each row has pipes for the sides, o's for the little things, and everything is separated by spaces.

The only exception for this is (1, 1), which is just a single o.

You will never get 0 for any of the dimensions.

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

var QUESTION_ID=84050,OVERRIDE_USER=31343;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Befunge, 144 Bytes

I would have prefered to comment to this post, but I don't have the reputation yet, so I'm putting an answer of my own, which works a similar way, but is slightly more compact

```<code>&::&*:1`v
v3*2:\/\_"o",@
>+:  v   >52*," |",, v
>,1-:vLEG O MAKERv::\<
^"_" _$\:|<v "o "_v
v52:+3*2$<,>,,1-:^$
>*,v <    ^"|":-1\<
v-1_@,
>:"-"^
</code>```

you can test the code here

Title: Print a Lego piece

Body:
Befunge, 144 Bytes

I would have prefered to comment to this post, but I don't have the reputation yet, so I'm putting an answer of my own, which works a similar way, but is slightly more compact

&::&*:1`v
v3*2:\/\_"o",@
>+:  v   >52*," |",, v
>,1-:vLEG O MAKERv::\<
^"_" _$\:|<v "o "_v
v52:+3*2$<,>,,1-:^$
>*,v <    ^"|":-1\<
v-1_@,
>:"-"^

you can test the code here


答:
ed, 13

```<code>/[13579]$/,$d
</code>```

Because real programmers use The Standard Text Editor.

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

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

Title: Implement Takewhile

Body:
ed, 13

/[13579]$/,$d

Because real programmers use The Standard Text Editor.

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

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


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

答:
Python 2, <s>140</s> 122 bytes

Updated:

def f(c):x=([180,0,0],[179,59,60])[1<sum(c[6:8])];print['NS'['N'in c]]+c[1:4]+['EW'['E'in c]]+map(lambda x,y:x-y,x,c[5:8])
```

<p>This uses a slightly different approach: setting the values to subtract from the longitude based on the minutes and seconds. If there are 0 mins and seconds, it subtracts 180 from the degrees, and if there are >0 mins and secs, it subtracts 179, 59, and 60 from the d, m, s respectively.</p>

<p>Original:</p>

<pre class="lang-python prettyprint-override"><code>def f(c):v=divmod;m,s=v((180-(c[5]+c[6]/60.+c[7]/3600.))*3600,60);d,m=v(m,60);print['NS'['N'in c]]+c[1:4]+['EW'['E'in c]]+map(round,[d,m,s])
</code>```

Takes input as a list: f(['N', 0, 0, 0, 'E', 0, 0, 0]), converts the longitude to decimal degrees, subtracts from 180, then converts back to degrees, minutes, seconds and re-constructs the list, flipping the directions in the process.

Un-golfed:

def f(c):
    minutes,seconds=divmod((180-(c[5]+c[6]/60.+c[7]/3600.))*3600,60)
    degrees,minutes=divmod(minutes,60)
    print ['NS'['N'in c]]+c[1:4]+['EW'['E'in c]]+map(round,[degrees,minutes,seconds])
```

Try it

Title: Dig to Australia - antipodes

Body:
Python 2, <s>140</s> 122 bytes

Updated:

def f(c):x=([180,0,0],[179,59,60])[1<sum(c[6:8])];print['NS'['N'in c]]+c[1:4]+['EW'['E'in c]]+map(lambda x,y:x-y,x,c[5:8])

This uses a slightly different approach: setting the values to subtract from the longitude based on the minutes and seconds. If there are 0 mins and seconds, it subtracts 180 from the degrees, and if there are >0 mins and secs, it subtracts 179, 59, and 60 from the d, m, s respectively.

Original:

def f(c):v=divmod;m,s=v((180-(c[5]+c[6]/60.+c[7]/3600.))*3600,60);d,m=v(m,60);print['NS'['N'in c]]+c[1:4]+['EW'['E'in c]]+map(round,[d,m,s])

Takes input as a list: f(['N', 0, 0, 0, 'E', 0, 0, 0]), converts the longitude to decimal degrees, subtracts from 180, then converts back to degrees, minutes, seconds and re-constructs the list, flipping the directions in the process.

Un-golfed:

def f(c):
    minutes,seconds=divmod((180-(c[5]+c[6]/60.+c[7]/3600.))*3600,60)
    degrees,minutes=divmod(minutes,60)
    print ['NS'['N'in c]]+c[1:4]+['EW'['E'in c]]+map(round,[degrees,minutes,seconds])

Try it


答:
Javascript with jQuery, 127 bytes

$.post("//codegolf.stackexchange.com/posts/84546/comments",{comment:"1234567890123456",fkey:StackExchange.options.user.fkey})
```
<p>Thanks to Ismael Miguel and nicael for a few bytes.</p>
<p>The <code>fkey</code> parameter is unique to your account, and can be found by examining local storage contents of your browser with a StackExchange page open. This code must be run in a browser with an open StackExchange session present. It automatically loads the <code>fkey</code> parameter from the browser's local storage (previous versions of this submission required it to be manually entered).</p>
<p>Unfortunately, the <code>ppcg.lol</code> URL can't be used, because it doesn't pass POST requests through.</p>
<p>Fun fact: if you attempt to run this code without the proper <code>fkey</code> value, you get an HTTP 418 response:</p>
<p><img src="https://i.stack.imgur.com/rX32H.png" alt="teapot" /></p>
<p>Example of how to find the <code>fkey</code> value in Chrome:</p>
<p><img src="https://i.stack.imgur.com/8lerc.png" alt="fkey" /></p>
<p>Apparently Winterbash stuff is still being stored. Neat.</p>
<p>For reference, the same thing in vanilla Javascript would be 314 bytes (thanks again to Ismael Miguel and nicael for some bytes off):</p>
<pre class="lang-js prettyprint-override"><code>with(new XMLHttpRequest()){
open("POST","//codegolf.stackexchange.com/posts/84546/comments",1)
setRequestHeader("Content-type","application/x-www-form-urlencoded")
setRequestHeader("Content-length",62)
setRequestHeader("Connection","close")
send("comment=1234567890123456&fkey="+StackExchange.options.user.fkey}))}
</code>```

Title: Leave a Comment

Body:
Task:

Make a program that leaves a comment on this question. The content should be 1234567890123456.

Edits:

You may leave your usernames and passwords as U and P if you are
using username and password. (if applicable)

No URL Shorteners (if applicable)

You may not use the browser console.

Body:
Javascript with jQuery, 127 bytes

$.post("//codegolf.stackexchange.com/posts/84546/comments",{comment:"1234567890123456",fkey:StackExchange.options.user.fkey})

Thanks to Ismael Miguel and nicael for a few bytes.

The fkey parameter is unique to your account, and can be found by examining local storage contents of your browser with a StackExchange page open. This code must be run in a browser with an open StackExchange session present. It automatically loads the fkey parameter from the browser's local storage (previous versions of this submission required it to be manually entered).

Unfortunately, the ppcg.lol URL can't be used, because it doesn't pass POST requests through.

Fun fact: if you attempt to run this code without the proper fkey value, you get an HTTP 418 response:

Example of how to find the fkey value in Chrome:

Apparently Winterbash stuff is still being stored. Neat.

For reference, the same thing in vanilla Javascript would be 314 bytes (thanks again to Ismael Miguel and nicael for some bytes off):

with(new XMLHttpRequest()){
open("POST","//codegolf.stackexchange.com/posts/84546/comments",1)
setRequestHeader("Content-type","application/x-www-form-urlencoded")
setRequestHeader("Content-length",62)
setRequestHeader("Connection","close")
send("comment=1234567890123456&fkey="+StackExchange.options.user.fkey}))}


答:
AppleScript with Safari, <s>269</s> 287 bytes

```<code>tell application "Safari"
activate
tell window 1
set current tab to (make new tab with properties {URL:"http://codegolf.stackexchange.com/q/84546"})
delay 5
do JavaScript "$('a')[66].click();$('textarea')[0].val('1234567890123456');$('input')[5].click()" in current tab
end tell
end tell
</code>```

To use this you need to enable Safari Developer Settings and then enable Allow JavaScript from Apple Events. I'm not sure if it's cheating or not to use the existing keychain + cookies but oh well.

I also managed to do this in OSX's Automator by just automating the clicks and keystrokes however I didn't think it stayed true to the idea of the challenge

Title: Leave a Comment

Body:
AppleScript with Safari, <s>269</s> 287 bytes

tell application "Safari"
activate
tell window 1
set current tab to (make new tab with properties {URL:"http://codegolf.stackexchange.com/q/84546"})
delay 5
do JavaScript "$('a')[66].click();$('textarea')[0].val('1234567890123456');$('input')[5].click()" in current tab
end tell
end tell

To use this you need to enable Safari Developer Settings and then enable Allow JavaScript from Apple Events. I'm not sure if it's cheating or not to use the existing keychain + cookies but oh well.

I also managed to do this in OSX's Automator by just automating the clicks and keystrokes however I didn't think it stayed true to the idea of the challenge


答:
Clojure - 55

```<code>(shuffle(mapcat #([[4 4][3 5]%](rand-int 2))(range 9)))
</code>```

Quite a fun trick.... exploits the mathematical structure of the problem that there must be exactly as many 3 par holes as 5 par holes.

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:
Clojure - 55

(shuffle(mapcat #([[4 4][3 5]%](rand-int 2))(range 9)))

Quite a fun trick.... exploits the mathematical structure of the problem that there must be exactly as many 3 par holes as 5 par holes.


答:
Python, 43 bytes

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

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

Title: Implement Takewhile

Body:
Python, 43 bytes

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

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


问:
Help me figure out what TeX I can use!
On TeX.SE the Help Centre says that the following is on topic:

```<code>Formats like LaTeX, ConTeXt and plain TeX
Engines like pdfTeX, LuaTeX and XeTeX
Distributions like TeX Live, MiKTeX, and MacTeX
Related software and tools, BibTeX, MakeIndex, Lyx, etc.
</code>```

I wanted you to write a program to tell me whether my TeX is in the on-topic types of TeX.

An explicit list of the valid TeX-s is as follows:

MetaPost

PostScript

MetaFUN

TeX

LaTeX

LuaLaTeX

LuaTeX

ConTeXt

BibTeX

pdfTeX

Lyx

MakeIndex

TeX Live

XeLaTeX

XeTeX

MacTeX

MiKTeX

Rules

You may use any language.

This is code-golf, to the shortest answer wins.

If you use Regex, you can just match correct ones.

You only need to match one at a time: no

Lyx
BibTeX

You must check with capitalization listed here.

Tests

```<code>TeX -> True/1/<match>
pTeX -> False/0/<not-match>
ConTeXt -> True/1/<match>
context -> False/0/<not-match>
MetaFun -> False/0/<not-match>
MetaFUN -> True/1/<match>
</code>```

P.S. Bonus points for an on-topic TeX answer!

答:
Python 3.5, <s>149</s> <s>147</s> <s>137</s> 136 bytes

import re;lambda f:re.fullmatch('TeX Live|(La|LuaLa|Lua|Bib|pdf|XeLa|Xe|Mac|MiK)?TeX|Lyx|MakeIndex|Meta(Post|FUN)|PostScript|ConTeXt',f)
```

An anonymous function that uses a regular expression to return a re match object (such as <_sre.SRE_Match object; span=(0, 5), match='LaTeX'>) as a truthy value and None as a falsy value. The actual regular expression is currently <s>102</s> <s>100</s> 99 bytes in length.

Try It Online! (Ideone)

Title: Help me figure out what TeX I can use!

Body:
Python 3.5, <s>149</s> <s>147</s> <s>137</s> 136 bytes

import re;lambda f:re.fullmatch('TeX Live|(La|LuaLa|Lua|Bib|pdf|XeLa|Xe|Mac|MiK)?TeX|Lyx|MakeIndex|Meta(Post|FUN)|PostScript|ConTeXt',f)

An anonymous function that uses a regular expression to return a re match object (such as <_sre.SRE_Match object; span=(0, 5), match='LaTeX'>) as a truthy value and None as a falsy value. The actual regular expression is currently <s>102</s> <s>100</s> 99 bytes in length.

Try It Online! (Ideone)


答:
Python, 41 bytes

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

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

Title: Implement Takewhile

Body:
Python, 41 bytes

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

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


答:
Julia, 24 bytes

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

Try it online!

Title: Implement Takewhile

Body:
Julia, 24 bytes

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

Try it online!


答:
Python 3, <s>131</s> 130 bytes

```<code>def f(w,x,y,z):S=60;d=divmod;a,b,c=y;l,m=d(648e3-c-S*b-S*S*a,S);return w,"N" if x=="S" else "S",d(l,S)+(m,),"E" if z=="W" else "W"
</code>```

Formats: angles are tuples of the form (deg,min,sec), directions are of the form N. Outputs a quadruple of 2 angles, each followed by its direction.

Ungolfed version:

```<code>def f(latitude,NS,longitude,EW):
    degree,minute,second=longitude
    minute,second=divmod(648000-second-60*minute-60*60*degree,60)
    return latitude, "N" if NS=="S" else "S", divmod(minute,60)+(second,), "E" if EW=="W" else "W"
</code>```

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:
Python 3, <s>131</s> 130 bytes

def f(w,x,y,z):S=60;d=divmod;a,b,c=y;l,m=d(648e3-c-S*b-S*S*a,S);return w,"N" if x=="S" else "S",d(l,S)+(m,),"E" if z=="W" else "W"

Formats: angles are tuples of the form (deg,min,sec), directions are of the form N. Outputs a quadruple of 2 angles, each followed by its direction.

Ungolfed version:

def f(latitude,NS,longitude,EW):
    degree,minute,second=longitude
    minute,second=divmod(648000-second-60*minute-60*60*degree,60)
    return latitude, "N" if NS=="S" else "S", divmod(minute,60)+(second,), "E" if EW=="W" else "W"


问:
Add two numbers
Input: Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Output: Their sum. Use the same format for output integers as input integers. For example, the input 5 16 would lead to the output 21.

Restrictions: No standard loopholes please. This is code-golf, answer in lowest amount of bytes wins.

Notes: This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is.

Test cases:

```<code>1 2 -> 3
14 15 -> 29
7 9 -> 16
-1 8 -> 7
8 -9 -> -1
-8 -9 -> -17
</code>```

Or as CSV:

```<code>a,b,c
1,2,3
14,15,29
7,9,16
-1,8,7
8,-9,-1
-8,-9,-17
</code>```

Leaderboard

var QUESTION_ID=84260,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

答:
Minecraft 1.10.x, <s>924</s> 512 bytes

Thanks to @quat for reducing the blytecount by 48 points and the bytecount by 412.

Alright, so, I took some of the ideas from this answer and made a version of my own, except that this one is capable of accepting non-negative input. A version may be found here in structure block format.

(new version looks kinda boring tbh)

Similar commands as the other answer:

```<code>scoreboard objectives add a dummy
execute @e[type=Pig] ~ ~ ~ scoreboard players add m a 1
execute @e[type=Cow] ~ ~ ~ scoreboard players add n a 1
scoreboard players operation n a += m a
tellraw @a {"score":{"name":"n","objective":"a"}}
</code>```

To input numbers, spawn in a number of cows and pigs. Cows will represent value "n" and pigs will represent value "m". The command block system will progressively kill the cows and pigs and assign values as necessary.

This answer assumes that you are in a world with no naturally occurring cows or pigs and that the values stored in "n" and "m" are cleared on each run.

Title: Add two numbers

Body:
Minecraft 1.10.x, <s>924</s> 512 bytes

Thanks to @quat for reducing the blytecount by 48 points and the bytecount by 412.

Alright, so, I took some of the ideas from this answer and made a version of my own, except that this one is capable of accepting non-negative input. A version may be found here in structure block format.

(new version looks kinda boring tbh)

Similar commands as the other answer:

scoreboard objectives add a dummy
execute @e[type=Pig] ~ ~ ~ scoreboard players add m a 1
execute @e[type=Cow] ~ ~ ~ scoreboard players add n a 1
scoreboard players operation n a += m a
tellraw @a {"score":{"name":"n","objective":"a"}}

To input numbers, spawn in a number of cows and pigs. Cows will represent value "n" and pigs will represent value "m". The command block system will progressively kill the cows and pigs and assign values as necessary.

This answer assumes that you are in a world with no naturally occurring cows or pigs and that the values stored in "n" and "m" are cleared on each run.


答:
Bash shell script (65 chars)

```<code>shuf -e `for x in {0..8}
do echo $((r=RANDOM%3+3)) $((8-r))
done`
</code>```

(shuf comes from the GNU coreutils package. Also, thanks Gareth.)

Title: Can you Golf Golf?

Body:
Bash shell script (65 chars)

shuf -e `for x in {0..8}
do echo $((r=RANDOM%3+3)) $((8-r))
done`

(shuf comes from the GNU coreutils package. Also, thanks Gareth.)


答:
Lua, 67 Bytes

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

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

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


问:
What's the second non-repeating character?
Based on this question from Code Review

Given a non-empty string of printable ASCII characters, output the second non-repeating character. For example, for input DEFD, output F.

Input

A single string, in any suitable format.

Output

The second character that doesn't repeat, when reading left-to-right, again in a suitable format.

The output character is case-insensitive.

If no such character exists (e.g., all characters repeat), output an empty string.

Rules

The algorithm should ignore case. That is, D and d count as the same character.

Either a full program or a function are acceptable.

The input string will be guaranteed non-empty (i.e., at least one character in length).

The input string is ASCII. Any valid character could repeat, not just alphanumeric (this includes spaces).

Standard loopholes are forbidden.

This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples

Input is on first line, output is on second line.

```<code>DEFD
F

FEED
D

This is an example input sentence.
x

...,,,..,,!@
@

ABCDefgHijklMNOPqrsTuVWxyz
B

AAAAAABBBBB

Thisxthis

This this.
.
</code>```

答:
TSQL, 128 bytes

Golfed:

```<code>DECLARE @ varchar(99)=',,zzzbb@kkkkkkJgg'

,@i INT=99WHILE @i>1SELECT
@i-=1,@=IIF(LEN(@)>LEN(x)+1,x,@)FROM(SELECT
REPLACE(@,SUBSTRING(@,@i,1),'')x)x PRINT SUBSTRING(@,2,1)
</code>```

Ungolfed:

```<code>DECLARE @ varchar(99)=',,zzzbb@kkkkkkJgg'

,@i INT=99

WHILE @i>1
  SELECT
    @i-=1,@=IIF(LEN(@)>LEN(x)+1,x,@)
  FROM
    (SELECT
       REPLACE(@,SUBSTRING(@,@i,1),'')x
    )x

PRINT SUBSTRING(@,2,1)
</code>```

Fiddle

Body:
TSQL, 128 bytes

Golfed:

DECLARE @ varchar(99)=',,zzzbb@kkkkkkJgg'

,@i INT=99WHILE @i>1SELECT
@i-=1,@=IIF(LEN(@)>LEN(x)+1,x,@)FROM(SELECT
REPLACE(@,SUBSTRING(@,@i,1),'')x)x PRINT SUBSTRING(@,2,1)

Ungolfed:

DECLARE @ varchar(99)=',,zzzbb@kkkkkkJgg'

,@i INT=99

WHILE @i>1
  SELECT
    @i-=1,@=IIF(LEN(@)>LEN(x)+1,x,@)
  FROM
    (SELECT
       REPLACE(@,SUBSTRING(@,@i,1),'')x
    )x

PRINT SUBSTRING(@,2,1)

Fiddle


答:
TSQL 67 bytes

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

SELECT n FROM(SELECT n,sum(n%2)over(order by i)z FROM @)x WHERE z=0
</code>```

Fiddle

Title: Implement Takewhile

Body:
TSQL 67 bytes

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

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

Fiddle


问:
Groups of repeating items

Challenge description

Given a list / array of items, display all groups of consecutive repeating items.

Input / output description

Your input is a list / array of items (you can assume all of them are of the same type). You don't need to support every type your language has, but is has to support at least one (preferably int, but types like boolean, although not very interesting, are also fine). Sample outputs:

```<code>[4, 4, 2, 2, 9, 9] -> [[4, 4], [2, 2], [9, 9]]
[1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4] -> [[1, 1, 1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
[1, 1, 1, 3, 3, 1, 1, 2, 2, 2, 1, 1, 3] -> [[1, 1, 1], [3, 3], [1, 1], [2, 2, 2], [1, 1], [3]]
[9, 7, 8, 6, 5] -> [[9], [7], [8], [6], [5]]
[5, 5, 5] -> [[5, 5, 5]]
['A', 'B', 'B', 'B', 'C', 'D', 'X', 'Y', 'Y', 'Z'] -> [['A'], ['B', 'B', 'B'], ['C'], ['D'], ['X'], ['Y', 'Y'], ['Z']]
[True, True, True, False, False, True, False, False, True, True, True] -> [[True, True, True], [False, False], [True], [False, False], [True, True, True]]
[0] -> [[0]]
</code>```

As for empty lists, output is undefined - it can be nothing, an empty list, or an exception - whatever suits your golfing purposes the best. You don't have to create a separate list of lists either, so this is a perfectly valid output as well:

```<code>[1, 1, 1, 2, 2, 3, 3, 3, 4, 9] ->

1 1 1
2 2
3 3 3
4
9
</code>```

The important thing is to keep the groups separated in some way. This is code-golf so the shortest code in bytes wins

答:
ListSharp, 134 bytes

```<code>STRG l = READ[<here>+"\\l.txt"]
[FOREACH NUMB IN 1 TO l LENGTH-1 AS i]
{
[IF l[i] ISNOT l[i-1]]
STRG o=o+"\n"
STRG o=o+l[i]
}
SHOW = o
</code>```

ListSharp doesnt support functions so the array is saved in a local file called l.txt

Title: Groups of repeating items

Body:
ListSharp, 134 bytes

STRG l = READ[<here>+"\\l.txt"]
[FOREACH NUMB IN 1 TO l LENGTH-1 AS i]
{
[IF l[i] ISNOT l[i-1]]
STRG o=o+"\n"
STRG o=o+l[i]
}
SHOW = o

ListSharp doesnt support functions so the array is saved in a local file called l.txt


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

答:
C#, 85 bytes

```<code>return Regex.Matches(new WebClient().DownloadString("http://enwp.org/"+d),"Canada").Count;
</code>```

Takes input d like July_1.

And July_1 is truly Canada Day, having the most references. With February_1 and April_23 sharing 2nd place with 18 "Canada"s each.

Find "Canada" day (in parallel), 207 bytes:

```<code>return Enumerable.Range(0,366).Select(i=>new DateTime(8,1,1).AddDays(i).ToString("MMMM_d")).AsParallel().OrderBy(d=>Regex.Matches(new WebClient().DownloadString("http://enwp.org/"+d),"Canada").Count).Last();
</code>```

(Year 8 is the leap year with the shortest representation). Potentially inefficient, in that the OrderBy probably generates >366 web calls, but just going for shorter and appears to complete in not much more time.

Title: Was it Really Canada Day?

Body:
C#, 85 bytes

return Regex.Matches(new WebClient().DownloadString("http://enwp.org/"+d),"Canada").Count;

Takes input d like July_1.

And July_1 is truly Canada Day, having the most references. With February_1 and April_23 sharing 2nd place with 18 "Canada"s each.

Find "Canada" day (in parallel), 207 bytes:

return Enumerable.Range(0,366).Select(i=>new DateTime(8,1,1).AddDays(i).ToString("MMMM_d")).AsParallel().OrderBy(d=>Regex.Matches(new WebClient().DownloadString("http://enwp.org/"+d),"Canada").Count).Last();

(Year 8 is the leap year with the shortest representation). Potentially inefficient, in that the OrderBy probably generates >366 web calls, but just going for shorter and appears to complete in not much more time.


答:
05AB1E, <s>92</s> <s>87</s> <s>83</s> <s>82</s> 77 bytes

```<code>>i‚˜,}¹iÐ¸˜Qis}GD})˜,}¹<i³v²y¢O}){0è,}¹Íi{s{Q,}¹Í<iÙv²y¢O³‹_iy}}),}svy†¬yQi¦}}
</code>```

Split by operation

```<code>>i                      # if 0
  ‚˜,}                  # addition
¹i                      # if 1
  Ð¸˜Qis}GD})˜,}        # multiplication
¹<i                     # if 2
   ³v²y¢O}){0è,}        # count
¹Íi                     # if 3
   {s{Q,}               # equality
¹Í<i                    # if 4
   Ùv²y¢O³÷Fy}}),}      # division
                        # else
   svy†¬yQi¦}}          # difference
</code>```

Explanation

Addition

```<code>‚˜,}
</code>```

Put one bag in other and flatten them to one bag.

Multiplication

```<code>Ð¸˜Qis}
</code>```

Make sure the number is on the top of the stack. Call this X.

```<code>GD})˜,}
</code>```

Duplicate the bag X times and join to one bag.

Count

```<code>³v²y¢O}){0è,}
</code>```

For each element in the divisor bag, count number of occurences in dividend bag.

The minimum count will be the number of bags we can make.

Equality

```<code> {s{Q,}
</code>```

Sort both bags and check if they're equal.

Division

```<code>Ùv²y¢O³÷Fy}}),}
</code>```

Count how many times each unique element occurs in the bag.

If it occurs at least as many times as the divisor. Keep (nr_of_copies_total // divisor) copies in the bag.

Difference

```<code>svy†¬yQi¦}}
</code>```

For each element in the subtrahend, sort it to the front of the minuend.

If the current subtrahend if equal to the first element in the minuend, remove it from the minuend.

Title: Implement bag operations

Body:
A bag, also called a multiset, is an unordered collection. You can call it a set that allows duplicates, or a list (or an array) that is not ordered/indexed. In this challenge, you are asked to implement bag operations: addition, difference, multiplication, division, counting and equality test.

Operations

The specified operations may not be conventional.

addition combines two bags into one, conserving the total number of each value

[1,2,2,3] + [1,2,4] = [1,1,2,2,2,3,4]

difference removes from a bag each element of another bag, or does nothing if no such element

[1,2,2,4] - [1,2] = [2,4]  [1,2,3] - [2,4] = [1,3]

multiplication multiplies each element in the bag.

[1,2,3,3,4] * 3 = [1,1,1,2,2,2,3,3,3,3,3,3,4,4,4] 2 * [1,3] = [1,1,3,3]

division is an uncommon one: each n equal elements are put in n equal new bags, elements that cannot form an n-group remain in the bag. Return any one of the n new bags.

[1,1,2,2,2] / 2 = [1,2] [1,2,2,3,3,3] / 3 = [3]

counting counts how many divisor bags can be produced from the dividend bag

[1,1,2,2,2,2,3,3,3] c [1,2,3] = 2

equality test checks if two bags have the same numbers of each element

[1,2,2,3] == [3,2,1,2] = truthy [1,2,3] == [1,2,2,3] = falsy (can also use = for this)

If you are using your own symbols for the operators, please specify.

Formats

Bags will be displayed as lists of the form [1,1,2,3,4]. You can use any other bracket than square ones, or even use quotes, or nothing at all. The elements will be integers(mathematically, not necessarily int) for the purpose of this question. Bags do not have to be sorted.

The input format will be two bags or a bag and an integer, with an operator. You can specify your own format as long as it contains these three.

The output format should be a single bag of the same format.

Rules

you may not use built-in functions, operations or libraries (including the standard library) that already implement these; it's ok though to use list concatenation and multiplication since they are by definition list operations, not bag operations (which happen to basically do the same thing)

standard loopholes apply

shortest answer wins

Test cases

```<code>[1,2,2,3] + [1,2,4]
[1,1,2,2,2,3,4]

[1,2,2,4] - [1,2]
[2,4]

[1,2,3] - [2,4]
[1,3]

[1,2,3,3,4] * 3
[1,1,1,2,2,2,3,3,3,3,3,3,4,4,4]

2 * [1,3]
[1,1,3,3]

[1,1,2,2,2] / 2
[1,2]

[1,2,2,3,3,3] / 3
[3]

[1,1,2,2,2,2,3,3,3] c [1,2,3]
2

[3,2,1,2] == [1,2,2,3]
truthy

[1,2,3] == [1,2,2,3]
falsy
</code>```

Body:
05AB1E, <s>92</s> <s>87</s> <s>83</s> <s>82</s> 77 bytes

>i‚˜,}¹iÐ¸˜Qis}GD})˜,}¹<i³v²y¢O}){0è,}¹Íi{s{Q,}¹Í<iÙv²y¢O³‹_iy}}),}svy†¬yQi¦}}

Split by operation

>i                      # if 0
  ‚˜,}                  # addition
¹i                      # if 1
  Ð¸˜Qis}GD})˜,}        # multiplication
¹<i                     # if 2
   ³v²y¢O}){0è,}        # count
¹Íi                     # if 3
   {s{Q,}               # equality
¹Í<i                    # if 4
   Ùv²y¢O³÷Fy}}),}      # division
                        # else
   svy†¬yQi¦}}          # difference

Explanation

Addition

‚˜,}

Put one bag in other and flatten them to one bag.

Multiplication

Ð¸˜Qis}

Make sure the number is on the top of the stack. Call this X.

GD})˜,}

Duplicate the bag X times and join to one bag.

Count

³v²y¢O}){0è,}

For each element in the divisor bag, count number of occurences in dividend bag.

The minimum count will be the number of bags we can make.

Equality

 {s{Q,}

Sort both bags and check if they're equal.

Division

Ùv²y¢O³÷Fy}}),}

Count how many times each unique element occurs in the bag.

If it occurs at least as many times as the divisor. Keep (nr_of_copies_total // divisor) copies in the bag.

Difference

svy†¬yQi¦}}

For each element in the subtrahend, sort it to the front of the minuend.

If the current subtrahend if equal to the first element in the minuend, remove it from the minuend.


问:
Implement BCD Arithmetic
Write the shortest function you can that takes two binary-coded decimal integers and a character indicating an arithmetic operation to perform and return the result.

Input Specification

You will be passed two 32-bit bit patterns representing unsigned BCD integers.  In C or Java, for example, you would be passed an int (unsigned, if you prefer).  The third argument to your function will be a single character denoting what operation to perform.  If your language requires fixed return sizes, return a 32-bit result and ignore overflow.  Your return value should also be encoded as a BCD.

You should support +, -, *, /, and %.  For subtraction, the first argument is the minuend and the second argument is the subtrahend.  For division and modulo, the first argument is the quotient and the second is the divisor.

Example

```<code>bcd(0x00000127, 0x00000003, '+') => 0x00000130 // NOT 0x0000012A
</code>```

ContentLicense: CC BY-SA 2.5

Title: Implement BCD Arithmetic

Body:
Python - 47 chars

bcd=lambda*a:"0x%08d"%eval("%x%s%x"%(a*2)[::2])

tests

>>> print bcd(0x00000127, 0x00000003, '+')
0x00000130
>>> print bcd(0x00000127, 0x00000003, '*')
0x00000381
>>> print bcd(0x00000127, 0x00000003, '/')
0x00000042
>>> print bcd(0x00000127, 0x00000003, '-')
0x00000124


答:
Haskell, 104 102 98 chars.

```<code>import System.Random
q l|sum l==72=print l|1>0=main
main=mapM(\_->randomRIO(3::Int,5))[1..18]>>=q
</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:
Haskell, 104 102 98 chars.

import System.Random
q l|sum l==72=print l|1>0=main
main=mapM(\_->randomRIO(3::Int,5))[1..18]>>=q


答:
C#, 50 bytes

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

Title: Implement Takewhile

Body:
C#, 50 bytes

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


答:
hashmap, 10 bytes

```<code>i" "ĥdĐ+
</code>```

Explanation:

```<code>i" "ĥdĐ+
i        Take input
 " "     Push space
    ĥ    Split the input by space
     dĐ  Convert the list to a double then flatten the list
       + Add them together
</code>```

Title: Add two numbers

Body:
Input: Two integers. Preferably decimal integers, but other forms of numbers can be used. These can be given to the code in standard input, as arguments to the program or function, or as a list.

Output: Their sum. Use the same format for output integers as input integers. For example, the input 5 16 would lead to the output 21.

Restrictions: No standard loopholes please. This is code-golf, answer in lowest amount of bytes wins.

Notes: This should be fairly trivial, however I'm interested to see how it can be implemented. The answer can be a complete program or a function, but please identify which one it is.

Test cases:

```<code>1 2 -> 3
14 15 -> 29
7 9 -> 16
-1 8 -> 7
8 -9 -> -1
-8 -9 -> -17
</code>```

Or as CSV:

```<code>a,b,c
1,2,3
14,15,29
7,9,16
-1,8,7
8,-9,-1
-8,-9,-17
</code>```

Leaderboard

var QUESTION_ID=84260,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="
"+e.body.replace(OVERRIDE_REG,"")+"
")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}</code>```

 <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

```

Body:
hashmap, 10 bytes

i" "ĥdĐ+

Explanation:

i" "ĥdĐ+
i        Take input
 " "     Push space
    ĥ    Split the input by space
     dĐ  Convert the list to a double then flatten the list
       + Add them together


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:
JavaScript, <s>138</s> <s>137</s> <s>129</s> <s>124</s> <s>112</s> 110

2 bytes improvement inspired by @Neil´s code

f=a=>a.map((v,i,a)=>i%4?i>6?v&&60-v:i>5?(59-v+!a[7])%60:i>4?179-v+!(a[7]|a[6]):v:'NEWS'[3-'NEWS'.indexOf(v)]);

input = output = array containing 2x(1 uppercase char and 3 int)

tested in Firefox

ungolfed

f=a=>a.map((v,i,a)=>
i%4?
    i>6?v&&60-v              // 7: invert seconds - old: (60-v)%60
    :i>5?(59-v+!a[7])%60     // 6: invert minutes, increase if seconds are 0
    :i>4?179-v+!(a[7]|a[6])  // 5: invert degrees, increase if seconds and minutes are 0
    :v                       // 1,2,3: unchanged
:'NEWS'[3-'NEWS'.indexOf(v)] // 0,4: swap directions
);

tests

<table id=out border=1><tr><th>in</th><th>out<th>expected</th><th>ok?</th></tr></table>
<script>
addR=(r,s)=>{var d=document.createElement('td');d.appendChild(document.createTextNode(s));r.appendChild(d)}
test=(x,e,f)=>{var y,r=document.createElement('tr');addR(r,x);addR(r,y=('function'==typeof f)?f(x):f);addR(r,e);addR(r,e.toString()==y.toString()?'Y':'N');document.getElementById('out').appendChild(r)}

samples=[
'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',0,0,0,'W',180,0,0,
'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,
];
while (samples.length)
{
    x=samples.splice(0,8);
    e=samples.splice(0,8);
    test(x,e,h);
    test(e,x,h);
}
</script>


答:
Befunge, 35 Bytes

This code handles numbers between 0 and 65535

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

Input format :

```<code>number_of_values    values(separated by a space)
</code>```

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

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

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

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

I don't know if this is acceptable, as I didn't count this trailing in the byte count

nb: it seems that because I'm storing number in the code, the interpreter won't let this program run twice in the correct way. You'll have to reload it.

How does this work:

The interpreter follows the arrows and skip an instruction when crossing '#'

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

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

Title: Implement Takewhile

Body:
Befunge, 35 Bytes

This code handles numbers between 0 and 65535

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

Input format :

number_of_values    values(separated by a space)

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

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

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

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

I don't know if this is acceptable, as I didn't count this trailing in the byte count

nb: it seems that because I'm storing number in the code, the interpreter won't let this program run twice in the correct way. You'll have to reload it.

How does this work:

The interpreter follows the arrows and skip an instruction when crossing '#'

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

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


问:
Reverse a string while maintaining the capitalization in the same places
The goal here is to simply reverse a string, with one twist:

Keep the capitalization in the same places.

Example Input 1: Hello, Midnightas

Example Output 1: SathginDim ,olleh

Example Input 2: .Q

Exmaple Output 2: q.

Rules:

Output to STDOUT, input from STDIN

The winner will be picked 13th of July on GMT+3 12:00 (One week)

The input may only consist of ASCII symbols, making it easier for programs that do not use any encoding that contains non-ASCII characters.

Any punctuation ending up in a position where there was an upper-case letter must be ignored.

答:
05AB1E, <s>19</s> <s>16</s> <s>15</s> 13 bytes

Thanks to Emigna for saving a 3 bytes!

Probably gonna get beat by Jelly... Code:

```<code>Âuvy¹Nè.lil}?
</code>```

Uses the CP-1252 encoding. Try it online!.

Body:
05AB1E, <s>19</s> <s>16</s> <s>15</s> 13 bytes

Thanks to Emigna for saving a 3 bytes!

Probably gonna get beat by Jelly... Code:

Âuvy¹Nè.lil}?

Uses the CP-1252 encoding. Try it online!.


答:
Actually, 25 bytes

```<code>;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ
</code>```

Try it online!

Explanation:

```<code>;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ
;                          create a copy of the input
 `úíuY"ùû"E£`M             for each character in input:
  úíuY                       0-based index in lowercase English letters, or -1 if not found, increment, boolean negate (1 if uppercase else 0)
      "ùû"E£                 `û` if the character is lowercase else `ù` (str.lower vs str.upper)
              @ùRZ         make the other copy of the input lowercase, reverse it, and zip it with the map result
                  `i@ƒ`M   for each (string, function) pair:
                   i@ƒ       flatten, swap, apply (apply the function to the string)
                        Σ  concatenate the strings
</code>```

Title: Reverse a string while maintaining the capitalization in the same places

Body:
The goal here is to simply reverse a string, with one twist:

Keep the capitalization in the same places.

Example Input 1: Hello, Midnightas

Example Output 1: SathginDim ,olleh

Example Input 2: .Q

Exmaple Output 2: q.

Rules:

Output to STDOUT, input from STDIN

The winner will be picked 13th of July on GMT+3 12:00 (One week)

The input may only consist of ASCII symbols, making it easier for programs that do not use any encoding that contains non-ASCII characters.

Any punctuation ending up in a position where there was an upper-case letter must be ignored.

Body:
Actually, 25 bytes

;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ

Try it online!

Explanation:

;`úíuY"ùû"E£`M@ùRZ`i@ƒ`MΣ
;                          create a copy of the input
 `úíuY"ùû"E£`M             for each character in input:
  úíuY                       0-based index in lowercase English letters, or -1 if not found, increment, boolean negate (1 if uppercase else 0)
      "ùû"E£                 `û` if the character is lowercase else `ù` (str.lower vs str.upper)
              @ùRZ         make the other copy of the input lowercase, reverse it, and zip it with the map result
                  `i@ƒ`M   for each (string, function) pair:
                   i@ƒ       flatten, swap, apply (apply the function to the string)
                        Σ  concatenate the strings


答:
Haskell, <s>83</s> <s>80</s> <s>75</s> 71 bytes

The most straightforward way I could think of.

```<code>import Data.Char
f a|isUpper a=toUpper|1>0=toLower
zipWith f<*>reverse
</code>```

Body:
Haskell, <s>83</s> <s>80</s> <s>75</s> 71 bytes

The most straightforward way I could think of.

import Data.Char
f a|isUpper a=toUpper|1>0=toLower
zipWith f<*>reverse


答:
Python, 71 bytes

lambda s:''.join((z*2).title()[c.isupper()-1]for c,z in zip(s,s[::-1]))
```

Try it online

-3 bytes from Ruud, plus the inspiration for 2 more.

-4 more bytes from FryAmTheEggman

Body:
Python, 71 bytes

lambda s:''.join((z*2).title()[c.isupper()-1]for c,z in zip(s,s[::-1]))

Try it online

-3 bytes from Ruud, plus the inspiration for 2 more.

-4 more bytes from FryAmTheEggman


答:
J, 30 bytes

```<code>(={"_1 toupper@]|.@,.])tolower
</code>```

Doesn't support non-ASCII

Body:
J, 30 bytes

(={"_1 toupper@]|.@,.])tolower

Doesn't support non-ASCII


答:
Brachylog, 28 bytes

```<code>@lr:?z:1ac.
h@u.,@A@um~t?|h.
</code>```

Explanation

Main Predicate:

```<code>@lr                 Reverse the lowercase version of the Input
   :?z              Zip that reversed string with the Input
      :1a           Apply predicate 1 to each couple [char i of reverse, char i of Input]
         c.         Output is the concatenation of the result
</code>```

Predicate 1:

```<code>h@u.,               Output is the uppercase version of the first char of Input
     @A@um~t?       The second char of Input is an uppercase letter
             |      Or
              h.    Output is the first char of Input
</code>```

Body:
Brachylog, 28 bytes

@lr:?z:1ac.
h@u.,@A@um~t?|h.

Explanation

Main Predicate:

@lr                 Reverse the lowercase version of the Input
   :?z              Zip that reversed string with the Input
      :1a           Apply predicate 1 to each couple [char i of reverse, char i of Input]
         c.         Output is the concatenation of the result

Predicate 1:

h@u.,               Output is the uppercase version of the first char of Input
     @A@um~t?       The second char of Input is an uppercase letter
             |      Or
              h.    Output is the first char of Input


答:
Pyth, <s>13</s> <s>11</s> <s>10</s> 9 bytes

Thanks to @FryAmTheEggman for reminding me about V and @LeakyNun for another byte.

```<code>srV_Qm!/G
</code>```

Try it online!
now on mobile, updating link in a bit

Body:
Pyth, <s>13</s> <s>11</s> <s>10</s> 9 bytes

Thanks to @FryAmTheEggman for reminding me about V and @LeakyNun for another byte.

srV_Qm!/G

Try it online!
now on mobile, updating link in a bit


答:
Dyalog APL, 12 bytes

```<code>⌽f¨⍨⊢≠f←819⌶
</code>```

819⌶ is the case folding function

f← because its name is long, we assign it to f

⊢≠f Boolean where text differs from lower-cased text

f¨⍨ use that (1 means uppercase, 0 means lowercase) to fold each letter...

⌽ ... of the reversed text

Handles non-ASCII according to the Unicode Consortium's rules.

Body:
Dyalog APL, 12 bytes

⌽f¨⍨⊢≠f←819⌶

819⌶ is the case folding function

f← because its name is long, we assign it to f

⊢≠f Boolean where text differs from lower-cased text

f¨⍨ use that (1 means uppercase, 0 means lowercase) to fold each letter...

⌽ ... of the reversed text

Handles non-ASCII according to the Unicode Consortium's rules.


Title: Dig to Australia - antipodes

Body:
Java, <s>199</s> 177 or 151 or 134 Bytes

177 Bytes solution which prints result

void t(int...a){int i=648000-(a[5]*3600+a[6]*60+a[7]);System.out.println(a[0]=='N'?"S":"N"+" "+a[1]+" "+a[2]+" "+a[3]+" "+(a[4]=='E'?"W":"E")+" "+i/3600+" "+i/60%60+" "+i%60);}

151 Bytes solution which returns result as array

Object[]y(int...a){int i=648000-(a[5]*3600+a[6]*60+a[7]);return new Object[]{a[0]=='N'?"S":"N",a[1],a[2],a[3],a[4]=='E'?"W":"E",i/3600,i/60%60,i%60};}

134 Bytes if we used lambda notation

a->{int i=648000-a[5]*3600-a[6]*60-a[7];return new Object[]{a[0]=='N'?"S":"N",a[1],a[2],a[3],a[4]=='E'?"W":"E",i/3600,i/60%60,i%60};}


答:
Pyke, <s>11</s> <s>10</s> 9 bytes

```<code>_FQo@UhAl
</code>```

Try it here!

```<code>_         -   reversed(input)
 F        -  for i in ^
   o      -      o+=1
  Q @     -     input[^]
     Uh   -    ^.is_upper()+1
       Al -   [len, str.lower, str.upper, ...][^](i)
          - "".join(^)
</code>```

Body:
Pyke, <s>11</s> <s>10</s> 9 bytes

_FQo@UhAl

Try it here!

_         -   reversed(input)
 F        -  for i in ^
   o      -      o+=1
  Q @     -     input[^]
     Uh   -    ^.is_upper()+1
       Al -   [len, str.lower, str.upper, ...][^](i)
          - "".join(^)


答:
TSQL, 175 bytes

Golfed:

```<code>DECLARE @ varchar(99)='Hello, Midnightas'

,@o varchar(99)='',@i INT=0WHILE @i<LEN(@)SELECT
@i+=1,@o+=IIF(ascii(x)=ascii(lower(x)),lower(y),upper(y))FROM(SELECT
SUBSTRING(@,@i+1,1)x,SUBSTRING(@,len(@)-@i,1)y)z
PRINT @o
</code>```

Ungolfed

```<code>DECLARE @ varchar(99)='Hello, Midnightas'

,@o varchar(99)=''
,@i INT=0

WHILE @i<LEN(@)
  SELECT @i+=1,@o+=IIF(ascii(x)=ascii(lower(x)),lower(y),upper(y))
  FROM
    (SELECT SUBSTRING(@,@i+1,1)x,SUBSTRING(@,len(@)-@i,1)y)z

PRINT @o
</code>```

Fiddle

Body:
TSQL, 175 bytes

Golfed:

DECLARE @ varchar(99)='Hello, Midnightas'

,@o varchar(99)='',@i INT=0WHILE @i<LEN(@)SELECT
@i+=1,@o+=IIF(ascii(x)=ascii(lower(x)),lower(y),upper(y))FROM(SELECT
SUBSTRING(@,@i+1,1)x,SUBSTRING(@,len(@)-@i,1)y)z
PRINT @o

Ungolfed

DECLARE @ varchar(99)='Hello, Midnightas'

,@o varchar(99)=''
,@i INT=0

WHILE @i<LEN(@)
  SELECT @i+=1,@o+=IIF(ascii(x)=ascii(lower(x)),lower(y),upper(y))
  FROM
    (SELECT SUBSTRING(@,@i+1,1)x,SUBSTRING(@,len(@)-@i,1)y)z

PRINT @o

Fiddle


答:
Python 2.7 - 447B (filesize)

This is my first try at Codegolf, I hope it satisfies. I needed 2h. (But I'm still a beginner at Python)

Edit: Thanks to "Kevin Lau - not Kenny" for pointing out these:

pythons self argument in a class can be replaced by anything

indentation only has to be a single space

the builtin sorted - funktion (I knew I had seen it, but I thought it to be a method in lists)

__ radd __ is not needed (I only support adding B-objects(Bag-type) anyways)

Edit: Additionally I saved space by replacing functions with lambdas and new lines and indentations with more semicolons.

Code:

```<code>class B:
 def __init__(S,L=[]):S.L=sorted(list(L));S.p=lambda:[[i]*S.L.count(i)for k,i in enumerate(S.L)if i!=S.L[k-1]];S.__eq__=lambda o:S.L==o.L;S.__rmul__=S.__mul__=lambda o:B(S.L*o);S.__add__=lambda o:B(S.L+o.L);S.__sub__=lambda o:B([i for k in S.p()for i in k[:max(0,S.L.count(k[0])-o.L.count(k[0]))]]);S.__div__=lambda o:B([i for k in S.p()for i in k[::o][:[-1,None][len(k)%o==0]]]);S.c=lambda o:min([S.L.count(i)//o.L.count(i)for i in o.L])
</code>```

checks:

```<code>print B([1,2,2,3]) + B([1,2,4]) == B([1,1,2,2,2,3,4]) # Add

print B([1,2,2,4]) - B([1,2]) == B([2,4]) #Substract
print B([1,2,3])   - B([2,4]) == B([1,3]) #Substract

print B([1,2,3,3,4]) * 3 == B([1,1,1,2,2,2,3,3,3,3,3,3,4,4,4])#Multiply
print 2 * B([1,3]) == B([1,1,3,3])                            #

print B([1,1,2,2,2])   /2 == B([1,2]) #Divide
print B([1,2,2,3,3,3]) /3 == B([3])   #

print B([1,1,2,2,2,2,3,3,3]).c(B([1,2,3]))==2 #Contained n times

print B([3,2,1,2]) == B([1,2,2,3]) # Equal
print B([1,2,3])   == B([1,2,2,3]) # Unequal
</code>```

Output:

```<code>True
True
True
True
True
True
True
True
True
False
</code>```

I might try it an other time with set as basis some time.
Edit: Maybe I'll even try with functions only.

Title: Implement bag operations

Body:
A bag, also called a multiset, is an unordered collection. You can call it a set that allows duplicates, or a list (or an array) that is not ordered/indexed. In this challenge, you are asked to implement bag operations: addition, difference, multiplication, division, counting and equality test.

Operations

The specified operations may not be conventional.

addition combines two bags into one, conserving the total number of each value

[1,2,2,3] + [1,2,4] = [1,1,2,2,2,3,4]

difference removes from a bag each element of another bag, or does nothing if no such element

[1,2,2,4] - [1,2] = [2,4]  [1,2,3] - [2,4] = [1,3]

multiplication multiplies each element in the bag.

[1,2,3,3,4] * 3 = [1,1,1,2,2,2,3,3,3,3,3,3,4,4,4] 2 * [1,3] = [1,1,3,3]

division is an uncommon one: each n equal elements are put in n equal new bags, elements that cannot form an n-group remain in the bag. Return any one of the n new bags.

[1,1,2,2,2] / 2 = [1,2] [1,2,2,3,3,3] / 3 = [3]

counting counts how many divisor bags can be produced from the dividend bag

[1,1,2,2,2,2,3,3,3] c [1,2,3] = 2

equality test checks if two bags have the same numbers of each element

[1,2,2,3] == [3,2,1,2] = truthy [1,2,3] == [1,2,2,3] = falsy (can also use = for this)

If you are using your own symbols for the operators, please specify.

Formats

Bags will be displayed as lists of the form [1,1,2,3,4]. You can use any other bracket than square ones, or even use quotes, or nothing at all. The elements will be integers(mathematically, not necessarily int) for the purpose of this question. Bags do not have to be sorted.

The input format will be two bags or a bag and an integer, with an operator. You can specify your own format as long as it contains these three.

The output format should be a single bag of the same format.

Rules

you may not use built-in functions, operations or libraries (including the standard library) that already implement these; it's ok though to use list concatenation and multiplication since they are by definition list operations, not bag operations (which happen to basically do the same thing)

standard loopholes apply

shortest answer wins

Test cases

```<code>[1,2,2,3] + [1,2,4]
[1,1,2,2,2,3,4]

[1,2,2,4] - [1,2]
[2,4]

[1,2,3] - [2,4]
[1,3]

[1,2,3,3,4] * 3
[1,1,1,2,2,2,3,3,3,3,3,3,4,4,4]

2 * [1,3]
[1,1,3,3]

[1,1,2,2,2] / 2
[1,2]

[1,2,2,3,3,3] / 3
[3]

[1,1,2,2,2,2,3,3,3] c [1,2,3]
2

[3,2,1,2] == [1,2,2,3]
truthy

[1,2,3] == [1,2,2,3]
falsy
</code>```

Body:
Python 2.7 - 447B (filesize)

This is my first try at Codegolf, I hope it satisfies. I needed 2h. (But I'm still a beginner at Python)

Edit: Thanks to "Kevin Lau - not Kenny" for pointing out these:

pythons self argument in a class can be replaced by anything

indentation only has to be a single space

the builtin sorted - funktion (I knew I had seen it, but I thought it to be a method in lists)

__ radd __ is not needed (I only support adding B-objects(Bag-type) anyways)

Edit: Additionally I saved space by replacing functions with lambdas and new lines and indentations with more semicolons.

Code:

class B:
 def __init__(S,L=[]):S.L=sorted(list(L));S.p=lambda:[[i]*S.L.count(i)for k,i in enumerate(S.L)if i!=S.L[k-1]];S.__eq__=lambda o:S.L==o.L;S.__rmul__=S.__mul__=lambda o:B(S.L*o);S.__add__=lambda o:B(S.L+o.L);S.__sub__=lambda o:B([i for k in S.p()for i in k[:max(0,S.L.count(k[0])-o.L.count(k[0]))]]);S.__div__=lambda o:B([i for k in S.p()for i in k[::o][:[-1,None][len(k)%o==0]]]);S.c=lambda o:min([S.L.count(i)//o.L.count(i)for i in o.L])

checks:

print B([1,2,2,3]) + B([1,2,4]) == B([1,1,2,2,2,3,4]) # Add

print B([1,2,2,4]) - B([1,2]) == B([2,4]) #Substract
print B([1,2,3])   - B([2,4]) == B([1,3]) #Substract

print B([1,2,3,3,4]) * 3 == B([1,1,1,2,2,2,3,3,3,3,3,3,4,4,4])#Multiply
print 2 * B([1,3]) == B([1,1,3,3])                            #

print B([1,1,2,2,2])   /2 == B([1,2]) #Divide
print B([1,2,2,3,3,3]) /3 == B([3])   #

print B([1,1,2,2,2,2,3,3,3]).c(B([1,2,3]))==2 #Contained n times

print B([3,2,1,2]) == B([1,2,2,3]) # Equal
print B([1,2,3])   == B([1,2,2,3]) # Unequal

Output:

True
True
True
True
True
True
True
True
True
False

I might try it an other time with set as basis some time.
Edit: Maybe I'll even try with functions only.


答:
JavaScript (ES6), <s>95</s> 83 bytes

```<code>s=>[...t=s.toLowerCase()].reverse().map((c,i)=>s[i]==t[i]?c:c.toUpperCase()).join``
</code>```

Edit: Saved a massive 12 bytes thanks to @edc65.

Body:
JavaScript (ES6), <s>95</s> 83 bytes

s=>[...t=s.toLowerCase()].reverse().map((c,i)=>s[i]==t[i]?c:c.toUpperCase()).join``

Edit: Saved a massive 12 bytes thanks to @edc65.


答:
Retina, <s>75</s> <s>67</s> 65 bytes

Byte count assumes ISO 8859-1 encoding.

```<code>$
±·$`
O$^`\G[^·]

s{T`L`l`±.
T01`l`L`±.*·[A-Z]
±·

±(.)
$1±
·.
·
</code>```

Try it online! (The first line enables a test suite with multiple linefeed-separated test cases.)

Body:
Retina, <s>75</s> <s>67</s> 65 bytes

Byte count assumes ISO 8859-1 encoding.

$
±·$`
O$^`\G[^·]

s{T`L`l`±.
T01`l`L`±.*·[A-Z]
±·

±(.)
$1±
·.
·

Try it online! (The first line enables a test suite with multiple linefeed-separated test cases.)