title: PPCG Jeopardy: Robbers

text:
# Question
Title: PPCG Jeopardy: Robbers
How well do you know the site? Let's find out.

This is a challenge. Cop's thread.

As a robber, you need to:

1. Find a non-deleted, non-closed challenge that matches a cop's submission. The challenge cannot have the following tags: , , , , , , , . The challenge must have restrictions on valid output.
2. Post the challenge here, and link to the cop you are cracking
3. Add a "Cracked" comment to the cops' post, with a link back to this answer

You will receive 1 point, plus 1 point for each 24-hour period the submission had remained uncracked (max 7). Tiebreaker is the total number of cracked submisisons.

Notes:

* If a challenge requires an output of `X`, and you output `XY` or `YX` where `Y` is anything besides whitespace, the submission is not valid for that challenge.
* A challenge newer than 2016-11-17 is not allowed.
* I reserve the right to ban certain challenges if they are widely applicable (could be applied to the majority of all submissions).
* Make sure you add a sentence or two as an explanation (it also helps your submission from being converted to a comment)
* Thanks to Daniel for the initial idea!

# Answer
## Calculate probability of getting half as many heads as coin tosses.

Cops entry (posted by Conor O'Brien): https://codegolf.stackexchange.com/a/100521/8927

Original question: Calculate probability of getting half as many heads as coin tosses.

---

The posted solution had a couple of obfuscation techniques applied, followed by multiple layers of the same obfuscation technique. Once past the first few tricks, it became a simple (if tedious!) task to extract the actual function:

```
nCr(a,b) = a! / ((a-b)! * b!)
result = nCr(x, x/2) / 2^x

```

Took a while to realise what I was looking at (for a while I suspected something to do with entropy), but once it twigged, I managed to find the question easily by searching for "probability of coin toss".

---

Since Conor O'Brien challenged an in-depth explanation of his code, here's a rundown of the more interesting bits:

It starts by obfuscating some built-in function calls. This is achieved by base-32 encoding the function names, then assigning them to new global-namespace names of a single character. Only 'atob' is actually used; the other 2 are just red-herrings (eval takes the same shorthand as atob, only to be overridden, and btoa simply isn't used).

```
_=this;
[
    490837, // eval -> U="undefined"       -> u(x) = eval(x) (but overwritten below), y = eval
    358155, // atob -> U="function (M,..." -> u(x) = atob(x)
    390922  // btoa -> U="function (M,..." -> n(x) = btoa(x), U[10] = 'M'
].map(
    y=function(M,i){
        return _[(U=y+"")[i]] = _[M.toString(2<<2<<2)]
    }
);

```

Next there are a couple of trivial string mix-ups to hide the code. These are easily reversed:

```
u(["","GQ9ZygiYTwyPzE6YSpk","C0tYSki","SkoYSkvZChhLWIpL2QoYikg"].join("K"))
// becomes
'(d=g("a<2?1:a*d(--a)"))(a)/d(a-b)/d(b) '

u("KScpKWIsYShFLCliLGEoQyhEJyhnLGM9RSxiPUQsYT1D").split("").reverse().join("")
// becomes
"C=a,D=b,E=c,g('D(C(a,b),E(a,b))')"

```

The bulk of the obfuscation is the use of the `g` function, which simply defines new functions. This is applied recursively, with functions returning new functions, or requiring functions as parameters, but eventually simplifies right down. The most interesting function to come out of this is:

```
function e(a,b){ // a! / ((a-b)! * b!) = nCr
    d=function(a){return a<2?1:a*d(--a)} // Factorial
    return d(a)/d(a-b)/d(b)
}

```

There's also a final trick with this line:

```
U[10]+[![]+[]][+[]][++[+[]][+[]]]+[!+[]+[]][+[]][+[]]+17..toString(2<<2<<2)
// U = "function (M,i"..., so U[10] = 'M'. The rest just evaluates to "ath", so this just reads "Math"

```

Although since the next bit is ".pow(T,a)", it was always pretty likely that it would have to be "Math"!

The steps I took along the route of expanding functions were:

```
// Minimal substitutions:
function g(s){return Function("a","b","c","return "+s)};
function e(a,b,c){return (d=g("a<2?1:a*d(--a)"))(a)/d(a-b)/d(b)}
function h(a,b,c){return A=a,B=b,g('A(a,B(a))')}
function j(a,b,c){return a/b}
function L(a,b,c){return Z=a,Y=b,g('Z(a,Y)')}
k=L(j,T=2);
function F(a,b,c){return C=a,D=b,E=c,g('D(C(a,b),E(a,b))')}
RESULT=F(
    h(e,k),
    j,
    function(a,b,c){return _['Math'].pow(T,a)}
);

// First pass
function e(a,b){
    d=function(a){return a<2?1:a*d(--a)}
    return d(a)/d(a-b)/d(b)
}
function h(a,b){
    A=a
    B=b
    return function(a){
        return A(a,B(a))
    }
}
function j(a,b){ // ratio function
    return a/b
}
function L(a,b){ // binding function (binds param b)
    Z=a
    Y=b
    return function(a){
        return Z(a,Y)
    }
}
T=2; // Number of states the coin can take
k=L(j,T); // function to calculate number of heads required for fairness
function F(a,b,c){
    C=a
    D=b
    E=c
    return function(a,b,c){return D(C(a,b),E(a,b))}
}
RESULT=F(
    h(e,k),
    j,
    function(a){return Math.pow(T,a)}
);

// Second pass
function e(a,b){...}
function k(a){
    return a/2
}
function F(a,b,c){
    C=a
    D=b
    E=c
    return function(a,b,c){return D(C(a,b),E(a,b))}
}
RESULT=F(
    function(a){
        return e(a,k(a))
    },
    function(a,b){
        return a/b
    },
    function(a){return Math.pow(2,a)}
);

// Third pass
function e(a,b) {...}
C=function(a){ // nCr(x,x/2) function
    return e(a,a/2)
}
D=function(a,b){ // ratio function
    return a/b
}
E=function(a){return Math.pow(2,a)} // 2^x function
RESULT=function(a,b,c){
    return D(C(a,b),E(a,b))
}

```

The structure of the function nesting is based around utility; the outer-most "D" / "j" function calculates a ratio, then the inner "C" / "h" and "E" (inline) functions calculate the necessary coin flip counts. The "F" function, removed in the third pass, is responsible for connecting these together into a usable whole. Similarly the "k" function is responsible for choosing the number of heads which need to be observed; a task which it delegates to the ratio function "D"/"j" via the parameter binding function "L"; used here to fix parameter `b` to `T` (here always 2, being the number of states the coin can take).

In the end, we get:

```
function e(a,b){ // a! / ((a-b)! * b!)
    d=function(a){return a<2?1:a*d(--a)} // Factorial
    return d(a)/d(a-b)/d(b)
}
RESULT=function(a){
    return e(a, a/2) / Math.pow(2,a)
}

```
> 5 votes

# Answer
## MATL, Luis Mendo, Count number of hefty decimals between 2 numbers

```
&:"@FYAYm7>vs

```

I figured out what it does by playing with the inputs, but I couldn't figure out for what challenge you'd have to calculate the number of integers in a range whose sum was greater than 7 times the number of digits. After reading the MATL docs, I put together an rough explanation of what this does:

```
&    % Change default input format
:    % Implictly input two integers, create inclusive range
"    % For each item in this range:
  @    % Push the item
  F    % Push false
  YA   % Convert to base N digits; N is false, so this produces base-10 digits
  Ym   % Calculate arithmetic mean
  7>   % Push 1 if this is greater than 7, 0 otherwise
  v    % Concatenate result into array with previous result
  s    % Sum
     % Implicitly end loop and output

```

I then switched from searching "digit sum greater than 7 times length" to "average digit greater than 7", which yielded the challenge I was looking for.
> 3 votes

# Answer
# 아희(Aheui), JHM, Shortest infinite loop producing no output

Tried it online, code just keeps running and there's no output.
> 3 votes

# Answer
# Reverse a 1-dimensional array

I think this is it, its hows up as the first answer for it.

https://codegolf.stackexchange.com/a/100368/31343
> 2 votes

# Answer
# C#, Yodle, Given an input, move it along the keyboard by N characters

Input a `string` and `int` and changes each `char` of the `string` to the `char` that's `N` keys away on the keyboard (wrapping around).
> 2 votes

# Answer
## Perl, Gabriel Benamy, Convenient palindrome checker

The code was obviously some kind of palindrome. Once I picked out the `y- - -` structure and noticed what was being transliterated, I knew what challenge it was.
> 2 votes

# Answer
# Pyth - https://codegolf.stackexchange.com/a/100391/31343

I quickly found out what the program did, but finding the challenge took pretty long.

Different Way Forward

this is my buffer.
> 2 votes

# Answer
# 05AB1E, 27 bytes, Adnan

Evaluating the score based from a chess FEN string

I decompressed the string and searched, and came up with this challenge.
> 1 votes

# Answer
# MATL, Luis Mendo, Calculate hamming weight with low hamming weight

```
dP7EGn:q^1J2/h)ts_hX=Gs[BE]Wd=~>~GBz*

```

I tested putting in numbers, and found the hamming weight thing on OEIS.

Then I searched on PPCG, tried putting in strings and it worked.
> 1 votes

# Answer
## C++, Karl Napf, Substring Sum Set

Online demo showing the first test case from the question.
> 1 votes

# Answer
## Ruby, histocrat, Implement a Truth-Machine

The code defines an iterated function system `f(n) = n*(3*n-1)/2` that runs until `n` mod 7 is 0. Input of `0` therefore terminates right away (after printing `0` once). Input of `1` gives `1`, leading to an infinite loop of printing `1`. Other input terminates after 1-3 steps if the initial `n` is congruent to 0, 2, 3, 5, or 6 mod 7, or grows forever if it is congruent to 1 or 4 mod 7. But that's irrelevant.
> 1 votes

# Answer
# Hexagony, 548 bytes, Martin Ender

This is the "Print every character your program doesn't have" challenge!

Prints:

```
Elizabeth obnoxiously quoted (just too rowdy for my peace): "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG," giving me a look

```

Which is very similar to the output in this one. The clue here was that the last `.` wasn't printed. Also, the code itself had no letters, and we all know that the phrases in the output contains all letters in the alphabet.
> 1 votes

# Answer
## Python, 935 Bytes, Mega Man, What is the smallest positive base 10 integer that can be printed by a program shorter (in characters) than itself?

I didn't actually try it. But I guess it prints a number longer than the program.
> 1 votes

# Answer
# Python 3, https://codegolf.stackexchange.com/a/100381/31343

Use xkcd's formula to approximate the world population

I just searched for challenges that involved leap years (because of the decoded divisibility by four checker) and that took no input.
> 0 votes

# Answer
# Brainfuck, FinW, Print the ASCII table

That was easy, since he posted his answer on that challenge.

Link to his answer
> 0 votes

# Answer
## Mathematica, JHM, Natural construction

The unary operator `±` computes a set-theory based representation of the natural numbers.
> 0 votes

# Answer
## Ruby, wat, 400th Question Celebration/Challenge

That was the first thing I found when searching for "400". That said, the challenge seems to be mistagged and should be a popcon and should probably also be closed for not having objective requirements.
> 0 votes

---
Tags: cops-and-robbers, obfuscation
---


title: Compute the height of a radix tree

text:
# Question
Title: Compute the height of a radix tree
## Introduction

A radix tree, also known as compressed trie or compressed prefix tree, is a tree-like data structure for storing a set of strings. The edges of the tree are labeled by nonempty strings, and each node is either terminal or nonterminal. The strings that the tree contains are exactly the labels of all paths from the root to a terminal node. The tree must be in the normal form defined by the following conditions:

* All nonterminal non-root nodes have at least two children.
* For every node, all outgoing edges have different first characters.

For example, here is the radix tree containing the set `["test", "testing", "tested", "team", "teams", "technical", "sick", "silly"]`, with `(N)` representing a nonterminal node and `(T)` a terminal node:

```
-(N)-te-(N)-st-(T)-ing-(T)
  |      |      |
  |      |      +-ed-(T)
  |      |
  |      +-am-(T)-s-(T)
  |      |
  |      +-chnical-(T)
  |
  +-si-(N)-ck-(T)
        |
        +-lly-(T)

```

In this challenge, your task is to compute the height of the tree, given the strings as input.

## Input

Your input is a non-empty list of strings of lowercase ASCII letters. It will not contain duplicates, but it may be in any order. It may contain the empty string. You may take the input in any reasonable format.

## Output

Your output shall be the length of the longest root-to-leaf path in the corresponding radix tree, measured in the number of nodes it contains.

In the above example, the correct output is 4, corresponding to the paths

```
(N)-te-(N)-st-(T)-ing-(T)
(N)-te-(N)-st-(T)-ed-(T)
(N)-te-(N)-am-(T)-s-(T)

```

which contain 4 nodes.

## Further examples

Here are a couple more examples of radix trees:

```
[""]
-(T)

["","fuller"]
-(T)-fuller-(T)

["","full","fuller"]
-(T)-full-(T)-er-(T)

["full","fuller"]
-(N)-full-(T)-er-(T)

["full","filler"]
-(N)-f-(N)-ull-(T)
        |
        +-iller-(T)

```

## Rules and scoring

You can write a full program or a function. This is code golf, so the lowest byte count wins.

You can use any built-ins or libraries you want, but remember to include all `import`s etc. in your byte count. Third-party libraries – those not included in the standard install of your language – are allowed, but must be listed in the header separately, e.g. **Python + pytrie0.2, 60 bytes**.

## Test cases

```
[""] -> 1
["fuller"] -> 2
["","fuller"] -> 2
["","full","fuller"] -> 3
["full","fuller"] -> 3
["full","filler"] -> 3
["full","filler","filter"] -> 4
["full","filler","fi","filter"] -> 5
["test","testing","tested","team","teams","technical","sick","silly"] -> 4
["a","aaaa","aabbaa","aabbaab","abaaa","aab","aabbb","aabba"] -> 8
["dbdbaca","ab","a","caaabaaa","adbbabdb","dbdbdbaca","dbbadbacaba","db"] -> 4
["db","dbbdbb","dbaa","cabcacaa","","acaabcacab","b","abaaaca","bacaaaaa"] -> 3
["aabaabdbb","bacaabadbbdb","abb","aabaa","ab","bcadbb","adbbcaaadbbb","caaa","bbdbcacadbab","dbbdbdb"] -> 4
["bbcaaabbbabbcadbbacadbbdbdb","b","bbbbaaaaaababa","ca","bb","bdbbacadbbdbbdbbababaacaca","abbaabbabcabaaa","bbbacacacabcacacabaaabb","bbcaaaab","bbbbcaacaadbcaaa","babbabcadbdbacacabbcacab","abcabbbaacadbcadb","bbcabbcadbcacaacaadbadbcaadb","dbbbdbbdbacaabbacabcadbdbacaca","bbaabdbdb","cabcadbbbadbadbbaadbcaca","adbadbadbdbcacadbdbbcaadbcaca","abaabbcab","aaabcaabcaab","bacacabcacaacadbadbb"] -> 6

```

# Answer
## JavaScript (Firefox 30-57), 137 bytes

```
f=(a,b=["",...a],s=new Set(b.map(w=>w[0])))=>b.length>1?(s.size>1)+Math.max(...(for(c of s)f(a,[for(w of b)if(w&&w[0]==c)w.slice(1)]))):1

```

There must be something wrong with my algorithm as I seem to have to special-case an empty string parameter.
> 2 votes

# Answer
## Retina, ~~69~~ 55 bytes

The trailing linefeed is significant.

```
m`.(?<=(?=\D*^\1(?!\2))\D*^(.*)(.))|^.
:$&
T`w
O`
A-2`

```

Input is a linefeed-separated list.

Performance can be increased significantly by inserting a `\A` before the last `\D` on the first line.

### Explanation

A node is inserted into a word in three places:

* The beginning.
* After any longest prefix shared with another word. That is, a shared prefix after which the two words differ.
* The end.

In Retina, it tends to be shorter to produce `N+1` when you've counted `N` things, so we're ignoring the one at the end. However, for the case of the empty input, we'll then also have to ignore the start, because beginning and end are the same.

To do the actual counting we insert `:` into every place where there is a node. Then we simply find the maximum number of `:` in a word and return that plus 1. Here is how the code does it:

```
m`.(?<=(?=\D*^\1(?!\2))\D*^(.*)(.))|^.
:$&

```

This detects all the nodes. It matches a character. Then it enters a lookbehind which captures that character into group `2` and the prefix before it into group `1`. Then it goes all the way to the beginning of the string to start a lookahead, which checks that it can find the prefix somewhere where it's *not* followed by the captured character. If we find this match we insert a `:` in front of the character. We also match the first character of the current word to insert a `:` at the beginning of non-empty words.

```
T`w

```

This removes all the letters and leaves only the `:`.

```
O`

```

This sorts the lines, bringing the maximum depth to the end.

```
A-2`

```

This discards all but the last line.

And the empty line at the end counts the number of empty matches in that line, which is one more than the number of colons in it.

Try it online! (The first line enables a linefeed-separated test suite, where each test case uses comma separation instead.)
> 1 votes

---
Tags: code-golf, string, data-structures, tree-traversal
---


title: The eruption of Eyjafjallajökull?

text:
# Question
Title: The eruption of Eyjafjallajökull?
Year of 2010, an Icelandic Vulcano, concisely named Eyjafjallajökull erupted, resulting in my long-planned flight being canceled.

In case this ever happens again, I would really like to know in advance, so please help me build a simple visual alert system !

**Input**

Take the Icelandic Meteorological Office volcanic activity alert code, as an input (string):

*GREEN* \- Volcano is in normal, non-eruptive state.

*YELLOW* \- Volcano is experiencing signs of elevated unrest above known background levels.

*ORANGE* \- Volcano is exhibiting heightened unrest with increased likelihood of eruption.

*RED* \- Eruption is forecasted to be imminent with significant emission of ash into the atmosphere likely.

**Output**

The graphic (ASCII art) alert, illustrating the state of Eyjafjallajökull.

*GREEN* (Eyjafjallajökull is resting)

```
      al   la
     j       j
  jaf         öku
 y               l
E                 l
-------------------

```

*YELLOW* (some smoke appears !)

```
       ~   ~
         ~
      al   la
     j       j
  jaf         öku
 y               l
E                 l
-------------------

```

*ORANGE* (more smoke !)

```
      ~  ~  ~
       ~   ~
         ~
      al   la
     j       j
  jaf         öku
 y               l
E                 l
-------------------

```

*RED* (even more smoke and some ash, too !)

```
   `~ ~ ~ ~ ~ ~`
    ` ~  ~  ~ `
     ` ~   ~ `
       ` ~ `
      al   la
     j       j
  jaf         öku
 y               l
E                 l
-------------------

```

**Rules**

* You may output to the screen (stdout), or return a string
* This is ! The shortest answer (in bytes), wins
* Feel free to replace **ö** with **o**
* Trailing spaces are allowed, but not required
* At most one trailing newline is allowed
* At most 4 leading newlines are allowed (in place of smoke)

# Answer
# Ruby, 161

Here's my take on Iceland's famous landmark, the Eyjafjallajökull Tower.

Reasonably short but I haven't come up with a good way to golf the smoke yet.

```
->n{m=85-n[-3].ord>>2
%w{`~+~+~+~+~+~` `+~++~++~+` `+~+++~+` `+~+` al%3sla j%7sj jaf%9soku y%15sl E%17sl}.map{|i|(i%"").tr(?++?`*m," ").center(19)}[m,9]+[?-*19]}

```

**Ungolfed in test program**

```
f=->n{m=85-n[-3].ord>>2     #From ASCII code of 3rd from last letter, derive m=0 for RED up to 4 for GREEN (uppercase.)
  %w{`~+~+~+~+~+~` `+~++~++~+` `+~+++~+` `+~+` al%3sla j%7sj jaf%9soku y%15sl E%17sl}.
  map{|i|                   #For each line above decode as follows:
    (i%"").                 #Replace %Xs with X spaces, by inserting  empty strings and padding sprintf style.
    tr(?++?`*m," ").        #Replace + with space. If not red, replace ` with space.
    center(19)}[m,9]+       #Centre output to 19 characters per line. Start printing at line m and go on to the end (never more than 9 lines.)
  [?-*19]                   #Add a row of --- at the bottom.
}

puts f[gets.chomp]

```
> 2 votes

# Answer
## Batch, 284 bytes

```
@set e=echo
@%e%off
set s=
set t=
goto %1
:RED
set t= `
%e%   `~ ~ ~ ~ ~ ~`
:ORANGE
%e%   %t%~  ~  ~%t%
:YELLOW
%e%    %t%~   ~%t%
%e%%s%%t%~%t%
:GREEN
%e%%s%al   la
%e%     j%s% j
%e%  jaf %s%  oku
%e% y %s%%s%  l
%e%E%s%%s%%s%l
%e%--------------------

```

Note: Lines 1 and 7 have one trailing space, line 3 has six and line 4 has three.
> 6 votes

# Answer
# JavaScript (ES6), ~~286~~ ~~262~~ ~~199~~ ~~194~~ 183 bytes

Pass input to the function `f()`, e.g. `f('GREEN')`.

```
Y=`7~3~
9~
`
f=n=>({G:'',Y,O:`5 ~2~2~
`+Y,R:'3`~ ~ ~ ~ ~ ~`\n4` ~2~2~ `\n5` ~3~ `\n7` ~ `\n'}[n[0]]+`6al3la
5j7j
2jaf9oku
 y15l
E17l
`+'-'.repeat(19)).replace(/\d+/g,n=>' '.repeat(n))
```

*-63 bytes: Used Regex instead of function to generate spaces.*
> 1 votes

# Answer
## JavaScript (ES6), ~~235~~ ~~220~~ 218 bytes

```
c=>[344,592,160,640,192,32,28,2,1,~0].map(n=>(s='6222222661116600660').replace(/./g,(_,i)=>n&(1<<i|512>>i-9)?(s+'6allajjjafökuylEl')[p++]||'-':' '),p=0).join`
`.replace(/\d/g,n=>n%4<'GYOR'.search(c[0])?n&4?'`':'~':' ')

```

```
let f =

c=>[344,592,160,640,192,32,28,2,1,~0].map(n=>(s='6222222661116600660').replace(/./g,(_,i)=>n&(1<<i|512>>i-9)?(s+'6allajjjafökuylEl')[p++]||'-':' '),p=0).join`
`.replace(/\d/g,n=>n%4<'GYOR'.search(c[0])?n&4?'`':'~':' ')

console.log(f('GREEN'))
console.log(f('YELLOW'))
console.log(f('ORANGE'))
console.log(f('RED'))
```
> 1 votes

# Answer
# PHP, ~~307~~ ~~288~~ 279 bytes

```
$o=" ";while($x<19)$o[$x+19*(($d=abs($x-9))>4?$d>7?$d-5:2:$d>3)]="Eyjafjal   lajokull"[$x++];echo strtr((($n=ord($argv[1])/8&3)-2?"":"   1~ ~ ~ ~ ~ ~2\n").($n%3?"     1~  ~  ~2\n":"").($n?"      1~   ~2\n       1 ~ 2\n":"").chunk_split(str_pad($o,114,"-"),19),12,$n-2?"  ":"`´");

```

uglyly bulky

**breakdown**

```
$o=" ";                                         // 0.init $o to string
while($x<19)$o[$x+19*(                      // 1.paint volcano
    ($d=abs($x-9))>4?$d>7?$d-5:2:$d>3           // 1a map [0..19] to row offsets
    )]="Eyjafjal   lajokull"[$x++];
echo strtr(                                     // 7. print
    (($n=ord($argv[1])/8&3)                     // 4.map GYOR to 0312
        -2?"":"   1~ ~ ~ ~ ~ ~2\n")             // 5a.add smoke & stuff for red
        .($n%3?"     1~  ~  ~2\n":"")           // 5b for orange
        .($n?"      1~   ~2\n       1 ~ 2\n":"")// 5c for yellow
    .chunk_split(                               // 3.insert linebreaks
        str_pad($o,114,"-")                     // 2.add ground
    ,19)
,12,$n-2?"  ":"`´");        // 6.replace stuff with ticks for red, with blanks else

```
> 1 votes

# Answer
# \>\<\> (Fish) ~~351~~ ~~339~~ 302 bytes

```
\l?!;o00.>~00.
\a"-------------------"a"l                 E"a"l               y "a"ukö         faj  "a"j       j     "a" al   la      "
\i:"R"-?!v
 " `  "a~<|.!00"   `~ ~ ~ ~ ~ ~`"a"    ` ~  ~  ~ ` "a"     ` ~   ~ ` "a"       ` ~"
\ :"G"-?!v
\}a"~         "a"~   ~       "
\{:"Y"-?!v
\~a"~  ~  ~      "

```

Fairly basic and ugly at the moment, I'm working on golfing it down lower but the 'RED' input makes it harder to re-use lines.

Edit 1; Moved the initial volcano string onto 1 line to reduce line breaks, moved the 'RED' string in reverse to fill empty space. (12 bytes saved)

Edit 2;Took out 'O' check and just print if the other 3 are not inputted (it doesn't specify any non 'green,red,orange,yellow' inputs. Also took out movement and used spaces in the strings to bypass extra commands. (37 bytes saved)

Online version to test!
> 1 votes

# Answer
## Python 2, 209 bytes (208 chars)

```
s=' '
y=' ~ '
v='ROY G'.index(input()[0])
a='` '[v>0]
print'\n'.join([s*3+a+'~'+' ~'*5+a,s*4+a+y*3+a,s*5+a+y*2+a,s*7+a+y+a,s*6+'al   la ',s*5+'j       j\n  jaf'+s*9+'öku\n y'+s*15+'l\nE'+s*17+'l','-'*19][v:])

```
> 0 votes

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


title: Dump core on Linux

text:
# Question
Title: Dump core on Linux
Write the shortest program which, when run with no arguments, stdin, or user input, triggers a core dump.

Your code must behave this way when run on some common out-of-the-box Linux distribution. Other than installing support for your target language, you may not reconfigure the system to make it more fragile than it is as provided.

25-byte C example: `int main(){*((int*)0)=0;}` on my Ubuntu outputs

```
Segmentation fault (core dumped)

```

# Answer
# C, 5 bytes

```
main;

```

Try it online!

## Slightly longer, 7 bytes

```
main=0;

```
> 7 votes

# Answer
# Jelly, 2 bytes

```
×ß

```

**TryItOnline!**

A dyadic atom (here `×`, but there are swathes of others) followed by the quick `ß` which instructs to call the same link (the whole line of code) with the same arity - calling it once more with any arity would also work, so, since it is the only line of code, `ß` could be replaced by any of `¢ÇçÑñ` (last link as a nilad, last link as a monad, last link as a dyad, next link as a monad, or next link as a dyad).
> 6 votes

# Answer
## NASM, 3 bytes

```
ret

```

I guess it tries to jump to whatever is on the default stack and immediately segfaults :).

Built with: `nasm -f elf64 golf.asm && ld golf.o -o golf`
> 3 votes

# Answer
## BASH, 10 bytes

```
kill -6 $$

```

kill -6 precisely does this
> 2 votes

# Answer
# C, 14 bytes

```
main(c){c/=0;}

```

It's that simple 8-)
> 0 votes

---
Tags: code-golf
---


title: Checking String for enum in Java

text:
# Question
Title: Checking String for enum in Java
Write a Java method to check if a given string matches any value in a given enum.

Your method will take two parameters, one a string and one an enum, and return `true` if the string representation of any of the enum's elements matches the given string, or `false` otherwise. Note that your method should still function normally if the String parameter is `null`, and that you aren't allowed to use any external libraries.

Test cases:

```
public enum E { A, B, C; }

public enum F { X, Y, Z; }

check("a", E.A); // is false (because "A" is uppercase)
check(null, E.A); // is false
check("C", E.A); // is true
check("X", F.X); // is true
check(null, F.X); // is false
check("y", F.X); // is false

```

The method has access (as a solver correctly understood) to a generic type E that has the only bound that "E extends Enum(E)".

Reference implementation (Ungolfed):

```
boolean <E extends Enum<E>> check(String s, E e){
    for(E ex : e.getDeclaringClass().getEnumConstants())
        if(ex.toString().equals(s)) return true;
    return false;
}

```

Another possible implementation (due to a solution) is (Ungolfed):

```
public static <E extends Enum<E>> boolean check(String s, E e){
    return java.util.stream.Stream.of(e.getDeclaringClass().getEnumConstants()).anyMatch(x->x.name().equals(s));
}

```

What I'm looking for is the shortest thing I could put after return (or, as a solutor did, after "(String s,E e)-\>)".

This is , so fewest bytes wins!

# Answer
> 1 votes
# Java 8, 86 bytes

```
(String s,E e)->java.util.stream.Stream.of(E.values()).anyMatch(x->x.name().equals(s))

```

Try it online!

# Answer
> 0 votes
# Java 4+, 96 bytes

```
boolean c(String a,Enum e){for(E f:values())if(f.toString().equals(a))return true;return false;}

```

Test code:

```
public enum E {
    A,B,C,D,E,F;
    public static void main(String[]a) {
        System.out.println(E.c("a",E));
        System.out.println(E.c("B",E));
        System.out.println(E.c("d",E));
        System.out.println(E.c("C",E));
        System.out.println(E.c("D",E));
        System.out.println(E.c("e",E));
        System.out.println(E.c("F",E));
    }
    boolean c(String a,Enum e){for(E f:values())if(f.toString().equals(a))return true;return false;}
}

```

Output:

```
false
true
false
true
true
false
true

```

---
Tags: code-golf, string, decision-problem, java
---


title: Create a version series

text:
# Question
Title: Create a version series
### The Definition

Given an integer `x`, a version series is a set of digits (base 10) from which any `x`-length subset of consecutive members is unique compared to all other possible subsets of the same length (a unique "version").

### The Task

Write a function which, when passed some subset length `x`, produces a version series, considering a scoring determined by the sum of the total number of characters outputted by inputs 1 through 10 (so, `f(1) + f(2) + ... + f(10)`).

### Further rules

* The output must always be the same for a specific `x`.
* Please do not change your algorithm (except for corrections) after posting and try to avoid using others' work.

### Examples

Let `f(x)` be the function which returns the version series.

```
>>> f(3)
0010111

```

Note that this is a valid version series as all possible consecutive subsets of length 3 (`001`, `010`, `011`, `111`) are unique. This would obviously be a terrible score, however.

```
>>> f(3)
0123456789876543210

```

This is another valid version series, with a slightly better score. This is valid for the same reasoning as before.

```
>>> f(3)
001010011110111

```

This is clearly not valid; the subsets `001`, `010`, `101`, `111` all occur more than once.

### Trivia

I have referred to this as a version series as it may be used to identify a range of compatible versions by taking a larger subset of consecutive values within the full set to identify a range of compatible versions that lie therein.

### Verifier (in Java)

```
import java.util.Scanner;
import java.util.ArrayList;

public class Checker {
    public static void main(String[] args) throws Exception {
        int substringLength = Integer.parseInt(args[0]);

        Scanner sc = new Scanner(System.in);
        sc.useDelimiter("");

        ArrayList<Character[]> active = new ArrayList<Character[]>();

        Character[] current = new Character[substringLength],
            compare, prev;

        for (int i = 0; i < substringLength; i++) {
            current[i] = sc.next().charAt(0);
        }

        for (int index = 0; sc.hasNext(); index++) {
            for (int k = 0; k < index; k++) {
                boolean differ = false;
                compare = active.get(k);
                for (int j = 0; j < substringLength; j++) {
                    differ = differ || compare[j].compareTo(current[j]) != 0;
                }
                if (!differ)
                    throw new Exception("Match found for subset " + index);
            }
            active.add(current);
            prev = current;
            current = new Character[substringLength];
            for (int k = 1; k < substringLength; k++) {
                current[k - 1] = prev[k];
            }
            current[substringLength - 1] = sc.next().charAt(0);
        }

        System.out.println("Input is a valid version series.");
    }
}

```

Compile this as Checker.java, and call with `program <x> | java Checker <x>`, where `x` is your input (obviously, the input to your program is flexible).

If you are unable (or unwilling) to use Java, you may implement your own verifier, as long as you post it with your answer and show that it works.

# Answer
> 1 votes
# Python 2, score: 11111111155

Score: `sum(10**x+x-1 for x in range(1,11))`

This program obtains the maximum possible score for any given `x`.

```
def f(x):
    s="0"*x
    while 1:
        for c in "1234567890":
            p=s+c
            if p[len(p)-x:]not in s:
                s=p
                break
        else:
            break
    return s

```

**Try it online**

This takes a long time to run for large inputs (like 6), because it's building strings thousands or millions of characters long. It also maintains a set of substrings and checks if a possible next substring is contained in it. It's not very efficient. I first tried a recursive solution, as well as a solution with a fixed number of iterations or something, but this was my working one.

### Explanation:

I solved this by recognizing a pattern in the optimal solutions for `x=1,2`, which I created by hand as below. I roughly implemented the method I used to create `f(2)` in the function above, except that I just did zero last altogether.

```
1   0123456789
2   00102030405060708091121314151617181922324252627282933435363738394454647484955657585966768697787988990

```

This algorithm tries every number in order, with zero last. Failing to do zero last will result in an early termination. `f(2)`, for example, would stop at `00102030405060708090`, because all possible values starting with `0` have been exhausted. When doing this by hand, I simply started with `f(1)`, added zeros between each digit, then went to every combination starting with a `1` (leaving out zero), then twos (leaving out zero and one), etc. Essentially, the algorithm must try the digit that you started with last.

The score is `sum(10**x+x-1 for x in range(1,11))`.

I used this formula to compute the score, because the output for all values `1-10` would probably take many days (months?) to complete. The highest I received the output for was `f(6)`, which took ~10-15 minutes. It'd take at least 10000 times that for `f(10)`. The lengths of `s` and `p` go from `1` to `10**x`. The `for` loop runs exactly 10 times, no matter what.

### Output:

They are slightly different than above because zeros are done last:

```
1   0123456789
2   00112131415161718191022324252627282920334353637383930445464748494055657585950667686960778797088980990
3   000111211311411511611711811911012212312412512612712812912013213313413513613713813913014214314414514614714814914015215315415515615715815915016216316416516616716816916017217317417517617717817917018218318418518618718818918019219319419519619719819919010210310410510610710810910022232242252262272282292202332342352362372382392302432442452462472482492402532542552562572582592502632642652662672682692602732742752762772782792702832842852862872882892802932942952962972982992902032042052062072082092003334335336337338339330344345346347348349340354355356357358359350364365366367368369360374375376377378379370384385386387388389380394395396397398399390304305306307308309300444544644744844944045545645745845945046546646746846946047547647747847947048548648748848948049549649749849949040540640740840940055565575585595505665675685695605765775785795705865875885895805965975985995905065075085095006667668669660677678679670687688689680697698699690607608609600777877977078878978079879979070870970088898808998908098009990900

```

*I was going to make a pastebin of `f(6)`, but it's past the maximum size limit a guest can create.*

**Validator** \- Counts how many unique subsets there are. If the result is `10**x`, it's correct.

# Answer
> 0 votes
# BruteForce

Tries to brute force every single possible combination using luck. Note that it does use the same seed all the time, so output is the same. Takes a single input in the `args` array to specify `i`.

```
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class BruteForce {
    private static Random rand = new Random(123);
    public static void main(String[] args) throws Exception {
        int length = Integer.valueOf(args[0]);
        List<List<Character>> used = new ArrayList<>();
        StringBuilder out = new StringBuilder();
        List<Character> put2 = new ArrayList<>();
        for(int i = 0; i < length-1; i++) {
            char one = (char) rand(48, 57);
            out.append(one);
            put2.add(one);
        }
        used.add(put2);
        long last;
        last = 0;
        for(int i = length-1; ; i++) {
            last = System.currentTimeMillis();
            List<Character> put = new ArrayList<>();
            do {
                if(last+1000 < System.currentTimeMillis()) {
                    System.out.println(out.toString());
                    return;
                }
                put.clear();
                for(int j = i-1; j >= i-length+1; j--) {
                    put.add(out.charAt(j));
                }
                put.add((char) rand(48, 57));
            } while(used.contains(put));
            used.add(put);
            out.append(put.get(length-1));
        }
    }
    public static int rand(int min, int max) {
        return rand.nextInt((max - min) + 1) + min;
    }
}

```

---
Tags: code-challenge, number, kolmogorov-complexity, optimized-output, algorithm
---


title: Make a regex polyglot

text:
# Question
Title: Make a regex polyglot
Write a regex that works in at least 2 regex flavors (or versions), and match a different string in each flavor (or version) it is running in.

The strings to be matched in this challenge are the first words of the Ubuntu code names, which are listed below. Your regex has to match from the top of the list. That is, if your regex works in 3 flavors, it has to match `Warty` `Hoary` and `Breezy`, and not others.

```
Warty
Hoary
Breezy
Dapper
Edgy
Feisty
Gutsy
Hardy
Intrepid
Jaunty
Karmic
Lucid
Maverick
Natty
Oneiric
Precise
Quantal
Raring
Saucy
Trusty
Utopic
Vivid
Wily
Xenial
Yakkety
Zesty
17.10
18.04
18.10
19.04
19.10
...

```

If your regex works in more than 26 flavors, you can match the Ubuntu version numbers instead. Starting from 17.10, for each new flavor, change the second number to 10 if it was 04, and increment the first number and change the second to 04 otherwise.

In each flavor, your regex should match only the supposed string and nothing else (not limited to the code names). Trailing newlines doesn't matter. That means your regex could either match only the string without the trailing newline, match only the string with the trailing newline, or match both. And it doesn't have to be consistent in different flavors. You can assume the input is in printable ASCII (except for the trailing newline, if there is one).

Your score is (the length of your code+10)/((number of flavors)^2). Lowest score wins.

# Answer
## 87 bytes, 5 flavours, (87+10)/25 = 3.88

```
^(((?=W)[[:word:]&&]art|Ho(?=a)\ar|Bre(?=ez)[]e]\z|E(?=dg)[[d]]g)y|(?=Da)[D-[E]]apper)$

```

I've gone with the easy to test flavours for now, which are:

The general structure is `^((...)y|...)$`, i.e. factoring out the trailing `y`s and adding anchors.

### Warty (PCRE)

```
(?=W)[[:word:]&&]art

```

In PCRE and Ruby, `[[:word:]]` is a POSIX character class matching a word character — in other flavours you get a `[[:word:]` character class then literal `&&]`, which fails the `(?=W)` assert. To make Ruby fail, `&&` is used to intersect the POSIX class with nothing, whereas in PCRE `&&` has no special meaning.

### Hoary (Javascript)

```
Ho(?=a)\ar

```

For whatever reason, Javascript is the only flavour out of the bunch where `\a` is a literal `a` — in other flavours it matches the bell character (ASCII 7).

### Breezy (Python)

```
Bre(?=ez)[]e]\z

```

In Python and Javascript, `\z` is a literal `z` — in the other flavours it is equivalent to the `$` end of string anchor. To make Javascript fail we use the char class `[]e]`, which is an empty char class `[]` then literal `e]` in Javascript, and a two-char class `[]e]` in Python.

### Dapper (.NET)

```
(?=Da)[D-[E]]apper

```

In `.NET`, `[D-[E]]` is a set difference, removing the set `[E]` from `[D]`. In PCRE, Javascript and Python, we have the class `[D-[E]` then a literal `]`. Ruby's a little different, but for some reason it parses as a class `[D-[E]]` which only matches `E`, and I have yet to figure out why...

### Edgy (Ruby)

```
E(?=dg)[[d]]g

```

Ruby allows char classes inside char classes, so `[[d]]` is actually equivalent to `[d]`, or just `d`. In the other flavours, we have `[[d]` then a literal `]`.
> 25 votes

---
Tags: code-challenge, regular-expression, polyglot
---


# Question
Title: Determine a string's Scrabble score and validity
Your task is to determine if a given string is of proper length and can be represented with Scrabble tiles and, if so, output the sum of each letter's score.

If you don't know how to play Scrabble:, you have 100 tiles with various letters A–Z printed on them, as well as two wildcards that can represent any letter. Each letter has a certain number of points, and each tile (but not necessarily word) can only be used once. When a word is played, the point value of each tile used is added up, which becomes the score. As there are a limited number of letters available, a word can only have a certain letter as many times as that letter has tiles + any unused wildcards. The Scrabble board is 15×15 cells, so the word must be between 2 and 15 characters long.

For a list of the quantity and score of each letter in the English version, see below or http://boardgames.about.com/od/scrabble/a/tile\_distribute.htm (archive).

```
Letter  Qty  Points        Letter  Qty  Points
-------------------        -------------------
A       9    1             O       8    1
B       2    3             P       2    3
C       2    3             Q       1    10
D       4    2             R       6    1
E       12   1             S       4    1
F       2    4             T       6    1
G       3    2             U       4    1
H       2    4             V       2    4
I       9    1             W       2    4
J       1    8             X       1    8
K       1    5             Y       2    4
L       4    1             Z       1    10
M       2    3             [wild]  2    0
N       6    1

```

## Further rules

* The program shall take a single string of input from STDIN or the like.
* The input will always contain only uppercase letters.
* If the string contains more copies of a letter than there are unused wildcards or tiles for that letter OR the string's length is not between 2 and 15 inclusive, the program should output `Invalid`.
* Otherwise, the score should be added up with using data from the chart above and output.
* Do not use wildcards unless necessary.
* Do not worry about bonuses such as double word scores or whether the string is a real word.
* The program shall output the result through STDOUT or the like.
* Loopholes that are forbidden by default are not allowed.
* Using an external source such as a website, as well as any libraries, APIs, functions, or the like that calculate Scrabble scores or proper quantities are not alllowed.
* This is , so fewest bytes wins.

## Walkthrough

```
Input: CODEGOLF
C -> 3, O -> 1, D -> 2, E -> 1, G -> 2, O -> 1, L -> 1, F -> 4
3 + 1 + 2 + 1 + 2 + 1 + 1 + 4 = 15
Output: 15

```

## Testcases

```
Input             Output
------------------------
SCRABBLE          14
JAZZ              19
STACKEXCHANGE     32
XYWFHQYVZVJKHFW   81
PIZZAZZ           Invalid
KIXOKEJAJAX       Invalid
MISUNDERSTANDING  Invalid

```

# Answer
> 15 votes
# Perl 5 ~~228 205 186 184 178 177 153 150 149 142 137~~ 135

Run with perl -E.

Golfed:

```
$_=<>;@a=@b=map-ord,'            0 0@0 H        ``'=~/./g;say s!.!($a[$q=64-ord$&]+=8)<8?$-+=1-29/$b[$q]:++$j!ge~~[2..15]&&$j<3?$-:Invalid

```

This solution uses some non-printable characters, so a hexdump is provided below:

```
00000000: 245f 3d3c 3e3b 4061 3d40 623d 6d61 702d  $_=<>;@a=@b=map-
00000010: 6f72 642c 2703 0904 0909 2030 2030 030e  ord,'..... 0 0..
00000020: 4030 0e20 0704 4809 1809 601d 0e0e 6027  @0. ..H...`...`'
00000030: 3d7e 2f2e 2f67 3b73 6179 2073 212e 2128  =~/./g;say s!.!(
00000040: 2461 5b24 713d 3634 2d6f 7264 2426 5d2b  $a[$q=64-ord$&]+
00000050: 3d38 293c 383f 242d 2b3d 312d 3239 2f24  =8)<8?$-+=1-29/$
00000060: 625b 2471 5d3a 2b2b 246a 2167 657e 7e5b  b[$q]:++$j!ge~~[
00000070: 322e 2e31 355d 2626 246a 3c33 3f24 2d3a  2..15]&&$j<3?$-:
00000080: 496e 7661 6c69 64                        Invalid

```

Alternatively, using Ctrl+Key:

```
$_=<>;@a=@b=map-ord,'^C^I^D^I^I 0 0^C^N@0^N ^G^DH^I^X^I`^]^N^N`'=~/./g;print s!.!($a[$q=64-ord$&]+=8)<8?$-+=1-29/$b[$q]:++$j!ge~~[2..15]&&$j<3?$-:Invalid

```

Ungolfed+commented:

```
# Read in input
$_=<>;
# @a and @b: represents approximately 8x the number of tiles (when rounded up). The
#   non-multiple-of-8 values distinguish tiles that are given equally, but are worth
#  different values
@b=@a=map-ord,"...."~=/./g;
# above is equivalent to
# @a=@b=(-03,-09,-04,-09,-09,-32,-48,-32,-48,-03,-14,-64,-48,-14,-32,-07,-04,-72,-09,-24,-09,-96,-29,-14,-14,-96);
say
    # for each character
    s!.!
        # $q: A->-1, B->-2, etc.
        # decrement number of $q tiles, add points if needed, otherwise
        #    increment j, which counts number of wilds used
        # truncate(1-29/b[q]): decimal values were chosen specifically
        #    for this to return the point value. b[q] is the number of tiles
        #    of the qth letter after a originally given.
        #  $- contains the score, is initially zero (if in a one line program,
        #   as the golfed version is), and is always an integer
        ($a[$q=64-ord$&]+=8)<8 ? $- += 1 - 29/$b[$q] : ++$j
    # s returns length, check if between 2 and 15
    !ge ~~ [2..15]
    # make sure less than 3 negative tiles (aka wilds)
    && $j < 3 ?
        # print score
        $-
    # or invalid
    : Invalid

```

# Answer
> 13 votes
# C, Rev 2, ~~151 145~~ 138

Inspired by the 159-byte code in @bebe's comment, I squeezed another ~~8 14~~ 21 characters out:

4 bytes saved by rearranging the length counter `i`. This is initialised to 1 (assuming the program takes no arguments) then multiplied by 4 every time a letter is read. It overflows to zero when the word length is greater than 15, so to check if the word length is bad, we simply check if `i<5` (I put `i<9` so it will still give invalid for one-letter words if the user accidentally intialises `i` to 2 by putting a single argument on the command line.)

4 bytes saved by changing the loop condition test to a simple `&31`. This requires that the word is terminated with a space (ASCII 32) or a null character (ASCII 0.) Normally keyboard input is terminated by a newline (ASCII 10) so the program's a bit inconvenient to use, because you have to type the space then press return as well to get the computer to read the buffer. For newline-terminated strings, I could match but not beat the way bebe does it.

~~6~~ 13 bytes saved by changing the encoding to **-(number of tiles of each letter)-(score for that letter-1)\*13**. This now requires a range from -4 for L,S,U to -118 for Q,Z. The reason for using negative numbers is to avoid the unprintable ASCII range 0 to 31. Instead the range used is the two's complement of the negative numbers 256-4=252 to 256-118=138. These are printable, extended ASCII characters. There are issues with copying and pasting these in Unicode (the way it simplifies back to ASCII depends on the code page installed which can lead to unpredictable results) so I have included the correct ASCII codes in the program comment.

The advantage of this encoding is the elimination of the variable `r` as the number of tiles is always reduced by 1 (as it is stored as a negative number, we do `t[x]++`. Additionally, the postfix operator means we can perform this increment at the same time as adding the score to `s`.

```
//char t[]={32,247,228,228,239,244,215,240,215,247,164,203,252,228,250,248,228,138,250,252,250,252,215,215,164,215,138,0};
b,s;
main(i,x){
  for(char t[]=" ÷ääïô×ð×÷¤ËüäúøäŠúüúü××¤×Š";x=getchar()&31;i*=4)
    t[x]%13?
      s-=t[x]++/13-1:
      b++;
  printf(i<9|b>2?"Invalid":"%d",s);
}

```

# C,~~184~~ Rev 1 173 (or 172 with compiler option)

I'm using GCC, and with the compiler option `-std=c99` it will allow me to move `char t[]="...."` into the initialization of the `for` loop for a saving of one additional semicolon. For readability, I have shown the program without this change, and with whitespace left in.

```
#define T t[x[1][i]-65]
i,b,s;
main(int r,char**x){
  char t[]="Z>>QxS=SZW6(><P>m<(<(SSWSm";
  for(;x[1][i];i++)
    T/10?
      s+=r=T%10+1,T-=r*10:
      b++;
  printf(i<2|i>15|b>2?"Invalid":"%d",s);
}

```

The trick is in the datatable. For each letter an ASCII code of the form **(total score of tiles for that letter)\*10+(score of one tile-1)** is stored in the table `t[]`. At runtime, these total scores are reduced as tiles are used up.

The total score of all the tiles for each letter ranges from 12 for E down to 4 for L,S,U. This form of encoding enables only printable ASCII characters to be used (ASCII 120,`x` for E down to ASCII 40,`(` for L,S,U.) Using the *number* of tiles would need a range from 120 down to 10, which is why I avoided it.

Thanks to a `#define` macro, a single symbol `T` is used in the main program to retrieve the letter index `i`from the first commandline argument, subtract ASCII `A`=65 from it to give an index ,and look it up in the table T: `t[x[1][i]-65]`.

The `for` loop is used more like a `while` loop: the loop ends when a zero byte (string terminator) is encountered in the input string.

If the tiles of that letter are not exhausted (`T/10` is nonzero) `s` is incremented by the tile score `T%10+1` to keep a total score. At the same time the tile score is stored in `r`, so that the value in the able represented by `T` can be decremented by `r*10` to indicate that one tile has been used. If the tiles are exhausted, the wildcard/blank counter `b` is incremented.

The `printf` statement is fairly self-explanatory. if the wordlength is out of bounds or the blank count is too high, print `Invalid` otherwise print the score `s`.

# Answer
> 5 votes
# JavaScript (ES6) - ~~241~~ ~~230~~ ~~199~~ 182

```
f=s=>{for(i=t=_=0,E=12,A=I=9,B=C=M=P=28,D=17,F=H=V=W=Y=41,G=16,J=X=92,K=53,L=S=U=4,N=R=T=6,O=8,Q=Z=118;c=s[i++];)this[c]%13<1?_++:t+=1+this[c]--/13|0;alert(i<3|i>16|_>2?"Invalid":t)}

```

*Edit* \- changed the way I encoded the quantities/scores to reduce size and remove non-ascii variables

*Edit 2* \- changed the quantity/score encodings to integers instead of strings

*Edit 3* \- switched to `%13` (thanks @edc65), inverted the encoding, modified the values directly, and a few other minor improvements

Tested in Firefox console.

# Answer
> 5 votes
# Python 3, ~~217~~ 201

```
b=2;i=s=0;w=input()
while i<26:n=w.count(chr(i+65));q=int('9224c232911426821646422121'[i],16);b-=max(0,n-q);s+=min(n,q)*int('1332142418513113a11114484a'[i],16);i+=1
print(["Invalid",s][-b<1<len(w)<16])

```

Ungolfed:

```
b=2    # number of blanks available
i=s=0  # letter index 0..25, running score tally
w=input()

# Loop through each letter of the alphabet
while i<26:
    # Get number of occurrences in the word
    n=w.count(chr(i+65))
    # Get quantity of the letter from hex encoded string
    q=int('9224c232911426821646422121'[i],16)
    # Remove blanks for each occurrence over that letter's quantity
    b-=max(0,n-q)
    # Score the non-blank tiles, getting scores from hex-encoded string
    s+=min(n,q)*int('1332142418513113a11114484a'[i],16)
    # Increment
    i+=1

# If b > -1 and 1 < len(w) < 16, print the score; otherwise, print "Invalid"
print(["Invalid",s][-b<1<len(w)<16])

```

**Edit:** Thanks to @BeetDemGuise for a tip that ultimately led me to much more than a 1-character reduction! Original code below:

```
q=[77-ord(x)for x in'DKKIAKJKDLLIKGEKLGIGIKKLKL'];b=2;s=0;w=input()
for c in set(w):n=w.count(c);o=ord(c)-65;b-=max(0,n-q[o]);s+=min(n,q[o])*(1+int('02210313074020029000033739'[o]))
print(["Invalid",s][-b<1<len(w)<16])

```

# Answer
> 4 votes
# JavaScript - 232 201

```
t=[9,2,2,4,12,2,3,2,9,1,1,4,2,6,8,2,1,6,4,6,4,2,2,1,2,1];w=r=0;for(i=y=z.length;i--;){x=z.charCodeAt(i)-65;if(!t[x])w++;else{t[x]--;r+=-~"02210313074020029000033739"[x]}}alert(w>2|y<2|y>15?"Invalid":r)

```

`z` stores word. Outputs as alert.

*Edit:* improved as per recommendations below.

# Answer
> 4 votes
# BEFUNGE 93 - 210 bytes.

But it doesn't check the 15 letter limit.

```
v1332142418513113:11114484: >01g:"0"-!#v_1-01p1+\v
 9224<232911426821646422121v  "Invalid"<      vp0<
<vp00p10"20"p200p900
>>~:55+-!#v_"@"-::1g:"0"-! #^_1-\1p0g+"0"-02g+>02p
_v#:-1<    #p90+g90-"0"g1:<
     @.g20<        @,,,,,,,<

```

# Answer
> 4 votes
# C, 197

Assumes the string is provided as a command line argument, e.g. `./scrabble STACKEXCHANGE`

```
s;n;m=31;main(int c,char**v){char d[]="BIBBDLBCBIAADBFHBAFDFDBBABA@ACCBADBDAHEACAACJAAAADDHDJ";for(;c=*v[1]++&m;d[c]--,s+=d[c+27]&m)n+=1+m*(!(d[c]&m||d[c=0]&m));printf(n>1&&n<16?"%d":"Invalid",s);}

```

# Answer
> 4 votes
# Haskell - 538

Save it as scrabble.hs and then compile it using

```
ghc --make scrabble && ./scrabble

```

Then enter your word as input and press enter

```
l=['A'..'Z']
sc=zip l [1,3,3,2,1,4,2,4,1,8,5,1,3,1,1,3,10,1,1,1,1,4,4,8,4,10]
vfs a y =snd $ filter (\x -> fst x == y) a !! 0
q = zip l [9,2,2,4,12,2,3,2,9,1,1,4,2,6,8,2,1,6,4,6,4,2,2,1,2,1]
i s =filter (\x -> (fst x) >=0) [(length [x | x <- s, x == a] - vfs q a,a) | a <- l]
main = do
 s <- getLine
 if length s <= 15 && length s > 2 && sum (map fst (i s)) <= 2 then
  putStrLn $ show (sum [vfs sc x| x <- s] - sum [(vfs sc (snd x)) * (fst x) | x <- (filter (\x -> fst x > 0) (i s))])
 else do
  putStrLn "Invalid"

```

# Answer
> 3 votes
# Python 2.7 - 263

I couldn't come anywhere close to DLosc's answer, but this treats each letter as a 'bag' that you pull from, until its empty, then you pull blanks, and when that is empty it errors.

```
S=input().lower()
X={chr(97+i):[int(y)+1]*(77-ord(x))for i,(x,y)in enumerate(zip('DKKIAKJKDLLIKGEKLGIGIKKLKL','02210313074020029000033739'))}
B=[0,0]
try:
 if len(S)>15:1/0
 print sum(map(lambda x:X[x].pop()if len(X[x])>0 else B.pop(),S))
except:
 print "invalid"

```

# Answer
> 2 votes
# Haskell, ~~290~~ 283

As far down as I could make it for now:

```
import Data.List
t="CdC8d::Od;D;d41N:dd:6dNdN;;4;6"
s w@(_:_:_)=let d=concat(zipWith(replicate.(`div`11).f 33)t("AEIO"++['A'..]))\\w;y=drop 15w in if length(d++w++y++y++y)>100 then s""else show$187-(sum$map((`mod`11).f 0.(t!!).f 61)d)
s _="Invalid"
f n=(-n+).fromEnum
main=interact s

```

This code abides by the rules very strictly, so make sure you don't pass it any extra characters (such as end-of-line). Use like this: `echo -n "JAZZ" | runghc scrabble.hs`.

## Explanation

The pattern `(_:_:_)` makes sure that only strings of at least two characters are considered, everything else results in `"Invalid"` (fallback pattern `_`). The table of tiles is encoded as `11*nTiles+value` converted to ASCII with an offset that allows the lookup modulo 11 to work, where the letters `AEIO` are duplicated because they occur more than 6 times each. The pool of tiles is then created using `replicate`, from which the characters in the word are removed as they occur (list difference, `\\`). The pool contains 98 tiles, so if the total length of the word and the remaining part of the pool is larger then 100, then we have used too many wildcards. Also, the word minus the first 15 letters is added three times to the length computation so any word longer than 15 letters automatically appears to use up three wildcards and therefore is invalid. Scoring is done on the remaining pool, which initially had 187 points, which we simply subtract from. Note the `f 61` rather than `f 65`, 65 being the ASCII number of `'A'`, because of the duplicate `"AEIO"` at the beginning of the pool. The rest is just boilerplate.

# Answer
> 1 votes
## Python3 - 197

```
s,i,c,r=input(),0x1a24182424416141611a2381612341151891243224c142232391,[],[]; p=len(s)
for w in s:e=8*ord(w)-520;c+=[s.count(w)<=i>>e+4&15];r+=[i>>e&15]
print(['Invalid',sum(r)][all([p>2,p<15]+c)])

```

Let's put the bignums to use :D (It doesn't handle wildcards currently, I've skipped reading that rule entirely, damn)

# Answer
> 1 votes
# Ruby - 195

```
b=2
i=s=0
w=$*[0]
(?A..?Z).map{|l|n=w.count(l);q='9224c232911426821646422121'[i].to_i(16);b-=[0,n-q].max;s+=[n,q].min*'1332142418513113a11114484a'[i].to_i(16);i+=1}
p(-b<1&&w.size<16?s:'Invalid')

```

I'm assuming the output of `"Invalid"` is fine, if not I would need to do `$><<(-b<1&&w.size<16?s:'Invalid')` which would bump it up to 198

# Clojure - 325

I haven't done clojure in a while so I'm sure there are several ways to improve my solution .ie the qty and pts lists

```
(let[w(first *command-line-args*)o(map #(count(filter #{%}(seq w)))(map char(range 65 91)))i(apply +(filter neg?(map #(- % %2)'(9 2 2 4 12 2 3 2 9 1 1 4 2 6 8 2 1 6 4 6 4 2 2 1 2 1) o)))](println(if(or(> -2 i)(not(<= 2(count w)15)))"Invalid"(apply +(map #(* % %2)o'(1 3 3 2 1 4 2 4 1 8 5 1 3 1 1 3 10 1 1 1 1 4 4 8 4 10))))))

```

Some what Un-golfed

```
(let [word    (first *command-line-args*)
      letters (map char(range 65 91))
      occ     (map #(count (filter #{%} (seq word))) letters)
      invalid (apply + (filter neg? (map #(- % %2)
                '(9 2 2 4 12 2 3 2 9 1 1 4 2 6 8 2 1 6 4 6 4 2 2 1 2 1)
                occ)))
      score   (apply + (map #(* % %2) occ '(1 3 3 2 1 4 2 4 1 8 5 1 3 1 1 3 10 1 1 1 1 4 4 8 4 10)))]
    (println
      (if (or (> -2 invalid)
              (not (<= 2 (count word) 15)))
        "Invalid"
        score)))

```

# Answer
> 1 votes
# ES6: 184 (non-strict)

`w` is assumed to already contain the word. `r` is the output string.

```
i=0,o=[..."291232342c124322491181541236181231a61416141242418241a"].map(c=>parseInt(c,16)),r=!w[16]&&w[2]&&[...w].every(c=>o[c=c.charCodeAt()*2-129]-->0?i+=o[c+1]:o[0]--)?i+"":"Invalid"

```

Here's it explained and a little less golfed:

```
// The sum.
i = 0,

// The data for the letters. It's encoded similar to the Ruby version, with
// the first being the wildcard holder. The rest hold in hex form the
// following: first = quantity left, second = value.
// The .map(c => parseInt(c, 16) simply parses all the hex characters.
o = [..."291232342c124322491181541236181231a61416141242418241a"]
  .map(c => parseInt(c, 16)),

// The result, `r`.
r = !w[16] || // If there is a 16th character in the word or no 2nd character,
    w[2] &&   // then the next section isn't evaluated. It immediately equates
              // to true, thus returning "Invalid".
   [...w] // Convert the string into an array of characters (ES6 equivalent to
          // `.split('')`
    .every(c => // This loop terminates when the callback returns a falsy
                // value.
      // Gets the ASCII value, subtracts 65, doubles it (the lookup table is
      // in pairs within one array), and decrements the counter at that entry.
      // The lookup table also doubles as a data holder.
      o[c = c.charCodeAt() * 2 - 129]--
        > 0 ?  // Test if there is something to take away. This must return
               // false at 0 and -1 so wildcards can be taken.
        i += o[c+1] : // If there was something to take away, then add the
                      // letter value to the sum.
        o[0]--) // Otherwise, take a wildcard. If this is already at 0, then
                // it returns falsy.
      ? "Invalid" : i + "" // This is where the text is returned.

```

# Answer
> 1 votes
## Dart - 201

```
main(a,{x:0xa14281424214161416a132181632145181194223421c24323219,i,r:0,m,s:2}){if((m=a[0].length)>1&&m<16)for(i in a[s=0].codeUnits)x>>(m=i*8-520)&15>0?r+=(x-=1<<m)>>m+4&15:++s;print(s<2?r:"Invalid");}

```

This requires bignums, so it won't compile to JavaScript.
With more whitespace:

```
main(a,{x:0xa14281424214161416a132181632145181194223421c24323219,i,r:0,m,s:3}){
  if((m=a[0].length)>1&&m<16)
    for(i in a[s=0].codeUnits)
      x>>(m=i*8-520)&15>0
      ? r+=(x-=1<<m)>>m+4&15
      : ++s;
  print(s<3?r:"Invalid");
}

```

# Answer
> 0 votes
# PHP, ~~180~~ ~~170~~ 168 bytes

```
for($q=str_split(KDKKIAKJKDLLIKGEKLGIGIKKLKL);$o=31&ord($argv[1][$i++]);)$s+=$q[$o]++>L?$q[0]++>L?$f=1:0:X02210313074020029000033739[$o]+1;echo$f|$i<3|$i>16?Invalid:$s;

```

Yay! beating JS!

**breakdown**

```
for(
    $q=str_split(KDKKIAKJKDLLIKGEKLGIGIKKLKL);  // init quantities: L=1,A=12
    $o=31&ord($argv[1][$i++]);                  // loop through characters: map to [1..26]
)
    $s+=                                          // increase score by ...
        $q[$o]++>L?                                 // old quantity below 1?
        $q[0]++>L?$f=1                              // no more wildcards? set error flag
        :0                                          // wildcard: 0 points
        :X02210313074020029000033739[$o]+1;         // else: letter score
echo$f|$i<3|$i>16?Invalid:$s;                   // output

```

I´m so glad there is no letter score larger than 10.

---
Tags: code-golf, string, board-game, scrabble
---


title: Bouncey-edged XY box with a marker at Z

text:
# Question
Title: Bouncey-edged XY box with a marker at Z
Long time lurker first time poster here.

Write a program which takes 3 inputs: X, Y and Z.

* X = across (columns)
* Y = down (rows)
* Z = Location Marker

The program should then print a visual grid X across and Y down. This grid will can be made of any character except "+". Each 'location' is given an index number, counting up from **1** at coordinate 1, 1 across and then down until the end.

X and Y will always be at least 3, and Z will never be bigger than `X * Y`.

Z will represent the location which is printed as a "+", on the location as well as 1 character left, right, up and down. For example:

```
 +
+++
 +

```

Finally, if the + characters would intercept the edges (top most, left most, right most and/or down most edge), then the + should bounce back along the same axis and overflow the other side.

Examples: Input = 5, 5, 13

```
-----
--+--
-+++-
--+--
-----

```

Input = 10, 10, 10

```
-------+++
---------+
---------+
----------
----------
----------
----------
----------
----------
----------

```

Input = 10, 10, 21

```
----------
+---------
+++-------
+---------
----------
----------
----------
----------
----------
----------

```

Edit : non square example 16,3,32

```
---------------+
-------------+++
---------------+

```

I think I've covered everything. There should be no limit to the input, but if your program requires, cap it off at 64 * 64.

~~**Bonus point (can I do that?):** Input Z should not be \> X * Y, but if it is larger than Y * Z, then output the center + to the middle of the grid.~~ **EDIT:** Input Z cannot be greater than X * Y

Edit 2:. Made some changes to X and Y to hopefully be clearer

This is code golf, shortest code wins.

# Answer
## Python 2, ~~172~~ 171 bytes

```
def f(x,y,z):A=[['-']*x for _ in' '*y];z-=1;X,Y=z%x,z/x;a=[2,-1];A[Y][X]=A[Y+a[Y>0]][X]=A[Y-a[Y<y-1]][X]=A[Y][X+a[X>0]]=A[Y][X-a[X<x-1]]='+';print'\n'.join(map(''.join,A))

```

Edit: Saved 1 bytes by converting to function.

Previous (more readable):

```
x,y,z=inputtt
A=[['-']*x for _ in' '*y]
z-=1
X,Y=z%x,z/x
a=[2,-1]
A[Y][X]=A[Y+a[Y>0]][X]=A[Y-a[Y<y-1]][X]=A[Y][X+a[X>0]]=A[Y][X-a[X<x-1]]='+'
print'\n'.join(map(''.join,A))

```
> 1 votes

# Answer
## JavaScript (ES6), 165 bytes

```
(x,y,z,a=[...Array(y)].map(_=>Array(x).fill`-`))=>a.map(a=>a.join``,a[b=--z/x|0][c=z%x]=a[b?b-1:2][c]=a[b][c?c-1:2]=a[y+~b?b+1:y-3][c]=a[b][++c<x?c:x-3]=`+`).join`\n`

```
> 1 votes

# Answer
# Befunge, 175 bytes

```
>&:10p60p&:00p&1-:10g%:20p\10g/:30p::1+00g-!-\!+2-50p::1+1v
vg02g01*`\4\`0:-g05\!-g03:g00p01-1<g06+p00-1<p04-2+!\-!-g0<
>-!*\10g40g-:0`\4\`**+!2*"+"+10g:#^_$5500g:#^_$$$>:#,_@

```

Try it online!

The first line (and a short continuation onto the second line) is where the parameters are read in and a few constants are calculated - the coordinates of the location (*lx*, *ly*), as well as adjusted coordinates which account for the bouncing off the edges:

```
ax = lx - (lx+1==w) + (lx==0) - 2
ay = ly - (ly+1==h) + (ly==0) - 2

```

The second and third lines contain the main loops over the height and width of the grid, the path of execution going from right to left initially before turning around onto the third line going left to right. For each coordinate in the grid (*gx*, *gy*) we calculate the following condition:

```
(gx==lx && gy>ay && gy<ay+4) || (gy==ly && gx>ax && gx<ax+4)

```

If that condition is true, we push a `"+"` onto the stack, if false we push a `"-"`. To avoid branching here, we're really just pushing `43 + 2 * !condition` (43 being the ASCII value of plus and 45 being minus).

Once the loops have finished, the final bit of code is just a standard output routine that prints out everything on the stack.
> 1 votes

# Answer
# JavaScript (ES6), 170

Still golfable

```
(w,h,z,t=--z%w,u=z/w|0,r='-'.repeat(w),S=(f,j)=>(r+f+r).substr(w-j,w))=>[...Array(h)].map((q=u-!!u-!(u+1-h),y)=>y-u?y>=q&y<q+3?S('+',t):r:S('+++',t-!!t-!(t+1-w))).join`
`

```

*Less golfed*

```
(w, h, z
, t=--z%w
, u=z/w|0
, r='-'.repeat(w)
, S=(f,j)=>(r+f+r).substr(w-j,w)
) => [...Array(h)].map(
    (q = u-!!u-!(u+1-h),
     y) => y-u?y>=q&y<q+3?S('+',t):r:S('+++',t-!!t-!(t+1-w))
).join`\n`

```

**Test**

```
F=
(w,h,z,t=--z%w,u=z/w|0,r='-'.repeat(w),S=(f,j)=>(r+f+r).substr(w-j,w))=>[...Array(h)].map((q=u-!!u-!(u+1-h),y)=>y-u?y>=q&y<q+3?S('+',t):r:S('+++',t-!!t-!(t+1-w))).join`
`

function update() {
  var [x,y,z] = I.value.match(/\d+/g)
  O.textContent = F(+x,+y,+z)
}

update()
```

```
<input value='5 6 10' oninput='update()' id=I>
<pre id=O>
```
> 0 votes

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


title: Hilbertify an image

text:
# Question
Title: Hilbertify an image
I like the Hilbert Curve.

---

Your task for this challenge is to take an image (strictly a square image where all the sides are a power of two pixels wide) and unravel it line by line in a zig-zagging fashion and ravel it back up in a pseudo-Hilbert curve.

## Unraveling

To unravel you will start with the pixel in the upper left hand corner and travel right until you arrive at the edge of the image. Once you have hit the edge of the image you will move down to the next row and begin traveling left until you hit the edge again. You will continue unraveling row by row switching the direction each time so you get one continuous curve. This should look like a well played game of snake

The result of unraveling should be an order of pixels that includes every pixel exactly once

## Reraveling

Once you have an order for the pixels you will rearrange them on a new equally sized canvas following the path of a pseudo-Hilbert curve. For a `2**n` sized square image you should use the nth iteration of the pseudo-hilbert curve. Each pixel will be placed in exactly one spot on the new canvas. You should reravel the image so that the point originally in the top left (the start of our snake curve) will remain there and point in the bottom right (the end of our snake curve) will be placed in the top right.

## I/O

Your program or function should take in an image of specified constraints via standard methods and output another image via standard methods.

## Scoring

This is program with the fewest bytes wins.

## Examples

### Input

### Output

---

### Input

### Output

---

### Input

### Output

---

I also recommend testing on a blank white or solid color image to make sure you are not missing any pixels.

Feel free to include your own results in your answers!

# Answer
> 8 votes
# Mathematica, ~~286~~ 273 bytes

```
Image[Array[1,{l=Length@#,l}]~ReplacePart~Thread[#&@@@Split[#&@@@FoldList[Switch[#2,"-",#{1,I},"+",#/{1,I},"F",#+{ReIm@Last@#,0},_,#]&,{{1,1},I},Characters@Nest[StringReplace@{"L"->"+RF-LFL-FR+","R"->"-LF+RFR+FL-"},"L",Log2@l]]]->Join@@MapAt[Reverse,#,2;;;;2]]]&@*ImageData

```

Phew! Challenging but fun!

# Explanation

```
ImageData

```

Convert an `Image` into an array of RGB values.

```
Array[1,{l=Length@#,l}]

```

Generate an `l` by `l` array with head `1`, where the `l` is the length of the input (i.e. the width of the image).

This yields `{{1[1, 1], 1[1, 2], ..., 1[1, L]}, {1[2, 1], ..., 1[2, L]}, ..., {1[L, 1], ..., 1[L, L]}}` (`l` written in caps to reduce confusion)

```
StringReplace@{"L"->"+RF-LFL-FR+","R"->"-LF+RFR+FL-"}

```

A `StringReplace` function that replaces every `"L"` with `"+RF-LFL-FR+"` and `"R"` with `"-LF+RFR+FL-"`

```
Nest[ ... ,"L",Log2@l]

```

Apply the `StringReplace` function to the `String` `"L"`, `Log2[l]` times.

```
Characters

```

Convert the resulting `String` into a `List` of characters.

```
Switch[#2,"-",#{1,I},"+",#/{1,I},"F",#+{ReIm@Last@#,0},_,#]&

```

An unnamed function that:

* If the second input is `"-"`, multiply the second element of the first input by `I`.
* If the second input is `"+"`, divide the second element of the first input by `I`.
* If the second input is `"F"`, increase the first input by the `ReIm` (separates the real and imaginary part of the input) of the second input.

```
FoldList[ ... ,{{1,1},I}, ... ]

```

Starting with `{{1,1},I}`, cumulatively apply the above unnamed function, using each element of the `List` of characters as the second input. This code yields the outputs of all iterations.

```
#&@@@Split[#&@@@ ... ]

```

Get rid of the second elements of each `List` and delete duplicates. (The steps up to this point generate a `List` of coordinates of the Hilbert curve)

```
Join@@MapAt[Reverse,#,2;;;;2]

```

Unravel the input RGB array (reverses every other row and flattens).

```
Thread[ ... -> ... ]

```

Create `Rule` objects, such that the first element in the first input (the coordinates of the Hilbert curve) is paired with the the first element of the second input (the unraveled image), the second element with the second input, and so on.

```
... ~ReplacePart~ ...

```

Apply those replacement `Rule`s to the `Array` from the second step.

```
Image

```

Convert to the array of RGB values into an `Image`.

# Sample in/out

Input:

Output:

---

Input:

Output:

# Inverse function (~~266~~ 253 bytes)

```
Image[MapAt[Reverse,Extract[#,#&@@@Split[#&@@@FoldList[Switch[#2,"-",#{1,I},"+",#/{1,I},"F",#+{ReIm@Last@b,0},_,#]&,{{1,1},I},Characters@Nest[StringReplace@{"L"->"+RF-LFL-FR+","R"->"-LF+RFR+FL-"},"L",Log2[l=Length@#]]]]]~Partition~l,2;;;;2]]&@*ImageData

```

# Answer
> 6 votes
# Octave 234 Bytes

```
I=imread(input(''));w=rows(I);X=[0,3;1,2];for k=2:log2(w);n=numel(X);X=[X',rot90(X',2)+3*n;X+n,X+2*n];end;for k = 1:3;I(2:2:end,:,k)=fliplr(I(2:2:end,:,k));end[~,S]=sort(X(:));I(S+(0:w^2:2*w^2))=permute(I,[2 1 3]);imwrite(I,input(''))

```

File names of input and output images should be provided form standard input. size of code without input/output is **194 bytes**.
Explanation:

The base pattern of indices is:

```
X =
  0 3
  1 2

```

In each iteration 4 copies from result of the previous iteration made and some transformation applied to each copy then all blocks concatenated to form the current result.

```
X =[0,3;1,2];
for k = 2:log2(s)
    n=numel(X);
    X = [X',rot90(X',2)+3*n;X+n,X+2*n];
end

```

so we have:

```
block(1,1): X'
block(1,2): rot90(X',2)+3*n
block(2,1): X+n
block(2,2): X+2*n

0    1  | 14   15
3    2  | 13   12
--------|--------
4    7  |  8   11
5    6  |  9   10

```

Hilbert indices sorted and indexes of sorted elements returned:

```
[~,S]=sort(X(:));

```

Unraveling applied flipping all even rows:

```
for k = 1:3
    I(2:2:end,:,k) = fliplr(I(2:2:end,:,k));
end

```

Reraveling applied :
-S repeted for each channel
-permutation applied since in Octave data arranged column wise

```
I(S+(0:w^2:2*w^2))=permute(I,[2 1 3]);

```

Example images:

---
Tags: code-golf, math, graphical-output, image-processing, fractal
---


title: Help! I have more homework!

text:
# Question
Title: Help! I have more homework!
My teacher was more than unhappy with my Martian Homework. I followed all the rules, but she says that what I output was gibberish... when she first looked at it, she was highly suspicious. "All languages should follow Zipf's law blah blah blah"... I didn't even know what Zipf's law was!

It turns out Zipf's law states that if you plot the logarithm of the frequency of each word on the y axis, and the logarithm of the "place" of each word on the x axis (most common = 1, second most common = 2, third most commmon = 3, and so on), then the plot will show a line with a slope of about -1, give or take about 10%.

For example, here's a plot for Moby Dick:

The x axis is the *n*th most common word, the y-axis is the number of occurences of the *n*th most common word. The slope of the line is about -1.07.

Now we're covering Venutian. Thankfully, Venutians use the latin alphabet. The rules are as follows:

* Each word must contain at least one vowel (a, e, i, o, u)
* In each word there can be up to three vowels in a row, but no more than two consonants in a row (a consonant is any letter that's not a vowel).
* No words longer than 15 letters
* Optional: group words into sentences 3-30 words long, delimited by periods

Because the teacher feels that I cheated on my Martian homework, I've been assigned to write an essay at least 30,000 words long (in Venutian). She's going to check my work using Zipf's law, so when a line is fitted (as described above) the slope has to be at most -0.9 but no less than -1.1, and she wants a vocabulary of at least 200 words. The same word should not be repeated more than 5 times in a row.

This is CodeGolf, so shortest code in bytes wins. Please paste the output to Pastebin or another tool where I can download it as a text file.

# Answer
> 3 votes
# Mathematica, 102 bytes

```
""<>RandomChoice[1/Range@215->Rest@Flatten@Outer[StringJoin,a={"v","a","e","i","o","u"},a,a,{" "}],8!]

```

Unnamed function taking no input and returning a string consisting of 40,320 three-letter Venusian words with trailing spaces.

`Outer[StringJoin,a={"v","a","e","i","o","u"},a,a,{" "}]` produces the 216 three-letter words possible using only the letters "vaeiou", each with its own trailing space. The first of these words, "vvv", is not valid Venusian, but `Rest` throws it away.

Then `RandomChoice[1/Range@215->...,8!]` makes 8! = 40,320 random choices from the resulting 215-word list, with frequency weights determined by the reciprocals of the first 215 integers (`1/Range@215`). Finally, `<>""...` concatenates the strings in the resulting list.

The output is far from deterministic; one run yielded this Venusian essay.

# Mathematica, 129 bytes

```
#2&@@@Sort[Join@@Table[{i,Rest@Flatten@Outer[StringJoin,a={"v","a","e","i","o","u"},a,a,{" "}]~Part~j},{j,215},{i,0,1,j/7!}]]<>""

```

This one is deterministic. The base set of 215 words is the same, but now each word is repeated an exact number of times (word #j is repeated roughly 7!/j times) to force zipf's law to hold. Then the words are interleaved equally to avoid repetitions. (Imagine each word is laid out on a ruler, with all the copies of that word equally spaced; when all the words are read in order, no particular word will repeat much, perhaps not at all.) The result is a 30,117-word Venusian essay.

# Answer
> 2 votes
# 05AB1E, ~~34~~ ~~33~~ 32 bytes

```
525DL/9*vNy<FD}})žMDâžNâJè3ô.rðý

525DL                            Yield [1, ..., 525]
     /                           Yield [525/1, ..., 525/525]
      9*                         Yield [4725/1, ..., 4725/525]. It's the number of occurences of each word. The sum of this array is greater than 30000
        v                        For each value (y = value, N = iteration counter starting from 0)
         N                       Push iteration counter
          y<FD}                  Push an array of "int(value)" times the iteration counter
               }                 End for
                )                Wrap everything in an array. At this point the array countains the sorted indices of all words that matches the frequency specs
                 žM              Push "aeiou"
                   Dâ            Cartesian product with itself (["aa", "ae", ...])
                     žN          Push the consonants
                       âJ        Cartesian product and join the values to make valid venutian words
                         è       Compute a big string with all words that correspond to the formerly computed indices
                          3ô     Since all words are concatenated, separate them into blocks of 3 letters
                            .r   Shuffle
                              ðý Join with whitespaces and implicitly display

```

Try it online!

I think it is still pretty golfable! For instance the numeric constants and `vNy<FD}` might be golfable.

Output example

## How does it work?

It generates all combinations of words following the rule "vowel+vowel+consonant", which makes 525 unique valid words (more than 200). It then associates to each of them a frequency that satisfies the law `f(x) = 4725/x` where `x` is the rank of the current word, starting at 1 and ending at 525. Then the frequencies are normalized and multiplied so there are at least 30000 words. This code always yields 32074 words to make the involved constants golfable (please see the code explanation). So each word is repeated the amount of times corresponding to the frequency of the same word. Finally the words are shuffled. However it does not guarantee that a word is never repeated five times in a row. Hence the programs generates more than the needed 200 unique words in order to decrease the probability of having a word repeated five times in a row. Please note that this code always generates the same word sequence. The only thing that differs between two runs is the result of the shuffling operation.

## How to evaluate frequency?

I made a simple Python3 code that takes the text in the file named "output" (from the algorithm point of view, it makes sense!) and outputs to "stats.csv".

```
from collections import Counter
from math import log10

with open("output", "r") as f:
    with open("stats.csv", "w") as stats:
        words = f.read().split()
        freqs = Counter(words)
        freqs = sorted([(i,freqs[i]) for i in freqs],key=lambda x:-x[1])

        print(len(words), "words")
        stats.write("logX;logF\n")
        for i, (key, f) in enumerate(freqs):
            stats.write(str(log10(i+1))+";"+str(log10(f))+"\n")

```

Which always yields the following distribution for my code:

So the slope is -1.0138. This value is now less close to -1 than the slope of the previous code, but it still satisfies the slope constraints.

# Answer
> 0 votes
# Bash/Core Utils, ~~122~~ 110 bytes

```
for w in {b,c,d}{a,e,i}{f,g,h}{o,u,a}{j,k,l};{ let ++x;yes $w|head -$[5575/x];}|shuf --random-source=<(yes ae)

```

Unrolled:

```
for w in {b,c,d}{a,e,i}{f,g,h}{o,u,a}{j,k,l};{
    let ++x
    yes $w|head -$[5575/x]
}|shuf --random-source=<(yes ae)

```

The `for w` loop generates 243 distinct words. `let ++x;` increments initially unset x (per arithmetic expression rules during that first execution, `x` is treated as 0 and thus its increment sets it to 1). The next line thus generates succeeding words at frequency 5575/x to approximate zipf frequency.

The next step is to permute this deterministically to fit the repetition requirement; despite `--random-source` being a terribly large flag name, using it with shuf beats the char count of hand rolling a mul-mod selector. `yes ae` is actually the shortest fixed "random" device I found to comply.

This generates this 33729 word essay \[pastebin\].

## Bash/Core Utils, ~~96~~ 84 bytes (non-competing)

For a non-deterministic approach, just chop off shuf flags:

```
for w in {b,c,d}{a,e,i}{f,g,h}{o,u,a}{j,k,l};{ let ++x;yes $w|head -$[5575/x];}|shuf

```

## Analysis

The zipf slope is tuned to be straight. Using Excel to plot on logarithmic scales:

The teacher should notice a zipf slope of =-1.000764.

---
Tags: code-golf
---


title: Make big rocks into small rocks

text:
# Question
Title: Make big rocks into small rocks
Welcome to the grinder.

Your task is to make big rocks into small rocks by grinding them.

Take an input of a big rock of size `n > 3`  and grind it.

Continue to grind the rocks by dumping them into the grinder until the size of all the rocks are `2`.

rocks are always grinded into equal even halves. If the result of a grinding is odd take result - 1.

Print the output of each grinding as you proceed.

### Examples

input: `5`

output: `22`

The result are two rocks of size 2

input: `50`

output:

```
2424 //two rocks of size 24
12121212 //four rocks of size 12
66666666 //8 rocks of size 6
2222222222222222

```

the result is 16 rocks of size 2

input: `30`

output:

```
1414
6666
22222222

```

the result is 8 rocks of size 2

This is so the shortest code wins! Have fun and good luck!

# Answer
# TSQL, ~~61~~ 59 bytes

```
DECLARE @ int=50

,@x int=1WHILE @>2SELECT @=@/4*2,@x*=2PRINT replicate(@,@x)

```

**Try it out**
> 12 votes

# Answer
# COW, ~~297~~ 291 bytes

```
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOmoOMoOmoOmoOoommOoMoOMOOmoOMMMmoOMMMmoOOOOMoOmOoMOOMOomoOmoO
MOOMOomOoMOomoOmoomOoMMMOOOMoOmoOMMMmOomOomoomoOmoOMOOMOomOomOomOoMOomoOmoOmoOmoomOomOomOo
mOomOoMMMmoOMMMMOOMOomoOOOMmOomOoMoOmoOmoomOomOoMoomoOmoOmoOMOOMOoMOomoOMoOmOomoomoOMMMOOO
mOoMMMMMMmOoMMMMOomoo

```

Try it online!

The code prints each number on its own line, and separates iterations with an additional newline. It also prints the first iteration by itself, followed by a newline. So an input of 5 would give an output that looks like `5 2 2`  except with newlines instead of spaces. Sample output for `50` is given below.

Explanation tree:

```
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOmoOMoOmoOmoOoom ;Store 10 in [0], 1 in [1], and integer input in [3]
mOoMoO                                        ;Store 1 in [2]
MOO                                           ;Loop while [2] is non-zero
   moOMMMmoOMMMmoOOOOMoOmOo                   ;   Copy [3] to [4], clear contents of [5], and store 1 in [5]
   MOO                                        ;   Loop while [4] is non-zero
      MOomoOmoO                               ;      Decrement 4 and move to 6
      MOO                                     ;      Loop while [6] is non-zero
         MOomOoMOomoO                         ;         Decrement [5] and [6]
      moo                                     ;      End loop once [6] is empty
      mOoMMMOOOMoOmoOMMMmOomOo                ;      Copy [5] to [6], and reset [5] to 1, then move back to [4]
   moo                                        ;   End loop now that [4] is empty.  [6] now contains the parity of [3]
   moOmoO                                     ;   Navigate to [6]
   MOO                                        ;   Loop while [6] is non-empty
      MOomOomOomOoMOomoOmoOmoO                ;      Decrememnt [3] and [6]
   moo                                        ;   End loop now that [6] is empty.  [3] now contains the largest even number less than the previous iteration.
   mOomOomOomOomOoMMMmoOMMM                   ;   Copy [1] to [2]
   MOO                                        ;   Loop while [2] is non-empty
      MOomoOOOMmOomOoMoOmoO                   ;      Decrement [2], increment [1], and print the number in [3].
   moo                                        ;   End loop now that [2] is empty
   mOomOoMoo                                  ;   Print a new line
   moOmoOmoO                                  ;   Navigate to [3]
   MOO                                        ;   Loop while [3] is non-empty
      MOoMOomoOMoOmOo                         ;      Decrement [3] twice and increment [4] once
   moo                                        ;   [4] now contains half of [3]
   moOMMMOOOmOoMMM                            ;   Copy [4] to [3] and clear [4]
   MMMmOoMMMMOo                               ;   Copy [3] to [2] and decrement once
moo                                           ;End loop now that [2] is empty

```

Sample output for input 50:

```
50

24
24

12
12
12
12

6
6
6
6
6
6
6
6

2
2
2
2
2
2
2
2
2
2
2
2
2
2
2
2

```
> 8 votes

# Answer
# 05AB1E, ~~12~~ 11 bytes

```
¸[4÷·€D=¬<#

```

Try it online!

**Explanation**

```
¸             # wrap input in a list
 [            # start infinite loop
  4÷          # elementwise integer divison by 4
    ·         # elementwise multiplication by 2
     €D       # duplicate each element in the list
       =      # print it
        ¬     # get the first element of the list
         <    # decrease it by 1
          #   # if true: exit loop

```
> 7 votes

# Answer
## Python 2, ~~55~~ 53 bytes

```
n=input()
while n[0]>2:n=len(n)*2*[n[0]/4<<1];print n

```

Divide by 4 and left shift by 1 to get the special division
> 6 votes

# Answer
# Haskell, ~~75 71 60 50~~ 47 bytes

```
f 0=[]
f n|x<-f$2*div n 4=show n:zipWith(++)x x

```

Try it online! Edit: As the output is now allowed to be a list including the input, ~~10~~ 13 bytes can be saved.

Usage:

```
Prelude> f 50
["50","2424","12121212","66666666","2222222222222222"]

```

---

**Original 60 byte version:**

```
2%x=""
n%x|z<-2*div n 4=([1..x]>>show z)++"\n"++z%(x*2)
(%2)

```

Try it online! Thanks to Christian Sievers for pointing out the shorter formula.

Usage:

```
Prelude> (%2)50
"2424\n12121212\n66666666\n2222222222222222\n"

```
> 4 votes

# Answer
## Python 2, ~~48~~ 47 bytes

```
s=input()
n=1
while s>3:s=s/4*2;n*=2;print`s`*n

```
> 3 votes

# Answer
# JavaScript (ES6) ~~64~~ ~~59~~ 57 Bytes

```
f=s=>{for(n=1;s>2;)console.log(`${s=s/4<<1}`.repeat(n*=2))}

console.log(f.toString().length);
f(5);
f(50);
f(30);
```
> 3 votes

# Answer
# C#, 88 86 83 bytes

*Saved 3 bytes thanks to Skorm*

*Saved another byte by changing the `while` to a `for` loop which includes variable declarations*

*Saved 1 bytes thanks to Yodle*

```
n=>{var r="";for(int i,c=2;n>2;c*=2,r+="\n")for(i=0,n=n/4*2;i++<c;)r+=n;return r;};

```

Anonymous function which returns a string composed of the result of each grinding.

Full program with ungolfed method and test cases \[before the last edit!\]:

```
using System;

public class Program
{
    public static void Main()
    {
        Func<int, string> f =
        n =>
        {
            var r = "";
            for (int i, c = 1; n > 2; )  // iterator and counter variable
            {
                    n = n/4 * 2;    // make sure the result if even
                    c *= 2;         // keep track of the number of rocks
                    for (i = 0; i++ < c; )  // store the current line made of [c] rocks of size [n]
                        r += n;
                    r += "\n";      // add a trailing newline to the string resulted from this step
            }
            return r;       // return the entire history
        };

        //test cases:
        Console.WriteLine(f(5));
        Console.WriteLine(f(50));
        Console.WriteLine(f(30));
    }
}

```
> 3 votes

# Answer
# Java, 85 bytes

```
n->{String s="";for(int q=2,i;n>2;q*=2,s+="\n")for(i=q,n=n/4*2;i-->0;)s+=n;return s;}

```

## Testing and ungolfed

```
import java.util.function.*;

class Ideone {
  public static void main(String[] args) throws java.lang.Exception {
    Function<Integer, String> f = number -> {
      String result = "";
      for (int quantity = 2, i; number > 2; quantity *= 2) {
        number = number / 4 * 2; // Make sure that the next is half or half - 1 if odd
        for (i = quantity; i > 0; i--) { // copy "quantity" times.
          result += number;
        }
        result += "\n"; // append new line
      }
      return result;
    };
    System.out.println(f.apply(50));
  }
}

```

Note: I don't know why, Ideone keeps giving internal error, so testing on it is a problem. To test, just copy/paste and run in your standard Java IDE. (It works there, I made sure of it ;) )
> 3 votes

# Answer
## CJam, 21 bytes

```
l~]{{2/-2&_}%_n_2-}g;

```

Try it online! (As a test suite.)

### Explanation

```
l~]      e# Read input, evaluate and wrap it in a singleton list.
{        e# Do while...
  {      e#   Map this block over the list of rocks.
    2/   e#   Halve the rock.
    -2&  e#   Bitwise AND with -2, clearing the least-significant bit and
         e#   rounding down to an even integer.
    _    e#   Duplicate.
  }%
  _n     e# Print a copy of the current list of rocks.
  _2-    e# Continue if the current list of rocks contains values that aren't 2.
}g
;        e# Discard the final result to prevent printing it again.

```
> 2 votes

# Answer
# Jelly, ~~13 12~~ 11 bytes

```
:4Ḥx2µȦÐ¿ṖY

```

**TryItOnline!**

Note: the OP stated that the input may also be in the output.

### How?

```
:4Ḥx2µȦÐ¿ṖY - Main link: rockSize
     µ      - monadic separation
       Ð¿   - loop collect intermediate results while
      Ȧ     - any
:4          -     integer division (vectorises) by 4
  Ḥ         -     double (vectorises)
   x2       -     repeat the elements 2 times
         Ṗ  - pop (remove the trailing list of zeros)
          Y - join with line feeds

```

Version without the input displayed for 12 bytes: `:4Ḥḟ0x2µÐĿḊG`
> 2 votes

# Answer
## Pyth, ~~18~~ ~~16~~ 13 bytes

```
WhQ=Q*2my/d4\n

```

<sup>* `\n` is a new line</sup>
Explanation :

```
W              # While
 hQ            # first element of Q - 0 is falsy
   =Q          # assign to Q
     *2        # the double of the (list) that is returned
       m       # form this \/ map
         /d4   # divide every element by 4
        y      # and double
            \n # print Q

```

Try here
> 2 votes

# Answer
# PHP, ~~72~~ ~~67~~ 64 bytes

```
for($n=$argv[$k=1];$n>2;)echo str_repeat($n=$n/2&~1,$k*=2),"\n";

```

Takes argument from command line. Run with `-r`.
> 2 votes

# Answer
# MATL, 13 bytes

```
`K/kEthttH>]x

```

Try it online!

```
`       % Do...while
  K/k   %   Divide by 4 and round down. Takes input implicitly in the first iteration
  E     %   Multiply by 2
  th    %   Attach a copy of itself (creates a longer array)
  t     %   Duplicate. This copy will be used for further grinding, keeping the original
  tH>   %   Duplicate. True if the values exceed 2. Used as loop condition
]       % End. The loop exits if the latest array contains 2
x       % Delete last copy. Implicitly display the entire stack

```
> 2 votes

# Answer
# Perl, ~~40~~ ~~35~~ 30 + 1 = 31 bytes

Run with the `-n` flag

-4 bytes thanks to @Dada

```
say$_ x($.*=2)while$_=$_>>1&~1

```

Try it online!

Perl automatically reads the input into the variable `$_` when `-n` is set. `$.` is a special variable set to `1` at the beginning of the program by the interpreter, so I can use it as a base for doubling. Every iteration of the `while` loop, it bit-shifts `$_` down and performs a logical AND against the negative of itself minus one to cancel out the ones bit.
> 2 votes

# Answer
# PowerShell 3+, ~~58~~ 54 bytes

```
for($s=$input;$s;$s=($s-shr2)*2){"$s"*(2-shl($i++)-1)}

```

Thanks TimmyD for saving me 4 bytes!

### Slightly Ungolfed (formatting)

```
for ( $s = $input ; $s ; $s = ( $s -shr 2 ) * 2 ) {
    "$s" * (2 -shl ($i++)-1)
}

```

### Explanation

I'm using the same divide by 4 multiply by 2 trick as a lot of the other answers, but I ran into a problem. PowerShell converts numbers to floating point if needed during division, and for golfing that's annoying because `$v/4*2` becomes something unsighlty like `[int]($v/4)*2`. I got around that using bitshifting for the division with `-shr`.

For calculating how many times to print an iteration I just take `(2^$i)-1` which works nicely and has the added effect of leaving out the input value. Trying to just multiply by 2 was problematic because starting from 0 makes it hard to increase the value with just `$i*=2` and starting from 1 requires too much correction to get the number right.

Since PowerShell doesn't have an operator for it, and I wanted to avoid `[Math]::Pow()`, I relied on bitshifting again for my powers of 2.
> 2 votes

# Answer
# Python 2, 47 Bytes

Since the OP said that a 1D array which included the input was fine I have come up with this recursive function, which unfortunately only ties with the current Python winner.

```
f=lambda s,n=1:[s]*n+(f(s/4*2,n*2)if s>3else[])

```
> 1 votes

# Answer
# Vim ~~61~~ 54 bytes

```
qqYpPJ0yw:s;\d*;="/2
;g
:let @t=(">7)+1
@tkjjG@qq@q

```

TryItOnline!

Unprintables:

```
qqYpPJ0yw:s;\d*;^R=^R"/2
;g
:let @t=(^R">7)+1
@tkjjG@qq@q

```

Luckily vim automatically truncates on x/2.
> 1 votes

# Answer
# Perl, 47 bytes

```
$a=<>>>1;say 2*(($a>>=1)||die)x(1<<$_)for 1..$a

```

No command-line options, this time (unusually for Perl). The basic idea is that as all the rocks at any given step are the same size, we just record the size (in `$a`) and the number (in `$_`), rather than recording the whole list. I couldn't find a way to get rid of the space (or `+`) after `say` ; you can move the `2*` but it won't parse correctly if it's followed by an opening parenthesis.

I can't help but shake the feeling that this is improvable, but I can't see how.
> 1 votes

# Answer
# JavaScript, ~~71~~ ~~63~~ ~~59~~ 58 Bytes

Well, I came up with this javascript solution. Totally new at golfing, but I foudn this a fun challenge

Saved 4 bytes thanks to Titus suggestion using a for loop.

ungolfed basis:

```
for(o = i = 30; i > 1; i= i/4<<1) {
   console.log(`${i}`.repeat(o / i));
}
```

Golfed version

```
for(o=i=30;i>1;i=i/4<<1){console.log(`${i}`.repeat(o/i));}

```

I'm open for suggestions how to improve it / learn golfing

input tester

```
function test(a){
var el = document.getElementById('output');
var text = [];
for(o = i = parseInt(a); i > 1; i= i/4<<1) {
   text.push(`${i}`.repeat(o / i));
}
  el.innerText = text.join('\n');
}
```

```
<input type="input" onchange="test(this.value)"><button>run</button>
<pre id="output">
</pre>
```
> 1 votes

# Answer
# BASH, 81 bytes

```
n=$1
h=1
while [ ${n//2} ];do
printf -v s %$[h=h*2]s
echo ${s// /$[n=n/4*2]}
done

```
> 1 votes

# Answer
# Swift, 84 Bytes

```
func g(n:Int){var n=n,i=2;while n>2{n=n/4*2;print(Array(repeating:n,count:i));i*=2}}

```

---

**Ungolfed**

```
func grind(rockSize: Int) {
    var rockSize = rockSize
    var rockCount = 1

    while rockSize > 2 {
        rockSize = rockSize / 4 * 2
        rockCount *= 2

        let output = Array(repeating: rockSize, count: rockCount)
        print(output)
    }
}

```
> 1 votes

# Answer
# Befunge, 45 bytes

```
&1vg0_\:.\v
:\<  ^!:-1<p00:*2\.:*2/4,+55_@#`2

```

Try it online!

**Explanation**

```
&           read the rock size
1           initialise the count
<           start of main loop going right to left

  \         swap the size to the top of the stack
  :2`#@_    if size is not > 2 then exit
  55+,      output a line break
  4/2*      size = size/4*2, i.e. split into even halves
  :.        output the size
  \         swap the count to the top of the stack
  2*        count = count*2
  :00p      save count for later

  <         start of inner loop
    1-      decrement the count
    :!^_    break out of the loop if the count is zero
    \       swap the size to the top of the stack
    :.      output the size
    \       swap the count to the top of the stack
    v       back to the start of the inner loop

  0g        restore the saved count
  v         back to the start of the main loop

```
> 1 votes

# Answer
# Javascript, 106 bytes

First code golf, thought I'd have a go. (It's not very good).

```
for(;i[i.length-1]>3;){for(var x=0;x<i.length;x++)i[x]/=2,i[x]%2===1&&i[x]--;i=i.concat(i),console.log(i)}

```

Unminified:

```
while (input[input.length - 1] > 3) {
    for (var x = 0; x < input.length; x++) {
        input[x] /= 2;
        if (input[x] % 2 === 1) input[x]--;
    }
    input = input.concat(input);
    console.log(input);
}

```
> 1 votes

---
Tags: code-golf, math, arithmetic
---


# Question
Title: Create an application that restarts itself after n-seconds once
In your favorite programming language, create an application that restarts itself once, after n seconds.

You need to find a way to restart after exiting the program. EG: run cmd to do it for you. Make sure it waits an amount of seconds specified by the user before restarting

For clarification: You can run a second program, or compile one at runtime to do the work for you.

Also, make sure the program works every time you execute it, not only once.

Example of algorithm:

```
If hasntrestartedalready
    read i
    exit
    wait(i)
    restart
end if

```

Least amount of bytes wins.

# Answer
# Batch, ~~34~~ 28 bytes

```
timeout/t %1
if %1 neq [] %0

```

Input time in seconds as the first argument. If no argument is present, as well as after restarting, it spews out error messages (follow both commands with `2>NUL` to get rid of them). The new instance opens in the same window (OP said it's allowed).
> 3 votes

# Answer
# bash + at, 29 bytes

```
at now+$[$1/60]min<<<bash\ $0

```

# zsh + at, 28 bytes

```
at now+$[$1/60]min<<<zsh\ $0

```

# bash + at or zsh + at, 23 bytes, arguably cheating

```
at now+$[$1/60]min<<<$0

```

The first version re-executes the program after the number of seconds given as a command-line argument (which must be a multiple of 60 because `at` has only minute granularity). `at` is a standard POSIX program for scheduling programs to be run in the future. The 29-byte and 28-byte programs each rerun the program with the shell it's designed for. The 23-byte program doesn't specify a shell, and thus may well accidentally rerun it with `sh`, which is likely to be unable to parse it; it's up to you whether you consider it reasonable for the restart to happen in the wrong language or not, so I presented both versions.

The time to wait is taken as a command-line argument. This means that the argument won't be present in the rerun, and thus the rerun will exit (with an error message due to the malformed expression, but which will be hidden by `at`; on some systems, it might be sent to you by email, but mine doesn't have that set up) rather than keep rerunning indefinitely.

`bash` considers the `$[]` syntax for arithmetic obsolete, but it still works and is shorter than the "official" syntax. `zsh` is fine with it, as far as I could tell from the documentation.
> 2 votes

---
Tags: code-golf
---