title: The half-step of Fibonacci

text:
# Question
Title: The half-step of Fibonacci
## Challenge

Implement the 1-indexed sequence A054049, which starts like this:

```
1, 2, 3, 6, 13, 5, 9, 377, 21, 11,
89, 14, 8, 233, 16, 987, 18, 2584, 20, 6765,
55, 23, 28657, 25, 75025, 27, 196418, 29, 514229, 31,
1346269, 33, 3524578, ...

```

This sequence is the lexicographically smallest sequence of positive integers, so that indexing into the sequence twice yields the regular Fibonacci sequence:

$$ a(a(1)) = a(1) = 1 \\ a(a(2)) = a(2) = 2 \\ a(a(3)) = a(3) = 3 \\ a(a(4)) = a(6) = 5 \\ a(a(5)) = a(13) = 8 \\ a(a(6)) = a(5) = 13 \\ a(a(7)) = a(9) = 21 \\ \vdots $$

The value of \\$a(34)\\$, the first term that does not fit into the OEIS page, is equal to \\$F(377+1)\\$, or

```
4444705723234237498833973519982908519933430818636409166351397897095281987215864

```

## I/O and scoring

The following I/O methods are allowed:

* Take no input, and output the sequence indefinitely.
* Take the value of \\$n\\$ (**1-indexed**), and output the value of \\$a(n)\\$.
    + This should follow the definition of \\$a(1) = 1\\$, \\$a(2) = 2\\$, and so on. The sequence is broken otherwise.
* Take the value of \\$n\\$, and output first \\$n\\$ values of the sequence.

Due to the indexing nature of this sequence, the indexing is fixed to 1-indexing. The sequence can be considered 0-indexed by including \\$a(0) = 1\\$ in front of the sequence; you may use this alternative definition for any of the I/O methods.

Standard rules apply. The shortest code in bytes wins.

# Answer
> 13 votes
# Python 2, 226 bytes

```
g=input()+2
f=lambda n,x=1,y=1:n and f(n-1,y,x+y)or x
k={1:1,2:2,3:3}
s=set(k)
x=4
y=6
while g/x:
	while g/x|g/y:k[y]=f(x);k[x]=y;s|={x};x,y=y,f(x)
	x,y=sorted(set(range(1,max(s)+3))-s)[:2];s|={y}
print map(k.get,range(1,g-1))

```

Try it online!

-33 bytes thanks to ovs

# Answer
> 6 votes
# Haskell, ~~181~~ 149 bytes

```
1:2:3:4#(0:1:z)
n#(0:x:y:t)|x<1=n#((n+1):f!!n:y:t)|m<-n+2=n#(m:x:f!!n:t)
n#(x:t)|(a,_:b)<-splitAt(f!!n-n-1)t=x:(n+1)#(a++f!!x:b)
f=1:scanl(+)1f
z=0:z

```

Try it online!

The infinite (1-indexed) sequence (it breaks after the 33rd element because of integer overflow, but the algorithm should in principle work for arbitrarily large numbers). Here you can find a version that uses the same algorithm with arbitrary precision `Integers` (and, incidentally, is also much more efficient).

## How?

To understand the algorithm I've implemented, imagine an infinite array `a` indexed by the positive integers, and a pointer `^` that moves along this array.

---

**Step 0**. Initially, the array looks like this:

```
n    |  1  2  3  4  5  6  7  8  9 10 11 12 13
a(n) |  1  2  3  . 13  .  .  .  .  .  .  .  .
                 ^

```

We hardcode into the array the values at positions `1`, `2`, `3` and `5`, and all the other cells of the array are empty. The pointer starts at position `4`, and will only move forwards.

---

**Step 1**. Assume the pointer is pointing at an empty cell (otherwise, go to **step 2**), say at position `n`. In the initial configuration, `n=4`.

```
n    |  1  2  3  4  5  6  7  8  9 10 11 12 13
a(n) |  1  2  3  . 13  .  .  .  .  .  .  .  .
                 ^

```

Let `m` be the index of the first empty cell after `n`. Conveniently, either `m=n+1` or `m=n+2`, since at most one of `n+1` and `n+2` is a Fibonacci number, and all non-Fibonacci-indexed cells after `n` are empty. Then we write `m` at position `n` and `f(n)` at position `m`, where `f(n)` is the `n`-th Fibonacci number. In the example, `m=6` since cell `5` is not empty; we set `a(4)=6` and `a(6)=f(4)=5`:

```
n    |  1  2  3  4  5  6  7  8  9 10 11 12 13
a(n) |  1  2  3  6 13  5  .  .  .  .  .  .  .
                 ^

```

After that, we go to **step 2** *without moving the pointer*.

---

**Step 2.** Let `n` be the position of the pointer. If we got to this point, there is a number (say `x`) at position `n`.

```
n    |  1  2  3  4  5  6  7  8  9 10 11 12 13
a(n) |  1  2  3  6 13  5  .  .  .  .  .  .  .
                 ^

```

In this example, `x=6`. It's not hard to see that cell `f(n)` will always be empty (except for this example, where `a(5)` was hardcoded). Then we write the number `f(x)` at position `f(n)`.

```
n    |  1  2  3  4  5  6  7  8  9 10 11 12 13
a(n) |  1  2  3  6 13  5  .  .  .  .  .  .  .
                 ^

```

After that, we advance the pointer by `1` and we go back to **step 1**.

```
n    |  1  2  3  4  5  6  7  8  9 10 11 12 13
a(n) |  1  2  3  6 13  5  .  .  .  .  .  .  .
                    ^

```

---

Here are the next few steps of the algorithm.

```
n    |  1   2   3   4   5   6   7   8   9  10  11  12  13
a(n) |  1   2   3   6  13   5   . 337   .   .   .   .   .
                        ^

```

**Step 2.** Write `f(13)=337` at position `f(5)=8`; advance the pointer.

```
n    |  1   2   3   4   5   6   7   8   9  10  11  12  13
a(n) |  1   2   3   6  13   5   . 337   .   .   .   .   8
                            ^

```

**Step 2.** Write `f(5)=8` at position `f(6)=13`; advance the pointer.

```
n    |  1   2   3   4   5   6   7   8   9  10  11  12  13
a(n) |  1   2   3   6  13   5   9 337  21   .   .   .   8
                                ^

```

**Step 1.** Write `m=9` at position `7`; write `f(7)=21` at position `m=9`.

# Answer
> 5 votes
# JavaScript (ES6),  ~~181~~  171 bytes

This is really just a port of @hyper-neutrino's answer.

Returns the \\$n\\$th term of the sequence.

```
n=>(s=new Set(k=[A=n=>s.has(++n)?A(n):s.add(n)|n,1,2,3]),h=(x,y)=>x>n?k[n]:(g=(x,y)=>x>n+1&y>n+1?h(A``,A``):g(y,k[k[s.add(x)|x]=y]=(F=p=>x--?F(q,q+=p):p)(q=1)))(x,y))(4,6)

```

Try it online!

### Commented

**Helper function `A`**

```
A = n =>                       // expects n zero'ish on the initial call
  s.has(++n) ?                 // increment n; if n belongs to the set:
    A(n)                       //   do a recursive call
  :                            // else:
    s.add(n) | n               //   add n to the set and return n

```

**Main function**

```
n => (                         // n = input
  s = new Set(                 // create a set s containing:
    k = [, 1, 2, 3]            //   the values of the array k = [undefined, 1, 2, 3]
  ),                           //   (undefined will be quietly ignored thereafter)
  h = (x, y) =>                // outer recursive function h taking (x, y):
    x > n ?                    //   if x is greater than n:
      k[n]                     //     we're done: return k[n]
    :                          //   else:
      ( g = (x, y) =>          //     inner recursive function g taking (x, y):
        x > n + 1 &            //       if min(x, y) is greater than n + 1:
        y > n + 1 ?            //
          h(A``, A``)          //         do a recursive call to h with the next two
                               //         values that are not yet in the set
        :                      //       else:
          g(                   //         do a recursive call to g:
            y,                 //           pass x = y
            k[                 //           update k[y]:
              k[s.add(x) | x]  //             add x to the set and do k[x] = y
              = y              //
            ] = (              //             set k[y] to the x-th Fibonacci number
              F = p =>         //             using yet another recursive function F
                x-- ?          //             to compute it
                  F(q, q += p) //
                :              //
                  p            //
            )(q = 1)           //             initial call to F
          )                    //         end of recursive call
      )(x, y)                  //     initial call to g
)(4, 6)                        // initial call to h

```

# Answer
> 3 votes
# Python 3, ~~191~~ 143 bytes\*

```
from itertools import*
s=lambda n:[l for l in product(*[range(1,9**9**n)]*9**9**n)if all(l[l[i]]+l[l[i+1]]==l[l[i+2]]for i in range(n))][0][:n]

```

The function `s` takes an integer `n` and returns a tuple of length `n` which starts with `(1, 1, 2, 3, 6, ...)`.

This is simple brute force, and is practically infeasible for even `n=2`. To make sure this works you can switch the `9**9**n` for an `8` and it should work for all \\$n\le4\\$

**\*NOTE:** this assumes that \\$\forall\left\\{n\ge1\right\\}:a\left(n\right)\<9^{9^n}\\$. I think it's fine as the regular Fibonacci sequence grows as less than \\$2^n\\$, but if that's false then we might switch this out for triple/quadruple exponentials for an extra cost of 6 bytes per extra exponential for both (just add `9**` before the first `9` on both occurrences in the code)

-30 bytes thanks to Bubbler (`import*` and reducing indentation)

-18 bytes thanks to Roee Sinai (converting `s` to a one-liner)

---
Tags: code-golf, math, sequence, fibonacci
---


title: Permutation Coefficient

text:
# Question
Title: Permutation Coefficient
## What is Permutation Coefficient

Permutation refers to the process of arranging all the members of a given set to form a sequence. The number of permutations on a set of n elements is given by n! , where “!” represents factorial. The Permutation Coefficient represented by P(n, k) is used to represent the number of ways to obtain an ordered subset having k elements from a set of n elements.

Mathematically,

### Examples:

```
P(10, 2) = 90
P(10, 3) = 720
P(10, 0) = 1
P(10, 1) = 10

```

To Calculate the Permutation Coefficient, you can use the following recursive approach:

`P(n, k) = P(n-1, k) + k * P(n-1, k-1)`

Though, this approach can be slow at times. So Dynamic approach is preferred mostly.

### Example of Dynamic Approach (Python)

### Input Format

`{n} {k}`

### Output Format

`{PermutationCoefficient}`

### Test Cases

```
INPUT - 100 2
OUTPUT - 9900

INPUT - 69 5
OUTPUT - 1348621560

INPUT - 20 19
OUTPUT - 2432902008176640000

INPUT - 15 11
OUTPUT - 54486432000

```

### Constraints in input

N will always be greater than or equal to K.

### (Not to be confused with Binomial Coefficient)

# Answer
# APL (Dyalog Extended), 5 bytes

```
⊣÷⍥!-

⊣      left argument
 ÷⍥!   divide over factorial, apply factorial to both arguments and then divide
    -  subtract

```

Try it online!
> 10 votes

# Answer
# Python 3.8 (pre-release), ~~51~~ ~~23~~ 21 bytes

```
import math
math.perm

```

Try it online!

---

No builtins:

# Python 3.8 (pre-release), 31 bytes

```
f=lambda n,k:k<1or n*f(n-1,k-1)

```

Try it online!
> 6 votes

# Answer
# C (gcc), ~~34~~ ~~32~~ 27 bytes

Saved 2 bytes thanks to Davide who credits Irratix's JavaScript answer!!!

```
f(n,k){n=k?n*f(n-1,k-1):1;}

```

Try it online!
> 4 votes

# Answer
# Husk, 4 bytes

```
Π↑↔ḣ

```

Try it online!

```
Π     # product of
 ↑    # the first k elements (k is 2nd argment) of
  ↔   # the reverse of
   ḣ  # 1...n (n is 1st argument)

```
> 4 votes

# Answer
# Jelly, 3 bytes

```
ḶạP

```

A dyadic Link accepting, the non-negative integers, `n` on the right and `k` on the left which yields `P(n,k)`.

**Try it online!**

### How?

```
ḶạP - Link: k, n          e.g. 3, 10
Ḷ   - lowered range (k)        [0, 1, 2]
 ạ  - absolute difference (n)  [10,9, 8]
  P - product                  720

```
> 4 votes

# Answer
# JavaScript ES6, 25 bytes

```
c=(n,k)=>k?n*c(n-1,k-1):1

```
> 3 votes

# Answer
# 05AB1E, 1 byte

```
e

```

Builtins ftw ¯\\\_(ツ)\_/¯

First input is \\$k\\$, second input is \\$n\\$.
`e` is a builtin for the number of permutations, so \\$P(n,k) = \frac{n!}{(n-k)!}\\$.

Try it online or verify all test cases.
> 3 votes

# Answer
# Whispers v2, 34 bytes

```
> Input
> Input
>> 1P2
>> Output 3

```

Try it online!

Builtins for the win
> 3 votes

# Answer
# , ~~26~~ 25 bytes

*Edit: -1 byte by using `scan()` to take input*

```
prod(diff(x<-scan())+1:x)

```

Try it online!

Input in reverse order ( `k` first, then `n`).
> 3 votes

# Answer
# MathGolf, 5 bytes

```
‼!-!/

```

Input in the order \\$k\text{ }n\\$.

Try it online.

**Explanation:**

```
‼      # Apply the following two commands on the stack separately:
 !     #  Take the factorial of the second (implicit) input-integer
  -    #  Subtract the second from the first (implicit) input-integers
   !   # Take the factorial of (n-k) as well
    /  # Integer-divide n! by (n-k)!
       # (after which the entire stack is output implicitly as result)

```
> 2 votes

# Answer
# PowerShell, 28 bytes

```
param($a,$b)'$a--*'*$b+1|iex

```

Try it online!

# PowerShell 7, 43 bytes

```
$f={param($a,$b)$b ?$a*(&$f($a-1)($b-1)):1}

```

no TIO link because TIO still runs on PS 6, which does not support the ternary operator.
> 2 votes

# Answer
# Pyth, 4

```
.P.*

```

Try it online!

# Explanation

```
    Q      Implicit input of 2-tuple
  .*       splat
.P         nPr
           Explicit output

```
> 2 votes

# Answer
## , ~~36~~ 35 bytes

Several attempts hitting the same number:

```
function(n,r)choose(n,r)*gamma(r)*r

```

or

```
function(n,r)gamma(r)/beta(n-r+1,r)

```

or yet

```
 function(n,r)"if"(r,n*f(n-1,r-1),1)

```

with

```
 function(n,r)dpois(n-r,1)/dpois(n,1)

```

doing even worse (by 1).

Try it online!
> 2 votes

# Answer
# x86 Machine Language, 14 bytes

```
86 31 C0 40 29 F7 4E 78 05 47 F7 E7 EB F8 C3

```

**Try it online!**

The above bytes of code define a function that calculates and returns the Permutation Coefficient, according to the formula given in the challenge. The function accepts two arguments, *n* and *k*, in the `EDI` and `ESI` registers, respectively.* The result is returned in the `EAX` register, as is conventional.

* Note that the selection of these two registers is quite flexible. `EDI` and `ESI` were chosen to match some standard C calling conventions, but since this is machine code, they can be changed to any other registers of your choice, except for `EAX` (which is used for the return value) and `EDX` (which is clobbered by the `MUL` instruction).

Ungolfed assembly mnemonics:

```
               PermutationCoefficient:
31 C0             xor    eax, eax               # \ assume
40                inc    eax                    # /  result = 1
29 F7             sub    edi, esi               # n -= k
               Top:                             # <======================\
4E                dec    esi                    # --k                    |
78 05             js     End                    # terminate if k < 0     |
47                inc    edi                    # ++n                    |
F7 E7             mul    edi                    # result *= n            |
EB F8             jmp    Top                    # =======================/
               End:
C3                ret

```

There's nothing especially fancy here. Just machine code at its finest, performing iterative arithmetic with a minimal number of bytes required to encode the instructions. The key innovation is basically just effective use of registers to track the appropriate changes in values of *n* and *k* across iterations, which allows the use of extremely small `INC`rement and `DEC`rement instructions (which can be encoded in only 1 byte). This reduces the number of 2-byte and 3-byte arithmetic operations that must be done inside of the loop, which in turn reduces overall code size. It is probably also a pretty efficient implementation, as far as iterative loops go.
> 2 votes

# Answer
# Julia, 20 bytes

nothing fancy here, just applying the basic definition

```
P(n,k)=prod(n-k+1:n)

```

Try it online!
> 1 votes

# Answer
# Charcoal, 7 bytes

```
ＩΠ⁻Ｎ…⁰Ｎ

```

Try it online! Link is to verbose version of code. Explanation:

```
      Ｎ Input `k`
    …⁰  Range from `0` to `k-1`
   Ｎ    Input `n`
  ⁻     Subtract i.e. range from `n-k+1` to `n` (inclusive)
 Π      Product
Ｉ       Cast to string
        Implicitly print

```
> 1 votes

# Answer
# Jelly, 4 bytes

```
_Ɱ‘P

```

Try it online!

```
 Ɱ      For each x in 1 .. k,
_       subtract it from n
  ‘     and increment.
   P    Take the product.

```

Alternatively,

# Jelly, 4 bytes

```
c×!}

```

Try it online!

```
c       nCk
 ×      times
  !}    k!

```

Bonus solution, 5 bytes, all ASCII: `,_!:/`
> 1 votes

# Answer
# Retina, 37 bytes

```
\d+
*
~[".+¶$.("|""L$v`(_*)_ \1
$.'$*

```

Try it online! Link includes test cases. Takes input in the order `k n`. Explanation:

```
\d+
*

```

Convert the inputs to unary.

```
L$v`(_*)_ \1
$.'$*

```

List the numbers from `n-k+1` to `n`, with a `*` suffixed to each.

```
|""

```

Don't separate the results with the default newline.

```
[".+¶$.("

```

Prefix the results with the given string.

```
~

```

Evaluate that as a Retina 1 expression.

Example: For the input `2 100`, there are two matches, where `$.'` takes the values `99` and `100`. The result of the `L` command is therefore

```
.+
$.(99*100*

```

When executed as a Retina program, this then replaces the input with the desired result.
> 1 votes

# Answer
# Wolfram Language (Mathematica), 11 bytes

```
#!/(#-#2)!&

```

Try it online!
> 1 votes

# Answer
# Factor, ~~28~~ 21 bytes

```
[ [0,b) n-v product ]

```

Try it online!

Inspired by Jonathan Allan's Jelly answer. Now beats the built-in solution!

Takes two numbers `n k` from the stack, subtracts `0..k-1` from `n`, and computes the product. The product of an empty sequence is 1.

# Factor, 27 bytes

```
USE: math.combinatorics
nPk

```

Try it online!

There's a built-in for this ... except that the import is horribly long.
> 1 votes

# Answer
# MATL, 7 bytes

```
Xn0G:p*

```

Because snog :p\*

```
Xn        % compute nchoosek
  0G:p    % compute k!
      *   % multiply

```

Try it online!
> 1 votes

# Answer
# Vyxal, 2 bytes

```
∆ƈ

```

Try it Online!

Another built-in, like 05AB1E, but not quite as concise. First input is `k`, second input is `n`.
> 1 votes

# Answer
# Excel, 14 bytes

```
=PERMUT(A1,A2)

```

An Excel built-in.
> 1 votes

# Answer
# Japt, 6 bytes

```
o áV l

```

Try it here
> 0 votes

# Answer
# Perl 5 -MList::Util=reduce, 36 bytes

```
sub f{reduce{$a*$b}$_[0]+1-pop..pop}

```

Try it online!
> 0 votes

# Answer
# Java (JDK), 45 bytes

```
(n,k)->{var r=1;for(;k-->0;)r*=n--;return r;}

```

Try it online!

Works only for results `<= Integer.MAX_VALUE`.

If `f(_,0)` wasn't a requirement, it could go down one byte:

```
(n,k)->{for(var x=n;k-->1;)n*=x--;return n;}

```
> 0 votes

# Answer
# Pari/GP, 16 bytes

```
p(n,k)=n!/(n-k)!

```

Try it online!
> 0 votes

# Answer
# Python 2, 54 bytes

```
lambda n,k:g(n)/g(n-k)
from math import factorial as g

```

Try it online!

There's a better python solution already.....
> 0 votes

---
Tags: code-golf
---


title: split and capitalize

text:
# Question
Title: split and capitalize
# Challenge :

Given a string split at specific positions and capitalize the first character of the given word. Capitalize the first word's first char if and only if it was already capitalized

# Input :

A string `s` and a character `c`.

# Ouput :

The string with each occurrence of `c` replaced with the first char capitalized

# Examples :

```
STRING(s)             CHARACTER(c)  RESULT
Hello_world           _             HelloWorld
me,no,like            ,             meNoLike
you-got-it            -             youGotIt
Am^I^clear            ^             AmIClear
go!full!caps          !             goFullCaps
weird&but&tRue        &             weirdButTRue
ProbleM1fixed1no      1             ProbleMFixedNo
!prob!!lem!s!Olved!!  !             ProbLemSOlved

```

---

# Note :

* Given input will always be valid. i.e : The first will always be a string with at least one instance of the character to replace at. The second will always will be a single character.
* The length of the input string will be greater 4.
* There will be at least one occurrence of the character to split at.
* The input is guaranteed to contain only letters and the separator (Thanks @Arnauld)
* Separator is anything that is not an alphabet (a-z / A-Z) (suggested by @Dennis)

---

# Winning criteria :

This is so shortest code in bytes for each language wins.

---

1. Thanks to @JonathanAllan for pointing out two mistakes.

# Answer
> 7 votes
# Python 3, 63 bytes

```
lambda s,c:''.join(map(min,s,s[0]+s.title()[1:])).replace(c,'')

```

Try it online!

# Answer
> 5 votes
# JavaScript (ES6), ~~58~~ 56 bytes

*Saved 2 bytes thanks to @l4m2 / @Downgoat*

Takes input in currying syntax `(s)(c)`.

```
s=>c=>s.replace(u=/./g,x=>u=x==c?'':u?x:x.toUpperCase())

```

Try it online!

### Commented

```
s => c =>                  // given s and c
  s.replace(u = /./g, x => // initialize u to a RegExp; replace each character x in s with,
    u =                    // and update u to:
      x == c ?             //   if x is the separator:
        ''                 //     an empty string
      :                    //   else:
        u ?                //     if u is not an empty string:
          x                //       x unchanged
        :                  //     else:
          x.toUpperCase()  //       x capitalized
  )                        // end of replace()

```

# Answer
> 5 votes
# C (gcc), ~~61~~ ~~53~~ 55 bytes

*-8 bytes thanks to Dennis!*

```
f(s,c)char*s;{for(;*s;putchar(*s++))if(*s==c)*++s&=95;}

```

Try it online!

# Answer
> 3 votes
# sed 4.2.2 (-r), 21

```
s/[^a-z]+(.)?/\u\1/gi

```

I tried `\W` instead of `[^a-z]`, but unfortunately that doesn't match `_`.

Try it online!

# Answer
> 3 votes
# APL (Dyalog Classic), 22 bytes

```
{⍵~⍨1(819⌶@(⍵=¯1⌽⊢))⍺}

```

Try it online!

# Answer
> 3 votes
# Perl 6 `-p`, 19 bytes

```
s:g[<:!L>(.)]=$0.uc

```

Try it online!

# Answer
> 3 votes
# Jelly, 8 bytes

```
Œt⁸1¦«⁸ḟ

```

Try it online!

### How it works

```
Œt⁸1¦«⁸ḟ  Main link. Left argument: s (string). Right argument: c (character).

Œt        Title case; capitalize the first character of each word.
  ⁸1¦     Replace the first character of the result with the first character of s.
     «⁸   Take the character-wise minimum of the result and s.
          Note that uppercase letters have lower code points than lowercase ones.
       ḟ  Filterfalse; remove all occurrences of c.

```

# Answer
> 3 votes
# Octave, ~~83~~, ~~66~~, 64 bytes

Saved 2 bytes thanks to Luis Mendo. `upper` instead of `toupper`.

```
@(s,c,k=upper(s(i=find(s==c)+1)))[strsplit({s(i)=k,s}{2},c){:}];

```

Try it online!

Wow, that's probably the messiest piece of Octave-code I've ever written! This uses two of the tricks posted in this tips question, namely Argument list, and cell arrays.

### Explanation:

**Argument list input:**

```
@(s,c,k        % An anonymous function that may take three input variables, s, c, k
               % where the third argument has the default value:
 k=upper(s(i=find(s==c)+1))

```

`k` is here the first character in `s` after each separator `c`, converted to upper case. The index of each capitalized character is stored in `i`.

**Cell array body:**

We create a cell array with two elements, one were we say that all i'th characters should be substituted by its counterpart in `k`, and the other one with `s`, that is now already updated. We index this using `{2}` so that we only get the whole, modified string back. This is fed to `strsplit`, which splits it into cells at the separator character. We convert it to a comma-separated list using `{:}`, and concatenates it back to a string using square brackets `[]`.

Apologies if that didn't make any sense to you... It barely makes sense to me :P

# Answer
> 3 votes
# Retina 0.8.2, 20 bytes

```
T`lLp`LL_`[\W\d_]+.?

```

Try it online! Takes the string only, separator optional. All non-alphabetic characters are deleted but any following alphabetic character is uppercased. Previous 34-byte version accepted arbitrary input:

```
T`l`L`(?=.*(.)$)\1+.
(?=.*(.)$)\1

```

Try it online! Link includes test suite. Assumes the input consists of the string and character concatenated together. Explanation: The first stage transliterates all characters immediately following occurrences of the end character from lower to upper case and the second stage then deletes all occurrences of the end character.

For both solutions, using a right-to-left match instead of a `+` also works.

# Answer
> 2 votes
# Scala, 83 bytes

```
def f(s:String)={val w=s.split("[^a-zA-Z]");w(0)+w.tail.map(_.capitalize).mkString}

```

Try it online!

Explanation:

```
def f(s: String) = {                        // takes a String "s" as input
  val w = s.split("[^a-zA-Z]");             // split on non-alpha chars
  w(0) + w.tail.map(_.capitalize).mkString  // upper case first letter of all words except first one and join array into a String
}                                           //

```

# Answer
> 2 votes
# , 6 ~~7~~ bytes

*1 byte saved by not using argument*

```
ÓÁˆ/õ±

```

Try it online!

The program takes in the text as input and the char as an argument.

Hexdump:

```
00000000: d3c1 882f f5b1                           .../..

```

This is a simple substitution. Uncompressed, it looks like the following

```
:s/\A(.)/\u\1/g

```

Perform a global substitution in which `\A`, a non-alphabetic character, followed by a character `(.)` is replaced with uppercased `\u` first capture group `\1`

# Answer
> 2 votes
# Röda, ~~57~~ 54 bytes

*-3 bytes thanks to Cows quack*

```
{(_/`\Q$_`)|{pull;[upperCase(_[:1]),_1[1:]]if[#_1>0]}}

```

Try it online!

Explanation:

```
{
  (_/`\Q$_`)| /* Pull two strings and split the first with the second */
  {
    pull;                /* Pull one string and print it */
                         /* For each string _1 in the stream: */
                         /*   If _1 is not empty: */
    [                    /*     Print: */
      upperCase(_[:1]),  /*       The first character capitalized */
      _1[1:]             /*       The rest of characters */
    ]if[#_1>0]           /*   End if */
  }
}

```

# Answer
> 1 votes
# Red, 87 bytes

```
func[s c][b: split s c prin b/1 foreach w next b[if w <>""[w/1: uppercase w/1 prin w]]]

```

Try it online!

# Answer
> 1 votes
# 05AB1E, 9 bytes

```
¡ćsvyćusJ

```

Try it online!

**Explanation**

```
¡           # split the string on the char
 ć          # extract the head of the resulting list
  s         # swap the head to the bottom of the stack
   vy       # for each string y in the rest of the list
     ću     # extract the head and capitalize it
       s    # swap it below the rest of the string
        J   # join everything to one string

```

# Answer
> 1 votes
# PHP, ~~91~~ 83 bytes

```
$a=explode($argv[2],$argv[1]);echo array_shift($a);foreach($a as$i)echo ucfirst($i);

```

Run with `-r`. Was 2 bytes shorter using split instead of explode, but ^ test fails due to regex.

-8 thanks to Med

# Answer
> 1 votes
# , 64 bytes

Pure regular expression solution using https://www.regular-expressions.info/replacecase.html. Unfortunately separators can be underscores so I couldn't use `\w` to capture letters. Improved version taking advantage of gsub's ignore.case parameter to save on `[a-zA-Z]`. Correction thanks to https://codegolf.stackexchange.com/users/95126/dominic-van-essen, who has a 25% shorter solution in the comments.

```
function(s,c)gsub('[^a-z]([a-z]?)([a-z]*)','\\U\\1\\E\\2',s,T,T)

```

Try it online!

https://codegolf.stackexchange.com/users/95126/dominic-van-essen 's solution, with an extra character removed (by using `?` for optional):

# , 47 bytes

```
function(s,c)gsub("[^a-z]+(.)?","\\U\\1",s,T,T)

```

Try it online!

# Answer
> 1 votes
# LaTeX, 97 bytes

## The function

```
\def~#1#2{{\seq_set_split:Nnn~{#2}{#1}\seq_map_function:NN~"}}\def"{\let"\text_titlecase_first:n}

```

## Complete document with test cases

```
\documentclass[preview,border=3.14]{standalone}

\ExplSyntaxOn
\catcode`\~13
\catcode`\"13

\def~#1#2{{\seq_set_split:Nnn~{#2}{#1}\seq_map_function:NN~"}}\def"{\let"\text_titlecase_first:n}

\ExplSyntaxOff

\begin{document}
~{Hello_world}_

~{me,no,like},

~{you-got-it}-

~{Am^I^clear}^

~{go!full!caps}!

~{weird&but&tRue}&

~{ProbleM1fixed1no}1

~{!prob!!lem!s!Olved!!}!
\end{document}

```

## Results (in PDF)

# Answer
> 1 votes
# Pinecone, 314 bytes

```
s:String.input;p:String.input;k:IntArray:s.len;k.set:0,-1;o:"";n:1;i:0|i<s.len|i:i+1@((s.sub:i,i+1)=p?(k.set:n,i;n:n+1))k.set:n,s.len;i:1|i<n+1|i:i+1@(x:k.get:i-1;y:k.get:i;x:x+1;j:s.sub:x,y;e:1|e<256|e:e+1@((j.sub:0,1)=e.ascii?(e<96?(o:o+(e.ascii)+(j.sub:1,(j.len)))|(o:o+(e-32).ascii+(j.sub:1,(j.len))))))print:o

```

This was extremely fun....

# Answer
> 1 votes
# Vyxal, 5 bytes

```
/ḣǐJṅ

```

Try it Online!

# Answer
> 0 votes
# , 87 bytes

```
g<-function(s,x,z=strsplit(s,x,T)[[1]])cat(z[1],capwords(z[-1]),sep="")
example(chartr)

```

Try it online!

Uses this trick can can not be properly executed in TIO so I simulated it.

We need the `T` otherwise one of the test cases fails.

# Answer
> 0 votes
## Groovy, 43 bytes, 45 bytes

```
s.replaceAll(/\$c(.)/){it[1].toUpperCase()}

```

Try it online. Test suite included excluding the last item as it lacks the separator char `c`.

# Answer
> 0 votes
# Go, ~~138~~ ~~92~~ 87 bytes

Dropped 46 bytes thanks to @Dennis' title case idea.

```
func f(s,d string){p:=Split(s,d);Print(p[0]+Replace(Title(Join(p[1:]," "))," ","",-1))}

```

Try it online!

# Answer
> 0 votes
# Husk, 10 bytes

```
ΣΓ·:mΓo:ax

```

Try it online!

### Explanation

```
ΣΓ·:mΓ(:a)x  -- example inputs: 'x' "abxbcxcdxdex"
          x  -- split on character: ["ab","bc","cd","de"]
 Γ           -- pattern match (x = head) (xs = tail) and do..
  ·:         -- | construct list (x:xs) but with the second argument do..
    m        -- | | map (eg. "bc")
     Γ(  )   -- | | | pattern match on first character
      ( a)   -- | | | | upper-case it
      (: )   -- | | | | and join again
             -- | | | : "Bc"
             -- | | : ["Bc","Cd","De"]
             -- : ["ab","Bc","Cd","De"]
Σ            -- concatenate: "abBcCdDe"

```

# Answer
> 0 votes
# F# (Mono), 122 bytes

```
let f(s:string)c=s|>Seq.mapi(fun i x->if i>0&&s.[i-1]=c then Char.ToUpper(x)else x)|>Seq.where((<>)c)|>Seq.toArray|>String

```

Try it online!

# Answer
> 0 votes
# Java 10, 141 bytes

```
s->c->{var r=s.split("\\"+c);var r=a[0],t;for(int i=0;++i<a.length;r+=t.isEmpty()?"":(char)(t.charAt(0)&~32)+t.substring(1))t=a[i];return r;}

```

Try it online.

**Explanation:**

```
s->c->{                    // Method with String and character parameters and String return-type
  var r=s.split("\\"+c);   //  Split String by character (with potential regex char)
  var r=a[0],              //  Result-String, starting at the first item
      t;                   //  Temp-String to reduce bytes
  for(int i=0;++i<a.length;//  Loop in the range [1, length_of_array)
      r+=                  //    After every iteration: append the result-String with:
         t.isEmpty()?      //     If the current item empty:
          ""               //      Append nothing
         :                 //     Else:
          (char)(t.charAt(0)&~32)
                           //      Capitalize the first character
          +t.substring(1)) //     And append the other characters as is
    t=a[i];                //   Set `t` to the current String-item of the array
  return r;}               //  Return the result-String

```

# Answer
> 0 votes
# Stax, 11 bytes

```
óKo{cplòüö\

```

Run and debug it

**Explanation**

```
/BsF1:/s^s|dl                 # Full Program, unpacked, Implicit Input
/                             # Split on substrings (Split input with symbol to split on)
 B                            # Remove first element from array. Push the tail of the array, then the removed element.
  s                           # Swap first two elements of stack
   F                          # Start for loop
    1:/                       # Split array at index; push both parts.
       s^s                    # Swap first two elements of stack, capitalize character, swap first two elements
         |dl                  # Get length of stack, listify that amount (entire stack), implicit output of array

```

There's a few parts I would really like to fix somehow. I can get it down to about 8 bytes, but it fails on the last test case \>.\<

# Answer
> 0 votes
# Ruby `-pl`, 36 bytes

```
$_.gsub!(/[^a-z]+(.|$)/i){$1.upcase}

```

Try it online!

Takes only the string without second argument. Uses the block version of `gsub!` method because with common `gsub! x,y` syntax `$1` is not readily filled with match data. `|$` in regex is necessary for the test case with separator in the end.

# Answer
> 0 votes
# Python 3, 77 bytes

```
o=[]
for x in s.split(c): o.append(chr(ord(x[0])-32)+x[1:])
print(''.join(o))

```

Try it online!

This assumes that the string is ASCII encoded and assumes that `s` and `c` are preloaded variables containing the input.

```
for x in s.split(x)       #loop through items in the string s split by x
    o.append(             #add the following to c
        chr(              #turn the following number into a character
            ord(          #turn the following character into a number
                x[0]      #the first character in string x
            )-32          #subtract 32 from this number
        +x[1:]            #add everything past and including the second character in string x

```

This solution works on the fact that in ASCII encoding, lowercase letters are positioned 32 entries after capitalised letters

Edit: i just realised that this also capitalises the first character in the string, which it shouldn't. but i'm quite proud of my nonsense, so i'll leave this up if that's allowed

# Answer
> 0 votes
# Pip, 23 bytes

```
Ya^by@0AL(UC@_.@>_M@>y)

```

might be shorter with regex substitution.

Try it online!

# Answer
> 0 votes
# Rust, ~~130~~ 125 bytes

```
|s,c|(|mut u|s.chars().flat_map(|x|if x==c{u=1;vec![]}else if u>0{u=0;x.to_uppercase().collect()}else{vec![x]}).collect())(0)

```

Try it online!

-5 bytes thanks to Aiden4

So Rust has no built-in support for regular expressions or title case, and the uppercase function can return multiple characters... On the plus side, this works for non-ASCII encodings :)

# Answer
> 0 votes
# Wolfram Language (Mathematica), 45 bytes

```
""<>MapAt[Capitalize,##~StringSplit~All,2;;]&

```

Try it online!

---
Tags: code-golf, string
---


title: Draw the South Korean flag

text:
# Question
Title: Draw the South Korean flag
When I stumbled upon this question I remembered that I had also once seen precise rules for the construction of the South Korean flag. And this is quite a different construction.

Source: Wikipedia

So you're to draw an exact construction of this one now!

## Specification

You can render the flag to file or screen using vector or raster graphics. If your output is rasterised, your image must have dimensions of 450x300 pixels or more.

All length ratios and positions need to be exactly as shown in the following diagram:

Source: Wikipedia

Note that the centres of the two small circles align with the diagonal.

For the colours, you must use the following palette:

* White: #FFFFFF
* Black: #000000
* Red: #C60C30
* Blue: #003478

The black boundary must not be drawn *unless* your drawing system does not let you specify a 3:2 canvas for technical reasons (otherwise, you should use a 3:2 canvas and the flag should fill all of it). If you do need to add the boundary, it may be arbitrarily thick - the flag should be considered strictly *inside* the black boundary. Any other helping lines or length indicators must not be drawn. I.e., the flag should appear exactly as in the first image.

## Scoring

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

As a word of warning, using existing compression (like embedding a compressed GIF) falls into several standard loopholes.

# Answer
# PHP/HTML/SVG, 324

(line breaks added for legibility)

```
<?=gzinflate(base64_decode('tVHBioMwFPyVwF5WSOzLi/tswQjdu9cevIk1KqtriaFd9utrgpSWFva0PPImMwzDkGTz
uWXnvrl8Tj8aOPAUebLNs5Y5W33PZrKjtpOrXPOuVEy7KMiD54mKMY3yrO5tPTTMaonM9MOg32qCWgHb5Nmpch076kIih/2y
PC4jRRCIU6BhbkwGV7lmAagk3d5nCfwQdKByVBwOFLagQu6exZLNzk5fjU+B9S4u/dF1Gh/apRw6Cb83uzHm0S69/cWbSIkx
YfSf5QT6dkk5UoACIeAfXTftepb/za8='));

```

The compressed data expands to the same SVG data as my earlier answer shown below, but with two changes to aid compression:

1. The two `<use>` sections are expanded to the original content of the `<defs>` section. This makes the source text longer, but reduces the entropy so it compresses better.
2. In the first `<g>` element, I changed `transform=translate(36,24)rotate(33.69)` to `transform=rotate(33.69)translate(43.27)`. This has the same effect geometrically, but compresses better because the sequence `><g transform=rotate(` now appears twice.

By default, PHP will serve this as `Content-Type: text/html`, so the invalid XML syntax shouldn't be a problem.

# SVG/HTML, 463

The HTML parser isn't too fussed about correct syntax, so we can do away with quotation marks in the parameters as long as they don't contain any spaces. It should be possible to squeeze this down further with a bit of Javascript.

```
<svg viewBox=0,0,72,48><defs><path d=M-25-6V6Zm3,0V6m3,0V-6M19-6V6Zm3,0V6m3,0V-6Z stroke=#000
stroke-width=2 id=p /></defs><g transform=translate(36,24)rotate(33.69)><circle r=12 fill=#c60c30
/><path d=M12,0A12,12,0,0,1-12,0A6,6,0,0,0,0,0A6,6,0,0,1,12,0Z fill=#003478 /><use xlink:href=#p
/><path d=M17,0h10z stroke=#fff stroke-width=1 /><g transform=rotate(112.62)><use xlink:href=#p
/><path d=M-27,0h4Zm6,0h4ZM20,0h4Z stroke=#fff stroke-width=1 /></g></g></svg>
```
> 14 votes

# Answer
## Python + Pycairo, ~~371 370~~ 366 bytes

```
from cairo import*
p=3.141593
c=Context(SVGSurface("F",12,8))
C=c.set_source_rgb;R=c.rectangle;T=c.rotate;F=c.fill
C(1,1,1);R(0,0,12,8);F()
c.translate(6,4);T(.588);b=3188
for o in[(0,.2,.47),(.77,.05,.19)]*2:C(*o);i=b/2%2;b+=1;c.arc(i,0,2-i,0,p+i*p);F();T(p)
C(0,0,0)
for x in(p,1.966)*2:
 for y in.5,0,1:
    for z in-1,1:R(3+y,-z,1./3,z*(2.75+b%2)/3);F()
    b/=2
 T(x)

```

Outputs a tiny SVG file named `F`.
> 45 votes

# Answer
## HTML + CSS, ~~966 906 843 792~~ 762 bytes

Not a winner anytime, but lots of fun drawing in CSS. This can be golfed a lot though.

**CSS, HTML**:

```
*{position:fixed}a{background:linear-gradient(0deg,#003478 50%,#C60C30 50%);width:2in;height:2in;transform:rotate(.6rad);top:1in;left:2in}d,e{width:50%;height:50%;background:#C60C30;left:0;top:25%}a,d,e{border-radius:50%}d{background:#003478;left:50%}b,i{width:1in;height:26em;top:-1em;left:15em;transform:rotate(.98rad)}g,f,k,j{width:1in;height:17%;background:repeating-linear-gradient(0deg,#000,#000 1em,#fff 1em,#fff 1.5em);bottom:0;left:0}g,j,p{top:-.5em}b{transform:rotate(-.98rad)}c,p,v,x{height:2em;width:.5em;background:#fff;transform:rotate(.98rad)}p{top:2.8in;left:28em;transform:rotate(-.98rad) scale(1,4)}x{top:3.9em;left:28.4em}c,v{top:23.8em;transform:none}c{top:3.5em}body{height:4in;width:6in;border:1px solid
```

```
<a><d><e></a><b><f><g></b><i><j><k></i><p></p><x><v><c
```

`;border:1px solid` is just for show as the `<body>` tag has clear boundaries which can be observed by Inspector or similar tools, as stated by the OP

**NOTE** Works only in Firefox (or Chrome canary/dev) due to usage non vendor specific transforms and gradients.

See it in action
> 31 votes

# Answer
# BBC Basic, ~~349~~ 343 ASCII characters, tokenised file size 330

Download emulator at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html

```
  p=1049q=25r=100VDU4118;275;-1,49,3076;19,7,-1;-1;531;255;7693;q;40;0;q,97,1200;800;29,640;400;
  FORa=38TO56STEP0.01x=r*COS(a)y=r*SIN(a)b=a*7DIV44/2IFb=3.5z=y<0ELSEz=x>0
  VDU18;1,p;-x;-y;q,153,r;0;18;2,p;x;y;q,153,r;0;18;0
  IFABS(y)DIV1=56VDUp;x*b+y;y*b-x;q;x/3;y/3;q,113,-2*y;2*x;18;7:b-=0.1VDUp;x*b+y/12;y*b-x/12;q;x/2;y/2;q,112-z,-y/6;x/6;
  NEXT

```

Using the correct colours added a lot, but golfing all the graphics commands down to raw VDU codes gives a saving of 6 characters overall compared with my original post. All graphics on the BBC micro is done via machine-specific ASCII control codes, so instead of using high-level graphics commands you can feed bytes direct to the VDU controller (generally shorter but at great expense to readability). A value ending in semicolon instead of comma is a 16-bit little-endian representation of 2 bytes.

**Ungolfed version**

```
  MODE16
  VDU19,1,-1,49,4,12                :REM adjust shade of red
  VDU19,7,-1,-1,-1,-1               :REM adjust shade of white to full brightness (63 is 2's complement representation of -1
  VDU19,4,-1,0,13,30                :REM adjust shade of blue
  RECTANGLEFILL40,0,1200,800        :REM plot background rectangle
  ORIGIN640,400
  FORa=38TO56STEP0.01
    x=COS(a)*100
    y=SIN(a)*100
    GCOL1:CIRCLEFILL-x,-y,100       :REM red
    GCOL4:CIRCLEFILLx,y,100         :REM blue
    GCOL0                           :REM black
    b=a*7DIV44/2                    :REM divide a by 2*(22/7) to get integer representation, then divide by 2 again.
    IFb=3.5THENz=y<0ELSEz=x>0       :REM decide whether to cut bar
    REM If the angle is correct (100*sin(a) = 56) draw bar. If required, cut out the middle of the bar.
    IFABS(INT(y))=56 MOVEx*b+y,y*b-x:MOVEBY x/3,y/3:PLOT113,-2*y,2*x:GCOL7:b-=0.1:MOVEx*b+y/12,y*b-x/12:MOVEBY x/2,y/2:IFz PLOT113,-y/6,x/6
  NEXT

```

At the beginning of the program I move the origin to the centre of the screen.

I don't draw any large coloured half circles. Instead I run a loop that draws small red and blue circles, spinning in an anticlockwise direction. I do nearly 3 complete revolutions (starting with blue at the right) which is obviously more than enough to fill in the disc. I stop on the 3rd revolution, just when the blue at lower right is in the correct position to line up with the bars (which have to be plotted.)

When the angle is right, I draw one of the bars. the vector x,y for drawing the current small blue circle serves to tell in which direction the bar should be. For each of the 3 revolutions, a different value of the integer `a*7DIV44` is calculated, which tells whether the first, second or third bar should be drawn, with its inner edge 6/8,7/8 or 8/8 units from the centre (according to the units used in the question spec.) Because the program units are 1/4 of those in the spec, this is still a half-unit, so we divide by 2 again before saving to variable ´b´ to avoid repeated halving later.

The bars are drawn solid, then the middle is deleted if necessary. This prevents kinks from joining half-bars. The variable z indicates if a bar should be cut. That is, when y is negative for the middle bars and when x is positive for the other bars.

`MOVE` is an absolute move. `MOVEBY` is a relative move. `PLOT133` considers the last two graphics cursor positions, plus the new one specified (in relative coordinates) as three corners of a parallelogram, and plots that parallelogram.

**Output (& discussion of language limitations)**

I selected a screen mode of 1280x800 logical pixels = 640x400 physical pixels, which by default has a black background. Onto this I draw a white rectangle from -600,-400 to 600,400 to act as my "canvas."

BBC Basic can handle 16 colours at once, from a reprogrammable pallete. But it only supports 18-bit colour, whereas the question specifies the colours as 24-bit. The colours as close as possible.
> 21 votes

# Answer
# Python 3 turtle (552 549 bytes)

*(Full size image)*

**Edit:** Now that we have Stack Snippets, here's a Stack Snippet test using Skulpt, with the help of ArtOfCode's answer here. Unfortunately, Skulpt hasn't fully implemented Python yet, so I had to mutilate half my code to get this to work. In other words, this snippet is only meant to indicate *how* my program works (without needing to pull up Python).

*(Also, I'm finding that this might not actually work on some browsers...)*

```
function out(a){var b=document.getElementById("output");b.innerHTML+=a}function builtinRead(a){if(void 0===Sk.builtinFiles||void 0===Sk.builtinFiles.files[a])throw"File not found: '"+a+"'";return Sk.builtinFiles.files[a]}
$(document).ready(function run(){Sk.canvas="canvas";Sk.configure({output:out,read:builtinRead});try{Sk.importMainWithBody("<stdin>",!1,'import turtle\nimport math\nt=turtle.Turtle()\nt.speed(9)\nR="#c60c30"\nr=56.3\nk=0.6\ns=60*k\noffsetx,offsety=-215,-145\nt.up()\nt.goto(offsetx,offsety)\nt.down()\ndef q():t.rt(90)\ndef Q():t.lt(90)\ndef K():t.color("black");t.begin_fill();q()\ndef A(g,G):t.fd(g);Q();t.fd(G);Q();t.fd(g);Q();t.fd(G);Q()\ndef E():t.up();t.fd(s);t.down();Q();t.end_fill();t.up();t.fd(30*k);t.down();\ndef i():K();t.up();t.bk(s);t.down();A(120*k,20*k);E()\ndef I():K();t.up();t.fd(5*k);t.down();A(55*k,20*k);t.up();t.bk(65*k);t.down();A(55*k,20*k);E()\ndef C():t.circle(120*k,180)\nA(720*k,480*k)\nt.seth(r)\nt.up()\nt.goto(459.8*k+offsetx,173.4*k+offsety)\nt.down()\nt.color(R)\nt.begin_fill()\nC()\nt.end_fill()\nt.begin_fill()\nt.color("#003478")\nC()\nt.circle(s)\nt.end_fill()\nt.color(R)\nC()\nt.begin_fill()\nt.circle(s)\nt.end_fill()\nq()\nt.up()\nt.fd(s)\nt.down()\ni()\ni()\ni()\nt.up()\nt.bk(530*k)\nt.down()\nI()\nI()\nI()\nt.up()\nt.fd(170*k)\nt.rt(2*r)\nt.fd(180*k)\nt.down()\nI()\ni()\nI()\nt.up()\nt.bk(530*k)\nt.down()\ni()\nI()\ni()\n')}catch(a){throw Error(a.toString());}})
```

```
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script><script src="http://www.skulpt.org/static/skulpt.min.js" type="text/javascript"></script><script src="http://www.skulpt.org/static/skulpt-stdlib.js" type="text/javascript"></script>
<canvas height="320" width="480" id="canvas" style="border:1px solid gray">Your browser does not support HTML5 Canvas!</canvas>
```

---

Actual code:

```
import turtle as t
b=t.begin_fill
c=t.circle
e=t.end_fill
f=t.fillcolor
R="#c60c30"
r=56.3
F=t.fd
B=t.bk
s=60
def q():t.rt(90)
def Q():t.lt(90)
def K():f(0,0,0);b();q()
def A(g,G):exec("F(g);Q();F(G);Q();"*2)
def E():F(s);Q();e();F(30)
def i():K();B(s);A(120,20);E()
def I():K();F(5);A(55,20);B(65);A(55,20);E()
def C():c(120,180)
A(720,480)
t.seth(r)
t.up()
t.goto(459.8,173.4)
f(R)
b()
C()
e()
b()
f("#003478")
C()
c(s)
e()
C()
f(R)
b()
c(s)
e()
q()
F(s)
i()
i()
i()
B(530)
I()
I()
I()
F(170)
t.rt(2*r)
F(180)
I()
i()
I()
B(530)
i()
I()
i()
t.ht()

```

Since the turtle's such a slowpoke, if you want instant results you can add `t.tracer(0)` after the first line before you run the script.

*Note: For some reason turtle keeps drawing what looks like extra black pixels even though I've already called `up()`, and I have no idea why...*
> 16 votes

# Answer
## HTML + ES6, 388

```
<canvas id=D width=576 height=384><script>c=D.getContext('2d')
T=x=>c.translate(x*72,x*48)
R=(x,y)=>T(4)+c.rotate(x*.59)+T(-4)+eval('for(i=j=0;i*j<6;i+=(j^=1))c.fillRect(72+24*i+(i>2)*288,144+j*52,16,44+52*(y>>i&1-j))')
A=(w,x,y,z)=>(c.fillStyle=c.fill()+c.beginPath()||w)*c.arc(x*4,192-y,48*y,0,3.1,z)||A
R(-1,21)
R(2,7)
A(r='#C60C30',72,2,1)('#003478',72,2)(0,84,1,1)(r,60,1)()</script>
```

If your browser supports ES6, you can view it on JSFiddle or run the snippet.

It constructs the flag out of some basic shapes, rotating the canvas first to account for the angles.
> 14 votes

# Answer
# Mathematica ~~404~~ 450

```
b=1&~Array~13;a=ReplacePart[b,7-> 0];d=Disk;r=RGBColor;
z@{q_,p_,s_}:=ArrayPlot[{q,q,{},p,p,{},s,s},Frame-> False,ImageSize-> 155];
m=r@@{0,.2,.5};
o=r@@{.8,0,.2};
t=-19.1;u=-12.75;v=-5;q=-3.33;
Graphics[{Line[{{-36,-24},{36,-24},{36,24},{-36,24},{-36,-24}}],
Inset[Rotate[z@#,#2 125 Degree],#3]&@@@{{{b,a,b},1,{t,u}},{{a,b,a},1,{-t,-u}},
{{a,a,a},-1,{-t,u}},{{b,b,b},-1,{t,-u}}},
{o,d[{0,0},12,{-.2 Pi,.8Pi}],m, d[{0,0},12,{.8Pi,1.8Pi}],o,d[{v,-q},6],m,d[{-v,q},6]}}]

```
> 6 votes

# Answer
# C++ TOO LARGE

Attempted this using my home made PPM drawing library. It's technically scalable, but I'm limited by my recursive fill function because it's unreliable and likes to segfault, I think it's using up too much memory, so I won't actually let the user set the scale. The image is irregular because the coordinates I entered for each corner of the bars are slightly off.

I set it up to start with a black background, then put a white circle in the middle, then red and blue circles in that. Used recursive fills to add the rest of red and blue. Then drew rectangles with white lines to mark the black bars. Split the black background into 4 sections with white lines and used 4 recursive fills to make each section white. Doing it in 1 pass would have caused a segfault. It's still very slow to render.

## Ungolfed main code ( the rest of the library is too large, golfing this doesn't matter )

```
#include "PPMDraw.h"
#include <iostream>

int main(){
    std::cout << "Drawing Korean Flag" << std::endl;

    int scale = 150;
    int width = 3 * scale;
    int height = 2 * scale;

    int xc = width/2;
    int yc = height/2;

    // coords for the bar corners
    float nwax = -0.773; float nway = -0.813;
    float nwbx = -0.707; float nwby = -0.773;
    float nwcx = -1.000; float nwcy = -0.360;
    float nwdx = -1.050; float nwdy = -0.400;
    float nwex = -0.667; float nwey = -0.747;
    float nwfx = -0.613; float nwfy = -0.693;
    float nwgx = -0.880; float nwgy = -0.293;
    float nwhx = -0.947; float nwhy = -0.333;
    float nwix = -0.560; float nwiy = -0.667;
    float nwjx = -0.507; float nwjy = -0.627;
    float nwkx = -0.773; float nwky = -0.227;
    float nwlx = -0.840; float nwly = -0.267;

    float neax = 0.747; float neay = -0.813;
    float nebx = 0.867; float neby = -0.627;
    float necx = 0.813; float necy = -0.587;
    float nedx = 0.680; float nedy = -0.773;
    float neex = 0.893; float neey = -0.587;
    float nefx = 1.030; float nefy = -0.400;
    float negx = 0.960; float negy = -0.360;
    float nehx = 0.840; float nehy = -0.547;
    float neix = 0.640; float neiy = -0.747;
    float nejx = 0.920; float nejy = -0.333;
    float nekx = 0.853; float neky = -0.293;
    float nelx = 0.587; float nely = -0.693;
    float nemx = 0.533; float nemy = -0.667;
    float nenx = 0.667; float neny = -0.493;
    float neox = 0.600; float neoy = -0.440;
    float nepx = 0.480; float nepy = -0.627;
    float neqx = 0.693; float neqy = -0.440;
    float nerx = 0.813; float nery = -0.267;
    float nesx = 0.747; float nesy = -0.227;
    float netx = 0.627; float nety = -0.400;

    float swax = -0.773; float sway = 0.200;
    float swbx = -0.507; float swby = 0.613;
    float swcx = -0.560; float swcy = 0.653;
    float swdx = -0.840; float swdy = 0.253;
    float swex = -0.880; float swey = 0.280;
    float swfx = -0.760; float swfy = 0.453;
    float swgx = -0.813; float swgy = 0.493;
    float swhx = -0.947; float swhy = 0.320;
    float swix = -0.733; float swiy = 0.507;
    float swjx = -0.613; float swjy = 0.680;
    float swkx = -0.667; float swky = 0.720;
    float swlx = -0.787; float swly = 0.547;
    float swmx = -0.987; float swmy = 0.347;
    float swnx = -0.707; float swny = 0.760;
    float swox = -0.773; float swoy = 0.800;
    float swpx = -1.053; float swpy = 0.387;

    float seax = 0.747; float seay = 0.200;
    float sebx = 0.813; float seby = 0.253;
    float secx = 0.693; float secy = 0.427;
    float sedx = 0.627; float sedy = 0.387;
    float seex = 0.853; float seey = 0.280;
    float sefx = 0.920; float sefy = 0.320;
    float segx = 0.800; float segy = 0.507;
    float sehx = 0.733; float sehy = 0.453;
    float seix = 0.960; float seiy = 0.347;
    float sejx = 1.036; float sejy = 0.387;
    float sekx = 0.893; float seky = 0.573;
    float selx = 0.840; float sely = 0.520;
    float semx = 0.600; float semy = 0.427;
    float senx = 0.667; float seny = 0.467;
    float seox = 0.547; float seoy = 0.653;
    float sepx = 0.480; float sepy = 0.613;
    float seqx = 0.707; float seqy = 0.493;
    float serx = 0.773; float sery = 0.547;
    float sesx = 0.640; float sesy = 0.733;
    float setx = 0.547; float sety = 0.680;
    float seux = 0.813; float seuy = 0.573;
    float sevx = 0.880; float sevy = 0.613;
    float sewx = 0.747; float sewy = 0.800;
    float sexx = 0.693; float sexy = 0.747;

    PPMDraw flag = PPMDraw(width, height);
    flag.fill(0, 0, 0);

    // draw white circle in middle
    flag.set_color(255, 255, 255);
    flag.draw_fill_circle(xc, yc, scale/2);

    // draw red and blue portions of circle
    flag.set_color(255, 0, 0);
    flag.draw_fill_circle(xc - .21*scale, yc - .14*scale, scale/3.9);
    flag.set_color(0, 0, 255);
    flag.draw_fill_circle(xc + .21*scale, yc + .14*scale, scale/3.9);
    flag.set_color(255, 0, 0);
    flag.recursive_fill(xc + .21*scale, yc - .21*scale);
    flag.set_color(0, 0, 255);
    flag.recursive_fill(xc - .21*scale, yc + .21*scale);

    // draw the northwest bars
    flag.set_color(255, 255, 255);

    flag.draw_line(xc + nwax*scale, yc + nway*scale, xc + nwbx*scale, yc + nwby*scale);
    flag.draw_line(xc + nwax*scale, yc + nway*scale, xc + nwdx*scale, yc + nwdy*scale);
    flag.draw_line(xc + nwbx*scale, yc + nwby*scale, xc + nwcx*scale, yc + nwcy*scale);
    flag.draw_line(xc + nwcx*scale, yc + nwcy*scale, xc + nwdx*scale, yc + nwdy*scale);

    flag.draw_line(xc + nwex*scale, yc + nwey*scale, xc + nwfx*scale, yc + nwfy*scale);
    flag.draw_line(xc + nwex*scale, yc + nwey*scale, xc + nwhx*scale, yc + nwhy*scale);
    flag.draw_line(xc + nwfx*scale, yc + nwfy*scale, xc + nwgx*scale, yc + nwgy*scale);
    flag.draw_line(xc + nwhx*scale, yc + nwhy*scale, xc + nwgx*scale, yc + nwgy*scale);

    flag.draw_line(xc + nwix*scale, yc + nwiy*scale, xc + nwjx*scale, yc + nwjy*scale);
    flag.draw_line(xc + nwix*scale, yc + nwiy*scale, xc + nwlx*scale, yc + nwly*scale);
    flag.draw_line(xc + nwjx*scale, yc + nwjy*scale, xc + nwkx*scale, yc + nwky*scale);
    flag.draw_line(xc + nwlx*scale, yc + nwly*scale, xc + nwkx*scale, yc + nwky*scale);
    //NE
    flag.draw_line(xc + neax*scale, yc + neay*scale, xc + nebx*scale, yc + neby*scale);
    flag.draw_line(xc + neax*scale, yc + neay*scale, xc + nedx*scale, yc + nedy*scale);
    flag.draw_line(xc + nebx*scale, yc + neby*scale, xc + necx*scale, yc + necy*scale);
    flag.draw_line(xc + necx*scale, yc + necy*scale, xc + nedx*scale, yc + nedy*scale);

    flag.draw_line(xc + neex*scale, yc + neey*scale, xc + nefx*scale, yc + nefy*scale);
    flag.draw_line(xc + neex*scale, yc + neey*scale, xc + nehx*scale, yc + nehy*scale);
    flag.draw_line(xc + nefx*scale, yc + nefy*scale, xc + negx*scale, yc + negy*scale);
    flag.draw_line(xc + nehx*scale, yc + nehy*scale, xc + negx*scale, yc + negy*scale);

    flag.draw_line(xc + neix*scale, yc + neiy*scale, xc + nejx*scale, yc + nejy*scale);
    flag.draw_line(xc + neix*scale, yc + neiy*scale, xc + nelx*scale, yc + nely*scale);
    flag.draw_line(xc + nejx*scale, yc + nejy*scale, xc + nekx*scale, yc + neky*scale);
    flag.draw_line(xc + nelx*scale, yc + nely*scale, xc + nekx*scale, yc + neky*scale);

    flag.draw_line(xc + nemx*scale, yc + nemy*scale, xc + nenx*scale, yc + neny*scale);
    flag.draw_line(xc + nemx*scale, yc + nemy*scale, xc + nepx*scale, yc + nepy*scale);
    flag.draw_line(xc + nepx*scale, yc + nepy*scale, xc + neox*scale, yc + neoy*scale);
    flag.draw_line(xc + nenx*scale, yc + neny*scale, xc + neox*scale, yc + neoy*scale);

    flag.draw_line(xc + neqx*scale, yc + neqy*scale, xc + nerx*scale, yc + nery*scale);
    flag.draw_line(xc + neqx*scale, yc + neqy*scale, xc + netx*scale, yc + nety*scale);
    flag.draw_line(xc + nerx*scale, yc + nery*scale, xc + nesx*scale, yc + nesy*scale);
    flag.draw_line(xc + netx*scale, yc + nety*scale, xc + nesx*scale, yc + nesy*scale);

    //sw
    flag.draw_line(xc + swax*scale, yc + sway*scale, xc + swbx*scale, yc + swby*scale);
    flag.draw_line(xc + swax*scale, yc + sway*scale, xc + swdx*scale, yc + swdy*scale);
    flag.draw_line(xc + swbx*scale, yc + swby*scale, xc + swcx*scale, yc + swcy*scale);
    flag.draw_line(xc + swcx*scale, yc + swcy*scale, xc + swdx*scale, yc + swdy*scale);

    flag.draw_line(xc + swex*scale, yc + swey*scale, xc + swfx*scale, yc + swfy*scale);
    flag.draw_line(xc + swex*scale, yc + swey*scale, xc + swhx*scale, yc + swhy*scale);
    flag.draw_line(xc + swfx*scale, yc + swfy*scale, xc + swgx*scale, yc + swgy*scale);
    flag.draw_line(xc + swhx*scale, yc + swhy*scale, xc + swgx*scale, yc + swgy*scale);

    flag.draw_line(xc + swix*scale, yc + swiy*scale, xc + swjx*scale, yc + swjy*scale);
    flag.draw_line(xc + swix*scale, yc + swiy*scale, xc + swlx*scale, yc + swly*scale);
    flag.draw_line(xc + swjx*scale, yc + swjy*scale, xc + swkx*scale, yc + swky*scale);
    flag.draw_line(xc + swlx*scale, yc + swly*scale, xc + swkx*scale, yc + swky*scale);

    flag.draw_line(xc + swmx*scale, yc + swmy*scale, xc + swnx*scale, yc + swny*scale);
    flag.draw_line(xc + swmx*scale, yc + swmy*scale, xc + swpx*scale, yc + swpy*scale);
    flag.draw_line(xc + swpx*scale, yc + swpy*scale, xc + swox*scale, yc + swoy*scale);
    flag.draw_line(xc + swnx*scale, yc + swny*scale, xc + swox*scale, yc + swoy*scale);

    //se
    flag.draw_line(xc + seax*scale, yc + seay*scale, xc + sebx*scale, yc + seby*scale);
    flag.draw_line(xc + seax*scale, yc + seay*scale, xc + sedx*scale, yc + sedy*scale);
    flag.draw_line(xc + sebx*scale, yc + seby*scale, xc + secx*scale, yc + secy*scale);
    flag.draw_line(xc + secx*scale, yc + secy*scale, xc + sedx*scale, yc + sedy*scale);

    flag.draw_line(xc + seex*scale, yc + seey*scale, xc + sefx*scale, yc + sefy*scale);
    flag.draw_line(xc + seex*scale, yc + seey*scale, xc + sehx*scale, yc + sehy*scale);
    flag.draw_line(xc + sefx*scale, yc + sefy*scale, xc + segx*scale, yc + segy*scale);
    flag.draw_line(xc + sehx*scale, yc + sehy*scale, xc + segx*scale, yc + segy*scale);

    flag.draw_line(xc + seix*scale, yc + seiy*scale, xc + sejx*scale, yc + sejy*scale);
    flag.draw_line(xc + seix*scale, yc + seiy*scale, xc + selx*scale, yc + sely*scale);
    flag.draw_line(xc + sejx*scale, yc + sejy*scale, xc + sekx*scale, yc + seky*scale);
    flag.draw_line(xc + selx*scale, yc + sely*scale, xc + sekx*scale, yc + seky*scale);

    flag.draw_line(xc + semx*scale, yc + semy*scale, xc + senx*scale, yc + seny*scale);
    flag.draw_line(xc + semx*scale, yc + semy*scale, xc + sepx*scale, yc + sepy*scale);
    flag.draw_line(xc + sepx*scale, yc + sepy*scale, xc + seox*scale, yc + seoy*scale);
    flag.draw_line(xc + senx*scale, yc + seny*scale, xc + seox*scale, yc + seoy*scale);

    flag.draw_line(xc + seqx*scale, yc + seqy*scale, xc + serx*scale, yc + sery*scale);
    flag.draw_line(xc + seqx*scale, yc + seqy*scale, xc + setx*scale, yc + sety*scale);
    flag.draw_line(xc + serx*scale, yc + sery*scale, xc + sesx*scale, yc + sesy*scale);
    flag.draw_line(xc + setx*scale, yc + sety*scale, xc + sesx*scale, yc + sesy*scale);

    flag.draw_line(xc + seux*scale, yc + seuy*scale, xc + sevx*scale, yc + sevy*scale);
    flag.draw_line(xc + seux*scale, yc + seuy*scale, xc + sexx*scale, yc + sexy*scale);
    flag.draw_line(xc + sevx*scale, yc + sevy*scale, xc + sewx*scale, yc + sewy*scale);
    flag.draw_line(xc + sexx*scale, yc + sexy*scale, xc + sewx*scale, yc + sewy*scale);

    // fill in the black to white
    flag.draw_line(xc, yc - scale/2, xc, 0);
    flag.draw_line(xc, yc + scale/2, xc, height);
    flag.draw_line(xc - scale/2, yc, 0, yc);
    flag.draw_line(xc + scale/2, yc, width, yc);

    flag.recursive_fill(0, 0);
    flag.recursive_fill(0, height-1);
    flag.recursive_fill(width - 1, 0);
    flag.recursive_fill(width - 1, height - 1);

    flag.save("flag.ppm");

}

```
> 3 votes

# Answer
# PostScript, ~~572~~ ~~477~~ 471 bytes

Golfed code:

```
5 5 scale 36 24 translate<</R{.75 .05 .19 setrgbcolor}/B{0 .20 .47 setrgbcolor}/a 2 3 atan/b{0 setgray[18 -6 2 12 21 -6 2 12 24 -6 2 12]rectfill 1 setgray{[18 -.5 2 1 24 -.5 2 1]rectfill}if{21 -.5 2 1 rectfill}if}>>begin a neg rotate R 0 0 12 0 180 arc closepath fill B 0 0 12 180 0 arc closepath fill R -6 0 6 0 360 arc closepath fill B 6 0 6 0 360 arc closepath fill true true b 2 a mul rotate false true b 180 rotate true false b -2 a mul rotate false false b showpage

```

Ungolfed code:

```
5 5 scale                                     % over-all scale
36 24 translate                               % over-all shift

% define some short-named procedures for later use
<<
  /R {.75 .05 .19 setrgbcolor}                % prodecure for setting red color
  /B {0 .20 .47 setrgbcolor}                  % procedure for setting blue color
  /a 2 3 atan                                 % calculate angle = arctan(2/3) = 33.7°
  /b {                                        % procedure for drawing bars
    0 setgray                                    %   black
    [18 -6 2 12 21 -6 2 12 24 -6 2 12] rectfill  %   draw 3 bars
    1 setgray                                    %   white
    {[18 -.5 2 1 24 -.5 2 1] rectfill} if        %   conditionally draw gap in inner/outer bars
    {21 -.5 2 1 rectfill} if                     %   conditionally draw gap in middle bar
  }
>> begin

a neg rotate                                  % rotate -33.7°
R 0 0 12 0 180 arc closepath fill             % big red half circle
B 0 0 12 180 0 arc closepath fill             % big blue half circle
R -6 0 6 0 360 arc closepath fill             % small red circle
B  6 0 6 0 360 arc closepath fill             % small blue circle
true true b                                   % draw bars (with gap in all bars)
2 a mul rotate                                % rotate 67.4°
false true b                                  % draw bars (with gap in inner/outer bars)
180 rotate                                    % rotate 180°
true false b                                  % draw bars (with gap in middle bar)
-2 a mul rotate                               % rotate -67.4°
false false b                                 % draw bars (without gaps)
showpage

```

Result (as animation to see how it is drawn):
> 3 votes

# Answer
# Wolfram Language (Mathematica), 31 bytes

```
"SouthKorea"~CountryData~"Flag"

```
> 3 votes

# Answer
# Python 2, 483 bytes

```
from math import*
w,k,r,b="255 "*3,"0 "*3,"198 12 48 ","0 52 120 "
print "P3 600 400 255 "
a=atan2(2,3)
c,s=cos(a),sin(a)
T=lambda x,y:(c*x-s*y,s*x+c*y)
S=lambda x,y:150<x<216.6and x%25<16.6and y*y<2500
C=lambda x,y,p=50:(x-p)**2+y*y<2500
for y in range(-200,200):
 for x in range(-300,300):X,Y=T(x,y);W,Z=T(-x,y);print [[w,k][(S(abs(X),Y)and(Y*Y>16or(166.6<X<191.4or-200>X or 0>X>-166.6)))or(S(abs(W),Z)and(W>0 or abs(Z)>4))],[b,r][(Z<0 or C(W,Z))and not C(W,Z,-50)]][W*W+Z*Z<10000]

```

Possible improvements:

* hardcode the cos,sin constants
* binary PPM
* transform to \[3,2\] plane
* optimize the boolean statements

Output as text PPM, usage:

```
python golf_korea.py > korea.ppm

```

### ungolfed beta version

```
from math import*
w,k,r,b="255 255 255 ", "0 0 0 ", "255 0 0 ", "0 0 255 "
g="0 255 0 "
print "P3 600 400 255 "
a=atan2(2,3)
c,s=cos(a),sin(a)
trans=lambda x,y:(c*x-s*y,s*x+c*y)
stripe=lambda x:150<x<216.6 and x%25<16.6
small=lambda x,y,p=50:(x-p)**2+y*y<2500
for y in range(-200,200):
 for x in range(-300,300):
  X,Y=trans(x,y)
  W,Z=trans(-x,y)
  if stripe(abs(X)) and Y*Y<2500:
   if abs(Y)>4:
    print k
   else:
    if X>0:
     if 166.6<X<191.4:
      print k
     else:
      print w
    else:
     if -200<X<-166.6:
      print w
     else:
      print k
  elif stripe(abs(W)) and Z*Z<2500 and(W>0 or abs(Z)>4):
   print k
  elif W*W+Z*Z<100*100:
   if (Z<0 or small(W,Z)) and not small(W,Z,-50):
    print r
   else:
    print b
  else:
   print w

```
> 1 votes

---
Tags: code-golf, graphical-output, kolmogorov-complexity, geometry
---


# Question
Title: Is it better to walk or run in the rain?
The age-old question - is it better to walk or run? There are two trains of thought. If you run, you cause the rain to effectively hit you from the front, which increases your surface area and basically causes you to run into the raindrops, getting hit with more water. However, if you walk, you spend longer in the rain.

Actually, there is no good answer, because if the rain is about to get worse, you'd better run to get out of it even if you get hit more immediately, because you don't want to get hit by the rain later on.

In fact, if you can't predict the future, you don't actually have a good way to know what the optimal strategy is. However, we are not subject to such constraints, and can take the future as input.

## Specification

You are trying to get somewhere \\$N\in\mathbb{Z}\_{\geq1}\\$ metres away (\\$N\\$ will be supplied as input). However, it has started raining. For the next \\$N\\$ seconds, a certain amount of rain will be falling per second, and will be constant within the span of a 1-second period of time. Specifically, during the \\$i\\$th second (\\$1\leq i\leq N\\$), there will be \\$a\_i\in\mathbb{Z}\_{\geq0}\\$ units of rain. You will also be given \\$\\{a\_1,a\_2,\dots,a\_N\\}\\$ as input. It rains the same amount at all locations across that distance, but once you reach your destination, you will no longer get hit by rain.

Now, you want to know how to get rained on the least. During each second, you must either walk or run. On the \\$i\\$th second, if you walk, you will move 1 metre and get hit by \\$a\_i\\$ units of rain. If you run, however, you will move 2 metres but get hit by \\$2a\_i\\$ units of rain. Note that if you are 1 metre from the finish, if you run, it only makes sense to be hit by half of that because you're in the shelter after the first half-second, but since \\$\frac{2a\_i}2=a\_i\\$, you can just walk instead, so you don't really need to consider this case.

What is the least amount of rain you can get hit by in order to cross those \\$N\\$ metres?

## I/O Format

You may take \\$N\\$ as an input if you wish. Since it's the same as the length of the list, you're allowed to exclude it.

You may take \\$\\{a\_1,a\_2,\dots,a\_N\\}\\$ as an input if you wish. I'm not sure how you'd solve the problem without it.

You must output a single non-negative integer, the least amount of rain (in units) that you can be hit by in order to cross those \\$N\\$ metres.

## Example

```
10 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

```

The rain is progressively getting worse. Clearly, every second you spend outside makes the rain worse, so it's better to get hit by double the amount now than wait and get hit by the larger amount later. If you run for 5 seconds, you will move 10 metres and get hit by \\$15\times2=30\\$ units of rain. In comparison, if you walk for 10 seconds, you get hit by 55 units.

```
6 [1, 0, 1, 0, 1, 0]

```

The rain is acting weird. In this case, if you run for 3 seconds, you get hit by 4 units of rain. However, if you only run during the second and fourth seconds, and walk during the first and third, you still cover 6 metres, but here you only get hit by 2 units since you run during the time when the rain is stopped, and no rain doubled is still no rain.

## Test Cases

```
7 [1, 0, 2, 5, 3, 0, 0]           -> 11
1 [1]                             -> 1
6 [2, 5, 5, 2, 3, 1]              -> 18
1 [5]                             -> 5
3 [3, 3, 5]                       -> 9
9 [1, 0, 3, 1, 1, 1, 3, 2, 3]     -> 9
5 [3, 2, 0, 0, 0]                 -> 5
7 [3, 1, 4, 4, 3, 5, 3]           -> 19

```

You can generate more test cases here; the input accepts the max \\$N\\$ and the max \\$a\_i\\$. It's also an ungolfed reference implementation (the `move` function) (I could have probably figured out a DP relation to solve this more efficiently, but I was too lazy, and since it's , I don't suppose anyone else will use a more efficient solution either...)

## Scoring

* this is ; since you are writing on your umbrella and have limited space, your code must be as short as possib- wait, you had an umbrella? \[...\]
* standard loopholes are forbidden as usual
* have fun and happy golfing!

# Answer
> 9 votes
# , 44 39 27 bytes

```
#{0,[:<./]+/\@#~1+2#:@i.@^#

```

Try it online!

-12 after reading rak1507's clever idea!

Using 3 3 5 as an example:

* `1+2#:@i.@^#` One plus all binary numbers from `0` to `2^<length>-1`

```
1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1
2 2 2

```
* `]...#~` Use each of those as a mask to replicate the input (trailing zeros are just fill):

```
3 3 5 0 0 0
3 3 5 5 0 0
3 3 3 5 0 0
3 3 3 5 5 0
3 3 3 5 0 0
3 3 3 5 5 0
3 3 3 3 5 0
3 3 3 3 5 5

```
* `+/\@` And scan sum each row:

```
3 6 11  0  0  0
3 6 11 16  0  0
3 6  9 14  0  0
3 6  9 14 19  0
3 6  9 14  0  0
3 6  9 14 19  0
3 6  9 12 17  0
3 6  9 12 17 22

```

At this point the problem is essentially solved, because the 3rd column is "how wet we are after moving 3 meters". All we need to do now is...
* `[:<./` Take the min of all rows and...
* `#{0,` Pluck the 3rd column.

## original approach, 39 bytes

```
[:<./1#.[(*2-~/\0,#<.+/\)"#.1+2#:@i.@^#

```

Try it online!

Tries all possible combinations.

Using 3 3 5 as an example:

* `1+2#:@i.@^#` One plus all binary numbers from `0` to `2^<length>-1`

```
1 1 1
1 1 2
1 2 1
1 2 2
2 1 1
2 1 2
2 2 1
2 2 2

```
* `+/\` Scan sum each row

```
1 2 3
1 2 4
1 3 4
1 3 5
2 3 4
2 3 5
2 4 5
2 4 6

```
* `#<.` Minimum of each element and input length, 3 in this case:

```
1 2 3
1 2 3
1 3 3
1 3 3
2 3 3
2 3 3
2 3 3
2 3 3

```
* `0,` Append 0:

```
0 1 2 3
0 1 2 3
0 1 3 3
0 1 3 3
0 2 3 3
0 2 3 3
0 2 3 3
0 2 3 3

```
* `2-~/\0` Successive deltas:

```
1 1 1
1 1 1
1 2 0
1 2 0
2 1 0
2 1 0
2 1 0
2 1 0

```
* `*` Multiply each by the input (J dyadic hook):

```
3 3 5
3 3 5
3 6 0
3 6 0
6 3 0
6 3 0
6 3 0
6 3 0

```
* `1#.` Sum rows:

```
11 11 9 9 9 9 9 9

```
* `[:<./` Minimum:

```
9

```

# Answer
> 9 votes
# Husk, 13 bytes

```
▼moΣ↑L¹MṘπL¹2

```

A (sorta) port of my APL solution, just for fun. Husk is certainly an ... interesting ... language.

-2 each from Razetime and Leo

```
▼moΣ↑L¹MṘπL¹2
         πL¹2     cartesian power of [1,2] of length of the list
       MṘ         replicate
 moΣ↑L¹           sum of len(input) take each list
▼                 minimum

```

Try it online!

# Answer
> 7 votes
# Wolfram Language (Mathematica), 41 bytes

```
f[a_,b___,c_]=a+Min[b~f~c,a+f@b]
f@a_:0=a

```

Try it online!

Input `f[a1, a2, ..., aN]`.

# Answer
> 6 votes
# Python 2, 51 bytes

```
f=lambda h=0,*t:t and h+min(f(*t),h+f(*t[:-1]))or h

```

Try it online!

Essentially a port of my Mathematica answer.

# Answer
> 5 votes
# Python 2, 53 bytes

```
f=lambda n,h=0,*t:n>0and h+min(f(n-1,*t),h+f(n-2,*t))

```

Try it online!

Uses a kind-of sketchy splatted input format of `f(N, l_1, l_2, ..., l_N)`.

**68 bytes**

```
lambda n,l:min(sum(l[:n-k]+sorted(l[:-k])[:k])for k in range(n/2+1))

```

Try it online!

An efficient solution, unlike the exponential-time solution above. Picks how many seconds `k` to walk, minimizing the sum of first `k` numbers plus the sum of the smallest `n-k` among them which are chosen to be doubled.

Here's a nifty recursive version:

**66 bytes**

```
f=lambda n,l:l and min(sum((l+sorted(l)+[1e999])[:n]),f(n,l[:-1]))

```

Try it online!

# Answer
> 5 votes
# APL (Dyalog Extended), 23 bytes

```
{⍺⊃0,⌊⌿+\⍵/⍤1⍨⍉1+⊤⍳2*⍺}

```

Takes the length as ⍺ and the array as ⍵.

```
{⍺⊃0,⌊⌿+\⍵/⍤1⍨⍉1+⊤⍳2*⍺}
              ⍉1+⊤⍳2*⍺   all possible combinations of 1 and 2 of length ⍺
         ⍵/⍤1⍨           replicate ⍵
       +\                cumulative sum
     ⌊⌿                  minimum reduce
 ⍺⊃0,                    take the ⍺-th item (prepend a dummy item so it works with 0 based indexing)

```

Try it online!

# Answer
> 5 votes
# JavaScript (ES6),  ~~53~~  52 bytes

*Saved 1 byte thanks to @l4m2*

Expects `(n)(list)`.

```
f=(n,[k,...a])=>n>0&&Math.min(f(n-1,a),f(n-2,a)+k)+k

```

Try it online!

# Answer
> 4 votes
# Python 2, 57 bytes

A direct recursive implementation of the task.

```
f=lambda N,a:N>0and min(f(N-x,a[1:])+x*a[0]for x in[1,2])

```

Try it online!

# Answer
> 4 votes
# Jelly, 11 bytes

```
2ṗx@"Fṁɗ€§Ṃ

```

A dyadic Link accepting \\$N\\$ on the left and \\$A\\$ on the right that yields the smallest amount of rain.

**Try it online!** Or see the test-suite.

### How?

```
2ṗx@"Fṁɗ€§Ṃ - Link: integer, N; list (of length N), A
2           - two
 ṗ          - (implicit range of 2 = [1,2]) Cartesian power (N)
        €   - for each (walk/run list, x):
       ɗ    -   last three links as a dyad - f(x, A):
    "       -     zip with:
   @        -       with swapped arguments:
  x         -         repeat elements
     F      -     flatten
      ṁ     -     mould like (A) (i.e. cut to length N)
         §  - sums
          Ṃ - minimum

```

# Answer
> 4 votes
# Vim, 90 bytes

```
"aDqmdd{"cyGO0<esc>Gp:.,$sor n
Go0<esc>ggVGJ0@awwhD:s/ /+/g
0C<c-r>=<c-r>"
,<c-r>b<esc>0"bD"cpG@mq@m0C<c-r>=min([<c-r>b])

```

Try it online!

This is vanilla vim (TIO supports V, which is backwards compatible with vim).

Vim doesn't really do branching recursion (at least, I don't know a good way without just writing pure vimscript, and it's possible that would be shorter, but certainly less fun!), so this answer uses a method that's different from most of the existing answers.

**tl;dr**: Takes N followed by the list, one int per line. Finds the minimum over prefices length `n-k` of the sum of that prefix plus its `k` smallest elements.

Long version:

## How?

We observe that, given a list `l` of length `n`, if we choose to run `k` times, we will always choose to run on the `k` smallest elements of the length `n-k` prefix of `l`, and we will avoid the length `k` suffix of `l` entirely. Thus, the solution can be arrived at by concatenating the length `n-k` prefix with the sorted version of itself, and taking the length `n` head of this new list which has length `2*(n-k)`. Once `2*(n-k)` becomes smaller than `n`, we must stop because we can't run more than `n/2` times.

```
"aDqmdd{"cyGO0<esc>Gp:.,$sor n
                                               " input like 3, [2, 1, 5] newline separated
"aD                                            " cut N into register a
   qm                                          " def m:
     dd{                                       " delete current line, go to top
        "cyG                                   " copy file contents into register c
            O0<esc>                            " prepend 0
                   Gp                          " go to end, paste register c below
                     :.,$sor n                 " sort the new copy of l numerically
                                               " -> [0,2,1,5,1,2,5]
Go0<esc>ggVGJ0@awwhD:s/ /+/g
Go0<esc>gg                                     " append a 0 at the end, go back to top
                                               " -> [0,2,1,5,1,2,5,0]
          VGJ                                  " join all the lines by spaces
             0@aw                              " go to the (n+1)th number
                 w                             " go one more and **exit function if we can't**
                                               " note that the prepended and appended 0 were necessary for this magic stopping condition to work
                  hD                           " go left to the preceding space and delete the rest of the line
                                               " -> '0 2 1 5'
                    :s/ /+/g                   " replace all spaces with '+'
                                               " ->'0+2+1+5'
0C<c-r>=<c-r>"                                 " eval the current line and replace it with the result
                                               " -> '8'
,<c-r>b<esc>0"bD"cpG@mq@m0C<c-r>=min([<c-r>b])
,<c-r>b<esc>                                   " append a comma followed by the contents of register b
                                               " -> '8,'
            0"bD                               " cut the result of that into b (accumulates)
                "cp                            " write back the original list
                   G@m                         " go to the end and recurse, causing the last element of l to get deleted at the start of m
                      q@m                      " stop defining m, then call it
                                               " now register b contains a comma separated list of the sub-results
                         0C<c-r>=min([<c-r>b]) " take the min of those and replace the current (only) line with the result

```

The next iteration will look like

```
[2,1]
-> [0,2,1,1,2,0]
-> '0 2 1 1 2 0'
-> '0 2 1 1'
-> '0+2+1+1'
-> '4'
-> '4,8,'

```

and finally:

```
[2]
-> [0,2,2,0]
-> '0 2 2 0'
-> **try to go past end of line and exit instead**

```

So after `m` terminates, the final state is

```
buffer: 0 2 2 0
b: 4,8,

```

And so the (only) line in the buffer gets replaced with the evaluation of `min([4,8,])` and we have the desired output: `4`.

A note on the stopping condition `@aww`: In the common case, what we want to do is delete everything from the `n+1`st number onwards, which is achieved by just `@aw` (and no prepending/appending 0s). However, just `@aw` won't cause `m` to exist by error if it moves at all, i.e. even if there are just two numbers ('words') on the line, so we need the second `w` to actually cause `m` to exit, hence the need to prepend 0. (We also can't decrement `N` before reading it because that would fail when N=1--`0w` doesn't move 0 words because `0` isn't a count; it moves to the beginning of the line and then moves 1 word!). The appended `0` is so that we always have something to delete even when there are exactly `n` numbers left, otherwise we would stop without checking the prefix of size `n/2` for even `n`.

# Answer
> 3 votes
# 05AB1E, 14 bytes

```
Åœʒà3‹}εœ€*}Oß

```

Try it online!

Tries all combinations by looking at every permutation of every integer partition of \\$N\\$ which only consists of 1's and 2's. Porting rak's APL answer will probably be shorter.

# Answer
> 3 votes
# , ~~68~~ 67 bytes

*Edit: -1 byte thanks to detective work by Giuseppe*

```
f=function(t,r,s=r[1])`if`(t>0,s+min(f(t-1,u<-r[-1]),s+f(t-2,u)),0)

```

Try it online!

A recursive function that pretty much follows the logic of the explanation.

Note to  golfers: I thought it should be possible to still save a byte by assigning the twice-used `r[-1]` to a variable at the first use (since `u<-r[-1]` and `u` together are shorter than two `r[-1]`s), but I just couldn't seem to make it work. Giuseppe has now managed to to make it run by just swapping the order of the arguments to `min` or by using a different variable name, which is rather wierd and doesn't fill me with unbounded confidence about  for my real-world work...

# Answer
> 1 votes
# Julia 0.6, ~~50~~ 44 bytes

```
n<r=n>0&&(!i=r[]i+(n-i<r[2:end]);min(!1,!2))

```

Try it online!

Thanks to MarcMush for -6 bytes.

# Answer
> 0 votes
# Charcoal, ~~39~~ 30 bytes

```
Ｉ⌊ＥΦＥＸ²⊕ＬθΦ⍘ι12μ⁼ΣιＬθΣＥι×Ｉλ§θμ

```

Try it online! Link is to verbose version of code. Explanation:

```
      ²                         Literal 2
     Ｘ                          Raised to power
         θ                      Input array
        Ｌ                       Length
       ⊕                        Incremented
    Ｅ                           Map over implicit range
            ι                   Current index
           ⍘                    Convert to string
             12                 Using digits `12`
          Φ    μ                Remove leading digit
    Φ                            Filter strings where
                   ι             Current string
                  Σ              Digital sum
                 ⁼               Equal to
                     θ           Input array
                    Ｌ            Length
  Ｅ                             Map over strings
                       ι        Current string
                      Ｅ         Map over characters
                          λ     Current character
                         Ｉ      Cast to integer
                        ×       Multiplied by
                            θ   Input array
                           §    Indexed by
                             μ  Current index
                     Σ          Take the sum
 ⌊                              Take the minimum
Ｉ                               Cast to string
                                Implicitly print

```

Previous less brute-forcey 39-byte version:

```
≔⟦υ⟦ω⟧⟧ηＦθ⊞η⁺⁺§η±²2⁺§η±¹1Ｉ⌊Ｅ⊟ηΣＥι×Ｉλ§θμ

```

Try it online! Link is to verbose version of code. Explanation:

```
≔⟦υ⟦ω⟧⟧η

```

Start with an (empty) list of ways of walking and running to get to a distance of `-1` and a list of one (empty) way of walking and running to get to a distance of `0`.

```
Ｆθ⊞η⁺⁺§η±²2⁺§η±¹1

```

Build up the ways of walking and running to get to distances of `1`..`N`.

```
Ｉ⌊Ｅ⊟ηΣＥι×Ｉλ§θμ

```

For each way of walking and running to get to a distance of `N`, calculate the amount of rain, and output the minimum.

---
Tags: code-golf, array
---