title: The Mystery String Printer (Robbers)

text:
# Question
Title: The Mystery String Printer (Robbers)
The cops thread can be found here: The Mystery String Printer (Cops)

# Your challenge

* Choose a submission from the cops thread, and print out the string from an answer in that thread.
* The submission that you choose must not be safe (it must be newer than 7 days).
* Your program, function, or REPL script needs to follow the same rules as the cops thread. Just to recap:

+ Your program must be ≤128 characters (if a cop's submission is in a smaller range of program lengths, your program must also be in that length range. For example, if a cop's program is ≤32 bytes, your program must be ≤32 bytes).
    + The program must produce the same output every time it is run.
    + No cryptographic functions.
    + The program must not take input.
    + No standard loopholes.
* All new submissions must use the same language. Submissions from before this rule was made are fine, even if they don't.

## Scoring

Scoring works similarly for robbers, but it is slightly different:

* Cracking any program of ≤8 bytes gives 1 point.
* Cracking a ≤16 byte program gives 2 points. ≤32 bytes gives 4 points, and so on.
* Every additional submission, no matter the length, earns +5 points
* Each cop's submission can only be cracked once- only the first person to crack each submission gets the points.

# Submissions

Each answer must include

* A link to the cop's submission.
* Your program and programming language.
* Also have the cop's program length (as a power of 2) as the last number in your header.

Additionally, please comment on the cop's submission with a link to your answer.

Here is a Stack Snippet to generate leaderboards. Please leave a comment if there is a problem with the snippet. If you would like to see all open cop submissions, see the snippet in the cops' challenge.

```
/* Configuration */

var QUESTION_ID = 60329; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";

/* App */

var answers = [],
  answers_hash, answer_ids, answer_page = 1,
  more_answers = true,
  comment_page;

function answersUrl(index) {
  return "//api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "//api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {

  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function(data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });

}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function(data) {
      data.items.forEach(function(c) {

        answers_hash[c.post_id].comments.push(c);

      });

      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var POINTS_REG = /(?:<=|≤|<=)\s?(?:<\/?strong>)?\s?(\d+)/
var POINTS_REG_ALT = /<h\d>.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {

  var valid = [];
  var open = [];

  answers.forEach(function(a) {

    var body = a.body;
    var cracked = false;

    var points = body.match(POINTS_REG);
    if (!points) points = body.match(POINTS_REG_ALT);

    if (points) {
      var length = parseInt(points[1]);
      var crackedpoints = 0;
      if (length > 64) crackedpoints = 16;
      else if (length > 32) crackedpoints = 8;
      else if (length > 16) crackedpoints = 4;
      else if (length > 8) crackedpoints = 2;
      else crackedpoints = 1;

      valid.push({
        user: getAuthorName(a),
        numberOfSubmissions: 1,
        points: crackedpoints

      });
    }
  });

  var pointTotals = [];
  valid.forEach(function(a) {

    var index = -1;
    var author = a.user;
    pointTotals.forEach(function(p) {
      if (p.user == author) index = pointTotals.indexOf(p);
    });

    if (index == -1) pointTotals.push(a);
    else {
      pointTotals[index].points += a.points;
      pointTotals[index].numberOfSubmissions++;
    }

  });

  pointTotals.forEach(function(a) {
    a.points += +((a.numberOfSubmissions - 1) * 5);
  });

  pointTotals.sort(function(a, b) {
    var aB = a.points,
      bB = b.points;
    return (bB - aB != 0) ? bB - aB : b.numberOfSubmissions - a.numberOfSubmissions;
  });

  pointTotals.forEach(function(a) {

    var answer = jQuery("#answer-template").html();
    answer = answer
      .replace("{{NAME}}", a.user)
      .replace("{{SUBMISSIONS}}", a.numberOfSubmissions)
      .replace("{{POINTS}}", a.points);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

  });

}
```

```
body {
  text-align: left !important
}
#answer-list {
  padding: 20px;
  width: 240px;
  float: left;
}
#open-list {
  padding: 20px;
  width: 450px;
  float: left;
}
table thead {
  font-weight: bold;
  vertical-align: top;
}
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>Robber's Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr>

        <td>Author</td>
        <td>Submissions</td>
        <td>Score</td>
      </tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>

<table style="display: none">
  <tbody id="answer-template">
    <tr>
      <td>{{NAME}}</td>
      <td>{{SUBMISSIONS}}</td>
      <td>{{POINTS}}</td>
    </tr>
  </tbody>
</table>
```

**This contest is now closed.**

**Overall winner: kennytm**

**Most submissions: Sp3000**

(Note that the amount of submissions doesn't translate exactly to the points, as the length of the cracked program is counted when calculating the score).

# Answer
> 29 votes
# Pyth, Dennis, ≤ 8

```
V./Tp*FN

```

Damn that was fun - the hardest part was figuring out how to do it short enough in Pyth.

### Analysis

The `1234` at the start hints that we're probably dealing with a list of numbers, printed without a separator. Let's try and split the numbers up in a way that makes sense:

```
1 2 3 4 4 6 5 8 8 9 6 12 10 12 7 16 16 18 12 15 16 8 24 20 24 14 27 18 20 9 32 32 36 24 30 32 16 36 21 24 25 10

```

There's a few hints that we're on the right track:

* All numbers have prime factors less than 10
* A lot of numbers are pretty close to their index in the list

However, there are a few peculiarities. The number at index 23 is 24, and is the only case where the number at the index is greater than the index itself. However, the bigger clue is that some numbers are clearly smaller than their neighbours, particularly the 7 at index 15, the 8 at index 22 and the 9 at index 30.

Noting that this forms a 7-8-9 pattern, we can also see that the last number is a 10 at index 42. Given @Dennis' recent question on abelian groups, a quick check on OEIS reveals that `15, 22, 30, 42` is a subsequence of the partition numbers. Pyth has a builtin for partitions, which gives us two of eight characters: `./`

But note that the last number is 10, which is suspicious because 10 is a preinitialised variable in Pyth, as `T`. `./T` gives a full list of the 42 partitions of the number 10, which looks like it might come in handy.

Now the printing is done without a separator, so this hints at a use of `p`. Perhaps we loop through each partition, do something to it, then print with `p`? This gives us the following template:

```
V./Tp??N

```

where `V` is a for loop which loops over an iterable, storing each element in the variable `N`.

A quick look at the second last partition `(5, 5)` should make it obvious that we want to take a product. The naive way to reduce a list by multiplication is

```
u*GHd1

```

where `d` is the list in question. However, this is far too long.

Unfortunately, this is where I had to pull out a brute forcer. I haven't kept up with Pyth for a while, so I didn't know many of the newer features. There were only two characters left, which looked entirely doable.

The brute forcer then returned:

```
V./Tp*FN

```

where `*F` is fold by `*` (multiplication). No wonder I didn't find it in my search - I was looking up the keyword "reduce" rather than "fold"!

# Answer
> 9 votes
# \>\<\>, VTCAKAVSMoACE, ≤ 64

```
'9?':?!;1-$:'@'+o'3'*'='%$30.

```

Ironically, not only is this much lower the range limit, it's also portable and works with the online interpreter.

### Analysis

Let's start with the target string:

```
yh[cPWNkz^EKLBiQMuSvI`n\Yw|JVXDUbZmfoRC_xrq{TlpHjGt]OadFAsgeyh[

```

\>\<\> pushes chars to the stack with `'` or `"` in string mode, but with 63 chars to print and only 64 bytes to work with, the presence of capital letters (invalid instructions in \>\<\>, for the standard looparound trick) make direct printing impossible. Hence, we must be doing something with the code points.

Converting to code points gives (I'm using Python here):

```
>>> L = [ord(c) for c in "yh[cPWNkz^EKLBiQMuSvI`n\Yw|JVXDUbZmfoRC_xrq{TlpHjGt]OadFAsgeyh["]
>>> L
[121, 104, 91, 99, 80, 87, 78, 107, 122, 94, 69, 75, 76, 66, 105, 81, 77, 117, 83, 118, 73, 96, 110, 92, 89, 119, 124, 74, 86, 88, 68, 85, 98, 90, 109, 102, 111, 82, 67, 95, 120, 114, 113, 123, 84, 108, 112, 72, 106, 71, 116, 93, 79, 97, 100, 70, 65, 115, 103, 101, 121, 104, 91]

```

Note that the last three numbers are the same as the first three. This hints at a possible modulo loop going on.

Let's take a look at how many different elements we have:

```
>>> len(set(L))
60

```

We have 63 elements in `L`, the first three of which coincide with the last three. This means that, aside from this collision, all other elements are unique. Now this hints at something like taking powers modulo a prime number. Indeed, `60 + 1 = 61` is prime, which is a good sign.

Let's try finding the smallest element

```
>>> min(L)
65

```

and use that to scale all the elements down so that the min element is 1:

```
>>> M = [x-64 for x in L]
>>> M
[57, 40, 27, 35, 16, 23, 14, 43, 58, 30, 5, 11, 12, 2, 41, 17, 13, 53, 19, 54, 9, 32, 46, 28, 25, 55, 60, 10, 22, 24, 4, 21, 34, 26, 45, 38, 47, 18, 3, 31, 56, 50, 49, 59, 20, 44, 48, 8, 42, 7, 52, 29, 15, 33, 36, 6, 1, 51, 39, 37, 57, 40, 27]

```

Note how the element after `1` is `51`. If there's some sort of powers/multiplication thing going on, this is a good guess for our multiplier.

Let's give it a shot:

```
>>> (57*51)%61
40
>>> (40*51)%61
27
>>> all((x*51)%61 == y for x,y in zip(M, M[1:]))
True

```

Bingo! We can now backtrack, giving the following code:

```
x = 57
for _ in range(63):
    print(chr(x + 64), end="")
    x = (x*51)%61

```

which was then translated to \>\<\>

# Answer
> 9 votes
# Mathematica, alphalpha, ≤ 32

```
GroupOrder[MonsterGroupM[]]

```

I hate to say this, but I just recognised the number on the spot.

# Answer
> 8 votes
# Pyth, Maltysen, ≤4

```
C.ZG

```

Brute force took so long that I did it faster manually.

### Analysis

`C` (convert string to base 256 int) is the easiest way to generate a large number in Pyth, so it's probably the first character. If we convert from base 256, we get:

```
xÚKLJNIMKÏÈÌÊÎÉÍË/(,*.)-+¯¨¬

```

Hmm... not very illuminating.

Now `G` is the alphabet string `"abc...z"`, which looks like it could be a source for a long string to feed into `C`. Looking through the docs I find:

```
.Z    Compresses or decompresses a string.

```

If we're dealing with compression here, it wouldn't be surprising to get all sorts of extended ASCII characters. Trying `C.ZG` then gave the answer.

# Answer
> 6 votes
# Fourier, Beta Decay, ≤ 32

```
2~x1~y20(xoy~z*x~yz~xq^~q)

```

Or alternatively, in CJam:

```
X0I{_2$+}*]2\f#

```

### Analysis

At the start we can see a lot of powers of 2:

```
2
1
2
2
4
8
32
256
8192
2097152
...

```

If we take the log base 2 of these numbers, we get:

```
1 0 1 1 2 3 5 8 13 21 ...

```

which is the Fibonacci series, starting at `1, 0`.

# Answer
> 6 votes
## Snails, feersum, ≤2 bytes

```
z

```

This is actually 2 bytes; the character `z` followed by a newline `\n`.

I have no idea how it works or what it's doing, but after testing all possible inputs apart from `~+` and `~,`, this was the only 2-byte program that produced `8` as output.

And it took *ages* to get this result. No wonder it's called "Snails" :-D

---

*Note to self: The next time you fuzz test unknown software, do it inside a VM.*

# Answer
> 5 votes
## Rust, Liam Noronha, ≤128 bytes

```
fn main(){print!("AACAAEGAAACIIMOAAACAAEGQQQSYYDFAAACAAEGAAACIIMOHHHJHHLNXXXAGGKMAAACAAEGAAACIIMOAAACAAEGQQQSYYDFOOO");}

```

Simply printing the string verbatim is 120 bytes...

# Answer
> 5 votes
# Macaroni 0.0.2, Doorknob, ≤64

```
set x "................................."print x print x print x

```

# Answer
> 5 votes
# Python 2, Clear question with examples, \<=64

One possible solution:

```
print ''.join([" `{.~{{~||"[int(c)] for c in str(3**4278)])

```

(`9**2139`, `27**1426` and `729**713` also give the same result)

# Answer
> 5 votes
# CoffeeScript, user2428118, ≤64

```
alert 0+(btoa k.substr -2 for k of document.body.style).join ''

```

(works only on Chrome 46.0.2490.71 as described by the Cop.)

---

The output is obviously a concatenation of short base64-encoded strings due to all the "=". After decoding them, we find a list of 2-character strings like

```
['nt', 'ms', 'lf', 'ne', 'll', 'on', 'ay', 'on', …

```

which does not seem to make sense. But I find some odd items in it, like `nX` and `tY`. After filtering these out we get

```
>>> # Python
>>>
>>> [i for i in tt if not re.match('[a-z]{2}$', i)]
['nX', 'nY', 'tX', 'tY', 'wX', 'wY', 'r', 'nX', 'nY', 'tX', 'tY', 'nX', 'nY', 'nX', 'nY', 'nZ', 'x', 'y']

```

These X and Y seem to indicate the original source code used position properties like `offsetX/Y`. A particularly interesting is the `nZ` item. To check my assumption, I searched for all properties that end with "Z":

```
// CoffeeScript
checked = []
f = (o) ->
    if !(o in checked)
        for k of o
            if /Z$/.test(k)
                console.log(o, k)
            if o[k] instanceof Object
                f o[k]
f window

```

which shows tons of `CSSStyleDeclaration, "webkitTransformOriginZ"`. From this we have a strong indication that the list is built up by the last 2 characters of all the keys of a `style` object, which the test above shows indeed is correct.

# Answer
> 5 votes
# Python 2, histocrat, ≤16

```
[[[51002**3/6]]]

```

---

The biggest hint is the promise that it won't work in Python 3. What's changed in Python 3? The biggest suspect is that the division operator returns a `float` in Python 3.

So I assume the solution is of the form ⌊αβ/n⌋ = c = 22111101102001, as exponentiation is the only short way to create huge numbers.

If {α, β, n} indeed forms a solution, then (cn)1/β ≈ α should be very close to an integer. Therefore I use the following to try to brute-force the {α, β} for each n:

```
(* Mathematica *)
n=2; Sort[Table[{N[Abs[k - Round@k] /. k -> (22111101102001*n)^(1/b), 12], b}, {b, 2, 50}]]

(* Output: {{0.00262542213622, 7}, ...}

   The first number is the "quality" of the solution, lower is better.
   the second number is β.
   Thus α ≈ (nc)^(1/β) = 89
   But (89^7)/2 = 22115667447764, which is still far away from the answer.

*)

```

The actual result quickly comes out when n = 6.

# Answer
> 4 votes
# MATLAB, StewieGriffin, ≤ 16

```
[36;87]*' |'*5

```

Prints:

```
ans =
        5760       22320
       13920       53940

```

# Answer
> 4 votes
# Mathematica, LegionMammal978, ≤64

```
Print@Nest[Compress,ExampleData[{"Text","ToBeOrNotToBe"}],13]

```

# Answer
> 4 votes
## Matlab, Luis Mendo, ≤16

I found it, yay!

```
fix(peaks(9).^2)

```

I didn't know that Octave can do this, too.

# Answer
> 4 votes
# Python, spacemanjosh, ≤ 64

```
n=0;d=1;L=[]
exec("L+=[10/(100-n)**.5];n+=d;d+=2;"*10)
print(L)

```

Glorious inverse symbolic calculator. Not well golfed, but hey it fits.

**Edit:** I golfed it.

```
print([10/(100-n*n)**.5for n in range(10)])

```

# Answer
> 4 votes
# JavaScript ES6, Cᴏɴᴏʀ O'Bʀɪᴇɴ, ≤128 bytes

```
var x=122,s='0037122342526683102122';for(var i=23;i<=505;i+=2)s+=(x+=i);s;

```

I doubt this is exactly right since I didn't need anywhere near 128 bytes, but finding a repeating sequence was fun challenge.

# Answer
> 4 votes
# Thue, ppperry, \<=64

```
0::=11
1::=22
2::=33
3::=44
4::=55
a::=bbb
b::=000
::=
aaaaaaa

```

Decomposes 2016 into its prime factors, essentially. 62 characters, so my guess is this is similar to what you were going for.

# Answer
> 4 votes
# Python, DLosc, ≤32

(This solution uses Python 2)

```
a=97
while a<4e31:a^=a*2;print a

```

# Answer
> 4 votes
# \>\<\>, Sp3000, \<=8

```
'l(?; o>

```

The instruction pointer wraps around and the following steps happen:

* `'l(?; o>'` pushes the ASCII values of `l(?; o>` to the stack
* `l` pushes the size of the stack on the stack
* `(` compare the top two stack elements: `size of stack` and `ord('>')`
* `?;` stops the program if the stack size was bigger
* `o` output the top element of the stack as character (this will be always `o`)
* `>` sets IP direction, here it is no-op
* we go back to the first step

Output is `oooooooooooo`.

We can get a lot of different outputs by changing `[space]` to something which pushes or pops on the stack and using another valid character instead of `>`, which may also push or pop.

# Answer
> 4 votes
# CJam, Reto Koradi, ≤ 4

```
HJK#

```

Pushes **17**, then **1920 = 37589973457545958193355601**.

Try it online.

There are only so many things you can do in four bytes. An integer this big had to involve powers or factorials somehow, and a factorial would have trailing zeroes.

# Answer
> 4 votes
# JavaScript, ev3commander, ≤ 32

```
console.log(0.1411200080598672)

```

OK, that was easy.

# Answer
> 4 votes
# Lua \<= 4, Egor Skriptunoff

A lot of users were getting agitated about this answer in chat, so I must relieve them from their misery. I don't know Lua and wasn't able to test it, but I would be very surprised if this doesn't work.

```
4^~9

```

This would be pretty obvious, but probably no one got it because bitwise operators were only added in version 5.3; ideone.com only has version 5.2.

# Answer
> 4 votes
# Pyth \<= 4, Dennis

```
ljyG

```

That's length of join on newlines of all subsets of the alphabet.

Test run:

```
$ pyth -cd 'ljyG'
==================== 4 chars =====================
ljyG
==================================================
imp_print(Plen(join(subsets(G))))
==================================================
939524095

```

I figured out the number was `2^27 * 7 - 1` which is a strong hint that it's based on `yG`, which is `2^26` elements long. I then guessed it had to be converted to a string and its length printed. However, the only way of doing this I could think of for a while was \`\`, repr. Then I thought of `j`, which fits perfectly.

# Answer
> 4 votes
# C, tucuxi, ≤64

```
main(i){for(i=0;i<11000;++i)if(!(i&2*i))printf("1%d",!(i&1));}

```

---

The output are all 0 and 1, but C cannot print binary directly, so it's very likely these are boolean results.

There are more 1 than 0s, so I recorded the positions of 0s (`3, 9, 13, 19, …`), which turns out to be OEIS A075318. This is not useful though, there isn't a simple formula to determine where a number is in this sequence.

But we note that there are all odd numbers, so perhaps `(x-1)/2 = {1, 4, 6, 9, 12, …}` have more useful information. And this is A003622.

A003622 can be defined as "positions of 1's in A003849", which is exactly what we need to crack here. And A003849 is defined as "A003714 mod 2", where A003714 are simply all integers that `x & (2*x) == 0`. Thus we have got the solution.

OEIS rox.

# Answer
> 4 votes
# Dyalog APL, Dennis, ≤4

```
*⍨⍟8

```

Computes ln(8)^ln(8). Would StackExchange stop converting my answers? I'll type a bunch of stuff here so it doesn't get turned into a comment.

# Answer
> 3 votes
# PARI/GP, alephalpha, ≤ 4

```
9!-9

```

I don't actually know the language, but that *has to* be the right answer.

# Answer
> 3 votes
# Pyth, xnor, ≤ 4

```
C`CG

```

`CG` (convert the alphabet string `"abc...z"` from base 256) is the typical Pyth way of generating a really large number. After that it's just stringify and convert from base again.

# Answer
> 3 votes
# Ruby, Doorknob, ≤64

```
'@@'=~/(.)(.)/
p$~
test 0 rescue p"#$!@@".gsub //,$!.inspect+$/

```

# Answer
> 3 votes
# Matlab/Octave, Wauzl, ≤16

```
"234"'*"567"

```

Using the same idea as Tom Carpenter's answer

(If it did not work, try this:)

```
[50;51;52]*'567'

```

# Answer
> 3 votes
# CoffeeScript, J Atkin, ≤ 16

```
Math.PI*Math.LN2

```

Hooray for the inverse symbolic calculator.

# Answer
> 3 votes
# TI-BASIC, quartata, ≤2

```
Xmin

```

On a fresh calculator, the window dimensions are `Xmin`=`Ymin`= -10, `Xmax`=`Ymax`=10. I actually posted about this in a TI-BASIC golfing tip answer before @quartata posted the cop!

> Current consensus is to allow all code to be run on a fresh interpreter. We can take advantage of this—all uninitialized real variables start at `0` in TI-BASIC, and `Xmin` starts as the possibly useful value `-10`. So if you ever need to take a running total in a program that doesn't take input from Ans, or you really need a `-10` in one less byte, this tip can help you.

There are therefore four solutions: `Xmin`, `Ymin`, `ZXmin`, and `ZYmin`—the latter are the zoom tokens, which I don't know the exact purpose of.

# Answer
> 3 votes
# LOLCODE, sysreq, ≤ 4

```
OBTW

```

Found the intended solution here. **:/**

# Answer
> 3 votes
# \>\<\> , randomra, ≤ 8

```
'ol(?;r>

```

For some reason, 23 was surprisingly hard to get.

# Answer
> 3 votes
# TI-BASIC, Thomas Kwa, ≤ 4

```
³√(tanh(7°

```

I don't have any way to test the code, so I'm not completely sure if the notation is correct. The sequence of steps I used to get the output are:

1. Value 7.
2. Convert from degrees to radians.
3. Apply hyperbolic tangent.
4. Apply cube root.

Cracking method:

* I made the assumption that the 4 bytes were one single byte constant, with 3 operators listed as "1 byte token" in the documentation applied to it.
* For the constants, I used the 10 single digit numbers, and pi, giving 11 options.
* For the operators, I picked the ones from the list of one byte tokens that looked like they would make sense in this context, resulting in a list of 26 operators.

This left me with brute forcing 11 * 26 * 26 * 26 possibilities, which a small C++ program completed in milliseconds on my laptop. Listing the smallest differences to the target value, it gave a bunch in the range of 1e-5, and a single one that was about 6e-8, which was close enough to be a solution.

# Answer
> 3 votes
# gs2, quartata, Range: \<= 8

```
\x01\x02\x01\x07/e\x81e

```

The number is simply 2^5040 (i.e., 2 raised to the power of 7 factorial). Factorizing it was the easy part. Finding out how to work gs2 took a lot longer.

The workings of the program are described below (using `\xNN` notation to represent non-ASCII bytes):

```
\x01\x02                   Push the number 2 onto the stack
        \x01\x07           Push the number 7 onto the stack
                /          Change this into a list [1,2,3,4,5,6,7]
                 e         Multiply everything in this list (5040)
                  \x81     Make a list containing [2,2,2...] 5040 times
                      e    Multiply everything together again

```

This leaves the number 27! on the stack, which is printed when the program exits.

# Answer
> 3 votes
# AppleScript, VTCAKAVSMoACE, ≤16

```
{1=1,1=0}>0

```

Needs 5 more bytes to redirect to stdout, so total size is exactly 16 bytes.

# Answer
> 3 votes
# JavaScript, histocrat, ≤ 32

Well, this was lucky. I needed exactly 32 bytes:

```
[...'aa0abaabaa4abaaaa6abaa']+''

```

**How this works:**

* the brand new `spread`-operator* creates an array from a string
* `+ ''` forces the array to be casted to string, which implies a concatenation by `,` in JavaScript
* the result of the expression is printed onto the console

So basically it's a shorter version of:

```
'aa0abaabaa4abaaaa6abaa'.split('').join()

```

* The spread-operator is a new Array Initializer in ECMAScript 2015 (ES6) standard. Works currently in Chrome and Firefox.

# Answer
> 2 votes
# Stuck, @quartata, ≤8

The following **Pyth** program:

```
^33 9

```

produces the desired output

```
46411484401953

```

Cracking method: Searched Google for the number.

# Answer
> 2 votes
# TI-BASIC, quartata, \<=7

```
πE8/e

```

I found this using RIES.

# Answer
> 2 votes
# Python 3, Mego, ≤128

(Using Python 3.5.0, not tested on previous versions. ~~105~~ 98 bytes.)

```
import sys
a=sys.stdout
sys.stdout=None
from this import*
a.write(s.translate(s.maketrans(d))[4:])

```

# Answer
> 2 votes
# Math++, SuperJedi224, ≤8 bytes

```
cbrt7835

```

I used the Inverse Symbolic Calculator.

# Answer
> 2 votes
# Python, Status, ≤128 bytes

```
print"NEENER"*3# This code outputs the following string: "NEENERNEENERNEENER". This is achieved by evaluating "NEENER" * 3.

```

# Answer
> 2 votes
# Microscript, SuperJedi224, ≤4 bytes

```
'~$q

```

It took me a while to find the `'` instruction...

# Answer
> 2 votes
# bc -l, NaN, \<=8

```
l(4.76)

```

Derived from a rather longer solution found using ISC.

# Answer
> 2 votes
# Javascript, user2428118, \<= 16

`Math.PI*9e9`

Thanks to Sven the Surfer for the help.

I used ISC which was used to crack one of my answers.

# Answer
> 2 votes
# TI-89 BASIC, @DankMemes, \<=8

```
236!

```

The string of zeroes at the end gave it away.

# Answer
> 2 votes
# Python, Zach Gates, ≤ 64

```
s='UCAG'
print(" ".join(x+y+z for x in s for y in s for z in s))

```

Behold the ton of other attempts:

```
# Python 3 only
from itertools import*
print(*map("".join,product(*["UCAG"]*3)))

# Python 2 only
def f(s):
 if s[2:]:print s,
 else:for x in"UCAG":f(s+x)
f("")

# Too long
o=""
for n in range(64):exec("o+='UCAG'[n%4];n//=4;"*3);o+=" "
print(o)

# Too long
L=[""]
exec("L=[x+y for x in L for y in'UCAG'];"*3)
print(" ".join(L))

```

# Answer
> 2 votes
# \>\<\>, Cole, ≤ 8

```
'l?!;}n!

```

Pretty obvious when the code points in the output give basically all the chars.

# Answer
> 2 votes
# PowerShell, TimmyD, ≤2

```
$?

```

I looked at this page of commands and found two that seemed like they would print true.

# Answer
> 2 votes
# Javascript ES6 REPL, pandorym, ≤16

```
6496/9090+"323"

```

# Answer
> 2 votes
# QBasic, DLosc, \<=32

```
FOR c=1TO 8
?TAB(c*c);c;
NEXT

```

The answer was so trivial, it was converted to a comment.

`TAB` can be used in a `PRINT` (shortcut `?`) statement to set the cursor position.

# Answer
> 2 votes
# JavaScript, Cᴏɴᴏʀ O'Bʀɪᴇɴ, ≤16 bytes

You could just enter the number in hexadecimal at the console like this:

```
0x6ffffffffffffe

```

This is one byte shorter:

```
s=1<<26;s*s*7-2

```

(In other languages, `(7<<52)-2` would have worked fine, but not Javascript.)

# Answer
> 2 votes
### VBA, JimmyJazzx, ≤32

```
Sub a()
MsgBox -2^31+23
End Sub

```

I think; I can't actually get it to stay like this since the VBA editor reformats and adds spaces between the math operators ... but typing that in works and doesn't error...

# Answer
> 2 votes
# Lua, Egor Skriptunoff, ≤ 32

```
_='()()()'print(_:gsub(_,_.rep))

```

# Answer
> 2 votes
# CJam, Dennis, ≤ 4

```
P2mh

```

Glorious inverse symboli... *shot*

# Answer
> 2 votes
# Pip, DLosc, ≤ 4

```
mTB3

```

The value is 1000 in base 3.

This one was easy to crack manually. The most obvious guess was that it was a number converted to binary. But that number would have been 105, which has no nice shortcut, and would result in 5 bytes of code. The next attempt was to try base 3 instead of base 2, and bingo!

# Answer
> 2 votes
# Javascript (ES6, console), Shaun H, \<= 64

```
[...[].pop+''].sort().map(x=>x.charCodeAt()+'').join('')

```

At first I thought I could get the Chrome string short enough with just hex literals, but then I realized what the code must have been doing.

Anyway, the main hint was that native functions have slightly different string representations in Chrome vs FF.

# Answer
> 2 votes
# J, Mauris, \<=4

```
%!7

```

This wasn't difficult. `0.000198413 = 1/5040 = 1/(7!)`

# Answer
> 2 votes
# J, Dennis, \<=4

```
8!^5

```

How I found it:

* assumed `f ? ? ?` format and inverted one-variable one-letter verbs (`f`) with no success
* assumed `x f g y` format and checked `fg == !!` with `(!!)"0/~i.10` then `fg == !^` with `(!^)"0/~i.10` which contained the desired output (`4.81845e12`) for `8!^5`

# Answer
> 1 votes
# Mathematica, Eridan, ≤64

```
IntegerString[18612512719586442658197,2]

```

# Answer
> 1 votes
# Fishing, Eridan, ≤ 32

```
v+CCCCCCCCCCC
  `65617`nSSP

```

Calculates `(65617^2)^2`.

# Answer
> 1 votes
# MATLAB, Tom Carpenter, ≤16

`v=ver;[v.Name]`

Thanks Martin for helping me out with this.

# Answer
> 1 votes
# Groovy, quartata, ≤128

Only checked on ideone, I'm not sure if the output is the same on all platforms.

```
ClassLoader.systemClassLoader.packages.each{if(!(it.name=~/ls$/))println it.name[6..-1].reverse()}

```

The `it.name=~/ls$/` is to filter out the additional `org.codehaus.groovy.tools` package.

# Answer
> 1 votes
# Octave, flawr, ≤4

```
i^-i

```

which is equal to *e**π*/2 ≈ 4.8105.

# Answer
> 1 votes
# vim, Doorknob, 16

```
:redi@"|Ni!
pg?G

```

# Answer
> 1 votes
# STATA, bmarks, ≤32 bytes

```
set ob 82
g a=_n*9/8
set ob 99
l

```

This uses the free interpreter.

# Answer
> 1 votes
# MATLAB, Tom Carpenter, ≤4

```
pi^i

```

It's not hard when the absolute value is 1.

# Answer
> 1 votes
## Javascript, Ludovic Zenohate Lagoua, ≤64

```
var a="'";for(var b=11;b<2004;b+=4){a+=b;}a+="'";console.log(a);

```

# Answer
> 1 votes
# Python 2.7.2, Beta Decay, ≤ 64

```
import math,re;print zip(dir(math),dir(re))

```

I had 2.7.10 installed, and the additional `__loader__` messed with the results, but this is probably it (I had to confirm with @BetaDecay in chat).

# Answer
> 1 votes
# Brainfuck, Daniel M., ≤ 64

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

```

The code points are

```
[40, 80, 60, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100, 102, 104]

```

So we print the first three separately, then using the 80 to increment by 2 each time for the rest of the chars.

# Answer
> 1 votes
## Python 2, \<=8, by Clear question with examples

```
947**687

```

Factorizing this number took no time at all :-)

# Answer
> 1 votes
# Hassium (in REPL), \<=32 bytes, by Jacob Misirian

```
for(i=0;i<99;i++)print(i%6==0)

```

Not too much fancy in this one.

# Answer
> 1 votes
# AppleScript, VTCAKAVSMoACE, ≤32 bytes

```
repeat 409 times
log "(**)"
end

```

The `log` command actually adds comment markers `(*`...`*)` to everything it outputs to the Messages window of the script editor, but it looks like they have to be added explicitly when printing to stdout. Either way, the program is still less than 32 characters.

I'm using Digital Trauma's trick of replacing `end repeat` with `end` to save a few bytes.

---

**EDIT:** As kennytm correctly pointed out, this outputs to stderr instead of stdout. As a workaround, I can suggest the following:

```
osascript -e 'repeat 409
log "(**)"
end' 2>&1

```

Including line breaks, the script inside the single quotes is 25 bytes, Add 5 bytes for  `2>&1` at the end of the command line to redirect stderr to stdout, and it's still within the 32 byte limit.

# Answer
> 1 votes
# Javascript, RononDex, ≤ 32 bytes

```
console.log(Math.log(42))

```

Very easy :-D

# Answer
> 1 votes
# Thue, histocrat, ≤64

```
a::=yellowyellowyellowredyellowred
::=
aaaaaa

```

# Answer
> 1 votes
# \>\<\>, Fongoid, ≤ 16

```
'$1-:0(?;$:o3+ !

```

That was some nice golfing practice.

# Answer
> 1 votes
# AppleScript, VTCAKAVSMoACE, ≤ 2 Bytes

```
id

```

I have no idea why this produces the output `missing value`; I just wrote a bash script to test all pairs of printable ASCII characters. I also found that `it` and `me` result in the output `«script»`.

# Answer
> 1 votes
# AppleScript, VTCAKAVSMoACE, ≤64

```
osascript -e 'repeat with i from 688 to 195049 by 629
log i mod 1e3
end' 2>&1

```

Needs a redirect to stdout, similar to https://codegolf.stackexchange.com/a/60601/32353. Total size is 64.

# Answer
> 1 votes
# MATLAB, Tom Carpenter, ≤ 2

```
!<

```

*Thanks to @AlexA. and @RetoKoradi for helping me test this. I don't have a Windows PC/VM...*

Googling the desired output immediately revealed it as a typical Windows Cmd error. In fact,

```
<

```

produces the desired output, and a MATLAB command that is prefixed by a `!` is a system command. I don't have MATLAB at hand to test this, but it should work.

# Answer
> 1 votes
# \>\<\>, quartata, ≤ 32

```
1"qq"+\
v!?:  <$*d$-1
>~n;

```

I'd like to thank @quartata for make this interesting - despite being such a long number, it's actually just `13^226`.

# Answer
> 1 votes
# \>\<\>, Fongoid, ≤64 Bytes

```
"!":"~"=a$.1+:"!"(?;::1-$oo20.
"+"f8+0pa0.2-"-"c0p"3"f7+0p

```

A little bit hard-coded since I had room and I couldn't really think of a good way to go down once I got to `~` in the output (there probably is one and I probably just don't see it).

You can try it online here.

# Answer
> 1 votes
# Pip, DLosc, ≤ 2

```
O_

```

I don't really understand what the code does, but 2 characters is wide open to brute force cracking.

# Answer
> 1 votes
# Wolfram programming language, Eridan, ≤32

```
ContinuedFraction[Zeta[3],36]

```

It's sequence A013631 on OEIS.

# Answer
> 1 votes
# Lua, jcgoble3, ≤ 128

```
x=111111111
h="haha"
p=h..3*x..2*x..h..7*x..h..2*x
q="ha"..6*x..p..p..h..6*x..h..7*x..h..4*x..h..5*x
"ha"..(q..h):rep(11)..q

```

124 bytes. Tested in Lua 5.3.1 REPL.

This is a cleaner version that can be executed as a single command or even a full program:

```
x=111111111 h="haha" p=h..3*x..2*x..h..7*x..h..2*x q=h..6*x..p..p..h..6*x..h..7*x..h..4*x..h..5*x print((q.."ha"):rep(11)..q)

```

125 bytes. Tested in Lua 5.3.1 REPL and ideone.

# Answer
> 1 votes
# Pyth, ConfusedMr\_C, ≤ 32

```
sm*2s_c4s_Mcd2%2_c4sCM127

```

Only needed 25 chars. Took some while though.

Try it online: Demonstration

The idea is to take all chars of the ranges 32-63 und 96-126 (Yes, 127 is not included), rearrange them, duplicate these strings and join them.

# Answer
> 1 votes
# Self-modifying Brainfuck, mbomb007, ≤8

```
<[-.+<]

```

stdin needs to be /dev/null and disregard the output from stderr.

# Answer
> 1 votes
# QBasic, DLosc, ≤16

```
?STRING$(3,34)

```

# Answer
> 1 votes
# QBasic, DLosc, ≤8

```
?TAN(22)

```

Does the leading/trailing space thingy. I guess it's a QBasic quirk.

# Answer
> 1 votes
# CJam, Eridan, ≤8

```
6C#E130#

```

I assumed it would be a list of numbers of the form *i^j*, so I did a search for those using substrings from output. I found that it was `str(6 ** 12) + str(14 ** 130)` using a Python script.

# Answer
> 1 votes
# Python 3, ppperry, ≤32

```
0x1d4f620cb7a9ca2c585c639763613

```

# Answer
> 1 votes
# J, randomra, ≤ 8

```
#:/:|i:9

```

Try it online.

### Cracking the code

Each row looks like the binary representation of a small integer, specifically of these integers:

```
9 8 10 7 11 6 12 5 13 4 14 3 15 2 16 1 17 0 18

```

These integers are a permutation of the range **0 … 18**, so they were most likely the product of "grading up" a list of length 19.

Grading that list up once more yields

```
17 15 13 11 9 7 5 3 1 0 2 4 6 8 10 12 14 16 18

```

meaning that we must find a list whose elements are in the same order as this one. This very same list would work, but we must find another that fits in the byte range.

An obvious candidate is

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

```

which can be generated by applying absolute value to the list

```
_9 _8 _7 _6 _5 _4 _3 _2 _1 0 1 2 3 4 5 6 7 8 9

```

### How it works

* `i:9` generates the range **-9 … 9**.
* `|` applies absolute value to each integer in that range.
* `/:` "grades up", i.e., sorts the indices of the above list by the values at those indices.
* `#:` converts the resulting indices to binary.

# Answer
> 1 votes
# Mathematica, quartata, 25 \<= 64 bytes

```
2^315 3^117 75844139371^9

```

# Method

```
output = 368921261...764501504

test = FactorInteger[output]
(* {{2,315},{3,117},{7,18},{11,9},{13,9},{17,9},{19,9},{23,9},{31,9},{47,9}} *)

(Times @@ Power @@@ Drop[test, 2])^(1/9)
(* 75844139371 *)

2^315 3^117 75844139371^9 == output
(* True *)

```

# Answer
> 1 votes
# TI-BASIC, Cᴏɴᴏʀ O'Bʀɪᴇɴ, ≤2

```
θStep

```

I was thinking of using one of these window tokens for my 4-byte cop, but I didn't want to abuse the "may assume default settings" rule too much.

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


title: Average of a string

text:
# Question
Title: Average of a string
You have been employed by a data analysis company, and have been appointed the task of finding the average character of a string of characters. However, this company has limited funding for code storage, so your code must be as small as possible.

## Task

Write a program or function that takes one string of characters as input, and outputs the average character of that string.

## Calculation of average

The average character of a string is the sum of the ASCII values of the individual characters divided by the total number of characters, then converted back to an ASCII character.
For example, the string `cat` consists of the sequence `99 97 116` of ASCII values. These values summed equals 312, which then divided by 3 gives an average of 104. 104 represents the ASCII character `h`. The average character of the string `cat` is therefore `h`.

## Rules

* You can assume the input string will only contain printable ASCII characters
* If the average of the string's ASCII values is floating point, it should be rounded to the nearest integer and then converted to the equivalent ASCII character (eg. an average of 66.4 would output `B`, and an average of 66.5 would output `C`)
* Input can be from STDIN (or language equivalent), or as a function parameter
* Output must be to STDOUT (or language equivalent), or as a return result if your program is a function
* Standard loopholes are not allowed
* This is , so shortest code in bytes wins

## Examples

Input → average → output
`Hello, world!``89.3076923076923``Y`
`Code golf``92.77777777777777``]`
`8112015``50.57142857142857``3`

# Answer
# Matlab, ~~23,21~~ 16 bytes

I think this is quite obvious, if you know that matlab handles strings as arrays of characters, which can be treated like integers, aparently rounding occurs automatically when concatenated with a string.

```
@(s)[mean(s),'']

```
> 8 votes

# Answer
# Julia, 41 bytes

With help from @AlexA.

```
a->Char(round(Int,mean([Int(i)for i=a])))

```

(Older version only worked in Julia 0.3.)
> 6 votes

# Answer
# JavaScript ES6, ~~87~~ ~~82~~ ~~81~~ 79 bytes

```
f=s=>String.fromCharCode([...s].reduce((r,c)=>r+c.charCodeAt(),0)/s.length+.5);

```

Thanks ETHproductions for the time to shorten by 5 bytes. Thanks rink.attendant for a byte less. Thanks Vihan for another 2 bytes.
> 4 votes

# Answer
## CJam, 11 bytes

```
q_1b\,d/moc

```

Test it here.

### Explanation

```
q    e# Read input.
_1b  e# Duplicate and get the ASCII sum by treating the character codes as base-1 digits.
\,   e# Swap with other copy and get its length.
d/   e# Convert to float and divide.
mo   e# Round to nearest integer.
c    e# Convert to character.

```
> 3 votes

# Answer
# Vitsy, 11 Bytes

This was what this was *MADE* for.

```
IVzV1-\+V/O
I           Get the length of the input stack.
 V          Save it as the final global variable, popping it.
  z         Push the input stack to the program stack.
   V1-\     Repeat the next item global variable size - 1.
       +    Add the top two items. This adds up everything.
        V/  Divide by the global variable.
          O Output as a character.
```
> 3 votes

# Answer
# Pyth, 9 bytes

```
C.R.OCMz0

```

Try it online.
> 2 votes

# Answer
# TeaScript, 14 bytes

```
ÇU(x¿lÅ)x¡/xn©

```

Probably can be golfed using a reduce

### Ungolfed

```
C(U(xs``.m(#lc())x()/xn))

C(       // Char from code from...
  U(      // Round
    xs``   // Split input
    .m(#   // Map over input
        lc()  // get char code
    ).x()  // Sum up array
    /xn    // Divided by input length
  )
)

```
> 1 votes

# Answer
# Mathematica, 47 bytes

```
FromCharacterCode@Round@Mean@ToCharacterCode@#&

```

or using composition:

```
FromCharacterCode@*Round@*Mean@*ToCharacterCode

```

String handling in Mathematica is such a joy...
> 1 votes

# Answer
# K5, 16 bytes

```
{`c$.5+(+/x)%#x}

```

The phrase `{(+/x)%#x}` is a classic K idiom for calculating an arithmetic mean, and in K5 characters naturally coerce to numbers with no special work. ``c$.5+` handles rounding and converting the result back into a character.

In action:

```
  {`c$.5+(+/x)%#x}'("Hello, world!";"Code golf";"8112015")
"Y]3"

```
> 1 votes

# Answer
# Ruby, ~~46~~ 45 characters

```
->s{'%c'%(s.bytes.reduce(0.0,:+)/s.size+0.5)}

```

Sample run:

```
2.1.5 :001 > ->s{'%c'%(s.bytes.reduce(0.0,:+)/s.size+0.5)}['Hello, world!']
 => "Y"

2.1.5 :002 > ->s{'%c'%(s.bytes.reduce(0.0,:+)/s.size+0.5)}['Code golf']
 => "]"

2.1.5 :003 > ->s{'%c'%(s.bytes.reduce(0.0,:+)/s.size+0.5)}['8112015']
 => "3"

```
> 1 votes

# Answer
# Python 3, 48 Bytes

Straightforward solution with an anonymous lambda function.

```
lambda k:chr(int(round(sum(map(ord,k))/len(k))))

```
> 1 votes

# Answer
# Japt, ~~31~~ 27 bytes

```
Ua r(X$,$Y =>Xc +Yc)/Ul)r d

```

Try it in the Stack Snippet interpreter! (Arrow functions require ES6-compliant browser, e.g. Firefox.)

### How it works

```
            // Implicit: U = input string
Ua          // Split U into chars.
r(X$,$Y =>  // Reduce the result by:
Xc +Yc      //  summing the char codes.
/Ul)        // Divide the result by the original string's length.
r d         // Round the result and turn back into a character.
            // Implicit: output last expression

```

(Side note: `c` works as `.charCodeAt` on strings and `Math.ceil` on numbers. The first time reduce is run, it will be between two strings, so `Xc` is necessary, but has no effect on the rest of the reducing.)

This is still much longer than it should be. The summing is 17 bytes when it could be 5 or so. Here's a 14-byte version I'd like to get working in the interpreter:

```
Uamc)r+ /Ul)rd
Uamc)          // Split input into chars, then replace each with its char code.
     r+        // Reduce the result with operator +. Equivalent to summing the array.
        /Ul)   // Divide the sum by the original string's length.
            rd // Round and turn into a character.

```
> 0 votes

# Answer
## CoffeeScript, 94 bytes

```
f=(x)->String.fromCharCode Math.round x.split('').reduce(((p,v)->p+v.charCodeAt 0),0)/x.length

```
> 0 votes

# Answer
# Haskell, ~~74~~ 69 bytes

```
s x=toEnum$round$(fromIntegral.sum.map fromEnum$x)/(foldr(\_ y->y+1)0x)

```

Pretty straightforward. A good chunk of the length is due to the fact that we can't apply the floating-point division operator (/) to integral types and that besides we need to round so we can't take advantage of the integral division's truncating behaviour.

*P.S. :* Shaved off 5 bytes by using a fold to avoid the second fromIntegral. Interestingly, replacing the dividend by a fold gives a *longer* program, probably because you need the fromIntegral there.
> 0 votes

# Answer
# Ruby, 48

```
->s{t=0.0;s.bytes{|i|t+=i};(t/s.size).round.chr}

```
> 0 votes

# Answer
## PowerShell, 60 Bytes

```
param([char[]]$a)$a|%{$b+=[int]$_};[char][int]($b/$a.Length)

```

Nothing esoteric. Takes input string `param(..)` and casts it as a `char[]`. Iterates over that array `$a|%{..}`, and each iteration adds the int value of that character to our accumulator `$b`. Then takes the average, casts it as `int` (which does implicit rounding to the nearest integer), then casts as a `char` for output. Since that's left on the pipeline, output is implicit.
> 0 votes

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


title: What's the weather like?

text:
# Question
Title: What's the weather like?
Pick six cities or villages, one from each of the populated continents, Asia, Africa, North America, South America, Europe and Australia. The forecasts cover 8351174 places, more than 2 million in the US, 150000 in Pakistan, 10000 in Uganda, and 16 places in the Shefa province in Vanuatu, so I think you'll find a place near you.

Make a table where the weather for each of the cities are listed, for the coming ten 6-hour periods. The cities should be listed in the order above (first an Asian city, then an African city ...).

The information that should be listed is:

* City: `Name, CC` (`CC` is the first two letters of the country name)
* Time: `yyyy-mm-dd`
* Period: `1`
* Weather: `Cloudy`
* Temperature: `24`

The output format has the following restrictions:

The order is given as below (Time, Period, Weather, Temperature, Weather Temperature, Weather, Temperature ...). The city name and country code are headers

```
                Kyoto, JA          Addis Ababa, ET     Minneapolis, US     Rio de Janeiro, BR    Genoa, IT          Perth, AU
2015-11-05, 3,  Cloudy, 15         Clear sky, 18       Heavy rain, 24      Cloudy, 12            Fair, 14           Rain, 26
2015-11-06, 0,  Cloudy, 12         Fair, 14            Rain, 26            Cloudy, 12            Fair, 14           Rain, 26
2015-11-06, 1,  Heavy rain, 14     Clear sky, 17       Rain, 22            Heavy rain, 14        Clear sky, 17      Rain, 22
2015-11-06, 2,  Rain, 15           Clear sky, 12       Rain, 25            Heavy rain, 14        Clear sky, 17      Rain, 22
2015-11-06, 3,  Partly cloudy, 9   Fair, 8             Heavy rain, 30      Clear sky, 8          Fair, 14           Partly cloudy, 25
2015-11-07, 1,  Clear sky, -8      Fair, 14            Partly cloudy, 25   Clear sky, 8          Fair, -14          Partly cloudy, 25
2015-11-07, 2,  Fog, 13            Partly cloudy, 15   Fair, 22            Clear sky, 8          Fair, 14           Partly cloudy, 25

```

The weather forecast can be found on www.yr.no. The weather data can be found on xml-format on urls such as:

```
http://www.yr.no/place/Australia/Western_Australia/Perth/forecast.xml
http://www.yr.no/place/Italy/Liguria/Genoa/forecast.xml
http://www.yr.no/place/Turks_and_Caicos_Islands/Other/Cockburn_Town/forecast.xml
http://www.yr.no/place/Bahamas/San_Salvador_and_Rum_Cay/Cockburn_Town/forecast.xml

```

Yes, there are apparently two places called "Cockburn Town". You can search for places on the main page (yr.no), and simply append `/forecast.xml` when you've found your place. (You can select language in the top right corner, the website might be shown in Norwegian).

The data has the following format:

```
<time from="2015-11-05T19:00:00" to="2015-11-06T00:00:00" period="3">
<!--
 Valid from 2015-11-05T19:00:00 to 2015-11-06T00:00:00
-->
<symbol number="4" numberEx="4" name="Cloudy" var="04"/>
<precipitation value="0" minvalue="0" maxvalue="0.4"/>
<!--  Valid at 2015-11-05T19:00:00  -->
<windDirection deg="131.5" code="SE" name="Southeast"/>
<windSpeed mps="3.7" name="Gentle breeze"/>
<temperature unit="celsius" value="12"/>
<pressure unit="hPa" value="1014.2"/>
</time>
<time from="2015-11-06T00:00:00" to="2015-11-06T06:00:00" period="0">...</time>
<time from="2015-11-06T06:00:00" to="2015-11-06T12:00:00" period="1">...</time>

```

As you can see, each 6 hour period has a period number "0", "1", "2" or "3". The table must have the date followed by the period number, `2015-11-06, 3` (might be separated by a comma, tab or whatever).

You must, for each of the periods list what type of weather it is, and the temperature, in this case: `Cloudy, 12` (not `12 Cloudy`). The values can be separated by a comma, tab, or whatever.

Each city must be separated from the others in such a way that they form distinct "blocks", as in the example output. The output should be on a table like format.

The details of the output format is optional.

These parts: `Italy/Liguria/Genoa/`, `Brazil/Rio_de_Janeiro/Rio_de_Janeiro/` of the code can be subtracted from the byte count (no need to chose the shortest city names). Url-shorteners are prohibited.

It must be possible to run your code a year from now, so you can't hard code dates etc.

The weather data is free and publicly available, as long as the following attribution is shown, so please include it in the bottom of your answer.

This is code golf, so the shortest answer in bytes win.

Weather forecast from yr.no, delivered by the Norwegian Meteorological Institute and the NRK.

# Answer
# Mathematica 418 bytes

These are the URL's. We will assume they are contained in variables and thus not count them.

t="http://www.yr.no/place/Japan/Tokyo/Tokyo/forecast.xml"; a="http://www.yr.no/place/Algeria/Alger/Algiers/forecast.xml"; b="http://www.yr.no/place/United\_States/Massachusetts/Boston/forecast.xml"; r="http://www.yr.no/place/Brazil/Pernambuco/Recife/forecast.xml"; p="http://www.yr.no/place/France/Île-de-France/Paris/forecast.xml"; c="http://www.yr.no/place/Australia/Australian\_Capital\_Territory/Canberra/forecast.xml";

This is the code used.

```
z@{s_,k_}:=Cases[s~Import~"XML",XMLElement["time",{"from"-> d_,b_,"period"->p_},
{XMLElement[_,{___,"name"->w_,___},{}],___,XMLElement["temperature",{___,"value"->t_},{}],
___}]:>{" "->Row[{d~StringTake~10,p},", "],k->Row[{w, t},", "]},Infinity];
w=Join@@(z/@{{t,"Tokyo, JA"},{a,"Algiers, AL"},{b,"Boston, US"},{r,"Recife, BR"},
{p,"Paris, FR"},{c,"Canberra, AU"}});
Dataset[Association/@(Prepend[Cases[w,{#,r__}:>r],#]&/@w[[All,1]])]

```

---
> 1 votes

---
Tags: code-golf, internet
---


title: Convert Brainfuck to MarioLANG

text:
# Question
Title: Convert Brainfuck to MarioLANG
MarioLANG is a two-dimensional programming language where the source code resembles a Super Mario Bros. level. Furthermore, its instruction set is very similar to Brainfuck's. This means that MarioLANG is essentially a 2-D Brainfuck where the instruction pointer moves like Mario. So when I wrote my MarioLANG submission for the Programming Language Quiz, I started by converting a Brainfuck "Hello, World!" program to MarioLANG. I noticed that this is possible with a very systematic process, so let's write a Brainfuck-to-MarioLANG compiler!

*Note:* The MarioLANG spec isn't entirely unambiguous, so I'm assuming the interpretation of the Ruby implementation.

I'll explain the process with the following Brainfuck program:

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

```

It prints `Hello!` and a trailing newline.

1. Convert `<` and `>` to `(` and `)`, respectively:

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

```
2. Add a floor for Mario to walk on:

```
++[)+++++[)+++++++)++++++++++)+++)+((((-](-]))++.)+.+++++++..+++.)+++.).
========================================================================

```
3. Now the issue is that MarioLANG doesn't have loops like `[` and `]`. Instead, we have to use elevators and directional instructions to make Mario actually walk in a loop. First, we replace `[` with `>` and change the floor to `"`. And we also replace `]` with `[!` and change the floor to `=#`:

```
++>)+++++>)+++++++)++++++++++)+++)+((((-[!(-[!))++.)+.+++++++..+++.)+++.).
=="======"===============================#===#============================

```
4. The `"` and `#` can form elevators (starting from `#`, ending at `"`), so now all we need are auxiliary floors for Mario to walk back on. The start with `!` and end with `<`:

```
++>)+++++>)+++++++)++++++++++)+++)+((((-[!(-[!))++.)+.+++++++..+++.)+++.).
=="======"===============================#===#============================
         !                               <
         #==============================="
  !                                          <
  #=========================================="

```

Note that all lines must be at least as long as the largest enclosing loop, because the interpreter isn't able to connect elevator ends across shorter lines. Therefore, we pad the middle lines with spaces.

And that's it. We've got a fully functional, equivalent MarioLANG program.

## The Challenge

Given a valid Brainfuck program, implement the above procedure to compile it into a MarioLANG program.

You may assume that there are only command characters in the input, i.e. no characters except `,.+-<>[]`.

All auxiliary floor must be as close as possible to the main program floor. You may choose to pad the lines of intermediate floors either as little as possible (up to the width of the largest enclosing loop) or to the end of the main program.

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. If you don't print the result to STDOUT, it should still be a single newline-separated string.

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

## Test Cases

The test cases are formatted as follows: the first line is the Brainfuck program (your input), then there's an empty line, and everything until the next empty line is the expected output in MarioLANG. These examples use the minimal amount of padded spaces. Alternatively, you may pad each line with spaces to the width of the first line of the output.

```
>,++-.<

),++-.(
=======

,[.,]

,>.,[!
="===#
 !   <
 #==="

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

))>-[!((>-))+(([!
=="==#=="=======#
  !  <  !       <
  #=="  #======="

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

++>)+++++>)+++++++)++++++++++)+++)+((((-[!(-[!))++.)+.+++++++..+++.)+++.).
=="======"===============================#===#============================
         !                               <
         #==============================="
  !                                          <
  #=========================================="

[][[[][[]]][]][[]]

>[!>>>[!>>[![![!>[![!>>[![!
"=#"""=#""=#=#=#"=#=#""=#=#
! <  ! < ! <    ! <   ! <
#="  #=" #="    #="   #="
        !    <       !    <
        #===="       #===="
    !          <
    #=========="
   !                <
   #================"

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

))+++++++))++))++++))+++++++))+))++++))+))+++))+))+++++))+))++))+))++++++))++))++++))+++++++))+))+++++))++))+))+))++++))+++++++))+))+++++))+))+))+))++++))+++++++))+))+++++))++++++++++++++))+))+))++++))+++++++))+))+++++))++))+))+))++++))+++++++))+))+++++))+++++++++++++++++++++++++++++))+))+))++++))+++++++))+))+++++))++))+))+))+++++))+))++++++))+))++))+))++++++))+))++))+))++++++))+))++))+))++++++))+))++))+))++++++))+))++))+))++++++))+))++))+))++++++))++))++++))+++++++))+))+++++))+++++++))+))+++++))+))+))+))++++))+))++))+))++++++))+))+++++))+++++++))+))++++))+))+))++))+++++))+))+++))+))++++))+))++))+))++++++))+))+++++))+++++++++++++++++++))++))++))+++))++))+))++))++++))+++++++))++))+++++))++++++++++))+))++))++++))+))++))+))++++++))++++++))+))+))+++++))+))++++++))++))+++++))+++++++))++))++++))+))++++++>(([!))>)++++++>-((++++++++++))[!((++..-------------------)>-(.))+([!)>-(+)[!)[!((>->->->->->->)++)[!(+++++++++++++++++++++++++++++)[!(++)[!(++++++++++++++)[!(+)[!(++)[!((>-).([!(([!
========================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================="===#=="======="================#=========================="========#="=====#==#=="="="="="="="=====#================================#=====#=================#====#=====#=="=====#===#
                                                                                !   <          !                <                          !        < !     <                 !     <                                                                      !     <
                                                                                #==="          #================"                          #========" #====="                 #====="                                                                      #====="
                                                                                !                                                                       <            !                                        <
                                                                                #======================================================================="            #========================================"
                                                                                !                                                <
                                                                                #================================================"
                                                                                !                                                                    <
                                                                                #===================================================================="
                                                                                !                                                                           <
                                                                                #==========================================================================="
                                                                                !                                                                                <
                                                                                #==================================================================================="
                                                                                !                                                                                <
                                                                                #=================================================================================================="

```

# Answer
# CJam, ~~148~~ 144 bytes

```
q"<>[""()>"er']/"[!"*_">!"1$|"\"#=":Cer:FF,[{SF,*L{'=t}/FI>(C#"['=-{_'##}{_CW</s}w],2*(:M'#tM('!tLM+ ;LW=34ctLW=('<tLW< ;L"S/=~:L;}fI]z~]{S-},N*

```

Try it online in the CJam interpreter.
> 5 votes

# Answer
# Python, 707 chars

```
def b(c):
 c,l,o,x,j,m=list(c.replace(">",")").replace("<","(")),[list("="*len(c))],[],[],0,0
 for i,z in enumerate(c):
  i+=j
  if"["==z:
   c[i],l[0][i]=">",'"'
   x.append(i)
  if"]"==z:
   c[i],l[0][i]="[!","=#"
   c,l[0],m,d,b=list("".join(c)),list("".join(l[0])),max(m,len(x)),0,x.pop()
   for a in o:d+=b<a[0]and-~i>a[0]or b<a[1]and-~i>a[1]
   o.append((b,i+1,d))
   j+=1
 for q in o:
  d=q[2]*2+1
  while len(l)<=d+1:l.append(list(" "*len(c)))
  l[d][q[0]],l[d+1][q[0]],l[d][q[1]],l[d+1][q[1]]="!","#","<",'"'
  for i in range(q[0]+1,q[1]):l[d+1][i]="="
 g="\n".join(l.rstrip()for l in("".join(c)+"\n"+"\n".join("".join(f)for f in l)).split("\n"))
 while"\n\n"in g:g=g.replace("\n\n","\n")
 return g

```

There's probably a lot of space to be golfed. Doesn't work for the last test case.

Example usage:

```
>>> print b("++[>+++<-]>[<+++>-]<.")
=="=======#="=======#==
  !       < !       <
  #=======" #======="

```

No lines in the output contains trailing spaces.
> 2 votes

---
Tags: code-golf, brainfuck, code-generation
---


title: Multiple program Quinecatenate!

text:
# Question
Title: Multiple program Quinecatenate!
Your task is to give three different languages A, B, C, and write two different programs P and Q such that:

P is a quine in language A, but not a quine in B nor C;

Q is a quine in language B, but not a quine in A nor C; and

Q concatenated after P (without any new characters added in between) is a quine in language C, but not in B nor A.

This is codegolf, where your score is the length of the final, concatenated quine. Again, adhere to the rules of proper quines -- no reading your source code, no empty programs etc.

# Answer
# Fission + CJam + GolfScript, ~~38~~ 36 bytes

### Fission, 6 bytes

```
'!+OR"

```

This is one of Martin Büttner's Fission quines. Try it online!

### CJam, 30 bytes

```
' {"''"@*" "+YX#<
\"0$~"N}0$~

```

The last byte is a linefeed. Try it online!

### GolfScript, 36 bytes

```
'!+OR"' {"''"@*" "+YX#<
\"0$~"N}0$~

```

The last byte is a linefeed. Try it online!

## Verification

```
$ wc -c P Q
 6 P
30 Q
36 total
$ cat P Q > P+Q
$
$ Fission P 2>&- | diff -qs - P
Files - and P are identical
$ cjam P 2>&- | diff -qs - P
Files - and P differ
$ golfscript P 2>&- | diff -qs - P
Files - and P differ
$
$ cjam Q 2>&- | diff -qs - Q
Files - and Q are identical
$ golfscript Q 2>&- | diff -qs - Q
Files - and Q differ
$ Fission Q 2>&- | diff -qs - Q
Files - and Q differ
$
$ golfscript P+Q 2>&- | diff -qs - P+Q
Files - and P+Q are identical
$ Fission P+Q 2>&- | diff -qs - P+Q
Files - and P+Q differ
$ cjam P+Q 2>&- | diff -qs - P+Q
Files - and P+Q differ

```

## How it works

### Fission

* `R` spawns an atom that moves right, wrapping around at the edge.
* `"` toggles printing mode. Everything up to the next `"` is printed.
* `'!` sets the atom's to the code point of '!'.
* `+` increments the atom's mass, setting it to the code point of `"`.
* `O` prints the character whose code point is the atom's mass and destroys the atom.

### CJam

```
'       e# Push a space character.
{       e# Push the following code block:
  "''"  e# Push that string.
  @*    e# Separate its characters by spaces.
  " "+  e# Append one more space.
  YX#   e# Raise 2 to the first power. Pushes 2.
  <     e# Discard all but the first two characters of the string, i.e., "' ".
  \     e# Swap the string "' " with the code block in execution.
  "0$~" e# Push that string.
  N     e# Push a linefeed.
}       e#
0$~     e# Push a copy of the code block and execute it.

```

### GolfScript

```
'!+OR"' # Push that string.
{       # Push the following code block:
  "''"  # Push that string.
  @*    # Join its characters, separating them by the first string.
  " "+  # Append a space.
  YX    # Undefined token. Does nothing.
  #<    # Comment.
  \     # Swap the string with the code block in execution.
  "0$~" # Push that string.
  N     # Undefined token. Does nothing.
}       #
0$~     # Push a copy of the code block and execute it.

```
> 10 votes

# Answer
# Self-modifying Brainfuck + GolfScript + CJam, ~~29~~ 27 bytes

### Self-modifying Brainfuck, 12 bytes

```
 {<[<]>[.>]}

```

Note the leading space. Try it online!

### GolfScript, 15 bytes

```
{So"0$~"N]}0$~

```

The last byte is a linefeed. Try it online!.

### CJam, 27 bytes

```
 {<[<]>[.>]}{So"0$~"N]}0$~

```

Note the leading space. The last byte is a linefeed. Try it online!

## Verification

```
$ wc -c P Q
12 P
15 Q
27 total
$ cat P Q > P+Q
$
$ timeout 10 smbf P | diff -sq - P
Files - and P are identical
$ golfscript P | diff -sq - P
Files - and P differ
$ cjam P | diff -sq - P
Files - and P differ
$
$ golfscript Q | diff -sq - Q
Files - and Q are identical
$ cjam Q | diff -sq - Q
Files - and Q differ
$ timeout 10 smbf Q | diff -sq - Q
Terminated
$
$ cjam P+Q | diff -sq - P+Q
Files - and P+Q are identical
$ golfscript P+Q | diff -sq - P+Q
Files - and P+Q differ
$ timeout 10 smbf P+Q | diff -sq - P+Q
Terminated

```

## How it works

### Self-modifying Brainfuck

SMBF starts with its source code on the left of the data pointer.

```
<space>        (ignored)
{              (ignored)
<              Move the data pointer left.
[<]            Move the data pointer left to the next null byte.
>              Move the data pointer right.
[.>]           Print and move the data pointer right until null byte.
}              (ignored)

```

### GolfScript

```
{            # Push the following code block:
  So         # Undefined token. Does nothing.
  "0$~"      # Push that string.
  N          # Undefined token. Does nothing.
  ]          # Wrap the stack in a array. Does not affect output.
}            #
0$~          # Push a copy of the code block and execute it.

### CJam

{<[<]>[.>]} e# Push that code block.
{           e# Push the following code block:
  So        e# Print a space. Since it is printed explicitly,
            e# it will appear at the beginning of the output.
  "0$~"     e# Push that string.
  N         e# Push a linefeed.
  ]         e# Wrap the stack in a array. Does not affect output.
            e# This makes the program an infinite, empty  loop
            e# in SMBF; it would be a quine otherwise.
}           e#
0$~         e# Push a copy of the code block and execute it.

```
> 6 votes

# Answer
# Tcl, CJam, GolfScript, 60 + 26 = 86 112 bytes

Not golfed well.

### Tcl, 60 bytes

```
{puts} [{join} {{} \{ \}\]} {{puts} [{join} {{} \{ \}\]} }]

```

Based on the quine on this page. It has a trailing newline.

### CJam, 26 bytes

```
{"' '@`+n@0"L~;"0$~"N}0$~

```

It has a trailing newline.

### GolfScript, 86 bytes

```
{puts} [{join} {{} \{ \}\]} {{puts} [{join} {{} \{ \}\]} }]
{"' '@`+n@0"L~;"0$~"N}0$~

```
> 5 votes

# Answer
# ShapeScript + CJam + GolfScript, ~~96~~ ~~95~~ 62 bytes

### ShapeScript, 16 bytes

```
'"%r"@%"0?!"'0?!

```

This is the standard ShapeScript quine. Try it online!

### CJam, 46 bytes

```
];{"'\"%r\"@%\"0?!\"'0?!];"SS#~(>
\"0$~"N}0$~

```

The last byte is a linefeed. Try it online!

### GolfScript, 62 bytes

```
'"%r"@%"0?!"'0?!];{"'\"%r\"@%\"0?!\"'0?!];"SS#~(>
\"0$~"N}0$~

```

The last byte is a linefeed. Try it online on Web GolfScript.

## Verification

```
$ wc -c P Q
16 P
46 Q
62 total
$ cat P Q > P+Q
$
$ shapescript P 2>&- | diff -qs - P
Files - and P are identical
$ cjam P 2>&- | diff -qs - P
Files - and P differ
$ golfscript P 2>&- | diff -qs - P
Files - and P differ
$
$ cjam Q 2>&- | diff -qs - Q
Files - and Q are identical
$ golfscript Q 2>&- | diff -qs - Q
Files - and Q differ
$ shapescript Q 2>&- | diff -qs - Q
Files - and Q differ
$
$ golfscript P+Q 2>&- | diff -qs - P+Q
Files - and P+Q are identical
$ shapescript P+Q 2>&- | diff -qs - P+Q
Files - and P+Q differ
$ cjam P+Q 2>&- | diff -qs - P+Q
Files - and P+Q differ

```

## How it works

### ShapeScript

```
'       Push a string that, when evaluated, does the following.
  "%r"  Push this formatting string. %r gets replaced by a string
        representation of the corresponding argument.
  @     Swap the string that is being evaluated on top of the stack.
  %     Apply formatting to the string on top of the stack.
  "0?!" Push that string.
'
0?!     Push a copy of the previous string and evaluate it.

```

### CJam

```
];      e# Clear the stack. Stack is already clear. Does nothing.
{       e# Push the following code block:

  "'\"%r\"@%\"0?!\"'0?!];"

  SS#   e# Find the index of " " in " ". Pushes 0.
  ~(    e# Apply logical NOT and decrement. Pushes -2.
  >     e# Discard all but the two rightmost characters from the string,
        e# i.e., reduce it to "];".
  \     e# Swap the string "];" with the code block in execution.
  "0$~" e# Push that string.
  N     e# Push a linefeed.
}       e#
0$~     e# Push a copy of the code block and execute it.

```

### GolfScript

```
'"%r"@%"0?!"'

0?!     # Find the index of the number 0 in the string and apply logical NOT.
];      # Clear the stack.
{       # Push the following code block:

  "'\"%r\"@%\"0?!\"'0?!];"

  SS    # Undefined token. Does nothing.
  #~(>  # Comment.
  \     # Swap the string with the code block in execution.
  "0$~" # Push that string.
  N     # Undefined token. Does nothing.
}       #
0$~     # Push a copy of the code block and execute it.

```
> 2 votes

---
Tags: code-golf, quine, polyglot
---