# Question
Title: Obfuscating text by cycling ternary digits
The goal of this challenge is the write the shortest function/program to take input text, encrypt it using the method below, and return the result.

As an example, I will use the string `hello world`.

**First**, get the input text.

```
hello world

```

**Second**, convert the string into ternary (base 3). Use this key:

```
a = 000
b = 001
c = 002
d = 010
e = 011
f = 012
g = 020

...

w = 211
x = 212
y = 220
z = 221
[space] = 222

```

With this key, `hello world` becomes `021011102102112222211112122102010`, as seen below.

```
 h   e   l   l   o       w   o   r   l   d
021 011 102 102 112 222 211 112 122 102 010

```

**Third**, move the first digit to the end.

```
021011102102112222211112122102010
becomes
210111021021122222111121221020100

```

**Fourth**, convert the number back into a string using the same key.

```
210 111 021 021 122 222 111 121 221 020 100
 v   n   h   h   r       n   q   z   g   j

```

**Lastly**, return the encrypted text.

```
vnhhr nqzgj

```

Here are some sample text and their output:

`the turtle ==> dvo fh ego`

`python ==> uudwqn`

`code golf ==> hpjoytqgp`

As this is code golf, the shortest entry in *bytes* wins. Errors are allowed if some of the characters are not lowercase letters or space. This is my first challenge, so any suggestions would be more than helpful.

Good luck!

**Leaderboard:**

```
var QUESTION_ID=54643;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:<(?:s>[^&]*<\/s>|[^&]+>)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;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="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><div id="language-list"> <h2>Winners 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><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
> 16 votes
# Pyth, ~~23~~ 22 bytes

```
sXc.<sXz=+GdJ^UK3K1KJG

```

Try it online: Regular Input / Test Suite

Thanks to @isaacg for one byte.

### Explanation:

```
sXc.<sXz=+GdJ^UK3K1KJG
        =+Gd             append a space the G (preinitialized with the alphabet)
               K3        assign 3 to K
            J^UK K       assign all 3-digit ternary numbers
                         [[0,0,0], [0,0,1],...,[2,2,2]] to J
      Xz  G J            translate input from G to J
     s                   sum (join all ternary numbers to one big list)
   .<             1      rotate by 1
  c                K     split into lists of size 3
 X                  JG   translate from J to G
s                        join chars to string and print

```

# Answer
> 14 votes
# Pyth, 26 bytes

```
J+Gds@LJiR3c.<s.DR9xLJz1 2

```

Try it online in the Pyth Compiler/Executor: demo | test cases

### Idea

Assume all input characters have already been mapped to the integers that step 2 specifies.

For every 3-digit ternary number, we have that **xyz3 = 9x + 3y + z**, so modular division by **9** yields quotient **x** and residue **3y + z**.

If the input is **abc3 def3 ghi3**, applying modular division to each yields **a, 3b + c, d, 3e + f, g, 3h + i**.

After rotating the list from above one unit to the left, we can group the integers into pairs. This yields the list **(3b + c, d), (3e + f, g), (3h + i, a)**.

Now, if we convert **(3y + z, w)** from base 3 to integer, we obtain **3(3y + z) + w = 9y + 3z + w = zyw3**.

Thus, applying base conversion to the list of pairs gives us **bcd3 efg3 hia3**, which is precisely the result of rotating the concatenated ternary digits one unit to the left.

All that's left to do is mapping the resulting integers back to characters.

### Code

```
J+Gd                        Concatenate "a...z" (G) with " " (d) and save in J.
                    L z     For each character in the input(z):
                   x J        Compute its index in J.
                 R          For each index I:
               .D 9           Compute (I / 9, I % 9).
              s             Concatenate the resulting pairs.
            .<         1    Rotate the resulting list one unit to the left.
           c             2  Split it back into pairs.
         R                  For each pair:
        i 3                   Perform conversion from base 3 to integer.
      L                     For each resulting integer:
     @ J                      Select the element of J at that index.
    s                       Concatenate the resulting characters.

```

# Answer
> 10 votes
# Python 2, 96

```
s=input()
r=y=''
for c in s+s[0]:x=(ord(c)-97)%91;r+=y and chr((y%9*3+x/9-26)%91+32);y=x
print r

```

Converts a character `c` to a value `x` as `x=(ord(c)-97)%91`, with the modulo affecting only space to convert it to 26. The reverse conversion is `i` to `chr((i-26)%91+32)`, with the modulo only affecting `i=26` to make it become spaces.

We loop through the characters, noting the current value `x` and the previous value `y`. We use the last two ternary digits of `y`, found as `y%9`, and the first ternary digit of `x`, found as `x/9`. The value of the concatenation is `y%9*3+x/9`. There's probably some optimizations combining this arithmetic with the shifting by `97` and fixing of space.

We make this loop around, we return to the first character of the string at the end. We also do one preparation loop to write in a previous value `y`, suppressing the character for the first loop when `y` has not yet been initialized.

# Answer
> 8 votes
# CJam, ~~39~~ 29 bytes

The cool thing about this one is that it doesn't even use base conversion.

```
q'{,97>S+:XZZm*:Yere_(+3/YXer

```

Try it online.

I just realized I had exactly the same idea as Jakube's Pyth answer. I actually ported this CJam code to Pyth before seeing his post, ending up with 25 bytes. Given it was my first Pyth golf I guess it's not too bad.

# Explanation

```
                              e# Z = 3
q                             e# Push input string
 '{,                          e# Push ['\0' ... 'z']
    97>                       e# Keep ['a' ... 'z']
       S+                     e# Append space
         :X                   e# Assign "a...z " to X
           ZZm*               e# Push 3rd cartesian power of [0 1 2]
                              e# i.e. all 3-digit permutations of 0, 1, 2
                              e# (in lexicographical order)
               :Y             e# Assign those permutations to Y
                 er           e# Translate input from X to Y
                   e_         e# Flatten resulting 2D array
                     (+       e# Rotate first element to the end
                       3/     e# Split back into 3-digit elements
                         YXer e# Translate from Y to X

```

# Answer
> 7 votes
# CJam, ~~30~~ ~~29~~ 27 bytes

```
q'{,97>S+:Af#9fmd(+2/3fbAf=

```

Try it online in the CJam interpreter.

The approach is the same as in my other answer, which is a port of this code to Pyth.

### How it works

```
q                           e# Read from STDIN.
 '{,                        e# Push ['\0' ... 'z'].
    97>                     e# Remove the first 97 elements (['\0' - '`']).
       S+:A                 e# Append a space and save in A.
           f#               e# Find the index of each input character in A.
             9fmd           e# Apply modular division by 9 to each index.
                 (+         e# Shift out the first quotient and append it.
                   2/       e# Split into pairs.
                     3fb    e# Convert each pair from base 3 to integer.
                        Af= e# Select the corresponding elements from A.

```

# Answer
> 6 votes
# Javascript (ES6), 175 bytes

A one-liner!

"Overuse of variable `v` award, anyone?"

update: Now ***only*** uses variables called `v`, for total confusion!

*Thanks @vihan for saving 6 bytes!*

*Thanks @Neil for saving 27 bytes!!*

```
v=>(([...v].map(v=>(v<"V"?53:v.charCodeAt()-70).toString(3).slice(1)).join``)+v[0]).slice(1).match(/..?.?/g).map(v=>(v=String.fromCharCode(parseInt(v,3)+97))>"z"?" ":v).join``

```

Defines an anonymous function. To use, add `v=` before the code to give the function a name, and call it like `alert(v("hello world"))`

# Answer
> 6 votes
# Pyth, ~~30~~ 29 bytes

```
K+Gdsm@Kid3c.<sm.[Z3jxKd3z1 3

```

Saved 1 byte thanks to @Jakube.

Live demo and test cases.

# Answer
> 5 votes
# Julia, ~~149~~ 137 bytes

My first golf!

```
s->(j=join;b=j([base(3,i==' '?26:i-'a',3)for i=s]);r=b[2:end]*b[1:1];j([i==26?" ":i+'a'for i=[parseint(r[i:i+2],3)for i=1:3:length(r)]]))

```

(partially) ungolfed:

```
f = s -> (
    # join the ternary represenations:
    b = join([base(3, i == ' ' ? 26 : i - 'a',3) for i = s]);
    # rotate:
    r = b[2:end] * b[1:1];
    # calculate the new numbers:
    n = [parseint(r[i:i+2],3) for i = 1:3:length(r)];
    # convert back to characters:
    join([i == 26 ? " " : 'a' + i for i = n])
)
assert(f("hello world") == "vnhhr nqzgj")
assert(f("the turtle")  == "dvo fh ego")
assert(f("python")      == "uudwqn")
assert(f("code golf")   == "hpjoytqgp")

```

# Answer
> 4 votes
# Javascript (ES6), ~~178~~, ~~172~~, 170

```
p=>{p=p.replace(' ','{');c="";l=p.length;for(i=0;i<l;){c+=String.fromCharCode(((p.charCodeAt(i)-97)%9)*3+(((p.charCodeAt((++i)%l)-97)/9)|0)+97)}return c.replace('{',' ')}

```

Replaced Math.floor with a bitwise or. Created an anonymous function. If I'm understanding correctly, this should fix my noobishness somewhat (thanks Dennis!) and get me another 2 bytes down.

# Answer
> 3 votes
# Julia, ~~169~~ 166 bytes

```
s->(J=join;t=J(circshift(split(J([lpad(i<'a'?"222":base(3,int(i)-97),3,0)for i=s]),""),-1));J([c[j:j+2]=="222"?' ':char(parseint(c[j:j+2],3)+97)for j=1:3:length(t)]))

```

Ungolfed + explanation:

```
function f(s::String)
    # Convert the input into a string in base 3, with space mapping to 222
    b = join([lpad(i < 'a' ? "222" : base(3, int(i) - 97), 3, 0) for i = s])

    # Split that into a vector of single digits and shift once
    p = circshift(split(b, ""), -1)

    # Join the shifted array back into a string
    t = join(p)

    # Convert groups of 3 back into characters
    c = [t[j:j+2] == "222" ? ' ' : char(parseint(t[j:j+2], 3) + 97) for j = 1:3:length(t)]

    # Return the joined string
    join(c)
end

```

# Answer
> 3 votes
# Haskell, 160 bytes

```
a!k|Just v<-lookup k a=v
x=['a'..'z']++" "
y="012";z=mapM id[y,y,y]
m(a:u:r:i:s)=[u,r,i]:m(a:s)
m[e,a,t]=[[a,t,e]]
main=interact$map(zip z x!).m.(>>=(zip x z!))

```

Ugh, this feels way too lengthy, but at least I'm... beating Python somehow. And Ruby.

# Answer
> 3 votes
# Javascript (ES6), ~~141~~ ~~124~~ 120 bytes

Believe it or not.... :-)

```
(t,i=0,c=w=>(t.charCodeAt(w)-123)%91+26)=>String.fromCharCode(...[...t].map(k=>(c(i)%9*3+c(++i%t.length)/9+65|0)%91+32))

```

As with my other answer, this is an anonymous function, and needs to be assigned to a variable before it can be used. Try it here:

```
e=(t,i=0,c=w=>(t.charCodeAt(w)-123)%91+26)=>String.fromCharCode(...[...t].map(k=>(c(i)%9*3+c(++i%t.length)/9+65|0)%91+32));

input=document.getElementById("input");
p=document.getElementById("a");
input.addEventListener("keydown", function(){
  setTimeout(function(){p.innerHTML = e(input.value);},10);
})
```

```
<form>Type your text here: <input type="text" id="input" value="hello world"/><br>
Only space and lowercase letters are allowed.</form>

<h3>Output:</h3>
<p id="a">vnhhr nqzgj</p>
```

I thought I might be able to shave a couple bytes off my previous answer by using a different technique, so I started out with one similar to Tekgno's and golfed my head off from there. I initialized some variables in the function's argument section, and again stuffed everything into a `.map` function. Then I realized the `String.fromCharCode` would be much more efficient outside the `.map`. After all was said and done, I had shaved off **more than ~~30~~ 45 bytes!**

**Edit 1:** Saved 17 bytes by getting rid of the `.replace`s, using a technique similar to xnor's Python solution.

OK, maybe it's time to move onto another challenge....

# Answer
> 2 votes
# Python 2, ~~182~~ 180 Bytes

This solution is not ideal, due to the replace being very costly.. Trying to figure out how to avoid that.

```
b=lambda k:k and b(k/3)*10+k%3
s=''.join('%03d'%b(ord(x)-6-91*(x>' '))for x in input())
print`[chr(int((s[1:]+s[0])[i:i+3],3)+97)for i in range(0,len(s),3)]`[2::5].replace('{',' ')

```

Input is like `"hello world"`.

# Answer
> 2 votes
# Javascript (ES6), 179 bytes

```
s=>[...s+s[0]].map(q=>`00${(q<'a'?26:q.charCodeAt(0)-97).toString(3)}`.slice(-3)).join``.slice(1,-2).match(/..?.?/g).map(q=>q>221?' ':String.fromCharCode(parseInt(q,3)+97)).join``

```

Props to vihan for the `.match` regex.

# Answer
> 2 votes
# Mathematica, 162 bytes

```
r=Append[#->IntegerDigits[LetterNumber@#-1,3]~PadLeft~3&/@Alphabet[]," "->{2,2,2}];StringJoin[Partition[RotateLeft[Characters@#/.r//Flatten,1],3]/.(#2->#1&@@@r)]&

```

(Re)Using a `Rule` to convert the digit lists to characters and back.

# Answer
> 1 votes
# Ruby, 177

Needs at least Ruby 1.9 for the `each_char` method

```
l=[*('a'..'z'),' '];n=(0..26).map{|m|m=m.to_s(3).rjust 3,'0'};s='';gets.chomp.each_char{|x|s+=n[l.index x]};puts("#{s[1..-1]}#{s[0]}".scan(/.../).map{|i|i=l[n.index i]}.join '')

```

# Answer
> 1 votes
## Java, 458 449 bytes

It made me a little sad to determine that I could shave off 10 bytes by not using Java 8 streams and the `map()` method.

Here is the golfed version:

```
import org.apache.commons.lang.ArrayUtils;class A{public static void main(String[]a){int b=0;String[] c=new String[27];for(;b<27;++b)c[b]=String.format("%03d",Integer.valueOf(Integer.toString(b,3)));String d=a[0],e="abcdefghijklmnopqrstuvwxyz ",f="",g="";for(b=0;b<d.length();++b)f+=c[e.indexOf(d.substring(b,b+1))];f=f.substring(1)+f.charAt(0);for(b=0;b<f.length();b+=3)g+=e.charAt(ArrayUtils.indexOf(c,f.substring(b,b+3)));System.out.println(g);}}

```

Here is a much less golfed version. It is intended to be readable, but I make no guarantees.

```
import org.apache.commons.lang.ArrayUtils;
class A {
    public static void main(String[] a) {
        int b=0;
        String[] c = new String[27];
        for (; b < 27; ++b)
            c[b] = String.format("%03d", Integer.valueOf(Integer.toString(b, 3)));
        String
            d = a[0],
            e = "abcdefghijklmnopqrstuvwxyz ",
            f = "",
            g = "";
        for (b = 0; b < d.length(); ++b)
            f += c[e.indexOf(d.substring(b, b + 1))];
        f = f.substring(1) + f.charAt(0);
        for (b = 0; b < f.length(); b += 3)
            g += e.charAt(ArrayUtils.indexOf(c, f.substring(b, b + 3)));
        System.out.println(g);
    }
}

```

This program takes the string to convert as a command-line argument. If you want to have spaces in your input, you have to surround it with double quotes.

I wanted to provide an example of using this from the command line, but I was unable to get this code to work outside of Eclipse. I never learned to use Java from the command line ^\_^; You can probably get this running inside the IDE of your choice without too much trouble.

# Answer
> 1 votes
# Javascript (ES6), ~~181~~ 180 bytes

```
t=>((x=[...t].map(k=>`00${(k<'!'?26:k.charCodeAt(0)-97).toString(3)}`.slice(-3)).join``).slice(1)+x[0]).match(/.../g).map(j=>j>221?' ':String.fromCharCode(parseInt(j,3)+97)).join``

```

This is an anonymous function, so it needs to be given a name before it can be used. (E.g. `encrypt=t=>...`) Try it out here:

```
e=t=>((x=[...t].map(k=>`00${(k<'!'?26:k.charCodeAt(0)-97).toString(3)}`.slice(-3)).join``).slice(1)+x[0]).match(/.../g).map(j=>j>221?' ':String.fromCharCode(parseInt(j,3)+97)).join``;

input=document.getElementById("input");
p=document.getElementById("a");
input.addEventListener("keydown", function(){
  setTimeout(function(){p.innerHTML = e(input.value);},10);
})
```

```
<form>Type your text here: <input type="text" id="input" value="hello world"/><br>
Only space and lowercase letters are allowed.</form>

<h3>Output:</h3>
<p id="a">vnhhr nqzgj</p>
```

I started out using multiple variables and `for` loops instead of `.map`. I then golfed it in every possible way without changing the algorithm, which put me somewhere around 217 bytes. After taking a look at UndefinedFunction's answer, I managed to get it down to 195, and some inspection of Dendrobium's answer resulted in another 14 golfed off.

As far as I'm aware, I can't go any further or my result would be practically identical to Dendrobium's (except for being one character shorter!). Can anyone find the place where I saved one char? :-)

As usual, suggestions are gladly welcome!

# Answer
> 0 votes
## Matlab, 113 bytes

```
x=dec2base(strrep(input('','s'),' ','{')-97,3)';strrep(char(base2dec(reshape(x([2:end 1]),3,[])',3)+97)','{',' ')

```

Input is through stdin.

Example:

```
>> x=dec2base(strrep(input('','s'),' ','{')-97,3)';strrep(char(base2dec(reshape(x([2:end 1]),3,[])',3)+97)','{',' ')
hello world
ans =
vnhhr nqzgj

```

# Answer
> 0 votes
# Julia - ~~92~~ ~~87~~ ~~61~~ 54 bytes

```
s->join(32+(3(i=[s...]%91+579)%27+i[[2:end,1]]÷9)%91)

```

Ungolfed:

```
function f(s)
  t=[s...];       # Convert the string into a char array
                      #
  i=t%91+579          # Mod 91 drops the alpha characters to sit just
                      # below space, then 579 is added as a trick,
                      # equivalent to subtracting 6 and adding 9*65
  v1=3i%27            # This shifts the bottom two ternary digits up
                      # and removes the first ternary digit
  v2=i[[2:end,1]÷9    # This shifts the first ternary digit down and
                      # removes the bottom two ternary digits. [2:end,1]
                      # rotates the array to put the first value at the end
  N=(v1+v2)%91+32     # this combines the ternary digits, then returns
                      # the values to the correct ASCII values
  j=join(N)           # join the char array back to a string
  return j
end

```

The trick may confuse you. Subtracting 6 moves 'a' down to zero after the mod. Adding 9\*65 is equivalent to adding 65 to v1+v2, which is part of the process of restoring the values to their ascii values. You could replace `i=t%91+579` with `i=t%91-6`, and then replace `N=(v1+v2)%91+32` with `N=(v1+v2+65)%91+32` to get the same result, but it requires one extra character.

---
Tags: code-golf, base-conversion, obfuscation
---


title: Ich ne know pas

text:
# Question
Title: Ich ne know pas
## Challenge

You must write a program which correctly identifies the language a passage is written in.

## Rules

The passage will be a string passed to your program either via STDIN or function arguments.

You may not use any external sources *except* for a local text file with words. The length of the text file must be included in your overall program length.

To know that your program meets the spec, it should correctly identify the languages of the following websites:

```
<code>.wikipedia.org/wiki/<Word for Wikipedia>
<code>.wikipedia.org/wiki/<Language name>

```

Where `<code>` is replaced by the language's code. For example, in English:

```
en.wikipedia.org/wiki/Wikipedia
en.wikipedia.org/wiki/English

```

For Lojban:

```
jbo.wikipedia.org/wiki/uikipidias
jbo.wikipedia.org/wiki/lojban.

```

You are strictly forbidden to hardcode any of the content or HTML code of the links.

To make sure that changes to the wiki don't affect your results, you should use the latest edit to the wiki page before the 15th August 2015, 21:00 BST (GMT+1).

If your language cannot identify the language in which the passage is written, you must return the following phrase:

```
Ich ne know pas

```

You can only identify languages which are on this list.

When you return the language name, you should return its English name, and in brackets its name in its own language.

In your answer, you should have a list of the languages that you identify.

## Examples

### French (Français)

> Une baguette de pain ou simplement baguette, ou encore pain français (québécisme et belgicisme), est une variété de pain, reconnaissable à sa forme allongée. Cette forme de pain est emblématique de la France, et l'était déjà avant l'invention de la baguette, quand les pains longs étonnaient les visiteurs. La baguette est aussi typique de l'Algérie.

### German (Deutsch)

> Die Wurst war und ist auch heute noch das Produkt des Wunsches nach einer möglichst großen Verwertung eines (geschlachteten) Tieres. Durch die Verarbeitung zur Wurst kann so auch das Fleisch länger haltbar gemacht werden. Die ersten Würste, wenn auch nicht im heutigen Sinne, wurden vermutlich bereits in der Antike oder sogar schon vorher hergestellt; siehe dazu auch Haggis oder Saumagen. Erste chinesische Erwähnung findet sich um das Jahr 589 v. Chr. zu einer Wurst, bei der Lamm- und Ziegenfleisch verwendet wurden.

### Welsh (Cymraeg)

> Bara llaith o Gymru sy'n cynnwys cyrens, rhesins neu syltanas, croen candi, a sbeis melys yw bara brith. Gweinir yn dafellau gyda menyn gan amlaf, am de'r prynhawn neu de mawr. Teisen furum yw bara brith yn draddodiadol, ond mae nifer o ryseitiau modern yn defnyddio ychwanegion megis soda pobi i'w lefeinio.

### English (English)

> A steak pie is a traditional meat pie served in Britain. It is made from stewing steak and beef gravy, enclosed in a pastry shell. Sometimes mixed vegetables are included in the filling. In Ireland Guinness Stout is commonly added along with bacon and onions, and the result is commonly referred to as a Steak and Guinness Pie (or Guinness Pie for short). A Steak and Ale pie is a similar creation, popular in British pubs, using one of a variety of ales in place of the Guinness. The dish is often served with "steak chips" (thickly sliced potatoes fried, sometimes fried in beef dripping). Steak pies are also available from chip shops, served with normal chips, referred to in Scotland as a steak pie supper.

## Scoring

Your score is the length in bytes of your program and any text files that you use divided by the number of languages that you support. The person with the lowest score wins.

```
score = (length of program + length of text file)/number of languages

```

# Answer
# ///, 8

Correctly identifies one language, Twi. Uses no text file.

```
Twi[Twi]

```
> 4 votes

---
Tags: code-challenge
---


# Question
Title: Empty a Swimming Pool . . . With Only a Red Solo Cup
You have a swimming pool that is filled to the brim with water. You need to empty it, but you can't think of an efficient method. So you decide to use your red solo cup. You will repeatedly fill the cup all the way and dump it outside the pool.

## Challenge

How long will it take to empty the pool?

### Input

`[shape of pool] [dimensions] [shape of cup] [dimensions] [speed]`

* `shape of pool` will be one of these strings: `circle`, `triangle`, or `rectangle`. Note that these actually refer to the 3-dimensional shapes: cylinder, triangular prism, and rectangular prism.
* `dimensions` will be different depending on the shape.
    + circle: `[radius] [height]`. Volume = π r2 h
    + triangle: `[base] [height] [length]`. Volume = 1/2(bh) * length
    + rectangle: `[width] [length] [height]` Volume = lwh
* `shape of cup` and `dimensions` work the same way. The cup can also be either a circle, triangle, or rectangle.
* `speed` is the amount of time it takes to empty one cup full of water **in seconds**.

### Output

The number of **seconds** it takes to empty the swimming pool. This can be rounded to the nearest second.

### Notes

* There will be no units in the input. All distance units are assumed to be the same (a shape won't have a height in inches and a width in feet).
* Use 3.14 for `pi`.
* Input will be made up of strings and floating-point numbers.
* It will never rain. No water will ever be added.
* You have a *very* steady hand. You will fill the cup exactly to the brim every time, and you will never spill any.
* Once you get near the end, it will get hard to scoop up a full cup of water. You do not need to worry about this. You're very strong, so you can tilt the pool onto its side (without using up any more time).
* Anytime you make a calculation, it's okay to **round to the nearest hundredth**. Your final answer will not need to be exact.

### Test Cases

Input: `triangle 10 12.25 3 circle 5 2.2 5`
Output: `10`
Even though there is less than 172.7 left on the last scoop, it still takes the whole five seconds to empty it.

Input: `triangle 5 87.3 20001 rectangle 5.14 2 105.623 0.2`
Output: `804.2`

* You should round to the nearest hundredth after each calculation.
* The **final calculation is rounded up** from 804.05567 to 804.2. This is because that last little bit of water must be emptied.

### Rules

* You can write a full program or function.
* Input should be taken from stdin or function parameters. Output should be printed through stdout or returned.
* The input format can be rearranged, as long as you specify that in the submission. You can also shorten the strings "circle", "triangle", and "rectangle."
* Libraries and built-in functions that involve volume or area are not allowed.

### Scoring

This is . Submission with least number of bytes wins.

# Answer
# JavaScript ES6, ~~100~~ ~~78~~ ~~82~~ ~~81~~ 74 bytes

*Thanks to @UndefinedFunction for helping golf off 4 bytes*

```
(a,z,d,f=([a,g,k,p])=>g*k*(a[6]?p/-~!a[8]:3.14*g))=>Math.ceil(f(a)/f(z))*d

```

Usage:

```
t(["triangle",10,12.25,3],["circle",5,2.2],5);

```
> 6 votes

# Answer
# CJam, 46 bytes

```
{rc:Xr~r~@'c={\_**3.14*}{r~**X't=)/}?}2*/m]r~*

```

Explanation:

```
{                                    }2*       e# Repeat two times:
 rc:X                                          e#   Read a token, take first char, assign to X
     r~r~                                      e#   Read and eval two tokens
         @'c={         }            ?          e#   If the char was 'c':
              \_*                              e#     Square the first token (radius)
                 *                             e#     Multiply by the second one (height)
                  3.14*                        e#     Multiply by 3.14
                        {          }           e#   Else:
                         r~                    e#     Read and eval a token
                           **                  e#     Multiply the three together
                             X't=)/            e#     Divide by 2 if X == 't'
                                               e# Now the two volumes are on the stack
                                        /m]    e# ceil(pool_volume / cup_volume)
                                           r~* e# Read and evaluate token (time) and multiply

```

Try it online.
> 5 votes

# Answer
# Julia, ~~122~~ ~~116~~ ~~95~~ ~~89~~ 79 bytes

```
f(p,P,c,C,s)=(V(a,x)=prod(x)*(a<'d'?3.14x[1]:a>'s'?.5:1);ceil(V(p,P)/V(c,C))*s)

```

This assumes that only the first letter of the shape names will be given. Otherwise the solution is 6 bytes longer.

Ungolfed + explanation:

```
function f(p::Char, P::Array, c::Char, C::Array, s)
    # p - Pool shape (first character only)
    # P - Pool dimensions
    # c - Cup shape (first character only)
    # C - Cup dimensions
    # s - Speed

    # Define a function to compute volume
    function V(a::Char, x::Array)
        prod(x) * (a < 'd' ? 3.14x[1] : a > 's' ? 0.5 : 1)
    end

    # Return the ceiling of the number of cups in the pool
    # times the number of seconds per cup
    ceil(V(p, P) / V(c, C)) * s
end

```

Saved 21 bytes thanks to edc65 and 10 thanks to UndefinedFunction!
> 3 votes

# Answer
# Python 3, ~~340~~ 304 bytes

```
def l(Y,Z):r=Z[1]*3.14*(Z[0]**2)if Y[0]in'c'else Z[0]*Z[1]*Z[2];return r/2 if Y[0]is't'else r
def q(i):import re,math;M,L,F,C=map,list,float,math.ceil;p,d,c,g,s=re.match("(\w)\s([\d .]+)\s(\w)\s([\d .]+)\s([\d.]+)",i).groups();k=lambda j:L(M(F,j.split(' ')));d,g=k(d),k(g);return C(C(l(p,d)/l(c,g))*F(s))

```

**Usage:**

```
q(i)

```

Where `i` is the string of information.

**Examples:**

* `q("t 10 12.25 3 c 5 2.2 5")`
* `q("t 5 87.3 20001 r 5.14 2 105.623 0.2")`

**Note:** The names of the shapes have been shortened to their first letters, respectively.
> 3 votes

# Answer
# Javascript (ES6), 91

Taking input as strings for the shapes, arrays of numbers for the dimensions, and a single number for the speed:

```
(a,b,c,d,e)=>(1+(v=(y,x)=>x[0]*x[1]*(y[6]?x[2]/(y[8]?1:2):x[0]*3.14))(a,b)/v(c,d)-1e-9|0)*e

```

This defines an anonymous function, so to use add `g=` before it. Then, it can be called like `alert(g("triangle", [10, 12.25, 3], "circle", [5, 2.2], 5))`

**Explanation:**

```
(a,b,c,d,e)=>    //define function
                   //a = pool shape, b = pool dimensions
                   //c = cup shape, d = cup dimensions
                   //e = speed

( 1+     //part of the rounding up below

  (v=(y,x)=>       //define volume function

      x[0] * x[1] *     //multiply first 2 values of dimension by:

          (y[6] ?
               x[2] /     //if rectangle or triangle, the 3rd dimension
                   (y[8] ? 1 : 2)     //but if triangle divide by 2
                :
               x[0] * 3.14     //or if circle the radius * pi
          )    //(implicit return)

  )(a,b) / v(c,d)     //call the volume function for the pool/cup, and divide

         -1e-9 |0    //but round up the result

) * e     //and multiply by e
//(implicit return)

```

My original solution took a single string, and was **111 bytes long:**

```
s=>(1+(v=x=>s[i++]*s[i++]*(s[x][6]?s[i++]/(s[x][8]?1:2):s[i-2]*3.14))((i=1)-1,s=s.split` `)/v(i++)-1e-9|0)*s[i]

```

This also defines an anonymous function, so to use add `f=` before it. Then, it can be called like `alert(f("triangle 5 87.3 20001 rectangle 5.14 2 105.623 0.2"))`
> 3 votes

# Answer
# F#, 217 186 184 160 bytes

Damn indentation requirements!

```
let e(p,P,c,C,s)=
 let V(s:string)d=
  match(s.[0],d)with
  |('c',[x;y])->3.14*x*x*y
  |('t',[x;y;z])->((x*y)/2.)*z
  |('r',[x;y;z])->x*y*z
 ceil(V p P/V c C)*s

```

**Usage:**

```
e("triangle",[5.;87.3;20001.],"rectangle",[5.14;2.;105.623],0.2);;

```

**Update**

Thanks to Alex for remarking on single space indentation, which F# seems to support

Managed to knock a load more off by changing from `array` to `list` types in the `match` statement
> 3 votes

# Answer
# K5 (oK), 123 bytes

```
v:{((({y*3.14*x*x};{z*(x*y)%2};{x*y*z})@"ctr"?s)..:'t#1_x;(1+t:2+~"c"=s:**x)_x)};f:{{(.**|r)*_(~w=_w)+w:x%*r:v y}.v[" "\x]}

```
> 3 votes

# Answer
## Python 2.7 306 Bytes

```
import math as z,re
t,m,r,w=float,map,reduce,[e.split() for e in re.split(' (?=[a-z])| (?=\d+(?:\.\d+)?$)',raw_input())]
def f(S,D):i=r(lambda x,y:x*y,D);return((i,i*.5)[S[0]=='t'],3.14*i*D[0])[S[0]=="c"]
print z.ceil(r(lambda x,y:x/y,m(lambda q:f(q[0],q[1:]),m(lambda x:[x[0]]+m(t,x[1:]),w[:-1]))))*t(*w[-1])

```

Takes input from stdin.
Testing it-

```
$ python pool.py
triangle 10 12.25 3 circle 5 2.2 5
10.0
$ python pool.py
triangle 5 87.3 20001 rectangle 5.14 2 105.623 0.2
804.2

```
> 2 votes

# Answer
# Python 2, ~~222~~ ~~146~~ ~~139~~ ~~119~~ ~~103~~ 93 bytes

Fairly straightforward implementation. Thanks to Sp3000 for the `-(-n//1)` trick for ceiling, which *should* work in all cases (i.e. haven't found an issue with it yet).

```
u=lambda q,k,l,m=1:k*l*[3.14*k,m][q>'c']*-~(q<'t')/2.
f=lambda a,b,c,d,s:-u(a,*c)//u(b,*d)*-s

```

Input should be formatted like so:

```
f(shape1, shape2, dimensions1, dimensions2, speed)
"Where shape1 and shape2 are one of 'c','r','t', dimensions1 is a list of the dimensions
 of the first shape, dimensions 2 is a list of the dimensions for the second shape, and
 speed is the speed of emptying in seconds."

```

Usage:

```
>>> f('t', 'r', [5, 87.3, 20001], [5.14, 2, 105.623], 0.2)
804.2
>>> f('t', 'c', [10, 12.25, 3], [5, 2.2], 5)
10.0

```

Ungolfed:

```
import math

def volume(shape, dimensions):
    out = dimensions[0] * dimensions[1]
    if shape == 'c':
        out *= 3.14 * dimensions[0]
    else:
        out *= dimensions[2]
    if shape == 't':
        out /= 2.0
    return out

def do(shape1, shape2, dimensions1, dimensions2, speed):
    volume1 = volume(shape1, dimensions1)
    volume2 = volume(shape2, dimensions2)
    return math.ceil(volume1 / volume2) * speed

```

---

## Original solution, 222 bytes

This was made when the rules still needed you to input the whole word rather than a letter. I used the fact that `hash(s)%5` mapped them to `circle -> 2, triangle -> 3, rectangle -> 1`, however if I just take one letter as input, I think I can get this shorter.

```
from math import*
u=lambda p,q:[[p[0]*p[1]*p[-1],3.14*p[0]**2*p[1]][1<q<3],0.5*p[0]*p[1]*p[-1]][q>2]
def f(*l):k=hash(l[0])%5;d=4-(1<k<3);v=l[1:d];r=hash(l[d])%5;g=4-(1<r<3);h=l[1+d:d+g];s=l[-1];print ceil(u(v,k)/u(h,r))*s

```

Usage:

```
>>> f('triangle',10,12.25,3,'circle',5,2.2,5)
10.0
>>> f('triangle',5,87.3,20001,'rectangle',5.14,2,105.623,0.2)
804.2

```
> 2 votes

# Answer
# Python 2/3, ~~252~~ 249 bytes

```
import re,math;i=[float(x)if re.match('[\d.]+',x)else x for x in re.sys.stdin.readline().split()]
for o in[0,[4,3][i[0]<'d']]:
 w=i[o+1]*i[o+2]*i[o+3]
 if i[o]<'d':w*=3.14*i[o+1]/i[o+3]
 if i[o]>'s':w*=.5
 a=a/w if o else w
print(math.ceil(a)*i[-1])

```

**Usage Examples:**

```
$ echo 'triangle 10 12.25 3 circle 5 2.2 5' | python stack_codegolf_54454.py
10.0
$ echo 'triangle 5 87.3 20001 rectangle 5.14 2 105.623 0.2' | python stack_codegolf_54454.py
804.2

```

The Python 2 only and Python 3 only versions are only different in how they receive input; `raw_input()` for Python 2 and `input()` for Python 3, as opposed to `re.sys.stdin.readline()` for the Python2/3 version.

# Python 2, ~~240~~ 237 bytes

```
import re,math;i=[float(x)if re.match('[\d.]+',x)else x for x in raw_input().split()]
for o in[0,[4,3][i[0]<'d']]:
 w=i[o+1]*i[o+2]*i[o+3]
 if i[o]<'d':w*=3.14*i[o+1]/i[o+3]
 if i[o]>'s':w*=.5
 a=a/w if o else w
print(math.ceil(a)*i[-1])

```

# Python 3, ~~236~~ 233 bytes

```
import re,math;i=[float(x)if re.match('[\d.]+',x)else x for x in input().split()]
for o in[0,[4,3][i[0]<'d']]:
 w=i[o+1]*i[o+2]*i[o+3]
 if i[o]<'d':w*=3.14*i[o+1]/i[o+3]
 if i[o]>'s':w*=.5
 a=a/w if o else w
print(math.ceil(a)*i[-1])

```

**Changes:**

Changed `for o in[0,3if i[0]<'d'else 4]:` to `for o in[0,[4,3][i[0]<'d']]:`. Thanks to Vioz for the inspiration :).
> 1 votes

# Answer
# Pyth - 40 39 36 ~~35~~ 34 bytes

Uses simple method, mapping over both containers and then reducing by division.

```
*h/Fmc*Ftd@,/JChd58c.318@d1Jc2PQeQ

```

Takes input comma separated from stdin, with the first letter of each shape like: `"t", 10, 12.25, 3, "c", 5, 2.2, 5`.

Test Suite.
> 1 votes

---
Tags: code-golf, math, geometry
---


# Question
Title: Help, I'm trapped in an infinite factory!
*This challenge is loosely inspired by the Zachtronics game Infinifactory.*

You are given a top-down view of a rectangular grid of conveyors, represented by `>v<^`. There may be cells without conveyors, represented by spaces. Here is an example:

```
> <vv    <
 v ^ >v v
  >v^^>vv^
    ^>^ v
>  v<v  >>
  >v v<^

```

This setup is implicitly surrounded by an infinite number of spaces.

Furthermore, you are given the dimensions of a rectangular piece of cargo which is placed onto the conveyors in the top left corner of the grid. Your task is to figure out whether the cargo ever comes to rest or whether it will end up moving in a loop.

Of course, the cargo is likely to cover several conveyors at once, so here are the rules for figuring out the direction of the cargo in each step:

1. Opposite conveyors cancel each other. So if a 3x2 cargo covers any of the following patches (outlined with hyphens and pipes for clarity), the result would be the same:

```
+---+   +---+   +---+
|>>^|   |  ^|   |v^^|
|^<<|   |^  |   |^^v|
+---+   +---+   +---+

```

The same goes for these:

```
+---+   +---+   +---+
|v^<|   |   |   |><>|
|>>>|   |>> |   |>><|
+---+   +---+   +---+

```

Since the exact position of a conveyor underneath the cargo is irrelevant, it doesn't matter which pairs you cancel.

This cancellation is applied before the other rules. Therefore, for the other rules there will only be conveyors in at most two directions.
2. If the cargo doesn't cover any conveyors at all (either because all conveyors cancel, because it covers only spaces or because it moved fully off the grid), it comes to rest.
3. If the cargo covers more conveyors of one direction than of the other, the cargo moves in that direction. E.g., if a 3x2 cargo covered the following patch

```
>>
^>^

```

it would move to the right, because there are more `>` than `^`. On the other hand, if it covered

```
>>^
  ^

```

this rule would not apply, because there's a tie between `>` and `^`.
4. This leaves only cases in which there is a tie between adjacent directions (a tie between opposite directions would have cancelled). In this case, the cargo keeps moving along the axis it is already moving in. E.g. if a right-moving *or* left-moving 3x2 cargo is now covering the patch

```
>>^
^

```

it would move to the right. If it had arrived on this patch moving up or down, it would now move up instead. If this kind of conflict occurs on the very first step of the simulation, assume that the cargo had been moving to the right.

## Detailed Examples

Consider the conveyor grid at the top and a 3x2 cargo. The following is a step-by-step visualisation of the process. Each step consists of the grid, with the cargo represented by `#`, a small box which shows the conveyors covered by the cargo, another box with the conveyors after cancellation, and the rule that determines where the cargo moves:

```
 ###vv    <    > <vv    <    > <vv    <    > <vv    <    > <vv    <    > <vv    <
 ###^ >v v     ###^ >v v      v ^ >v v      v ^ >v v      v ^ >v v      v ^ >v v
   >v^^>vv^    ###v^^>vv^    ###v^^>vv^     ###^^>vv^      ###^>vv^      >###>vv^
     ^>^ v         ^>^ v     ### ^>^ v      ###^>^ v       ###>^ v        ###^ v
 >  v<v  >>    >  v<v  >>    >  v<v  >>    >  v<v  >>    >  v<v  >>    >  v<v  >>
   >v v<^        >v v<^        >v v<^        >v v<^        >v v<^        >v v<^

+---+  +---+  +---+  +---+  +---+  +---+  +---+  +---+  +---+  +---+  +---+  +---+
|> <|  |   |  | v |  | v |  |  >|  |  >|  | >v|  | >v|  |>v^|  |> ^|  |v^^|  | ^^|
| v |  | v |  |  >|  |  >|  |   |  |   |  |   |  |   |  |  ^|  |   |  | ^>|  |  >|
+---+  +---+  +---+  +---+  +---+  +---+  +---+  +---+  +---+  +---+  +---+  +---+

   Rule 3        Rule 4        Rule 3        Rule 4        Rule 4        Rule 3

 ================================================================================

 > <vv    <    > <###   <    > <vv    <
  v ###v v      v ###v v      v ###v v
   >###>vv^      >v^^>vv^      >###>vv^
     ^>^ v         ^>^ v         ^>^ v
 >  v<v  >>    >  v<v  >>    >  v<v  >>
   >v v<^        >v v<^        >v v<^

+---+  +---+  +---+  +---+  +---+  +---+
|^ >|  |  >|  |vv |  | v |  |^ >|  |  >|
|v^^|  | ^^|  |^ >|  |  >|  |v^^|  | ^^|
+---+  +---+  +---+  +---+  +---+  +---+

   Rule 3        Rule 4        Rule 3

```

At this point, the cargo enters a loop between the last two frames.

Now consider a 2x3 cargo instead:

```
 ##<vv    <    >##vv    <    > <vv    <    > <vv    <    > <vv    <    > <vv    <
 ## ^ >v v      ##^ >v v      ##^ >v v      v ^ >v v      v ^ >v v      v ^ >v v
 ##>v^^>vv^     ##v^^>vv^     ##v^^>vv^     ##v^^>vv^      ##^^>vv^      >v^^>vv^
     ^>^ v         ^>^ v      ## ^>^ v      ## ^>^ v       ##^>^ v       ##^>^ v
 >  v<v  >>    >  v<v  >>    >  v<v  >>    >##v<v  >>    > ##<v  >>    > ##<v  >>
   >v v<^        >v v<^        >v v<^        >v v<^        >v v<^        ## v<^

 +--+  +--+    +--+  +--+    +--+  +--+    +--+  +--+    +--+  +--+    +--+  +--+
 |> |  |> |    | <|  |  |    |v |  |v |    | >|  | >|    |>v|  |>v|    |  |  |  |
 | v|  | v|    |v |  |v |    | >|  | >|    |  |  |  |    |  |  |  |    | v|  | v|
 |  |  |  |    | >|  |  |    |  |  |  |    |  |  |  |    | v|  | v|    |>v|  |>v|
 +--+  +--+    +--+  +--+    +--+  +--+    +--+  +--+    +--+  +--+    +--+  +--+

   Rule 4        Rule 3        Rule 4        Rule 3        Rule 3        Rule 3

 ================================================================================

 > <vv    <    > <vv    <    > <vv    <
  v ^ >v v      v ^ >v v      v ^ >v v
   >v^^>vv^      >v^^>vv^      >v^^>vv^
     ^>^ v         ^>^ v         ^>^ v
 > ##<v  >>    >  v<v  >>    >  v<v  >>
   ## v<^        ## v<^        >v v<^
   ##            ##            ##
                 ##            ##
                               ##

 +--+  +--+    +--+  +--+    +--+  +--+
 | v|  | v|    |>v|  |>v|    |  |  |  |
 |>v|  |>v|    |  |  |  |    |  |  |  |
 |  |  |  |    |  |  |  |    |  |  |  |
 +--+  +--+    +--+  +--+    +--+  +--+

   Rule 3        Rule 4        Rule 2

```

In the last step, rule 2 applies because the cargo has moved off the grid, so it comes to rest and there won't be a loop.

## Rules and Assumptions

Your input will be the conveyor grid as described above along with the width and height of the cargo. You may take these three parameters in any convenient order and format. For the grid, this means that you can read a single string with lines separated by newlines or other characters, or an array of strings, or an array of arrays of characters, as long as the individual grid cells are still represented by the characters `>v<^` and spaces.

You should output a truthy value if the setup results in a loop of at least two frames or a falsy value if the cargo will come to rest.

You may assume that the grid will be padded to a rectangle with spaces, and that the cargo will initially fit into the grid.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

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

## Test Cases

The test cases are grouped by grids.

```
Grid (2x2):

>v
^<

Width  Height  Loop?
1      1       True
1      2       True
2      1       True
2      2       False

Grid (3x3):

> v

^ <

Width  Height  Loop?
1      1       False
1      2       False
1      3       False
2      1       False
2      2       True
2      3       True
3      1       False
3      2       True
3      3       False

Grid (4x3):

>^>v
v^v
^ <<

Width  Height  Loop?
2      2       False

Grid (6x5):

>v>v>v
^v^v^v
^v^v^v
^>^>^v
^<<<<<

Width  Height  Loop?
1      1       True
1      2       False
2      1       True
2      2       True
2      4       True
2      5       False
3      1       False
3      2       True
3      3       True
3      5       True
6      2       False
6      3       True
6      5       False

Grid (10x6):

> <vv    <
 v ^ >v v
  >v^^>vv^
    ^>^ v
>  v<v  >>
  >v v<^

Width  Height  Loop?
1      1       False
2      3       False
2      6       False
3      2       True
5      4       False
6      1       True
10     6       False

```

As an additional set of test cases, consider that any input where the grid consists solely of spaces must yield a falsy result.

I've checked all the test cases manually, so let me know if you think I've made a mistake.

# Answer
# Ruby, ~~306 298 251 204~~ 198

```
->g,w,h{m=->y,x,d,v=[]{q=y,x
r=->s{([""]*h+g)[y+h,h].map{|l|(?x*w+l)[x+w,w]}.join.count s}
z=k=r[?v]-r[?^],j=r[?>]-r[?<]
q[d=[d,1,0][j*j<=>k*k]]+=z[d]<=>0
v&[q<<d]!=[]?q!=v[-1]:m[*q,v<<q]}
m[0,0,1]}

```

**Edit:** Thanks a lot to Ventero who shortened the code a lot by applying some amazing tricks!

### Input and output

The code represents a ruby function that takes three parameters:

* the grid, represented as an array of strings (each row is a different string)
* the width of the cargo
* the height of the cargo

It returns `1` (truthy) in case there's a loop, or `nil` (falsy) in case the cargo rests.

### Tests

Here it is passing all of Martin's tests: http://ideone.com/zPPZdR

### Explanation

There are no clever tricks in the code; it's a pretty straightforward implementation of the rules.

In the code below, `move` is a recursive function that makes a move according to the rules, and:

* returns truthy in case of a loop
* returns falsy in case of a rest
* otherwise calls itself to execute the next move

A more readable version is available here.

***Note:** the golfed code has undergone several modifications and is no longer similar to the readable version.*
> 7 votes

# Answer
# Julia - ~~394~~ ~~300~~ ~~246~~ 214 bytes

```
f(A,x,y)=(Z=sign;(S,T)=size(A);X=x+1;Y=y+1;G=fill(5,S+2y,T+2x);G[Y:S+y,X:T+x]=A;C=0G;D=1;while C[Y,X]!=D C[Y,X]=D;i,j=sum(i->1-[19 8]i%82%3,G[Y:Y+y-1,X:X+x-1]);D=Z(2i^2-2j^2+(i!=0)D);X+=Z(i+D*i);Y+=Z(j-D*j)end;D^2)

```

Returns 1 if the cargo loops, and 0 if it comes to a stop. It's not "strictly" truthy/falsy, in that Julia doesn't permit 0 and 1 in boolean contexts... but I consider values `x` for which `bool(x)==true` are truthy and `bool(x)==false` are falsy.

Input `A` should be of the form of a character array. If you're copy/pasting the conveyor grid, you'll need to get it into the appropriate form. To save you from having to manually handle it, use the following:

```
A=foldl(hcat,map(collect,split("""(PASTE GRID HERE)""","\n")))'

```

Where obviously, `(PASTE GRID HERE)` should be replaced with the grid itself. Double-check the spaces at the end of each line, to make sure it actually has all of the spaces (it doesn't check to make sure that all lines are equal length). Note that this line isn't part of the actual solution code, just a convenient piece of code to make using the solution code a bit easier.

Ungolfed:

```
function f(A,x,y)
  # Determine size of grid for use later
  (S,T)=size(A)
  # Initialise starting position (performed here to save characters)
  X=x+1
  Y=y+1
  # Create an expanded field that is functionally "spaces" (to provide
  # spaces at edges for the cargo to stop in)
  G=fill(5,S+2y,T+2x)
  # Put the conveyor grid into centre of the expanded field
  G[Y:S+y,X:T+x]=A
  # Create an array storing the most recent movement direction:
  # will use 1=horizontal, -1=vertical, 0=stopped
  C=0G
  # Initialise current direction (same system as C)
  D=1
  # Loop until it finds itself repeating a coordinate/direction pair
  while C[Y,X]!=D
    # Mark current coordinate/direction pair in array
    C[Y,X]=D
    # Determine the net coordinate pairing, stored in two variables
    # for golf purposes *SEE NOTE*
    i,j=sum(i->1-[19 8]i%82%3,G[Y:Y+y-1,X:X+x-1])
    # Determine new movement axis (if D=0, cargo stopped)
    D=sign(2i^2-2j^2+(i!=0)D)
    # Update X or Y depending on signs of D and the appropriate direction
    X+=sign(i+D*i)
    Y+=sign(j-D*j)
  end
  # if D=±1, return 1 (cargo is still moving), otherwise return 0
  return D^2
end

```

Note: `1-[19 8]i%82%3` has been chosen to map the five possible characters to the appropriate coordinate pairs by the most efficient method I could find. This is also the reason for using 5 to fill the spaces when creating `G` \- it's a single-digit character that maps to `[0 0]`.

Example of usage:

```
julia> A=foldl(hcat,map(collect,split(""">v>v>v
       ^v^v^v
       ^v^v^v
       ^>^>^v
       ^<<<<<""","\n")))';

julia> f(A,2,1)
true

julia> f(A,3,3)
true

julia> f(A,5,2)
false

```
> 8 votes

# Answer
# Python 2, 207 bytes

```
def f(L,w,h,u=0,v=0,D=1,S=[]):a,b,c,d=map(`[r[u*(u>0):u+w]for r in L[v*(v>0):v+h]]`.count,"v^><");D=cmp(abs(a-b),abs(c-d))<D;T=u,v,D;return T in S or a-b|c-d and f(L,w,h,u+cmp(c,d)*D,v+cmp(a,b)*0**D,D,S+[T])

```

Input the grid as a list of rows, e.g.

```
['>v>v>v', '^v^v^v', '^v^v^v', '^>^>^v', '^<<<<<']

```

followed by the width and height. Returns `0` or `True` accordingly.

## Explanation

```
def f(L,          # Grid
      w,h,        # Width, height of cargo
      u=0,v=0,    # Position of top-left of cargo, initially (0, 0)
      D=1,        # Moving left/right = 1, up/down = 0
      S=[]        # Seen (pos, axis) pairs, initially empty
     ):

     # Arrows under cargo - no need for "".join since we only need to count v^<>
     A = `[r[u*(u>0):u+w]for r in L[v*(v>0):v+h]]`

     # Count for each arrow
     a,b,c,d=map(A.count,"v^><")

     # Golfed form of abs(a-b) < abs(c-d) or (abs(a-b) == abs(c-d) and D == 1)
     D=cmp(abs(a-b),abs(c-d))<D
     T=u,v,D

     return (T in S                # Return True if (pos, axis) previously seen
             or a-b|c-d               # Return 0 if all conveyors cancel
             and f(L,w,h,             # Otherwise, recurse
                   u+cmp(c,d)*D,      # Update u if moving left/right
                   v+cmp(a,b)*0**D,   # Update v if moving up/down
                   D,
                   S+[T]          # Add (pos, axis) to seen
                  )
            )

```
> 8 votes

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


title: Shortening a long number

text:
# Question
Title: Shortening a long number
When dealing with long numbers when code golfing, getting the length of your code down can be difficult, so do you have any tips for making a number shorter and easier to manage?

For example, the following Pyth code prints "Hello world", but at 44 bytes, that is unsatisfactory:

```
Vcjkj85942000775441864767076 2 7=k+kCiN2)k

```

So how would I shorten the long number, `85942000775441864767076`?

# Answer
> 10 votes
Perfect timing for this question. @isaacg just added a new feature today, that allows to shorten such numbers immensely.

The basic technique is to convert the number to base 256 and convert it to chars. You can do this using the code `++NsCMjQ256N`. You can then use the resulting string in combination with `C`, which does exactly the opposite (convert chars to int and interpret the result as base-256 number). So you get 13 chars: `C"2ìÙ½}ü¶d"`. Some of the chars are unprintable.

But notice that I said 13 CHARS, not bytes. If I copy the chars and count the with https://mothereff.in/byte-counter, it says 13 chars and 18 bytes. This is due the character encoding of chars, which is UTF-8 by default. And UTF-8 only allows 2^7 different 1-byte character. Every char `c` with `ord(c) > 127` actually gets stored using two bytes instead of one.

And here come's @isaacg's new feature into play. He changed the default code-format from UTF-8 to iso-8859-1. iso-8859 can represent 256 characters with only 1 byte. So now you can actually reach 13 BYTES. This is only possible with the standard compiler though, this doesn't work in the online compiler.

First you want to convert the number to hex-values by using this script: `jdm.[2.Hd"0"jQ256`. This gives you `12 32 ec d9 bd 07 7d fc b6 64`. Afterwards copy those numbers into your code-file using a hex-editor (e.g. hexedit for linux).

Notice:

* Obviously you remove the `"` at the end, if the string is the last part of the code.
* This only works if there is no `34` (the byte `22`) in the base-256 representation of you numbers, since this is the `"` char and will end the string. Escaping works though (`5C 22`).
* Btw, when you open a file with a hex-editor you will likely see the byte `0A` or `0d 0a` at the end, which you can remove. This only indicates the end of the line.

---
Tags: code-golf, tips, pyth
---


title: Two Makes All The Difference - Robbers

text:
# Question
Title: Two Makes All The Difference - Robbers
# For the main cops' challenge, click here

> **NOTICE** \- This challenge is now closed. Any cracks which are posted now will not be counted on the leaderboard and the accepted answer will *not* change.

## Challenge

Given the original program, its output and the output of the changed program, you have to find out which characters need to be changed, removed or added to get the expected output.

When you crack someone's code, leave a comment with a link to your crack on their answer.

## Formatting

```
# [<language>, <username of program owner>](<link to answer>)

## Description

<description of change and how you found it>

## Code

<changed code>

```

## Winning

The person who has cracked the most solutions wins.

## Leaderboard

### 13 cracks:

* Dennis

### 8 cracks:

* Alex Van Liew

### 5 cracks:

* Sp3000
* isaacg

### 3 cracks:

* Luis Mendo
* jimmy23013
* Dom Hastings

### 2 cracks:

* mbomb007
* Sluck49

### 1 crack:

* TheNumberOne
* Jakube
* ProudHaskeller
* David Zhang
* samgak
* paul.oderso
* rayryeng
* mgibsonbr
* n̴̖̋h̷͉̃a̷̭̿h̸̡̅ẗ̵̨́d̷̰̀ĥ̷̳
* Stewie Griffin
* abligh

# Answer
# CJam, by Mauris

### Description

Mauris' original code does the following:

```
"f~"     e# Push that string on the stack.
    :i   e# Cast each to integer. Pushes [102 126].
      :# e# Reduce by exponentiation. Pushes 102^126.

```

No other of CJam's mathematical operators would yield a number that large for small inputs, so `:#` cannot be modified. Since `#`, when used for exponentiation, only takes integers as input, `:i` cannot be removed as well. This leaves only one place to modify the input: the string `"f~"`.

No matter how many characters the string holds, the result will be a left-associative power tower. CJam supports characters in the range from 0 to 65535 (with the exception of surrogates), so we have to express the output as **bn×k×j**, where **b**, **n**, **k** and **j** are integers in that range.

The decimal logarithm of the integer that results from the modified code is slightly smaller than **log10(2.44×10242545) = log10(2.44) + 242545**, so we can divide this value by the logarithms of all possible bases to find proper values for **n×k×j**.

In fact:

```
$ cjam <(echo '65536,2>{2.44AmL242545+1$AmL/i:I#s8<"24399707"=}=SIN')
5 347004

```

Comparing the first 8 digits turned out to be sufficient.

This means that we can express the output as **5347,004 = 1562557,834 = 1259×102×126**, so it suffices to **replace `"f~"` with `"㴉"` or `"} f~"`**.

### Code

```
"㴉":i:#

```

or

```
"}  f~":i:#

```

Note that the spaces in the ASCII code should actually be a tabulator.

Attempting to execute this code in the online interpreter is probably a bad idea, but here's how you can verify the results from the command line:

```
$ wget -q https://bpaste.net/raw/f449928d9870
$ cjam <(echo '[15625 57834]:c`":i:#") > mauris.cjam
$ cat mauris.cjam; echo
"㴉":i:#
$ cjam mauris.cjam | diff -s - f449928d9870
Files - and f449928d9870 are identical
$ echo -en '"}\tf~":i:#' > mauris-ascii.cjam
$ cat mauris.cjam; echo
"}  f~":i:#
$ cjam mauris-ascii.cjam | diff -s - f449928d9870
Files - and f449928d9870 are identical

```
> 10 votes

# Answer
# Ruby, histocrat

## Description

Changed x to be an array instead of scalar by adding `*`

Changed the last `9` to be a string instead of a number by adding `?`

The result is made of an array with a single element (`[9]`) multipled 9 times then imploded with `"9"` as separator.

## Code

```
x=*9;puts x*9*?9

```
> 15 votes

# Answer
# Python 2, muddyfish

## Description

Through trials and tribulations involving factorizing large numbers and looking for consequtive factors, I realized that changing the 87654 to 58116 would be enough. Then, I factorized 58116 as 87\*668. Then I realised that 01234 = 668, so I just needed to change 87654 to 87 and remove the 01234 entirely. This is accomplished with a comment.

## Code

```
print (sum(range(054321)*9876)*87)#654)/01234

```
> 12 votes

# Answer
# Shakespeare, AboveFire

In Scene III, one has to change Claudius into Claudio in the following snippet:

```
[Enter Claudio]

Claudius:
 Thou art as stupid as the sum of thee and the product of the
 product of me and Helen and Helena

[Exeunt]

```

## Modified code:

```
The Hidden Change.

Helen, a young woman with a remarkable patience.
Helena, a likewise young woman of remarkable grace.
Claudio, a remarkable man much in dispute with Claudius.
Claudius, the flatterer.
The Archbishop of Canterbury, the useless.

          Act I: Claudius's insults and flattery.

          Scene I: The insulting of Helen.

[Enter Claudius and Helen]

Claudius:
 Thou art as hairy as the sum of a disgusting horrible fatherless
 dusty old rotten fat-kidneyed cat and a big dirty cursed war.
 Thou art as stupid as the product of thee and a fat smelly
 half-witted dirty miserable vile weak son.

[Exeunt]

          Scene II: The complimenting of Helena.

[Enter Claudio and Helena]

Claudio:
 Thou art the sunny amazing proud healthy peaceful sweet joy.
 Thou art as amazing as the product of thee and the pretty
 lovely young gentle handsome rich Hero. Thou art as great
 as the sum of thee and the product of a fair golden prompt good honest
 charming loving noble king and a embroidered rich smooth golden angel.

[Exeunt]

          Scene III: The insulting of Claudio

[Enter Claudius and Helen]

Helen:
 Thou art as stupid as the sum of the sum of thee and a cat and me.
[Exit Helen]

[Enter Claudio]

Claudio:
 Thou art as stupid as the sum of thee and the product of the
 product of me and Helen and Helena

[Exeunt]

          Scene IV: The Final Countdown

[Enter The Archbishop of Canterbury and Claudius]

Claudius:
 Thou art the sum of you and a cat.

The Archbishop of Canterbury:
 Am I better than a fine road?

Claudius:
 If not, let us return to the insulting of Claudio.

[Exit The Archbishop of Canterbury]

[Enter Claudio]

Claudius:
 Open your heart!
 Open your heart!
[Exeunt]

```

Using the compiler linked by @AboveFire, this prints `11`.
> 11 votes

# Answer
# Prolog, Fatalize

## Description

Add two `\`s. `\` is bitwise negation and `\/` is bitwise or.

## Code

```
X is \1\/42.

```
> 10 votes

# Answer
## MATLAB/OCTAVE, Stewie Griffin

A simple bit of complex arithmetic.

```
acos(i)

```
> 8 votes

# Answer
# C, LambdaBeta

## Description

Turn `main(a,_)` into `main(_)`. The first argument of main is `argc` which is initialized as `1`.

## Code

```
main(_){puts(_*_-1||_*_*_-1||_*_*_*_-1?"Expected Output":"?");}

```
> 7 votes

# Answer
# Python 2, rp.belrann

Change the outermost list comprehension into a set comprehension. Partial credit to @mbomb007, who eliminated all of the "boring" solutions (swapping `x` and `y` around, tweaking operators, changing the range).

```
'~'*sum({(x,y)[x%2] for x in[y for y in range(8)]})

```

### Explanation:

In the original, `[(x,y)[x%2]for x in[y for y in range(8)]]` generates the following list:

```
[0, 7, 2, 7, 4, 7, 6, 7]

```

This is because in Python 2.7, the `y` in the inner list comprehension *leaks* into the enclosing scope at it's last known value (which, at the end of a range, is 7). So, in the tuple, `y` is always 7. `x`, however, goes through the list as normal, ranging from 0 to 7. When `x` is even, it chooses the value of `x`, when it's odd, it chooses `y` (which is always 7). I noticed that if I included exactly one 7 and all the rest of the values of `x`, I got 19; then I realized that I could transform the outer comprehension into a set comprehension, which would eliminate all duplicate values and leave me with exactly 19.

This was pretty clever, I don't think I've ever used a set comprehension before. Kudos.
> 6 votes

# Answer
# Jonas, Matlab/Octave

## Description

I noticed the answer was `i^pi`, so then I justed had to turn `sin` into a nop.

## Code

```
0i+(i^pi)

```

`s` -\> `0`, `n` -\> `+`
> 6 votes

# Answer
# Bash, Dennis

Original code:

```
echo {{{1..9}}}

```

Original output:

```
{{1}} {{2}} {{3}} {{4}} {{5}} {{6}} {{7}} {{8}} {{9}}

```

Modified code:

```
echo {,{1..9},}

```

Modified output:

```
1 2 3 4 5 6 7 8 9

```

Explanation:

In Bash you can output a comma separated list of items inside a pair of braces, like this:

```
echo {a,b,c}

```

prints

```
a b c

```

So the modified code is printing out a list of nothing, the numbers 1..9, nothing.
> 5 votes

# Answer
# MATLAB, Luis Mendo

Original code:

```
-sin(2:.5:3)
ans =
   -0.9093   -0.5985   -0.1411

```

New answer:

```
psi(2:.5:3)
ans =
    0.4228    0.7032    0.9228

```

# Description:

Changed `-sin` to `psi`, the polygamma function in MATLAB. The `-` sign is substituted by `p` and the `n` is removed.
> 5 votes

# Answer
# Brainfuck, Kurousagi

## Description

Remove the first `>` and change the first `<` to `.`

Tested at brainfuck.tk. Note that the output doesn't match Kurousagi's post *exactly*, due to SE eating up unprintable characters.

## Code

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

```
> 4 votes

# Answer
# C, LambdaBeta

## Description

Change `-1` into `*0` so that the result of the multiplication is `0` (a falsy value).

## Code

```
main(a,_){puts(_*_*_*_*_*0?"Expected Output":"?");}

```
> 4 votes

# Answer
# Fantom, Cain

Security through obscurity is a very poor form of security (especially when the two methods are right next to each other in the Fantom docs and anyone who knows what a float looks like will immediately know what to do).

```
Float.makeBits32(1123581321)

```
> 4 votes

# Answer
# CJam, by Basset Hound

```
25me

```

Calculates **e25**. Try it online.

The online interpreter gives a slightly different result in my browser, which seems to be a rounding issue.

The Java interpreter prints `7.200489933738588E10`, which is the desired output, but in a different format.
> 4 votes

# Answer
# Python 2, Sp3000

## Description

Changed `01234` to `0x1234` and `min` to `9in`.

The fact that `4669 = (01234-1)*sum(m<<m in R for m in R)` is misleading.

## Code

```
R=range(0x1234);print sum(m<<9in(m,n)for m in R for n in R)

```
> 4 votes

# Answer
# MATLAB / Octave, Stewie Griffin

## Description

This required negating the input into the anonymous function `g`, as well as changing the scaling factor of the `g` function to 2 instead of 7:

## Code

```
>> f=@(x)x^.7;g=@(x)2/f(x);g(-7)

ans =

  -0.3011 - 0.4144i

```
> 4 votes

# Answer
# Perl, abligh

## Description

Add in string repetition operator, `x` and insert additional digit!

## Code

```
print sin 95x7

```
> 4 votes

# Answer
# Java, TheNumberOne

## Description

The program is a one-off implementation of `Random.next()` with a initial seed of `Integer.MAX_INT` and all the hex numbers converted to decimal. Changing the seed to the complement of `MAX_INT` generates the output:

```
class T{public static void main(String[]a){System.out.print(((~Integer.MAX_VALUE^25214903917L)&281474976710655L)*25214903917L+11L&281474976710655L);}}

```

(since there must be exactly two changes, pick any sort of no-op change: adding a space somewhere, an extra semicolon, etc)
> 3 votes

# Answer
# Brainfuck, AboveFire

this program is a modification of this code me a cookie answer. that answer works by first pre-calculating a table of useful ascii codes of useful characters, and then has three conditional statements made up by three loops which are entered to by having a `1` in the correct position.

the start of how i broke the code is that the repeating pattern in the changed output is mostly what is printed if you enter the third loop with the table shifted left.

```
++++++++++[->++++++++<]>>++++++[-<---------->]<-------[----------->>>-<<+<[->->+<<]]>>>+<<>>>+++[->++++++++++<]>(<)++ .<+++++++++[->>>>>>>++++++++++<+++++<++++++++++++++<++++++++++<+++++<++++++++++<<]++++++++++>>+++++...>++>++>-->+>(>)++++<<<<<<<.<<<[->>>>>>.<<>>>>>.<<<<<.>>>>>.<<<<<>>>.<<<<.>>>>>.<<<<.>>>>>.<<<<<.>>>>.<<<<<.>>>>.<<...>.<<<<<<]>[->>>>>.<<...>>>.<<<<.>>>>>.<<<<...>>>>.<<<<<.>>>>.<<...>.<<<<<]>[->>>>.<<>>>>>>.<<<<<<..>>>.<<<<.>>>>>.<<<<>>>>>>.<<<<<<.>>>>>>.<<<<<<>>>>.<<<<<.>>>>.<<...>.<<<<]

```

(the additional characters are marked with parentheses)
> 3 votes

# Answer
# Python 2, muddyfish

## Description

Change `<<` to `<>` (deprecated version of `!=`) and `0x156` to `0156`, the code point for `"n"` (which appears 3 times in the length 23 string `'<built-in function sum>'`).

## Code

```
print sum((ord(i)<>0156 for i in `sum`))

```
> 3 votes

# Answer
# JavaScript, by Razvan

### Description

The modified output is clearly Euler's natural number, which can be accessed as `Math['E']`.

By changing `''` to `'3'` and `32` to `36`, `String.fromCharCode` generates the `E`.

### Code

```
a=1,b=a*2,c=a+b,d=[a+b];while(c>b)c-=a;for(i=1;i<=c;i++)d.push(i);i='3'+c*d['length']*d['length'];alert(Math[String.fromCharCode(i.charCodeAt(0) * i.charCodeAt(1) / 36)])

```
> 3 votes

# Answer
# Fantom, Cain

## Description

The array indexing is set up already, so I just need to make a 55. Honestly, the hardest part was downloading the language.

## Code

```
[7115432d/9,219.or(64),37,55,55][3]

```

(Inserted a comma, `0` -\> `3`)
> 3 votes

# Answer
# Shakespeare, AboveFire

# NOT CORRECT - sorry :(

Will look further into it when i get home from work In the original Claudio's value is 1132462081 and Claudius' value is 1

In the final Scene Claudio's value is printed twice,

```
[Enter Claudio]

Claudius:
 Open your heart!
 Open your heart!

```

open your heart x2 = print value of the other person on stage (Claudio). So if you change Claudius to Claudio(2 chars) - the value of Claudius will be printed - which is 1 - twice

```
The Hidden Change.

Helen, a young woman with a remarkable patience.
Helena, a likewise young woman of remarkable grace.
Claudio, a remarkable man much in dispute with Claudius.
Claudius, the flatterer.
The Archbishop of Canterbury, the useless.

          Act I: Claudius's insults and flattery.

          Scene I: The insulting of Helen.

[Enter Claudius and Helen]

Claudius:
 Thou art as hairy as the sum of a disgusting horrible fatherless
 dusty old rotten fat-kidneyed cat and a big dirty cursed war.
 Thou art as stupid as the product of thee and a fat smelly
 half-witted dirty miserable vile weak son.

[Exeunt]

          Scene II: The complimenting of Helena.

[Enter Claudio and Helena]

Claudio:
 Thou art the sunny amazing proud healthy peaceful sweet joy.
 Thou art as amazing as the product of thee and the pretty
 lovely young gentle handsome rich Hero. Thou art as great
 as the sum of thee and the product of a fair golden prompt good honest
 charming loving noble king and a embroidered rich smooth golden angel.

[Exeunt]

          Scene III: The insulting of Claudio

[Enter Claudius and Helen]

Helen:
 Thou art as stupid as the sum of the sum of thee and a cat and me.
[Exit Helen]

[Enter Claudio]

Claudius:
 Thou art as stupid as the sum of thee and the product of the
 product of me and Helen and Helena

[Exeunt]

          Scene IV: The Final Countdown

[Enter The Archbishop of Canterbury and Claudius]

Claudius:
 Thou art the sum of you and a cat.

The Archbishop of Canterbury:
 Am I better than a fine road?

Claudius:
 If not, let us return to the insulting of Claudio.

[Exit The Archbishop of Canterbury]

[Enter Claudio]

Claudio: << changed Claudius to Claudio
 Open your heart!
 Open your heart!
[Exeunt]

```
> 3 votes

# Answer
# Matlab / Octave, Jonas

## Description

In the last line, add `'` to transform `arg'` into the string `'arg'`, which will then be interpreted as ASCII numbers. And then add another `'` at the end to maintain the column format.

The almost unnecessary `'` in the original code was the main clue. Also, in restrospect, the fact that `arg` was defined separately (instead of directly within the `sin` line) should have looked suspicious.

## Code

```
format long
arg = [.1 .2 .3];
sin('arg'*exp(9))'

```
> 3 votes

# Answer
# VBA by JimmyJazzx

Changed `IRR` to `MIRR` and changed `5` to a `,` so there are 3 parameters.

I found this while looking for how Excel's `IRR` function works. There was an article: How Excel's MIRR Function Can Fix the IRR Function. That tipped me off. Clever attempt, though. I'd never used VBA before, so that was interesting as well.

```
Sub q()
Dim a(2) As Double
a(0)=-5
a(1)=10
msgBox MIRR(a,0.2,3)
End Sub

```
> 3 votes

# Answer
# bc, abligh

Merely inserted the math operators. Took about 1 minute to solve once I looked up what bc was and what math operations it had. The first thing I thought of was division, but there weren't common factors that looked nice. So I immediately went for exponentiation and modulus. At least 15 digits were necessary for the modulus b/c of the expected output. After that, I guessed twice and found it.

```
4518^574%615489737231532

```
> 3 votes

# Answer
# Lua, TreFox

## Description

"\_G" is the global table, making "\_G.load" refer to the global function "load". Converting a function to a string results in returning the function's address, which is then made into the length of the string by the length-operator "#".

## Code

```
G={load="lfkjgGsHjkU83fy6dtrg"}
print(#tostring(_G.load))

```

Also, since this is my first post on here, I can't make a comment on the original answer.
> 3 votes

# Answer
# Python, rp.beltran

## Description

I noticed that the needed letters were always 2 in front of a digit. changing the third `\w` to `\d` got all of the right letters except the spaces. `\D` was the only `\` group I could find that allowed letters and spaces.

## Code

```
import re;''.join(re.findall('\D(?=\w\d)','t74q joh7 jv f9dfij9j bfjtf0e nnjen3j nnjrb6fgam3gtm5tem3hj s3eim7djsd3ye d5dfhg5un7ljmm8nan3nn6n k m2ftm5bsof5bf r5arm4ken8 adcm3nub0 nfrn6sn3jfeb6n d m6jda5 gdif5vh6 gij7fnb2eb0g '))

```

`w` -\> `D`, `w` -\> `d` in the regex.
> 3 votes

# Answer
# Pyth, isaacg

### Description

The original code does the following:

```
 CG      Convert "abcdefghijklmnopqrstuvwxyz" from base 256 to integer, yielding
         156490583352162063278528710879425690470022892627113539022649722.
   ^3y21 Compute 3^(2 * 21).
%        Calculate the modulus.

```

Since **156490583352162063278528710879425690470022892627113539022649722 - 58227066** gives **156490583352162063278528710879425690470022892627113538964422656**, which equals **226 × 3 × 7 × 7477 × 381524422711 × 17007550201751761 × 2288745700077000184147**, the desired output can be obtained by replacing `^3y21` with something that evaluates to a divisor of this product and is larger than **58227066**.

The `^` in the original code suggests that we might use it to calculate a power of **2**, the **3** that we could calculate a fitting divisor of the form **3 × 2n**.

Both are misleading. Solutions with a Levenshtein distance of 3 (`%CG^2 26`, `%CG^y2 13`, `%CG^4y13`) or 4 (`%CG.<3y13`) are readily found, but the solution at distance 2 requires a different approach.

The lowercase alphabet (`G`) has 26 letters, so its power set (the set of all strictly increasing sequences of lowercase letters) has **226** elements. By **replacing `y2` with `yG`**, we compute this power set.

We can retrieve the set's length by **replacing `3` with `l`**, which leaves us with `^lyG1`, i.e., **226** raised to the first power.

### Code

```
%CG^lyG1

```

Note that this will only work on a computer with enough available memory (roughly 6.43 GiB, according to `time`), so it will not work with the online interpreter.

Here's how you can verify the results from the command line:

```
$ \time -v pyth -c '%CG^lyG1'
58227066
        Command being timed: "pyth/pyth.py -c %CG^lyG1"
        User time (seconds): 30.73
        System time (seconds): 2.12
        Percent of CPU this job got: 100%
        Elapsed (wall clock) time (h:mm:ss or m:ss): 0:32.85
        Average shared text size (kbytes): 0
        Average unshared data size (kbytes): 0
        Average stack size (kbytes): 0
        Average total size (kbytes): 0
        Maximum resident set size (kbytes): 6742564
        Average resident set size (kbytes): 0
        Major (requiring I/O) page faults: 0
        Minor (reclaiming a frame) page faults: 2269338
        Voluntary context switches: 1
        Involuntary context switches: 58
        Swaps: 0
        File system inputs: 0
        File system outputs: 0
        Socket messages sent: 0
        Socket messages received: 0
        Signals delivered: 0
        Page size (bytes): 4096
        Exit status: 0

```
> 3 votes

# Answer
# APL, Mauris

### Description

This was pretty much trial and error. I knew I had to insert a `¯` (negative number) and use mathematical functions like  (trigonometic) or  (logarithm) that yield complex number for negative input, or directly insert a `J` (imaginary part).

After *a lot* or errors, I finally tried **inserting a `¯` before `7` and a  before `/`**.

### Code

```
-⍟/3⍴15¯7

```

Try it online in ngn/apl demo, the online interpreter recommended by the cop.

Note that this won't work in, e.g., Dyalog APL, which requires a space before the high minus.
> 3 votes

# Answer
# APL, Mauris

### Description

Unlike the two APL answers I cracked before, the indented output of this one reveals very little about the required changes, so I decided to try a brute force approach.

Two characters aren't enough for loops, so the added characters (if any) had to be parts of numeric literals, mathematical functions or .

I chose a subset and hoped I'd get lucky. Using this CJam script, I generated all source codes (many of them with syntax errors) at an edit distance of 2 or less that only add character from the chosen set. This yielded 28,014 different potential solutions.

Aside from the online interpreter, ngn/apl is available for NodeJS. It even has a command-line flag (`-l`) that executes code linewise, which is almost perfect for this purpose.

After a minor change that condensed error output to a single line, I was able to grep the output to find the line number of the correct source code. The interpreter powered through the roughly 28,000 possible solutions in less than 6 seconds.

This sums up what I did:

```
$ diff apl.js `which ngn-apl`
4806c4806
<                       return e + '\n';
---
>                       return ('' + e).replace(/\n/g, '') + '\n';
$ cjam gen-edit-dist-2.cjam > brute-force.apl
3⍟877
0123456789.¯+-÷×⌈⌊*!|⍟○⊥⊤⍨
$ wc -l brute-force.apl
28014 brute-force.apl
$ time ngn-apl -l < brute-force.apl | grep -n '0\.2001649'
3791:0.20016493054644696
20128:0.20016493054644696

real    0m5.506s
user    0m5.516s
sys     0m0.252s
÷3⍟○77
3⍟⍨○77

```

This reveals two possible solutions: **replacing `8` with  and inserting `÷` before `3`**, or **replacing `8` with `⍨○`**.

### Code

```
÷3⍟○77

```

or

```
3⍟⍨○77

```

Try them online in the ngn/apl demo.1

These modifications calculate **1 / log3 77π = log77π 3**, which yields the desired output.

---

1 Note that the last digit may be a `3` on some machines.
> 3 votes

# Answer
# C++, f41lurizer

Good old trigraphs.

```
#include <iostream>
int main()
{
    //can you figure it out??/
    std::cout << "I like cake and";
}

```
> 2 votes

# Answer
# Python 2, muddyfish

## Description

Change ``i`` to ``id` = '<built-in function id>'` and `1234` to `01234` (octal). Found by recalling the wise words of Sir @xnor (paraphrased): "If you ever need a string that's 22 chars long..."

## Code

```
i=long;j=map;print reduce(i.__mul__,j(i,j(ord,`id`)))/01234

```
> 2 votes

# Answer
# VBA, JimmyJazzx

## Description

First of all the call of `a(2)` was strange since only `a(0)` and `a(1)` get used, that was actually a big hint.

Next i looked into what the function IRR really does (see here). There is no combination of integer `a(0)` and `a(1)` that can possibly yield the modified output.

So I looked for combinations of `a(0)` and `a(2)` (\<- first character changed) that resulted in the desired output and found `a(0) = -1` and `a(2) = 8`. Since multiplying `a(0)` and `a(2)` with the same number doesn't change the outcome I simply multiplied both with 5 so `a(0)` would stay the same.

## Code

```
Sub q()
Dim a(2) As Double
a(0) = -5
a(2) = 40
MsgBox IRR(a, 0.253)
End Sub

```
> 2 votes

# Answer
# Clojure, Bob Jarvis

Base conversions are fun.

```
(printf "%d\n" 7r2155263413256326162)

```
> 2 votes

# Answer
# PHP, Ismael Miguel

```
print_r(range(1,07));

```

I guess it really was that simple.
> 2 votes

# Answer
# modern Perl 5, msh210

## Description

The `s///` call has to only apply to the first element in the `@array` and using `each` with the `for` covers it off!

## Code

```
@array = (qw smiles) x 11;
s/.*// for each @array;
print "@array\n";

```

Added space in between `for` and `each`. I
> 2 votes

# Answer
# Matlab/Octave, paul.oderso

## Description

I took the natural log, and recognized it as near pi ^ 2. From there it was easy.

## Code

```
e^(pi*pi)+2

```

Added a `p`, `1` -\> `2`
> 2 votes

# Answer
# MATLAB, Jonas

## Description

Change `1+1` to `49+1`. I don't actually have MATLAB so I can't test this, but the number looks right

## Code

```
sin(49+1)

```
> 2 votes

# Answer
# Matlab / Octave, Jonas

## Description

Just change `tragic` by `magic` in the second line.

`tragic` is a symmetric, integer-valued matrix. The difference between both inputs is integer-valued but not symmetric. So a new kind of matrix was needed. The integer values and the name `traffic` looked familiar.

## Code

```
mistake=-1;tragic=rosser;a=hilb(8)*42;
a(:,:)+magic(8)/mistake

```
> 2 votes

# Answer
# Wolfram Language Mathematica or WolframAlpha, belisarius

## Original Code

```
8.!

```

## Changed Code

```
8.^i!

```

## Original Output

```
40320.

```

## Changed output

```
2.67182 - 0.891969 I

```
> 2 votes

# Answer
# GolfScript, Dennis

## Description

`9,:n9` doesn't work because `n9` would be one variable name. In GolfScript you usually get rid of this by using a symbol as the variable name, so...

## Code

```
9,: 9

```

More explanations.
> 2 votes

# Answer
# JavaScript, Razvan

## Description

Changed `1` to `.1` and added a semicolon.

## Code

```
a=(((b=(a=.1)+a)+a)-b-a)*(a=[b]);['length'];
alert(a);

```
> 2 votes

# Answer
# PHP, Razvan

### Description

Inserted `(` and `)`, so `$T_I_(M_E * $A_U_T_U_M_N)` executes `TAN(M_E * 2)`, where `M_E` is Euler's natural number.

### Code

```
$S_U_M_M_E_R = 1;
$A_U_T_U_M_N = 2;
$T_I_M_E = 1;

if ($T_I_M_E == $S_U_M_M_E_R) {
    $A_C_=$T_I_=$O_N= 'SWIM' ? 'TAN' : 'DRINK';
}

print $T_I_(M_E * $A_U_T_U_M_N);

```
> 2 votes

# Answer
# Ruby, histocrat

## Description

Need to make the regex at the end work on the string literal `?9` so we need to make the variable `$_` instead of `_`, also need to start the regex itself. Didn't realise that you could omit the `{}` when interpolating variables into regex in ruby.

## Code

```
p $_=?9;p$.+=1until /#$./

```
> 2 votes

# Answer
# Octave, Daniel

### Description

111 is the code point of the ASCII character **o**, so the desired output can be achieved by **replacing `cos` with `"o"`**.

`(1)` retrieves the first character of the string and `*1` casts to integer.

### Code

```
format long;
"o"(1)*1

```
> 2 votes

# Answer
# APL, jimmy23013

### Description

The output is obviously **1/9** with rounding errors and the code already contains a  (logarithm), so using it together with `*` (exponentiation) seems a natural choice for introducing that error.

In fact, **inserting  between  and `9`, and `*` between `9` and `9`** produces the intended output.

reverses the arguments of the preceding dyadic function, so this calculates **log999 ≈ 1/9** with the intended error.

### Code

```
9⍟⍨9*9

```

Try it online in the ngn/apl demo.
> 2 votes

# Answer
# PHP, Dom Hastings

Comment out the first two lines so they all append together.

```
define('E','!');

$x = 4;
$t = " Hello World";
$t .= #;
$t .= #;
$t .= E;

print($t);

```
> 1 votes

# Answer
# Lua, TreFox

In Lua, `#` is the "sizeof" operator. The discrepancy in the original behavior (15 or 23) is because the solution involves the size of the string created by converting a table to a string, and that string contains the address of the table (which is 16 characters on a 64-bit system and 8 on a 32-bit system). It looks like the particular distribution TreFox has is 64-bit. Also, apparently arguments in Lua work like arguments in Javascript, in which they don't seem to care how many arguments are passed, so changing the `.` to a `,` only causes `G` to be printed.

```
G={string="gs_hSDrGSFG5;U*ts"}
print(#tostring(G,string))

```

Secretly, I think this challenge was designed to make you think about skimpy underwear the whole time you were working on it.
> 1 votes

# Answer
# Matlab / Octave, rayryeng

## Description

Change `eig` to `eigs` and `sin` to `sind`.

The main clue was that the modified output has six eigenvalues sorted by magnitude, which is what `eigs` returns.

## Code

```
eigs(cov(reshape(sind(1:60),5,[])))

```
> 1 votes

# Answer
# SWI-Prolog, Fatalize

## Description

Replace an `E` for an `F` (or the other way around) and change a single digit in one of the numbers input.

## Code

```
assert(d(F,F):-(print(E),print(F))). d(123456,123457).

```
> 1 votes

# Answer
# SWI-Prolog, mgibsonbr

## Description

Change `,` (conjunction) to `;` (disjunction).

Add a space to make the distance 2.

## Code

```
assert((o(X,Y,Z):-ABC is X**X; print(ABC))). o(99,y,z).

```
> 1 votes

# Answer
# JavaScript, Razvan

## Description

The changed output being 10/3 was a dead giveaway.

## Code

```
one = 1;
two = one + one;
three = two + one;
zero = three - two - one;
numbers = [three, two, one];

for (i = numbers.length - 1; i <= zero; i--) {
    numbers.pop();
}

infinity = 10 / numbers['length'];
alert(infinity);

```
> 1 votes

# Answer
# Pyth, Beta Decay

## Description

This one's just obvious.

## Code

```
.!10

```

`77` -\> `10`
> 1 votes

# Answer
# CSS, Qwertiy

## Description

After seeing that the first number was a zero what needed changed seemed pretty clear

## Code

```
body:after{counter-reset:b 512;content:counter(a)"%"}
```
> 1 votes

# Answer
# Stuck, Vioz-

Change the first two numbers both to `3`.

```
3R3R3R4R5R6R7R8R9R9z]

```

Zipping in Stuck works like zipping in Python (I imagine `z` is backed by `zip()`), which is the shortest sequence is taken as the max length. Without the `]`, the output is a list of tuples, and I don't really know what `]` does. Pops the list at the top of the stack and pushes everything in it onto the stack, it looks like.

@Vioz-: Particularly for your `scipy` module, you should make sure that if the `numpy` or `scipy` libraries aren't available it doesn't crash with `ImportError`, but rather defines any methods that module supplies to just raise `NotImplementedError` or something similar. Also, you probably shouldn't commit `.pyc` files to your repo.
> 1 votes

# Answer
# Python, rp.beltran

### Description

Changed `dis` to `this`.

`import this` is an easter egg which prints The Zen of Python.

### Code

```
import this
def torun():
 print "hello world"
try:
 print dis.dis(torun)
except:
 pass

```
> 1 votes

# Answer
# CJam, Basset Hound

### Description

Finding the proper changes is easier if we work from the desired output. `5010670554118` looks like an integer in base 8 or higher.

```
5010670554118Ab8b
S
5010670554118Ab9b

```

prints `344786655312 1415926558979`, and the second group of digits look a lot like the decimal expansion of Pi.

In fact, `Ps` pushes `"3.141592653589793"` (Pi cast to string), `"3."-` (**added `3`)** removes all occurrences of **3** and **.**, `i` converts the result to the integer `1415926558979` and `9b` (**replaced `2` with `9`**) performs the required base conversion.

### Code

```
Ps"3."-i9b

```

Try it online.
> 1 votes

# Answer
# Perl, Adam Katz

### Description

`$_=cos 99` saves **0.0398208803931389** in the variable `$_`. If we multiply this amount by **0x7275**, we obtain **1166.79161639936**, which is roughly 4 times the original output and 8 times the modified output.1

The original code archives *almost-division-by-4* by substituting *the first* **3** in `$_` with a **0** by executing `s/[3-8]/0/`, which modifies `$_` and returns the number of substitutions (1), by which `$_` is then divided.2

After noting that there are eight digits between **3** and **8** in the unmodified value of `$_`, attempting to replace all of them by **appending `g` to `s/[3-8]/0/`** seemed natural, since this will divide the (modified) value of `$_` by the number of substitutions.

Finally, to diminish the effect of the *almost-division-by-4*, it suffices to replace the first **3** (and all occurrences of **3** and **8** that follow) with a **3** by **replacing `s/[3-8]/0/` with `s/[3-8]/3/`**.

### Code

```
$_=cos 99;printf"%.14f",0x7275*sin $_/s/[3-8]/3/g

```

---

1 The code actually applies sine to `$_` before multiplying, but **sin x ≈ x** when **x** is close to **0**.
2 Again, this completely ignores the sine, which is almost linear near **0**.
> 1 votes

# Answer
# Python, Beta Decay

### Description

Calling `math.tan` on the desired ouput gives **0.777…**, so it suffices to replace `tan` with `atan` and `749` with `7/9`.

### Code

```
import math, decimal
print(decimal.Decimal(math.atan(7/9)))

```

The output is actually `0.66104316885068692410953872240497730672359466552734375` on my machine, which rounds the (intermediate) result of `math.atan(7/9)` differently.
> 0 votes

---
Tags: cops-and-robbers
---


title: What have I got in my pocket?

text:
# Question
Title: What have I got in my pocket?
> **Synopsis:** Find characters that are enclosed by `MYPOCKET`.

**Example Input**

```
MYPHEIF
YFOCKVH
MBNDEIF
TEUFTMY
ESNDUWP
KBOVUVO
CENWFKC
OPYMTEB

```

**Example Output**

```
F
BND
EUF
SNDUW
BOVUV
ENWF

```

Huh? How did we get that as an output? The "pocket" can sometimes be difficult to see. This will make it clearer:

```
**MYP**HEIF
**Y**F**OCK**VH
**M**BND**E**IF
**T**EUF**TMY**
**E**SNDUW**P**
**K**BOVUV**O**
**C**ENWF**KC**
**OPYMTE**B

```

The letters in bold indicate a ring of characters connected orthogonally to each other consisting of the string `MYPOCKET` repeated over and over again. Your program should output the characters that are within that ring.

Notes:

* There will only be one "pocket".
* Trailing new lines or spaces after lines are allowed.
* The rest of the grid may also contain characters from `MYPOCKET`, but not in a way that makes the shape of the ring ambiguous.
* The `M` is not always in the top-right corner.
* The "pocket" can move in either a clockwise or a counter-clockwise direction.
* The "pocket" won't move in diagonal directions -- that is, each letter is connected left, right, up, or down to the next.

Here's another input you can test your program with.

**Example Input**

```
EKCYMOPD
KCOPHAYM
EKNDSEST
JETHACKE
KRMYPOBN

```

**Example Output**

```
  HA
NDSES
 HA

```

# Answer
> 1 votes
# Perl 5, 414

```
map{$y=0;push@{$h{$_}},[$-,$y++]for@$_;$-++}@l=map[/./g],<>;sub n{($a,$b,$c,$d)=@_;$a==$c&&1==abs$b-$d||$b==$d&&1==abs$a-$c}sub c{my($x,$y,$n)=@_;for(grep{($f=defined$x)?n$x,$y,@$_:1}@{$h{(MYPOCKET=~/./g)[$n%8]}}){($m,$l)=@$_ if!$f;return@r=([@$_],@r)if$n>2&&n(@$_,$m,$l)||c(@$_,$n+1)}''}c;$l[$_->[0]][$_->[1]]=$" for@r;($l[$_]=join'',@{$l[$_]})=~s/^(\w+)\s|\s(\w+)$/$"x($1||$2)=~y%%%c/eg for 0..@l;print join$/,@l

```

Usage: save as pocket.pl and run with:

```
perl pocket.pl <<< '<grid>'

```

I went for a recursive function to brute-force the path, which might not have been the best, but was the first approach I considered.

Whilst it works for both of the current test cases there are some caveats:

* it includes leading spaces (which I didn't see mentioned in the rules...); and
* it will definitely not work with a 'pocket' that contains characters in the middle (say U shaped or similar).

I want to continue working on this, but wanted to show that there is interest in the question! Happy to document my process if helpful.

# Answer
> 5 votes
## Python 2.7 ~~571~~ ~~542~~ 509

```
import sys
o,l,v,k,w="MYPOCKET",[list(e)for e in sys.stdin],[],enumerate,len
def f(z,q,t):
 for r,c in(z,q+1),(z,q-1),(z+1,q),(z-1,q):
  if w(l)>r>=0 and 0<=c<w(l[r])and o[t]==l[r][c]:
    v.append((r,c))
    if f(r,c,(t+1)%w(o)):return 1
    else:v.pop()
 if z==1 and(0,q)in v or z==0 and(z,q+1)in v:return 1
for i,x in k(l[0]):
 v=[(0,i)]
 if x==o[0]and f(0,i,1):break
for i in range(1,w(l)-1):b=[y for x,y in sorted(v)if x==i];print"".join(["".join(e)if w(e)>0 else" "for e in[l[i][b[j-1]+1:y]for j,y in k(b)][1:]])

```

Works as a program(banking on a recursive function) and accepting input from stdin.
Demo here.
Testing it (`ex1.txt` and `ex2.txt` are the examples from the question)-

```
$ python pockets.py < ex1.txt
F
BND
EUF
SNDUW
BOVUV
ENWF
$ python pockets.py < ex2.txt
  HA
NDSES
 HA

```

Ungolfed version with comments -

```
s="""
EKCYMOPD
KCOPHAYM
EKNDSEST
JETHACKE
KRMYPOBN
"""
li2=[list(e.strip()) for e in s.split("\n") if e.strip()!='']
buf=[]
def find_precious(row, col, c_ind):
    for r,c in[(row,col+1),(row,col-1),(row+1,col),(row-1,col)]:
        if len(li2)>r>=0 and 0<=c<len(li2[r]) and seq[c_ind]==li2[r][c]:
            if (r,c)in buf:return True
            buf.append((r,c))
            if find_precious(r,c,(c_ind+1)%len(seq)):return True
            else:buf.pop()
    if row==1 and (row-1,col) in buf or row==0 and (row,col+1) in buf:return True
    return False

for i,x in enumerate(li2[0]):
    if x==seq[0]:
        buf=[(0,i)]
        if find_precious(0,i,1):break
if len(buf)==1:
    exit("Failed")

#Calculate the middle men
for i in range(1,len(li2)-1):
    b=[y for x,y in sorted(buf)if x==i]
    print "".join(["".join(e)for e in [li2[i][b[j-1]+1:y]for j,y in enumerate(b)][1:]if len(e)>0])

```

Let me know, if I did something stupid or something can be done better.
I know it's looong, but it's the best I could do :P

---
Tags: code-golf
---