title: The greedy regex (cops)

text:
# Question
Title: The greedy regex (cops)
*This is the cops' post. The robbers' is here.*

You make a program and a regex.

For most inputs, one of the following happens:

* the regex doesn't match, and the program returns a falsey value
* the regex doesn't match, and the program returns a truthy value
* the regex matches, and the program returns a truthy value

But for one (or more) input, the regex matches, but the program returns a falsy value.

You should try to keep this input hidden. Robbers will try to find an input where the regex matches, but the program returns a falsy value.

Post your program and your regex, as well as your language name, byte count of the program, regex flavor, and byte count of the regex.

If a robber finds an input where the regex matches, but the program returns a falsy value, even if it wasn't the intended input your program is considered cracked, and you edit in a link to the robber's crack.

If nobody has cracked your program & regex after a week, then edit in that your submission is safe and is therefore not eligible for cracking. Also edit in the intended input. The shortest (program bytes + regex bytes) non-cracked submission wins.

## Example

Let's say your regex is (all of the flavors):

```
/^[0-9]$/

```

And your program is (JS):

```
x=>Boolean(parseInt(x))

```

Then a valid crack would be `0`, because the regex matches `0` but `0` is falsey.

Delimiters don't count in the byte count.

**I can't enforce the banning of hash functions with rules, but please don't use SHA/RSA or anything that is unfair to the robbers**

# Answer
# Python, cracked

Regex: `(?!.)`

Program: `from operator import not_`

This is a little easier than my previous one.
> 2 votes

# Answer
# JavaScript (Cracked)

Regex: `..`
Program: `a=>[...a].length-1`

This is an easy one.

---

**Intended solution**

>
> 2 votes

# Answer
# JavaScript ES6, 12 bytes + 3 bytes

Regex: `...`

Code: `a=>a+1<a-1+2`
> 1 votes

# Answer
# Python 3, cracked by ovs

Regex: `.`

Program: `lambda a:len(a.lower()) == 1`

This ~~shouldn't be~~ wasn't too hard.
> 0 votes

# Answer
# Pyth

Regex: `.*`

Program: `!qC%.hz^TT"U|(¡`

Try it online!

Simple hash function, shouldn't be allowed, but it is. I could've made it much stronger, but I tried to optimize for byte count.
> 0 votes

# Answer
# Java (OpenJDK 9), 198 bytes, (Cracked)

```
public static boolean isProgramValid(String n) {
    try{
        Class.forName(n);
    } catch(Exception e){
       return false;
    }
    return true;
}

public static String regex = "^(?is)([a-z]+\\.){4}.*$";

```

Should be an easy one.

Try it online!
> -1 votes

---
Tags: code-golf, string, cops-and-robbers, regular-expression, obfuscation
---


title: Separate alphabets and numbers

text:
# Question
Title: Separate alphabets and numbers
A paragraph of text has numbers and alphabetic letters mixed. Your task is to separate the numbers to the left side and the alphabetic letters to the right side in the same order of each line.

Rules:

1. Numbers are plain integers; so no decimal point, and no negative/positive signs.
2. Numbers may or may not be contiguous, but whatever the case may be, they have to be pushed to left side in the same order.
3. Numbers may occur in between words.
4. The text contains only ASCII alphabetic letters and numbers, along with spaces, underscores, commas and dots.
5. The one who does this with minimum keystrokes (like vim macros) or least amount of bytes in case of scripting is the winner.

Example Text:

```
A word can have any number of text like 433884,
but all the numb89ers has to be moved left side
but alph6abetical va9lues has to be pas46ted on right side.
The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
meaningless1 words co43mbined togeth81er.

```

Expected output:

```
433884A word can have any number of text like ,
89but all the numbers has to be moved left side
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
14381meaningless words combined together.

```

# Answer
## Retina, 14 bytes

```
O%$`\d|(.)
$#1

```

Try it online!

### Explanation

`O` introduces a sorting stage. `%` tells Retina to apply the transformation to each line separately. `$` tells it to sort the matches by the result of the specified substitution.

The regex itself is `\d|(.)` which either matches a digit, or anything else which is captured into group `1`. This is substituted with `$#1` which is the number of captures of group `1`. That is, the sorting key for digits is `0` and the sorting key for everything else is `1`. Since sorting in Retina is stable, this simply moves digits to the left and everything else to the right.
> 11 votes

# Answer
## 05AB1E, ~~14~~ 10 bytes

**Code:**

```
|vyþyyþ-¶J

```

**Explanation:**

```
|                 # push all lines in input as array of strings
 v                # for each line in array
  yþ              # push only digits from line
    yyþ-          # push line without digits
        ¶         # push newline char
         J        # join as string
                  # end loop and print explicitly

```

**Example Input:**

> A word can have any number of text like 433884,
> but all the numb89ers has to be moved left side
> but alph6abetical va9lues has to be pas46ted on right side.
> The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
> meaningless words co43mbined togeth81er.

**Example Output:**

> 433884A word can have any number of text like ,
> 89but all the numbers has to be moved left side
> 6946but alphabetical values has to be pasted on right side.
> 4292The text might contain characters shuffled like hlep or dfeintino or even
> 4381meaningless words combined together.

Try it online
> 9 votes

# Answer
# Python 3, 64 bytes

Three equivalent solutions! I can’t pick.

```
while 1:print(*sorted(input(),key=lambda x:-x.isdigit()),sep='')
while 1:print(*sorted(input(),key=lambda x:x<'0'or'9'<x),sep='')
while 1:print(*sorted(input(),key=str.isdigit,reverse=1),sep='')

```
> 8 votes

# Answer
## Perl, 17 bytes

**16 bytes code + 1 switch**

```
s/\d/!print$&/ge

```

Requires `-p`.

### Usage

```
perl -pe 's/\d/!print$&/ge' <<< 'a1b2c3d4e5f6'
123456abcdef

```

---

Alternatively:

```
print/\d/g,/\D/g

```

Requires `-n`.

### Usage

```
perl -ne 'print/\d/g,/\D/g' <<< 'a1b2c3d4e5f6'
123456abcdef

```
> 5 votes

# Answer
## Hoon, ~~92~~ 83 bytes

```
|*
*
(turn (lore +<) |=(@ `tape`(welp (skid (trip +<) |=(@ !=(~ (rush +< nud)))))))

```

`++lore` splits a multi-line cord into a `(list cord)`, `(trip +<)` turns it into a tape. `++skid` seperates a list in two: one side where the function returns yes, one side where it returns no. Our function tries to parse the character with `++nud` (numeric) and checks if it parses fully, and then we weld the two lists back together into a tape.

```
> %.
  '''
  A word can have any number of text like 433884,
  but all the numb89ers has to be moved left side
  but alph6abetical va9lues has to be pas46ted on right side.
  The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
  meaningless1 words co43mbined togeth81er.
  '''
  |*
  *
  (turn (lore +<) |=(@ `tape`(welp (skid (trip +<) |=(@ !=(~ (rush +< nud)))))))
<<
  "433884A word can have any number of text like ,"
  "89but all the numbers has to be moved left side "
  "6946but alphabetical values has to be pasted on right side."
  "4292The text might contain characters shuffled like hlep or dfeintino or even"
  "14381meaningless words combined together."
>>

```
> 5 votes

# Answer
# MATL, ~~13~~ 12 bytes

```
`jt4Y2m&)hDT

```

Exits with an error (allowed by default), producing the correct output.

**Try it online!**

### Explanation

```
`          T    % infinite loop
 j              % input one line as a string
  t             % duplicate
   4Y2          % predefined literal: '0123456789'
      m         % true for elements of string that are digits, false for the rest
       &)       % two-output indexing: push digits, then non-digits
         h      % concatenate the two strings
          D     % display

```
> 4 votes

# Answer
# V, 12 bytes

```
òí¨Ä©¨ä©/²±

```

V, is an unfinished, 2D string based golfing language. Although it is unfinished, this program works as of commit 45, which was published last night, making this a competing answer. (Most of my previous V answers were non-competing.)

Note, the trailing newline is necessary, although this is due to a bug.

Try it online!

Explanation:

```
ò            #Recursively, do:
 í           #Substitute on every line
  ¨Ä©¨ä©/²±  #The following regex.

```

`¨Ä©¨ä©/²±` expands into the vim regex:

```
:%s/\(\D\)\(\d\)/\2\1

```

which is a non-digit `(\D)` followed by a digit `(\d)`, and swap them.

Since this is filled with gross unicode characters, here is a reversible hexdump:

```
00000000: f2ed a8c4 a9a8 e4a9 2fb2 b10a            ......../...

```
> 4 votes

# Answer
# CJam, ~~9~~ ~~13~~ 16 bytes

```
qN/{{A,s-,}$}%N*

```

There isn't `f$`...

This 13 bytes version nearly works:

```
{l{A,s-,}$N}h

```
> 3 votes

# Answer
## Pyth, ~~16~~ 15 bytes

1 byte thanks to @FryAmTheEggman.

```
jms+@J`MTd-dJ.z

```

Try it online!

Sample input:

```
A word can have any number of text like 433884,
but all the numb89ers has to be moved left side
but alph6abetical va9lues has to be pas46ted on right side.
The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
meaningless1 words co43mbined togeth81er.

```

Sample output:

```
433884A word can have any number of text like ,
89but all the numbers has to be moved left side
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
14381meaningless words combined together.

```

## How it works

```
jms+@J`MTd-dJ.z

 m           .z    for each line (d):
         d           yield d (the line)
     J                 assign J to
        T              [0,1,2,3,...,9]
      `M               with each number converted to string
    @                intersect with J
   +                 append:
          -dJ          filter d for characters not in J
  s                  convert to one string
j                  join by newline

```
> 3 votes

# Answer
# Javascript ES6, 40 bytes

`a=>a.replace(/\D/g,'')+a.replace(/\d/g,'')`

Tried several other solutions, but couldn't get it smaller than this.
My first try was `a=>[...a.match(/\d/g),...a.match(/\D/g)].join``` but that's 5 bytes longer

Try it here

```
f=
a=>a.replace(/\D/g,'')+a.replace(/\d/g,'')

a.innerHTML='
'+
  ['A word can have any number of text like 433884,',
 'but all the numb89ers has to be moved left side',
 'but alph6abetical va9lues has to be pas46ted on right side.',
 'The text might con4tain chara29cters s2huffled like hlep or dfeintino or even',
 'meaningless words co43mbined togeth81er.'].map(b=>f(b)).join('
')+'
'
```

```

```
> 3 votes

# Answer
## PowerShell v2+, 55 bytes

```
$args[0]-split"`n"|%{($_-replace'\D')+($_-replace'\d')}

```

Due to the need to support multi-line input, we have to encapsulate our `-replace` statements with a loop and `-split` on newlines. Otherwise basically equivalent to the JavaScript solution.
> 3 votes

# Answer
# Pyth - 11 bytes

Don't like my grouping test. Takes input as list of lines, tell me if that's not ok.

```
jms_.g}k`MT

```

Try it online here.
> 3 votes

# Answer
# Retina, 16 bytes

Stable bubble sort.

```
%+`(\D)(\d)
$2$1

```

Sample input:

```
A word can have any number of text like 433884,
but all the numb89ers has to be moved left side
but alph6abetical va9lues has to be pas46ted on right side.
The text might con4tain chara29cters s2huffled like hlep or dfeintino or even
meaningless1 words co43mbined togeth81er.

```

Sample output:

```
433884A word can have any number of text like ,
89but all the numbers has to be moved left side
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
14381meaningless words combined together.

```

Try it online!
> 2 votes

# Answer
# Java 8, ~~130~~ ~~126~~ 86 bytes

```
a->{for(String s:a)System.out.println(s.replaceAll("\\D","")+s.replaceAll("\\d",""));}

```

-4 bytes converting Java 7 to 8 and removing an unused character
-40 bytes converting program to function and changing `[^\\d]` to `\\D`

**Explanation:**

Try it here.

```
a->{                             // Method with String-array parameter and no return-type
  for(String s:a)                //  Loop over the array
    System.out.println(          //   Print with a trailing new-line:
      s.replaceAll("\\D","")     //    All digits,
      +s.replaceAll("\\d",""));  //    plus all non-digits

```
> 2 votes

# Answer
## C#, 59 bytes

```
I=>Regex.Replace(I,"[^0-9]","")+Regex.Replace(I,@"\d+","");

```

A simple C# lambda function using regex.

## Sample output

```
433884A word can have any number of text like ,
89but all the numbers has to be moved left side
6946but alphabetical values has to be pasted on right side.
4292The text might contain characters shuffled like hlep or dfeintino or even
14381meaningless words combined together.

```
> 2 votes

# Answer
# GNU Sed, 28

Score includes +1 for `-r` option to sed.

```
:
s/([^0-9])([0-9])/\2\1/
t

```

Repeatedly switches one non-number character followed by one number character until no more substitutions are made.

Sadly sed regexes don't have `\d` or `\D`, so these have to be written out longhand.

Ideone.
> 2 votes

# Answer
# C# (LINQ), 110 bytes

```
s=>string.join("",s.Where(c=>"0123456789".Contains(c).Concat(s.SelectMany(c=>new[]{c}.Except("0123456789"))));

```

Not the shortest solution, by far, but I thought this would be a good use of LINQ.
> 2 votes

# Answer
# Factor 61

```
[ "\n"split [ [ digit? ] partition [ write ] bi@ nl ] each ]

```

It's a naive approach.

`"\n"split` splits the string on top of the stack into lines. Then, for `each` line:

1. `[ digit? ] partition` splits each line into digits-only and non-digits-only
2. `[ write ] bi@` outputs both, and `nl` prints a newline.

PS:

**As a word 90 bytes** (71 if you replace the-factorish-long-name with 1 letter):

```
: numbers-to-the-front ( s -- ) "\n"split [ [ digit? ] partition [ write ] bi@ nl ] each ;

```
> 2 votes

# Answer
# Pyth, 14 bytes

```
FG.zo_:N"\d"0G

```

Try it online!

Explanation:

```
FG             : For every G in ...
  .z           : the-list-where-lines-of-input-are-stored ...
               : (implicitly print)
    o        G : sorted G ...
     _N        : where, a negative key is given ...
       :"\d"0  : to the individual character if it is a digit

```

The logic of the solution is the same as in Lynn's answer.
> 2 votes

# Answer
# Octave, ~~37~~ 32 bytes

```
@(s)disp([s(x=s>47&s<58),s(~x)])

ans('The text might con4tain chara29cters s2huffled like hlep or dfeintino or even')
4292The text might contain characters shuffled like hlep or dfeintino or even

```
> 1 votes

# Answer
## Clojure, 113 bytes

```
(fn[s](map(fn[x](println(apply str(sort-by #(when-not(Character/isDigit %)1)x))))(clojure.string/split-lines s)))

```

Sorts digits to the beginning of the line.
> 1 votes

# Answer
# Oracle SQL 11.2, 131 bytes

The lines in the input string are separated by '¤'. That way it is not necessary to create a table to use as the input.

```
A word can have any number of text like 433884,¤but all the numb89ers has to be moved left side ¤but alph6abetical va9lues has to be pas46ted on right side.¤The text might con4tain chara29cters s2huffled like hlep or dfeintino or even¤meaningless1 words co43mbined togeth81er.

```

Query :

```
SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^0-9]')||REGEXP_REPLACE(COLUMN_VALUE,'[0-9]')FROM XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"'));

```

Un-golfed

```
SELECT REGEXP_REPLACE(COLUMN_VALUE,'[^0-9]')||  -- Every number
       REGEXP_REPLACE(COLUMN_VALUE,'[0-9]')     -- Every character not a number
FROM   XMLTABLE(('"'||REPLACE(:1,'¤','","')||'"'))  -- Split on ¤

```
> 1 votes

# Answer
## APL, 28 chars

```
{⍵[⍋(~⍵∊⎕D)++\¯1⌽⍵=⎕UCS 13]}

```
> 1 votes

# Answer
# Haskell, 60 bytes

```
import Data.List;g(n,l)=n++l;f=g.partition(`elem`['0'..'9'])

```

### Usage

```
f "A word can have any number of text like 433884,"

```
> 1 votes

# Answer
# Sed, 35 bytes

```
h
s/[0-9]//g
x
s/[^0-9]//g
G
s/\n//

```

This makes a copy of the line, removes digits from one copy and letters from the other, before recombining them.
> 1 votes

# Answer
# Bash, 42 bytes

```
read a&&echo "${a//[^0-9]}${a//[0-9]}"&&$0

```

Be warned that this recursive implementation forks a new process for each line of input!
> 1 votes

# Answer
# Japt v2, ~~14~~ 12 bytes

*-2 bytes thanks to ETHproductions*

```
®o\d +Zr\d}R

```

Run it
> 1 votes

# Answer
# Julia 0.6, 77 bytes

```
x->(l=r="";for c=x
c=='\n'?(println(l*r);l=r=""):'/'<c<':'?(l*=c):(r*=c)
end)

```

Anonymous function taking a string and printing output. Loops over characters, adding them to the left `l` or right `r` buffers until it finds a newline, then it prints and empties buffers. Lots of potential useful constructs like `sort`, `filter` and logical indexing (indexing with an array of boolean values) don't work on Strings.

Try it online!
> 0 votes

# Answer
# Vim, 30 keystrokes

```
qr:%s/\v(\D+)(\d+)/\2\1/<Enter>@rq@r

```

Record a search and replace action that moves digits to the left of non-digits. Call the macro recursively until an exception is thrown by the pattern not being found (when there are no more digits to the right of any non-digits).
> 0 votes

# Answer
# C (gcc), 106 bytes

```
g(s,x)char*s;{for(;*s;s++)isdigit(*s)^x&&putchar(*s);}f(s,n)char**s;{for(;n--;puts(""))g(*s,0),g(*s++,1);}

```

Try it online!
> 0 votes

# Answer
# Jelly, 10 bytes

```
Ỵðf;ḟµ€ØDY

```

Try it online!
> 0 votes

# Answer
# K4, 21 bytes

**Solution:**

```
{x(&a),&~a:x in .Q.n}

```

**Example:**

```
q)k){x(&a),&~a:x in .Q.n}"The text might con4tain chara29cters s2huffled like hlep or dfeintino or even"
"4292The text might contain characters shuffled like hlep or dfeintino or even"

```

**Explanation:**

```
{x(&a),&~a:x in .Q.n} / the solution
{                   } / lambda function, implicit arg x
                .Q.n  / list "0123456789"
           x in       / true/false for each character of x
         a:           / save as variable a
        ~             / negate (so non numerics)
       &              / indices where true
      ,               / joined with
  (&a)                / indices where true
 x                    / index into x at these indices

```

**Bonus:**

**23 byte** implementation in K (oK):

```
{x(&a),&~a:x in 48+!10}

```

Try it online!
> 0 votes

# Answer
# ReRegex, 25 bytes

```
([^\n\d])(\d)/$2$1/#input

```

Try it online!
> 0 votes

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


title: Orient the Rubik's Cube

text:
# Question
Title: Orient the Rubik's Cube
### Introduction:

I collect twisty puzzles, so I'm quite the fan of -challenges (even though most are fairly difficult). So, let's try a fairly easy -challenge for a change.

When an NxNxN Cube gets scrambled during a WCA (World Cubing Association) competition, the cube is always held in the same way before executing the scramble-algorithm:

> ## Article 4: Scrambling
>
> * 4d) Scrambling orientation:
>     + 4d1) **NxNxN puzzles** and Megaminx **are scrambled starting with the white face** (if not possible, then the lightest face) **on top and** the **green face** (if not possible, then the darkest adjacent face) **on the front**.

"*NxNxN puzzles are scrambled starting with the white face on top and the green face on the front.*"

### Challenge:

For the sake of this challenge we only have to look at the centers, so we'll use a 1x1x1 instead of a 3x3x3. Given a valid 1x1x1 Cube in any orientation, output which rotations of `x`/`x'`, `y`/`y'`, and/or `z`/`z'` are required to have green at the front and white at the top.

### Input:

The input will be a 1x1x1 Cube layout in the following format (where `F` is the front, and `U` is the top):

```
 U
LFRB
 D

```

For example:

```
 Y
BRGO
 W

```

### Output:

The output will be the least amount of rotations of `x`/`x'`, `y`/`y'`, and/or `z`/`z'` required to have the white center at the top and green center at the front.

```
         x                      y                      z

```

```
         x'                     y'                     z'

```

We basically always want to end up in this orientation:

```
 W
OGRB
 Y

```

The example given above would therefore result in either of these outputs: `x2y`/`xxy`/`x'x'y`.

NOTE: In the still image of the gifs above, White is the Upper face and Red is the Front face. So the still image of the gif is:

```
 W
GRBO
 Y

```

### Challenge rules:

* You are allowed to take the input in any reasonable format.
    + You could use other characters or numbers (i.e. `0-5`/`1-6`) instead of `WYROGB`
    + You can take the input as single String, as new-line delimiter single String, as String-array, character-array or -matrix, integer-array or -matrix, etc. Your call. (For example, `WOGRBY` is a valid input in the format `ULFRBD`.)
    + **Please specify what input-format you've used!**
* The output must use `xyz`, but instead of `x'` you are also allowed to use `x3` or `X`, or instead of `x2` you can also use `xx` (NOTE: You are NOT allowed to use `xxx` instead of `x'`/`x3`/`X`).
    + Always output the *least amount of rotations*. So although `x'x'y'y'y'` instead of `x2y` results in the same orientation of the Cube in the end, it's not a valid output because there is a better alternative. Same applies to `x2y2`, because `xy'z` is one move shorter (`x2`/`xx` counts as two moves).
    As thumb rule: every possible input results in 0-2 `x`, 0-2 `y` and/or 0-2 `z` rotations, and you'll never need more than three rotations in total (i.e. `x2z2``y2`)
* You can assume all inputs are valid 1x1x1 Cubes.
* If the input is already in the correct position (green front, white top), output nothing (or something indicating nothing, like `null`, `false`, `0`, an error, etc.)

### General rules:

* This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* Default Loopholes are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.

### Test cases:

```
Input:   Output (multiple valid answers are possible for some):

 Y
BRGO     x2y   y'x2   z2y'   yz2   zy'x   zxz   xzx   xyz
 W

 W
OGRB     nothing
 Y

 G
RWOY     y2x'   z2x   yzy   xy2   x'z2   yx'z   zxy   zyz
 B

 W
RBOG     y2
 Y

 R
BWGY     yz   zx   xy
 O

 G
WOYR     x'z   zy   yx'
 B

```

# Answer
# Jelly,  ~~47~~  43 bytes

To answer my own question, yes a straight hash is shorter, and not just a little!

```
“ḥɦƁþhƓWsFUḃṡIụA]OṆrṠ€5ⱮI’ṃ“XZyxzY ”Ḳɓ%⁽'Ṙị

```

A monadic link taking an integer with `WOGRBY` as `145362` and returning a list of characters using the **x**, **xx**, **X** format.

**Try it online!**

### How?

Uses the hash function found by Herman Lauenstein in their JavaScript answer -- go give credit!

```
“ḥɦƁþhƓWsFUḃṡIụA]OṆrṠ€5ⱮI’ṃ“XZyxzY ”Ḳɓ%⁽'Ṙị - Main link 1: integer, N
“ḥɦƁþhƓWsFUḃṡIụA]OṆrṠ€5ⱮI’                  - base 250 literal = 3078729180217463783054936423617578759678999380687706537574
                           “XZyxzY ”        - literal list of characters = "XZyxzY "
                          ṃ                 - base decompress = "X Zyx ZX z ZY zz x Y zx zy Zyy zzX xx zX y zY Z zzx  Zx zzy Zxx Zy yy"
                                            - (use the seven characters as digits 1,2,3,4,5,6,0)
                                    Ḳ       - split at spaces = ["X","Zyx","ZX","z","ZY","zz","x","Y","zx","zy","Zyy","zzX","xx","zX","y","zY","Z","zzx","","Zx","zzy","Zxx","Zy","yy"]
                                     ɓ      - new dyadic chain with swapped arguments
                                       ⁽'Ṙ  - 10955
                                      %     - modulo (N) by (10955)
                                          ị - index into (the move list)
                                            -   Note: Jelly indexing is 1-based & modular
                                            -         so a %24 is surplus to requirements

```
> 1 votes

# Answer
# JavaScript (ES6), 95 bytes

```
n=>'y2+X+Zyx+ZX+z+ZY+z2+x+Y+zx+zy+Zy2+z2X+x2+zX+y+zY+Z+z2x++Zx+z2Y+Zx2+Zy'.split`+`[n%10955%24]

```

This works similarly to @Arnauld's answer (credits to him for the idea), but inputs as a base-10 integer (with `123456` instead of `WYROGB`), which skips the base decoding.

## Hash function

```
Input  | mod 10955 | mod 24 | Output
-------+-----------+--------+-------
136452 |      4992 |      0 | "y2"
145362 |      2947 |     19 | ""
153642 |       272 |      8 | "Y"
164532 |       207 |     15 | "y"
235461 |      5406 |      6 | "z2"
246351 |      5341 |     13 | "x2"
254631 |      2666 |      2 | "Zyx"
263541 |       621 |     21 | "z2Y"
315264 |      8524 |      4 | "z"
326154 |      8459 |     11 | "Zy2"
352614 |      2054 |     14 | "zX"
361524 |         9 |      9 | "zx"
416253 |     10918 |     22 | "Zx2"
425163 |      8873 |     17 | "Z"
451623 |      2468 |     20 | "Zx"
462513 |      2403 |      3 | "ZX"
514236 |     10306 |     10 | "zy"
523146 |      8261 |      5 | "ZY"
531426 |      5586 |     18 | "z2x"
542316 |      5521 |      1 | "X"
613245 |     10720 |     16 | "zY"
624135 |     10655 |     23 | "Zy"
632415 |      7980 |     12 | "z2X"
641325 |      5935 |      7 | "x"

```

## Test Cases

```
f=n=>'y2+X+Zyx+ZX+z+ZY+z2+x+Y+zx+zy+Zy2+z2X+x2+zX+y+zY+Z+z2x++Zx+z2Y+Zx2+Zy'.split`+`[n%10955%24]
console.log(f(263541))
console.log(f(145362))
console.log(f(531426))
console.log(f(136452))
console.log(f(361524))
console.log(f(514236))
```
> 6 votes

# Answer
# JavaScript (ES6), 114 bytes

*Saved 15 bytes thanks to @ngn*

Picking the results from a lookup table turns out to be significantly shorter than my best attempt so far at golfing a solver.

Outputs **X**, **Y** and **Z** instead of **x'**, **y'**, **z'**.

```
s=>'X//Zy//Zyx/z2/zX/Zx2//z2Y/x/Zy2//x2/Zx/z2X/zY/z2x/ZY/z/y//ZX/zy/y2//zx/Z/Y/'.split`/`[parseInt(s+0,35)%405%31]

```

### Test cases

```
let f =

s=>'X//Zy//Zyx/z2/zX/Zx2//z2Y/x/Zy2//x2/Zx/z2X/zY/z2x/ZY/z/y//ZX/zy/y2//zx/Z/Y/'.split`/`[parseInt(s+0,35)%405%31]

console.log(f('YBRGOW')); // z2Y
console.log(f('WOGRBY')); // nothing
console.log(f('GRWOYB')); // z2x
console.log(f('WRBOGY')); // y2
console.log(f('RBWGYO')); // zx
console.log(f('GWOYRB')); // zy
```

### Solver

Here is the solver used to generate the moves stored in the lookup table.

```
s => {
  const rot = [ '215304', '023415', '152043' ];
  const S = [];

  // recursive function looking for all possible solutions of at most 6 clockwise moves
  const g = (s, m, r = 0) => {
    if(s == 'WOGRBY') {
      // this is a solution; replace 3 consecutive identical clockwise moves with a
      // single counterclockwise move; rewrite 2 consecutive identical moves as 'x2';
      // store the result in S[]
      S.push(m.replace(/(.)\1\1/g, s => s[0].toUpperCase()).replace(/(.)\1/g, '$12'));
    }
    else if(!m[5]) {
      // try the next rotation on the current cube
      if(r < 2) {
        g(s, m, r + 1);
      }
      // apply the current rotation and restart from there
      g([...rot[r]].reduce((r, i) => r + s[i], ''), m + 'xyz'[r]);
    }
  }

  // find all solutions
  g(s, '');
  // find the length of the shortest solution(s)
  const min = Math.min(...S.map(s => s.length));
  // return the 1st solution matching this length
  return S.find(s => s.length == min);
}

```

### Hash function

Below is a summary of the results provided by the hash function for all 24 valid inputs, along with the corresponding solutions.

```
 input    | base 35->10 | * 35        | mod 405 | mod 31 | output
----------+-------------+-------------+---------+--------+--------
 "WOGRBY" |  1717434494 | 60110207290 |     370 |     29 | ""
 "WBOGRY" |  1698256454 | 59438975890 |     175 |     20 | "y"
 "WRBOGY" |  1721718494 | 60260147290 |      55 |     24 | "y2"
 "WGRBOY" |  1705881974 | 59705869090 |     400 |     28 | "Y"
 "OGWBYR" |  1285921692 | 45007259220 |      45 |     14 | "Zx"
 "OYGWBR" |  1312271862 | 45929515170 |     120 |     27 | "Z"
 "OBYGWR" |  1278510372 | 44747863020 |     270 |     22 | "ZX"
 "OWBYGR" |  1309058862 | 45817060170 |     255 |      7 | "Zx2"
 "GRWOYB" |   882269476 | 30879431660 |     110 |     17 | "z2x"
 "GYRWOB" |   892568926 | 31239912410 |      80 |     18 | "ZY"
 "GOYRWB" |   877856956 | 30724993460 |     155 |      0 | "X"
 "GWOYRB" |   889441606 | 31130456210 |     395 |     23 | "zy"
 "RBWGYO" |  1435990314 | 50259660990 |     150 |     26 | "zx"
 "RYBWGO" |  1469623284 | 51436814940 |     135 |     11 | "Zy2"
 "RGYBWO" |  1443572994 | 50525054790 |     285 |      6 | "zX"
 "RWGYBO" |  1466838684 | 51339353940 |     360 |     19 | "z"
 "BYOWRG" |   629831036 | 22044086260 |     250 |      2 | "Zy"
 "BRYOWG" |   619745786 | 21691102510 |     325 |     15 | "z2X"
 "BWRYOG" |   626960756 | 21943626460 |     295 |     16 | "zY"
 "BOWRYG" |   615161906 | 21530666710 |      10 |     10 | "x"
 "YOBRGW" |  1822264042 | 63779241470 |     230 |     13 | "x2"
 "YGOBRW" |  1810797202 | 63377902070 |      35 |      4 | "Zyx"
 "YRGOBW" |  1826976442 | 63944175470 |       5 |      5 | "z2"
 "YBRGOW" |  1803428722 | 63120005270 |     350 |      9 | "z2Y"

```
> 5 votes

# Answer
# Ruby, ~~84~~ 83 bytes

```
->a{k=a.index(0);%W{#{} z x Z X zz xx}[k+=k/5*a[2]/3]+%W{#{} Y yy y}[a[c=1+k%2]-c]}

```

Try it online!

Llambda function taking an array of 6 numbers 0..5 representing the faces, with the following solved configuration

```
   0
  1234
   5

```

Searches for the index of the array element containing `0` and selects a string for the move required to move it to the top: either by rotating in the x or z axis (or the empty string if it is already there, represented by `#{}` in `%W{}` notation.)

Then, inspect either array element 1 or 2 (whichever would not be altered by performing the move in the above step), select a string (always rotation in the y axis) for the move required to move the contents of the element to their solved location, and return the concatenated moves.

An issue arises when the index of the array containing `0` is 5, as there are two possible moves that will return it to the top: `zz` and `xx`. If array element 2 (the front of the cube) contains `2` the cube can be completely solved by `zz`, and if it contains `4` it can be solved by `xx`. The default is value to be returned is `zz` but if the front face contains `3` or `4` the expression `k/5*a[2]/3` adds 1 to the index of `%W{#{} z x Z X zz xx}` that is returned, correcting it to `xx`. (Note that if the front face contains `1` or `3` it doesn't matter whether `xx`or `zz` is used as in these cases an additional 90 deg rotation will be required about the y axis regardless of whether `xx` or `zz` is used.)
> 3 votes

# Answer
# Jelly, 75 bytes

I've been meaning to do this challenge for a while. I wonder if a straight hashing approach will be shorter than this solver.

```
“¡Çµ‘ṗÐ€7Ḷ¤Ẏ
œ?ạ⁸%7¤¦7
⁹Ḣ¤ç¥⁹¿
ỤỤḣ3çÐ€ÑĠḢịÑ+9µŒgPL⁼¥¡€3Fµ€LÞḢ×28+62%⁹%9ị³Ṣ¤

```

A full program accepting a list of characters as input and printing the result to STDOUT using the **x**, **xx**, **X** format.

For the sake of saving two**!** bytes it uses the somewhat confusing input:

```
X = White     Y = Orange    Z = Green
z = Yellow    y = Red       x = Blue      note: this makes the solved state XYZyxz

```

**Try it online!**

### How?

Defines a dyadic link which can perform an **x**, **y**, or **z** to its right argument, an Up-Left-Front triple (ULF) of faces where:

```
1 = White     2 = Orange    3 = Green
6 = Yellow    5 = Red       4 = Blue      note: the solved state has ULF = 1,2,3
7             7             7       <--  ...and the sums of opposite faces are all 7

```

for certain left arguments:

```
if left % 6 == 0 and left % 7 in (0, 3):     # e.g. left = 0
    performs x
    # switches U&F, ULF to FLU, (permutation 0)
    # and switches the new U (index 0 or 3) to its opposite colour (7-value)
elif left % 6 == 2 and left % 7 in (0, 3):   # e.g. left = 14
    performs y
    # switches L&F, ULF to UFL, (permutation 2)
    # and switches the new L (index 0 or 3) to its opposite colour (7-value)
elif left % 6 == 3 and left % 7 in (-1, 2):  # e.g. left = 9
    performs z
    # switches U&L, ULF to LUF, (permutation 3)
    # and switches the new U (index -1 or 2) to its opposite colour (7-value)
else:
    does some other permutation and opposite colour swap which we wont use.

```

Creates all sequences made from the left inputs `0,14,9` of length zero to six

```
i.e. [[],[0],[14],[9],[0,0],[0,14],[0,9],[14,0],...,[9,9,9,9,9,9]]

```

and then repeatedly applies the link to the ULF of the translated input with the numbers in the list as the left arguments.

Translation of the input is performed by a double application of grade-up, , since the ordering used is chosen to make that work (the natural ordering of the characters is `XYZxyz`); while UFL is extracted by simply taking the first three results, `ḣ3`.

The sequences that result in a transformation to `[1,2,3]` (the solved state) are then transformed such that any run of exactly three of the same move are multiplied together.

Some arithmetic is performed to transform the results to be the indexes of `"XYZxyz"`. This was found by brute-force to be to add nine prior to the multiplication, then to multiply all results by 28, to add another 62, to modulo by 256 to modulo again by 9 and finally to modulo by 6 (although the final modulo may be performed by indexing into something of length 6 since Jelly indexing is modular)

```
move  value     add 9      product  times 28  add 62  mod 256  mod 9  mod 6
 X    [ 0, 0, 0] [ 9, 9, 9]   729     20412    20474   250       7      1
 Y    [14,14,14] [23,23,23] 12167    340676   340738     2       2      2
 Z    [ 9, 9, 9] [18,18,18]  5832    163296   163358    30       3      3
 x     0          9             9       252      314    58       4      4
 y    14         23            23       644      706   194       5      5
 z     9         18            18       504      566    54       0      0

```

All that remains is to take the first shortest result and to index into the sorted input, `"XYZxyz"`

---

Commented code:

```
“¡Çµ‘ṗÐ€7Ḷ¤Ẏ - Link 1, get all sequences of 0,14,9 up to length 6: no arguments
“¡Çµ‘        - code-page indices = [0,14,9]
          ¤  - nilad followed by link(s) as a nilad:
        7    -   literal seven
         Ḷ   -   lowered range = [0,1,2,3,4,5,6]
      Ð€     - map across right:
     ṗ       -   Cartesian power -> [[[]],[[0],[14],[9]],[[0,0],[0,14],[0,9],...,[9,9]],...,[[0,0,0,0,0,0],...,[9,9,9,9,9,9]]]
           Ẏ - tighten -> [[],[0],[14],[9],[0,0],[0,14],[0,9],...,[9,9],...,[0,0,0,0,0,0],...,[9,9,9,9,9,9]]

œ?ạ⁸%7¤¦7 - Link 2, perform a manoeuvre: integer, N; list of integers, [U,L,F]
œ?        - Nth permutation of [U,L,F]
        7 - literal seven
       ¦  - sparse application...
  ạ       - ...of: absolute difference (from 7) -- i.e. opposite colour
      ¤   - ...to indexes: nilad followed by link(s) as a nilad:
   ⁸      -   chain's left argument = N
     7    -   literal seven
    %     -   modulo

⁹Ḣ¤ç¥⁹¿   - Link 3, perform manoeuvres: list of integers, [U,L,F], list of integers, M
      ¿   - while...
     ⁹    - ...condition: chain's right argument, M (while there are manoeuvres)
    ¥     - ...do: last two links as a dyad:
  ¤       -   nilad followed by link(s) as a nilad:
⁹         -     chain's right argument, M
 Ḣ        -     pop head -- gets the first element and modifies M
   ç      -     call last link (2) as a dyad (right is chain's left argument, [U,L,F])

ỤỤḣ3çÐ€ÑĠḢịÑ+9µŒgPL⁼¥¡€3Fµ€LÞḢ×28+62%⁹%9ị³Ṣ¤ - Main link: list of characters, S
Ụ                                            - grade-up (sort indices by value)
 Ụ                                           - grade-up again (net effect X->1, Y=>2, Z->3, x->4, y->5, z->6)
  ḣ3                                         - head to index three (get the ULF triple)
       Ñ                                     - call next link (1) as a monad (the input is not consumed, but that's OK)
     Ð€                                      - map across right with:
    ç                                        -   call last link (3)
        Ġ                                    - group the indices by value (placing all solved indices in the head, since [1,2,3] is less than others)
         Ḣ                                   - head
           Ñ                                 - call next link (1) as a monad (get the instructions again)
          ị                                  - index into (get the solving instruction lists)
            +9                               - add nine to all values in all instruction lists
              µ          µ€                  - for €ach instruction list:
               Œg                            -   group runs of equal elements
                       3                     -   literal three
                     ¡€                      -   repeat for €ach group...
                 P                           -   ...action: product
                    ¥                        -   ...number of times: last two links as a dyad
                  L                          -     length
                   ⁼                         -     equal to (three)? -- i.e. take the product of any run of exactly three values
                        F                    -   flatten (back to a single list)
                            Þ                - sort by:
                           L                 -   length (getting the shorted solving instruction list to the front)
                             Ḣ               - head
                              ×28            - multiply all the values by 28
                                 +62         - add 62 to all the values
                                     ⁹       - literal 256
                                    %        - modulo by (256)
                                      %9     - modulo by 9
                                           ¤ - nilad followed by link(s) as a nilad:
                                         ³   -   program's (1st) input
                                          Ṣ  -   sort (always = "XYZxyz")
                                        ị    - index into
                                             - implicit print to STDOUT

```
> 1 votes

---
Tags: code-golf, string, rubiks-cube
---


# Question
Title: How many squares, cubes, fourth powers, etc. do I need to sum to n?
You are given a nonnegative integer `n` and an integer `p >= 2`. You need to add some `p`-th powers (`p=2` means squares, `p=3` means cubes) together to get `n`. This is always for any nonnegative `n`, but you don't know many `p`-th powers (of any **positive** integer) you'll need.

This is your task: find the minimum number of `p`-th powers that can sum to `n`.

**Examples**

```
>>> min_powers(7, 2)
4                       # you need at least four squares to add to 7
                        # Example: (2)^2 + (1)^2 + (1)^2 + (1)^2 = 4 + 1 + 1 + 1 = 7
>>> min_powers(4, 2)
1                       # you need at least one square to add to 4
                        # Example: (2)^2 = 4
>>> min_powers(7, 3)
7                       # you need at least seven cubes to add to 7
                        # Example: 7*(1)^3 = 7
>>> min_powers(23, 3)
9                       # you need at least nine cubes to add to 23
                        # Example: 2*(2)^3 + 7*(1)^2 = 2*8 + 7*1 = 23

```

A related Wikipedia article on this problem, Waring's problem.

**Rules**

* Your code *must* be a program or a function.
* Input is two integers `n` and `p` in any order. You can assume all inputs are valid (`n` is any positive integer, `p >= 2`
* Output is an integer representing the number of powers needed to sum to `n`.
* This is code golf, so **the shortest program** wins., not necessarily the most efficient.
* Any and all built-ins are allowed.

As always, if the problem is unclear, please let me know. Good luck and good golfing!

# Answer
> 5 votes
# Pyth, ~~20~~ 19 bytes

*Saved 1 byte thanks to FryAmTheEggman.*

```
L&bhSmhy-b^dQS@bQyE

```

Takes input on two lines, `p` first and then `n`.

Try it online. Test suite.

### Explanation

The code defines a recursive function `y(b)` that returns the result for `min_powers(b, p)`.

```
L                      define a function y(b):
 &b                      return b if it's 0
             S           get a list of positive integers less than or equal to
              @bQ        the p:th root of b
     m                   map the integers to:
        -b                 subtract from b
          ^dQ              the p:th power of the current integer
       y                   recurse on the above
      h                    increment the result
    hS                   find the smallest result number and return it
                 yE    calculate y(n) and print

```

# Answer
> 8 votes
# Mathematica ~~61~~ 50 bytes

With 11 bytes saved by LegionMammal978.

When restricted to powers of counting numbers, this problem is straightforward (in Mathematica). When extended to include powers of integers, it's a nightmare.

```
(k=0;While[PowersRepresentations[#,++k,#2]=={}];k)&

```

---

**Test Cases**

```
(k = 0; While[PowersRepresentations[#, ++k, #2] == {}]; k) &[7, 2]
(k = 0; While[PowersRepresentations[#, ++k, #2] == {}]; k) &[4, 2]
(k = 0; While[PowersRepresentations[#, ++k, #2] == {}]; k) &[7, 3]
(k = 0; While[PowersRepresentations[#, ++k, #2] == {}]; k) &[23, 3]

```

> 4
>
> 1
>
> 7
>
> 9

---

`PowersRepresentationsp[n,k,p]` finds all the cases in which `n` can be expressed as a sum of `k` positive integers raised to the `p`-th power.

---

For example,

```
PowersRepresentations[1729, 2, 3]

```

> {{1, 12}, {9, 10}}

Checking,

```
1^3 + 12^3

```

> 1729

---

```
9^3 + 10^3

```

> 1729

# Answer
> 3 votes
## Java - 183 177 bytes

```
int p(int a,int b){int P,c,t,l=P=t=a,f=0;double p;while(P>0){a=t=l;c=0;while(t>0){if(a-(p=Math.pow(t,b))>=0&&t<=P){while((a-=p)>=0)c++;a+=p;}t--;}f=c<f||f==0?c:f;P--;}return f;}

```

---

**183 bytes**

```
int p(int a,int b){int P,c,t,l,f=0;P=t=l=a;double p;while(P>0){a=t=l;c=0;while(t>0){if(a-(p=Math.pow(t,b))>=0&&t<=P){while((a-=p)>=0){c++;}a+=p;}t--;}f=c<f||f==0?c:f;P--;}return f;}

```

## Ungolfed

```
int p(int a, int b){
    int P,c,t,l=P=t=a,f=0;
    double p;
    while (P>0){
        a=t=l;
        c=0;
        while (t>0){
            if (a-(p=Math.pow(t, b))>=0 && t<=P){
                while((a-=p)>=0)c++;
                a+=p;
            }
            t--;
        }
        f=c<f||f==0?c:f;
        P--;
    }
    return f;
}

```

---

## Result

```
System.out.println(p(7, 2));    // 4
System.out.println(p(4,2));     // 1
System.out.println(p(7,3));     // 7
System.out.println(p(23,3));    // 9

```

# Answer
> 1 votes
# Python 2, 66 bytes

```
f=lambda n,p:n and-~min(f(n-k**p,p)for k in range(1,n+1)if n/k**p)

```

Recursively tries subtracting each `p`-th power which leaves the remainder non-negative, computing its value on each remainder, and taking the minimum plus 1. On 0, outputs 0.

The ugly check `if n/k**p` (equivalent to `if k**p<=n`) is to stop the function from going into the negatives and trying to take the `min` of the empty list. If Python has `min([])=infinity`, this wouldn't be needed.

# Answer
> 0 votes
# C (gcc), 122 bytes

```
r(n,p,k,s,j,b){if(!k)return n!=s;for(b=j=1;j<n;b*=r(n,p,~-k,s+(int)pow(j++,p)));n=b;}f(n,p,k){for(k=0;r(n,p,++k,0););n=k;}

```

Try it online!

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


title: Code golf for my real friends

text:
# Question
Title: Code golf for my real friends
> ...and real golf for my code friends.

This is a challenge based on a one year old XKCD comic which consists mostly of toasts (parodies of the first in the comic) following a distinct pattern, but with some slight variation.

Your task is to write a program (or function) that takes the first half of any toast from the comic (everything up to and including the `friends`) as input (via stdin or a function argument) and outputs (or returns) the precise text of the second half. You do not have to handle invalid input, standard loopholes apply, shortest code in bytes wins.

### Examples

To help those who don't want to copy the toasts from anywhere else, here are all of them, separated into input and output.

```
Input: Champagne for my real friends
Output: and real pain for my sham friends!

Input: Pseudopods for my real friends
Output: and real pods for my pseudo-friends!

Input: Petticoats for my real friends
Output: and real coats for my petty friends.

Input: Loosestrife for my real friends
Output: and real strife for my loose friends!

Input: Ladybugs for my real friends
Output: and real bugs for my lady friends!

Input: Single-payer for my real friends
Output: and RealPlayer for my single friends.

Input: Tumbleweeds for my real friends
Output: and real weed for my Tumblr friends!

Input: Fauxhawks for my real friends
Output: and real hawks for my faux friends!

Input: Platonic solids for my real friends
Output: and real solids for my platonic friends!

```

# Answer
# Retina, 119 bytes

The previous version didn't manage correctly the space in "platonic solids", this one works and is shorter :)

```
ew
rw
eds
ed
(\w+) ?([^oatr ]\w{3}.+)real
and real $2$1
C
S
gne
in
o
o-
ti
ty
T`TL`Tl
p\w+y.+
$&.
s$
s!
real -p
RealPl

```

Try it online!

This transforms the input into the output through a series of substitutions.

The most interesting part is this substitution (kind of a regex golf):

```
(\w+) ?([^oatr ]\w{3}.+)real
and real $2$1

```

Which does almost all the job, by splitting the first word, placing its pieces in the right places, removing extra spaces, and building the structure of the output. To work correctly on the "Tumbleweeds" test case this depends on the previous substitution "eds"-\>"ed".

The rest is mostly composed by substitutions that deal with special cases. Other interesting parts are:

```
T`TL`Tl

```

This turns everything except "T" (for Tumblr) to lowercase.

```
p\w+y.+
$&.
s$
s!

```

This places a "." at the end of each sentence containing a word with a "y" some letters after a "p" ("petty" and "payer" in practice). Then places a "!" at the end of all sentences ending with an "s" (all the others).
> 18 votes

# Answer
# Python 2, 291 269 293 255 247 bytes

*Thanks to `Erik the Outgolfer` for saving 22 bytes!*

*+24 bytes to account for some outputs ending in `.` instead of `!`*

```
lambda x:'and '+['real '+'pain%ssham ,pods%spseudo-,coats%spetty ,strife%sloose ,bugs%slady ,weed%sTumblr ,hawks%sfaux ,solids%splatonic '.split(',')['noarsekc'.find(x[7])],'RealPlayer%ssingle ']['-'in x]%' for my '+x[-7:]+'!.'['-'in x or'tt'in x]

```

Simple solution to start things off. Checks the eighth letter of the input, as suggested in the comments, and looks up the corresponding output in a dictionary an array.

Try it Online!
> 10 votes

# Answer
# Python 3, 788, 403, 359 396 bytes

**Latest Version**

This is now my fifth attempt. I've managed to half the size of my original program. It now includes the missing "-" and I believe is a complete solution. Still I suspect on the bulky side; but much closer to the goal. I've had **a lot of help**. Thanks for all the helpful guidance.

```
s=input()
x=0
l= "Ch,pain,Sham,Ps,pods,psuedo-,Pe,coats,petty,Lo,strife,loose,La,bugs,lady,Si,RealPlayer,single,Tu,weed,Tumblr,Fa,hawks,faux,Pl,solids,platonic".split(",")
a,b,c,d,e,f,g,h = " and real","for my","friends",".!","print(a,l[p+1],b,l[p+2]",",c+d[0])","+c+d[1])",",c+d[1])"
for p in range(0,27,3):
 x+=1
 if s[:2] == l[p]:
  if x == 2: eval(e+g)
  else: eval(e+f if x in(3,6) else e+h)

```

Try it online!

---

**Original Posting**

This is my first post on code golf so apologies in advance for my clumsy program. Can't see how a program could be made to convert "Champagne" to "pain", "sham" by parsing the words. However I would like to see someone else solve that. So, as my level of ability dictates that my program needs to know in advance that "Champagne" is "pain", "sham", there seemed little point in actually coding an input request. As a result I've left it out and been a bit literal with my print output. Hope that's ok : )

```
phraseList= [   ("Champagne","pain","Sham"),
                ("Psudeopods","pods","psuedo-"),
                ("Petticoats","coats","petty"),
                ("Loosestrife","strife","loose"),
                ("Ladybugs","bugs","lady"),
                ("Single-payer","coats","petty"),
                ("Petticoats","RealPlayer","single"),
                ("Tumbleweeds","weed","Tumblr"),
                ("Fauxhawks","hawks","faux"),
                ("Platonic solids","real solids","platonic")
                ]

for phrase in phraseList:
    print("Input: ",phrase[0], "for my real friends.")
    if "-" in phrase[2]:
        print("Output: and real", phrase[1], "for my", phrase[2]+ "friends!")
    else:
        print("Output: and real", phrase[1], "for my", phrase[2], "friends!")

```
> 6 votes

# Answer
# Röda, ~~299~~ ~~292~~ ~~288~~ 259 bytes

*4 bytes saved thanks to @fergusq for using `,` instead of `..` in the `push` statements*

*Bytes saved thanks to @fergusq showing me the way of `indexOf`*

```
h a{r=indexOf(a[7:8],"noarspekc")A="pain>pods>coats>strife>Player>bugs>weed>hawks>solids>sham >pseudo->petty >loose >lady >single >Tumblr >faux >platonic >!>!>.>!>!>.>!>!>!"/">";["and "];["Real"]if[r=4]else["real "];[A[r]," for my ",A[r+9],"friends",A[r+18]]}

```

Try it online!

So close to Python... so close.... ~~Your move, Python.~~

### Explanation

```
h a{
  r=indexOf(a[7:8],"noarspekc")  /*Gets the index of the character in this string*/
  /*Variable A contains all the unique words for each test case*/
  A="pain>pods>coats>strife>Player>bugs>weed>hawks>solids>sham >pseudo->petty >loose >lady >single >Tumblr >faux >platonic >!>!>.>!>!>.>!>!>!"/">"
  ["and "]
  ["Real"]if[r=4]else["real "]   /*RealPlayer*/
  [A[r]," for my ",A[r+9],"friends",A[r+18]]   /*Print everything using var A*/
}

```
> 6 votes

# Answer
# SOGL, 143 bytes

```
_╔x⅜²‘,8WWAa"⅞+1Tλ²⅞ƨ◄…χŗbdŗu8ņ∑Ι⅓I‼hzΔμō┘═q‼xΘ▼²ηpG⅔─┌¡↕+wd÷[≈┐α┌ļ○(‚δΦEΤα{‚φ▒k׀:╚s&⅛↑»‘ |Θwθ1w"ρ└⁸‘S∆∫⁴‘a1>*+oo"¤Ε○Φr‘o2w _@ŗo"æn‘o"χ}49⁶‘aWT

```

This uses this string as the main part. "|" are the splitters and "\_" are space placeholders so split would work correctly.

```
RealPlayer single_|weed Tumblr_|strife loose_|bugs lady_|pods pseudo-|pain sham_|solids platonic_|coats petty_|hawks faux_

```

Input example: "Platonic solids for my real friends" Explanation:

```
..‘,8WWAa"..‘ |Θwθ1w"..‘S∆∫⁴‘a1>*+oo"..‘o2w _@ŗo"..‘o"..‘aWT  strings shortened
..‘                                                           push "personcake" (the indexing string) ["personcake"]
    8W                                                        get the 8-th char
   ,                                                           from the input                         ["personcake", "c"]
      W                                                       get its in "personcake" (1-indexed)     [7]
       Aa                                                     save on variable A                      [7]
         "..‘                                                 push the long string                    [7, "RealPlayer...faux_"]
              |Θ                                              split on "|"                            [7, ["RealPlayer single_", ..., "hawks faux_"]]
                w                                             get the Ath item of the array           [["..."], "solids platonic_"]
                 θ                                            split on spaces                         [["..."], ["solids", "platonic_"]]
                  1w                                          get the 1st item                        [["..."], ["solids", "platonic_"], "solids"]
                    "..‘                                      push "and "                             [["..."], ["solids", "platonic_"], "solids", "and "]
                        S∆∫⁴‘                                 push "real "                            [["..."], ["solids", "platonic_"], "solids", "and ", "real "]
                             a1>*                             multiply by A(index) > 1                [["..."], ["solids", "platonic_"], "solids", "and ", "real "]
                                 +                            join together                           [["..."], ["solids", "platonic_"], "solids", "and real "]
                                  o                           output                                  [["..."], ["solids", "platonic_"], "solids"]
                                   o                          output (the 1st item of the array)      [["..."], ["solids", "platonic_"]]
                                    "..‘o                     output " for my "                       [["..."], ["solids", "platonic_"]]
                                         2w                   get the 2nd item of the array           [["..."], ["solids", "platonic_"], "platonic_"]
                                            _@ŗ               replace "_" with " "                    [["..."], ["solids", "platonic_"], "platonic "]
                                               o              output that                             [["..."], ["solids", "platonic_"]]
                                                "..‘o         output "friends"                        [["..."], ["solids", "platonic_"]]
                                                     "..‘     push ".!!!!!!.!"                        [["..."], ["solids", "platonic_"], ".!!!!!!.!"]
                                                         aW   get the Ath item                        [["..."], ["solids", "platonic_"], "!"]
                                                           T  output, disabling implicit output       [["..."], ["solids", "platonic_"]]

```
> 6 votes

# Answer
## JavaScript (ES6), ~~230~~ ~~228~~ ~~221~~ 216 bytes

```
s=>'and '+((n='paonrsekc'.search(s[7]))?'real ':'')+'RealPl740s5 /450p3y /540p5-/pain0s3 /460l4 /340l3 /540T4r /350f3 /860p7 '.split`/`[n].replace(/\d\d?/g,n=>s.substr(n/10+1,n%10)||' for my ')+'friends'+'.!'[+(n>1)]

```

### Test

```
let f =

s=>'and '+((n='paonrsekc'.search(s[7]))?'real ':'')+'RealPl740s5 /450p3y /540p5-/pain0s3 /460l4 /340l3 /540T4r /350f3 /860p7 '.split`/`[n].replace(/\d\d?/g,n=>s.substr(n/10+1,n%10)||' for my ')+'friends'+'.!'[+(n>1)]

console.log(f("Champagne for my real friends"));
console.log(f("Pseudopods for my real friends"));
console.log(f("Petticoats for my real friends"));
console.log(f("Loosestrife for my real friends"));
console.log(f("Ladybugs for my real friends"));
console.log(f("Single-payer for my real friends"));
console.log(f("Tumbleweeds for my real friends"));
console.log(f("Fauxhawks for my real friends"));
console.log(f("Platonic solids for my real friends"));
```
> 5 votes

# Answer
# PHP, 202 220 204 203 bytes

```
and real <?=[pods,solids,hawks,strife,RealPlayer,pain,bugs,weed,coats][$q=md5($argv[1].LnI)%9].' for my '.[pseudo,platonic,faux,loose,single,sham,lady,Tumblr,petty][$q].' -'[!$q].friends.'.!'[!$q||$q&3];

```
> 3 votes

# Answer
# Perl, ~~173~~ 168 bytes

Removing newlines and indentations, this becomes 173 bytes of Perl5 code. Shamelessly stole first regexp from Leo's Retina answer. (Mine was a few chars longer)

```
sub f{
  my($_)=@_;
  s,(\S+[oieyxm ])(\S{4}.+)real,and real $2\l$1,;
  s,gne,in,;
  s,ch,sh,;
  s,ti,ty,;
  s,eds,ed,;
  s,tumble,Tumblr,;
  s,real -p,RealPl,;
  s,o ,o-,;
  s,c ,c,;
  /ng|tt/?"$_.":"$_!"
}

```

For perl5 version \>= 5.14 another 5 bytes can be shaved off with eval and the new /r regexp substitution modifier. Ending up with 168 bytes:

```
sub f{my($_)=@_;eval's,(\S+[oieyxm ])(\S{4}.+)real,and real $2\l$1Xgne,inXch,shXti,tyXeds,edXtumble,TumblrXreal -p,RealPlXo ,o-Xc ,c,;/ng|tt/?"$_.":"$_!"'=~s/X/,;s,/gr}

```

Try it online!
> 3 votes

# Answer
# Java 7, ~~585~~ 553 bytes

```
import java.util.*;String c(String s){Map m=new HashMap(){{put("Ch","pain");put("Ps","pods");put("Pe","coats");put("Lo","strife");put("La","bugs");put("Si","Player");put("Tu","weed");put("Fa","hawks");put("Pl","solids");put("Ch1","sham ");put("Ps1","pseudo-");put("Pe1","petty ");put("Lo1","loose ");put("La1","lady ");put("Si1","single ");put("Tu1","Tumblr ");put("Fa1","faux ");put("Pl1","platonic ");}};String r=s.substring(0,2);int c=r.charAt(1);return"and "+(c=='i'?"Real":"real ")+m.get(r)+" for my "+m.get(r+1)+"friends"+(c=='i'|c=='e'?'.':'!');}

```

-32 bytes thanks to *@Zircon*.

Can definitely be golfed by using something different than a Map..

**Explanation:**

```
import java.util.*;            // Import required for the Map & HashMap
String c(String s){            // Method with String parameter and String return-type
  Map m=new HashMap(){{        //  The Map
    put("Ch","pain");put("Ps","pods");put("Pe","coats");put("Lo","strife");put("La","bugs");put("Si","Player");put("Tu","weed");put("Fa","hawks");
                               //  Add mapping from first two characters with first word
    put("Ch1","sham ");put("Ps1","pseudo-");put("Pe1","petty ");put("Lo1","loose ");put("La1","lady ");put("Si1","single ");put("Tu1","Tumblr ");put("Fa1","faux ");put("Pl1","platonic ");
                               //  Add mapping from first two characters + "1" with second word (+ space or '-' for edge-case `pseudo-friends`)
  }};                          // End of Map initialization
  String r=s.substring(0,2);   //  Get the first two characters of the input String
  int c=r.charAt(1);           //  Get the second character
  return "and "                //  return "and "
    + (c=='i'?"Real":"real ")  //   + "Real" or "real " for edge-case `RealPlayers`
    + m.get(r)                 //   + first word from Map
    + " for my "               //   + " for my "
    + m.get(r+1)               //   + second word from Map
    + "friends"                //   + "friends"
    + (c=='i'|c=='e' ? '.'     //   + '.' for edge-cases 'Petticoats' and 'Single-player
      : '!');                  //     or '!' for all other cases
}                              // End of method

```

**Test code:**

Try it here. (ideone.com is bugged lately, so I'm using TIO now..)

```
import java.util.*;
class M{
  static String c(String s){Map m=new HashMap();m.put("Ch","pain");m.put("Ps","pods");m.put("Pe","coats");m.put("Lo","strife");m.put("La","bugs");m.put("Si","Player");m.put("Tu","weed");m.put("Fa","hawks");m.put("Pl","solids");m.put("Ch1","sham ");m.put("Ps1","pseudo-");m.put("Pe1","petty ");m.put("Lo1","loose ");m.put("La1","lady ");m.put("Si1","single ");m.put("Tu1","Tumblr ");m.put("Fa1","faux ");m.put("Pl1","platonic ");String r=s.substring(0,2);int c=r.charAt(1);return"and "+(c=='i'?"Real":"real ")+m.get(r)+" for my "+m.get(r+1)+"friends"+(c=='i'|c=='e'?'.':'!');}

  public static void main(String[] a){
    System.out.println(c("Champagne for my real friends"));
    System.out.println(c("Pseudopods for my real friends"));
    System.out.println(c("Petticoats for my real friends"));
    System.out.println(c("Loosestrife for my real friends"));
    System.out.println(c("Ladybugs for my real friends"));
    System.out.println(c("Single-player for my real friends"));
    System.out.println(c("Tumbleweeds for my real friends"));
    System.out.println(c("Fauxhawks for my real friends"));
    System.out.println(c("Platonic solids for my real friends"));
  }
}

```
> 2 votes

# Answer
# C, 367 bytes

Didn't end up as short as it seemed it would.

```
i,j,c;f(char*s){c=s[7]-97;char t[9],u[200];char*r=s;s+=j=c&&c-17?c-10&&c-18?c-2?5:8:3:4;for(i=0;*++s-32;t[i++]=*s);t[c-4?i:i-1]=0;for(i=0;*r++-t[0];)u[i++]=*(r-1);u[i]=32;u[i+1]=0;u[0]+=32;u[c?i:i-1]=c?c-2?c-14?32:45:0:121;printf("and %s%s for my %sfriends%c",c-15?"real ":"RealPlayer",c-15?c-13?t:"pain":"",c-13?c-4?c-17?u:"loose ":"Tumblr ":"sham ",c&&c-15?33:46);}

```
> 2 votes

# Answer
# C (gcc), 311 bytes

Clear patterns, but so many exceptions. Still, there must be a better way than this!

```
f(char*s){char*t="\"5$#(=931",*r[]={"pain", "sham","pods","pseudo","coats","petty","strife","loose","bugs","lady","Player","single","weed","Tumblr","hawks","faux","solids","platonic"};int i=strchr(t,*s^s[2])-t;printf("and %s%s for my %s%cfriends%c",i^5?"real ":"Real",r[i*2],r[i*2+1],i^1?32:45,i^5&&i^2?33:46);}

```

Try it online!
> 2 votes

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


title: Golf a golf-scorer

text:
# Question
Title: Golf a golf-scorer
As a kid, I used to play the card game *"golf"* a lot. Your challenge, should you choose to accept it, is to calculate the score of a golf hand. Since there are over 9000 variations on this card game1, we will go with the rules I remember playing.

# Rules (of the game)

* You end a round with 6 cards, and you want as few points as possible.
* Jokers are not used.
* Aces and 2s are worth -1, and -2 points respectively.
* Jacks and Kings are both worth 0 points.
* Cards from 3 to 10 are worth face value. However, these are cancelled when you pair them off. For example, a 5 is worth 5 points, but two 5s are worth zero. Three 5s are worth 5 points, (since the first 2 are paired off, but the 3rd is not.) and four 5s are worth 0 (since it makes 2 pairs).
* Queens are worth 15 points. Queens cannot be cancelled, e.g. 2 queens are worth 30 points.

# Rules (of the challenge)

Input will be an array of integers, or 6 individual integers. Whichever one you prefer. 1 represents an ace, 2-10 represents 2-10, and Jack, Queen, and King represents 11, 12, and 13. Output is the score of the hand according to the rules above. You can safely assume that all inputs are valid, e.g. no number appears more than 4 times, and all numbers are in the range `[1, 13]`. Input and output can be in any reasonable format.

# Test IO:

```
[11, 10, 3, 1, 2, 2]    --> 8
[4, 5, 5, 3, 8, 7]      --> 22
[2, 2, 2, 2, 1, 1]      --> -10 (The lowest score possible)
[12, 12, 12, 12, 10, 9] --> 79 (The highest score possible)
[9, 9, 9, 9, 11, 1]     --> -1
[8, 8, 8, 8, 11, 13]    --> 0
[10, 9, 3, 7, 12, 2]    --> 42
[1, 2, 3, 4, 5, 6]      --> 15
[10, 9, 2, 3, 4, 1]     --> 23
[10, 3, 12, 3, 7, 12]   --> 47

```

Shortest answer in bytes wins!

---

*1not really, but there are a lot of variations.*

# Answer
# Pyth, ~~28~~ ~~27~~ 25 bytes

```
s+*L%/Qd2}3Tm?<d3_d*15q12

```

Try it online. Test suite.

### Explanation

* Firstly, Pyth auto-appends some variables. The code is now `s+*L%/Qd2}3Tm?<d3_d*15q12dQ`.
* `}3T` generates the list `[3, 4, 5, 6, 7, 8, 9, 10]`.
* Multiply each number in that list (`*L`) by the count of that number in the input (`/Qd`), modulo 2 (`%``2`). The result is 0 for paired numbers and the number itself for non-paired ones.
* Map over the input numbers (`m``Q`):
    + If the number is less than 3 (`?<d3`), negate it (`_d`).
    + Otherwise check if it's 12 (`q12d`), and multiply the boolean by 15 (`*15`). The result is 15 for queens and 0 for anything else.
* Concatenate the lists (`+`). The resulting list now contains the scores for the non-paired numbers (the first part) and the special cards A, 2, Q (the second part), with some extra zeroes.
* Finally, take the sum of the result (`s`).

### Alternative 25-byte solution

```
-+s*L%/Qd2}3T*15/Q12s<#3Q

```

This works similarly to the first one, but counts the queens separately and negates the aces and twos with a filter.
> 3 votes

# Answer
## Python 2, ~~72~~ 70 bytes

```
f=lambda x,*T:[x*(-1)**T.count(x),~x%2*15,-x][(x-3)/8]+(T>()and f(*T))

```

At one point I wished Python treated `0**0 == 0` for once so that I could do `(-condition)**num`. Call like `f(11, 10, 3, 1, 2, 2)`.

Previous 72-byte version:

```
f=lambda x,*T:[~x%2*15,x*(-1)**(x<3or T.count(x))][x<11]+(T>()and f(*T))

```
> 11 votes

# Answer
# \>\<\>, ~~63 57~~ 56+2 = ~~65 59~~ 58 bytes

The input numbers are expected to be on the stack at program start, so +2 bytes for the `-v` flag. Try it online!

```
</!?lp6$+1g6:
3\0
?\::6g2%*{+}1+:b=
;\~16g-26g2*-c6gf*+n

```

As all unused values in the code field are initialised to `0`, it can be used to work out how many of each value is present on the stack by getting the value at `[value,6]`, incrementing it, and putting it back in the code field. The total is then calculated as:

```
T = 0 + {for x in 3 to 10, x*([x,6]%2)} - [1,6] - 2*[2,6] + 15*[12,6]

```

*Edit: golfed 6 bytes off by restructuring the input and switching the calculation steps around. Previous version:*

```
:6g1+$6pl0=?\
/-*2g62-g610/
c ;n$\
6:b=?/>::6g2%*{+}1+!
\gf*+3/

```

*Edit 2: saved 1 byte, thanks to Sp3000*
> 5 votes

# Answer
# MATL, ~~27~~ 26 bytes

```
3:10=s2\7M*G12=15*Gt3<*_vs

```

The input is a column array, that is, values are separated by semicolons.

Try it online! or verify all test cases (this adds a loop to take all inputs, and replaces `G` by `1$0G` to push latest input).

### Explanation

```
3:10=    % Take input implicitly. Compare with range [3 4 ... 10], with broadcast
s        % Sum of each column: how may threes, fours, ... tens there are
2\       % Modulo 2
7M       % Push [3 4 ... 10] again
*        % Element-wise multiply (the sum of this array is the score of 3...10)
G        % Push input again
12=      % Compare with 12, element-wise
15*      % Multiply by 15 (this is the score of 12)
G        % Push input again
t3<      % Duplicate. True for entries 1 or 2
*_       % Multiply and negate (the sum of this array is the score of 1, 2)
v        % Concatenate all stack concents into a vertical array
s        % Sum of array. Implicitly display

```
> 5 votes

# Answer
# Pyth - ~~37~~ ~~36~~ 35

This is seems way too large, but FGITW.

```
J<#h;K-QS2++*15/K12sm*d%/Jd2{J_s@S2

```

Test Suite.
> 4 votes

# Answer
## JavaScript (ES6), 63 bytes

```
a=>a.map(e=>r+=e<3?-e:e>10?e-12?0:15:(m[e]^=1)?e:-e,r=0,m=[])|r

```

Or if you prefer,

```
a=>a.map(e=>r-=e<3?e:e>10?e-12?0:-15:(m[e]^=1)?-e:e,r=0,m=[])|r

```
> 3 votes

# Answer
# Perl 5.10.0 \+ `-n`, ~~115~~ ~~64~~ ~~60~~ 56 bytes

```
$p+=$_-12?$_>2?$_<11?++$l[$_]%2?$_:-$_:0:-$_:15}{say$p

```

Try it online!

## Explanation:

Adding the `-n` loop around it:

```
# Used variables:
# $_: input (auto)
# $p: points
# $l[n]: number of occurences of n (for 3-10)
while (<>) { # for every input
    $p += $_ - 12 ? # if the input is not 12 (queen) ...
        $_ > 2 ? # then: if it's > 2 (not ace or 2) ...
            $_ < 11 ? # then: if < 11 (3-10) ...
                ++$l[$_] % 2 ? # then: if it's an odd occurence (1st, 3rd, 5th, ...)
                    $_ # add it
                    : -$_ # else subtract it
            : 0 # no points for other stuff (J, K)
        : -$_ # negative points for ace and 2
    : 15 # 15 points for queen
}
{ # after input:
    say $p # output points
}

```
> 0 votes

# Answer
# Perl 5, 74 +1 (`-a`) = 75 bytes

```
map$s+=/12/?15:$_<3?-$_:$_<11?$k{$_}?-delete$k{$_}:($k{$_}=$_):0,@F;say $s

```

Try it online!
> 0 votes

---
Tags: code-golf, math, game, card-games
---


title: Heightmap of Boxes

text:
# Question
Title: Heightmap of Boxes
Have a look at this ascii art diagram of various boxes:

```
+--------------------------------------------------------------+
|                                                              |
|   +-------------------------------+          +-------+       |
|   |                               |          |       |       |
|   |                               |          |       |       |
|   |     +----------------+        |          |       |       |
|   |     |                |        |          +-------+       |
|   |     |                |        |                          |
|   |     |                |        |          +-------+       |
|   |     +----------------+        |          |       |       |
|   |                               |          |       |       |
|   |                               |          |       |       |
|   +-------------------------------+          +-------+       |
|                                                              |
+--------------------------------------------------------------+

```

Each box is formed with pipe characters for the vertical parts (`|`), dashes for the horizontal parts (`-`), and pluses for the corners (`+`).

The diagram also shows boxes inside other boxes. We'll call the number of boxes that a box is contained within that box's *layer*. Here's the diagram again with the layer of each box annotated:

```
+--------------------------------------------------------------+
|                                                              |
|   +-------------------------------+          +-------+       |
|   |                               |          |       |       |
|   |                               |          |   1   |       |
|   |     +----------------+        |          |       |       |
|   |     |                |        |    0     +-------+       |
|   |     |        2       |   1    |                          |
|   |     |                |        |          +-------+       |
|   |     +----------------+        |          |       |       |
|   |                               |          |   1   |       |
|   |                               |          |       |       |
|   +-------------------------------+          +-------+       |
|                                                              |
+--------------------------------------------------------------+

```

Your program will take in a box diagram similiar to the one at the top as input. As output, your program should output the box diagram with:

* The box on layer 0 should be filled with the character `#` (NB: There will only ever be one box on layer 0);
* Boxes on layer 1 should be filled with the character `=`;
* Boxes on layer 2 should be filled with the character `-`;
* Boxes on layer 3 should be filled with the character `.`;
* Boxes on layer 4 and above should not be filled.

Here is what the output of the example input should look like:

```
+--------------------------------------------------------------+
|##############################################################|
|###+-------------------------------+##########+-------+#######|
|###|===============================|##########|=======|#######|
|###|===============================|##########|=======|#######|
|###|=====+----------------+========|##########|=======|#######|
|###|=====|----------------|========|##########+-------+#######|
|###|=====|----------------|========|##########################|
|###|=====|----------------|========|##########+-------+#######|
|###|=====+----------------+========|##########|=======|#######|
|###|===============================|##########|=======|#######|
|###|===============================|##########|=======|#######|
|###+-------------------------------+##########+-------+#######|
|##############################################################|
+--------------------------------------------------------------+

```

Here is another input and output showing layers 3, 4, and 5. Note the horizontal lines at the top that are very close together. In these cases there is not enough space to fill any characters there.

```
+-----------------------------------------------------------------------+
|     +--------------------------------------------------------------+  |
|     |      +-----------------------------------------------------+ |  |
|     |      |         +-----------------------------------------+ | |  |
|     |      |         |           +---------------------------+ | | |  |
|     |      |         |           |         +-------------+   | | | |  |
|     |      |         |           |         |             |   | | | |  |
|     |      |         |           |         +-------------+   | | | |  |
|     |      |         |           +---------------------------+ | | |  |
|     |      |         |                                         | | |  |
|     |      |         +-----------------------------------------+ | |  |
|     |      |                                                     | |  |
|     |      |                                                     | |  |
|     |      +-----------------------------------------------------+ |  |
|     |                                                              |  |
|     +--------------------------------------------------------------+  |
|                                                                       |
|                                                                       |
|                                                                       |
+-----------------------------------------------------------------------+

```

The output:

```
+-----------------------------------------------------------------------+
|#####+--------------------------------------------------------------+##|
|#####|======+-----------------------------------------------------+=|##|
|#####|======|---------+-----------------------------------------+-|=|##|
|#####|======|---------|...........+---------------------------+.|-|=|##|
|#####|======|---------|...........|         +-------------+   |.|-|=|##|
|#####|======|---------|...........|         |             |   |.|-|=|##|
|#####|======|---------|...........|         +-------------+   |.|-|=|##|
|#####|======|---------|...........+---------------------------+.|-|=|##|
|#####|======|---------|.........................................|-|=|##|
|#####|======|---------+-----------------------------------------+-|=|##|
|#####|======|-----------------------------------------------------|=|##|
|#####|======|-----------------------------------------------------|=|##|
|#####|======+-----------------------------------------------------+=|##|
|#####|==============================================================|##|
|#####+--------------------------------------------------------------+##|
|#######################################################################|
|#######################################################################|
|#######################################################################|
+-----------------------------------------------------------------------+

```

Another input, this time with the vertical lines close together as well:

```
+-------------+
|+-----------+|
||           ||
||           ||
||           ||
|+-----------+|
+-------------+

```

The output:

```
+-------------+
|+-----------+|
||===========||
||===========||
||===========||
|+-----------+|
+-------------+

```

**Additional Notes**

* There can be whitespace around the outermost box.
* Boxes cannot have an internal width or height of 0 (so they'll always be some space inside them)
* Boxes on the same layer can touch each other.

# Answer
> 3 votes
# Ruby 163 ~~164~~

```
w=l=-1
x=$<.map{|l|w=l.size;l}.join
b=[]
x.size.times{|i|c=x[i]
x[i..i+1]=='+-'&&(x[i+w]!=?|?b-=[i%w]:b<<i%w)
c>?z&&l+=b&[i%w]!=[]?1:-1
$><<(c==' '&&'#=-.'[l]||c)}

```

Try online: test case #1, test case #2.

The ungolfed program:

```
  # read all lines from STDIN
  input = $<.map{|l|l}.join
  width = input.index(?\n)+1

  box_left_margins = []
  current_layer = -1

  input.size.times{|i|
    c = input[i]

    if c == ?+ && input[i+1] == ?-
      #we're at a box's left margin
      if input[i+width] == ?|
        # we're at the box's top - mark this index as a left margin
        box_left_margins << i%width
      else
        # we're at the box's bottom - this index is no longer a left margin
        box_left_margins-=[i%width]
      end
    end

    if c == ?|
      if box_left_margins.include? (i%width)
        current_layer += 1
      else
        current_layer -= 1
      end
    end

    if c == ' '
      $><< ('#=-.'[current_layer]||' ')
    else
      $><<c
    end
  }

```

# Answer
> 2 votes
# Java, ~~476~~ 466 bytes

```
import java.util.*;class H{public static void main(String[]a){Scanner p=new Scanner(System.in);char[]l=p.nextLine().toCharArray(),d={'#','=','-','.'};int s=l.length,b,i;int[]m=new int[s];String o=new String(l);for(;;){o+='\n';l=p.nextLine().toCharArray();if(l[0]=='+')break;o+='|';b=0;for(i=1;i<s;++i){char c=l[i];switch(c){case' ':c=b>3?' ':d[b];break;case'+':m[i]=l[i-1]=='-'?-++m[i]:- --m[i];break;case'|':b+=m[i];}o+=c;}}o+=new String(l);System.out.println(o);}}

```

This reads the first line to determine the width (s) of the outermost box. With this it keeps an array of length s. This array stores from left to right where boxes begin and end and is initialized with 0s. It also stores the box-height.

The program reads the input line by line and watches for the following characters:

* '+' is, as we know, the edge of a box. If the input char to the left is a '-', it is the end of the box, else it is the beginning. The marker array gets updated as follows:
    + If the marker at this index is 0, set the value to 1 (beginning) or -1 (end).
    + Else set the value to 0. (We reached the bottom of the box, it is not important anymore)
* '|' changes the current box-height by the marker at the current index.
* ' ' Every char gets output as it was, except for blanks, which are replaced according to the current box-height.

Edit: Thanks to TheNumberOne for the suggestion. I also replaced while(true) with for(;;).

# Answer
> 2 votes
# CJam, ~~114~~ ~~111~~ ~~108~~ ~~104~~ ~~103~~ ~~102~~ 98 bytes

```
q"-+":R/Ws*N/z{_,{"|1"/Bs*}*}%z{_,,{_I=S&{_I>_1sf&s,\"|+"f&s,m5e<" #=2."=I\t}&}fI}%N*Ws/R*Cs"|-"er

```

Try it online in the CJam interpreter.

### How it works

```
q               e# Read all input from STDIN.
"-+":R/Ws*      e# Replace each "-+" with "-1".
N/z             e# Split at linefeeds and zip. Pushes the array of columns.
{               e# For each column:
  _,            e#   Push its length.
  {             e#   Do that many times:
    "|1"/Bs*    e#   Replace each "|1" with "11".
  }*            e#
}%              e#
z               e# Transpose. Goes back to array of rows.
{               e# For each row:
  _,,           e#   Push the array of its indexes.
  {             e#   For each index I:
    _I=         e#     Get the Ith character of the row.
    S&{         e#     If it is a space:
      _I>       e#       Get the characters after the Ith.
      _1sf&s,   e#       Count how many characters are 1's.
      \"|+"f&s, e#       Count how many are |'s or +'s.
      m5e<      e#       Subtract and truncate at 5.
      " #=2."=  e#       Retrieve the corresponding character.
      I\t       e#       Replace the Ith character of the row with that one.
    }&          e#
  }fI           e#
}%              e#
N*              e# Join the rows, separating by linefeeds.
Ws/R*           e# Turn "-1"s back to "-+"s.
Cs"|-"er        e# Turn 1's and 2's into |'s and -'s.

```

# Answer
> 2 votes
# JavaScript (*ES6*) 156

Run snippet in Firefox to test

```
F=b=>(
  r=b.split(/\n/),q=[n=0],
  r.map((r,i)=>(
    [...r].map((c,p)=>c=='+'?(q[p]=r[p-1]=='-'?-1:1,c):c<'!'?' #=-.'[n]||' ':((n+=q[p]|0),c)).join(''))
  ).join('\n')
)

// TEST

o=x=>O.innerHTML += x+'\n\n'

;[`+--------------------------------------------------------------+
|                                                              |
|   +-------------------------------+          +-------+       |
|   |                               |          |       |       |
|   |                               |          |       |       |
|   |     +----------------+        |          |       |       |
|   |     |                |        |          +-------+       |
|   |     |                |        |                          |
|   |     |                |        |          +-------+       |
|   |     +----------------+        |          |       |       |
|   |                               |          |       |       |
|   |                               |          |       |       |
|   +-------------------------------+          +-------+       |
|                                                              |
+--------------------------------------------------------------+`
,`+-----------------------------------------------------------------------+
|     +--------------------------------------------------------------+  |
|     |      +-----------------------------------------------------+ |  |
|     |      |         +-----------------------------------------+ | |  |
|     |      |         |           +---------------------------+ | | |  |
|     |      |         |           |         +-------------+   | | | |  |
|     |      |         |           |         |             |   | | | |  |
|     |      |         |           |         +-------------+   | | | |  |
|     |      |         |           +---------------------------+ | | |  |
|     |      |         |                                         | | |  |
|     |      |         +-----------------------------------------+ | |  |
|     |      |                                                     | |  |
|     |      |                                                     | |  |
|     |      +-----------------------------------------------------+ |  |
|     |                                                              |  |
|     +--------------------------------------------------------------+  |
|                                                                       |
|                                                                       |
|                                                                       |
+-----------------------------------------------------------------------+`
,`+-------------+
|+-----------+|
||           ||
||           ||
||           ||
|+-----------+|
+-------------+`
].forEach(t=>o(t+'\n'+F(t)+'\n'))
```

```
pre { font-size:10px;}
```

```
<pre id=O></pre>
```

# Answer
> 1 votes
# CJam, ~~76~~ 74 bytes

```
q:Q"-+":R/Ws*{_"| "#"]_QN#~%'|m0='+=2*(U+:U+~; \"#=-.\"+U5e<= "S/=~}%Ws/R*

```

Try it online in the CJam interpreter.

### How it works

```
q:Q        e# Read all input from STDIN and save it in the variable Q.
"-+":R/Ws* e# Replace each "-+" with "-1".
           e# This allows us to easily keep track of right corners.
{          e# For each charcter in the modified input:
  _"| "#   e#   Push its index in the string (0 for '|', 1 for ' ', -1 otherwise).

  "]_QN#~%'|m0='+=2*(U+:U+~; \"#=-.\"+U5e<= "S/

           e#   Split the pushed string at spaces, which results in three chunks:

           e#     ]        Turn the entire stack into a string.
           e#     _QN#     Compute the first index of a linefeed (row length).
           e#     ~%       Retrieve every previous character in the current column,
           e#              starting with the last.
           e#     '|m0=    Get the first character that is not a vertical bar.
           e#     '+=2*(   Push 1 if it's a plus sign and -1 otherwise.
           e#     U+:U     Add to U (initially 0) to keep track of the layer.
           e#     +~;      Add U to the string (casts to Array), dump and discard U.

           e#     "#=-."+  Concatenate this string with the space on the stack.
           e#     U5e<     Truncate U at 5.
           e#     =        Retrieve the corresponding character to replace the space.

           e#     (empty)

  =~       e#   Select and execute the proper chunk.
}%         e#
Ws/R*      e# Replace each "-1" with "-+".

```

# Answer
> 1 votes
# APL (Dyalog Unicode), 50 bytesSBCS

```
s[⊃¨0~¨⍨a,¨5|5⌊+⍀+\(⊢×¯1*+⍀++\)5=a←⎕⍳⍨s←' #=-.+|']

```

Try it online!

`s←' #=-.+|'` assign a string to variable `s`

evaluated input, it must be a character matrix

`⎕⍳⍨s` replace every element of  with its index in `s`

`a←` assign to `a`

`5=` return a boolean matrix of where the `+`-es are in `a` (`s[5]` is `'+'`)

`(⊢×¯1*+⍀++\)` this is a train of functions:

* `+\` matrix of partial sums by row
* `+` plus
* `+⍀` matrix of partial sums by column
* `¯1*` negative one to the power of - turn odds into ¯1 and evens into 1
* `⊢×` multiply by the train's argument - zero out everything except box corners

`+⍀+\` partial sums by column of partial sums by row

`5⌊` minimum of that and 5

`5|` modulo 5

`a,¨` pair up the elements of `a` and of the current matrix

`0~¨⍨` remove 0 from the pairs

`⊃¨` first each of what's remaining

`s[ ]` use every element as an index in `s`

# Answer
> 0 votes
# C (gcc), ~~190~~ 179 bytes

-11 bytes thanks to ceilingcat

Fails if sizeof(int) \> 9, but then you can take solace in the fact that your computer is from the future.

```
l;*H,*h,d;f(S){h=H=calloc(l=index(S,10)-S,9);for(char*s=S;*s;s++)h=*s^10?h:H-1,d=*s-43?d:s!=S&s[-1]==45|s-S>l&s[~l]=='|'?-1:1,*h+=*s^45?0:d,h+=write(1,*s^32|*h>4?s:" #=-."+*h,1);}

```

Try it online!

# Answer
> 0 votes
# \>\<\>, ~~118 115~~ 87 bytes

```
]0{i:0(?;:"-"=?\:"+"=?\:" "=?\$3l$g+}:ob(?
~$?:g2.10p1+4f:<p3l+10/.16@:$/>.!0"#"$
 #=-.

```

Try it online!

~~If one of the symbols wasn't a `-` then this could be 6 bytes shorter.~~ Eh, made it a ~~bit~~ lot smaller anyway

### How It Works:

```
] Resets the stack
 0{ Pushes a 0 and rotates the stack
    If the stack is empty, this initialises 0 as the counter
    Otherwise it adds an extra 0 to the stack and pushes the counter to the top
   i:0(?; Gets input and ends if it is EOF
         :"-"=?\ If the inputted character is a -
         p1+4f:< Put a - at cell (19, 1)
      .10        And skip to the end of this line

         :"+"=?\ Else if the inputted character is +
            ?10/ Generate either -1 or 1, depending on what was last put into cell (19,1)
                 The question mark represents cell (19,1), which is either + or -
         p3l     Put this number on (3, length of the stack)
.10p1+4f:<       Repeat the exact same code as with the -, except we put a + at cell (19,1)
         :" "=?\ Else if the character is a space
            @:$/ Create a copy of the counter
         .16     Skip to cell (1,6)
      g2         Get the cell (2, counter) (the  #=-.)
   ~$?           If that cell is a zero, pop it, leaving the initial space.
                 Else pop the space, leaving the fetched character
        Else if the character is a | or a newline
        $3l$g+   Get the cell at (3, length of the stack) and add it to the counter
    For everything but the last else, we are at the end of the second line
       >.!0"#"$ Skip to the 35th instruction on the first line

 } Push the counter to the bottom of the stack
  :o Output the current character
    b(? If the character is smaller than 11 (a newline)
 ]          Skip the clear stack at the start of the line
 Repeat this until EOF

```

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


title: Deranged Rearrangements

text:
# Question
Title: Deranged Rearrangements
Your task is to write a computer program such that when it is cut up into lines (split on the newline character) every arrangement of the lines will output a different number between **1** and **n!** (where **n** is the total number of lines). No number should be output by two different arrangements and every arrangement should output a number on this range. Since there are **n!** ways to arrange the lines of a program this means each number should be output by one rearrangement.

For example the python program

```
print 1;"""
print 2;"""

```

Has two arrangements

```
print 1;"""
print 2;"""

```

and

```
print 2;"""
print 1;"""

```

The first outputs `1` and the second outputs `2`.

You may use whatever output formats are standard in the language you are using. You may not assume any sort of boilerplate. I think this challenge is more interesting if you have to work around whatever formats the language insists on.

## Scoring

Your score will be the number of lines in your program with a higher score being better. You may choose to output numbers from **0** to **n!-1** if you would like.

# Answer
## CJam, score: ∞

Each line is of the form

```
];Lx+:L{__(f<0+:+\,,(;1+:**\(;}h]:+

```

where `x` is a number from `0` to `n-1`. The result is in the range `0` to `n!-1`.

Try it online! (For `n=3`.)

Credits to jimmy23013 for the code that computes the actual permutation index. I've only replaced the bit that reads the input with `];Lx+:L` which discards the result from the previous line and then adds the index of the current line to the variable `L` (which is initially an empty array).
> 7 votes

# Answer
# Perl: ∞

```
$z.="-1,";$_.=A;END{$m.=!!s/./{${z}B}/g,map(/B/||s/\d+\K/,/g*/(-\d*,).*\1/||($n{$_}||=$m++),sort glob),print$n{$z}if/A/}
$z.="-2,";$_.=A;END{$m.=!!s/./{${z}B}/g,map(/B/||s/\d+\K/,/g*/(-\d*,).*\1/||($n{$_}||=$m++),sort glob),print$n{$z}if/A/}
$z.="-3,";$_.=A;END{$m.=!!s/./{${z}B}/g,map(/B/||s/\d+\K/,/g*/(-\d*,).*\1/||($n{$_}||=$m++),sort glob),print$n{$z}if/A/}

```

Extend to any length you like

Will quickly run out of memory since memory usage is like O(n^n). It would however be easy to replace the permutation indexer by O(n) code, just longer. I'm just illustrating the way you can use `END{}` for this task in perl. All `END{}` blocks run at exit time, but only the first one that get called (the one last in the code) will output anything due to the `/A/` test which is only true once

Notice that the `$m` counter must count as a string because as a number it would overflow (later than the end of the universe but it's the principle that counts). For the same reason I "count" the number of lines by constructing a string of `A`s instead of using a real counter though this overflow would happen even later.

Another way to do this in perl:

```
@{$b.=A; if($a eq $b) {use bigint; $n=0;$n++for@F;$c=0;$c=$c*$n--+map{$z=$_;$a=grep$_&&$_>$z,@F;$_=0;}@F;print$c}}=()x push@F,"1".!($a.=A),
@{$b.=A; if($a eq $b) {use bigint; $n=0;$n++for@F;$c=0;$c=$c*$n--+map{$z=$_;$a=grep$_&&$_>$z,@F;$_=0;}@F;print$c}}=()x push@F,"2".!($a.=A),
@{$b.=A; if($a eq $b) {use bigint; $n=0;$n++for@F;$c=0;$c=$c*$n--+map{$z=$_;$a=grep$_&&$_>$z,@F;$_=0;}@F;print$c}}=()x push@F,"3".!($a.=A),

```

This uses that fact that in `foo = bar` `bar` is executed after `foo`. This version by the way doesn't go crazy in time and space but that makes the code longer

Yet another idea is to use `DESTROY` which has the advantage that only one of them will be executed. I'm not going to repeat the permutation indexing code of which I already gave two examples.

```
push@F,"1";bless\@F;DESTROY{print"Work out permutation index of @{$_[0]}\n" }
push@F,"2";bless\@F;DESTROY{print"Work out permutation index of @{$_[0]}\n" }
push@F,"3";bless\@F;DESTROY{print"Work out permutation index of @{$_[0]}\n" }

```

Or using `BEGIN`:

```
BEGIN{push@F,"1"} print"Work out permutation index of @F\n"; exit;
BEGIN{push@F,"2"} print"Work out permutation index of @F\n"; exit;
BEGIN{push@F,"3"} print"Work out permutation index of @F\n"; exit;

```
> 4 votes

# Answer
# Jelly, ∞

```
;3ÇQŒ¿$⁼Q$?
;2ÇQŒ¿$⁼Q$?
;1ÇQŒ¿$⁼Q$?

```

(Example with `n=3`.)

Try it online!

~~23~~ ~~13~~ 11 bytes per line.

For a program with `n` lines, the lines will have the format

`;` `<i>` `ÇQŒ¿$⁼Q$?`

where `<i>` represents the number literal `i` and each line has a different value for `i` ranging from `1` to `n`. (The values for `i` don't actually have to be these specific numbers, they just have to have unique positive values.) This program no longer uses `n` in the line structure.

**How?**

* Without an argument Jelly starts with `0`.
* `;1` appends `1` to `0` or the active list.
* `⁼Q$` is the conditional monad for the if statement (`?`) that checks whether the list's elements are unique. If they are, the link above is called (`Ç`) and another number is appended to the list. If they are not unique, that means we have wrapped around to the first link. The repeated element is removed from the list (`Q`) and the index of the permutation is found (`Œ¿`). Note that there is a `0` at the beginning of the list when `Œ¿` is taken but it does not affect the output since the values for `i` are all positive.

### New Jelly feature

With the newly added `Ƒ` quick, we can reduce `⁼Q$` to , saving a byte.

**10 bytes/line** (for single digits)

```
;1ÇQŒ¿$QƑ?

```

Try it online!
> 3 votes

# Answer
# Brain-Flak, 3

```
(({}){})
({}())
(()(){([()()]{})()(){[()()](<{}>)}}{})

```

Try it online!

I posted this in chat earlier but hopefully by posting it here people can build off of it.

## Explanation

We start with the basic program

```
(({}){})
({}())

```

This scores 2 on its own. In order to step up to the next level I want to add a new line. My begining guess was

```
(()(){[()()]{}(<()>)}{})

```

This sets the TOS to `2` if it it is zero and does nothing otherwise. This actually is a good start. With the other two lines we are able to get all the numbers from `1` to `6` except `4`, because there are `2` ways to output `2`:

```
({}())
(({}){})
(()(){[()()]{}(<()>)}{})

```

and

```
({}())
(()(){[()()]{}(<()>)}{})
(({}){})

```

In order to remedy this we make our line also set `2` to be `4`. This can be done with

```
(()(){([()()]{})()(){[()()](<{}>)}}{})

```

For clarity this basically implements the Haskell function

```
f 0 = 2
f 2 = 4
f x = x

```

This fixes our problem because one of the programs that was previously outputting `2` now outputs `4` with no other program changing.
> 2 votes

# Answer
# Java 7, score: ∞

```
public class DerangedRearrangements implements B{public void a(){System.out.println("0");}public static void main(String[]a)throws Exception{java.util.regex.Pattern p=java.util.regex.Pattern.compile("^(?:public )?class ([\\w]+).*");java.io.BufferedReader r=new java.io.BufferedReader(new java.io.FileReader("./DerangedRearrangements.java"));String line; while((line=r.readLine())!=null){java.util.regex.Matcher m=p.matcher(line);if(m.matches()){((B)Class.forName(m.group(1)).getDeclaredConstructor().newInstance()).a();}}}}interface B{void a();}
class b1 implements B{public void a(){System.out.println(getClass().getName().substring(1));}}

```

Try it online!

This is can print out **0** to **n!-1**. Additional lines are of the following format (where INDEX is a number from **1** to **n!-1**):

```
class b<INDEX> implements B{public void a(){System.out.println(getClass().getName().substring(1));}}

```

This method works by reading its own source in order to determine the order classes are listed in it. Unfortunately there was no cooler method I could find by parsing the compiled file or creating a custom ClassLoader thanks to how java does JIT compilation. I suppose I could have each additional class just print out a statically defined number but this seemed more fun. That would also make it so I could remove the `B` interface but the scoring isn't based on bytes so I'll leave that in for fun.

### How it works (high level):

Reads its own source code line by line. Since each line declares a new class, we use reflection to create an instance of the new class and invoke it's `a` method which it needs to have because it implements the `B` interface.
> 2 votes

# Answer
# Ruby, score: ∞

```
(a||=[])<<2;a.size<3?0:(p 1+a.sort.permutation.to_a.index(a))
(a||=[])<<1;a.size<3?0:(p 1+a.sort.permutation.to_a.index(a))
(a||=[])<<3;a.size<3?0:(p 1+a.sort.permutation.to_a.index(a))

```

Try it online!

This program has 61 bytes per line (for n\<10). It has the same basic format as dylnan's solution; the first number in each line will be a different value between `1` and `n`, and the second number in each line will be `n`.

I was hoping to find a way to avoid including `n` in the program, but I couldn't find one.
> 1 votes

# Answer
# Brain-Flak, 2 (with `-d`)

```
{}(@ltN)

```

Try it online!
> 1 votes

# Answer
# 05AB1E, score: 1,114,112

```
0ˆ¯JD{œsk
1ˆ¯JD{œsk
2ˆ¯JD{œsk

```

Try it online! 0-indexed. The ˆ at the start of each line pushes the distinct characters to the global array. The rest of the code is uselessly executed except on the last line, where it concatenates the values into a string, then finds its permutation index. 1,114,112 is the number of possible Unicode characters at time of writing (code points 48-57 are the easiest to demonstrate with of course).
> 0 votes

---
Tags: code-challenge, combinatorics, permutations, source-layout
---