title: Translate numbers to French

text:
# Question
Title: Translate numbers to French
The French spell out numbers in a peculiar way.

* **1-16** are "normal"
* **17-19** are spelled out **10+7. 10+8, 10+9**.
* **20-69** are "normal" (OK, OK! Not really, but they are in this challenge)
* **70-79** are **60+10, 60+11 ... 60+10+7, 60+10+8, 60+10+9**.
* **80-99** are **4\*20, 4\*20+1, 4\*20+2 ... 4\*20+16, 4\*20+10+7, 4\*20+10+8, 4\*20+10+9**

**Challenge:**

Take a positive integer in the range **\[1,100\]**, and output it the "French way". You must output it exactly as it's shown below, with `*` and `+`, so `97` is `4*20+10+7`, not `[4 20 10 7]` or something else.

Test cases:

```
1  - 1
.. - ..
16 - 16
17 - 10+7
18 - 10+8
19 - 10+9
20 - 20
21 - 21
.. - ..
69 - 69
70 - 60+10
71 - 60+11
72 - 60+12
77 - 60+10+7
78 - 60+10+8
79 - 60+10+9
80 - 4*20
81 - 4*20+1
82 - 4*20+2
.. - ..
90 - 4*20+10
91 - 4*20+11
96 - 4*20+16
97 - 4*20+10+7
98 - 4*20+10+8
99 - 4*20+10+9
100 - 100

```

# Answer
> 13 votes
## Excel, ~~153~~ 149 Bytes

```
=IF(OR(A1<17,A1>99,AND(A1>19,A1<70)),A1,IF(A1<20,"10+"&A1-10,IF(A1<80,"60","4*20")&IF(A1=80,,IF(MOD(A1,20)>16,"+10+"&MOD(A1,20)-10,"+"&MOD(A1,20)))))

```

I'm sure this could be better, I struggled to find an efficient way to account for #80.

edit: Consolidated the 'Normal' cases better to save 4 bytes. #80 still sucks.

Can't find a specific answer on here, not sure the rules of code-golf tbh. Can I use multiple cells in Excel, and add the byte count of each?

ie. For an input in cell A1

A2: 11 Bytes

```
=MOD(A1,20)

```

A3 (result): 125 Bytes

```
=IF(OR(A1<17,A1>99,AND(A1>19,A1<70)),A1,IF(A1<20,"10+"&A1-10,IF(A1<80,"60","4*20")&IF(A1=80,,IF(A2>16,"+10+"&A2-10,"+"&A2))))

```

For a total of 136?

# Answer
> 8 votes
# Retina, ~~52~~ 48 bytes

*4 bytes saved thanks to Neil*

```
^7\B
60+1
^9\B
81
^8\B
4*20+
1(?=7|8|9)
10+
\+0

```

Try it online! or verify all inputs (provided by Neil)

**Explanation**

```
^7\B
60+1
^9\B
81
^8\B
4*20+

```

First we handle the translation of 70, 80, and 90. In these first 3 stages, a 7 at the start with another character following it is replaced by `60+1`. Similarly, `9` is replaced by `81`, and `8` by `4*20+1`. The replacement of `9` is essentially changing it to "eighty-ten" and such, so that the `8` is then handled by the next replacement, which saves bytes over writing `4*20+1` twice.

```
1(?=7|8|9)
10+

```

This handles the cases of `17`, `18`, and `19`, by replacing the `1` in each with `10+`.

```
\+0

```

Finally, there should never be a `+0` at the end, so delete it if it's there.

# Answer
> 8 votes
# Python 2, 98 bytes

```
f=lambda x:[`x`*(x%100<70),'10+'+`x-10`][16<x<20]or['60+'+f(x-60),'4*20'+x/81*('+'+f(x-80))][x/80]

```

Try it online!

# Answer
> 7 votes
## JavaScript (ES6), ~~73~~ 71 bytes

```
f=n=>n>16&n<20?'10+'+n%10:n<70|n>99?n:n%20?f(n-n%20)+'+'+f(n%20):'4*20'

```

Bonus version that prints the numbers as they are actually spelled for an extra 2 bytes:

```
f=n=>n<17|n>99?n:n<20?'10+'+n%10:n%20?f(n-n%20)+'+'+f(n%20):n-80?n:'4*20'

```

# Answer
> 5 votes
# R, 110 bytes

```
i=scan()
r=i%%10;paste0(ifelse(i>16&i<20,"10+",ifelse(i>69&i<80,"60+10+",ifelse(i>16&i<20,"4*20+",i-r/10))),r)

```

# Answer
> 5 votes
# PHP, 99 bytes (I wanna be happy version)

a straight port of ETHproductions´ JS, 4 bytes golfed. Prints the numbers as asked for by the OP.

```
function f($n){return$n<17|$n>19?$n>60&$n<100?($m=$n%20)?f($n-$m)."+".f($m):'4*20':$n:"10+".$n%10;}

```

**breakdown**

```
function f($n){return
    $n<17|$n>19
        ?$n>69&$n<100
            ?($m=$n%20)
                ?f($n-$m)."+".f($m) # 70..79, 81..99
                :'4*20'             # 80
            :$n                     # 1..16, 20..69
        :"10+".$n%10                # 17..19
    ;
}

```

## I wanna be right version, ~~114~~ 98 bytes

new approach inspired by ETHproductions, prints the numbers as they are actually spelled out.

```
function f($n){return$n>16&$n<100?$n-80?($m=$n%($n>60?20:10))?f($n-$m)."+".f($m):$n-$m:'4*20':$n;}

```

try it online.

**breakdown**

```
function f($n){return
    $n>16&$n<100
        ?$n-80
            ?($m=$n%($n>60?20:10))
                ?f($n-$m)."+".f($m) # $n%$m>0
                :$n-$m              # 10,20,30,40,50,60
            :'4*20'                 # 80
        :$n                         # 1..16, 100
;}

```

# Answer
> 4 votes
# Python 2, ~~130~~ 108 bytes

*22 bytes saved thanks to @mathjunkie*

```
f=lambda x:79<x<100and('4*20'+('+'+f(x-80))*(x>80))or 69<x<100and'60+'+f(x-60)or 16<x<20and'10+'+`x-10`or`x`

```

Try it online!

# Answer
> 3 votes
## Batch, ~~220~~ 217 bytes

```
@set/pn=
@set s=
@if %n% gtr 99 goto g
@if %n% gtr 79 set s=+4*20&set/an-=80
@if %n% gtr 69 set s=+60&set/an-=60
@if %n% gtr 16 if %n% lss 20 set s=%s%+10&set/an-=10
:g
@if %n% gtr 0 set s=%s%+%n%
@echo %s:~1%

```

Takes input on STDIN. Generating and removing the leading `+` saves 1 byte over special-casing 80. Edit: Saved 3 bytes thanks to @ConorO'Brien.

# Answer
> 2 votes
# Pyth, ~~61~~ 56 bytes

```
L?}b}17 19++T\+eb|bk?}/QTr6T.s+?<Q80"60+""4*20+"y%Q20\+y

```

Test it online!

Thanks to Leaky Nun for a 5 byte improvement!

Explanation:

```
                     | Implicit: Q=eval(input())
L                    | Define y(b):
 ?}b}17 19           |  If b is in the inclusive range from 17 to 19:
          ++T\+eb    |   Return "10+" + (last digit of b)
                 |b  |  Else: if b!=0: return b
                   k |   Else: return an empty string (Leaves a trailing '+' for case 80)
_____________________|________________
?}/QTr6T                              | If 70<=Q<100:
          +                           |  Concatenate the next two expressions:
           ?<Q80                      |   If Q<80:
                "60+"                 |    Evaluate to "60+"
                     "4*20+"          |    Else: Evaluate to "4*20+"
                            y%Q20     |   y(Q%20)
        .s                       \+   |  Strip off trailing '+', if present (for case 80)
                                   y  | Else: return y(Q)
                                   (Q)| Trailing Q is implicitly added

```

# Answer
> 2 votes
# Jelly, 55 bytes

```
⁹
’,ṃ60Ṁ€
⁹%80“4*20”,
Dj⁾0+µ¹e?“×ØŒ‘
%ȷ2:“FP‘S‘ŀḟ0Ç€j”+

```

**Try it online!** or see a test suite

*No doubt there is a shorter way!*

### How?

```
+ - Link 1, helper for 1-69&100: number s=0, number n
⁹ - link's right argument, n

’,ṃ60Ṁ€ - Link 2, helper for 70-79: number s=1, number n
’       - decrement s -> 0
 ,      - pair -> [0,n]
  ṃ60   - base decompress (vectorises) using [1,2,...60]  effectively -> [60,[1,n%60]]
     Ṁ€ - maximum for €ach effectively -> [60,n%60]

⁹%80“4*20”, - Link 3, helper for 80-99: number s=2, number n
⁹           - link's right argument, n
 %80        - mod 80
    “4*20”  - literal ['4','*','2','0']
          , - pair -> [['4','*','2','0'],n]

Dj⁾0+µ¹e?“×ØŒ‘ - Link 4, reformat 17-19: element v (may be char list or number)
        ?      - if
       e       - v exists in
         “×ØŒ‘ - literal [17,18,19]
               - then:
D              -   convert to decimal list  e.g. [1,7]
  ⁾0+          -   literal ['0','+']
 j             -   join                          [1,'0','+',7]
     µ         - else:
      ¹        -   identity, v

%ȷ2:“FP‘S‘ŀḟ0Ç€j”+ - Main link: number n in [1,100]
 ȷ2                - literal 100
%                  - mod (convert 100 to 0)
    “FP‘           - literal [70,80]
   :               - integer division (vectorises)
        S          - sum (0 for 1-69&100; 1 for 70-79; 2 for 80-99)
         ‘         - increment (...1, 2 or 3)
          ŀ        - call link at index (1, 2 or 3) as a dyad(sum, n)
           ḟ0      - filter out zeros (remove 0 from 4*20+0)
             Ç€    - call the last link (4) as a monad for each
                ”+ - literal '+'
               j   - join

```

# Answer
> 1 votes
## Python3, 127 bytes

```
m,r=map,range;l=[*r(1,17),*m("10+{}".format,(7,8,9))];f=[0,*l,*r(20,61),*m("60+{}".format,l),"4*20",*m("4*20+{}".format,l),100]

```

Each array element contains its representation:

```
for i in range(1,101):
    print(i, f[i])

```

The code does not actually create a function, just an array -- I don't know if that's allowed. Otherwise, I'd have to make this 139 bytes by adding `f=[...].__getitem__`.

# Answer
> 0 votes
# Java 7, ~~97~~ ~~96~~ 109 bytes

```
String c(int i){return i>16&i<20?"10+"+(i-10):i%100<70?i+"":i<80?"60+"+c(i-60):"4*20"+(i<81?"":"+"+c(i-80));}

```

+13 bytes for bug-fixing case `80`.. :(

**Explanation:**

```
String c(int i){      // Method with integer parameter and String return-type
  return i>16&i<20?   //  If 17..19:
    "10+"+(i-10)      //   Return "10+" + `i`-10
   :i%100<70?         //  Else if 1..16; 20..69; 100:
    i+""              //   Return `i`
   :i<80?             //  Else if 70..79:
    "60+"+c(i-60)     //   Return "60+" + recursive-call with `i`-60
   :                  //  Else (80..99):
    "4*20"+           //   Return "4*20" +
     (i<81?           //   If 80:
      ""              //    nothing
     :                //   Else (81..99)
      "+"+c(i-80));   //    recursive-call with `i`-80
}                     // End of method

```

**Test code:**

Try it here.

```
class M{
  static String c(int i){return i>16&i<20?"10+"+(i-10):i%100<70?i+"":i<80?"60+"+c(i-60):"4*20"+(i<81?"":"+"+c(i-80));}

  public static void main(String[] a){
    for (int i = 1; i <= 100; i++) {
      System.out.println(c(i));
    }
  }
}

```

---
Tags: code-golf, number, kolmogorov-complexity
---


# Question
Title: Zero an arbitrarily large cell in Brainf***
Your task is to write a piece of code that zeros the current cell in the Brainfuck variant that, each cell can contain a **signed** integer of arbitrarily large magnitude, instead of the normal 0 to 255.

You may assume there are *l* cells to the left and *r* cells to the right of the current cell that are initially zero. You program may only access these *l*+*r*+1 cells. After your code ends it should leave the *l*+*r* extra cells zero and the pointer to the current cell at the original position.

You may not use any input/output.

The code with smallest *l*+*r* wins. If there is a tie, the shortest code wins. It is recommended to also state the time complexity of your program for reference, where *n* is the absolute value of the original integer in the current cell.

### Useful tools

You can test a Brainfuck program in this variation using this interpreter on TIO by mbomb007.

You can also use the interpreter in this answer by boothby (other Python answers probably also work, but I didn't test).

# Answer
> 17 votes
# l+r = 0+2 = 2, ~~55~~ ~~53~~ 51 bytes

```
[>+[-<+>>+<]<[>]>[+[-<+<->>]<[->+<]]>[-<+>]<<]>[-]<

```

# l+r = 1+2 = 3, ~~46~~ 44 bytes

```
[[>+[-<+<+>>]<[<+[->->+<<]]>]>[>]<[-]<<[-]>]

```

My own algorithm. The pointer should begin at the number that needs to be zeroed. The time complexity is O(n^2).

### How it works:

* We start with the number `n`.
* We increment one, so the number becomes `n+1`.
* We decrement two, so the number becomes `n+1-2 = n-1`
* We increment three, so the number becomes `n-1+3 = n+2`.
* We decrement four, so the number becomes `n+2-4 = n-2`.

We repeat the process, increasing the in-/decrement each step, until we get zero.

# Answer
> 9 votes
# l + r = 0 + 2 = 2; 58 bytes

```
>+<[>[<->>+<-]>+<<[>]>[<<+>+>-]<[->+<]>[<]>+[-<+>]<<]>[-]<

```

The complexity is O(n^2).

The following is my testing program generator, so you can see that I actually tried to test it in case it doesn't work...

```
p='''
>+<
[
>
[<->>+<-]
>+<
<[>]>
[<<+>+>-]
<
[->+<]
>[<]>
+ [-<+>]
<<
]
> [-] <
'''

p = ''.join(p.split())

cpp = '''
#include <bits/stdc++.h>
using namespace std;
void test(int q) {
long long t[3] = {q, 0, 0};
int i = 0;
ZZZ
printf("q=%d %lld %lld %lld\\n", q, t[0], t[1], t[2]);
}
int main() {
while(true) {
    int q; cin >> q; test(q);
}
}
'''

d = {
'>': '++i; assert(i<3);',
'<': '--i; assert(i>=0);',
'+': '++t[i];',
'-': '--t[i];',
'[': 'while(t[i]){',
']': '}',
}

print cpp.replace('ZZZ', ''.join(d[c] for c in p))

```

---
Tags: code-challenge, number, brainfuck
---


# Question
Title: Find how many alphanumeric characters can be made up of a single number
The alphanumeric characters have ASCII-values:

```
0-9  ->  48-57
A-Z  ->  65-90
a-z  ->  97-122

```

Your challenge is to take an integer as input, and output how many characters can be made using consecutive digits of that number. The character codes may be overlapping. `666` should result in `2`, since you have `66` twice.

**Test cases:**

```
Input: 5698
Possible characters: '8' (56), 'E' (69), 'b' (98)
Output: 3

Input: 564693
Possible characters: '8' (56), 'E' (69)
Output: 2

Input: 530923864209124521
Possible characters: '5' (53), 'V' (86), '4' (52)
Output: 3

Input: 1111111
Possible characters: 'ooooo' (5*111)
Output: 5

Input: 5115643141276343
Possible characters: '3' (51), '8' (56), 'L' (76), 's' (115)
Output: 4

Input: 56789
Possible characters: '8' (56), 'C' (67), 'N' (78), 'Y' (89)
Output: 4

Input: 94
Possible characters: ''
Output: 0

Input: 1
Output: 0

```

Input and output formats are optional (yes, you may take the integer as a string).

# Answer
> 11 votes
# 05AB1E, ~~8~~ 7 bytes

```
žKÇIŒÃg

```

Try it online!

**Explanation**

```
žK       # push [a-zA-Z0-9]
  Ç      # convert to list of ascii codes
   IŒ    # push all substrings of input
     Ã   # keep only the subtrings which exist in the list of acsii codes
      g  # push length of resulting list

```

# Answer
> 7 votes
# MATL, ~~17~~ 13 bytes

```
8Y2"G@oVXf]vn

```

Try it online! Or verify all test cases.

### Explanation

```
8Y2     % Predefined literal: string with all letters, uppercase and lowercase,
        % and digits
"       % For each character in that string
  G     %   Push input, for example the string '5115643141276343'
  @     %   Push current character, such as 'A'
  o     %   Convert to its ASCII code, such as 65
  V     %   String representation, such as '65'
  Xf    %   Find string '65' within string '5115643141276343'. This gives a vector
        %   (possibly empty) with indices of occurrences
]       % End
v       % Concatenate all stack contents vertically
n       % Number of entries. Implicitly display

```

# Answer
> 6 votes
# Brachylog, 22 bytes

```
∧Ạụ:Ạ:Ịcạ:?{tT&h∋~sT}ᶜ

```

Try it online!

### Explanation

```
       c                 Concatenate together:
∧Ạụ:                       "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    Ạ:                     "abcdefghijklmnopqrstuvwxyz"
      Ị                    "0123456789"
        ạ                Get the list of ASCII codes of that string
         :?{        }ᶜ   Count the number of results, for input [list of codes, Input], of:
            tT             Call the Input T
              &h∋          Take one ASCII code
                 ~sT       It is a substring of T

```

# Answer
> 6 votes
# Java 8, ~~204~~ ~~197~~ ~~195~~ ~~186~~ 174 bytes

```
n->{int r=0,i=0,e=n.length()-1,t;for(;i<e;r+=t>47&t<57|t>64&t<91|t>96&t<100|(t=new Short(n.substring(i,i++>e-2?i:i+2)))>99&t<123?1:0)t=new Byte(n.substring(i,i+2));return r;}

```

-9 bytes thanks to *@ceilingcat*.

Try it online.

**Explanation:**

```
n->{                   // Method with String parameter and integer return-type
  int r=0,             //  Result, starting at 0
      i=0,             //  Index
      e=n.length()-1,  //  Length of String -1
      t;               //  Temp integer
  for(;i<e             //  Loop over the String using the index
      ;                //    After every iteration:
       r+=             //     Increase the result-sum by:
          t>47&t<57|t>64&t<91|t>96&t<100
                       //      If two adjacent digits are a digit or letter
          |            //      or
          (t=new Short(n.substring(i,i++>e-2?i:i+2)))>99&t<123?
                       //      if three adjacent digits are a letter:
           1           //       Increase the sum by 1
          :            //      Else:
           0)          //       Keep the sum the same by adding 0
    t=new Byte(n.substring(i,i+2));
                       //   Set `t` to the substring of [i, i+2) converted to integer
  return r;}           //  Return the result-sum

```

# Answer
> 5 votes
## JavaScript (ES6), ~~71~~ 70 bytes

```
f=([a,...b])=>a?(a&(a+=b[0])+b[1]<123|a>47&a<58|a>64&a<91|a>96)+f(b):0

```

### Test cases

```
f=([a,...b])=>a?(a&(a+=b[0])+b[1]<123|a>47&a<58|a>64&a<91|a>96)+f(b):0

console.log(f("5698"))                // 3
console.log(f("564693"))              // 2
console.log(f("530923864209124521"))  // 3
console.log(f("1111111"))             // 5
console.log(f("5115643141276343"))    // 4
console.log(f("56789"))               // 4
console.log(f("94"))                  // 0
console.log(f("1"))                   // 0
```

# Answer
> 4 votes
# Perl 5, 47 bytes

46 bytes of code + `-p` flag.

```
$"="|";$_=()=/(?=@{[48..57,65..90,97..122]})/g

```

Try it online!

I couldn't find any shorter way to write that `48..57,65..90,97..122`: `map{ord}0..9,a..z,A..Z` (getting the ascii value of the characters) is one byte longer. And doing `for$c(0..122){$\+=chr($c)=~/\pl|\d/ for/(?=$c)/g}}{` (looking for all numbers, but keeping only those whose numbers corresponds to the ascii value of letters (`\pl`) or digits (`\d`)) will be 5 bytes longer (note that `\pl|\d` can't be replaced by `\w` as the latter also includes underscores)).

---

Previous approach (49 bytes):

```
for$@(48..57,65..90,97..122){$\+=()=/(?=$@)/g}}{

```

# Answer
> 2 votes
# PHP, 68 Bytes

```
for(;a&($a=$argn)[$i];)$d+=ctype_alnum(chr($a[$i].$a[++$i]));echo$d;

```

Online Version

# Answer
> 1 votes
# JavaScript (ES), ~~165~~ ~~161~~ ~~156~~ ~~154~~ 153 bytes

Yeah, RegEx definitely wasn't the right tool for the job here!

```
n=>[/\d{2}/g,/\d{3}/g].map(e=>eval("while(x=e.exec(n)){a.push(m=x[0]);e.lastIndex-=m.length-1}"),a=[])|a.filter(x=>x>47&x<58|x>64&x<91|x>96&x<123).length

```

---

## Try It

```
f=

n=>[/\d{2}/g,/\d{3}/g].map(e=>eval("while(x=e.exec(n)){a.push(m=x[0]);e.lastIndex-=m.length-1}"),a=[])|a.filter(x=>x>47&x<58|x>64&x<91|x>96&x<123).length

console.log(f(5698))//3
console.log(f(564693))//2
console.log(f(530923864209124521))//3
console.log(f(1111111))//5
console.log(f(5115643141276343))//4
console.log(f(56789))//4
console.log(f(94))//0
console.log(f(1))//0
```

# Answer
> 1 votes
# Haskell, ~~161~~ ~~157~~ ~~138~~ ~~129~~ 126 bytes

```
import Data.List
f x=sum[1|y<-nub$concat$words.concat<$>mapM(\c->[[c],c:" "])x,any(elem$read y)[[48..57],[65..90],[97..122]]]

```

I wonder if there is a better way to remove dupes of the list than importing Data.List for nub?

# Answer
> 1 votes
# Pyth, ~~19~~ ~~17~~ 14 bytes

```
l@jGUTmr0Csd.:

```

takes a string.

*-3 Bytes thanks to @LeakyNun*

Try it!

### Explanation

```
l@jGUTmr0Csd.:
    UT                # the list of digits [0,1,2,...,9]
  jG                  # join that on the lowercase alphabet (repetition doesn't matter)
              Q       # implicit input
            .:        # all substrings of the input
      m               # for each of those substrings
          sd          # Convert the string to a base 10 integer
         C            # convert that integer to the character with that number
       r0             # make that character lowercase
l@                    # length of the intersection of those two list of chars we generated

```

# Answer
> 1 votes
# Retina, 52 bytes

```
&`1[01]\d|12[012]|4[89]|5[0-7]|6[5-9]|[78]\d|9[0789]

```

Try it online! (includes test suite)

# Answer
> 1 votes
# Python 2, ~~74~~ ~~64~~ 62 bytes

```
f=lambda n:n and chr(n%10**(3-(n%1000>122))).isalnum()+f(n/10)

```

Try it online!

# Answer
> 0 votes
# Jelly, 8 bytes

```
ØBODf@ẆL

```

Input is a digit array.

Try it online!

### How it works

```
ØBODf@ẆL  Main link. Argument: A (digit array)

ØB        Base 62; yield all alphanumeric ASCII characters.
  O       Ordinal; get their code points.
   D      Decimal; convert the code points into digit arrays.
      Ẇ   Window; yield all contiguous subarrays of A.
    f@    Filter swapped; keep all elements of the result to the right that appear
          in the result to the left.
       L  Length; count the matches.

```

# Answer
> 0 votes
# Ruby, 50 bytes

```
p (0..~/$/).any?{|n|$_[n,2].to_i.chr=~/\p{Alnum}/}

```

Reads from standard input; requires the Ruby interpreter be invoked with the `-n` option (implicit `while gets` loop).

Could be reduced to 43 bytes if it were allowed to match underscores.

```
p (0..~/$/).any?{|n|$_[n,2].to_i.chr=~/\w/}

```

# Answer
> 0 votes
# Japt, 24 bytes

```
;è"(?={9ò ¬+B+C ¬mc q|})

```

Try it online!

Alternate 27-byte version:

```
è"(?={#~o f_d f"%d|%l"Ãq|})

```

Try it online!

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


title: printf-style string formatting

text:
# Question
Title: printf-style string formatting
# Challenge

Write a function that implements C `printf`-style string formatting.

# Rules

1. You **must** implement at least `%%`, `%c`, `%s`, `%d` and `%f`.
2. You **must not** use a built-in string formatting method.
3. You **must not** run external programs or connect to the Internet from your program.
4. It's up to you to decide how to handle invalid input, but your program **must not** terminate abnormally.
5. You **should** write a variadic function if possible.

> The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.

# Answer
## APL (73)

```
{⊃,/,⌿↑(⊂2∘↓¨Z⊂G),⊂{'c'0≡⍵,∊⊃⍺:⎕UCS⍺⋄⍕⍺}/⍵,⍪⌷∘G¨1↓1+(Z←G='%')/⍳⍴G←'%!',⍺}

```

Some tests:

```
      'a:%c b:%s c:%d'{⊃,/,⌿↑(⊂2∘↓¨Z⊂G),⊂{'c'0≡⍵,∊⊃⍺:⎕UCS⍺⋄⍕⍺}/⍵,⍪⌷∘G¨1↓1+(Z←G='%')/⍳⍴G←'%!',⍺} 65 'foo' 67
a:A b:foo c:67

      printf←{⊃,/,⌿↑(⊂2∘↓¨Z⊂G),⊂{'c'0≡⍵,∊⊃⍺:⎕UCS⍺⋄⍕⍺}/⍵,⍪⌷∘G¨1↓1+(Z←G='%')/⍳⍴G←'%!',⍺}
      '1:%s 2:%s 3:%d 4:%c 5:%c' printf 'foo' 'bar' 100 110 'z'
1:foo 2:bar 3:100 4:n 5:z
      'The %s brown %c%c%c jumps over the %s dog.' printf 'quick' 102 111 'x' 'lazy'
The quick brown fox jumps over the lazy dog.

```

Explanation:

* `G←'%!',⍺`: prefix a dummy specifier to the string (for easier processing)
* `(Z←G='%')/⍳⍴G`: find the indices of all the `%` characters in the string; also store a bitmask in `Z`
* `⌷∘G¨1↓1+`: select all the characters next to the `%`s, and drop the dummy.
* `⍵,⍪`: match up each specifier with its value from the right argument.
* `{`...`}/`: run the following function on each pair:
    + `'c'0≡⍵,∊⊃⍺`: if the argument is a number and the specifier is `c`:
    + `:⎕UCS⍺`: then return the unicode value of the argument,
    + `⋄⍕⍺`: otherwise, return the string representation of the argument.
* : enclose
* `⊂2∘↓¨Z⊂G`: split the string on the `%`s and then remove the first two characters of each substring (this is where the dummy comes in), and enclose the result of that.
* : make a matrix out of the two enclosed arrays, matching up each substring with the value that should follow it.
* `,⌿`: join each substring with its value.
* `⊃,/`: then join the resulting strings.
> 4 votes

# Answer
# Lua 5.2, 115 bytes

```
-- Function definition, 115 chars
function f(f,...)n,t=0,{...}return(f:gsub('%%(%a)',function(s)n=n+1return(({c=s.char})[s]or tostring)(t[n])end))end

-- Usage example
print(f('Happy %cew %d %s %f',78,2014,'Year!',math.pi))
-- Output: Happy New 2014 Year! 3.1415926535898

```
> 2 votes

# Answer
# Ruby: 102 characters

```
f=->s,*a{s.gsub(/%(.)/){$1==?%??%:a.shift.send({?c=>:chr,?s=>:to_s,?d=>:to_i,?f=>:to_f}[$1])rescue$&}}

```

Sample run:

```
irb(main):001:0> f=->s,*a{s.gsub(/%(.)/){$1==?%??%:a.shift.send({?c=>:chr,?s=>:to_s,?d=>:to_i,?f=>:to_f}[$1])rescue$&}}
=> #<Proc:0x96634ac@(irb):1 (lambda)>

irb(main):002:0> puts f["percent : %%\n   char : %c or %c\n string : %s or %s or %s\ndecimal : %d or %d or %d\n  float : %f or %f or %f\ninvalid : %x or %s or %d or %f", 65, 'B', 'format me', 42, Math::PI, 42, Math::PI, '2014', 42, Math::PI, '2014', 'more']
percent : %
   char : A or B
 string : format me or 42 or 3.141592653589793
decimal : 42 or 3 or 2014
  float : 42.0 or 3.141592653589793 or 2014.0
invalid : %x or  or 0 or 0.0
=> nil

```

Invalid format specifiers are kept in place. Format specifiers without argument value are replaced with the empty value of the given type.
> 2 votes

# Answer
# C++ (281 characters)

```
#include<sstream>
#include<cstdarg>
#define q(x)va_arg(v,x);break;case
std::string p(char*f,...){std::ostringstream r;va_list v;va_start(v,f);while(*f)if(*f=='%')switch(++f,*f++){case's':r<<q(char*)'d':r<<q(int)'c':r<<(char)q(int)'%':r<<'%';}else r<<*f++;va_end(v);return r.str();}

```

I hate C++, but it seemed like a good choice (I really would go with C, if not that `char*` pointer requires too much effort to be actually useful). Takes `char*` arguments, and `std::string` result, but hey, that's C++, so who cares about consistency (in language that itself isn't consistent)?
> 1 votes

# Answer
# Java, ~~201~~ ~~186~~ 174 bytes

12 bytes thanks to Kevin Cruijssen

```
String f(String s,Object...a){String r="";for(char c,i=0,j=0;i<s.length();r+=c==37?(c=s.charAt(i++))<38?c:c==99?(char)(int)a[j++]:a[j++]:c==37?"":c)c=s.charAt(i++);return r;}

```

Try it online!
> 1 votes

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


title: Create a vortex!

text:
# Question
Title: Create a vortex!
Your mission today is to create a vortex given a single parameter.

This parameter determines the length of each arm in characters.

Each "layer" of each arm contains one more character than the last.

Here's how the vortex will look, given the arm length:

```
0:

#

1:

 #
###
 #

2:

 #
  # #
 ###
# #
   #

3:

##  #
  # #
 ###
# #
#  ##

4:

#     #
 ##  #
   # #
  ###
 # #
 #  ##
#     #

10:

             #
             #
             #
             #
            #
####        #
    ###     #
       ##  #
         # #
        ###
       # #
       #  ##
      #     ###
      #        ####
      #
     #
     #
     #
     #

```

Standard loopholes apply, trailing whitespace optional, any single non-whitespace character in ASCII can replace "#".

This is so the shortest answer in bytes wins.

# Answer
# Charcoal, 30 bytes

```
#ＮβＦβ«¿ι«×#⌊⟦ιβ⟧Ａ⁻βιβ↑»»‖←⟲Ｏ²⁴⁶

```

## Explanation

```
#                                    Print "#"
 Ｎβ                                 Input number to b
    Ｆβ«                  »          For i in range(b)
        ¿ι«              »           If i is truthy (to skip 0)
           ×#⌊⟦ιβ⟧                   Print "#" * minimum of i and b
                  Ａ⁻βιβ↑            Assign b-i to b
                           ‖         Reflect right
                            ⟲Ｏ²⁴⁶  Rotate overlap 90, 180 and 270 degrees

```

Try it online!
> 1 votes

# Answer
# MATL, 60 bytes

```
3<G+Eqt&OlG8M+t&(1G:8*X^Q2/kG+G:Gq+&vG2=+Z{(XJ3:"J@X!+]g35*c

```

Try it online! Or verify test cases: , , , , , 10.

This turned out to be funnier than I expected. Explaining is going to be harder, though...
> 5 votes

# Answer
# Jelly, 48 bytes

```
Rȯ1ĖŒṙ‘Ė’ḣµ;NµN0¦€U;
Ç+;ẋ2W$+⁸<3¤µFṀR,þ$e€€ị⁾# Y

```

**Try it online!**

(Make it all more square by replacing the final `Y` with `G`, adding a space between each column).

### How?

Builds a list of `#` coordinates of an arm relative to the centre. Transforms that to the coordinates of the four arms from the top-left corner and adds the centre coordinate. Builds a table of all the coordinates in the space and sets the arms to `#` and the space to  and joins up the rows with newlines.

```
Rȯ1ĖŒṙ‘Ė’ḣµ;NµN0¦€U; - Link 1, arm coordinates relative to centre: arm-length a
R                    - range: [1,2,...,a]
 ȯ1                  - or 1 (stops Œṙ erroring with arm-length 0; builds no redundant coordinates in the end)
   Ė                 - enumerate: [[1,1],[2,2],...[a,a]]  (or [[1,1]] if a=0)
    Œṙ               - run-length decode: [1,2,2,...,a,a,...,a] (or [1] if a=0)
      ‘              - increment: [2,3,3,...,a+1,a+1,...,a+1] (or [2] if a=0)
       Ė             - enumerate: [[1,2],[2,3],...,[T(a)-a,a+1],[T(a)-a+1,a+1],...,[T(a),a+1]] where T(a)=(a+1)*a/2 (or [[1,2]] if a=0)
        ’            - decrement: [[0,1],[1,2],...,[T(a)-a-1,a],[T(a)-a,a],...a[T(a)-1),a]] (or [[0,1]] if a=0)
         ḣ           - head to a (first a of those) - these are an arm's relative coordinates from the central `#` at [0,0])
          µ          - monadic chain separation (call that list r)
           ;         - r concatenated with
            N        - negate r (gets the opposite arm)
             µ       - monadic chain separation (call that list s)
                 €   - for €ach coordinate pair in s:
               0¦    -     apply to index 0 (the right of the two values):
              N      -         negate
                  U  - upend (reverse each pair of that, gives the other two arms)
                   ; - concatenate that list with s (gives all four arms)

Ç+;ẋ2W$+⁸<3¤µFṀR,þ$e€€ị⁾# Y - Main link: arm-length a
Ç                           - call the last link(1) as a monad (get centre-relative coordinates)
 +                          - add a (make the coordinates relative to the top-left)
      $                     - last two links as a monad:
   ẋ2                       -     repeat a twice: [a,a]
     W                      -     wrap in a list: [[a,a]] (the centre coordinate)
  ;                         - concatenate (add the centre coordinate)
           ¤                - nilad followed by link(s) as a nilad:
        ⁸                   -     link's left argument, a
         <3                 -     less than three?
       +                    - add (a in 0,1,2 are special cases requiring a grid one-by-one more than all the rest)
            µ               - monadic separation (call that c)
             F              - flatten c into one list
              Ṁ             - get the maximum (the side-length of the space)
                  $         - last two links as a monad:
               R            -     range: [1,2,...,side-length]
                ,þ          -     pair table: [[[1,1],[1,2],...,[1,side-length]],[[2,1],[2,2],...,[2,side-length]],...,[[side-length,1],[side-length,2],[side-length, side-length]]]
                   e€€      - exists in c? for €ach for €ach (1 if a # coordinate, 0 otherwise)
                       ⁾#   - literal ['#',' ']
                      ị     - index into
                          Y - join with new line characters
                            - implicit print

```
> 3 votes

# Answer
## Mathematica ~~139~~ 172 Bytes

The idea is to create a single arm with a function - `{⌊.5+.5(-7+8#)^.5⌋,#-1}` that spits out the index of each element of the arm assuming the middle element has index (0,0). No one has picked up on that yet, but I suspect this idea would result in a winning answer in a better golfing language. Then I rotate the arm through multiples of 90 degrees, re-index and construct the matrix.

`SparseArray` seemed like the obvious choice for constructing the matrix, but could have gone with `BoxMatrix` and `ReplacePart`.

```
Grid[SparseArray[Max@#+#+1&[Join@@Table[RotationMatrix[i Pi/2].#&/@{{0,0}}~Join~Array[{⌊.5+.5(-7+8#)^.5⌋,#-1}&,#],{i,4}]]->X,2#+1,""]]&

```

Ungolfed (Hard coded for arm length=3,`%` means previous output):

```
{{0,0}}~Join~Table[{Floor[1/2 (1+Sqrt[-7+8x])],x-1},{x,1,3}]
Table[RotationMatrix[i Pi/2].#&/@%,{i,4}]
Flatten[%,1]
Max[%]+%+1
Normal@SparseArray[%->X,Automatic,""]
Grid[%/. 0->""]

```

Usage %@4

```
X                       X
    X   X           X
            X       X
        X   X   X
    X       X
    X           X   X
X                       X

```

As I've learned the output must be pure ASCII without extra spacing or formatting, the code has to get a little longer (172 bytes):

```
StringRiffle[ReplacePart[Array[" "&,{1,1}*2#+1],Max@#+#+1&[Join@@Table[RotationMatrix[i Pi/2].#&/@{{0,0}}~Join~Array[{⌊.5+.5(-7+8 #)^.5⌋,#-1}&,#],{i,4}]]->"#"],"\n",""]

#     #
 ##  #
   # #
  ###
 # #
 #  ##
#     #

```
> 0 votes

---
Tags: code-golf, ascii-art
---


title: Apply Kirchhoff's law

text:
# Question
Title: Apply Kirchhoff's law
Kirchhoff's law says that when you sum up all the currents (positive for the currents going to a junction, and negative for current leaving a junction), you will always get as result 0.

Look at the following diagram:

Using Kirchhoff's law, you can see that i1 + i4 - i2 - i3 = 0, so i1 + i4 = i2 + i3.

Given two lists, one with all the currents entering the junction and one with all the currents leaving the junction except one, output the last one.

Testcases:

```
[1, 2, 3], [1, 2] = 3
[4, 5, 6], [7, 8] = 0
[5, 7, 3, 4, 5, 2], [8, 4, 5, 2, 1] = 6

```

The second list always has one item less than the first list. The output cannot be negative. Smallest program wins.

# Answer
# Jelly, 2 bytes

```
_S

```

Try it here!

Takes the entering currents in the first argument, and the leaving currents in the second argument. `_` subtracts them pairwise, leaving the single element from the longer list as-is, and `S` sums the result.
> 14 votes

# Answer
## Haskell, 14 bytes

```
(.sum).(-).sum

```

Usage example: `( (.sum).(-).sum ) [5,7,3,4,5,2] [8,4,5,2,1]` -\> `6`.

Sum each list and take the difference.
> 9 votes

# Answer
## CJam, ~~8~~ 6 bytes

```
q~.-:+

```

Input uses two CJam-style arrays.

Run all test cases. (This reads multiple test cases at once and includes a framework to process each line individually, discarding the expected result from the input.)

### Explanation

```
q~  e# Read and evaluate input.
.-  e# Elementwise difference.
:+  e# Get sum.

```

`.-` works reliably because we're guaranteed that the first list is always longer than the second. (Otherwise, the extraneous elements of the second list would be appended to the result which would add them to the sum instead of subtracting them.)
> 5 votes

# Answer
# MATL, 3 ~~4.0~~ bytes

```
_hs

```

Inputs are: leaving currents first, then entering currents.

**Try it online!**

```
_     % implicitly input array with leaving currents (except one). Negate
h     % implicitly input array with entering currents. Concatenate
s     % sum of all elements in concatenated array

```
> 4 votes

# Answer
# 05AB1E, 4 bytes

Code:

```
OEO-

```

Explanation:

```
O     # Take the sum of the input list
 E    # Evaluate input
  O   # Take the sum of the input list
   -  # Substract from each other

```

---

Thanks to **Luis Mendo** for reminding me that I need to implement a concatenate function. If I've had implemented it sooner, it would have been 3 bytes:

**Non-competing version (3 bytes):**

The first list is the leaving current list, the second is the entering current list. Code:

```
(«O

```

Explanation:

```
(    # Negate the list, e.g. [3, 4, 5] would become [-3, -4, -5]
 «   # Concatenate the second list to the first
  O  # Take the sum and implicitly output it

```

Uses CP-1252 encoding.
> 3 votes

# Answer
# Javascript, 36 bytes

```
(a,b)=>eval(a.join`+`+'-'+b.join`-`)

```

```
f=
(a,b)=>
    eval(
        a.join`+`
        +'-'+
        b.join`-`
    )

document.body.innerHTML = '<pre>' +
  'f([1,2,3],[1,2]) = ' + f([1,2,3],[1,2]) + '\n' +
  'f([4,5,6],[7,8]) = ' + f([4,5,6],[7,8]) + '\n' +
  'f([5,7,3,4,5,2],[8,4,5,2,1]) = ' + f([5,7,3,4,5,2],[8,4,5,2,1]) + '\n' +
'</pre>'
```
> 3 votes

# Answer
# Mathematica, ~~17~~ 11 bytes

```
Tr@#-Tr@#2&

```

Quite simple.
> 2 votes

# Answer
## Common Lisp, 40

```
(lambda(x y)(-(reduce'+ x)(reduce'+ y)))

```
> 2 votes

# Answer
# Perl 6, 11 bytes

```
*.sum-*.sum

```

### Usage:

```
# give it a lexical name
my &code = *.sum-*.sum;

say code [1, 2, 3], [1, 2]; # 3
say code [4, 5, 6], [7, 8]; # 0
say code [5, 7, 3, 4, 5, 2], [8, 4, 5, 2, 1]; # 6

```
> 2 votes

# Answer
# Python 3, 24 bytes

```
lambda a,b:sum(a)-sum(b)

```

or

# Python 2, 19 bytes

```
print sum(a)-sum(b)

```

depending if I am required to print the result or just create a function that returns it.
> 2 votes

# Answer
## ES6, 39 bytes

```
(i,o)=>i.reduceRight((r,a,j)=>r+a-o[j])

```

Because I wanted to use `reduceRight`.
> 1 votes

# Answer
# Python 2, 30 bytes

```
a,b=map(sum,input());print a-b

```
> 1 votes

# Answer
## Pyth, 6 bytes

```
-.*sRQ

```

Explanation

```
       - autoassign Q = eval(input())
   sRQ - map(sum, Q)
-.*    - imp_print(minus(*^))

```

Try it here
> 1 votes

# Answer
# K5, 5 bytes

```
-/+/'

```

Difference over (`-/`) sum over (`+/`) each (`'`).

In action:

```
  (-/+/')'((1 2 3;1 2);(4 5 6;7 8);(5 7 3 4 5 2;8 4 5 2 1))
3 0 6

```
> 1 votes

# Answer
# Pyth, 5 bytes

```
-FsMQ

```

Try it online. Test suite.

`M`ap `s`um on both input lists, then `F`old subtraction (`-`).

This could also be written as `-sQsE`, which takes the lists on two lines.
> 0 votes

# Answer
# , 5 chars / 7 bytes

```
⨭î-⨭í

```

`Try it here (Firefox only).`

Wut.

# Explanation

`sum(input1) - sum(input2)`
> 0 votes

# Answer
# Common Lisp REPL, SBCL ~~28~~ 24 bytes

write this into REPL:

```
#.`(-(+ #1=,@(read))#1#)

```

then write input lists like this:

```
(2 3 4)
(2 3)

```

I hope it's okay to use such list format (instead of e.g. `'(2 3 4)`) I used coredump's answer as formula for my solution and then achieved his calculation effect in a different way.

### Explanation

Let `e_1,...,e_n` be elements of the first list and `f_1,...,f_{n-1}` be elements of second list. We want to evaluate expression `(-(+ e_1 e_2 ... e_n)f_1 f_2 ...f_{n-1})` It would mean subtracting elements of second list from sum of elements of first list. The needed expression is constructed like so:

backqoute stops evaluation

`#1=` saves a bit of writting, remembering `,@(read)`

`,@` stops effects of backquote (so that (read) will be evaluated) and takes elements out of a list.

`(read)` asks for input

`#1#` "loads" Lisp object saved by `#1=`

`#.` does evaluation of printed representation of an Lisp object
> 0 votes

---
Tags: code-golf, array, electrical-engineering
---


title: D&D 5e HP Calculator

text:
# Question
Title: D&D 5e HP Calculator
I have trouble remembering everything I have to do when leveling up a D&D character. For whatever reason, one of the things that gives me trouble is figuring out what their new maximum HP value should be. For this challenge, you will write a program or function to calculate the correct value automatically.

# Terminology

The first thing you need to know about to calculate max HP is the "Constitution modifier". Each DND character has six integer ability scores, including one for Constitution. The only relevant knowledge required for this challenge is how the Constitution ability score affects another stat, which is the Constitution modifier. In short, the modifier is equal to `floor( (ability_score - 10) / 2 )`. Adventurers can only have ability scores from 1 to 20, inclusive. Your code will never have to handle scores outside that range, which also means it will never have to handle a modifier lower than -5 or greater than +5. Though the Constitution modifier can change as a character levels up, its effects on HP are applied retroactively, so only its current value is needed to calculate current max HP.

> (This is entirely irrelevant to the challenge, but if you're curious about how it affects maximum HP: You can assume the "Tough" feat adds 2 to a character's Constitution modifier for the purposes of HP calculation, since that's *effectively* what it does. That's not the text of the feat but the math works out to be exactly the same. You don't have to handle this feat in your answer.)

Next, every class has an assigned "hit die" type, which is involved in calculating HP. The following table lists the hit dice for each class.

```
Sorcerer:  d6
Wizard:    d6
Bard:      d8
Cleric:    d8
Druid:     d8
Monk:      d8
Rogue:     d8
Warlock:   d8
Fighter:   d10
Paladin:   d10
Ranger:    d10
Barbarian: d12

```

Finally, the character's level. All that this affects is how many times to add a value to the running total in the following section. A character's level is an integer from 1 to 20, inclusive1. Your code will never have to handle a level outside that range. To reach level `n`, a character starts at level 1 and levels up `n-1` times. For example, a level 3 character got to where they are by being a level 1 character and levelling up twice.

# How to Calculate Max HP

A character's maximum HP is equal to their HP at level 1 plus the sum of the increase they received at each level.

### At level 1

At level 1, a character's HP is equal to the highest possible roll on their hit die (the number in the name of the die, for those of you unfamiliar with dice that have more than 6 sides) plus their Constitution modifier. Remember that when calculating HP at a later level, you may assume a character's Constitution has always been the same, as this part of the calculation is re-done every time Constitution changes.

### When levelling up

Every time a character levels up, they have two options. They may either roll one of their hit dice or take the average roll of that die (rounded up). Whichever they choose, their Constitution modifier is added to the result. This total is the amount that their HP increases. For this challenge, the average roll is always taken, so output is deterministic. (Again, if you're not familiar with \>6 sided dice, you can calculate the rounded-up average roll as `(highest_possible_roll / 2) + 1`.)

There is one notable exception. A character's maximum HP always increases by at least 1 each time they level up2. If the instructions in the above paragraph would result in an increase of 0 or less when leveling up, it increases by 1 instead.

# The Challenge

Your program or function will take three inputs:

* The character's class, as a string
* The character's level
* The character's Constitution ability score (*not* modifier)

It will output only one thing: The character's current maximum HP.

# Examples

Every possible combination of inputs and their associated outputs can be found at this link. For the sake of having something to look at on this page, here are 30 test cases chosen at random:

```
Barbarian, 15th level, 13 CON: 125
    Rogue, 10th level, 18 CON: 93
   Wizard, 15th level, 18 CON: 122
   Wizard, 16th level,  1 CON: 16
Barbarian, 15th level,  7 CON: 80
  Warlock, 15th level,  3 CON: 18
   Ranger, 14th level,  1 CON: 18
  Warlock,  3rd level, 14 CON: 24
    Druid,  3rd level,  4 CON: 9
   Cleric, 11th level,  5 CON: 25
     Bard, 20th level, 11 CON: 103
Barbarian, 11th level, 13 CON: 93
     Bard,  8th level, 19 CON: 75
     Bard, 16th level, 17 CON: 131
  Fighter, 10th level,  6 CON: 44
     Monk, 10th level,  2 CON: 13
   Cleric, 14th level, 17 CON: 115
   Cleric,  6th level,  5 CON: 15
    Rogue,  7th level, 13 CON: 45
   Cleric,  4th level, 14 CON: 31
    Rogue, 19th level, 15 CON: 136
  Paladin, 13th level, 13 CON: 95
   Cleric, 13th level, 15 CON: 94
     Bard,  8th level,  5 CON: 19
     Monk, 20th level, 11 CON: 103
Barbarian,  8th level, 20 CON: 101
     Monk,  1st level,  4 CON: 5
     Bard,  5th level, 17 CON: 43
     Monk, 18th level,  7 CON: 57
   Wizard, 17th level,  5 CON: 19

```

---

1. Strictly speaking, I don't think there's a rule that says 20 is the maximum level. However, 21 is the point where there stop being tables in the book to tell you what some of the various numbers in the rules should be, including the amount of experience you need to obtain to reach it. That's a good enough level cap for me.

2. I actually don't think this is true with RAW. I asked on rpg.se and such a thing doesn't appear to be written down anywhere. However, Mike Mearls, lead designer of D&D, tweeted it in March 2015. This is not authoritative the way that you could argue a tweet from lead rules developer Jeremy Crawford would be, but it is evidence that it's what they intended, so I'll use it for this challenge.

# Answer
> 2 votes
# Jelly, 34 bytes

```
OSị“#®Ʋ?[’ṃ6¤ð+‘»1×⁵’¤+⁸Ḥ¤+ð⁹_10:2

```

Full program taking three command line arguments: class, score, level.

**Try it online!**

### How?

The middle of the code, separated by `ð`s is a dyadic link which calculates the result from some previously calculated values:

```
+‘»1×⁵’¤+⁸Ḥ¤+ - maxHitPoints(halfDieValue, modifier)
+             - add: halfDieValue + modifier
 ‘            - increment
  »1          - maximum of that and 1: this is the level-up delta
       ¤      - nilad followed by links as a nilad:
     ⁵        -   program's 3rd argument, level (5th command line argument)
      ’       -   decrement: this is the number of level-ups
    ×         - multiply: level-ups * level-up delta
           ¤  - nilad followed by links as a nilad:
         ⁸    -   link's left argument: halfDieValue
          Ḥ   -   double: dieValue
        +     - add: level-ups * level-up delta + dieValue
            + - add: level-ups * level-up delta + dieValue + modifier

```

The modifier is calculated at the right hand side:

```
⁹_10:2 - getModifier(class, score)
⁹      - link's right argument, the 2nd argument, the score
 _10   - minus 10
    :2 - integer divide by 2

```

Half the die value is calculated at the left hand side:

```
OSị“#®Ʋ?[’ṃ6¤ - getHalfDieValue(class)
O             - cast to ordinals
 S            - sum
            ¤ - nilad followed by link(s) as a nilad:
   “#®Ʋ?[’    -   base 250 literal 140775266092
          ṃ6  -   convert to base 6 but with 6s in place of 0s
  ị           - index into (1-indexed and modular)

```

Considering the ordinal sums of the class names modulo `m` such that `m` is minimal while keeping the classifications (by die) from colliding yields `m=15`. Placing the required values (half-die roll) at those indexes in a list of length 15 allows lookup using Jelly's modular indexing with . Compressing the list as a base 6 number with the lone `6` replaced by a `0` is a byte shorter than the alternatives of base-7 compression or base-4 compression & increasing the values (with the byte overhead associated with using an extra nilad in the chain). The base 6, rather than 7, decompression is achieved by using the fact that base decompression,  (rather than base conversion, `b`), has implicit range construction when it's right argument, `r`, is an integer, which means is is like converting to base `r` and then changing any `0` to an `r` all in one go.

That is:

```
         class: Sorcerer,Wizard,Bard,Cleric,Druid,Monk,Rogue,Warlock,Fighter,Paladin,Ranger,Barbarian
   Ordinal sum: 837,     625,   377, 594,   504,  405, 514,  723,    713,    697,    607,   898
        mod 15:  12,      10,     2,   9,     9,    0,   4,    3,      8,      7,      7,    13
required value:   3,       3,     4,   4,     4,    4,   4,    4,      5,      5,      5,     6

```

Rearranging to the list, converting the 6 at index 13 to a zero and making it minimal in base 6:

```
mod 15:    2   3   4           7   8   9  10      12  13      0
 value: 1, 4,  4,  4,  0,  0,  5,  5,  4,  3,  0,  3,  0,  0,  4

```

Making the code

```
                list: [1,4,4,4,0,0,5,5,4,3,0,3,0,0,4]
         from base 6: 140775266092
         to base 250: [36,9,154,64,92]
code page characters:   # ®   Ʋ  ?  [
          final code: “#®Ʋ?[’ṃ6

```

# Answer
> 8 votes
## JavaScript (ES6), ~~81~~ ~~78~~ ~~76~~ 74 bytes

Takes input as *(class, level, constitution\_ability\_score)*. The class is case-insensitive.

```
(c,l,s,h=(d=parseInt(c,34)*59.9%97%77%6|4)+(s-10>>1))=>(h>0?h*l:h+l-1)+d-2

```

This is essentially using the same math as my initial version, but ***d*** is now computed without any lookup table.

### Test cases

```
let f =

(c,l,s,h=(d=parseInt(c,34)*59.9%97%77%6|4)+(s-10>>1))=>(h>0?h*l:h+l-1)+d-2

console.log(f('Barbarian', 15, 13))  // 125
console.log(f('Rogue',     10, 18))  // 93
console.log(f('Wizard',    15, 18))  // 122
console.log(f('Wizard',    16,  1))  // 16
console.log(f('Barbarian', 15,  7))  // 80
console.log(f('Warlock',   15,  3))  // 18
console.log(f('Ranger',    14,  1))  // 18
console.log(f('Warlock',    3, 14))  // 24
console.log(f('Druid',      3,  4))  // 9
console.log(f('Cleric',    11,  5))  // 25
console.log(f('Bard',      20, 11))  // 103
console.log(f('Barbarian', 11, 13))  // 93
console.log(f('Bard',       8, 19))  // 75
console.log(f('Bard',      16, 17))  // 131
console.log(f('Fighter',   10,  6))  // 44
console.log(f('Monk',      10,  2))  // 13
console.log(f('Cleric',    14, 17))  // 115
console.log(f('Cleric',     6,  5))  // 15
console.log(f('Rogue',      7, 13))  // 45
console.log(f('Cleric',     4, 14))  // 31
console.log(f('Rogue',     19, 15))  // 136
console.log(f('Paladin',   13, 13))  // 95
console.log(f('Cleric',    13, 15))  // 94
console.log(f('Bard',       8,  5))  // 19
console.log(f('Monk',      20, 11))  // 103
console.log(f('Barbarian',  8, 20))  // 101
console.log(f('Monk',       1,  4))  // 5
console.log(f('Bard',       5, 17))  // 43
console.log(f('Monk',      18,  7))  // 57
console.log(f('Wizard',    17,  5))  // 19
```

---

## Initial version, ~~87~~ 84 bytes

```
(c,l,s,h=(d=+'55654607554506'[parseInt(c,35)%24%15])+(s-10>>1))=>(h>0?h*l:h+l-1)+d-2

```

### How it works

The tricky part is to convert the class string ***c*** into the corresponding hit dice. More precisely, the value that we're going to store is ***d = dice / 2 + 1***.

We use the formula `parseInt(c, 35) % 24 % 15` which gives:

```
Class       | Base 35 -> decimal | MOD 24 | MOD 15 | d
------------+--------------------+--------+--------+---
"Sorcerer"  |      1847055419467 |     19 |      4 | 4
"Wizard"    |               1138 |     10 |     10 | 4
"Bard"      |             484833 |      9 |      9 | 5
"Cleric"    |          662409592 |     16 |      1 | 5
"Druid"     |           20703143 |     23 |      8 | 5
"Monk"      |             973475 |     11 |     11 | 5
"Rogue"     |           41566539 |      3 |      3 | 5
"Warlock"   |        59391165840 |      0 |      0 | 5
"Fighter"   |        28544153042 |      2 |      2 | 6
"Paladin"   |        46513817828 |     20 |      5 | 6
"Ranger"    |         1434103117 |     13 |     13 | 6
"Barbarian" |     25464249364423 |      7 |      7 | 7

```

By inserting the values of ***d*** at the corresponding positions into a string and padding unused slots with zeros, we get:

```
00000000001111
01234567890123
--------------
55654607554506

```

Hence the final formula:

```
d = +'55654607554506'[parseInt(c, 35) % 24 % 15]

```

Once we have ***d***, we compute:

```
h = d + ((s - 10) >> 1))

```

which is the theoretical number of points that are gained at each level-up.

If ***h*** is positive, we simply compute:

```
h * l

```

If not, we need to take into account the fact that at least 1 point is gained at each level-up. So we compute instead:

```
h + l - 1

```

In both cases, we adjust the result by adding ***d - 2***, so that the initial number of points is correctly integrated.

### Test cases

```
let f =

(c,l,s,h=(d=+'55654607554506'[parseInt(c,35)%24%15])+(s-10>>1))=>(h>0?h*l:h+l-1)+d-2

console.log(f('Barbarian', 15, 13))  // 125
console.log(f('Rogue',     10, 18))  // 93
console.log(f('Wizard',    15, 18))  // 122
console.log(f('Wizard',    16,  1))  // 16
console.log(f('Barbarian', 15,  7))  // 80
console.log(f('Warlock',   15,  3))  // 18
console.log(f('Ranger',    14,  1))  // 18
console.log(f('Warlock',    3, 14))  // 24
console.log(f('Druid',      3,  4))  // 9
console.log(f('Cleric',    11,  5))  // 25
console.log(f('Bard',      20, 11))  // 103
console.log(f('Barbarian', 11, 13))  // 93
console.log(f('Bard',       8, 19))  // 75
console.log(f('Bard',      16, 17))  // 131
console.log(f('Fighter',   10,  6))  // 44
console.log(f('Monk',      10,  2))  // 13
console.log(f('Cleric',    14, 17))  // 115
console.log(f('Cleric',     6,  5))  // 15
console.log(f('Rogue',      7, 13))  // 45
console.log(f('Cleric',     4, 14))  // 31
console.log(f('Rogue',     19, 15))  // 136
console.log(f('Paladin',   13, 13))  // 95
console.log(f('Cleric',    13, 15))  // 94
console.log(f('Bard',       8,  5))  // 19
console.log(f('Monk',      20, 11))  // 103
console.log(f('Barbarian',  8, 20))  // 101
console.log(f('Monk',       1,  4))  // 5
console.log(f('Bard',       5, 17))  // 43
console.log(f('Monk',      18,  7))  // 57
console.log(f('Wizard',    17,  5))  // 19
```

# Answer
> 3 votes
## Batch, 172 bytes

```
@set/aa=1-%3/2,h=4-a
@for %%c in (-1.Sorcerer -1.Wizard 1.Fighter 1.Paladin 1.Ranger 2.Barbarian)do @if %%~xc==.%1 set/aa-=c=%%~nc,h+=c*2
@cmd/cset/a"a*=(a>>9),-~a*~-%2+h

```

Takes class, level, and constitution as command-line arguments. Explanation: The HP can be calculated as (HP at level 1) + (level - 1) + min(further HP per level, 0) * (level - 1). The further HP per level is half the hit die plus the constitution modifier. Most classes use d8 so this becomes one less than half the constitution (`%3/2-1`), while the HP at level 1 is 3 more than that. The further HP per level and HP at level 1 are then adjusted for the six classes that don't use d8. The further HP per level is then limited to 0 (this actually uses the negative value as it's slightly golfier this way.)

# Answer
> 2 votes
## R, ~~181~~ 163 bytes

```
function(s,n,t){a=Hmisc::Cs(rc,za,rd,er,ui,mk,gu,rl,gh,la,ng,rb)
b=c(6,6,rep(8,6),rep(10,3),12)
d=b[a == substr(s,3,4)]
m=floor((t-10)/2)
d+m+(n-1)*max(d/2+1+m,1)}

```

Anonymous function. Runs as `f(class, level, CON)`.

Explanation: Creates vectors for class `s` to dice max `d`, using the 3rd and 4th letters in the class name (smallest unique mapping I found).

CON mod `m` is straight from the spec, and HP = first level (`d + m`) + the rest of the levels (`(n-1) * max(average_die + m, 1)`.

```
> f("Barbarian", 15, 13)
[1] 125
> f("Rogue", 10, 18)
[1] 93
> f("Wizard", 15, 18)
[1] 122
> f("Wizard", 16, 1)
[1] 16
> f("Barbarian", 15, 7)
[1] 80
> f("Warlock", 15, 3)
[1] 18
> f("Ranger", 14, 1)
[1] 18

```

---
Tags: code-golf
---


title: Stop walking into walls!

text:
# Question
Title: Stop walking into walls!
Some text-based rogue-likes don't let you walk into walls, and give you your move back if you try to. Why do that when you can make the player move in the closest valid direction?

## The challenge

Write a program of function that, given a direction and a 3 by 3 grid of characters, outputs the same grid after the player has taken a step.

For example,

```
9
#..
.@#
#.#

```

becomes

```
#.@
..#
#.#

```

## Input

* The direction is given by a single digit from 1 to 9, each corresponding to 8 cardinal directions and standing still. This is derived from the relative locations of the numbers on a keypad:

```
NW   N   NE
..\  |  /
...7 8 9
W- 4 5 6 -E
...1 2 3
../  |  \
SW   S   SE

```
However, you may also use the numbers 123, 456, 789 instead of 789, 456, 123. In other words, you may swap the top and bottom 2 rows or numbers if you so choose. These are the only 2 acceptable index combinations.
* The 3 by 3 grid will consist of 3 distinct, printable ASCII characters representing walkable floor, walls, and the player. (In the test cases, `.` is used for floor, `#`s are walls, and `@` is the player)
* You may choose what characters your program uses, but you must state them in your answer and they must be consistent over multiple trials.
* The character representing the character will always be in the middle of the 3 by 3 grid, and the direction will always be between 1 and 9 (incl.)
* You may take input in any order
* The 3 by 3 grid can be input as a char array, a string array, a 9 length string, or another reasonable alternative.

## Output

* Return from a function, or output to StdOut or closest alternative
* Trailing spaces and newlines are allowed
* You must use the same character representations as the input
* The same formats allowed for inputs are allowed for outputs

## How the player moves

If the specified direction is blocked by a wall (e.g. if the above example had direction 6), then look at the 2 closest directions:

* If one (and only one) direction is free, move the player in that direction.
* If no directions are free, look at the next closest 2 directions (excluding direction 5). If you have wrapped all the way around and found no open direction (player surrounded by walls), do not move the player
* If both of the directions are open, pick one to move to at random (although not necessarily uniformly).

If the given direction is a 5, do not move the player

## Test cases

(`#` = wall, `.` = floor, `@` = player)

```
Input:

9
#..
.@#
#.#

Output:

#.@
..#
#.#

Input:

3
#..
.@#
#.#

Output:

#..
..#
#@#

Input:

7
##.
#@#
..#

Output:

##@      ##.
#.#  or  #.#
..#      @.#

Input:

5
...
.@.
...

Output:

...
.@.
...

Input:

2
###
#@#
###

Output:

###
#@#
###

```

## Scoring

This is , so the shortest answer in bytes wins.

# Answer
> 2 votes
# Pyth - ~~73~~ 70 bytes

```
Kmsd"78963214"DPGJXXYt@K+xKQG\@4\.R?q/J\#/Y\#Jk=YwV5=GflTmPd(N_N)IGOGB

```

Try It

Input consists of two lines:

1st line: direction of move

2nd line: The board (positions 123456789, with 123 being the top row)

# Answer
> 3 votes
# JavaScript (ES6), ~~192~~ 163 bytes

```
a=>b=>a[(a[4]=0)+--b]?(A=(c,d)=>c==b|(e=a[c])-(f=a[d])|!e?(a[c-b?(e?e<f:new Date&1)?c:d:4]=2,a):A(+g[c],+h[d]))(+(g="3016X2785")[b],+(h="1250X8367")[b]):(a[b]=2,a)

```

# Notes

This function uses a special input format. The first input is an array of integers (`0` for `floor`, `1` for `wall` and `2` for `player`) representing the map. The second input is the (flipped) direction: `1` is north-west, `2` is north, `3` is north-east, `4` is west etc. The inputs should be given through currying syntax (`Z(a)(b)`).

# Test cases

The maps and directions have been modified to suit my input format.

```
Z=
a=>b=>a[(a[4]=0)+--b]?(A=(c,d)=>c==b|(e=a[c])-(f=a[d])|!e?(a[c-b?(e?e<f:new Date&1)?c:d:4]=2,a):A(+g[c],+h[d]))(+(g="3016X2785")[b],+(h="1250X8367")[b]):(a[b]=2,a)

testcases = [
    [[1,0,0,0,2,1,1,0,1], 3],
    [[1,0,0,0,2,1,1,0,1], 9],
    [[1,1,0,1,2,1,0,0,1], 1],
    [[0,0,0,0,2,0,0,0,0], 5],
    [[1,1,1,1,2,1,1,1,1], 2]
]
for (test of testcases) {
    console.log(Z(test[0])(test[1]))
}
```

# Answer
> 1 votes
# Python 3, ~~120~~ ~~104~~ ~~153~~ ~~176~~ 175 bytes

```
def f(n,l):
 n-=1
 if n!=4and'.'in l:l[sorted(enumerate(l),key=lambda x:abs(x[0]%3-n%3+(x[0]//3-n//3)*1j)-ord(x[1])-__import__('random').random()/9)[1][0]],l[4]='@.'
 return l

```

Try it online!

This method get direction and list of '.', '#' and '@'. Indexes start with 1 to 9 (with 0 to 8 in list really). So it has the form

```
123
456
789

```

Method return new list with new positions.

This line

```
sorted(enumerate(l),key=lambda x:abs(x[0]%3-n%3+(x[0]//3-n//3)*1j)-ord(x[1])-__import__('random').random()/9)

```

returns a list of this type:

```
>>>n=7
>>> l=['#','#','#','.','@','#','.','#','.']
>>> sorted(enumerate(l),key=lambda x:abs(x[0]%3-n%3+(x[0]//3-n//3)*1j)-ord(x[1])-__import__('random').random()/9)
[(4, '@'), (8, '.'), (6, '.'), (3, '.'), (7, '#'), (5, '#'), (1, '#'), (0, '#'), (2, '#')]

```

We calculate distances to free points and add randomness. Because `ord('#') <= ord('.') - 8 and ord('.') + 8 <= ord('@')` we can say that the nearest '.' for n=7(index in list) has an index of 8.

Example:

```
>>> f(9, ['#','.','.','.','@','#','#','.','#'])
['#', '.', '.', '.', '.', '#', '#', '@', '#']
>>> f(3, ['#','.','.','.','@','#','#','.','#'])
['#', '.', '@', '.', '.', '#', '#', '.', '#']
>>> f(5, ['.','.','#','.','@','.','#','.','#'])
['.', '.', '#', '.', '@', '.', '#', '.', '#']
>>> f(7, ['#','#','#','#','@','#','#','#','#'])
['#', '#', '#', '#', '@', '#', '#', '#', '#']
>>> f(7, ['#','.','.','.','@','#','#','.','#'])
['#', '.', '.', '@', '.', '#', '#', '.', '#'] or ['#', '.', '.', '.', '.', '#', '#', '@', '#']

```

---
Tags: code-golf, random
---


title: Build a Mass Spectrometer!

text:
# Question
Title: Build a Mass Spectrometer!
## Challenge

Given the high resolution molecular mass of an organic molecule, output the molecule's molecular formula.

## Explanation

The input will be a single number to three decimal places of precision, the relative molecular mass of the molecule.

Here, the molecular mass is defined as the sum of the masses of the atoms in the compound. Since you only are finding the molecular formulae of organic compounds, the atomic masses you need to know are:

* **C**, Carbon: 12.011
* **H**, Hydrogen: 1.008
* **O**, Oxygen: 15.999
* **N**, Nitrogen: 14.007

Your formula should only ever contain carbon, hydrogen, oxygen or nitrogen.

When writing the formula, it should take the form:

```
CaHbOcNd

```

Where the elements must be in that order (`C -> H -> O -> N`, so `C2O8N4H6` should be `C2H6O8N4`) and `a`, `b`, `c` and `d` are numbers of the preceding element in the molecule (i.e. `C2` means that there are two carbon atoms in the molecule).

If `a`, `b`, `c` or `d` are zero, that element should not be included in the formula (e.g. `C2H6O2N0` should be `C2H6O2`). Finally, if `a`, `b`, `c` or `d` are one, you should not include the number in the formula (e.g. `C1H4` should be `CH4`).

The input will always be valid (i.e. there will be a molecule with that mass). If the input is ambiguous (multiple molecules have the same mass), you must only output one of the molecules. How you choose this molecule is up to you.

## Worked Example

Suppose the input is `180.156`, there is only one combination of the elements which can have this molecular mass:

```
12.011*6 + 1.008*12 + 15.999*6 + 14.007*0 = 180.156

```

So there are:

* 6 Carbons
* 12 Hydrogens
* 6 Oxygens
* 0 Nitrogens

Therefore, your output should be:

```
C6H12O6

```

## More Examples

```
Input -> Output

28.054 -> C2H4
74.079 -> C3H6O2
75.067 -> C2H5O2N
18.015 -> H2O

```

## Winning

Shortest code in bytes wins.

# Answer
# Mathematica, 108 bytes

```
Print@@Join@@({Characters@"CHON",#}ᵀ/.a_/;Last@a<2:>Table@@a)&/@{12011,1008,15999,14007}~FrobeniusSolve~#&

```

Pure function expecting the input as an integer (1000 times the relative molecular mass); it prints all possible answers to STOUD (and returns an array of `Null`s).

The heavy lifting is done by the builtin `{12011,1008,15999,14007}~FrobeniusSolve~#`, which finds all nonnegative integer combinations of the hardcoded weights that equal the input. `{Characters@"CHON",#}ᵀ` puts each such combination in a form like `{{"C", 0}, {"H", 1}, {"O", 2}, {"N", 3}}`. ( is actually the 3-byte private Mathematica character U+F3C7.)

The transformation rule `/.a_/;Last@a<2:>Table@@a` changes pairs of the form `{x, 0}` to `{}` and pairs of the form `{x, 1}` to `{x}` (and spits out errors as it tries to apply to the whole expression as well). Then `Print@@Join@@` prints the result in the correct form, avoiding the need to cast the integers as strings and concatenate.
> 2 votes

# Answer
# Python 2, 242 bytes

```
b=[12011,1008,15999,14007]
def p(m):
 if m in b:x=[0,]*4;x[b.index(m)]=1;return x
 elif m<1:return 0
 else:
  for i in range(4):
   x=p(m-b[i])
   if x:x[i]+=1;return x
  return 0
print''.join(a+`n`*(n>1)for n,a in zip(p(input()),'CHON')if n)

```

Try it online!
Recursive function, the input is an integer (1000 times the relative molecular mass) thanks Stephen S for the idea

---

My machine took 40 segs to turn `672336` into `C33H115O3N8` with this modified code. It contains a lookup table for hits/fails to reduce the amount of recursive calls and a optimization to count an element multiple times (if the mass is high enough)
> 2 votes

# Answer
## JavaScript (ES6), ~~159~~ 158 bytes

Not exactly fast...

```
w=>[...Array(w**4|0)].some((_,n)=>![12011,1008,15999,14007].reduce((p,c,i)=>p-c*(x[i]=n%w|!(n/=w)),w*1e3,x=[]))&&x.map((v,i)=>('CHON'[i]+v).slice(0,v)).join``

```

### Demo

```
let f =

w=>[...Array(w**4|0)].some((_,n)=>![12011,1008,15999,14007].reduce((p,c,i)=>p-c*(x[i]=n%w|!(n/=w)),w*1e3,x=[]))&&x.map((v,i)=>('CHON'[i]+v).slice(0,v)).join``

console.log(f(28.054))  // -> C2H4
console.log(f(18.015))  // -> H2O
```

---

## Faster version, ~~174~~ 173 bytes

```
w=>[...Array(w**3|0)].some((_,n)=>r=(d=w*1e3-14007*(a=n/w/w%w|0)-15999*(b=n/w%w|0)-12011*(c=n%w|0))%1008|d<0?0:[c,d/1008,b,a])&&r.map((v,i)=>('CHON'[i]+v).slice(0,v)).join``

```

### All test cases

```
let f=

w=>[...Array(w**3|0)].some((_,n)=>r=(d=w*1e3-14007*(a=n/w/w%w|0)-15999*(b=n/w%w|0)-12011*(c=n%w|0))%1008|d<0?0:[c,d/1008,b,a])&&r.map((v,i)=>('CHON'[i]+v).slice(0,v)).join``

console.log(f(180.156)) // -> C6H12O6
console.log(f(28.054))  // -> C2H4
console.log(f(74.079))  // -> C3H6O2
console.log(f(75.067))  // -> C2H5O2N
console.log(f(18.015))  // -> H2O
```
> 2 votes

---
Tags: code-golf, chemistry
---


title: When will SE be down?

text:
# Question
Title: When will SE be down?
### SE will be down/read only ~~today~~ 2017-05-04 at 00:00 UTC until 00:20 UTC.

Your challenge is to output a truthy value if SE is down/read only and a falsy value if SE is not. You may not have any input, and you must use date builtins to determine if SE is down/read only (no actually querying the SE api!) Example output:

```
12:34 UTC 03 May 2017 -> false

00:00 UTC 04 May 2017 -> true

00:20 UTC 20 May 2017 -> undefined, see below

```

That's undefined behavior, because it's too far after the window of time. To be clear, you can assume your program will be run from UTC `8:00` today (5/3/17) to UTC `1:00` tomorrow (5/4/17).

```
00:21 UTC 04 May 2017 -> false

00:20 UTC 04 May 2017 -> true

00:10 UTC 04 May 2017 -> true

```

Note that any truthy or falsy values are allowed, not just `true` and `false`. You must be accurate to the nearest second, and no changing the system clock! You may assume that your program is being run on a machine on the `+0 UTC` time zone.

# Answer
# 05AB1E, ~~32~~ ~~26~~ ~~11~~ ~~9~~ 8 bytes

```
žažb«21‹

```

Explanation:

```
ža          Is the current hour &
  žb        current minute
     «      concatenated
        ‹   less than
      21    twenty one?

```

Try it online!
> 14 votes

# Answer
# JavaScript (ES6), ~~26~~ ~~24~~ ~~23~~ ~~22~~ 21 bytes

Saved 3 bytes thanks to Shaggy and 1 byte thanks to Luke.

```
_=>new Date/12e5%72<1

```

Checks if time passed in current day is less than 1200000ms (1200s or 20min). Assumes downtime to be 20 minutes not 21, which appears to be the case in the linked post. `00:20UTC` is the exclusive upper bound.
> 15 votes

# Answer
# Python 2, ~~41~~ 39 bytes

Saved 2 bytes thanks to Erik the Outgolfer

```
import time
print time.time()/1200%72<1

```

Try it online!

Uses the same algorithm as my JS and Charcoal answers.
> 8 votes

# Answer
# Jelly, 9 bytes

```
6ŒT|0Ḍ<21

```

Requires `TZ` to be set to `UTC`, which is the case for TIO.

Try it online!

### How it works

```
6ŒT|0Ḍ<21  Main link. No arguments.

6ŒT        Get the current time as a string, in the format HH:MM.
   |0      Bitwise OR each character with 0. This casts the characters to int and
           maps the non-digit character : to 0.
     Ḍ     Undecimal; convert from base 10 to integer.
      <21  Compare the result with 21, so 00:00 to 00:20 return 1, all others
           return 0.

```
> 6 votes

# Answer
# Japt, ~~32~~ 11 bytes

```
K/12e5%72<1

```

Try it online!
> 5 votes

# Answer
# JS (ES6), ~~52~~ ~~50~~ 49 bytes

```
y=>(x=new Date).getUTCMinutes()<21&&!x.getUTCHours()

```

Why is `Date` so long? Just gets the minutes past `00:00` and returns `true` if they are \< 21, and `false` otherwise.
> 3 votes

# Answer
## zsh, 38 37 bytes:

```
date +%H\ %M|read h m;((h==0&&m<21))

```
> 3 votes

# Answer
## bash, 40 bytes:

```
read h m< <(date +%H\ %M);((h==0&&m<21))

```
> 3 votes

# Answer
# APL (Dyalog), 14 bytes

```
∧/1 20>2↑3↓⎕TS

```

`∧/` is it all-true (AND reduction) that

`1 20>` these numbers are greater than

`2↑` the first two elements of

`3↓⎕TS` the current **T**ime **S**tamp with three elements dropped
> 2 votes

# Answer
# Python 3 (NON-REPL) + time, ~~81~~ 77 bytes

<sup>-4 bytes thanks to Bahrom</sup>

```
import time;e=str(time.strftime('%H:%M'));print(e[:2]=='00'and int(e[3:])<21)

```

A naïve approach, turning the current date to string and analysing its characters.
> 2 votes

# Answer
# Charcoal, 25 bytes

```
‹﹪÷ＵＰtime.time⟦⟧¹²⁰⁰¦⁷²¦¹

```

Prints `-` for truthy, nothing for falsy.

## Explanation

```
    ＵＰtime.time⟦⟧          Python function time.time()
   ÷               ¹²⁰⁰      Divided by 1200
 ﹪                    ¦⁷²   Modulo 72
‹                         ¦¹ Less than 1

```

Try it online!
> 2 votes

# Answer
# MATL, 10 bytes

*Thanks to Dennis for several corrections*

```
Z'1\480*7<

```

Try it online!

### Explanation

```
Z'    % Push current date and time as a float. Integer part is day, decimal part is time
1\    % Modulo 1. This gives the time, in units of one day
480*  % Multiply by 480
7<    % Less than 7? Note that 21 minutes / one day equals 7 / 480. Implicitly display.

```
> 2 votes

# Answer
## Alice, 17 bytes

```
/o
\T@/4&;'-.C+n

```

Try it online!

Assumes to be run on a machine whose timezone is set to UTC (like the TIO server).

### Explanation

While in Ordinal mode, the IP bounces diagonally up and down through the program. While in Cardinal mode, the IP wraps around the edges like most other Fungeoids.

```
/   Reflect to SE. Switch to Ordinal.
T   Push a string representing the current date and time, in the format:
    YYYY-MM-DDTHH:MM:SS.mmm±AA:BB
/   Reflect to E. Switch to Cardinal.
4&  Run the next command 4 times.
;   Discard four elements from the top of the stack. Since we're in Cardinal mode,
    this attempts to discard four integers. But the top stack value is a string so
    it gets implicitly converted to all the integers contained in the string. So
    year, month, day, hour, minute, seconds, milliseconds, timezone hour,
    timezone minute will be pushed separately. Then the last four of these
    will be discarded, so that we end up with the minute and the hour on
    top of the stack.
'  Push 21.
-   Subtract it from the minutes. Gives something negative for minutes 0 to 20.
.C  Compute the binomial coefficient n-choose-n. This gives 0 for negative
    results and 1 for non-negative ones. SE is down if both this value and
    the current hour are zero.
+   Add the two values. Iff they are both zero, we still get a zero.
n   Logical NOT of the value. Turns 0 into 1 and everything else into 0.
\   Reflect to NE. Switch to Ordinal.
o   Implicitly convert the result to a string and print it.
@   Terminate the program.

```
> 2 votes

# Answer
# Pyth, 11 bytes

```
&g20.d7!.d6

```

Online interpreter link
> 1 votes

# Answer
# Bash, ~~55~~ ~~53~~ ~~51~~ 50 bytes

*-1 byte from @robbie0630's comment.*

```
a=`date +%s`;echo $[1493856000<a&a<1493857200?1:0]

```

Try it online!

The advantage of this solution is that it works for any date (so will return `1` only for the period defined in the challenge, as it uses epoch time).
> 1 votes

# Answer
# Swift + Foundation, 178 bytes

```
import Foundation;var d=String(describing:Date());func g(_ s:Int)->String{return String(d[d.index(d.startIndex,offsetBy:s)])};print(g(11)+g(12)=="00" ?Int(g(14)+g(15))!<21:false)

```

Quite short by swift standards. **Check it out!**

As in my Python answer, I basically converted the current `Date` to a string and have analysed its digits, depending on which I printed the bool.
> 0 votes

# Answer
## R, 65 bytes

```
library(lubridate)
x=Sys.time()
print(all(!hour(x)&minute(x)<21))

```

Checks if the hour == 0 and the minute \< 21.
> 0 votes

# Answer
# PostgreSQL, 43 characters

```
select now()between'170503'and'170503 0:20'

```

Just because I prefer SQL for date/time calculations.

Sample run:

```
bash-4.3$ psql -c "select now()between'170503'and'170503 0:20'"
 ?column?
----------
 f
(1 row)

```
> 0 votes

---
Tags: code-golf, decision-problem, date
---


# Question
Title: The code-golfer way of searching a library
# Challenge:

I have thousands of songs in my music collection, and luckily for me, my favorite player has a search function. I also have a great memory—I can remember the title of every song in my collection. However, I'm very lazy and don't like to type—each extra keystroke is a chore!

* What is the shortest string I must search for to isolate one song? Help me memorize a list of keys I can use to minimize typing when searching!

This is , so shortest code wins.

---

# Rules:

Given an input list of song titles, generate a list of search keys subject to the following constraints:

1. Each song title should have a search key.
2. The total number of characters in the output list must be as few as possible.
3. My favorite music player is foobar2000:
    * The search function is not case-sensitive. (`apple` is the same as `aPpLE`).
    * Each search key must consist of one or more "words", in any order, separated by spaces:
        + Each word must be a substring of the corresponding song title.
        + If the same substring is specified multiple times, then it must occur that many times in its corresponding song title.
        + If a substring itself contains a space, then that substring must be surrounded with quotes.

**Hints:**

* Often, for some song titles, there are multiple search keys meeting rule 2. In such a case, any one key will do, but you get brownie points for listing them all.
* You may assume that the input list will only ASCII characters, but brownie points will be awarded for UTF-8 compatibility.
* Was Rule 3 hard to follow? Here's how it works:

```
+----------------------+ +--------+ +----------------+ +------------------------------------+
|         Input        | | Output | |   Statistics   | |             Explanation            |
|----------------------| |--------| |----------------| |------------------------------------|
|                      | | Search | |  Key   |  # of | |                                    |
|      Song title      | |  Key   | | length | words | |   Why is the output what it is?    |
|----------------------| |--------| |--------|-------| |------------------------------------|
| Wanna Be A Wanna Bea | | e e    | |      3 |     2 | |      ["Wanna Be A Wanna Bea"]      |
|                      | |        | |        |       | |   is the only string containing    |
|                      | |        | |        |       | |            ["e"] twice             |
|----------------------| |--------| |--------|-------| |------------------------------------|
| Wanta Bea A Wanna B  | | t ea   | |      4 |     2 | |       ["Wanta Bea A Wanna B"]      |
|                      | |        | |        |       | | is the only string containing both |
|                      | |        | |        |       | |          ["t"] and ["ea"]          |
|----------------------| |--------| |--------|-------| |------------------------------------|
| Wanta Be A Wanna B   | | t "e " | |      6 |     2 | |       ["Wanta Be A Wanna B"]       |
|                      | |        | |        |       | | is the only string containing both |
|                      | |        | |        |       | | ["t"] and ['e' preceding a space]  |
+----------------------+ +--------+ +----------------+ +------------------------------------+

Total number of characters in output (par): 13
```

---

# Example:

If my music collection consisted only of two albums, Michael Jackson's *Off the Wall* and *Thriler*:

```
+--------------------------------+ +--------+ +----------------+
|             Input              | | Output | |   Statistics   |
|--------------------------------| |--------| |----------------|
|                                | | Search | |  key   | # of  |
|           Song title           | |  key   | | length | words |
|--------------------------------| |--------| |--------+-------|
| Don't Stop 'Til You Get Enough | | Do     | |      2 |     1 |
| Rock with You                  | | Ro     | |      2 |     1 |
| Working Day and Night          | | Wo     | |      2 |     1 |
| Get on the Floor               | | Fl     | |      2 |     1 |
| Off the Wall                   | | ff     | |      2 |     1 |
| Girlfriend                     | | lf     | |      2 |     1 |
| She's out of My Life           | | Sh     | |      2 |     1 |
| I Can't Help It                | | Ca     | |      2 |     1 |
| It's the Falling in Love       | | v      | |      1 |     1 |
| Burn This Disco Out            | | Bu     | |      2 |     1 |
| Wanna Be Startin' Somethin'    | | nn     | |      2 |     1 |
| Baby Be Mine                   | | Ba     | |      2 |     1 |
| The Girl Is Mine               | | G M    | |      3 |     2 |
| Thriller                       | | hr     | |      2 |     1 |
| Beat It                        | | Bea    | |      3 |     1 |
| Billie Jean                    | | J      | |      1 |     1 |
| Human Nature                   | | Hu     | |      2 |     1 |
| P.Y.T. (Pretty Young Thing)    | | .      | |      1 |     1 |
| The Lady in My Life            | | La     | |      2 |     1 |
+--------------------------------+ +--------+ +----------------+

Total number of characters in output (par): 37
```

You may use the lists above to test your program. Here is the raw version of the second list:

```
["Don't Stop 'Til You Get Enough","Rock with You","Working Day and Night","Get on the Floor","Off the Wall","Girlfriend","She's out of My Life","I Can't Help It","It's the Falling in Love","Burn This Disco Out","Wanna Be Startin' Somethin'","Baby Be Mine","The Girl Is Mine","Thriller","Beat It","Billie Jean","Human Nature","P.Y.T. (Pretty Young Thing)"]

```

# Answer
> 5 votes
## Python 2, 556 bytes

Try it online.

-10 bytes, thanks to @Riker, @ovs

Took me couple evenings to make everything works.
Outputs song name, array of search keys and lenght of search keys combined (including spaces and quotes)

```
import re
S=map(str.lower,input())
T=len
for s in S:
 y=s;n=T(s)
 def R(r,t):
    global n,y
    l=T(' '.join(t))+2*sum(map(lambda x:' 'in x,t))
    if l>n:return
    if(lambda K:T([s for s in S if T(s)-T(reduce(lambda x,y:re.sub(re.escape(y),'',x,1),K,s))==T(''.join(K))])==1)(t)and l<n:y=t;n=l
    u=[(lambda s,n:n and[''.join(y) for y in eval('zip(s%s)'%(''.join(',s[%s:]'%-~x for x in range(n))))]or list(s))(r,i)for i in range(T(r))]
    for i in range(T(r)):
     for j in range(T(r)-i):R(r[j+T(u[i][j]):],t+[u[i][j]])
 R(s,[])
 print[' 'in x and'"%s"'%x or x for x in y]

```

---

**Some explanation:**

```
T=len

```

Function `len()` used very often here, so this renaming saves bytes

---

```
L=lambda s,n:n and[''.join(y) for y in eval('zip(s%s)'%(''.join(',s[%s:]'%-~x for x in range(n))))]or list(s)

```

Evaluates all possible substrings of string s lenght n.
`eval(...)` creates command `zip(s,s[1:],s[2:],...,s[n:])`
It creates substrings of lenght `n` from every index of `s` if possible. So for `s='budd'` and `n='2'` it will produce **bu, ud, dd**

---

```
F=lambda K:len([s for s in S if len(s)-len(reduce(lambda x,y:re.sub(re.escape(y),'',x,1),K,s))==len(''.join(K))])==1

```

Filter to check if provided keys (K) are for unique song name.
re.sub is requered for multiple identical keys, like \['nn','nn'\] in examples.

---

Inner function `def R(r,t)` is a recursive one to create all possible combinations of substring, that may describe song name.
Every combination is compared with currently shortest one (if there was any) to lower number of created combinations - if it is larger, it won't be accepted as all of it derivatives.
Function uses 2 variable to track state: `n` for lenght of current shortest key combination and `y` for combination itself

---

```
l=T(' '.join(t))+2*sum(map(lambda x:' 'in x,t))

```

This calculates length of key combination. `' '.join` add spaces between keys and `2*sum(...)` calculates number of needed quotes for keys with spaces.

---

```
u=[L(r,i)for i in range(0,T(r))]

```

Uses first lambda function to get all possible key combination (of every possible length) for current string.

---

Two for cycles to look through all generated keys and pass them individually to the next recursive step. Key place (`j`) is needed to correctly slice string at the end of it: `r[j+T(u[i][j]):]`.
Slice provides string, that started where current key ends, so there won't be any overlaps.
If place is unknown, equal keys would mess everything up.

---

```
[' 'in x and'"%s"'%x or x for x in y]

```

Much longer than just `y`, but keys with spaces should be surrounded by quotes

---
Tags: code-golf, string, search, optimized-output
---


title: Let's play countdown!

text:
# Question
Title: Let's play countdown!
For those of you who have seen the popular daytime TV show Countdown, you will know that the contestants are given 9 randomly selected letters and must then find the longest word they can in 30 seconds.

Your challenge is, given a string of 9 letters, to find the longest word that is an anagram of the largest subset of input letters, this means that you don't have to use all of the letters in the input string.

Input/output can be stdin/stdout, or whatever the equivalent in your language is.

## Rules

* Input will always a 9 letter string, all lower-case
* You can use as few or as many of the letters from the input string
* A word is allowed if it is found in the specified dictionary file, the dictionary file containing all the allowed words can be found here (note: I didn't compile this, credit goes to the github uploader). The file is is a .txt file which contains ~101,000 words with each word on a new line - approx 985kB.
* You **must** use the dictionary file specified above, this is to ensure that all fairness across all the entries, e.g. so everyone has the same chance of finding the longest word.
* You are allowed to manipulate the dictionary file in such a way that none of the words are edited in any way and no new ones are added, for example copying all the words to an array, making all words comma separated or copying the whole contents of the file to another file would be allowed.
* Inputs may contain any number of vowels and consonants, e.g. 9 vowels or 8 consonants and 1 vowel
* If there are multiple words with the same length, then you must output all of them (up to a limit of 5 - to prevent long lists of 5/6 letter words). Multiple words must be delimited, but this can be done in any way - comma, space etc.

## Test Cases

Input: `mhdexaspo`

Output: `hexapods, mopheads`

Input: `iesretmng`

Output: `regiments`

Input: `cmilensua`

Output: `masculine calumnies`

Input: `floiufhyp`

Output: `huffily puffily`

Input: `frtuasmjg`

Output: `frusta,jurats,jumars,tragus,grafts`

This is , so shortest code wins!

# Answer
> 4 votes
# CJam, 51 bytes

```
Laeas$W%{1$f++}/:A;qN/{$aA&},{,~}$5<_0=,:L;{,L=},S*

```

CJam has no file I/O, so I opted to read the dictionary (converted to Unix format) from STDIN and read the string of letters as a command-line argument.

### Test cases

```
$ for w in mhdexaspo iesretmng cmilensua floiufhyp frtuasmjg
> do cjam countdown.cjam $w < dictionary.txt
> echo
> done
hexapods mopheads
regiments
calumnies masculine
huffily puffily
frusta gamuts grafts jumars jurats

```

### How it works

```
La        " Push T := [ '' ].                                                         ";
eas       " Push the command-line argument (R) as a string.                           ";
$W%       " Sort its letters, then reverse.                                           ";
{1$f++}/  " Iterate over the letters; prepend them to copies of the strings in T.     ";
:A;       " Save in A and discard. A contains all sorted substrings of R.             ";
qN/       " Read from STDIN and split at linefeeds.                                   ";
{$aA&},   " Filter; keep dictionary words D such that {sort(D)} ∩ A ≠ ∅.              ";
{,~}$     " Sort by negated word length.                                              ";
5<        " Keep only the first five words.                                           ";
_0=,:L;   " Save the length of the first in L.                                        ";
{,L=},    " Filter; keep dictionary words D such that len(D) = L.                     ";
 S*       " Separate by spaces.                                                       ";

```

# Answer
> 2 votes
# Python 3, 171 bytes

This requires the dictionary to be stored in a file named `w` with each word separated by spaces.

Thanks to @wjandrea

```
s=input()
z=lambda s,f:all(f>{c}and not f.remove(c)for c in s)
l=[i for i in open('w').read().split()if z(i,set(s))]
print([x for x in l if len(x)==max(len(x)for x in l)])

```

## Examples

```
gbahrcswn # Input
['branch', 'whangs'] # Output

andapandamandarandaonsdf
['fandoms', 'pardons']

```

# Answer
> 1 votes
## Python, 175

Instead of checking if each word in the dictionary is an anagram of the input, this program calculates all the anagrams of the input and looks for them in ths dictionary. If the dictionary is pre-sorted, this scales logarithmically, instead of linearly, with the size of the dictionary; it's probably also shorter :)

```
from itertools import*
s=raw_input()
n=9
J="".join
while n:
 W=[J(p)for c in combinations(s,n)for p in set(permutations(c))if J(p)+"\n"in open("d")];n-=1
 if W:print W[:5];n=0

```

Assumes the dictionary is in a newline-terminated file named `d` in the current directory.

Note that the golfed program is ridiculously slow since it re-reads `d` on every search. If you want to test it, add `D=set(open("d"))` at the beginning, and replace `open("d")` with `D`.

# Answer
> 1 votes
# JavaScript (ES6), 165 bytes

I fear I may have gone down the wrong path with this one - it's pretty ugly! It works, but it's *very* resource intensive - I thought my machine might explode if I tried a combination of letters that only contained 6 (or fewer) letter words!

I was so focused on getting this to work that I didn't leave myself much time to golf it; any help would be appreciated. In particular, I'm trying to figure out why, when I pass the initial string of letters as a single element array, thus allowing me to remove the 2 `split`s and the `join`, it throws an error on `y.replace()`

Assumes the dictionary is already available in an array variable named `d`.

```
f=s=>(a=d.filter(w=>s.split`,`.some(n=>r(n)==r(w)),r=x=>[...x].sort()+"")).length?a.slice(0,5):s.length&&f(s.split`,`.map(y=>[...y].map(v=>y.replace(v,""))).join`,`)

```

---

## Try It

As I said, this solution is resource intensive so the following Snippet uses a limited dictionary, with only the words necessary for the 2 test cases I've included. If you're brave enough to try the *full* dictionary and your own input, you can do so here.

```
d=["dapping","genipap","huffily","kepping","knapped","peaking","puffily"]
f=s=>(a=d.filter(w=>s.split`,`.some(n=>r(n)==r(w)),r=x=>[...x].sort()+"")).length?a.slice(0,5):s.length&&f(s.split`,`.map(y=>[...y].map(v=>y.replace(v,""))).join`,`)
console.log(f("floiufhyp"))
console.log(f("ingpepkad"))
```

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


title: Output "Hello, World!" in the clipboard

text:
# Question
Title: Output "Hello, World!" in the clipboard
Make a program (or a function) that copies the exact text "Hello, World!" to the clipboard, and terminates.

# Answer
# JavaScript (ES6), 19 bytes

Run in your browser's console.

```
copy`Hello, World!`

```
> 0 votes

# Answer
## Mathematica, 31 bytes

```
CopyToClipboard@"Hello, World!"

```
> 0 votes

# Answer
# Notepad++, 15 keystrokes

```
Hello, World!<C-a><C-c>

```
> 0 votes

# Answer
# Windows command shell, 23 characters

```
echo Hello, World!|clip

```
> 0 votes

---
Tags: code-golf, hello-world
---