问:
Lucas Vs. The Garage Door Remote

Disclaimer

While I know there is this particular related question, my question uses two garage doors, a randomizing component, and I'm also basing this on real life events, seeing my son accidentally lowered one of said garage doors whilst I was walking out of the garage last week... Nothing like a blow to the head to get the creative juices flowing! ;)

The Background

Lucas (my 15 month old son) likes to play with the garage remote. There are two buttons on this remote, one for the left garage door, and one for the right garage door. Both buttons work in the same manner; press once to get the door to start opening, press again to stop, press again to start closing, press again to stop again, and so on.

Lucas loves this remote, he'll randomly press one of the buttons, or both, or none at all. If both are pressed, no signal is sent, but a press of one button will send out a signal.

So, the code-golf challenge is divided on two parts:

Part One

Generate a 60 character long string representing Lucas random button presses over a minute. "Random" in this case means "with an equal chance of each input at each tick". The characters are as follows:

0: Lucas has either pressed no button, or has pressed both buttons. Either way, no signal has been sent.

1: The button for the left garage door has been pressed by Lucas

2: The button for the right garage door has been pressed by Lucas

Part Two

Using the string generated in Part One, simulate the opening and closing of the two-car garage using the numbers as triggers for opening, stopping and closing these doors.

My garage doors are pretty quick (see Disclaimer above as to why).  Once you press the button it takes four seconds to be fully open or closed.

So, if closed:

0 sec: 0% open (closed); when button is pressed, door starts opening

1 sec: 25% open

2 sec: 50% open

3 sec: 75% open

4 sec: 100% open, door stops

And therefore, if open:

0 sec: 100% open; when button is pressed, door starts closing

1 sec: 75% open

2 sec: 50% open

3 sec: 25% open

4 sec: 0% open (closed), door stops

If a particular door is in motion, a signal to that same door will stop it. The next signal sent to that same door after that will send it moving in the opposite direction. If a door is stopped when it has previously been in motion and is now fully open or fully closed when the "stop" signal is received, the door will register as "stopped" in the fully-open or fully-closed state, ready to move in the opposite direction when it receives a new signal.

With this simulation, both garage doors will be initially in the closed position. So, let's look at a 10 second list of commands and see what happens if Lucas was to perform them on the remote:

```<code>2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)
</code>```

Output

The first part of the output requires the display of the 60 character long string of random "0", "1" and "2" characters generated from Part One. eg.
212022112021202211202120221120212022112021202211202120221120

Below this string, is the processing of these "signals" according to the rules mentioned above of how the garage doors will behave with each respective character (on a second by second basis). You should end up with 60 lines as a result below the initial display string.

Each of these processed lines will be in the form of:
N: (L:X% XXXXXXX, R:Y% YYYYYYY) where:

N is the nth character from the respective random string, which will be in the form of a 0, 1, or 2.

X% is the percentage of openness of the left door (there is no zero padding)

XXXXXXX is the status of the left door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".

Y% is the percentage of openness of the right door (there is no zero padding)

YYYYYYY is the status of the right door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".

Example shown below using 10 "signals" and 10 processed lines

```<code>2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)
</code>```

This is code-golf, so the shortest code will be the clear winner. I've made this a little easy by using phrases like "opening", "stopped" and "closing", which are all seven letters... so you may want to work that into your strategy.

Best of luck!

答:
Python 2, <s>377</s> <s>370</s> <s>361</s> <s>357</s> <s>345</s> <s>335</s> <s>326</s> <s>316</s> <s>312</s> <s>306</s> 304 bytes

The second indent level is a raw tab (\t), which plays really badly with Markdown, so it's been replaced by two spaces.

from random import*
p=[randint(0,2)for d in[[0]*3]*60]
print`p`[1::3]
v=[-1]*3
c=[0]*3
f=lambda y:str(c[y]*25)+'% '+'csoltpooespnipinengdg'[d[y]+1::3]
for x in p:
 for i in 1,2:
  q=d[i];c[i]+=q
  if(2*-~q==c[i])*q:v[i]=q;d[i]=0
 z=d[x]
 if z:v[x]=z
 d[x]=-v[x]*(z==0);print'%d: (L:%s, R:%s)'%(x,f(1),f(2))
```

<p>I'm almost certain this can be golfed further.</p>

<p>Ungolfed, with comments:</p>

<pre class="lang-py prettyprint-override"><code>import random

# Generate the random string - represented as a list of ints
presses = [random.randint(0, 2) for _ in range(60)]
print ''.join(map(str, presses))

# Constants for door states used for easier reading
CLOSING = -1
STOPPED = 0
OPENING = 1

# Variables representing the state of the garage doors
# There's a third element in these so that x[0] resolves to a dummy slot
# (this way, we can avoid a conditional down the road)
prev_states = [CLOSING, CLOSING, 0]
door_states = [STOPPED, STOPPED, 0]
door_pcts = [0, 0, 0]  # delta 1 = 25%

for press in presses:
  # Close/open the door 1 more
  for i in 1, 2:
    if door_states[i] != STOPPED:
      delta_pct, stop_pct = (-1, 0) if door_states[i] == CLOSING else (1, 4)
      door_pcts[i] += delta_pct
      if door_pcts[i] == stop_pct:
        prev_states[i] = door_states[i]
        door_states[i] = STOPPED

  # Handle pressing a button
  # If the press is 0 (no press), the 0th element resolves to a dummy
  # door, thus saving us an expensive conditional

  if door_states[press] == STOPPED:
    door_states[press] = -prev_states[press]
  else:
    prev_states[press] = door_states[press]
    door_states[press] = STOPPED

  # Print the status update
  print '%d: (L:%d%% %s, R:%d%% %s)' % (
    press,
    door_pcts[0]*25,
    ['closing', 'stopped', 'opening'][door_states[0]+1],
    door_pcts[1]*25,
    ['closing', 'stopped', 'opening'][door_states[1]+1],
  )
</code>```

Saved <s>4</s> <s>14</s> 15 bytes thanks to @TheBikingViking!

Saved 6 bytes thanks to @ValueInk!

Title: Lucas Vs. The Garage Door Remote

Body:
Python 2, <s>377</s> <s>370</s> <s>361</s> <s>357</s> <s>345</s> <s>335</s> <s>326</s> <s>316</s> <s>312</s> <s>306</s> 304 bytes

The second indent level is a raw tab (\t), which plays really badly with Markdown, so it's been replaced by two spaces.

from random import*
p=[randint(0,2)for d in[[0]*3]*60]
print`p`[1::3]
v=[-1]*3
c=[0]*3
f=lambda y:str(c[y]*25)+'% '+'csoltpooespnipinengdg'[d[y]+1::3]
for x in p:
 for i in 1,2:
  q=d[i];c[i]+=q
  if(2*-~q==c[i])*q:v[i]=q;d[i]=0
 z=d[x]
 if z:v[x]=z
 d[x]=-v[x]*(z==0);print'%d: (L:%s, R:%s)'%(x,f(1),f(2))

I'm almost certain this can be golfed further.

Ungolfed, with comments:

import random

# Generate the random string - represented as a list of ints
presses = [random.randint(0, 2) for _ in range(60)]
print ''.join(map(str, presses))

# Constants for door states used for easier reading
CLOSING = -1
STOPPED = 0
OPENING = 1

# Variables representing the state of the garage doors
# There's a third element in these so that x[0] resolves to a dummy slot
# (this way, we can avoid a conditional down the road)
prev_states = [CLOSING, CLOSING, 0]
door_states = [STOPPED, STOPPED, 0]
door_pcts = [0, 0, 0]  # delta 1 = 25%

for press in presses:
  # Close/open the door 1 more
  for i in 1, 2:
    if door_states[i] != STOPPED:
      delta_pct, stop_pct = (-1, 0) if door_states[i] == CLOSING else (1, 4)
      door_pcts[i] += delta_pct
      if door_pcts[i] == stop_pct:
        prev_states[i] = door_states[i]
        door_states[i] = STOPPED

  # Handle pressing a button
  # If the press is 0 (no press), the 0th element resolves to a dummy
  # door, thus saving us an expensive conditional

  if door_states[press] == STOPPED:
    door_states[press] = -prev_states[press]
  else:
    prev_states[press] = door_states[press]
    door_states[press] = STOPPED

  # Print the status update
  print '%d: (L:%d%% %s, R:%d%% %s)' % (
    press,
    door_pcts[0]*25,
    ['closing', 'stopped', 'opening'][door_states[0]+1],
    door_pcts[1]*25,
    ['closing', 'stopped', 'opening'][door_states[1]+1],
  )

Saved <s>4</s> <s>14</s> 15 bytes thanks to @TheBikingViking!

Saved 6 bytes thanks to @ValueInk!


问:
Find the right path
Given a list of paths, output the correct path.

Example of path:

```<code>    /\
----+/
    |
</code>```

- and | are horizontal and vertical paths.

/ and \ are 90° turns.

+ is treated as a - or a | depending of the current direction.

Paths may go in any direction and a character may be used in multiple paths.

Input will be like this:

```<code>       /--\
A------+--+--#
B------/  \--:
C------------#
D------------#
</code>```

A, B, C and D are path starts

# is a wall (the path is bad)

: is the end (the path is correct)

So here the output will be B.

You can assume:

: and # will always be reached from the left.

The character at the right of the start of a path will always be -.

Paths will always be well formed.

# and : will always be in the same column.

There will always be only one : and 4 paths.

Test cases

```<code>A------#
B------#
C------#
D------:
=>
D
</code>```

```<code>A-\ /---:
B-+-/ /-#
C-+---+-#
D-+---/
  \-----#
=>
B
</code>```

```<code>  /-\
A-+\\---#
B-/\-\/-#
C----++-#
D----+/
     \--:
=>
A
</code>```

```<code>A-\
B-+\
C-++\/----#
D-+++//---:
  \++-//--#
   \+--//-#
    \---/
=>
A
</code>```

```<code>  /-\
A-+-/-\
B-+-+-\--#
C-+-/ |/-#
D-\---++-#
  \---+/
      \--:
=>
B
</code>```

Since this is code-golf, the shortest answer win.

ContentLicense: CC BY-SA 3.0

Title: Find the right path

Body:
Perl 211 Bytes

sub f{for($s=-1;++$s<~~@_;){if($_[$s][0]ne' '){$r=$s;$c=$m=0;$n=1;while($_[$r][$c]ne'#'){if($_[$r][$c]eq':'){return$_[$s][0];}($m,$n)=$_[$r][$c]eq'/'?(-$n,-$m):$_[$r][$c]eq'\\'?($n,$m):($m,$n);$r+=$m;$c+=$n;}}}}

Ungolfed:

sub q{
    for($start = -1; ++$start <~~@_;) {
        if($_[$start][0] ne ' ') {
            $row = $start;
            $col = $rowMove = 0;
            $colMove = 1;
            while($_[$row][$col] ne '#') {
                if($_[$row][$col] eq ':') {
                    return $_[$start][0];
                }
                ($rowMove, $colMove) =  $_[$row][$col] eq '/' ? (-$colMove,-$rowMove) :
                                        $_[$row][$col] eq '\\' ? ($colMove,$rowMove) :
                                        ($rowMove, $colMove);
                $row += $rowMove;
                $col += $colMove;
            }
        }
    }
}

This is my first Perl golf, so suggestions are welcome :)


答:
Javascript (ES6), <s>277</s> <s>275</s> <s>263</s> <s>253</s> <s>250</s> <s>247</s> 234 bytes

```<code>_=>(d=[0,0],l=s='',[...Array(60)].map(_=>(s+=`
${c=Math.random()*3|0}:(`,l+=c,d=d.map((v,i)=>(v=v&8?v&16?v-27?v+1:20:v-9?v-1:0:v,v^=c+~i?0:v&8||24,s+='LR'[i]+`:${(v&7)*25}% `+(v&8?v&16?'opening':'closing':'stopped')+',)'[i],v)))),l+s)
</code>```

Ungolfed and commented

```<code>_ => (
  // Initialize array:
  //   - d = door states as integers
  //     - bits 0 to 2: door opening state (from 0b000 = 0% to 0b100 = 100%)
  //     - bit #3: door in motion (0: no, 1: yes)
  //     - bit #4: door direction (0: closing, 1: opening)
  d = [0, 0],

  // Initialize strings:
  //   - l = list of commands
  //   - s = door states in plain text
  l = s = '',

  // Iterate on an array of 60 entries.
  [...Array(60)].map(_ => (
    // c = new random command (0, 1 or 2)
    // Append new line and new command to s.
    s += `\n${c = Math.random() * 3 | 0}:(`,

    // Append new command to l.
    l += c,

    // For each door ...
    d = d.map((v, i) => (
      // If the door is in motion, update its opening state.
      // Clear the 'in motion' bit if a bound is reached (either closed or fully open).
      v = v & 8 ? v & 16 ? v - 27 ? v + 1 : 20 : v - 9 ? v - 1 : 0 : v,

      // If the current command is intended for this door, update its direction and
      // 'in motion' bit. Direction is changed on the 'stopped => moving' transition.
      v ^= c + ~i ? 0 : v & 8 || 24,

      // Translate the door state in plain text and append it to s
      s +=
        'LR'[i] +
        `:${(v & 7) * 25}% ` +
        (v & 8 ? v & 16 ? 'opening' : 'closing' : 'stopped') +
        ',)'[i],

      // Value to be taken into account by map()
      v
    ))
  )),

  // Final result to be returned
  l + s
)
</code>```

Demo

let f =
_=>(d=[0,0],l=s='',[...Array(60)].map(_=>(s+=`
${c=Math.random()*3|0}:(`,l+=c,d=d.map((v,i)=>(v=v&8?v&16?v-27?v+1:20:v-9?v-1:0:v,v^=c+~i?0:v&8||24,s+='LR'[i]+`:${(v&7)*25}% `+(v&8?v&16?'opening':'closing':'stopped')+',)'[i],v)))),l+s)

console.log(f())```

Title: Lucas Vs. The Garage Door Remote

Body:
Disclaimer

While I know there is this particular related question, my question uses two garage doors, a randomizing component, and I'm also basing this on real life events, seeing my son accidentally lowered one of said garage doors whilst I was walking out of the garage last week... Nothing like a blow to the head to get the creative juices flowing! ;)

The Background

Lucas (my 15 month old son) likes to play with the garage remote. There are two buttons on this remote, one for the left garage door, and one for the right garage door. Both buttons work in the same manner; press once to get the door to start opening, press again to stop, press again to start closing, press again to stop again, and so on.

Lucas loves this remote, he'll randomly press one of the buttons, or both, or none at all. If both are pressed, no signal is sent, but a press of one button will send out a signal.

So, the code-golf challenge is divided on two parts:

Part One

Generate a 60 character long string representing Lucas random button presses over a minute. "Random" in this case means "with an equal chance of each input at each tick". The characters are as follows:

0: Lucas has either pressed no button, or has pressed both buttons. Either way, no signal has been sent.

1: The button for the left garage door has been pressed by Lucas

2: The button for the right garage door has been pressed by Lucas

Part Two

Using the string generated in Part One, simulate the opening and closing of the two-car garage using the numbers as triggers for opening, stopping and closing these doors.

My garage doors are pretty quick (see Disclaimer above as to why).  Once you press the button it takes four seconds to be fully open or closed.

So, if closed:

0 sec: 0% open (closed); when button is pressed, door starts opening

1 sec: 25% open

2 sec: 50% open

3 sec: 75% open

4 sec: 100% open, door stops

And therefore, if open:

0 sec: 100% open; when button is pressed, door starts closing

1 sec: 75% open

2 sec: 50% open

3 sec: 25% open

4 sec: 0% open (closed), door stops

If a particular door is in motion, a signal to that same door will stop it. The next signal sent to that same door after that will send it moving in the opposite direction. If a door is stopped when it has previously been in motion and is now fully open or fully closed when the "stop" signal is received, the door will register as "stopped" in the fully-open or fully-closed state, ready to move in the opposite direction when it receives a new signal.

With this simulation, both garage doors will be initially in the closed position. So, let's look at a 10 second list of commands and see what happens if Lucas was to perform them on the remote:

```<code>2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)
</code>```

Output

The first part of the output requires the display of the 60 character long string of random "0", "1" and "2" characters generated from Part One. eg.
212022112021202211202120221120212022112021202211202120221120

Below this string, is the processing of these "signals" according to the rules mentioned above of how the garage doors will behave with each respective character (on a second by second basis). You should end up with 60 lines as a result below the initial display string.

Each of these processed lines will be in the form of:
N: (L:X% XXXXXXX, R:Y% YYYYYYY) where:

N is the nth character from the respective random string, which will be in the form of a 0, 1, or 2.

X% is the percentage of openness of the left door (there is no zero padding)

XXXXXXX is the status of the left door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".

Y% is the percentage of openness of the right door (there is no zero padding)

YYYYYYY is the status of the right door. If the door is not in motion (i.e. not opening or closing) the status "stopped" is enforced, meaning it has been stopped in motion (only possible at 25%, 50% or 75%) or stopped when fully open (100%) or fully closed (0%). Otherwise, the door will either be "opening" or "closing".

Example shown below using 10 "signals" and 10 processed lines

```<code>2120221120
2: (L:0% stopped, R:0% opening)
1: (L:0% opening, R:25% opening)
2: (L:25% opening, R:50% stopped)
0: (L:50% opening, R:50% stopped)
2: (L:75% opening, R:50% closing)
2: (L:100% stopped, R:25% stopped)
1: (L:100% closing, R:25% stopped)
1: (L:75% stopped, R:25% stopped)
2: (L:75% stopped, R:25% opening)
0: (L:75% stopped, R:50% opening)
</code>```

This is code-golf, so the shortest code will be the clear winner. I've made this a little easy by using phrases like "opening", "stopped" and "closing", which are all seven letters... so you may want to work that into your strategy.

Best of luck!

Body:
Javascript (ES6), <s>277</s> <s>275</s> <s>263</s> <s>253</s> <s>250</s> <s>247</s> 234 bytes

_=>(d=[0,0],l=s='',[...Array(60)].map(_=>(s+=`
${c=Math.random()*3|0}:(`,l+=c,d=d.map((v,i)=>(v=v&8?v&16?v-27?v+1:20:v-9?v-1:0:v,v^=c+~i?0:v&8||24,s+='LR'[i]+`:${(v&7)*25}% `+(v&8?v&16?'opening':'closing':'stopped')+',)'[i],v)))),l+s)

Ungolfed and commented

_ => (
  // Initialize array:
  //   - d = door states as integers
  //     - bits 0 to 2: door opening state (from 0b000 = 0% to 0b100 = 100%)
  //     - bit #3: door in motion (0: no, 1: yes)
  //     - bit #4: door direction (0: closing, 1: opening)
  d = [0, 0],

  // Initialize strings:
  //   - l = list of commands
  //   - s = door states in plain text
  l = s = '',

  // Iterate on an array of 60 entries.
  [...Array(60)].map(_ => (
    // c = new random command (0, 1 or 2)
    // Append new line and new command to s.
    s += `\n${c = Math.random() * 3 | 0}:(`,

    // Append new command to l.
    l += c,

    // For each door ...
    d = d.map((v, i) => (
      // If the door is in motion, update its opening state.
      // Clear the 'in motion' bit if a bound is reached (either closed or fully open).
      v = v & 8 ? v & 16 ? v - 27 ? v + 1 : 20 : v - 9 ? v - 1 : 0 : v,

      // If the current command is intended for this door, update its direction and
      // 'in motion' bit. Direction is changed on the 'stopped => moving' transition.
      v ^= c + ~i ? 0 : v & 8 || 24,

      // Translate the door state in plain text and append it to s
      s +=
        'LR'[i] +
        `:${(v & 7) * 25}% ` +
        (v & 8 ? v & 16 ? 'opening' : 'closing' : 'stopped') +
        ',)'[i],

      // Value to be taken into account by map()
      v
    ))
  )),

  // Final result to be returned
  l + s
)

Demo

let f =
_=>(d=[0,0],l=s='',[...Array(60)].map(_=>(s+=`
${c=Math.random()*3|0}:(`,l+=c,d=d.map((v,i)=>(v=v&8?v&16?v-27?v+1:20:v-9?v-1:0:v,v^=c+~i?0:v&8||24,s+='LR'[i]+`:${(v&7)*25}% `+(v&8?v&16?'opening':'closing':'stopped')+',)'[i],v)))),l+s)

console.log(f())


问:
PKCS#7 padding validation
In cryptography, PKCS#7 padding is a padding scheme which adds a number of bytes N ≥ 1, where the value of each added byte is equal to N.

For example, Hello, World!, which has 13 bytes, is the following in hex:

```<code>48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21
</code>```

If we choose to PKCS#7 pad to length 16, then the result is:

```<code>48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 03 03 03
</code>```

And if we choose to pad to length 20, then the result is:

```<code>48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 07 07 07 07 07 07 07
</code>```

Note that in the first example we add three 03 bytes, and in the second we add seven 07 bytes.

Your task will be to validate whether a string (or integer array) has correct PKCS#7 padding. That is, if the last byte of the input string is N, then your program should check that the last N bytes of the string are equal to N.

Input

A single nonempty ASCII string containing characters between code points 1 and 127 inclusive. If you wish, you may take input as an array of integers instead.

Output

A truthy value if the input string has valid PKCS#7 padding, otherwise a falsy value.

Both functions and full programs are acceptable. This is code-golf, so the aim is to minimise the number of bytes in your code.

Test cases

The integer array version of inputs is presented here — the string version would have unprintable characters for many of the following test cases:

Truthy:

```<code>[1]
[1, 1]
[2, 1]
[2, 2]
[5, 6, 5, 3, 3, 3]
[1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2]
[95, 115, 80, 32, 71, 7, 122, 49, 13, 7, 7, 7, 7, 7, 7, 7, 7]
[27, 33, 54, 65, 97, 33, 52, 55, 60, 1, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
[15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15]
</code>```

Falsy:

```<code>[2]
[1, 2]
[5, 5, 5, 5]
[5, 6, 5, 4, 4, 4]
[3, 3, 3, 94, 3, 3]
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 127]
[50, 39, 94, 105, 49, 29, 74, 102, 2, 106, 44, 7, 7, 7, 7, 7, 7]
[26, 27, 59, 25, 122, 110, 20, 30, 114, 6, 9, 62, 121, 42, 22, 60, 33, 12]
</code>```

答:
C 91 Bytes

```<code>int f(int*l){int n;for(n=0;l[++n];);l+=n-1;for(int i=*l;i;)if(l[-i--+1]^*l||n<*l)return 0;}
</code>```

Input: a pointer to a null-terminated array.

Output: returns 0 for invalid padding and non-zero for valid (the last element in the array)

Examples:

```<code>int a[] = {5, 6, 5, 3, 3, 3, 0};
printf("%d\n", f(&a[5], 6));

int b[] = {1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 0};
printf("%d\n", f(&b[11],12 ));

int m[] = {5, 6, 5, 4, 4, 4, 0};
printf("%d\n", f(&m[5], 6));

int n[] = {3, 3, 3, 94, 3, 3, 0};
printf("%d\n", f(&n[5], 6));
</code>```

Gives:

```<code>3
2
0
0
</code>```

This does rely on undefined behavior. If the padding is valid there is no return statement, but using gcc -std=c99 this returns the last element of the array that was passed in (at least on my machine).

Title: PKCS#7 padding validation

Body:
C 91 Bytes

int f(int*l){int n;for(n=0;l[++n];);l+=n-1;for(int i=*l;i;)if(l[-i--+1]^*l||n<*l)return 0;}

Input: a pointer to a null-terminated array.

Output: returns 0 for invalid padding and non-zero for valid (the last element in the array)

Examples:

int a[] = {5, 6, 5, 3, 3, 3, 0};
printf("%d\n", f(&a[5], 6));

int b[] = {1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 0};
printf("%d\n", f(&b[11],12 ));

int m[] = {5, 6, 5, 4, 4, 4, 0};
printf("%d\n", f(&m[5], 6));

int n[] = {3, 3, 3, 94, 3, 3, 0};
printf("%d\n", f(&n[5], 6));

Gives:

3
2
0
0

This does rely on undefined behavior. If the padding is valid there is no return statement, but using gcc -std=c99 this returns the last element of the array that was passed in (at least on my machine).


问:
Stock Exchange KoTH
The stock market is all about the speed of knowledge. Unlike previous challenges, the current stock price is not random: it is determined by those playing the game.  If you can identify an under-priced stock before anybody else, then you've written yourself a money-making program.

Price refers to the how much people are trading the stock for, while Value refers to the amount the stock is worth at the end of the game.

Each player starts with 1000 of each stock, and 0 relative net worth.  Each stock has a secret value, and your score at the end of the game is (stockValue for each ownedStock) + netWorth.  Your net worth can be negative.  In an N-player game, there are N stocks.

Steps:

The game follows the following steps:

You are given the secret value of a single stock.

You make an offer to sell X of Y stock for $Z

All players are given the offers, and each may choose one to accept

All players are informed of accepted offers

Go back to step 2

Each of the steps are given in detail below:

void secretValue(int stockType, int value):

The value you learn is not revealed to any other player.

The value is between 0 and 1000

Low values are more like to occur than high values (squared uniform distribution)

Offer makeOffer(List<Stock> currentStock)

You can return null to make no offer.

Offer acceptOffer(List<Offer> offers)

You can return null to accept none of them

If there are no available offers, this will not be called

If you accept, your net worth goes down by $Z (can go negative) and receive X of Y stock.  The opposite occurs with the seller.

If you accept an offer, the exchange will occur immediately, and the offer will be removed so additional players cannot accept it.

void acceptedOffers(List<Offer> offers)

Includes your accepted offers as well

Static variables or writing to files is not allowed.  (No persistent data from game to game)  Non-serious contenders are allowed.

Interfaces:

```<code>public final class Stock {
    public Stock(int stockType, int amount);
    public int getType();
    public int getAmount();
    public Stock minus(Stock other);
    public Stock plus(Stock other);
    public Stock minus(int amount);
    public Stock plus(int amount);
    public Stock setAmount(int amount);
}
public class Offer {
    public Offer(Stock offer, int payment);
    public Stock getOffer();
    public int getPayment();
}
</code>```

Non-Java submissions:

All calls consist of two lines: The first line is the function being called: SecretValue, MakeOffer, AcceptOffer, AcceptedOffers, SetRandom, and the second line containing the actual data.

Stocks are formatted with a : delimiter: stockType:stockAmount.

Offers are formatted with a @ delimiter: offer@price

Lists are formatted with a ; delimiter

SecretValue is formatted with a : delimiter: stockType:value

RandomSeed is used to make your submission deterministic.  If your submission uses randomness, please use the integer value passed as the seed!

All function calls need a response.  If the response is null or void, return an empty string.

Please include a command.txt that gives the command line arguments to run your submission

Scoring

Games consisting of 1000 turns will be run multiple times.  Players will be scored according to the ELO system, and paired with players of similar skill levels.  The player with the highest final ELO score wins!  (I've modified the system so that each game, ELO scores are updated for each player pairing)

The controller includes an autodownloader, so please start your submission with a header: Name, Language.  If your submission is not in Java, each code block should start with the name of the file.  (excluding the command file, which should be the first block in your post)

Running

There are 2 ways to run this project:

Download the source code, compile and run.  You can find the source on Github.  Run git clone --recursive https://github.com/nathanmerrill/StockExchange.git

Download the JAR executable.  Submissions should be placed in your current working directory in the /submissions folder.  You can download just the JAR, just the submissions, or both

Pass in run to run the project (default option), or pass in download to download all submissions so far from this question.

Scoreboard

```<code>1.  1308.1220497323848  Cheater
2.  1242.0333695640356  InsideTrader
3.  1158.3662658295411  UncleScrooge
4.  1113.8344000358493  BlackMarket
5.  1051.8370015258993  DartMonkey
6.  983.0545446731494   WarGamer
7.  939.457423938002    Spammer
8.  901.4372529538886   DumbBot
9.  859.0519326039137   ShutUpAndTakeMyMoney
10. 852.9448222849587   VincentKasuga
11. 718.2112067329083   Profiteer
</code>```

答:
WarGamer, Java

Upon a perfunctory examination of the rules I have decided that the primary winning move is not to play. Anyone offering to sell stock likely knows the price and will profit from the sale. It can be toggled so it will make "joke" offers to sell a stock for Integer.MAX_VALUE dollars hoping shut up and take my money will bite.

import java.util.List;
import com.ppcg.stockexchange.*;
import com.ppcg.kothcomm.game.AbstractPlayer;
import com.ppcg.kothcomm.utils.Tools;

import java.util.List;

public class WarGamer extends Player {
static final boolean FRAUD = false;
    /**
     * @param offers All available offers
     * @return An offer you want to accept, or null if you want to accept neither.
     */
    public Offer acceptOffer(List<Offer> offers){
        return null;
    }

    public Offer makeOffer(List<Stock> currentStock){
    if(FRAUD)
    return new Offer(new Stock(0,1),Integer.MAX_VALUE);
        //defraud shut up and take my money
    return null;
    }
}
```

Title: Stock Exchange KoTH


问:
Implement a Truth-Machine
A truth-machine (credits goes to this guy for coming up with it) is a very simple program designed to demonstrate the I/O and control flow of a language. Here's what a truth-machine does:

Gets a number (either 0 or 1) from STDIN.

If that number is 0, print out 0 and terminate.

If that number is 1, print out 1 forever.

Challenge

Write a truth-machine as described above in your language of choice. The truth-machine must be a full program that follows these rules:

take input from STDIN or an acceptable alternative

If your language cannot take input from STDIN, it may take input from a hardcoded variable or suitable equivalent in the program

must output to STDOUT or an acceptable alternative

If your language is incapable of outputting the characters 0 or 1, byte or unary I/O is acceptable.

when the input is 1, it must continually print 1s and only stop if the program is killed or runs out of memory

the output must only be either a 0 followed by either one or no newline or space, or infinite 1s with each 1 followed by either one or no newline or space. No other output can be generated, except constant output of your language's interpreter that cannot be suppressed (such as a greeting, ANSI color codes or indentation). Your usage of newlines or spaces must be consistent: for example, if you choose to output 1 with a newline after it all 1s must have a newline after them.

if and only if your language cannot possibly terminate on an input of 0 it is acceptable for the code to enter an infinite loop in which nothing is outputted.

Since this is a catalog, languages created after this challenge are allowed to compete. Note that there must be an interpreter so the submission can be tested. It is allowed (and even encouraged) to write this interpreter yourself for a previously unimplemented language. Other than that, all the standard rules of code-golf must be obeyed. Submissions in most languages will be scored in bytes in an appropriate preexisting encoding (usually UTF-8).

Catalog

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```<code>## Language Name, N bytes
</code>```

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:

```<code>## Ruby, <s>104</s> <s>101</s> 96 bytes
</code>```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:

```<code>## Perl, 43 + 2 (-p flag) = 45 bytes
</code>```

You can also make the language name a link which will then show up in the snippet:

```<code>## [><>](http://esolangs.org/wiki/Fish), 121 bytes
</code>```

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

Shortest Solution by Language

Language	User	Score

Leaderboard

	Author	Language	Size

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

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

```

答:
PowerShell, 22 21 bytes

Variable $a into the pipeline, prints once, then prints again if the input evaluates as true. Less elegant than TimmyD's but shorter.

```<code>$a|%{$_;while($_){$_}}
</code>```

After looking at his though it could also be written as below, dropping it to 21 bytes

```<code>$a|%{do{$_}while($_)}
</code>```

Title: Implement a Truth-Machine

Body:
PowerShell, 22 21 bytes

Variable $a into the pipeline, prints once, then prints again if the input evaluates as true. Less elegant than TimmyD's but shorter.

$a|%{$_;while($_){$_}}

After looking at his though it could also be written as below, dropping it to 21 bytes

$a|%{do{$_}while($_)}


答:
ShutUpAndTakeMyMoney, Java

```<code>import java.util.List;
import com.ppcg.stockexchange.*;

public class ShutUpAndTakeMyMoney extends Player {
    public ShutUpAndTakeMyMoney() {}

    public Offer acceptOffer(List<Offer> offers) {
        try {
            return offers.get(0);
        } catch (Exception ex) {
            return null;
        }
    }
    public Offer makeOffer(List<Stock> stock) {
        return null;
    }
}
</code>```

It accepts any offer.

Title: Stock Exchange KoTH

Body:
The stock market is all about the speed of knowledge. Unlike previous challenges, the current stock price is not random: it is determined by those playing the game.  If you can identify an under-priced stock before anybody else, then you've written yourself a money-making program.

Price refers to the how much people are trading the stock for, while Value refers to the amount the stock is worth at the end of the game.

Each player starts with 1000 of each stock, and 0 relative net worth.  Each stock has a secret value, and your score at the end of the game is (stockValue for each ownedStock) + netWorth.  Your net worth can be negative.  In an N-player game, there are N stocks.

Steps:

The game follows the following steps:

You are given the secret value of a single stock.

You make an offer to sell X of Y stock for $Z

All players are given the offers, and each may choose one to accept

All players are informed of accepted offers

Go back to step 2

Each of the steps are given in detail below:

void secretValue(int stockType, int value):

The value you learn is not revealed to any other player.

The value is between 0 and 1000

Low values are more like to occur than high values (squared uniform distribution)

Offer makeOffer(List<Stock> currentStock)

You can return null to make no offer.

Offer acceptOffer(List<Offer> offers)

You can return null to accept none of them

If there are no available offers, this will not be called

If you accept, your net worth goes down by $Z (can go negative) and receive X of Y stock.  The opposite occurs with the seller.

If you accept an offer, the exchange will occur immediately, and the offer will be removed so additional players cannot accept it.

void acceptedOffers(List<Offer> offers)

Includes your accepted offers as well

Static variables or writing to files is not allowed.  (No persistent data from game to game)  Non-serious contenders are allowed.

Interfaces:

```<code>public final class Stock {
    public Stock(int stockType, int amount);
    public int getType();
    public int getAmount();
    public Stock minus(Stock other);
    public Stock plus(Stock other);
    public Stock minus(int amount);
    public Stock plus(int amount);
    public Stock setAmount(int amount);
}
public class Offer {
    public Offer(Stock offer, int payment);
    public Stock getOffer();
    public int getPayment();
}
</code>```

Non-Java submissions:

All calls consist of two lines: The first line is the function being called: SecretValue, MakeOffer, AcceptOffer, AcceptedOffers, SetRandom, and the second line containing the actual data.

Stocks are formatted with a : delimiter: stockType:stockAmount.

Offers are formatted with a @ delimiter: offer@price

Lists are formatted with a ; delimiter

SecretValue is formatted with a : delimiter: stockType:value

RandomSeed is used to make your submission deterministic.  If your submission uses randomness, please use the integer value passed as the seed!

All function calls need a response.  If the response is null or void, return an empty string.

Please include a command.txt that gives the command line arguments to run your submission

Scoring

Games consisting of 1000 turns will be run multiple times.  Players will be scored according to the ELO system, and paired with players of similar skill levels.  The player with the highest final ELO score wins!  (I've modified the system so that each game, ELO scores are updated for each player pairing)

The controller includes an autodownloader, so please start your submission with a header: Name, Language.  If your submission is not in Java, each code block should start with the name of the file.  (excluding the command file, which should be the first block in your post)

Running

There are 2 ways to run this project:

Download the source code, compile and run.  You can find the source on Github.  Run git clone --recursive https://github.com/nathanmerrill/StockExchange.git

Download the JAR executable.  Submissions should be placed in your current working directory in the /submissions folder.  You can download just the JAR, just the submissions, or both

Pass in run to run the project (default option), or pass in download to download all submissions so far from this question.

Scoreboard

```<code>1.  1308.1220497323848  Cheater
2.  1242.0333695640356  InsideTrader
3.  1158.3662658295411  UncleScrooge
4.  1113.8344000358493  BlackMarket
5.  1051.8370015258993  DartMonkey
6.  983.0545446731494   WarGamer
7.  939.457423938002    Spammer
8.  901.4372529538886   DumbBot
9.  859.0519326039137   ShutUpAndTakeMyMoney
10. 852.9448222849587   VincentKasuga
11. 718.2112067329083   Profiteer
</code>```

Body:
ShutUpAndTakeMyMoney, Java

import java.util.List;
import com.ppcg.stockexchange.*;

public class ShutUpAndTakeMyMoney extends Player {
    public ShutUpAndTakeMyMoney() {}

    public Offer acceptOffer(List<Offer> offers) {
        try {
            return offers.get(0);
        } catch (Exception ex) {
            return null;
        }
    }
    public Offer makeOffer(List<Stock> stock) {
        return null;
    }
}

It accepts any offer.


问:
Four weights to produce integer scale differences from 0 through 40 pounds
Just-in-time edit: I decided to reveal part of the answer and highlight a single aspect of the challenge.

Show how 4 weights, of 1, 3,  9, and 27 lbs. can be used to produce "weight differences" from 0 to 40 lbs.

You have a two - pan balance scale.

We define the difference in pan weights as the total weight placed on the left pan minus the total weight on the right pan.

The difference in pan weights for the empty scale is 0 lbs.

You have 4 rocks, a,b,c, and d, weighing 1, 3, 9 and 27 lbs respectively

Show how you can produce all integer weight differences from 0 to 40 lbs.

Simpler example:

Problem: With weights of 1 and 3 lbs. show how you can generate all weight differences from 0 to 4 lbs.

Output: for a=1, b=3;

For the 4 weight, 40 pound version, your output should consist of
a table with columns displaying the weight difference, the symbolic amounts in each pan, and the absolute weights in each pan.

You may format the table in a way congenial to the language you are coding in.

Scoring: Shortest code wins

Bonus: 50% of your score if the same code can present the results for the case where 3, 4, and 5 weights are used (for 13, 40, and 121 lbs.)

答:
Perl, 201 (or 166) chars + 50% bonus = 100.5 (or 83)

eek, brute forcing this turned out to be more complex than i anticipated. im interested to see others' certainly more analytical approaches

change the problem size by modifying the value of $j defined at the top to 3, 4, or 5.

this will demonstrate all ways to generate the differences, not any pairs in particular.

some additional characters are used to print the differences in order. otherwise, you can remove the outer for$n(0..$s){} loop and the $$x[$j]-$$_[$j]==$n test to save 14+21 chars for a total of 166 chars.

```<code>$k=($j=4)-1;@a=map{$s=0;$s+=$_ for@$_;[@$_,$s]}map{$c=$_;[map{$c&1<<$_&&3**$_}0..$k]}0..2**$j-1;for$n(0..$s){for$x(@a){$$x[$j]-$$_[$j]==$n&&print"$n {@$x[0..$k],@$_[0..$k]} {$$x[$j],$$_[$j]}",$/for@a}}
</code>```

or slightly more formatted (no more readable):

```<code># set $j to the problem domain size
$k = ($j = 4) - 1;

# gather up all possible combinations and their sums
@a = map{ $s=0; $s+=$_ for @$_; [@$_,$s] } map { $c=$_; [map { $c & 1<<$_ && 3**$_ } 0..$k] } 0 .. 2**$j-1;

# walk through the pairs of combinations and find the differences
for $n (0..$s)
{
  for $x (@a)
  {
    $$x[$j] - $$_[$j] == $n &&
      print "$n {@$x[0..$k],@$_[0..$k]} {$$x[$j],$$_[$j]}", $/ for @a
  }
}
</code>```

Body:
Perl, 201 (or 166) chars + 50% bonus = 100.5 (or 83)

eek, brute forcing this turned out to be more complex than i anticipated. im interested to see others' certainly more analytical approaches

change the problem size by modifying the value of $j defined at the top to 3, 4, or 5.

this will demonstrate all ways to generate the differences, not any pairs in particular.

some additional characters are used to print the differences in order. otherwise, you can remove the outer for$n(0..$s){} loop and the $$x[$j]-$$_[$j]==$n test to save 14+21 chars for a total of 166 chars.

$k=($j=4)-1;@a=map{$s=0;$s+=$_ for@$_;[@$_,$s]}map{$c=$_;[map{$c&1<<$_&&3**$_}0..$k]}0..2**$j-1;for$n(0..$s){for$x(@a){$$x[$j]-$$_[$j]==$n&&print"$n {@$x[0..$k],@$_[0..$k]} {$$x[$j],$$_[$j]}",$/for@a}}

or slightly more formatted (no more readable):

# set $j to the problem domain size
$k = ($j = 4) - 1;

# gather up all possible combinations and their sums
@a = map{ $s=0; $s+=$_ for @$_; [@$_,$s] } map { $c=$_; [map { $c & 1<<$_ && 3**$_ } 0..$k] } 0 .. 2**$j-1;

# walk through the pairs of combinations and find the differences
for $n (0..$s)
{
  for $x (@a)
  {
    $$x[$j] - $$_[$j] == $n &&
      print "$n {@$x[0..$k],@$_[0..$k]} {$$x[$j],$$_[$j]}", $/ for @a
  }
}


问:
Highlight the Bounding Box, Part II: Hexagonal Grid
You're given a hexagonal grid of the characters . and #, like this:

```<code> . . . . . . . .
. . . . # . . .
 . # . . . # . .
. . . # . . . .
 . . . . . # . .
. . . . . . . .
</code>```

Your task is to fill the entire axis-aligned bounding box of the # with further #:

```<code> . . . . . . . .
. . # # # # . .
 . # # # # # . .
. . # # # # # .
 . . # # # # . .
. . . . . . . .
</code>```

The axis-aligned bounding box is the smallest convex hexagonal shape which contains all the #. Note that in the case of the hexagonal grid, there are three axes to consider (W/E, SW/NE, NW/SE):

Here is another example to show that in some cases, one or more sides will contain only one #:

```<code>. . . . . . . .         . . . . . . . .
 . # . . . . . .         . # # # # . . .
. . . . . # . .         . . # # # # . .
 . . # . . . . .         . . # # # . . .
. . . . . . . .         . . . . . . . .
</code>```

You can either view these as hexagons with degenerate sides, or you can draw the bounding box around them, like I have done above, in which case they are still hexagons:

Too hard? Try Part I!

Rules

You may use any two distinct non-space printable ASCII characters (0x21 to 0x7E, inclusive), in place of # and .. I'll continue referring to them as # and . for the remainder of the specification though.

Input and output may either be a single linefeed-separated string or a list of strings (one for each line), but the format has to be consistent.

You may assume that the input contains at least one # and all lines are the same length. Note that there are two different "kinds" of lines (starting with a space or a non-space) - you may not assume that the input always starts with the same type. You may assume that the bounding box always fits inside the grid you are given.

You may write a program or a function and use any of the our standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

Each test case has input and output next to each other.

```<code>#    #

 . .      . .
# . #    # # #
 . .      . .

 . #      . #
. . .    . # .
 # .      # .

 # .      # .
. . .    . # .
 . #      . #

 # .      # .
# . .    # # .
 . #      # #

 . #      # #
# . .    # # #
 . #      # #

. . #    . # #
 . .      # #
# . .    # # .

# . .    # # .
 . .      # #
. . #    . # #

. . . . . . . .         . . . . . . . .
 . . # . # . . .         . . # # # . . .
. . . . . . . .         . . . # # . . .
 . . . # . . . .         . . . # . . . .

. . . . . . . .         . . . . . . . .
 . . # . . . # .         . . # # # # # .
. . . . . . . .         . . . # # # # .
 . . . # . . . .         . . . # # # . .

. . . . . . . .         . . . . . . . .
 . # . . . . . .         . # # # # . . .
. . . . . # . .         . . # # # # . .
 . . . . . . . .         . . . . . . . .

. . . . . . . .         . . . . . . . .
 . # . . . . . .         . # # # # . . .
. . . . . # . .         . . # # # # . .
 . . # . . . . .         . . # # # . . .

. . . . # . . .         . . # # # # . .
 . # . . . # . .         . # # # # # . .
. . . # . . . .         . . # # # # # .
 . . . . . # . .         . . # # # # . .
</code>```

答:
Jelly, <s>45</s> <s>3513</s> <s>42</s> 41 bytes

```<code>Ṁ€»\
ṚÇṚ«Çṁ"
ŒDṙZL$ÇṙL’$ŒḌ«Ç
ṚÇṚ«Ç
n⁶aÇo⁶
</code>```

This is a list of links; the last one has to be called on the input to produce the output.

I/O is in form of string arrays, where . indicates empty and @ indicates filled.

Try it online! or verify all test cases.

Background

Let's consider the following example.

```<code>. . . . . . . .
 . @ . . . . . .
. . . . . @ . .
 . . @ . . . . .
</code>```

By drawing a pair or parallel lines – the closest pair that encloses all filled positions – in each of the three directions, we can determine the hexagonal bounding box.

In the implementation, we replace all characters between those two lines with @, and everything outside these lines with ., with the possible exception of diagonals that only contains spaces).

For the horizontal axis, this gives

```<code>................
@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@
</code>```

for the falling diagonal axis, it gives

```<code>..@@@@@@@......
...@@@@@@@......
....@@@@@@@.....
 ....@@@@@@@....
</code>```

and for the raising diagonal axis, it gives

```<code>....@@@@@@@@@...
...@@@@@@@@@....
..@@@@@@@@@....
.@@@@@@@@@.... .
</code>```

By taking the character-wise minimum of all three, since . < @, we get

```<code>...............
...@@@@@@@......
....@@@@@@@....
 ....@@@@@.... .
</code>```

All that's left to do is restoring the spaces.

How it works

```<code>n⁶aÇo⁶           Main link. Argument: A (array of strings)

n⁶               Not-equal space; yield 0 for spaces, 1 otherwise.
  aÇ             Take the logical AND with the result the 4th helper link.
                 This will replace 1's (corresponding to non-space characters) with
                 the corresponding character that result from calling the link.
    o⁶           Logical OR with space; replaces the 0's with spaces.
</code>```

```<code>ṚÇṚ«Ç            4th helper link. Argument: A

Ṛ                Reverse the order of the strings in A.
 Ç               Call the 3rd helper link.
  Ṛ              Reverse the order of the strings in the resulting array.
    Ç            Call the 3rd helper link with argument A (unmodified).
   «             Take the character-wise minimum of both results.
</code>```

```<code>ŒDṙZL$ÇṙL’$ŒḌ«Ç  3rd helper link. Argument: L (array of strings)

ŒD               Yield all falling diagonals of L. This is a reversible operation,
                 so it begins with the main diagonal.
   ZL$           Yield the length of the transpose (number of columns).
  ṙ              Shift the array of diagonals that many units to the left.
                 This puts the diagonals in their natural order.
      Ç          Call the helper link on the result.
        L’$      Yield the decremented length (number of columns) of L.
       ṙ         Shift the result that many units to the left.
                 This puts the changed diagonals in their original order.
           ŒḌ    Undiagonal; reconstruct the string array.
              Ç  Call the 2nd helper link with argument L (unmodified).
             «   Take the character-wise minimum of both results.
</code>```

```<code>ṚÇṚ«Çṁ"          2nd helper link. Argument: M (array)

Ṛ                Reverse the rows of M.
 Ç               Call the 1st helper link on the result.
  Ṛ              Reverse the rows of the result.
    Ç            Call the 1nd helper link with argument M (unmodified).
   «             Take the minimum of both results.
     ṁ"          Mold zipwith; repeat each character in the result to the left
                 as many times as needed to fill the corresponding row of M.
</code>```

```<code>. . . . . . . .
 . @ . . . . . .
. . . . . @ . .
 . . @ . . . . .
</code>```0

Body:
Jelly, <s>45</s> <s>3513</s> <s>42</s> 41 bytes

Ṁ€»\
ṚÇṚ«Çṁ"
ŒDṙZL$ÇṙL’$ŒḌ«Ç
ṚÇṚ«Ç
n⁶aÇo⁶

This is a list of links; the last one has to be called on the input to produce the output.

I/O is in form of string arrays, where . indicates empty and @ indicates filled.

Try it online! or <a href="http://jelly.tryitonline.net/#code=4bmA4oKswrtcCuG5msOH4bmawqvDh-G5gSIKxZJE4bmZWkwkw4fhuZlM4oCZJMWS4biMwqvDhwrhuZrDh-G5msKrw4cKbuKBtmHDh2_igbYK4bu0w4dZCsWT4bmj4oCcwrbCtuKAncOH4oKsauKAnMK2wrbigJ0&input=&args=QAoKIC4gLiAKQCAuIEAKIC4gLiAKCiAuIEAgCi4gLiAuCiBAIC4gCgogQCAuIAouIC4gLgogLiBAIAoKIEAgLiAKQCAuIC4KIC4gQCAKCiBAIEAgCkAgQCBACiBAIEAgCgouIC4gLiAuIC4gLiAuIC4gCiAuIC4gQCAuIEAgLiAuIC4KLiAuIC4gLiAuIC4gLiAuIAogLiAuIC4gQCAuIC4gLiAuCgouIC4gLiAuIC4gLiAuIC4gCiAuIC4gQCAuIC4gLiBAIC4KLiAuIC4gLiAuIC4gLiAuIAogLiAuIC4gQCAuIC4gLiAuCgouIC4gLiAuIC4gLiAuIC4gCiAuIEAgLiAuIC4gLiAuIC4KLiAuIC4gLiAuIEAgLiAuIAogLiAuIC4gLiAuIC4gLiAuCgouIC4gLiAuIC4gLiAuIC4gCiAuIEAgLiAuIC4gLiAuIC4KLiAuIC4gLiAuIEAgLiAuIAogLiAuIEAgLiAuIC4gLiAuCgouIC4gQCAuIEAgLiAuIC4gCiAuIEAgLiAuIC4gQCAuIC4KLiAuIC4gQCAuIEAgQCAuIAogLiAuIEAgLiAuIEAgLiAu" rel="nofollow">verify all test cases.

Background

Let's consider the following example.

. . . . . . . .
 . @ . . . . . .
. . . . . @ . .
 . . @ . . . . .

By drawing a pair or parallel lines – the closest pair that encloses all filled positions – in each of the three directions, we can determine the hexagonal bounding box.

In the implementation, we replace all characters between those two lines with @, and everything outside these lines with ., with the possible exception of diagonals that only contains spaces).

For the horizontal axis, this gives

................
@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@
@@@@@@@@@@@@@@@@

for the falling diagonal axis, it gives

..@@@@@@@......
...@@@@@@@......
....@@@@@@@.....
 ....@@@@@@@....

and for the raising diagonal axis, it gives

....@@@@@@@@@...
...@@@@@@@@@....
..@@@@@@@@@....
.@@@@@@@@@.... .

By taking the character-wise minimum of all three, since . < @, we get

...............
...@@@@@@@......
....@@@@@@@....
 ....@@@@@.... .

All that's left to do is restoring the spaces.

How it works

n⁶aÇo⁶           Main link. Argument: A (array of strings)

n⁶               Not-equal space; yield 0 for spaces, 1 otherwise.
  aÇ             Take the logical AND with the result the 4th helper link.
                 This will replace 1's (corresponding to non-space characters) with
                 the corresponding character that result from calling the link.
    o⁶           Logical OR with space; replaces the 0's with spaces.

ṚÇṚ«Ç            4th helper link. Argument: A

Ṛ                Reverse the order of the strings in A.
 Ç               Call the 3rd helper link.
  Ṛ              Reverse the order of the strings in the resulting array.
    Ç            Call the 3rd helper link with argument A (unmodified).
   «             Take the character-wise minimum of both results.

ŒDṙZL$ÇṙL’$ŒḌ«Ç  3rd helper link. Argument: L (array of strings)

ŒD               Yield all falling diagonals of L. This is a reversible operation,
                 so it begins with the main diagonal.
   ZL$           Yield the length of the transpose (number of columns).
  ṙ              Shift the array of diagonals that many units to the left.
                 This puts the diagonals in their natural order.
      Ç          Call the helper link on the result.
        L’$      Yield the decremented length (number of columns) of L.
       ṙ         Shift the result that many units to the left.
                 This puts the changed diagonals in their original order.
           ŒḌ    Undiagonal; reconstruct the string array.
              Ç  Call the 2nd helper link with argument L (unmodified).
             «   Take the character-wise minimum of both results.

ṚÇṚ«Çṁ"          2nd helper link. Argument: M (array)

Ṛ                Reverse the rows of M.
 Ç               Call the 1st helper link on the result.
  Ṛ              Reverse the rows of the result.
    Ç            Call the 1nd helper link with argument M (unmodified).
   «             Take the minimum of both results.
     ṁ"          Mold zipwith; repeat each character in the result to the left
                 as many times as needed to fill the corresponding row of M.

Ṁ€»\             1st helper link. Argument: N (array)

Ṁ€               Take the maximum of each row of N.
  »\             Take the cumulative maxima of the resulting characters.


问:
Duplicate & switch case
The goal is, having taken a string as input, duplicate each latin letter and "toggle" its case (i.e. uppercase becomes lowercase and vice-versa).

Example inputs & outputs:

```<code>Input      Output
bad        bBaAdD
Nice       NniIcCeE
T e S t    Tt eE Ss tT
s E t      sS Ee tT
1!1!1st!   1!1!1sStT!
n00b       nN00bB
(e.g.)     (eE.gG.)
H3l|@!     Hh3lL|@!
</code>```

The input consists of printable ASCII symbols.

You shouldn't duplicate non-latin letters, numbers, special chars.

答:
PowerShell, 102 Bytes

```<code>-join([char[]]$args[0]|%{$_;if($_-cmatch'[A-Z]'){"$_".ToLower()}if($_-cmatch'[a-z]'){"$_".ToUpper()}})
</code>```

Run the script with an argument like so:

```<code>PS C:\PretendDirectory> .\DupeCase.ps1 "Hello World ?!!1"
HheElLlLoO WwoOrRlLdD ?!!1
</code>```

Ungolfed:

```<code>-join([char[]]$args[0] | % {
    $_
    if($_-cmatch'[A-Z]'){
        "$_".ToLower()
    }
    if($_-cmatch'[a-z]'){
        "$_".ToUpper()
    }
})
</code>```

Explanation:

This script splits the argument from a string into a character array, and loops through the array. It returns a given character then, if it's an upper case letter between A and Z returns a lowercase version using the built in function, does the same for lowercase letters. To wrap up it joins the array into a single string.

Title: Duplicate & switch case

Body:
PowerShell, 102 Bytes

-join([char[]]$args[0]|%{$_;if($_-cmatch'[A-Z]'){"$_".ToLower()}if($_-cmatch'[a-z]'){"$_".ToUpper()}})

Run the script with an argument like so:

PS C:\PretendDirectory> .\DupeCase.ps1 "Hello World ?!!1"
HheElLlLoO WwoOrRlLdD ?!!1

Ungolfed:

-join([char[]]$args[0] | % {
    $_
    if($_-cmatch'[A-Z]'){
        "$_".ToLower()
    }
    if($_-cmatch'[a-z]'){
        "$_".ToUpper()
    }
})

Explanation:

This script splits the argument from a string into a character array, and loops through the array. It returns a given character then, if it's an upper case letter between A and Z returns a lowercase version using the built in function, does the same for lowercase letters. To wrap up it joins the array into a single string.


答:
DumbBot, Java

Use this bot when creating your own.  Offers its secret stock at a discounted price.

```<code>import java.util.List;
import com.ppcg.stockexchange.*;
public class DumbBot extends Player {
    public Offer acceptOffer(List<Offer> offers) {
        return null;
    }
    public Offer makeOffer(List<Stock> currentStock){
        return new Offer(currentStock.get(secretStockType).setAmount(1), Math.max(1, secretStockValue - 5));
    }
    public void secretValue(int stockType, int value) {
        super.secretValue(stockType, value);
    }
    public void acceptedOffers(List<Offer> acceptedOffers) {
    }
}
</code>```

Title: Stock Exchange KoTH

Body:
DumbBot, Java

Use this bot when creating your own.  Offers its secret stock at a discounted price.

import java.util.List;
import com.ppcg.stockexchange.*;
public class DumbBot extends Player {
    public Offer acceptOffer(List<Offer> offers) {
        return null;
    }
    public Offer makeOffer(List<Stock> currentStock){
        return new Offer(currentStock.get(secretStockType).setAmount(1), Math.max(1, secretStockValue - 5));
    }
    public void secretValue(int stockType, int value) {
        super.secretValue(stockType, value);
    }
    public void acceptedOffers(List<Offer> acceptedOffers) {
    }
}


问:
Visible Buildings
This puzzle is derived from CodinGame SamSi's "Heart of the City" puzzle.

Description

You decide to take a walk in an n * n tile city and go to the center tile. All of the buildings are infinitely small, but you have super vision and can see everything close up and far away.

Constraints

n is always odd

You can see any building that is not directly obstructed by another one

Task

Mark each building visible with *. The building is visible iff it is not blocked by another building on the exact same line of vision.

In other words, if @ is the origin, the building is visible iff the x-coordinate and the y-coordinate are co-prime to each other.

Example input and output

Input:

```<code>7
</code>```

Output:

```<code> ** **
* * * *
*******
  *@*
*******
* * * *
 ** **
</code>```

* is a visible building,
 is an invisible building, and
@ is where you are.

Scoring

Remember, this is code-golf, so the answer with the least bytes wins.

var QUESTION_ID=91394,OVERRIDE_USER=59057;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}*{font-family:"Helvetica",sans-serif}</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

```

答:
Pyth, 40 bytes

```<code>L@"@* "hS[b2)jsMcQyM.aMiM*.**2[r_/Q2h/Q2
</code>```

I'm very new to Pyth, so this can likely be golfed further.

Try it online

How it works

```<code>L@"@* "hS[b2)jsMcQyM.aMiM*.**2[r_/Q2h/Q2

L@"@* "hS[b2)                              Lambda y. Input: b
L                                          Declare lambda
         [b2)                              List [b, 2]
        S                                  Sort ascending
       h                                   Head. Yield first element a, clamping to max 2
  "@* "                                    String literal "@* "
 @                                         Index into string with a, yielding string[a]

             jsMcQyM.aMiM*.**2[r_/Q2h/Q2   Program. Input: Q
                                _/Q2 /Q2   -Q//2 and Q//2
                                    h      Head. Q//2+1
                               r           Range [-Q//2, Q//2+1]
                              [            List
                            *2             Duplicate
                          .*               Splat. Unpack
                         *                 Cartesian product. Yield all coordinate pairs
                       iM                  Map GCD over above
                    .aM                    Map absolute value over above
                  yM                       Map y over above, yielding required characters
                cQ                         Chunk. Split above into Q pieces
              sM                           Map concatenate over above
             j                             Join on newlines
                                           Implicitly print
</code>```

Title: Visible Buildings

Body:
Pyth, 40 bytes

L@"@* "hS[b2)jsMcQyM.aMiM*.**2[r_/Q2h/Q2

I'm very new to Pyth, so this can likely be golfed further.

Try it online

How it works

L@"@* "hS[b2)jsMcQyM.aMiM*.**2[r_/Q2h/Q2

L@"@* "hS[b2)                              Lambda y. Input: b
L                                          Declare lambda
         [b2)                              List [b, 2]
        S                                  Sort ascending
       h                                   Head. Yield first element a, clamping to max 2
  "@* "                                    String literal "@* "
 @                                         Index into string with a, yielding string[a]

             jsMcQyM.aMiM*.**2[r_/Q2h/Q2   Program. Input: Q
                                _/Q2 /Q2   -Q//2 and Q//2
                                    h      Head. Q//2+1
                               r           Range [-Q//2, Q//2+1]
                              [            List
                            *2             Duplicate
                          .*               Splat. Unpack
                         *                 Cartesian product. Yield all coordinate pairs
                       iM                  Map GCD over above
                    .aM                    Map absolute value over above
                  yM                       Map y over above, yielding required characters
                cQ                         Chunk. Split above into Q pieces
              sM                           Map concatenate over above
             j                             Join on newlines
                                           Implicitly print


答:
python_starter, Python 3

Use this as a starting point for any python (or other language) programs

Accepts a random offer.

Command file:

```<code>python3 starter.py
</code>```

Program:

```<code>starter.py
import random
from functools import total_ordering

LIST_DELIMITER = ';'
STOCK_DELIMITER = ':'
OFFER_DELIMITER = '@'

@total_ordering
class Stock:
    @staticmethod
    def parse(string: str):
        return Stock(*map(int, string.split(STOCK_DELIMITER)))

    def __init__(self, stock_type: int, amount: int):
        self.type = stock_type
        self.amount = max(amount, 0)

    def __str__(self):
        return str(self.type)+STOCK_DELIMITER+str(self.amount)

    def __eq__(self, other):
        return self.amount == other.type

    def __lt__(self, other):
        return self.amount < other.amount

    def update(self, amount) -> 'Stock':
        return Stock(self.type, amount)

    def __mul__(self, other: int) -> 'Stock':
        return self.update(self.amount*other)

    def __floordiv__(self, other: int) -> 'Stock':
        return self.update(self.amount//other)

    def __add__(self, other: int) -> 'Stock':
        return self.update(self.amount+other)

    def __sub__(self, other: int) -> 'Stock':
        return self.update(self.amount-other)

class Offer:
    @staticmethod
    def parse(string: str) -> 'Offer':
        try:
            offer, payment = string.split(OFFER_DELIMITER)
        except ValueError:
            raise Exception("Cannot unpack "+string)
        return Offer(Stock.parse(offer), int(payment.strip()))

    def __init__(self, offer: Stock, payment: int):
        self.offer = offer
        self.payment = payment

    def __str__(self):
        return str(self.offer)+OFFER_DELIMITER+str(self.payment)

def read_stock_value(value: str):
    global hidden_price, hidden_stock
    stock, price = value.split(STOCK_DELIMITER)
    hidden_price = float(price)
    hidden_stock = int(stock)

def process_input():
    handlers = {
        "SecretValue": read_stock_value,
        "RandomSeed": read_seed,
        "MakeOffer": make_offer,
        "AcceptOffer": accept_offer,
        "AcceptedOffers": accepted_offers,
    }
    method = input().strip()
    data = input().strip()
    output = handlers[method](data)
    if output is not None:
        print(str(output))
    else:
        print()

def read_seed(seed: str):
    random.seed(int(seed))

def start():
    while True:
        process_input()

hidden_stock = None
hidden_price = None

def make_offer(current_stock: str):
    current_stock = map(Stock.parse, current_stock.split(LIST_DELIMITER))
    pass

def accept_offer(available_offers: str):
    available_offers = list(map(Offer.parse, available_offers.split(LIST_DELIMITER)))
    return random.sample(available_offers, 1)[0]

def accepted_offers(offers: str):
    offers = map(Offer.parse, offers.split(LIST_DELIMITER))
    pass

if __name__ == "__main__":
    start()
</code>```

Title: Stock Exchange KoTH

Body:
python_starter, Python 3

Use this as a starting point for any python (or other language) programs

Accepts a random offer.

Command file:

python3 starter.py

Program:

starter.py
import random
from functools import total_ordering

LIST_DELIMITER = ';'
STOCK_DELIMITER = ':'
OFFER_DELIMITER = '@'

@total_ordering
class Stock:
    @staticmethod
    def parse(string: str):
        return Stock(*map(int, string.split(STOCK_DELIMITER)))

    def __init__(self, stock_type: int, amount: int):
        self.type = stock_type
        self.amount = max(amount, 0)

    def __str__(self):
        return str(self.type)+STOCK_DELIMITER+str(self.amount)

    def __eq__(self, other):
        return self.amount == other.type

    def __lt__(self, other):
        return self.amount < other.amount

    def update(self, amount) -> 'Stock':
        return Stock(self.type, amount)

    def __mul__(self, other: int) -> 'Stock':
        return self.update(self.amount*other)

    def __floordiv__(self, other: int) -> 'Stock':
        return self.update(self.amount//other)

    def __add__(self, other: int) -> 'Stock':
        return self.update(self.amount+other)

    def __sub__(self, other: int) -> 'Stock':
        return self.update(self.amount-other)

class Offer:
    @staticmethod
    def parse(string: str) -> 'Offer':
        try:
            offer, payment = string.split(OFFER_DELIMITER)
        except ValueError:
            raise Exception("Cannot unpack "+string)
        return Offer(Stock.parse(offer), int(payment.strip()))

    def __init__(self, offer: Stock, payment: int):
        self.offer = offer
        self.payment = payment

    def __str__(self):
        return str(self.offer)+OFFER_DELIMITER+str(self.payment)

def read_stock_value(value: str):
    global hidden_price, hidden_stock
    stock, price = value.split(STOCK_DELIMITER)
    hidden_price = float(price)
    hidden_stock = int(stock)

def process_input():
    handlers = {
        "SecretValue": read_stock_value,
        "RandomSeed": read_seed,
        "MakeOffer": make_offer,
        "AcceptOffer": accept_offer,
        "AcceptedOffers": accepted_offers,
    }
    method = input().strip()
    data = input().strip()
    output = handlers[method](data)
    if output is not None:
        print(str(output))
    else:
        print()

def read_seed(seed: str):
    random.seed(int(seed))

def start():
    while True:
        process_input()

hidden_stock = None
hidden_price = None

def make_offer(current_stock: str):
    current_stock = map(Stock.parse, current_stock.split(LIST_DELIMITER))
    pass

def accept_offer(available_offers: str):
    available_offers = list(map(Offer.parse, available_offers.split(LIST_DELIMITER)))
    return random.sample(available_offers, 1)[0]

def accepted_offers(offers: str):
    offers = map(Offer.parse, offers.split(LIST_DELIMITER))
    pass

if __name__ == "__main__":
    start()


问:
Draw the Union Jack

Preface

There are many "draw x flag" challenges, and upon searching it turns out there are no challenges to draw the union Jack! I feel like this would be a harder flag to draw but it should still be possible.

Challenge

Draw the Union Jack. It can be outputted to a file in any freely available graphics file format or drawn onto the screen.

Code Golf rules apply, shortest code in bytes wins.

Standard loopholes apply.

No builtins for flag drawing allowed.

Dimensions shall be as below. Minimum size 600x300 pixels (or units if your language supports only scalable graphics.) Maximum error 1 pixel.

Colours shall be red, white and blue as defined by your language or its documentation, or #CC0000, #FFFFFF and #003399 per Wikipedia page.

答:
SVG, 298 bytes

score excludes 3 unnecessary newlines added for clarity.

```<code><svg xmlns="http://www.w3.org/2000/svg">
<path d="M67,0h466L0,267v-234L533,300h-466L600,33v232z" fill="blue"/>
<path d="M0,0v22L300,172L45,300h-45L600,0h-45L300,128L600,278v22z" fill="red"/>
<path d="M-10,110h270v-120h80v120h270v80h-270v120h-80v-120h-270z" fill="red" stroke="#fff" stroke-width="20"/>
</code>```

Inspired by Siren's deleted answer (and in particular the saving in bytes from omitting </svg> at the end of the document), I came up with an SVG that is both dimensionally correct and slightly shorter.

It consists of a blue path and a red path (filled, without strokes) for the diagonal parts and a red path (filled, with 20 unit white border) for the final cross. Because of the thickness of the white border, the specified dimensions of the cross must exceed the required dimensions by 10 all around.

This works fine for me in Microsoft IE and Edge. Sometimes displays an "extra content at the end of the document" warning in Chrome.

Here's how it appears without and with the final cross. 8 points are required to describe the blue path, 10 points to describe the red path, and 12 points for the final cross. The intersections of straight lines within the first two paths do not have to be given.

Title: Draw the Union Jack

Body:
SVG, 298 bytes

score excludes 3 unnecessary newlines added for clarity.

<svg xmlns="http://www.w3.org/2000/svg">
<path d="M67,0h466L0,267v-234L533,300h-466L600,33v232z" fill="blue"/>
<path d="M0,0v22L300,172L45,300h-45L600,0h-45L300,128L600,278v22z" fill="red"/>
<path d="M-10,110h270v-120h80v120h270v80h-270v120h-80v-120h-270z" fill="red" stroke="#fff" stroke-width="20"/>

Inspired by Siren's deleted answer (and in particular the saving in bytes from omitting </svg> at the end of the document), I came up with an SVG that is both dimensionally correct and slightly shorter.

It consists of a blue path and a red path (filled, without strokes) for the diagonal parts and a red path (filled, with 20 unit white border) for the final cross. Because of the thickness of the white border, the specified dimensions of the cross must exceed the required dimensions by 10 all around.

This works fine for me in Microsoft IE and Edge. Sometimes displays an "extra content at the end of the document" warning in Chrome.

Here's how it appears without and with the final cross. 8 points are required to describe the blue path, 10 points to describe the red path, and 12 points for the final cross. The intersections of straight lines within the first two paths do not have to be given.


问:
The longest period iterating quine
As we know, a quine is a program that outputs its own source code. However, it's also possible to write a program that outputs another, different program, that outputs the first program again. For example, the Python 2 program

```<code>x = '''x = {}
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3'''
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3
</code>```

will, when run, output the following text:

```<code>print """x = '''x = {}
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3'''
print 'print '+'"'*3+x.format("'"*3+x+"'"*3)+'"'*3"""
</code>```

When run as a Python program, this will output the original code again. This is called an iterating quine. Because you have to run it twice to get the original code back, we say it has period 2. But of course, much higher periods are possible.

Your challenge is to write an iterating quine with as long a period as you can, in 100 bytes or less, in the language of your choice. (Note that my example above doesn't fit this spec, as it's 119 bytes, including the trailing newline.)

Please note the following rules and clarifications:

The usual quine rules apply, i.e. your program can't use language features that would let it access its own source code directly.

The iterated outputs have to eventually loop back to exactly your original code, and you have to include a demonstration or proof that it will.

You must also include an explanation of why the cycle is as long as you say it is. This doesn't have to be at the level of a mathematical proof, but it should be convincing to someone familiar with your language. (This rule is here because I expect some of the answers to involve very, very large numbers.)

It's fine to say something like "at least 1,000,000 iterations" rather than giving the exact number, as long as you can prove that it is at least that long. In this case, your score would be 1,000,000. Otherwise, your score is the period of your quine.

The 100 byte limit only applies to your initial program - the programs it outputs can be longer, though of course they'll eventually have to get back down to 100 bytes in order to output your original code.

You can assume your machine has infinite RAM and infinite runtime, but you can't assume unlimited precision data types (such as integers) if your language doesn't have them. You can assume there is no limit to the length of input your parser can handle.

The highest score wins.

Please note: there is an existing challenge called Quit Whining; Start Quining that also involves iterating quines. However, aside from being based on the same concept, these are completely different types of challenge. The other one is straight up code golf, whereas this one is (intentionally!) really a busy beaver problem in disguise. The techniques needed to produce a good answer to this question are likely to be very different from what's needed to answer the other question, and this is very much by design.

答:
PHP, period 2,100,000,000

Who would've thought that this is possible in PHP?! :-)

This is actually my first ever quine and it's 99 bytes long:

```<code><?$i=1;$i*=21e8>$i;printf($a='<?$i=%d;$i*=21e8>$i;printf($a=%c%s%c,++$i,39,$a,39);',++$i,39,$a,39);
</code>```

Although PHP supports bigger numbers than 2 * 10^8 by switching from integer to double, the increment no longer works (leads to an infinite loop) and I haven't found another solution which fits into the 100 bytes. Yet.

Proof is fairly simple, since it's just counting up on each iteration until it reaches the reset point at 2.1 billion.

Credits to dave, who posted the approach in pseudo code in the comments and to Bob Twells, from whom I copied the code for a minimal PHP quine.

Test program (sloooooow):

```<code><?php
$o = file_get_contents('quine.php');
for ($i = 0; $i < 22e8; $i++) {
    if ($i%2==0) exec('php q > p'); else exec('php p > q');
    $a = file_get_contents(($i%2==0) ? 'p' : 'q');
    echo "\r" . str_pad($i,6,' ') . ":\t$a";
    if ($a == $o) {
        die;
    }
}
</code>```

Well, at least I'm the first one to answer.

Title: The longest period iterating quine

Body:
PHP, period 2,100,000,000

Who would've thought that this is possible in PHP?! :-)

This is actually my first ever quine and it's 99 bytes long:

<?$i=1;$i*=21e8>$i;printf($a='<?$i=%d;$i*=21e8>$i;printf($a=%c%s%c,++$i,39,$a,39);',++$i,39,$a,39);

Although PHP supports bigger numbers than 2 * 10^8 by switching from integer to double, the increment no longer works (leads to an infinite loop) and I haven't found another solution which fits into the 100 bytes. Yet.

Proof is fairly simple, since it's just counting up on each iteration until it reaches the reset point at 2.1 billion.

Credits to dave, who posted the approach in pseudo code in the comments and to Bob Twells, from whom I copied the code for a minimal PHP quine.

Test program (sloooooow):

<?php
$o = file_get_contents('quine.php');
for ($i = 0; $i < 22e8; $i++) {
    if ($i%2==0) exec('php q > p'); else exec('php p > q');
    $a = file_get_contents(($i%2==0) ? 'p' : 'q');
    echo "\r" . str_pad($i,6,' ') . ":\t$a";
    if ($a == $o) {
        die;
    }
}

Well, at least I'm the first one to answer.


答:
R, 191 187 <s>168</s> <s>156</s> <s>98</s> 99 bytes

99 bytes due to improvements fro Giuseppe and MickyT.

```<code>paste0(x<-unlist(strsplit(readline(),"")),gsub("[^A-Za-z]","",chartr("a-zA-Z","A-Za-z",x)),collapse="")
</code>```

Title: Duplicate & switch case

Body:
The goal is, having taken a string as input, duplicate each latin letter and "toggle" its case (i.e. uppercase becomes lowercase and vice-versa).

Example inputs & outputs:

```<code>Input      Output
bad        bBaAdD
Nice       NniIcCeE
T e S t    Tt eE Ss tT
s E t      sS Ee tT
1!1!1st!   1!1!1sStT!
n00b       nN00bB
(e.g.)     (eE.gG.)
H3l|@!     Hh3lL|@!
</code>```

The input consists of printable ASCII symbols.

You shouldn't duplicate non-latin letters, numbers, special chars.

Body:
R, 191 187 <s>168</s> <s>156</s> <s>98</s> 99 bytes

99 bytes due to improvements fro Giuseppe and MickyT.

paste0(x<-unlist(strsplit(readline(),"")),gsub("[^A-Za-z]","",chartr("a-zA-Z","A-Za-z",x)),collapse="")


答:
Python, 160 * 50% = 80

```<code>def f(n):
 for i in range(3**n/2+1):g=lambda z:'+'.join(`3**x`for x in range(n)if(i+3**x/2)/3**x%3==z)or'0';print i,'[%s, %s]'%(g(1),g(2)),map(eval,(g(1),g(2)))
</code>```

Shows how each weight difference can be produced, given 'n' different weights.

Title: Four weights to produce integer scale differences from 0 through 40 pounds

Body:
Just-in-time edit: I decided to reveal part of the answer and highlight a single aspect of the challenge.

Show how 4 weights, of 1, 3,  9, and 27 lbs. can be used to produce "weight differences" from 0 to 40 lbs.

You have a two - pan balance scale.

We define the difference in pan weights as the total weight placed on the left pan minus the total weight on the right pan.

The difference in pan weights for the empty scale is 0 lbs.

You have 4 rocks, a,b,c, and d, weighing 1, 3, 9 and 27 lbs respectively

Show how you can produce all integer weight differences from 0 to 40 lbs.

Simpler example:

Problem: With weights of 1 and 3 lbs. show how you can generate all weight differences from 0 to 4 lbs.

Output: for a=1, b=3;

For the 4 weight, 40 pound version, your output should consist of
a table with columns displaying the weight difference, the symbolic amounts in each pan, and the absolute weights in each pan.

You may format the table in a way congenial to the language you are coding in.

Scoring: Shortest code wins

Bonus: 50% of your score if the same code can present the results for the case where 3, 4, and 5 weights are used (for 13, 40, and 121 lbs.)

Body:
Python, 160 * 50% = 80

def f(n):
 for i in range(3**n/2+1):g=lambda z:'+'.join(`3**x`for x in range(n)if(i+3**x/2)/3**x%3==z)or'0';print i,'[%s, %s]'%(g(1),g(2)),map(eval,(g(1),g(2)))

Shows how each weight difference can be produced, given 'n' different weights.


答:
VincentKasuga, Java

Not sure if my Java is valid. Please review.

How it works

<s>
 - if you own all the stocks, you can set the price of the stock. You are the only seller.
  1. Buy all the stocks.
  2. Set the price of all the stocks to be super high on the last tick.
  3. PROFIT!
 - This isn't normally possible because...

The price would usually skyrocket to infinity... but there's a limit!

... (more reasons to come)

How it works, v2

The price is artificially set at a maximum by some anarchist state

This is bad economically

The bot doesn't predict - it exploits an inherent flaw in the structure of the market!
</s>

Todo

Corner the market multiple times! Muahaha!

FAQ

Q: Who's Vincent Kasuga?

A: He bought all the onions and onion futures in the United States. (put them all in a secret warehouse) Held the industry at ransom - give me X million or I'll set the price sky-low and you'll all go bankrupt.

But he didn't stop there.

Then, he secretly shorted the onion ETF (bet that it would go down). He sold all the onions at one time, physically delivering them in thousands of trucks to the stock exchange. The onion bag cost less than the onions. He made millions AGAIN.  In short, the Hudson river overflowed with onions.

He's a real person.

The code

```<code>import com.ppcg.stockexchange.Offer;
import com.ppcg.stockexchange.Player;
import com.ppcg.stockexchange.Stock;

import java.util.List;

public class VincentKasuga extends Player {
    private int knownStock;
    private int knownPrice;
    private int corneredStockType = -1;
    private int corneredLikelehood = 0;
    private boolean marketCornered;
    private int ticks;

    public Offer acceptOffer(List<Offer> offers) {
        if (!marketCornered) {
            Offer maxOffer = null;
            int maxAmount = 0;
            if (corneredStockType == -1) {
                for (Offer offer: offers) {
                    if (offer.getOffer().getAmount() > maxAmount) {
                        maxAmount = offer.getOffer().getAmount();
                        maxOffer = offer;
                    }
                }
            } else {
                for (Offer offer: offers) {
                    if (offer.getOffer().getAmount() > maxAmount && offer.getOffer().getType() == corneredStockType) {
                        maxAmount = offer.getOffer().getAmount();
                        maxOffer = offer;
                    }
                }
            }

            if (maxOffer == null) {
                // may have cornered the market
                corneredLikelehood++;
                if (corneredLikelehood == 5) {
                    // probably cornered the market
                    marketCornered = true;
                }
            }
            return maxOffer;
        } else {
            // who needs offers when the market is cornered!?
            return null;
        }
    }

    public Offer makeOffer(List<Stock> currentStock) {
        ticks++;
        if (ticks >= 999) {
            // SELL SELL SELL!
            return new Offer(new Stock(corneredStockType, 1000), 1000);
        } else {
            return null;
        }
    }

    public void secretValue(int stockType, int value) {
        knownStock = stockType;
        knownPrice = value;
        if (stockType == corneredStockType) {
            if (knownPrice == 1000) {
                corneredLikelehood += 3;
            } else if (knownPrice < 900){
                // didn't corner the market.
                corneredLikelehood = 0;
            }
        }
    }
}
</code>```

"I've cornered the Gold Market, Mr. Bond!"

Title: Stock Exchange KoTH

Body:
VincentKasuga, Java

Not sure if my Java is valid. Please review.

How it works

<s>
 - if you own all the stocks, you can set the price of the stock. You are the only seller.
  1. Buy all the stocks.
  2. Set the price of all the stocks to be super high on the last tick.
  3. PROFIT!
 - This isn't normally possible because...

The price would usually skyrocket to infinity... but there's a limit!

... (more reasons to come)

How it works, v2

The price is artificially set at a maximum by some anarchist state

This is bad economically

The bot doesn't predict - it exploits an inherent flaw in the structure of the market!
</s>

Todo

Corner the market multiple times! Muahaha!

FAQ

Q: Who's Vincent Kasuga?

A: He bought all the onions and onion futures in the United States. (put them all in a secret warehouse) Held the industry at ransom - give me X million or I'll set the price sky-low and you'll all go bankrupt.

But he didn't stop there.

Then, he secretly shorted the onion ETF (bet that it would go down). He sold all the onions at one time, physically delivering them in thousands of trucks to the stock exchange. The onion bag cost less than the onions. He made millions AGAIN.  In short, the Hudson river overflowed with onions.

He's a real person.

The code

import com.ppcg.stockexchange.Offer;
import com.ppcg.stockexchange.Player;
import com.ppcg.stockexchange.Stock;

import java.util.List;

public class VincentKasuga extends Player {
    private int knownStock;
    private int knownPrice;
    private int corneredStockType = -1;
    private int corneredLikelehood = 0;
    private boolean marketCornered;
    private int ticks;

    public Offer acceptOffer(List<Offer> offers) {
        if (!marketCornered) {
            Offer maxOffer = null;
            int maxAmount = 0;
            if (corneredStockType == -1) {
                for (Offer offer: offers) {
                    if (offer.getOffer().getAmount() > maxAmount) {
                        maxAmount = offer.getOffer().getAmount();
                        maxOffer = offer;
                    }
                }
            } else {
                for (Offer offer: offers) {
                    if (offer.getOffer().getAmount() > maxAmount && offer.getOffer().getType() == corneredStockType) {
                        maxAmount = offer.getOffer().getAmount();
                        maxOffer = offer;
                    }
                }
            }

            if (maxOffer == null) {
                // may have cornered the market
                corneredLikelehood++;
                if (corneredLikelehood == 5) {
                    // probably cornered the market
                    marketCornered = true;
                }
            }
            return maxOffer;
        } else {
            // who needs offers when the market is cornered!?
            return null;
        }
    }

    public Offer makeOffer(List<Stock> currentStock) {
        ticks++;
        if (ticks >= 999) {
            // SELL SELL SELL!
            return new Offer(new Stock(corneredStockType, 1000), 1000);
        } else {
            return null;
        }
    }

    public void secretValue(int stockType, int value) {
        knownStock = stockType;
        knownPrice = value;
        if (stockType == corneredStockType) {
            if (knownPrice == 1000) {
                corneredLikelehood += 3;
            } else if (knownPrice < 900){
                // didn't corner the market.
                corneredLikelehood = 0;
            }
        }
    }
}

"I've cornered the Gold Market, Mr. Bond!"


问:
Score my golf round!
Since this SE community is about golfing, I thought a golf-related challenge would be appropriate.

Explanation

Normally, the objective of golf is to finish a hole (and consequently, the entire round) with the least amount of strokes. This is a simple version of golf: Play until you hole the ball and sum up your score. Finally subtract it from the total par and the resulting number indicates your score: 0 if you played exactly par, positive if you played worse and negative if you played better.

But in 1898 a guy named Dr. Frank Barney Gorton Stableford devised a new system of playing which was designed to be more forgiving. This system awards a number of points to a player, based on a relative rating per hole, called the stroke index (SI) which is based on a player rating called handicap. This limits the amount of points a player can lose per hole. Additionally, the handiccp ensures fair competition between players despite skill difference.

This format isn't used in professional golf, but can be found almost anywhere in amateur golf.

The scoring algorithm

For anyone unfamiliar with golf, the algorithm for scoring a hole based version is as follows.

Beginning with the hardest hole (rating 1) to the easiest one (rating 18), increase the stroke index of that hole by 1 and decrement the handicap. If you exhaust the handicap, stop. If you hit the easiest hole you wrap around to the hardest and continue. (Ex: stroke index for hcp 24 and [1..18]: [2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1]).

For every score on a hole, subtract it from the sum of par and stroke index and add 2 (formula: (par + stroke index) - achieved score + 2). These are the stableford points received for that hole. Note that you cannot receive less than 0 points.

Sum up all the points. The resulting total is the total number of stableford points.

Thus, reaching 36 points is equivalent to playing exactly one's handicap, and more points are better.

Rules

Your task will be to calculate the total number of stableford points of an arbitrary golf round on an arbitrary golf course given a handicap.

You will be given a list of difficulty ratings, a list of pars, a list of scores and the handicap to use. You may order these arguments as you wish, but please state how you order them.

You may write a function ot program, input can be taken either as command line argument or function argument.

Output may either be printed to STDOUT or the return value of a function.

You may assume the following about the input:

Every list will contain exactly 18 elements.

The lists are orderd by hole: First element = info for first hole, etc.

The handicap will be an integer between 0 and 54 inclusive.

Pars will be between 3 and 7.

The score is always a positive integer.

The difficulty rating list will always be a permutation of [1..18].

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

Examples

```<code>Input: hcp: 0
       difficulty: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
       pars: [3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5]
       score: [3,3,3,3,4,4,4,4,4,4,4,4,4,4,5,5,5,5]
Output: 36

Input: hcp: 15
       difficulty: [9,3,1,13,11,17,15,7,5,18,14,10,4,6,12,16,8,2]
       pars: [4,4,4,3,5,4,3,4,4,4,3,4,4,4,5,3,5,4]
       score: [5,5,4,5,4,4,4,4,5,7,3,5,5,6,4,6,5,5]
Output: 38

Input: hcp: 28
       difficulty: [9,3,1,13,11,17,15,7,5,18,14,10,4,6,12,16,8,2]
       pars: [4,4,4,3,5,4,3,4,4,4,3,4,4,4,5,3,5,4]
       score: [5,5,5,6,3,7,3,6,5,8,4,6,7,8,4,7,6,5]
Outut: 37

Input: hcp: 54
       difficulty: [9,3,1,13,11,17,15,7,5,18,14,10,4,6,12,16,8,2]
       pars: [4,4,4,3,5,4,3,4,4,4,3,4,4,4,5,3,5,4]
       score: [9,10,9,10,9,10,9,10,9,10,9,10,9,10,9,10,9,10]
Output: 3
</code>```

Happy golfing!

答:
Pyth, 46 bytes

```<code>u+G.)S[0+-++@@Q2Hg%hQ18@@Q1H/hQ18@@Q3H2)Ul@Q1Z
</code>```

A program that takes input as a list of the form [handicap, [difficulties], [pars], [scores]] and prints the overall score.

I am very new to Pyth, so this can probably be golfed further.

Try it online

How it works

```<code>u+G.)S[0+-++@@Q2Hg%hQ18@@Q1H/hQ18@@Q3H2)Ul@Q1Z  Program. Input: Q

 +G.)S[0+-++@@Q2Hg%hQ18@@Q1H/hQ18@@Q3H2)        Function. Inputs: G, H
            @@Q2H                               Q[2][H]
                   hQ                           Q[0]
                     18                         18
                  %                             Q[0]%18
                       @@Q1H                    Q[1][H]
                 g                              Q[0]%18>=Q[1][H]
           +                                    Q[2][H]+Q[0]%18>=Q[1][H]
                             hQ                 Q[0]
                               18               18
                            /                   Q[0]//18
          +                                     Q[2][H]+Q[0]%18>=Q[1][H]+Q[0]//18
                                 @@Q3H          Q[3][H]
         -                                      Q[2][H]+Q[0]%18>=Q[1][H]+Q[0]//18-Q[3][H]
                                      2         2
        +                                       Q[2][H]+Q[0]%18>=Q[1][H]+Q[0]//18-Q[3][H]+2
       0                                        0
      [                                )        List [0, above expression]
     S                                          Sort ascending
   .)                                           Pop last value, clamping negatives to 0
  G                                             G
 +                                              G + popped value

u                                       Ul@Q1Z
                                          @Q1   Q[1]
                                         l      Length
                                        U       Unary range, yielding [0, len(Q[1])-1]
                                             Z  0
u                                               Reduce the function over that, start at 0
</code>```

Title: Score my golf round!

Body:
Pyth, 46 bytes

u+G.)S[0+-++@@Q2Hg%hQ18@@Q1H/hQ18@@Q3H2)Ul@Q1Z

A program that takes input as a list of the form [handicap, [difficulties], [pars], [scores]] and prints the overall score.

I am very new to Pyth, so this can probably be golfed further.

Try it online

How it works

u+G.)S[0+-++@@Q2Hg%hQ18@@Q1H/hQ18@@Q3H2)Ul@Q1Z  Program. Input: Q

 +G.)S[0+-++@@Q2Hg%hQ18@@Q1H/hQ18@@Q3H2)        Function. Inputs: G, H
            @@Q2H                               Q[2][H]
                   hQ                           Q[0]
                     18                         18
                  %                             Q[0]%18
                       @@Q1H                    Q[1][H]
                 g                              Q[0]%18>=Q[1][H]
           +                                    Q[2][H]+Q[0]%18>=Q[1][H]
                             hQ                 Q[0]
                               18               18
                            /                   Q[0]//18
          +                                     Q[2][H]+Q[0]%18>=Q[1][H]+Q[0]//18
                                 @@Q3H          Q[3][H]
         -                                      Q[2][H]+Q[0]%18>=Q[1][H]+Q[0]//18-Q[3][H]
                                      2         2
        +                                       Q[2][H]+Q[0]%18>=Q[1][H]+Q[0]//18-Q[3][H]+2
       0                                        0
      [                                )        List [0, above expression]
     S                                          Sort ascending
   .)                                           Pop last value, clamping negatives to 0
  G                                             G
 +                                              G + popped value

u                                       Ul@Q1Z
                                          @Q1   Q[1]
                                         l      Length
                                        U       Unary range, yielding [0, len(Q[1])-1]
                                             Z  0
u                                               Reduce the function over that, start at 0