title: Quine Anagrams! (Cops' Thread)

text:
# Question
Title: Quine Anagrams! (Cops' Thread)
This is the cops' thread. For the robbers' thread, click here.

### Cops' Task

* First, write a quine in a language of your choosing.
* Next, scramble the quine. Make sure to do this well as the robbers will be trying to unscramble it and find the original source code! Note that the scrambled code does not need to work.
* Post an answer on this thread. Include the language, the byte count, and the scrambled code.

Your program may not print to STDERR.

Here is an example of a cop submission:

> # Python, 29 bytes
>
> ```
> nt _%=_r;_riinp;pr_='t _%%%_'
>
> ```

### Robbers' Task

For the robbers' thread, click here.

### Safe Submissions

If your submission has not yet been cracked after a week of posting, you may add the solution and specify that it is safe. If you do not, your submission may still be cracked.

### Scoring

This is , so the user with the safe submission with the fewest bytes will be the winner of this section.

### Leaderboard

Here is a stack snippet to generate a learderboard for this challenge. For it to display properly, please format your submission like this:

```
# Language Name, N bytes

... other stuff ...

```

If your submission gets cracked, please format like this:

```
# Language Name, N bytes, [Cracked!](link)

... other stuff ...

```

If your submission is safe, format like this:

```
# Language Name, N bytes, Safe!

... other stuff ...

```

```
<script>site = 'meta.codegolf'; postID = 5686; isAnswer = false; QUESTION_ID = 99469;</script><script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>jQuery(function(){var u='https://api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)</code></pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script>
```

# Answer
# C#, 288 bytes

```
Stag is a great shoW.        "="=""="="Agent"plastic"Was"tryin"to"Release"an"Astroid"."$Money$"st@le"tigers"and"Agent"plastic"got"mad"."$Money$"sic","man","t0tally"rad"."Sistrs"Rms"titAnic";"Civic"Ace"in"{sC@m}{hic}{vicis}..{cats}sAc}((@))((@)){{{>>{{{{{{}}}}}}}}}\\\\\\\;;;(@)((@)()),,;;

```

My strategy is for all the short ones to get cracked and nobody bothers with this considering how long it is... Also I suppose I should note that this is a full program, not just a function.
> 14 votes

# Answer
# JavaScript, 1574 bytes, Safe!

I spent way too much time on this. Behold the obfuscation.

```
(notice that an unmatch parenthesis remains throughout the entire text.

dear "sir",

|    i cannot express my loathing to you and your things. they truly are a loathsome sight. (regar'less of their quality, they function as the most appalling devices...)[1]

|    these avocads of thine possession are most unpleasent. (ce n'est pas faux.) Queer; Careful; An' in total repulsing. in this form, those are not seulement cringe... So; CAB's is quite Cruel. (Cruel indeed...)

|    intention is not great (heh, intention, ;}) run, no, run, since {tu est le ;AqC;};

{{{{============================================}}}}

[1]: see? am i not insane? You may dictate the opposite, so i dictate thus.

9 + 4 is 13. Y is this. Y + 4 is 9 + 9 minus one. N is this. f(x) is {x + x}, so f(N) is N plus N is N + N is 3.

:^) i'm cruel; not so cruel.)
                                  rrrrrrrrrr 0nnnccnnggrrrrttssBBC
{({[}(<[<))(((((){{})}[}][[]{}(]))))|} f f r 0nnnccnngrrrrrttesBBA
())(((()))))()))()()()((((()))}{{})((} f f r 0nnnccnngrrrrrttesBBY
]]}(([][]{{{}}})()({}(){}{()}{}()[])][ f f r 4nnnccnngrrrrrttesBSY
))({})(}{)({{{{(()))())))))))()))()()( f f r 4nnnccnngrrrrrtpesqSY
)()()((((((((((Z))))))))()(()((()((((( f f r 5nnnccnngrrrrrtlefoSY
(((;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;''' f f r 3nnncccngrrrrxtleifSY
''''''''''''''''''',,,,,,,,[[[[[[]]]]] f f r 3nnncccngrrrrxtleifZQ
[ ] ] + + + + + + + + + + + + + + + ++ f f r 9nnncccggrrrrxtleifZQ
+ + + + too not fun...fffffffffffffuuu f f r 5nnncccggrrrrxtlli0ZQ
uuuuuuuuuuuu.. | | | |99S            ) f f r 0nnncccggrrrrxxll01QQ

```

## Here's the original source!

> ```
> function Y(x){return x.charCodeAt()};
> function Q(x){return String.fromCharCode(x)};
> N=Array.prototype;
> function B(f,g,h){return function(){
>   return f(g.apply(h||this,arguments));
> }};
> function S(f,h){return function(){
>   return f.apply(h||this,N.reverse.call(arguments))}}
> function id(x){return x};
> function format(){
>   args = N.slice.call(arguments);
>   str = args.shift(); res = []+[];
>   for(i = 0; i < str.length; i++){
>     c = function(){return str[i]};
>     if(B(Y,c) == 95){
>       res += args.shift();
>     } else if(S(B)(c,Y)() == 94){
>       res += q = B(id,Q)(34);
>       res += args.shift();
>       res += q;
>     } else if(Y(c()) == 39){
>       i++;
>       res += c() == ([][0]+[])[1] ? Q(10) : []+[];
>     } else res += c();
>   }
>   return res;
> }
> console.log(format(Z="function Y(x){return x.charCodeAt()};'nfunction Q(x){return String.fromCharCode(x)};'nN=Array.prototype;'nfunction B(f,g,h){return function(){'n  return f(g.apply(h||this,arguments));'n}};'nfunction S(f,h){return function(){'n  return f.apply(h||this,N.reverse.call(arguments))}}'nfunction id(x){return x};'nfunction format(){'n  args = N.slice.call(arguments);'n  str = args.shift(); res = []+[];'n  for(i = 0; i < str.length; i++){'n    c = function(){return str[i]};'n    if(B(Y,c) == 95){'n      res += args.shift();'n    } else if(S(B)(c,Y)() == 94){'n      res += q = B(id,Q)(34);'n      res += args.shift();'n      res += q;'n    } else if(Y(c()) == 39){'n      i++;'n      res += c() == ([][0]+[])[1] ? Q(10) : []+[];'n    } else res += c();'n  }'n  return res;'n}'nconsole.log(format(Z=^,Z))",Z))
> ```
> 10 votes

# Answer
# MATL, 20 bytes. Cracked

```
It'D-whoLl&w#ck'f0Gz

```

Don't attempt to crack this. It'd wholly wack fogs.
> 9 votes

# Answer
## CJam, 39 bytes, Safe

!""$)+023345679:AEORYZZ\_```bbceeffimmz
</code></pre>

Solution:

> `")A!0z`eZOmRZ$Yei`E"_`\32fm95b67b43f+:c`
> Uses some base encoding for obfuscation. However, since the characters are all in ASCII I would have thought someone might be able to figure out `32fm95b??b??f+:c` which would be enough to brute force the rest.
> 5 votes

# Answer
# Underload, 20 bytes, Cracked!

```
~*)(a):*(*a:S(*S*~S)

```

I scrambled this via randomizing the order of the characters, because what could be more scrambled than random?

A correctly written Underload interpreter crashes when seeing a newline at the top level of the program. As usual in golfing competitions, there's no newline at the end of the program; I'm just placing this reminder here because it's very easy to add one by mistake when copying the program to an interpreter.
> 5 votes

# Answer
## Retina, 20 bytes, Cracked

```
S`(\?)\1*

S`(\?)\1*

```

The program (and output) contains exactly two linefeeds.

You can try Retina online here.

A small hint:

> In the process of designing this cop, I found a new shortest Retina quine, which I'll post to our quine challenge once this answer is either cracked or safe.
> 5 votes

# Answer
# Pyth, 38 bytes, Safe

Not quite golfed, but works.

<pre><code>````::""@@@@++++22ggKKKKKKKKNNNNZZZZ

Unsorted version:

```
K"K++@KZ:`K@`NZNgK2"++@KZ:`K@`NZNgK2

```
> 4 votes

# Answer
# Python 2, 54 bytes, Cracked!

```
=l`;lrt,]l n`p,i=,' 1,1'lnt[ll[;,0  ]['r[`][`0'ipll] ]

```
> 3 votes

# Answer
# Vim, 22 bytes, Cracked!

```
pit^[^[p00tqqqq^V"ltxltx"

```

The `^[` are the literal escape key, and `^V` is `Ctrl-V`, and are therefore counted as one byte, and are kept together in the scrambled code.
> 3 votes

# Answer
# , 20 bytes -- Safe!

```
"$033lpqxx|áäéééñññ

```

Note the trailing newline.

I wasn't really sure how to scramble them, so I just sorted the characters by ASCII value.

Unlike most V answers, this one contains *zero* unprintable characters. Here is a hexdump:

```
0000000: 2224 3033 336c 7071 7878 7ce1 e4e9 e9e9  "$033lpqxx|.....
0000010: f1f1 f10a                                ....

```

# Unscrambled code:

```
éññ3äl0éé$áx3|"qpñx

```

Try it online!

Side not about this link. In previous versions of V, a newline was always automatically printed, which is why this version has the trailing newline. The interpreter at the time I wrote this was a valid quine, although now you can just remove the newline to make it valid.

Explanation:

```
éñ                      " Insert a 'ñ' character
  ñ              ñ      " Put all of the following into register 'q' and run it when it's done recording
   3äl                  " Make 3 copies of the character under the cursor
      0                 " Move to the first column
       éé               " Insert an 'é' character
         $              " Move to the last column
          áx            " Append an 'x'
            3|          " Move to the third column
              "qp       " Paste register 'q' (all of the commands we just ran)
                  x     " Delete a character

```
> 3 votes

# Answer
# Haskell, 86 bytes, cracked by nimi

```
putStr$"Study:ric====>>>>yummy:candy:circus:party:in:syrirrr!!!!!!$[;['=['[$]']='];]$"

```

This a valid Haskell expression which prints:

```
Study:ric====>>>>yummy:candy:circus:party:in:syrirrr!!!!!!$[;['=['[$]']='];]$

```

So if Ric studies, he can go to the yummy candy circus party! That is, if he figures out where *Syrirrr* is.
> 3 votes

# Answer
# JavaScript, 147 bytes, Cracked by ETHProductions

I'll be very impressed if someone manages to crack this...

   """"''''((((()))))+++++++++.//99;;;;;;=========>>[[[[[]]]]]``````````````cccdddddddeeeeeeeeeeeffiiiiiiinnnnnnnoooooooorrrrrrrrsttttuuwwwwwwx{{}}

### Intended solution:

e=o=>{n=o;``[r=`constructor`][r](`return e=>{`+o+`}`)````};d=e+"";e`for(i in window)if(/ert/.exec(i))w=window[i];w('e='+d+';d=e+"";e'+d[9]+n+d[9])`
</code></pre>
> 3 votes

# Answer
# Haskell, 99 bytes, Safe

```
"super.quine?"=>#$$$%%%%%&&(())))**++++,,,,/;<<==>>STaabbdeffggghhhjlmmnoppqqrrsssttttuuuvvwwwwxxxx

```

Another Haskell quine, this time with a nice odd 99 bytes.

> ```
> g%w=(g< $ >w)++w++pure(g.last$w);main=putStr$pred%"h&x>)h=%?x*,,x,,qvsf)h/mbtu%x*qvuTus%qsfe&#"
> ```
> Try it on Ideone. The spaces in "g\< $ \>w" must be removed, I put them there because otherwise the \<,$, and \> vanish (most likely being interpreted as html tag). The gibberish string is a string of the program with each char mapped to it's successor, including a final `"` (which is possible to include into the string without escaping because it's mapped to `#`). The helper function `%` takes the string and maps each char to it's predecessor using `pred` (yielding `code"`), then appends the original string (yielding `code"gibberish_code`) and the last char of the decoded string (yielding `code"gibberish_code"`). To convert a char `c` to a string it would normally suffice to put it into a list `[c]` as strings in Haskell are simply char lists, however the successor of `[` is `\`, which would need escaping in the successor-encoded string, so instead `pure` is used which lifts arbitrary types into a Monad (which Monad to use is inferred from the context).
> 3 votes

# Answer
# PHP, 110 bytes, Cracked

```
php$=))$)<9 php .(().)'heroes ?  $0(9carrot3?$;<.()trash3,.((3=)catarrh$$9 (,'9cry(3);  ;;tryccchhhrrrrxxxxxx

```
> 2 votes

# Answer
# Javascript ES6, 49 bytes (cracked)

```
{{$((((((('`fuck rent =+> turn off fin`')))))))}}

```

Is it bad if I focused more on forming coherent words in the scrambled solution?

In any case, this is my first Cops and Robbers challenge.

**Update**: see comments for cracked code.
> 1 votes

# Answer
# FurryScript, 199 bytes, Safe!

```
UT  TTEDU DT   T U T D   ES DGT GEL L   GL
-<<<<<<+++++++[[[[#BESTQUINEEVER!#BESTQUINEEVER!#BESTQUINEEVER!#BESTQUINEEVER!#BESTQUINEEVER!#]]]]+++++++>>>>>>-

X   XG WPW   SS  X  PW S US WWTLWP  XS  PE

```

Should be fairly easy to crack.

# Unscrambled Code

```
BESTQUINE[ DUP LT +SW +GT +< BESTQUINE#> ]
EVER![ DUP EX+ SW EX- LT +SW +GT +< EVER!#> ]
<BESTQUINE[ DUP LT +SW +GT +< BESTQUINE#> ]> BESTQUINE#
<EVER![ DUP EX+ SW EX- LT +SW +GT +< EVER!#> ]> EVER!#

```

Just the regular quine, but with two subroutines and some more code to swap the strings.
> 1 votes

# Answer
# Vim, 17 bytes

```
<CR>""&(())::::\npps

```

The `<CR>` is Enter (`^M` or `^J`) in the input and an **added** newline in the output. It is **not** the implicit end of file newline (see `:help 'eol'`). The 17 bytes are what is added to an empty buffer. (Newlines in a text editor are weird; let me know if this isn't clear.)
> 1 votes

# Answer
# Python 2, 105 bytes, Cracked!

```
    ######%%%%''(((((((())))))))****--0011::::;;==@@@@@@@@@@[[[[]]]]aaaaaaggggggiiiiiiiinnpprrrrrrrrrtt~~

```

The other one was cracked, so this one is more difficult.

> ```
> print'To find the solution, get to work!'
> ```
> 0 votes

# Answer
# \>\<\>, 36 bytes, Cracked!

```
!!!'''***+...00002333:::;???dddforrr

```
> 0 votes

# Answer
# Befunge-93, 15 bytes, Cracked!

```
:::@#%+-_,<910g

```

Try it online!
> 0 votes

# Answer
## Ruby, 53 bytes - Cracked

```
**TEN sTupID,sTupID NET,"TIN"<22"DEN"<<It<DEtINDE\n\n

```

The `\n` are literal newlines.
> 0 votes

# Answer
## QB64, 89 bytes

```
(_+cad:effecs:fact), =+cred:scarf:attaccd?, =+eff4c3d:cars:craccd?, (_+csc:f4c3d:fact), "

```

Some salient points:

* The code will not work in QBasic: it uses QB64-specific features
* Syntax expansion is off
* No dollar signs and only one quotation mark
* "Poetry" would be a stretch, but it does rhyme
> 0 votes

# Answer
# Befunge-93, 24 bytes

I'm afraid this is a bit late, but I wanted to attempt one without the `g` command.

```
<<_:@00278899p,**++###>!

```

Try it online!
> 0 votes

# Answer
# OIL, 77 bytes, Safe

```
0
0
1
1
1
1
1
1
1
1
1
2
2
4
4
4
6
8
10
11
11
11
12
17
18
18
18
18
22
26
26
32

```

Good luck with that.

Solution, "commented" (remove comments before running or it won't work):

```
0 # nop twice
0
1 # copy element from cell 1 to 1 (so do nothing again)
1
1
4 # print what's in cell 1 (a zero)
1
11 # print a newline
4 # and the same thing again; printing zero and a newline
1
11
1 # copy what's in cell 2 (a 1) into cell 2
2
2
1 # copy what's in cell 12 (two lines before; a 2) into cell 18
12
18
10 # check if the value in the cell of the following line (starting with 2; we'll jump back here)
18 # (this is cell 18)
1 # is equal-ish to the one in cell 1 (a zero)
32 # if yes, jump somewhere
22 # otherwise jump one cell ahead
1 # copy what's currently in cell 18 (first a 2) into cell 26
18
26
4 # print cell 26
26
8 # increment cell 18
18
11 # print a newline
6 # and jump back to cell 17
17

```

So to summarize, it works by first printing two zeros, and then comparing every line starting with the third one with zero, and if it isn't zero, printing it, else exiting (since OIL reads zero from any empty/non-existent cell). Any variable lines contain the value they have when they are printed (since I'm lazy, I obtained this by first making a near-quine where those cells have some arbitrary non-zero value, and using the result, which is a quine).
> 0 votes

# Answer
# Jelly, 3 bytes, Cracked!

```
Ṙ”Ṙ

```

Try it online!

Here is the solution:

> What, you want the solution? Find it!
> -2 votes

---
Tags: code-golf, quine, cops-and-robbers, permutations
---


title: Chebyshev Rotation

text:
# Question
Title: Chebyshev Rotation
Consider a regular grid, where each cell has integer coordinates. We can group the cells into (square-shaped) "rings" where the cells in each ring have the same Chebyshev distance (or chessboard distance) from the origin. Your task is to take such a cell coordinate and rotate that cell by one position counter-clockwise within its ring. This implements the following mapping:

So for example if the input is `(3, -2)` you should output `(3, -1)`. Note that `(0, 0)` is the only input that should map to itself.

## Rules

The I/O format is fairly flexible. You can use two individual numbers, a pair/list/array/tuple of numbers, a single complex number, a string containing two numbers, etc.

You may assume that `-128 < x,y < 128`.

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

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

This is , so the shortest valid answer – measured in *bytes* – wins.

## Test Cases

```
(0, 0)       => (0, 0)
(1, 0)       => (1, 1)
(1, 1)       => (0, 1)
(0, 1)       => (-1, 1)
(-1, 1)      => (-1, 0)
(-1, 0)      => (-1, -1)
(-1, -1)     => (0, -1)
(0, -1)      => (1, -1)
(1, -1)      => (1, 0)
(95, -12)    => (95, -11)
(127, 127)   => (126, 127)
(-2, 101)    => (-3, 101)
(-65, 65)    => (-65, 64)
(-127, 42)   => (-127, 41)
(-9, -9)     => (-8, -9)
(126, -127)  => (127, -127)
(105, -105)  => (105, -104)

```

# Answer
## JavaScript (ES6), ~~60~~ 59 bytes

Takes input with currying syntax `(x)(y)` and returns an array `[new_x, new_y]`.

```
x=>y=>(x|y&&((z=x+(y<0))>-y?z>y?y++:x--:z>y?x++:y--),[x,y])

```

### How it works

Our main task is to determine in which quadrant we are, so that we know in which direction to move.

We can use this formula as a first approximation:

```
x > -y ? (x > y ? 0 : 1) : (x > y ? 2 : 3)

```

Here is what we get:

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

```

Almost there. But the bottom left and bottom right corners of the rings are invalid. We need to shift the lower half of the matrix by one position to the left, so we define `z` as:

```
z = y < 0 ? x + 1 : x

```

And we replace `x` with `z` in our formula:

```
z > -y ? (z > y ? 0 : 1) : (z > y ? 2 : 3)

```

Which leads to:

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

```

The whole matrix is now correct, except for the special case `[0, 0]` (no move at all) which must be addressed separately.

### Test cases

```
let f =

x=>y=>(x|y&&((z=x+(y<0))>-y?z>y?y++:x--:z>y?x++:y--),[x,y])

console.log(f(0)(0));       // => (0, 0)
console.log(f(1)(0));       // => (1, 1)
console.log(f(1)(1));       // => (0, 1)
console.log(f(0)(1));       // => (-1, 1)
console.log(f(-1)(1));      // => (-1, 0)
console.log(f(-1)(0));      // => (-1, -1)
console.log(f(-1)(-1));     // => (0, -1)
console.log(f(0)(-1));      // => (1, -1)
console.log(f(1)(-1));      // => (1, 0)
console.log(f(95)(-12));    // => (95, -11)
console.log(f(127)(127));   // => (126, 127)
console.log(f(-2)(101));    // => (-3, 101)
console.log(f(-65)(65));    // => (-65, 64)
console.log(f(-127)(42));   // => (-127, 41)
console.log(f(-9)(-9));     // => (-8, -9)
console.log(f(126)(-127));  // => (127, -127)
console.log(f(105)(-105));  // => (105, -104)
```
> 16 votes

# Answer
# Jelly, ~~20~~ ~~14~~ 12 bytes

```
S;IṠN0n/¦Ạ¡+

```

Input and output are in form of arrays. Try it online! or verify all test cases.

### Background

To figure out in which direction we have to move, we can observe the relative position of the start point to the quadrant bisectors **x + y = 0** (blue) and **x - y = 0** (red).

* The origin is fixed. We advance by adding **\[0, 0\]** to the start point.
* Points in the topmost triangle – including the bisector of the first quadrant – have positive sum and non-negative delta (**y - x**). We advance by adding **\[-1, 0\]** to the start point.
* Points in the leftmost triangle – including the bisector of the second quadrant – have non-positive sum and positive delta. We advance by adding **\[0, -1\]** to the start point.
* Points in the bottommost triangle – including the bisector of the third quadrant – have negative sum and non-positive delta. We advance by adding **\[1, 0\]** to the start point.
* Points in the rightmost triangle – including the bisector of the fourth quadrant – have non-negative sum and negative delta. We advance by adding **\[0, 1\]** to the start point.

To figure out the correct direction, we compute **\[-sign(x + y), -sign(y - x)\]**, which has only nine possible outcomes.

The following table illustrates which outcomes have to get mapped to which directions.

```
    sign(x+y) |  sign(y-x) | -sign(x+y) | -sign(y-x) |     Δx     |     Δy
  ------------+------------+------------+------------+------------+------------
        0     |      0     |      0     |      0     |      0     |      0
        1     |      0     |     -1     |      0     |     -1     |      0
        1     |      1     |     -1     |     -1     |     -1     |      0
        0     |      1     |      0     |     -1     |      0     |     -1
       -1     |      1     |      1     |     -1     |      0     |     -1
       -1     |      0     |      1     |      0     |      1     |      0
       -1     |     -1     |      1     |      1     |      1     |      0
        0     |     -1     |      0     |      1     |      0     |      1
        1     |     -1     |     -1     |      1     |      0     |      1

```

This leaves three cases.

* If at least one of the signs is **0**, **\[Δx, Δy\] = \[-sign(x+y), -sign(y-x)\]**.
* If the signs are equal and non-zero, **\[Δx, Δy\] = \[-sign(x+y), 0\]**.
* If the signs are different and non-zero, **\[Δx, Δy\] = \[0, -sign(y-x)\]**.

### How it works

```
S;IṠN0n/¦Ạ¡+  Main link. Argument: [x, y] (pair of integers)

S             Sum; compute x + y.
  I           Increments; compute [y - x].
 ;            Concatenate; yield [x + y, y - x].
   Ṡ          Sign; compute [sign(x + y), sign(y - x)].
    N         Negate; yield [-sign(x + y), -sign(y - x)].
          ¡   Do n times:
         Ạ      Set n to all([-sign(x + y), -sign(y - x)]), i.e., 1 if the signs
                are both non-zero and 0 otherwise.
        ¦       Conditional application:
      n/          Yield 1 if the signs are not equal, 0 if they are.
     0            Replace the coordinate at 1 or 0 with a 0.
              This returns [Δx, Δy].
           +  Add; yield  [Δx + x, Δy + y].

```
> 14 votes

# Answer
# Pyth, 19 bytes

```
&Q+^.jZ1.RhycPQ.n0Z

```

Try it online!

Translation of my Julia answer:

```
&Q                    If input is 0, then 0, else:
             PQ         Get phase of input
            c  .n0      Divide by π
           y            Double
          h             Add one
        .R        Z     Round to integer
   ^.jZ1                Raise i to this power
  +                     Add to input

```
> 5 votes

# Answer
## Python, 55 bytes

```
lambda x,y:(x-(-y<x<=y)+(y<=x<-y),y+(~x<y<x)-(x<y<=-x))

```

Detects the four diagonal quadrants, and shifts the appropriate coordinate.
> 5 votes

# Answer
# Haskell, ~~77~~ ~~71~~ 69 bytes

```
x#y|y>=x,-x<y=(x-1,y)|y>x=(x,y-1)|y< -x=(x+1,y)|y<x=(x,y+1)|1>0=(0,0)

```

This is just checking each of those tilted quadrants, and modifying the input accordingly. Note that the spaces are necessary, otherwise e.g. `>-` would be understood as an operator (which is not defined).

Thank you @nimi for removing a few more bytes!
> 4 votes

# Answer
# Ruby, 68

Lambda function takes complex number as argument, returns complex number.

```
->z{k=1
4.times{z*=?i.to_c
x,y=z.rect
y*y>=x*x&&y<-x&&(z+=k;k=0)}
z}

```

We rotate the point through 90 degrees 4 times by multiplying by `i`. It therefore passes through all 4 quadrants, and would be returned unchanged - except for the fact we modify it when it is in a specific one of them. The fact it is always modified in the same quadrant simplifies the modification.

It is easiest to follow if we alter it `z` when it is in the righthand quadrant. in this case we need to increase the y coordinate by 1 (i.e add `i` to `z`.)

We check `x.abs>=y.abs` by comparing the squares of `x` and `y`. This tells us the point is in the righthand or lefthand quadrant, not top or bottom. To check it is in fact in the righthand quadrant we further check that `x>y` (strictly greater because we want to exclude the case `x=y` which belongs to the "top" quadrant.) Where this is true we add `i` to `z`.

For golfing reasons, adding `i` is not desirable. Instead we modifiy the number when it is in the bottom quadrant, in which case we have to add 1 to the `x` coordinate (add 1 to `z`.) In this case we test that `y*y>=x*x` to check it is in the top or bottom quadrant. To further ensure it is in the bottom quadrant we need to check `y<-x` (strictly excluding the case of the bottom right corner where `y=-x`.)

An advantage of this check is there is no special case for the coordinate 0,0. Unfortunately it was found that moving the point can shift it to a different quadrant and this means that a second movement must be suppressed should that quadrant be checked again, which probably negates the advantage.

**Example 1**

```
Input                                        95,-12
Rotate 90deg                                 12,95
Rotate 90deg                                -95,12
Rotate 90deg                                -12,-95
Rotate 90deg                                 95,-12
y.abs>=x.abs=TRUE, y<-x=TRUE, increase x     95,-11

The check and alteration of the coordinate is done AFTER the rotation.
Thus in this case it gets done in the 4th iteration of the loop, not the 1st.
If the code were rewritten to do the check and alteration BEFORE the rotation,
it would be done in the 1st iteration instead of the 4th.

```

**Example 2**

```
Input                                        -1,0
Rotate 90deg                                  0,-1
y.abs>=x.abs=TRUE, y<-x=TRUE, increase x      1,-1
Rotate 90deg                                  1,1
Rotate 90deg                                  1,-1
Rotate 90deg                                 -1,-1
y.abs>=x.abs?=TRUE, y<-x=TRUE but DO NOT CHANGE x!

This is an unusual situation due to the fact that the first move caused the
point to advance by one quadrant. We do NOT want to move it again, for this
reason we need to set k to 0 the first time it is moved.

```

**In test program**

```
f=->z{k=1                   #amount to be added to coordinate
4.times{z*=?i.to_c          #iterate 4 times, rotating point by 90deg till it reaches the original orientation
x,y=z.rect                  #separate out x and y for testing
y*y>=x*x&&y<-x&&(z+=k;k=0)} #if y.abs>=x.abs and y negative and not equal -x, move the point and zero k.
z}                          #return z

puts f[Complex(0, 0)]       # (0, 0)
puts f[Complex(1, 0)]       # (1, 1)
puts f[Complex(1, 1)]       # (0, 1)
puts f[Complex(0, 1)]       # (-1, 1)
puts f[Complex(-1, 1)]      # (-1, 0)
puts
puts f[Complex(-1, 0)]      # (-1, -1)
puts f[Complex(-1, -1)]     # (0, -1)
puts f[Complex(0, -1)]      # (1, -1)
puts f[Complex(1, -1)]      # (1, 0)
puts f[Complex(95, -12)]    # (95, -11)
puts f[Complex(127, 127)]   # (126, 127)
puts
puts f[Complex(-2, 101)]    # (-3, 101)
puts f[Complex(-65, 65)]    # (-65, 64)
puts f[Complex(-127, 42)]   # (-127, 41)
puts f[Complex(-9, -9)]     # (-8, -9)
puts f[Complex(126, -127)]  # (127, -127)
puts f[Complex(105, -105)]  # (105, -104)

```

**Diagram**

The following image shows (blue) the area where `x*x>=y*y`, (yellow) the area where `y<-x` and (green) the intersection of these, which is the region where the correct transformation is the addition of 1 to `z`.
> 4 votes

# Answer
## Python, 52 bytes

```
h=lambda z:z and 1j*h(z/1j)if'-'in`z*1j-z-1`else z+1

```

Complex input and output. To test the point for being in the lower diagonal quadrant, first rotate it 135 counterclockwise to move that quadrant to the (x\>0, y\>0) standard quadrant, and test if the result has no minus symbol in the string representation. Subtracting 1 first takes care of the boundary condition.

If it's not in that quadrant, rotate the whole problem 90 degrees. The input is zero is specially handled to output itself.

Other attempts with complex numbers:

```
## 56 bytes
## Coordinate input, complex output
q=lambda x,y:(y<=x<-y)*(1j*y-~x)or x+1j*y and 1j*q(y,-x)

## 60 bytes
h=lambda z:(z+1)*(z.imag<=z.real<-z.imag)or z and 1j*h(z/1j)

## 63 bytes
from cmath import*
h=lambda z:z and 1j**(phase(z*1j-z)*2//pi)+z

```
> 4 votes

# Answer
# Julia, ~~38~~ 34 bytes

```
!z=z==0?0:z+im^int(2angle(z)/pi+1)

```

Dennis saved four bytes. Thanks!

Try it online!
> 3 votes

# Answer
## Mathematica, 34 bytes

```
±0=0
±z_:=z+I^Floor[2Arg@z/Pi+3/2]

```

This defines a unary operator `±` which takes and returns a complex number whose components represent `x` and `y`.

Now that Lynn has revealed the complex number solution and Dennis has beaten my score, I don't feel so bad for posting my golfed referenced implementation. :) (It turns out to be virtually identical to Lynn's answer.)
> 3 votes

# Answer
# MATL, ~~19~~ 17 bytes

```
t|?JGJq*X/EYP/k^+

```

This uses complex numbers as input and output.

Try it online! Or verify all test cases.

### Explanation

Let's take input `-127+42j` as an example.

```
t|       % Implicit input. Duplicate and take absolute value
         % STACK: -127+42j, 133.764718816286
?        % If nonzero
         % STACK: -127+42j
  J      %   Push j (imaginary unit)
         %   STACK: -127+42j, j
  GJq*   %   Push input multiplied by -1+j. This adds 3*pi/4 to the phase of the input
         %   STACK: -127+42j, j, 85-169i
  X/     %   Phase of complex number
         %   STACK: -127+42j, j, -1.10478465600433
  EYP/   %   Divide by pi/2
         %   STACK: -127+42j, j, -0.703327756220671
  k      %   Round towards minus infinity
         %   STACK: -127+42j, j, -1
  ^      %   Power
         %   STACK: -127+42j, -j
  +      %   Add
         %   STACK: -127+41j
         % Implicit end
         % Implicit display

```
> 3 votes

# Answer
# Ruby, 51 bytes

**Original form**

```
->x,y{d=x*x-y*y
[x+(d>0?0:-y<=>x),y+(d<0?0:x<=>y)]}

```

**Alternate form per Xnor's comment**

```
->x,y{[x+(x*x>y*y ?0:-y<=>x),y+(x*x<y*y ?0:x<=>y)]}

```

Uses the same type of inequalities as my other answer, but in a different way.

**In test program**

```
f=->x,y{d=x*x-y*y
[x+(d>0?0:-y<=>x), #if y.abs>=x.abs: x+=1 if -y>x, x-=1 if -y<x
y+(d<0?0:x<=>y)]}  #if x.abs>=y.abs: y+=1 if  x>y, y-=1 if  x<y

p f[0, 0]       # (0, 0)
p f[1, 0]       # (1, 1)
p f[1, 1]       # (0, 1)
p f[0, 1]       # (-1, 1)
p f[-1, 1]      # (-1, 0)
puts
p f[-1, 0]      # (-1, -1)
p f[-1, -1]     # (0, -1)
p f[0, -1]      # (1, -1)
p f[1, -1]      # (1, 0)
p f[95, -12]    # (95, -11)
p f[127, 127]   # (126, 127)
puts
p f[-2, 101]    # (-3, 101)
p f[-65, 65]    # (-65, 64)
p f[-127, 42]   # (-127, 41)
p f[-9, -9]     # (-8, -9)
p f[126, -12]   # (127, -127)
p f[105, -105]  # (105, -104)

```
> 3 votes

# Answer
# C++, 94 bytes

```
#define a(x) (x>0?x:-(x))
#define f(x,y) y>a(x-.5)?x--:-y>a(x+.5)?x++:x>a(y+.5)?y++:x|y?y--:x;

```

Ungolfed:

```
#define a(x) (x>0?x:-(x))  //shorter than std::abs from <cmath>
#define f(x,y)
    y>a(x-.5)?      // shift absolute value function by 0.5 to the right to get upper fourth
        x--:
        -y>a(x+.5)? //same for lower fourth
            x++:
            x>a(y+.5)? //same for right fourth
                y++:
                x|y? //only left fourth and 0 are left
                    y--:
                    x; //can't be empty, just does nothing

```

Usage:

```
#include <iostream>
void test(int x, int y, int rx, int ry){
    std::cout << "(" << x << ", " << y << ")=>";
    f(x,y);
    std::cout << "(" << x << ", " << y << ") - " << ((x==rx&&y==ry)?"OK":"FAILURE") << std::endl;
}

//Using the test cases from the question
int main() {
    test(0, 0, 0, 0);
    test(1, 0, 1, 1);
    test(1, 1, 0, 1);
    test(0, 1, -1, 1);
    test(-1, 1, -1, 0);
    test(-1, 0, -1, -1);
    test(-1, -1, 0, -1);
    test(0, -1, 1, -1);
    test(1, -1, 1, 0);
    test(95, -12, 95, -11);
    test(127, 127, 126, 127);
    test(-2, 101, -3, 101);
    test(-65, 65, -65, 64);
    test(-127, 42, -127, 41);
    test(-9, -9, -8, -9);
    test(126, -127, 127, -127);
    test(105, -105, 105, -104);

    return 0;
}

```

Try it online
> 2 votes

# Answer
## R, 131 110 bytes

A function that takes the two integers, `x,y` as inputs and writes the output to stdout. The solution follows @Dennis' control flow scheme but could probably be golfed.

EDIT: Updated code based on @JDL's suggestions and saved a bunch of bytes.

```
function(x,y){X=sign(x+y);Y=sign(y-x);if(!X|!Y){x=x-X;y=y-Y}else if(X==Y&X&Y)x=x-X else if(X-Y&X)y=y-Y;c(x,y)}

```

**Ungolfed**

```
f=function(x,y){
    X=sign(x+y)                 # calculate sign
    Y=sign(y-x)                 #  =||=
    if(!X|!Y){x=x-X;y=y-Y}      # if at least one is 0: subtract sign
    else if(X==Y&X&Y)x=x-X      # if signs are equal and non-zero: add sign to x
    else if(X-Y&X)y=y-Y         # if signs are not equal and non-zero: add sign to y
    c(x,y)                      # print to stdout
}

```
> 2 votes

# Answer
# JavaScript (ES6), 57 bytes (55–63†)

Accepts an \[x, y\] array, modifies it in-place, and returns it.

```
c=>([x,y]=c,i=x>y|x==y&x<0,c[i^x<-y|x==-y]-=-i|!!(x|y),c)

```

## How it works

```
c=>(

```

This is a single-parameter arrow function with a `return`-free concise body.

```
[x,y]=c

```

The parameter is immediately destructured into `x` and `y` variables.

```
,

```

The comma operator combines multiple expressions into one, using the result of the last.

```
i=x>y|x==y&x<0

```

`i` is used for differentiating increment and decrement cases. When `x` is greater than `y`, we are in either the bottom or right quadrant, and need to advance in one dimension (`i=1` by boolean-to-number coercion). Likewise when we are on the negative portion of the dividing **x = y** diagonal. In all other cases—including the origin—no increment is required (`i=0`).

```
c[i^x<-y|x==-y]

```

We use a somewhat similar expression for controlling which array index to adjust. When we are incrementing and not in the left or bottom quadrants (or when we are *not* incrementing and *in* the left or bottom), then the bitwise XOR will produce `1` and we will adjust the **y** value. Likewise for when we are on the dividing **x = -y** diagonal (including the origin). In all other cases, the index will be `0` (**x**).

```
-=-i|!!(x|y)

```

When `i` is `1`, we will add it to the specified value. When `i` is `0`, we will subtract 1 from the value *if and only if* we are not at the origin. The latter is detected by `x|y` yielding nonzero, clipped to {0, 1} by boolean coercion, and the negation of `i` allows us to use bitwise OR instead of logical (since `-1` has no zero bits, it is safe from modification).

```
c

```

The array is last, so it will be returned.

## Testing

```
let f =
    c=>([x,y]=c,i=x>y|x==y&x<0,c[i^x<-y|x==-y]-=-i|!!(x|y),c)

let cases = `
(0, 0)       => (0, 0)
(1, 0)       => (1, 1)
(1, 1)       => (0, 1)
(0, 1)       => (-1, 1)
(-1, 1)      => (-1, 0)
(-1, 0)      => (-1, -1)
(-1, -1)     => (0, -1)
(0, -1)      => (1, -1)
(1, -1)      => (1, 0)
(95, -12)    => (95, -11)
(127, 127)   => (126, 127)
(-2, 101)    => (-3, 101)
(-65, 65)    => (-65, 64)
(-127, 42)   => (-127, 41)
(-9, -9)     => (-8, -9)
(126, -127)  => (127, -127)
(105, -105)  => (105, -104)
`;

let failures = cases.trim().split("\n").filter(l => {
    const FAIL = true;
    let m = /.*?(-?\d+).*?(-?\d+).*?(-?\d+).*?(-?\d+)/.exec(l);
    if (!m) return FAIL;
    let [_, x, y, X, Y] = m;
    let [x2, y2] = f([+x, +y]);
    if (x2==X && y2==Y) return !FAIL;
    console.log("(%s) yielded (%s); expected (%s)", [x, y], [x2, y2], [X, Y]);
    return FAIL;
});
console.log("failures: " + failures.length);
// => failures: 0
```

## †Variations

We can save two more bytes by skipping a meaningful return value and using *only* the input mutation:

```
c=>([x,y]=c,i=x>y|x==y&x<0,c[i^x<-y|x==-y]-=-i|!!(x|y))

```

…or we can skip input mutation and make all variables local for a pure function, at the cost of six bytes:

```
([x,y],i=x>y|x==y&x<0,c=[x,y])=>(c[i^x<-y|x==-y]-=-i|!!(x|y),c)

```
> 2 votes

# Answer
## Racket 191 bytes

```
(cond[(= 0 x y)(list x y)][(= x y)(if(> x 0)(list(sub1 x)y)(list(add1 x)y))][(> x y)(if(>= x(abs y))
(list x(add1 y))(list(add1 x)y))][(< x y)(if(> y(abs x))(list(sub1 x)y)(list x(sub1 y)))])

```

Ungolfed (directly translating figure directions to code without using any intermediate formula):

```
(define(f x y)
  (cond
    [(= 0 x y) (list x y)]
    [(= x y)
     (if (> x 0)
         (list (sub1 x) y)   ; left
         (list (add1 x) y))] ; right
    [(> x y)
     (if (>= x (abs y))
         (list x (add1 y))   ; up
         (list (add1 x) y))] ; right
    [(< x y)
     (if (> y (abs x))
         (list (sub1 x) y)   ; left
         (list x (sub1 y)))] ; down
    ))

```

Testing:

```
(f 0  0)
(f 1  0)
(f 1  1)
(f 0  1)
(f -1  1)
(f -1  0)
(f -1  -1)
(f 0  -1)
(f 1  -1)
(f 95  -12)
(f 127  127)
(f -2  101)
(f -65  65)
(f -127  42)
(f -9  -9)
(f 126  -127)
(f 105  -105)

```

Output:

```
'(0 0)
'(1 1)
'(0 1)
'(-1 1)
'(-1 0)
'(-1 -1)
'(0 -1)
'(1 -1)
'(1 0)
'(95 -11)
'(126 127)
'(-3 101)
'(-65 64)
'(-127 41)
'(-8 -9)
'(127 -127)
'(105 -104)

```
> 1 votes

# Answer
## JavaScript (ES6), ~~80~~ 76 bytes

```
(x,y,s=Math.max(x,y,-x,-y))=>(s?x+s?y-s?x-s?x++:y++:x--:y+s?y--:x++:0,[x,y])

```
> 1 votes

# Answer
## Haskell, 53 bytes

```
0%0=(0,0)
x%y|y>=0-x,y<x=(x,y+1)|(p,q)<-(-y)%x=(q,-p)

```

Takes two numbers, outputs a tuple. If the point is in the east section `-x<=y<x`, increase the second coordinate by 1. Otherwise, cycle the quadrants by rotating the input point 90 degrees, calling the function on it, then rotating back.
> 1 votes

# Answer
# Actually, 16 bytes

This takes a complex number as input and outputs another complex number. Golfing suggestions welcome! Try it online!

```
;`₧╦@/τuLïⁿ+0`╬X

```

**Ungolfing**

```
         Implicit input z.
;        Duplicate z.
`...`╬   If z is non-zero (any a+bi except 0+0j), run the following function.
           Stack: z, z
  ₧        Get phase(z).
  ╦@/      Divide phase(z) by pi.
  τuL      Push floor(2*phase(z)/pi + 1).
  ïⁿ       Push 1j ** floor(2*phase(z)/pi + 1).
  +        And add it to z. This is our rotated z.
  0        Push 0 to end the function.
X        Discard either the duplicate (0+0j) or the 0 from the end of function.
         Implicit return.

```
> 1 votes

# Answer
# Scala, 184 bytes

```
val s=math.signum _
(x:Int,y:Int)=>{val m=x.abs max y.abs
if(x.abs==y.abs)if(s(x)==s(y))(x-s(x),y)else(x,y-s(y))else
if(x.abs==m)(x,y+Seq(0,x).indexOf(m))else(x-Seq(0,y).indexOf(m),y)}

```

### Ungolfed:

```
import math._

(x: Int, y: Int) => {
  val max = max(x.abs, y.abs)
  if (x.abs == y.abs)
    if (signum(x) == signum(y))
      (x - signum(x), y)
    else
      (x, y - signum(y))
  else
    if (x.abs == max)
      (x, y + Seq(0, x).indexOf(max))
    else
      (x - Seq(0, y).indexOf(max), y)
}

```

### Explanation:

```
val s=math.signum _             //define s as an alias to math.signum
(x:Int,y:Int)=>{                //define an anonymous function
  val m=x.abs max y.abs           //calculate the maximum of the absolute values,
                                  //which is 1 for the innermost circle and so on.
  if(x.abs==y.abs)                //if we have a cell at a corner of a circle
    if(s(x)==s(y))                  //if it's at the top-left or bottom-right, we need to
                                    //modify the x value
      (x-s(x),y)                      //if x is positive (bottom-right),
                                      //we need to return (x+1,y),
                                      //(x-1,y) If it's at the top-left.
                                      //This can be simplified to (x-s(x),y)
    else                            //for top-right and bottom-left,
      (x,y-s(y))                      //modify y in the same way.
  else                            //we don't have a corner piece
    if(x.abs==m)                    //if we're at the left or right edge of the square
      (x,y+Seq(0,x).indexOf(m))       //if it's a piece from the right edge, add one
                                      //to y, else subtract 1
    else                            //it's a piece from the top or bottm edge
      (x-Seq(0,y).indexOf(m),y)       //subtract 1 from x if it's from the top edge,
                                      //else subtract -1
}

```
> 0 votes

---
Tags: code-golf, geometry, grid
---


title: Figure and Ground

text:
# Question
Title: Figure and Ground
Source: Wikipedia

For this challenge, you should write two programs which resemble the figure and ground of the above image, such that one of them prints `figure` and the other prints `ground`. Specifically:

1. Write a program which takes no input and prints the string `figure`. The only allowed whitespace characters in your program are spaces (code point 0x20) and newlines (carriage returns, 0x0D, linefeeds, 0x0A, or a combination of both).
2. Ignoring the newlines, the number of space characters (code point 0x20) and non-space characters has to be the same. For example, this would be a valid program (in a hypothetical language):

```
ab c
   d
e f

```

Note that there is a trailing space on the first line.
3. If you swap the **n**th space character with the **n**th non-whitespace character, the program should print `ground` instead. For the above example the program would look like this:

```
  a b
cde
 f

```

Note that there are trailing spaces on the second and third lines.

Both the *figure* and the *ground* solutions should be full programs in the same language which print to STDOUT. You may print a single optional trailing newline in either case. You may output anything you want to STDERR, as long as STDOUT is correct.

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

This is , so the shortest valid answer – measured in *bytes* – wins.

## Helper Script

You can use this CJam script to convert between a *figure* and *ground* program. Simply paste one of the two into the *Input* field and run the program. It will also tell you if there the number of spaces and non-spaces doesn't match up.

## Leaderboard

```
function answersUrl(a){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+a+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(a,b){return"http://api.stackexchange.com/2.2/answers/"+b.join(";")+"/comments?page="+a+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(a){answers.push.apply(answers,a.items),answers_hash=[],answer_ids=[],a.items.forEach(function(a){a.comments=[];var b=+a.share_link.match(/\d+/);answer_ids.push(b),answers_hash[b]=a}),a.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(a){a.items.forEach(function(a){a.owner.user_id===OVERRIDE_USER&&answers_hash[a.post_id].comments.push(a)}),a.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(a){return a.owner.display_name}function process(){var a=[];answers.forEach(function(b){var c=b.body;b.comments.forEach(function(a){OVERRIDE_REG.test(a.body)&&(c="<h1>"+a.body.replace(OVERRIDE_REG,"")+"</h1>")});var d=c.match(SCORE_REG);d?a.push({user:getAuthorName(b),size:+d[2],language:d[1],link:b.share_link}):console.log(c)}),a.sort(function(a,b){var c=a.size,d=b.size;return c-d});var b={},c=1,d=null,e=1;a.forEach(function(a){a.size!=d&&(e=c),d=a.size,++c;var f=jQuery("#answer-template").html();f=f.replace("{{PLACE}}",e+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link),f=jQuery(f),jQuery("#answers").append(f);var g=a.language;g=jQuery("<a>"+g+"</a>").text(),b[g]=b[g]||{lang:a.language,lang_raw:g,user:a.user,size:a.size,link:a.link}});var f=[];for(var g in b)b.hasOwnProperty(g)&&f.push(b[g]);f.sort(function(a,b){return a.lang_raw.toLowerCase()>b.lang_raw.toLowerCase()?1:a.lang_raw.toLowerCase()<b.lang_raw.toLowerCase()?-1:0});for(var h=0;h<f.length;++h){var i=jQuery("#language-template").html(),g=f[h];i=i.replace("{{LANGUAGE}}",g.lang).replace("{{NAME}}",g.user).replace("{{SIZE}}",g.size).replace("{{LINK}}",g.link),i=jQuery(i),jQuery("#languages").append(i)}}var QUESTION_ID=101275,ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",OVERRIDE_USER=8478,answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:350px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"><div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table></div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table></div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody></table>
```

# Answer
> 20 votes
# Jelly, 20 bytes

### Figure

```
“¦ĠȮ“©ụd» Ṃ

```

Nine trailing spaces. Try it online!

### Ground

```
         “ ¦ĠȮ“©ụd»Ṃ

```

No trailing spaces. Try it online!

### How it works

First, note that spaces aren't atoms, so the space characters outside the string literals do not affect the program in any way.

The string literals use Jelly's built-in dictionary-based string compression to produce the desired words. A compressed string literal begins with , ends with `»`, and uses  internally to create an array of strings.

In the **figure** program, `“¦ĠȮ“©ụd»` yields the string pair **(“figure”, “ground”)**, and the atom  selects the lexicographical minimum, i.e., **“figure”**.

In the ground program, `“ ¦ĠȮ“©ụd»` yields the string pair **(“logicallyAbacs”, “ground”)** instead. The lexicographical minimum is now **“ground”**, which  selects dutifully.

In both cases, the interpreter automatically prints the last return value – i.e., the selected minimum – to STDOUT.

# Answer
> 14 votes
# 05AB1E, ~~15~~ 14 bytes

### **Figure**

```
 'ŠÂ,'í¶

```

Try it online!

### **Ground**

```
'       ŠÂ,'í¶

```

Try it online!

Uses the **CP-1252** encoding. Note the trailing spaces. In the **Figure** program, it's a normal program without errors. It decompresses the following words:

```
'ŠÂ  ->  figure
'í¶  ->  ground

```

The comma prints pops and prints the `figure`  word with a newline. Since something has been printed, the top of stack is not printed anymore.

In the **Ground** program, there are some errors which is convenient in this case. The following part:

```
'<space>

```

pushes a space character on top of the stack. The `Š` rotates the stack, which has an arity **3**. There is just one element on the stack and no input, so this gives an exception, clearing the stack. The `Â` bifurcates the top of the stack, but this has the same story as the rotate operator. So basically the `,` command prints nothing.

That means that the program will still output the top of the stack which is `'í¶`. Resulting into `ground`.

# Answer
> 14 votes
# Python 2, 53 bytes

Replace `·` with space in both answers:

```
····················
print'······figureground'[6:12]#

```

Prints `figure`.

```
print'figureground'[
······6:12]#····················

```

Prints `ground`.

# Answer
> 9 votes
# Retina, 31 bytes

### Figure:

```
|
figure
 |ground

```

### Ground:

```
 |figure

|
ground
```

Figure and Ground. Both programs require that STDIN be left empty to be valid figure or ground programs.

# Answer
> 9 votes
# Pyth, 30 bytes

### Figure

```
"figure" "ground

```

14 trailing spaces.

Test

### Ground

No trailing spaces

```
        "       figure""ground

```

Test

### How it works

Rather helpfully, a space supresses printing in Pyth, while string literals with no closing `"` are implicitly closed.

The first program therefore consists of two strings, `"figure"` and `"ground "`. The first string is implicitly printed, and the printing of the second is supressed, meaning that just `figure` is printed.

The second program consists of two strings, `" figure"` and `"ground"`. The printing of the first is supressed, and the second is implicitly printed, meaning that just `ground` is printed.

# Answer
> 6 votes
# MATL, 37 bytes

### First program

```
'figure'
%x'ground'

```

Each line has 9 trailing spaces.

Try it online!

### Second program

```
    'figure'%
      x'ground'

```

There are no traling spaces here.

Try it online!

### Explanation

Nothing terribly fancy...

* Spaces and newlines between statements are ignored by MATL.
* `%` is the comment symbol, which ignores the rest of the line.
* `x` deletes the top of the stack.
* The stack is implicitly printed at the end of the program.

# Answer
> 6 votes
## Java, 180 bytes

Replace `.` with space.

Prints "figure":

```
class
A{public
static
void
main(String[]a){System.out.println(
//"ground"
//
.....
........
......
....
...................................
..
........
..........
....
"figure");}}

```

Prints "ground":

```
.....
........
......
....
...................................
..........
..
class
A{public
static
void
main(String[]a){System.out.println(
//
"ground"
//"figure"
);}}
............

```

# Answer
> 5 votes
## Befunge, 54 bytes

**Figure** (Try it online!)

```
#v "erugif"v          >
      :#,_@>
"dnuorg"
```

Ten trailing spaces on the second line.

**Ground** (Try it online!)

```
  #         v"erugif"v
>:#,_@      >"dnuorg"

```

One trailing space on the first line and eight spaces on the third line.

# Answer
> 4 votes
# Mathematica, ~~50~~ 34 bytes

Uses a REPL environment. (Adding a `Print[]` wrapper with an equal number of spaces would increase the byte count by 14.) The two programs are

```
01figure+0 1ground

```

(with 16 trailing spaces) and

```
          0       1figure+01ground

```

The key here is that Mathematica treats digit concatentation without spaces as a single number, but intervening spaces are interpreted as neighborly multiplication, as is the concatenation of numbers and arbitrary variable names. So the first expression evaluates to `1*figure+0*1*ground`, which is `figure`; the second expression evaluates to `0*1*figure+1*ground`, which is `ground`.

# Answer
> 4 votes
# PHP, ~~44~~ 42 bytes

figure: (16 trailing spaces, 5 spaces between figure & ;)

```
echo''?ground:figure     ;

```

ground: (20 leading spaces)

```
                     echo' '?ground:figure;

```

Pretty simple really, works because `''` is falsey and `' '` is truthy. Use like:

```
php -r "echo''?ground:figure     ;                "
php -r "                    echo' '?ground:figure;"

```

edit: 2 retrospectively obvious bytes saved thanks to Martin Ender

# Answer
> 3 votes
# Haskell, ~~96~~ ~~94~~ ~~88~~ ~~82~~ 77 bytes

First program, prints `"figure"`:

```
main              =          putStr$idid"ground"
idid    _          ="figure"

```

Second program, prints `"ground"`:

```
    main=putStr$id id"ground"
    idid _="figure"

```

Calls one of two differently named constant functions

# Answer
> 3 votes
## Haskell, ~~88~~ 65 bytes

```
main=putStr
...........--
.."figure"..........
--"ground"........

```

and

```
...........
main=putStr..
--........"figure"--
.........."ground"

```

`.` indicates a space. Just some line comment (-\> `--`) juggling.

# Answer
> 3 votes
## JavaScript (ES6), 56 bytes

```
alert('figure'
                //&&'ground'
           )

alert('figure'//
&&'ground')
```

The figure has no trailing spaces.

# Answer
> 3 votes
## Python 2, 52 bytes

```
........................
print"figure"
an
d
"ground"

```

`.`s indicate spaces. The last three lines are split up to error out without having a `SyntaxError` which would prevent the code from running in the first place.

The ground version just uses `and` to make the second string be printed.

---

Alternative (longer) attempts:

```
.......
print(#"ground")#
"figure")...................

print"figure"""and"ground"
.............
.............

```

# Answer
> 2 votes
## Rail, 56 bytes

**Figure**

```
$'main'
 -[figure]o
-          [ground]o

```

There are 16 trailing spaces on the second line. The program terminates with an error.

Try it online!

**Ground**

```

$          'main'-[figure]o
 -[ground]o
```

There are 7 spaces on the first line and 9 trailing spaces on the last line. This program also terminates with an error.

Try it online!

### Explanation

Rail looks for a line starting with (regex notation) `\$.*'main'` to find an entry point. The train (instruction pointer) then starts from the `$` moving south-east. Things that aren't reachable by the train can be ignored completely for the program. This includes anything on the same line as the entry point. Since, the `-` south-east of the `$` immediately turns the train east, both programs simply reduce to:

```
 -[figure]o

```

```
 -[ground]o

```

`[...]` denotes a string literal and `o` prints it. Normally, you need a `#` to end the rail, but if you omit it, the program terminates anyway (but complains on STDERR that the train crashed).

# Answer
> 2 votes
## \>\<\>, 39 bytes

Using `·` to represent spaces.

**Figure**

```
v·
"·dnuo
e·
r·
u·
g··
i··
f···
"·
>·o·

```

Try it online!

**Ground**

```
·v
·"····
·d
·n
·u
·oe
·ru
·gif
·"
·>·o

```

Try it online!

Both programs terminate with an error.

### Explanation

By writing the code vertically, I was able to reuse the `g` and the `r` between both solutions, as well as the quotes and the `>` and `o` for the output loop.

In both cases, the only bit that gets executed is the column below the `v`, which pushes the letters of the required word onto the stack in reverse order. Then `>` redirects the instruction pointer to the right, where it loops through the `o`, printing the characters until the stack is empty.

# Answer
> 2 votes
## Fission, 37 bytes

Using `·` to represent spaces.

**Figure**

```
D·
"···
f··
i··
g·
u·
r·
e·ound
"·
;·

```

Try it online!

**Ground**

```
·D
·"fi
·gu
·re
·o
·u
·n
·d····
·"
·;

```

Try it online!

### Explanation

Works basically the same as my \>\<\> answer (although I actually found this one first). The only differences are that `"` prints the characters immediately in Fission, which is why the words aren't written upside down and why we only need to terminate the program with `;` at the end.

# Answer
> 2 votes
# Brian & Chuck, ~~55~~ 53 bytes

**Figure**

```
erugif?dnuorg
}<.<.<.<.<.<.

```

There are 13 trailing spaces on each line.

Try it online!

**Ground**

```
             erugif?dnuorg
             }<.<.<.<.<.<.

```

Try it online!

### Explanation

Ah, it's been a while since the last time I used Brian & Chuck. As a short reminder, Brian and Chuck are two Brainfuck-like instances, which use each others' source code as their tape. Only Chuck can use the printing command `.`, `?` switches between the two instances conditionally, and `}` is sort of like `[>]` in Brainfuck. Unknown commands are simply ignored.

Since the spaces at the beginning of the programs are ignored, the two programs are almost identical. The only difference comes from the fact that after the switching command `?`, the instruction pointer moves *before* executing the next command. Hence, the first command on Chuck's tape is always skipped. So the only real difference is that the ground program executes the `}` whereas the figure program doesn't. So here is how the code works:

```
?   Switch control to Chuck.
}   GROUND PROGRAM ONLY: Move the tape head on Brian to the end of the tape.
<.  Move the tape head left and print the character there.
... Do the same another five times to print the remainder of the string.

```

# Answer
> 1 votes
# reticular, 46 bytes

```
                      "ground""figure"" "?$$o;

```

Try it online! This prints `ground`.

```
"ground""figure"""?$$o                 ;

```

Try it online! This prints `figure`.

## ground

Relevant code:

```
"ground""figure"" "?$$o;
................          push these two strings
                " "?$     pop " " off (since " " is truthy, `?` executes `$`)
                     $    pop TOS ("figure")
                      o;  output and terminate

```

## figure

Relevant code:

```
"ground""figure"""?$$o;
................         push these two strings
                ""?$     doesn't activate
                    $    pop ""
                     o;  output and terminate

```

# Answer
> 0 votes
# WinDbg, 74 bytes

### Ground

```
                      ea2000000"      groundfigure";;;da       2000006  L6

```

### Figure

```
ea2000000"groundfigure          ";;;da                  2000006       L6

```

Figure has 2 trailing spaces. I feel like at least 2 or 4 bytes ought to be golfable...

It works by writing a string to memory and showing 6 chars from it. The chars in the string are re-arranged so the shown chars change between the programs:

```
* Ground:
ea 2000000 "      groundfigure";     * Write string "      groundfigure" starting at 2000000
;                                    * No-op
;                                    * No-op
da 2000006 L6                        * Print 6 ascii chars, from 2000006, ie- ground

* Figure:
ea 2000000 "groundfigure          "; * Write string "groundfigure          " to memory
;                                    * No-op
;                                    * No-op
da 2000006 L6                        * Print 6 ascii chars, ie- figure

```

Output:

```
0:000>                       ea2000000"      groundfigure";;;da       2000006  L6
02000006  "ground"
0:000> ea2000000"groundfigure          ";;;da                  2000006       L6
02000006  "figure"

```

---
Tags: code-golf, source-layout, whitespace
---


# Question
Title: C.U.S.R.S - The Completely Useless String Refactoring System!
# Introduction

I'm a real big fan of the SBU (Short But Unique) challenges that crop up on PPCG all of the time. The CUSRS is a system designed to refactor strings, a CUSRS function takes 2 parameters and outputs 1 String.

# Challenge

Produce a program, function, lambda or acceptable alternative to do the following:

Given `String input` and `String refactor` (as examples), refactor `input` using `refactor` as follows:

The `refactor` String will be in the format of `((\+|\-)\w* *)+` (regex), for example:

```
+Code -Golf -lf +al

```

Each section is a refactoring action to perform on `input`. Each program also has a pointer.

`+` Will insert it's suffix (without the plus) at the pointers current location in the String and then reset the pointer to 0.

Each operation should be applied to the `input` String and the result should be returned.

Example:

```
input:
Golf +Code //pointer location: 0

output:
CodeGolf //pointer location: 0

```

`-` Will increment the pointer through the String until it finds the suffix. The suffix will be removed from the String and the pointer will be left on the left side of the removed text. If no suffix is found the pointer will simply progress to the end of the String and be left there.

```
input:
Golf -lf //pointer location 0

output:
Go //pointer location 2

```

# Examples

```
input:
"Simple" "-impl +nip -e +er"

output:
"Sniper"

input:
"Function" "-F +Conj"

output:
"Conjunction"

input:
"Goal" "+Code -al +lf"

output:
"CodeGolf"

input:
"Chocolate" "Chocolate"

output:
"Chocolate" //Nothing happens...

input:
"Hello" "-lo+p        +Please" //Spaces are irrelevant

output:
"PleaseHelp"

input:
"Mississippi" "-s-s-i-ppi+ng" //Operations can be in any order

output:
"Missing"

input:
"abcb" "-c -b +d"

output:
"abd"

input:
"1+1=2" "-1+22-=2+=23"

outut:
"22+1=23"

```

# Example Code

The example is Java, it's not golfed at all.

```
public static String refactor(String input, String swap) {
    int pointer = 0;
    String[] commands = swap.replace(" ", "").split("(?=[-+])");

    for (String s : commands) {
        if (s.startsWith("+")) {
            input = input.substring(0, pointer) + s.substring(1) + input.substring(pointer, input.length());
            pointer = 0;
        } else {
            if (s.startsWith("-")) {
                String remove = s.substring(1);
                for (int i = pointer; i < input.length(); i++) {
                    if (input.substring(i, i + remove.length() > input.length() ? input.length() : i + remove.length()).equals(remove)) {
                        pointer = i;
                        input = input.substring(0, i) + input.substring(i + remove.length(), input.length());
                        break;
                    }
                }
            }
        }
    }

    return input;
}

```

# Rules

* Standard Loopholes Apply
* Shortest code, in bytes, wins

# Answer
## Python 3 (~~164~~ ~~194~~ ~~186~~ ~~181~~ ~~168~~ 165 bytes)

```
p=0
w,*x=input().split()
for i in x:
 if '-'>i:w,p=w[:p]+i[1:]+w[p:],0
 else:
  try:p=w.index(i[1:],p)
  except:p=len(w)
  w=w[:p]+w[p:].replace(i[1:],'',1)
print(w)

```

Example demonstrating the pointer moving to the end if it doesn't find a substring:

```
Input: HelloThere -x +Friend
Output: HelloThereFriend

```

Special thanks to Artyer for saving me 13 bytes.

Another thanks to Artyer for saving me another 3 bytes via the `beg` parameter of `index`.

Old answer:

```
p=0
x=input().split()
w=x[0]
for i in x[1:]:
 if i[0]=='+':
  w=w[:p]+i[1:]+w[p:]
  p=0
 else:
  p=w[p:].index(i[1:])+p
  w=w[:p]+w[p:].replace(i[1:],'',1)
print(w)

```

Example demonstrating the pointer works (all the examples in the Q work even if you don't factor in the pointer and simply replace on first occurence):

```
Input: HelloThereCowboy -r -e -y +ySays +Oh
Output: OhHelloTheCowboySays

```

Edit: Since 2 minutes ago my answer is now invalid according to a comment by the asker.

> aaa -b +b would result with aaab because the pointer would go all the way to the end.

Edit2: Fixed.
> 1 votes

# Answer
# GolfScript, 97 Bytes

```
" "%(:s;0:p;{("-"0=={.s p>\?.-1={;;s,:p;}{:p;,:l;s p<s p l+>+:s;}if}{s p<\+s p>+:s;0:p;}if}/"\n"s

```

Test: golfscript.tryitonline.net
> 1 votes

# Answer
# APL, ~~91~~ 90 bytes

```
{s l←⍵0⋄s⊣{g←1↓⍵⋄'+'=⊃⍵:+s∘←(l↑s),g,l↓s⋄l∘←¯1+1⍳⍨g⍷s⋄+s∘←(l↑s),s↓⍨l+⍴g}¨{1↓¨⍵⊂⍨⍵=⊃⍵}' ',⍺}

```

This takes the string as its right argument, and the commands as its left argument, like so:

```
      '+Code -al +lf' {s l←⍵0⋄s⊣{g←1↓⍵⋄'+'=⊃⍵:+s∘←(l↑s),g,l↓s⋄l∘←¯1+1⍳⍨g⍷s⋄+s∘←(l↑s),s↓⍨l+⍴g}¨{1↓¨⍵⊂⍨⍵=⊃⍵}' ',⍺} 'Goal'
CodeGolf

```
> 1 votes

# Answer
## JavaScript (ES6), 117 bytes

```
(s,r,t='')=>r.match(/\S\w*/g).map(r=>(q=r.slice(1),r<'-'?(s=t+q+s.t=''):([b,...a]=s.split(q),t+=b,s=a.join(q))))&&t+s

```

Explanation: Instead of using a cumbersome pointer, I keep the left half of the string in `t` and the right half in `s`. Additionally, `split` and `join` are a convenient way to perform the removal.
> 0 votes

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


title: Overlapping Line Ordering

text:
# Question
Title: Overlapping Line Ordering
(Inspired while drawing on a dry erase board)

### Challenge:

Given an input string containing characters that represent different colors of dry erase markers on a white board, output the order in which they were drawn, from first to last.

### Input:

A string which contains dry erase marker colors which are represented by alphabetical letters (upper ones are different than lowercase, you may substitute any characters used in my examples as long as each color has a distinct letter). The rest of the whiteboard will be white-space. There will only be one line of each color per board. There won't be inputs where all lines overlap each other (See test case `4`). All lines will be straight and either horizontal or vertical.

### Output:

The order in which the lines were drawn on the board, from the first one drawn to the last one. If there are multiple solutions for any input, you may output any one of them. The output can be formatted anyway you'd prefer: single string of characters or separated by spaces, newlines, etc. as long as the characters used match the ones used in your input.

### Test Cases:

Input 1:

```
  R
  R
BBRBB
  R

```

Output 1:

```
BR

```

Input 2:

```
    GY
    GY
RRRRGYRRR
    GY
    GY
BBBBBBBB
    GY
    GY

```

Output 2:

```
RGYB // or RYGB

```

Input 3:

```
    R    P
    R    P
AAAARAAAAPA
    R    P
    R    P
GGGGRGGG P
    R

```

Output 3:

```
AGPR // or APGR

```

Input 4:

```
 O Y
RRRYR
 O Y
GOGGG
 O Y

```

Output 4:

```
// Undefined, does not need to be handled by your program

```

Input 5:

```
YYYB
   B
   B

```

Output 5:

```
// YB or BY

```

### Rules:

This is , so shortest code in bytes wins.

# Answer
# Perl, 103+2 = 105 bytes

```
s/$/$"x y===c/gem;$a=$_;$_.=$"while$a=~s/^./!($_.=$&)/gem;s/$1/-/g,$b="$&$b"while/\s(\w)(\1|-)+ /;say$b

```

Run with `-n0` (2 byte penalty).

Explanation:

```
# -n0: read entire input into `$_` at start of program
# (technically speaking it reads to the first NUL byte, but there aren't any)

# We want to be able to extract columns from the input, so we need to add spaces
# to the ends of each line such that each column is complete. Adding too many
# space is OK, so to ensure we have enough, we add a number of spaces equal to the
# length of the input.
s/$/             # At the end of {something},
$" x             # append a number of spaces ($" is a space by default)
y===c            # obtained by counting the characters in $_
/gem;            # where {something} is each (g) line (m)

$a = $_;         # store a copy of the transformed input in $a

# The next step is to create a transposition of the input. To do that, we
# repeatedly extract the first column of $a and append it to $_. This will lead to
# a bunch of junk whitespace at the end of $_ (of varying lengths, because once a
# line is empty it's omitted from the extracted column), but we're OK with that.
# To transpose properly, we'd want to place newlines between the extracted
# columns; however, it happens that the rest of the program treats space the same
# way it would newline, and separating via spaces is shorter, so we do that.

while (          # keep looping as long as there are matches
  $a =~ s/^./    # replace the first character of {something related to $a}
  !(             # with the null string (NOT of something truthy)
    $_.=$&)      # but append that character ($&) to $_
  /gem) {        # {something} is each (g) line (m) of $a
  $_.=$"         # append a space ($", equivalent to newline here) to $_
}

# Finally, we repeatedly replace every character in the topmost line with the -
# character (treating a line as continuous through the - character but not through
# other characters), thus finding the lines from top to bottom. Because we
# appended the transpose of $_ to $_ above, each line appears twice: once
# horizontally, once vertically. We find only the horizontal copy, but replace
# both with hyphens.
# (Note: I rewrote the regex into a bit more readable of a form in this ungolfed
# version, because the original version wouldn't allow me room to write comments
# inside it. The two should be equivalent; I tested the golfed version.)
while (          # keep looping as long as there are matches
  /\s(\w)        # match a space or newline, $1 (a letter/digit/underscore),
    (\1|-)+      # any positive number of $1s and hyphens,
    \ /x) {      # and a space
  s/$1/-/g,      # changes all $1s to spaces; set $& to $1, $1 becomes invalid
  $b = "$&$b"    # prepend $& to $b
}

# We need to output the lines from first (i.e. bottom) to last (i.e. top).
# We found them in the opposite order, but reversed them via prepending
# (not appending) the partial results to $b.
say $b           # output $b

```

One slight subtlety here comes with input like this:

```
   ABC
DDDDDDDDD
   ABC
   ABC
   ABC

```

Look at the fourth line here. If the order of writing were BACBD, there could genuinely be a *horizontal* line of `B`s along there without violating any of the assumptions of the problem (other than that there's only one line of each colour, something that we don't check). In order to get around this, we ensure in the last regex that each line *starts* with a letter (or digit or underscore, but those are impossible), and rely on the fact that parallel lines will be found left-to-right and top-to-bottom (because the regex will find the first match within the string). As such, the first character of each ambiguous line here gets overwritten before the line itself is seen as a match, and that prevents the regex matching.
> 5 votes

# Answer
# Python 2, 199 bytes

```
l=input()
w=len(l[0])
j="".join(l)
c=set(j)-{" "}
def f(s):
 for h in s:
  i=j.index(h);I=j.rindex(h);o=f(s-{h})
  if{0}>c-s&set(j[i:I:w**(i+w<=I)])and`o`>"Z":return[h]+o
 if{0}>s:return[]
print f(c)

```

This ended up a lot longer than I initially thought it would. Apart from the `rindex` I could see this as a very good program to translate into Pyth.

Takes in a list of lines and outputs a list of characters. The code generates permutations recursively, making sure that none of the drawn lines are supposed to be drawn on top of the current line.

The code abuses a lot of Python's features, for example taking `w` to the power of a boolean, testing for empty sets by checking subsets of `{0}` (since my sets never contain non-strings), and my favorite, distinguishing any list from `None` by checking if its representation is greater than `Z`.

### Explained code

```
lines = input()
width = len(lines[0])
joined = "".join(lines)
characters = set(joined) - {" "} # find unique characters except space in input

def solve(chars_left): # returns a solution for the given set of lines
    for try_char in chars_left: # try all lines left

        start_index = joined.index(try_char) # find start position of this line
        end_index = joined.rindex(try_char) # and end position

        step = width ** (start_index + width <= end_index) # take every width'th character if start
                                                           # and end indices differ by at least width

        used_chars = characters - chars_left # find all drawn lines

        line_chars = set(joined[start_index:end_index:step]) # find the characters inside the current line
        missed_chars = used_chars & line_chars # find all lines that are already drawn but should be on
                                               # top of this line

        solution = solve(chars_left - {try_char}) # find solutions if this line was drawn now

        if {0} > missed_chars and `solution` > "Z": # there should be no missed lines and a solution
                                                    # should exist
            return [try_char] + solution # solution found, prepend current character and return

    if {0} > chars_left: # if no lines are left
        return [] # solution found

print solve(characters) # solve for all lines

```
> 2 votes

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


title: Josephus problem with three inputs

text:
# Question
Title: Josephus problem with three inputs
There's a question on this site that is similar to this question, but I have added a twist.

You have three inputs, the number of people in the circle *n*, the *k*-th person counted out at each step, and the *q*-th person that survives. The people in the circle are numbered 1 to *n*.

For example, in a circle of 20 people, the 20th person to survive is the very first person removed, the 19th survivor is the second person removed and so on. Normally, the Josephus problem is to determine the *last* person removed, here called the *first* survivor.

Write the shortest program or function that, with those three inputs, returns the number of the *q*-th person to survive.

If there are any issues with clarity, please let me know.

Some examples:

```
>>> josephus(20, 3, 9)
4
>>> josephus(4, 3, 1)
1
>>> josephus(100, 9, 12)
46

```

**Edit:** Assume all inputs are valid. That is no one will ask for 0 or any negative numbers and no one will ask for the 20th survivor in a circle of 5 people (that is, 1 ≤ q ≤ n)

**Edit:** I'll accept an answer at midnight UTC+7 at the start of December 2.

# Answer
> 6 votes
# Pyth, 16 bytes

```
eu.<PGvzh-QvwShQ

```

Try it online: Demonstration or Test Suite

Input is of the form `k<newline>n<newline>q`.

### Explanation:

```
eu.<PGvzh-QvwShQ   implicit: z = first input line (string)
                             Q = second input line (integer)
              hQ   Q + 1
             S     the range [1, 2, ..., Q+1]
 u      h-Qvw      apply the following statement (Q-input()+1) times to G=^
    PG                remove the last number of G
  .<  vz              and rotate eval(z) to the left
e                  print the last number of the resulting list

```

# Answer
> 7 votes
# Piet, ~~280~~ 273 codels

**Edit:** I have golfed this down some more, and I think I can golf it down even further, but that is still to come. For now, I'm just glad it works, and that I had room to sign it in the bottom left-hand corner. Two ideas I have to save more codels are a) to change the end instructions be `pop, push 1, add, out num` (pop n, output r+1) and b) to duplicate again at the bottom left corner to save codels in stack manipulation later on in the loop.

The picture above is my code at 8 pixels per codel. In general, it's the same algorithm as my Python answer, but with the inputs in the order of **k**, **q**, **n**. In practice, there is a also a great deal of stack manipulation. You can try it here by opening the image there and running the code with it.

**Explanation**

This is a step-by-step ungolfing of the solution.

```
in num    get k
dup       Stack: k k
push 1
subtract  Stack: k k-1
in num    get q
dup       Stack: k k-1 q q
dup       Stack: k k-1 q q q
push 4
push 2
roll      Stack: k q q k-1 q
mod       Stack: k q q r
in num    get n
# note: the loop will return to the following codel
dup       Stack: k q q r n n
push 4
push 3
roll      Stack: k q r n n q
greater   1 or 0
pointer   Here the loop begins. If q>n, the pointer moves clockwise.
          Else, it points straight ahead

LOOP:     Stack: k i r n (i=q at the start of the loop)
push 4
push 2
roll      Stack: r n k i
push 1
add       Stack: r n k i=i+1
push 2
push 1
roll      Stack: r n i k
dup       Stack: r n i k k
push 5
push 4
roll      Stack: n i k k r
add       Stack: n i k m=r+k
push 3
push 2
roll      Stack: n k m i
dup       Stack: n k m i i
push 3
# here it turns the corner
push 1
roll      Stack: n k i m i
mod       Stack: n k i r=m%i
push 4
# here it turns the corner and avoids the black codels
push 1
roll      Stack: r n k i
dup       Stack: r n k i i
push 5
push 3
roll      Stack: k i i r n
dup       Stack: k i i r n n
# and we meet up with the dark green codel once more
push 4
push 3
roll      Stack: k i r n n i
greater   Stack: k i r n (0 or 1)
pointer   if else again

# else    Stack: k i r n
push 2
push 1
roll      Stack: k i n r
# and turn the corner
push 1
add       Stack: k i n r+1
out num   print r+1
# turn the corner into the end pattern (the shape with the black edges)
END

```

# Answer
> 4 votes
# CJam, ~~22~~ ~~20~~ 19 bytes

```
q~_,@a@*{m<)\}%\~=)

```

This reads the input as `q k n`. Try it online in the CJam interpreter.

### How it works

```
q~                   Read and evaluate all input. This pushes q, k, and n.
  _,                 Push A := [0 ... n-1].
    @a               Rotate on top of the stack and wrap it in an array.
      @*             Rotate the original n on top and repeat [k] n times.
        {    }%      For each of the n k's:
         m<            Rotate A k units to the left.
           )\          Pop the last element and swap it with A.
               \~    Swap the resulting array with q and apply bitwise NOT.
                 =)  Select the corresponding element and add 1 to it.

```

# Answer
> 3 votes
## Golfscript, ~~58~~ ~~56~~ ~~55~~ ~~35~~ ~~31~~ 30 bytes

Assuming the three inputs are already in the stack, in the order **n**, **k**, **q**

```
~1$(1$%3$),@),-{\2$+\%}%\)])\;

```

That solution assumes I need to get rid of everything but the final answer.

### How it works

See `j(n,k,q)` in my Python 3 solution for more detail.

```
~                                   Read the inputs n, k, q
 1$(                                Duplicate k, decrement
    1$                              Duplicate q
      %                             (k-1)%q
       3$),                         Create array [0..n+1]
           @),                      Create array [0..q+1]
              -                     Subtract the second array from the first,
                                        leaving only [q+1..n+1]
               {      }%            Map the following statement onto [q+1..n+1].
                                        The numbers from this array will be denoted i.
                \                   Swap i and r
                 2$+                Duplicate k, add to r
                    \               Swap r and i
                     %              r mod i
                        \)          Swap the leftover array from map with r, increment
                          ]         Put the whole stack into an array
                           )        Remove the last member of the array, r
                            \;      Pop the array, leaving only the result

```

**Edit 1:** Used @Doorknob's suggestion (Added a + to get all the inputs into the array)

Formerly,

```
\.(2$2$*1$4$%-{.5$3$*>!}{~)2$*1$/~)}while 4$3$*\-)\;\;\;\;

```

**Edit 2:** Added ~, per the rules of the wiki, and shortened the code. Thanks @Dennis

Formerly,

```
[\.(2$2$*1$4$%-{.5$3$*>!}{~)2$*1$/~)}while 4$3$*\-)]+)\;

```

**Edit 3:** Implemented a shorter algorithm.

Formerly,

```
~\.(2$2$*1$4$%-{.5$3$*>!}{~)2$*1$/~)}while 4$3$*\-)]-1=

```

**Edit 4:** Figured out that I could use `%` as map.

Formerly,

```
~1$(1$%{1$4$<}{\)\2$+1$%}while)])\;

```

**Edit 5:** Minor edit. Changed `2$` to `@` to make `[0..q-1]` and `3$` to `2$` to retrieve `k`. Saved a bite

Formerly,

```
~1$(1$%3$),2$),-{\3$+\%}%\)])\;

```

# Answer
> 3 votes
# JavaScript (ES6), 56 bytes

```
(n,k,q)=>{r=(k-1)%q;for(i=q;i<n;r=(r+k)%++i);return r+1}

```

## Ungolfed

Basically a JavaScript adaptation of @Sherlock9's Python answer.

```
(n,k,q)=>{
  r=(k-1)%q;
  for(i=q;i<n;r=(r+k)%++i);
  return r+1
}

```

## Test

```
n = <input type="number" id="N" value="100" /><br />
k = <input type="number" id="K" value="9" /><br />
q = <input type="number" id="Q" value="12" /><br />
<button onclick="result.innerHTML=(

(n,k,q)=>{r=(k-1)%q;for(i=q;i<n;r=(r+k)%++i);return r+1}

)(+N.value,+K.value,+Q.value)">Go</button><br />
<pre id="result"></pre>
```

# Answer
> 2 votes
## Python 3, ~~72~~ ~~66~~ 62 bytes

A dynamic programming function in 62 bytes. Adapted from the algorithm on Wikipedia. There used to be a direct implementation of this algorithm when q=1 (i.e. i=1, r=0) on that page, but I see that has been removed now.

**Edit 1:** I removed `i` to save 4 bytes. Explanation remains unchanged.

**Edit 2:** Miscalculation in byte count. I was using `\r\n` for EOL and didn't notice when that added 3 bytes. I have lowered my byte count accordingly.

```
def j(n,k,q):
 r=(k-1)%q
 while q<n:q+=1;r=(r+k)%q
 return r+1

```

### How this works

```
def j(n,k,q):
 i=q;r=(k-1)%q              We start with the smallest possible circle to have a q-th
                                survivor, a circle of q people.
 while i<n:i+=1;            Iterate from q to n
                r=(r+k)%i   Every time you add people to the circle, r increases by k,
                                modulo the current size of the circle i.
 return r+1                 Return the result.

```

Thanks to @Dennis for reminding me that I should explain my code (if only implicitly, because he included one in his answer). If anything is unclear, please let me know.

### Edit:

Formerly,

An iterative function that is adapted from *Concrete Mathematics* by Graham, Knuth and Patashnik. Though this algorithm is longer, it is faster for large *n* and small *k*.

```
def t(n,k,q):
 m=k-1;z=q*k-m%q
 while z<=n*m:z=-(-z*k//m)
 return n*k-z+1

```

# Answer
> 2 votes
# C, ~~81~~ 73 bytes

Based off @user81655's Javascript implementation of my Python answer.

**Edit:** Removed i

```
int j(int n,int k,int q){int r=(k-1)%q;for(;q<n;r=(r+k)%++q);return r+1;}

```

### Test

```
#include <stdio.h>
int j(int n,int k,int q){int r=(k-1)%q;for(;q<n;r=(r+k)%++q);return r+1;}
int main()
{
    printf("%d\n", j(20,3,9));
    return 0;
}

```

# Answer
> 1 votes
# Mathematica, 50 bytes

```
<<Combinatorica`
Tr@Position[Josephus@##2,1+#2-#]&

```

An anonymous function. Takes inputs in the order `q,n,k`.

# Answer
> 1 votes
# Haskell, ~~48~~ ~~47~~ 43 bytes

```
(n!k)q=1+foldl(mod.(k+))(mod(k-1)q)[q+1..n]

```

Based on a Haskell algorithm on the Rosetta Code page of the Josephus function with two inputs. Golfing suggestions are welcome.

**Edit:** My thanks to nimi for help with golfing the first algorithm via suggesting a pointfree version, and for help with golfing the second algorithm by letting me know that the `until` keyword exists.

```
(n#k)q|m<-k-1=1+n*k-until(>n*m)(\z-> -div(-z*k)m)(q*k-mod m q)

```

A version of the algorithm at the end of my Python answer adapted from Concrete Mathematics by Graham, Knuth and Patashnik. Though this algorithm is longer at 62 bytes, and has not been golfed down as much as the first, it is faster for large `n` and small `k`.

**Ungolfed:**

First algorithm

```
jos_g num step q = 1 + foldl (\x -> mod (x + step) ) (mod (step-1) q) [q+1..num]

```

Second algorithm

```
jos_gkp num step q
    -- ceiling throws a type-related fit with ceiling(z*k/(k-1))
    -- better to use - div (-z * k) (k - 1)
    | m <- step-1 = 1 + num*step - until (>num*m)(\z-> -div (-z*k) m) (q*step - mod m q)

```

# Answer
> 1 votes
## PHP, 71 bytes

Based off of @Sherlock9's answers. See his Python answer for the algorithm.

```
function a($n,$k,$q){for($r=($k-1)%$q;$q<$n;$r=($r+$k)%++$q);echo$r+1;}

```

Alternatively, here is my original naive approach without the algorithm. This uses an array to mark which people are found.

**91 bytes**

```
function a($n,$k,$q){for($r=--$i;$q<=$n;++$i%$k||$c[$r]=$q++)while($c[$r=++$r%$n]);echo$r;}

```

# Answer
> 1 votes
# GameMaker Language (GML), 88 bytes

Based on @user81655's answer

```
r=argument0
k=argument1
q=argument2
r=(k-1)mod q;for(i=q;i<n;r=(r+k)mod ++i){}return r+1

```

# Answer
> 1 votes
# Jelly, ~~14~~ 13 bytes

```
Rµṙ⁴ṖµL>⁵µ¿⁴ị

```

**TryItOnline!**

### How?

```
Rµṙ⁴ṖµL>⁵µ¿⁴ị - Main link: n, k, q
 µ            - monadic chain separation
R             - range(n): [1,2,3,...,n] - the circle of people
     µ   µ¿   - while
      L       -     length
       >      -     greater than
        ⁵     -     5th program argument (3rd input), i.e. q
  ṙ           -         rotate left by
   ⁴          -         4th program argument (2nd input) i.e. k
    Ṗ         -         pop - remove the rightmost person
            ị - get index
           ⁴  - 4th program argument (2nd input), i.e. k

```

# Answer
> 0 votes
# Ruby, ~~53~~ 48 bytes

A lambda.

```
->n,k,q{r=(k-1)%q;(q+=1;r=(r+k)%q)while q<n;r+1}

```

### How it works

```
def j(n,k,q)
  r=(k-1)%q   # r starts at j[q,k,q]
  while q<n
    q+=1
    r=(r+k)%q # Every time you add people to the circle, r increases by k,
              # modulo the current size of the circle q.
  end
  r+1         # Return the result.
end

```

---
Tags: code-golf
---