title: Turing-Complete polyglot

text:
# Question
Title: Turing-Complete polyglot
Write a polyglot (code that works in two or more languages) that has a "mid-section" that can be modified to do any computational task. This question is similar to https://stackoverflow.com/questions/1053931/code-golf-shortest-turing-complete-interpreter.

**Rules**:

The program must be able to preform a computation and print the results. Pseudorandom number capability is a plus but not necessary. The results must be the same in all languages, minor string-formatting differences are OK.

There is a section in the program that can be modified (in a straight-forward way) to do any computation (Turing complete). This is like the "comments section" in http://ideology.com.au/polyglot/polyglot.txt for which any comment can be inserted.

You must use at least 2 languages (this rule is here so you don't sue me).

**Edit**: Ideally you only need to write the "computation" part once. It is less interesting to use comment blocks, etc to knock out A so you have a block from B and then knockout B to write code from A. However, the one block solution is very difficult unless the languages have enough "overlap".

Also, using very similar languages (like C# and Java) isn't as interesting. It is still *allowed* but will probably earn less votes.

**Grading**

The winning is a popularity contest (Mar 1st).

# Answer
> 4 votes
## Ruby and Spidermonkey JS

```
i=0
r=rand
=begin
=Math.random(); n=print;
var end=''; y
=end
//=~''; def n(x); puts x; end

while ((i+=1) < 5)
  if (i%2==0)
    n('Hi!')
  else
    n('Bye!')
  end;
end;

a=17*r
n(a);

```

This works because...

* `rand` is random in Ruby, but a variable in JS that gets assigned to `Math.random()`. A slight improvement would be assigning JS's `rand` to `Math.random` so that you can execute rand() in both.
* `=begin...=end` is a comment block in Ruby and assignment in JS
* The middle part is polyglot. If you gave the list of any functions you'd like, I'd def them in Ruby so they are the same as the JS ones or possibly define them in JS.
* `end`, needed to end code blocks in ruby is now defined as `''` in JS.
* `while` is the same in both languages, as is `+=`, `==`, `-=`, `*`, `-`, `+`, `=`, `%`, `/`, `'strings'`
* `//` is the start of a comment in JS but a regex in Ruby.
* `n` is defined in Spidermonkey JS to be `print` (which outputs to stdout). In Ruby, I redefined it to be `puts`, much the same. If I weren't in a mindset, I would have `def print(x)` instead of `n(x)`.
* **No use of polyglot comments!**

# Answer
> 9 votes
## C, Python, and Brainfuck

The Brainfuck program on the line starting with `pgm=` can be changed into any valid Brainfuck program (so it is Turing-complete). The program will then run in C, Python, and Brainfuck. The given program prints `Hello World!`.

The interpreters in both C and Python have the following characteristics:

* 8-bit cells
* Infinite tape in both directions
* -1 (255) on EOF

It runs like this:

```
$ gcc poly_bf.c; ./a.out
Hello World!
$ python poly_bf.c
Hello World!
$ bf poly_bf.c
Hello World!

```

And here's the program:

```
#define AA [
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define BB ]
#define PGM char*\
pgm="++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.";
#define ZZ \
""" [-][";
struct cell { char val; struct cell *prev; struct cell *next; };
struct cell *prv(struct cell *c) {
    if (!c->prev) {
        struct cell *z = malloc(sizeof(struct cell));
        z->next = c;
        z->prev = 0;
        z->val = 0;
        c->prev = z;
    }
    return c->prev;
}
struct cell *nxt(struct cell *c) {
    if (!c->next) {
        struct cell *z = malloc(sizeof(struct cell));
        z->prev = c;
        z->next = 0;
        z->val = 0;
        c->next = z;
    }
    return c->next;
}
int main() {
    PGM
    int ip=0, t=0;
    struct cell *c = malloc(sizeof(struct cell));
    memset(c, 0, sizeof(struct cell));
    while (pgm[ip]) {
       switch(pgm[ip]) {
           case '+': c->val++;break;
           case '-': c->val--;break;
           case '>': c=nxt(c);break;
           case '<': c=prv(c);break;
           case '.': putchar(c->val);break;
           case ',': c->val=getchar();break;
           case '[':
               if (c->val) break;
               ip++;
               t=1;
               while (t) {
                  t += pgm[ip] == '[';
                  t -= pgm[ip] == ']';
                  ip++;
               }
               ip--;
               break;
           case ']':
               if (!c->val) break;
               ip--;
               t=1;
               while (t) {
                  t -= pgm[ip] == '[';
                  t += pgm[ip] == ']';
                  ip--;
               }
               ip++;
               break;
       }
       ip++;
    }
    return 0;
}
#define YY \
" """;
#define XX /*
import sys;
ip=t=0
class Cell:
  pv=None
  nx=None
  val=0

  def prev(self):
     if not self.pv:
        self.pv = Cell()
        self.pv.nx = self
     return self.pv
  def next(self):
     if not self.nx:
        self.nx = Cell()
        self.nx.pv = self
     return self.nx

cell=Cell()
while ip<len(pgm):
  if pgm[ip]=='+': cell.val+=1;cell.val%=256
  elif pgm[ip]=='-': cell.val-=1;cell.val%=256
  elif pgm[ip]=='>': cell=cell.next()
  elif pgm[ip]=='<': cell=cell.prev()
  elif pgm[ip]=='.': sys.stdout.write(chr(cell.val))
  elif pgm[ip]==',':
      ch=sys.stdin.read(1)
      if ch:cell.val=ord(ch)
      else:cell.val=255
  elif pgm[ip]=='[' and not cell.val:
      t=1
      ip+=1
      while t:
        t += pgm[ip] == '['
        t -= pgm[ip] == ']'
        ip+=1
      ip-=1
  elif pgm[ip]==']' and cell.val:
      t=1
      ip-=1
      while t:
        t -= pgm[ip] == '['
        t += pgm[ip] == ']'
        ip-=1
      ip+=1
  ip+=1
#]*/

```

# Answer
> 2 votes
# Ruby and C

```
//; def void x; end; def main x, &b; b.call; end; def int x; end; arg = nil

//# Welcome to the Ruby/C polyglot thingy!
//# Simply insert whatever code you would like below.

void main(int arg) {

//; puts 1+1 # any Ruby code can be inserted on this line
//; puts 2+2 # the Ruby version is extendable to an arbitrary amount of lines
//; puts 3+3
//; puts 4+4

#define f printf(1+1) // any C code can be inserted on this line
//;f=nil
f;
#define g printf(2+2) // the C version is somewhat extendable
#define h printf(3+3)
#define i printf(4+4)
//;g=h=i=nil
g;h;i;

}

```

This takes advantage of the fact that

* `//#` is a comment in both languages
* `//;` is a comment in only C
* `"#define x "` (with the space!) is (somewhat of) a comment in only Ruby
    + you then have to actually put it in the code, which is why I assign all the vars to `nil` and then simply place them in a new line

# More extendable C version

```
//; def method_missing m, *args; end
#define a printf(1+1);
#define b printf(1+1);
#define c printf(1+1);
#define codegolf printf(1+1);
#define llama printf(1+1);
a b c codegolf llama

```

# Answer
> 0 votes
# PHP, ASP and JS:

WARNING: THIS WAS NOT TESTED:

Here is an attempt:

```
<!--<?error_reporting(0);?><% WebService Language="JScript" Class="MyClass" %>-->
<script runat="server">
console.log('/*<?=#*/$a='Math';/*?>*///#?>');
</script>

```

What should happen:

It should run the Javascript code on the server, when running on ASP.

In php, should output absolutely only the Javascript part, Saying 'Math' inside the whole comments.

In Javascript, it should put all that "garbage" in the console.

If it is invalid, just comment and I will remove this answer.

---
Tags: popularity-contest, polyglot
---


# Question
Title: Count characters, turn them into a cipher
**Problem:**

You must make a program that does the following:

* takes a large string of lowercase text, and counts all the occurrences of each letter.
* then you put the letters in order from greatest to least occurences.
* then you take that list and turns it into an encoder/decoder for the text.
* then encodes the text with that cipher.

Hard to understand? See this example:

**Example:**

Input text:

> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sed dui at nisi euismod pellentesque ac sed enim. Nullam auctor justo quis diam faucibus, eu fringilla est porttitor. Pellentesque vel pharetra nisl. Vestibulum congue ultrices magna a fringilla. Quisque porttitor, risus suscipit pellentesque tristique, orci lorem accumsan nisi, scelerisque viverra turpis metus sit amet sapien. Fusce facilisis diam turpis, nec lobortis dui blandit nec. Vestibulum ac urna ut lacus commodo sollicitudin nec non velit. Nulla cursus urna sem, at tincidunt sem molestie vel. Nullam fringilla ante eu dolor bibendum, posuere iaculis nunc lacinia. Sed ac pretium est, vel scelerisque nisl. Phasellus lobortis dolor sodales sapien mollis hendrerit. Integer scelerisque tempor tellus, viverra varius neque mattis in. Integer porta vestibulum nisl, et feugiat tortor tincidunt vel. Aenean dignissim eleifend faucibus. Morbi nec neque vel ante pulvinar mollis eu in ipsum.

Convert to lowercase.

Char count (per letter. spaces and punctuation ignored):

> \[('a', 49), ('b', 11), ('c', 34), ('d', 22), ('e', 93), ('f', 9), ('g', 10), ('h', 3), ('i', 89), ('j', 1), ('k', 0), ('l', 61), ('m', 31), ('n', 56), ('o', 37), ('p', 20), ('q', 12), ('r', 47), ('s', 71), ('t', 59), ('u', 65), ('v', 15), ('w', 0), ('x', 0), ('y', 0), ('z', 0)\]

Ordered char count:

> \[('e', 93), ('i', 89), ('s', 71), ('u', 65), ('l', 61), ('t', 59), ('n', 56), ('a', 49), ('r', 47), ('o', 37), ('c', 34), ('m', 31), ('d', 22), ('p', 20), ('v', 15), ('q', 12), ('b', 11), ('g', 10), ('f', 9), ('h', 3), ('j', 1), ('k', 0), ('w', 0), ('x', 0), ('y', 0), ('z', 0)\]

Then create a lookup table using the original and sorted lists:

```
abcdefghijklmnopqrstuvwxyz
||||||||||||||||||||||||||
eisultnarocmdpvqbgfhjkwxyz

```

Python dictionary:

```
{'o': 'v', 'n': 'p', 'm': 'd', 'l': 'm', 'k': 'c', 'j': 'o', 'i': 'r', 'h': 'a', 'g': 'n', 'f': 't', 'e': 'l', 'd': 'u', 'c': 's', 'b': 'i', 'a': 'e', 'z': 'z', 'y': 'y', 'x': 'x', 'w': 'w', 'v': 'k', 'u': 'j', 't': 'h', 's': 'f', 'r': 'g', 'q': 'b', 'p': 'q'}

```

And now encode the original text with this lookup table:

> 'Lvgld rqfjd uvmvg frh edlh, svpflshlhjg eurqrfsrpn lmrh. Njps flu ujr eh prfr ljrfdvu qlmmlphlfbjl es flu lprd. Njmmed ejshvg ojfhv bjrf ured tejsrijf, lj tgrpnrmme lfh qvghhrhvg. Plmmlphlfbjl klm qaeglhge prfm. Vlfhrijmjd svpnjl jmhgrslf denpe e tgrpnrmme. Qjrfbjl qvghhrhvg, grfjf fjfsrqrh qlmmlphlfbjl hgrfhrbjl, vgsr mvgld essjdfep prfr, fslmlgrfbjl krklgge hjgqrf dlhjf frh edlh feqrlp. Fjfsl tesrmrfrf ured hjgqrf, pls mvivghrf ujr imepurh pls. Vlfhrijmjd es jgpe jh mesjf svddvuv fvmmrsrhjurp pls pvp klmrh. Njmme sjgfjf jgpe fld, eh hrpsrujph fld dvmlfhrl klm. Njmmed tgrpnrmme ephl lj uvmvg irilpujd, qvfjlgl resjmrf pjps mesrpre. Slu es qglhrjd lfh, klm fslmlgrfbjl prfm. Paeflmmjf mvivghrf uvmvg fvuemlf feqrlp dvmmrf alpuglgrh. Iphlnlg fslmlgrfbjl hldqvg hlmmjf, krklgge kegrjf plbjl dehhrf rp. Iphlnlg qvghe klfhrijmjd prfm, lh tljnreh hvghvg hrpsrujph klm. Alplep urnprffrd lmlrtlpu tejsrijf. Mvgir pls plbjl klm ephl qjmkrpeg dvmmrf lj rp rqfjd.'

I love python!

**Rules:**

* Your program will accept a string and output one.
* Convert all input to lowercase before doing anything
* I don't care how you do the list sorting, but only count lowercase letters
* Bonus points (-30) for making a decryptor (no copying the decryption list, do it from scratch
* This is , so the shortest code wins!
* Have fun!

# Answer
> 3 votes
### GolfScript, 39 characters

```
:I{97,26,{97+}%{[.32-]I\-,}$+'{|}~'+=}%

```

Online version for testing. Note that the sorting is not defined if multiple characters have the same count in the input string.

*Example output*

> Lvgld rqfjd uvmvg frh edlh, svpflshlhjg eurqrfsrpn lmrh. Njps flu ujr eh prfr ljrfdvu qlmmlphlfbjl es flu lprd. Njmmed ejshvg ojfhv bjrf ured tejsrijf, lj tgrpnrmme lfh qvghhrhvg. Plmmlphlfbjl wlm qaeglhge prfm. Vlfhrijmjd svpnjl jmhgrslf denpe e tgrpnrmme. Qjrfbjl qvghhrhvg, grfjf fjfsrqrh qlmmlphlfbjl hgrfhrbjl, vgsr mvgld essjdfep prfr, fslmlgrfbjl wrwlgge hjgqrf dlhjf frh edlh feqrlp. Fjfsl tesrmrfrf ured hjgqrf, pls mvivghrf ujr imepurh pls. Vlfhrijmjd es jgpe jh mesjf svddvuv fvmmrsrhjurp pls pvp wlmrh. Njmme sjgfjf jgpe fld, eh hrpsrujph fld dvmlfhrl wlm. Njmmed tgrpnrmme ephl lj uvmvg irilpujd, qvfjlgl resjmrf pjps mesrpre. Slu es qglhrjd lfh, wlm fslmlgrfbjl prfm. Paeflmmjf mvivghrf uvmvg fvuemlf feqrlp dvmmrf alpuglgrh. Iphlnlg fslmlgrfbjl hldqvg hlmmjf, wrwlgge wegrjf plbjl dehhrf rp. Iphlnlg qvghe wlfhrijmjd prfm, lh tljnreh hvghvg hrpsrujph wlm. Alplep urnprffrd lmlrtlpu tejsrijf. Mvgir pls plbjl wlm ephl qjmwrpeg dvmmrf lj rp rqfjd.

# Answer
> 3 votes
# Bash/coreutils, 91 chars

```
tr a-z `echo {a..z} $1|fold -w1|grep '[a-z]'|sort|uniq -c|sort -rn|awk '{printf $2}'`<<<$1

```

Save as `cipher.sh`, chmod +x it and run:

```
$ ./cipher.sh "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sed dui at nisi euismod pellentesque ac sed enim. Nullam auctor justo quis diam faucibus, eu fringilla est porttitor. Pellentesque vel pharetra nisl. Vestibulum congue ultrices magna a fringilla. Quisque porttitor, risus suscipit pellentesque tristique, orci lorem accumsan nisi, scelerisque viverra turpis metus sit amet sapien. Fusce facilisis diam turpis, nec lobortis dui blandit nec. Vestibulum ac urna ut lacus commodo sollicitudin nec non velit. Nulla cursus urna sem, at tincidunt sem molestie vel. Nullam fringilla ante eu dolor bibendum, posuere iaculis nunc lacinia. Sed ac pretium est, vel scelerisque nisl. Phasellus lobortis dolor sodales sapien mollis hendrerit. Integer scelerisque tempor tellus, viverra varius neque mattis in. Integer porta vestibulum nisl, et feugiat tortor tincidunt vel. Aenean dignissim eleifend faucibus. Morbi nec neque vel ante pulvinar mollis eu in ipsum."
Lvgld rqfjd uvmvg frh edlh, svpflshlhjg eurqrfsrpn lmrh. Njps flu ujr eh prfr ljrfdvu qlmmlphlfbjl es flu lprd. Njmmed ejshvg ojfhv bjrf ured tejsrijf, lj tgrpnrmme lfh qvghhrhvg. Plmmlphlfbjl jlm qaeglhge prfm. Vlfhrijmjd svpnjl jmhgrslf denpe e tgrpnrmme. Qjrfbjl qvghhrhvg, grfjf fjfsrqrh qlmmlphlfbjl hgrfhrbjl, vgsr mvgld essjdfep prfr, fslmlgrfbjl jrjlgge hjgqrf dlhjf frh edlh feqrlp. Fjfsl tesrmrfrf ured hjgqrf, pls mvivghrf ujr imepurh pls. Vlfhrijmjd es jgpe jh mesjf svddvuv fvmmrsrhjurp pls pvp jlmrh. Njmme sjgfjf jgpe fld, eh hrpsrujph fld dvmlfhrl jlm. Njmmed tgrpnrmme ephl lj uvmvg irilpujd, qvfjlgl resjmrf pjps mesrpre. Slu es qglhrjd lfh, jlm fslmlgrfbjl prfm. Paeflmmjf mvivghrf uvmvg fvuemlf feqrlp dvmmrf alpuglgrh. Iphlnlg fslmlgrfbjl hldqvg hlmmjf, jrjlgge jegrjf plbjl dehhrf rp. Iphlnlg qvghe jlfhrijmjd prfm, lh tljnreh hvghvg hrpsrujph jlm. Alplep urnprffrd lmlrtlpu tejsrijf. Mvgir pls plbjl jlm ephl qjmjrpeg dvmmrf lj rp rqfjd.
$

```

# Answer
> 2 votes
### Ruby, ~~104~~ ~~92~~ 91 characters

Saved quite a few characters thanks to @Chron

```
f=->(s){m=[*?a..?z];l=m.map{|x|[-s.downcase.count(x),x]};s.tr(m*'',l.sort.transpose[1]*'')}

```

Online Version here. Sorting of characters with the same count is not defined, as mentioned in another answer. With the input "asdf", each answer has another output so far.

In other words: all answers have the same behaviour (thus represent a decodable encoding) when the input contains the whole alphabet with each letter having a unique count.

# Answer
> 1 votes
# Mathematica 171

```
f@m_:=StringReplace[m,Thread[(CharacterRange["a",
FromCharacterCode[96+Length@(l=Reverse@SortBy[Tally[Select[Characters@m,
(LetterQ@#\[And]LowerCaseQ@#)&]],Last][[All,1]])]])->l ]]

```

Assuming `t` is the Lorem ipsum text.

```
f[t]

```

> "Lvgld rqfjd uvmvg frh edlh,svpflshlhjg eurqrfsrpn lmrh.Njps flu ujr eh prfr ljrfdvu qlmmlphlfbjl es flu lprd.Njmmed ejshvg ojfhv bjrf ured tejsrijf,lj tgrpnrmme lfh qvghhrhvg.Plmmlphlfbjl vlm qaeglhge prfm.Vlfhrijmjd svpnjl jmhgrslf denpe e tgrpnrmme.Qjrfbjl qvghhrhvg,grfjf fjfsrqrh qlmmlphlfbjl hgrfhrbjl,vgsr mvgld essjdfep prfr,fslmlgrfbjl vrvlgge hjgqrf dlhjf frh edlh feqrlp.Fjfsl tesrmrfrf ured hjgqrf,pls mvivghrf ujr imepurh pls.Vlfhrijmjd es jgpe jh mesjf svddvuv fvmmrsrhjurp pls pvp vlmrh.Njmme sjgfjf jgpe fld,eh hrpsrujph fld dvmlfhrl vlm.Njmmed tgrpnrmme ephl lj uvmvg irilpujd,qvfjlgl resjmrf pjps mesrpre.Slu es qglhrjd lfh,vlm fslmlgrfbjl prfm.Paeflmmjf mvivghrf uvmvg fvuemlf feqrlp dvmmrf alpuglgrh.Iphlnlg fslmlgrfbjl hldqvg hlmmjf,vrvlgge vegrjf plbjl dehhrf rp.Iphlnlg qvghe vlfhrijmjd prfm,lh tljnreh hvghvg hrpsrujph vlm.Alplep urnprffrd lmlrtlpu tejsrijf.Mvgir pls plbjl vlm ephl qjmvrpeg dvmmrf lj rp rqfjd."

The replacement rules generated by `Thread…-> l` were:

> {"a" -\> "e", "b" -\> "i", "c" -\> "s", "d" -\> "u", "e" -\> "l", "f" -\> "t", "g" -\> "n", "h" -\> "a", "i" -\> "r", "j" -\> "o", "k" -\> "c", "l" -\> "m", "m" -\> "d", "n" -\> "p", "o" -\> "v", "p" -\> "q", "q" -\> "b", "r" -\> "g", "s" -\> "f", "t" -\> "h", "u" -\> "j"}

# Answer
> 1 votes
# K, 43

```
{x^(b!b^26$>#:'=a@&(a:_x)in b:"c"$97+!26)x}

```

# Answer
> 1 votes
**C# 386**

```
using System.Collections.Generic;using System.Linq;namespace N{class P{static void Main(string[]a){char[] f="abcdefghijklmnopqrstuvwxyz".ToCharArray();Dictionary<char,int>l=new Dictionary<char,int>();foreach (char c in f) l.Add(c, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sed dui at nisi euismod pellentesque ac sed enim. Nullam auctor justo quis diam faucibus, eu fringilla est porttitor. Pellentesque vel pharetra nisl. Vestibulum congue ultrices magna a fringilla. Quisque porttitor, risus suscipit pellentesque tristique, orci lorem accumsan nisi, scelerisque viverra turpis metus sit amet sapien. Fusce facilisis diam turpis, nec lobortis dui blandit nec. Vestibulum ac urna ut lacus commodo sollicitudin nec non velit. Nulla cursus urna sem, at tincidunt sem molestie vel. Nullam fringilla ante eu dolor bibendum, posuere iaculis nunc lacinia. Sed ac pretium est, vel scelerisque nisl. Phasellus lobortis dolor sodales sapien mollis hendrerit. Integer scelerisque tempor tellus, viverra varius neque mattis in. Integer porta vestibulum nisl, et feugiat tortor tincidunt vel. Aenean dignissim eleifend faucibus. Morbi nec neque vel ante pulvinar mollis eu in ipsum.".ToLower().Trim().Count(v => v == c));foreach (KeyValuePair<char, int> i in l.OrderByDescending(p => p.Value))System.Console.Write(i.Key +""+i.Value);}}}

```

Uncompressed.

```
using System.Collections.Generic;
using System.Linq;
namespace N {
    class P {
        static void Main(string[]a){
            char[] f="abcdefghijklmnopqrstuvwxyz".ToCharArray();
            Dictionary<char,int>l=new Dictionary<char,int>();
            foreach (char c in f)
                l.Add(c, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc sed dui at nisi euismod pellentesque ac sed enim. Nullam auctor justo quis diam faucibus, eu fringilla est porttitor. Pellentesque vel pharetra nisl. Vestibulum congue ultrices magna a fringilla. Quisque porttitor, risus suscipit pellentesque tristique, orci lorem accumsan nisi, scelerisque viverra turpis metus sit amet sapien. Fusce facilisis diam turpis, nec lobortis dui blandit nec. Vestibulum ac urna ut lacus commodo sollicitudin nec non velit. Nulla cursus urna sem, at tincidunt sem molestie vel. Nullam fringilla ante eu dolor bibendum, posuere iaculis nunc lacinia. Sed ac pretium est, vel scelerisque nisl. Phasellus lobortis dolor sodales sapien mollis hendrerit. Integer scelerisque tempor tellus, viverra varius neque mattis in. Integer porta vestibulum nisl, et feugiat tortor tincidunt vel. Aenean dignissim eleifend faucibus. Morbi nec neque vel ante pulvinar mollis eu in ipsum.".ToLower().Trim().Count(v => v == c));
            foreach (KeyValuePair<char, int> i in l.OrderByDescending(p => p.Value))
                System.Console.Write(i.Key +""+i.Value);
        }
    }
}

```

# Answer
> 0 votes
# PHP, 151

<sup>*(with setting `short_open_tag = On`)*</sup>

```
<?$c=array_slice(count_chars(strtolower($s=$argv[1])),97,26,1);arsort($c);echo strtr($s,array_combine(range('a','z'),array_map('chr',array_keys($c))));

```

This expects the text as the first argument to the script. Like so:

```
php cypher.php "Lorem ipsum [...]"

```

# Answer
> 0 votes
## R, 137

```
l=letters;s=strsplit(readline(),"")[[1]];g=grep("[a-z]",s);s[g]=names(sort(table(factor(tolower(s),l)),d=T))[match(s[g],l)];cat(s,sep="")

```

Output (based on example in question):

> Lvgld rqfjd uvmvg frh edlh, svpflshlhjg eurqrfsrpn lmrh. Njps flu ujr eh prfr ljrfdvu qlmmlphlfbjl es flu lprd. Njmmed ejshvg ojfhv bjrf ured tejsrijf, lj tgrpnrmme lfh qvghhrhvg. Plmmlphlfbjl klm qaeglhge prfm. Vlfhrijmjd svpnjl jmhgrslf denpe e tgrpnrmme. Qjrfbjl qvghhrhvg, grfjf fjfsrqrh qlmmlphlfbjl hgrfhrbjl, vgsr mvgld essjdfep prfr, fslmlgrfbjl krklgge hjgqrf dlhjf frh edlh feqrlp. Fjfsl tesrmrfrf ured hjgqrf, pls mvivghrf ujr imepurh pls. Vlfhrijmjd es jgpe jh mesjf svddvuv fvmmrsrhjurp pls pvp klmrh. Njmme sjgfjf jgpe fld, eh hrpsrujph fld dvmlfhrl klm. Njmmed tgrpnrmme ephl lj uvmvg irilpujd, qvfjlgl resjmrf pjps mesrpre. Slu es qglhrjd lfh, klm fslmlgrfbjl prfm. Paeflmmjf mvivghrf uvmvg fvuemlf feqrlp dvmmrf alpuglgrh. Iphlnlg fslmlgrfbjl hldqvg hlmmjf, krklgge kegrjf plbjl dehhrf rp. Iphlnlg qvghe klfhrijmjd prfm, lh tljnreh hvghvg hrpsrujph klm. Alplep urnprffrd lmlrtlpu tejsrijf. Mvgir pls plbjl klm ephl qjmkrpeg dvmmrf lj rp rqfjd.

# Answer
> 0 votes
# Smalltalk, 138

input in s:

```
m:=(s select:[:c|cisLetter])asLowercase asBag sortedCounts map:#value.
i:=($ato:$z).m:=m,(i copyWithoutAll:m).
s copyTransliterating:i to:m

```

the decoder is:

```
s copyTransliterating:m to:i

```

but as (if I understand correctly) I may not reuse "i" and "m", I'll golf without it. Code above has two additional CRs inserted for readability, which were uncounted in the char count.

# Answer
> 0 votes
# Clojure, 135

(Assuming the input text is contained in the var `s`)

```
(let[a(map char(range 97 123))m(->> s .toLowerCase frequencies(sort-by val >)keys(filter(set a))(zipmap a))](apply str(map #(m % %)s)))

```

# Answer
> 0 votes
# Python 2.7 (147)

Not the shortest code at all but as Python is not yet represented and as I see "I love python!" in the problem setting, here I go,

```
import sys;s=sys.argv[1];a=map(chr,range(97,123));print"".join([sorted(a,key=lambda x:-s.lower().count(x))[ord(c)-97]if c in a else c for c in s])

```

Expects the input string to be passed via the command line. (number of characters are reduced to **122** if the input string was magically inserted into the variable "s")

```
a=map(chr,range(97,123));print"".join([sorted(a,key=lambda x:-s.lower().count(x))[ord(c)-97]if c in a else c for c in s])

```

## Ouput

> Lvgld rqfjd uvmvg frh edlh, svpflshlhjg eurqrfsrpn lmrh. Njps flu ujr eh prfr ljrfdvu qlmmlphlfbjl es flu lprd. Njmmed ejshvg ojfhv bjrf ured tejsrijf, lj tgrpnrmme lfh qvghhrhvg. Plmmlphlfbjl klm qaeglhge prfm. Vlfhrijmjd svpnjl jmhgrslf denpe e tgrpnrmme. Qjrfbjl qvghhrhvg, grfjf fjfsrqrh qlmmlphlfbjl hgrfhrbjl, vgsr mvgld essjdfep prfr, fslmlgrfbjl krklgge hjgqrf dlhjf frh edlh feqrlp. Fjfsl tesrmrfrf ured hjgqrf, pls mvivghrf ujr imepurh pls. Vlfhrijmjd es jgpe jh mesjf svddvuv fvmmrsrhjurp pls pvp klmrh. Njmme sjgfjf jgpe fld, eh hrpsrujph fld dvmlfhrl klm. Njmmed tgrpnrmme ephl lj uvmvg irilpujd, qvfjlgl resjmrf pjps mesrpre. Slu es qglhrjd lfh, klm fslmlgrfbjl prfm. Paeflmmjf mvivghrf uvmvg fvuemlf feqrlp dvmmrf alpuglgrh. Iphlnlg fslmlgrfbjl hldqvg hlmmjf, krklgge kegrjf plbjl dehhrf rp. Iphlnlg qvghe klfhrijmjd prfm, lh tljnreh hvghvg hrpsrujph klm. Alplep urnprffrd lmlrtlpu tejsrijf. Mvgir pls plbjl klm ephl qjmkrpeg dvmmrf lj rp rqfjd.

# Answer
> 0 votes
## Perl, 84

```
$c{$_}++for lc($_=<>)=~/./g;@h{a..z}=sort{$c{$b}-$c{$a}}a..z;s/[a-z]/$h{$&}/ge;print

```

.

> perl cipher.pl
>
> .. input skipped ..
>
> Lvgld rqfjd uvmvg frh edlh, svpflshlhjg eurqrfsrpn lmrh. Njps flu ujr eh prfr lj rfdvu qlmmlphlfbjl es flu lprd. Njmmed ejshvg ojfhv bjrf ured tejsrijf, lj tgrpn rmme lfh qvghhrhvg. Plmmlphlfbjl klm qaeglhge prfm. Vlfhrijmjd svpnjl jmhgrslf d enpe e tgrpnrmme. Qjrfbjl qvghhrhvg, grfjf fjfsrqrh qlmmlphlfbjl hgrfhrbjl, vgsr mvgld essjdfep prfr, fslmlgrfbjl krklgge hjgqrf dlhjf frh edlh feqrlp. Fjfsl te srmrfrf ured hjgqrf, pls mvivghrf ujr imepurh pls. Vlfhrijmjd es jgpe jh mesjf s vddvuv fvmmrsrhjurp pls pvp klmrh. Njmme sjgfjf jgpe fld, eh hrpsrujph fld dvmlf hrl klm. Njmmed tgrpnrmme ephl lj uvmvg irilpujd, qvfjlgl resjmrf pjps mesrpre. Slu es qglhrjd lfh, klm fslmlgrfbjl prfm. Paeflmmjf mvivghrf uvmvg fvuemlf feqrl p dvmmrf alpuglgrh. Iphlnlg fslmlgrfbjl hldqvg hlmmjf, krklgge kegrjf plbjl dehh rf rp. Iphlnlg qvghe klfhrijmjd prfm, lh tljnreh hvghvg hrpsrujph klm. Alplep ur nprffrd lmlrtlpu tejsrijf. Mvgir pls plbjl klm ephl qjmkrpeg dvmmrf lj rp rqfjd.

P.S. Was it a joke, about decipher? Or should I claim 30 bonus for proving it impossible? Is `aab` deciphered to `aab` or `bba`? Or `babaca`, was it `cacaba` or `ababcb` in original, or `babaca` itself, literally?

# Answer
> 0 votes
# C# – 393 bytes

```
string e(string i){char[] f="abcdefghijklmnopqrstuvwxyz".ToCharArray();Dictionary<char,int>l=new Dictionary<char,int>();foreach (char c in f) l.Add(c, i.ToLower().Count(v => v == c));var w = (l.OrderByDescending(p => p.Value)).ToDictionary(q=>q.Key, y=>y.Value);var z = w.Keys.ToList();string r = "";foreach(char c in i) {if((int)c <=97 || (int)c>=122)r+=c;else r += z[((int)c-97)];}return r;}

```

The extended version of @PauloHDSousa’s answer

---
Tags: code-golf
---


title: A program that ends but never ends

text:
# Question
Title: A program that ends but never ends
Write a program that starts itself again when finishes.

There should be no more than one instance of the program running at same time. Not even for a slightest moment of time.

You can ignore any instance that is manually started by user during your cycle. But your code should not do it in your restart cycle.

Program can start after any amount of time, as long as it is guaranteed that it starts again.

The only way to stop the cycle is to kill the process.

Your solution should not involve restarting of the environment (in which program is running, includes OS, machine, VM, shell etc). Only your program is allowed to restart.

# Answer
> 50 votes
# Bash script, 3 chars (Shortest, possibly the most elegant, though admittedly controversial)

```
$0&

```

Simply places a new instance of itself in the background (new process), then quits. The new instance likely will remain in the scheduler run-queue until the previous instance is done.

### Warning - this is hard to `kill`, as the PID is continually changing. Temporarily renaming the script file is probably the simplest way to break the cycle.

A single-core system is assumed. Of course this is not realistic with Linux on modern bare-metal hardware, but it is easily configurable when running in a VM. We could probably achieve a similar trick using `taskset`, but that would reduce the impact of the 3-char solution.

This answer bends the rules a little bit in that it applies a specific meaning of "running". There will be moments when the new process has been `fork()`ed and the old process is still alive - i.e. it may be possible to observe more than one PID. However the new process will be placed on the Linux scheduler run-queue to wait for CPU cycles, while the existing process will continue to execute. At this point all that needs to be done by the existing process is for `bash` itself to `exit()`. This does take a finite amount of time, though I'm fairly confident that it will be done way before the current timeslice/scheduler quantum is done. Supporting evidence is the fact that `bash` starts up and shuts down in 2ms on my VM:

```
$ time bash -c :

real    0m0.002s
user    0m0.000s
sys 0m0.000s
$

```

Further supporting evidence that the new process does not actually run until the previous process is done can be seen in `strace` output:

```
strace -f -tt -o forever.strace bash -c ./forever.sh

```

In the output, we see the original process has PID 6929. We can see the `fork()` call (actually `clone()`), which returns a new PID of 6930. At this point there are 2 PIDs, but only 6929 is currently running:

```
6929  12:11:01.031398 clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7f2f83ac49d0) = 6930
6929  12:11:01.031484 rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
6929  12:11:01.031531 rt_sigprocmask(SIG_BLOCK, [CHLD], [], 8) = 0
6929  12:11:01.031577 rt_sigprocmask(SIG_BLOCK, [CHLD], [CHLD], 8) = 0
6929  12:11:01.031608 rt_sigprocmask(SIG_SETMASK, [CHLD], NULL, 8) = 0
6929  12:11:01.031636 rt_sigprocmask(SIG_BLOCK, [CHLD], [CHLD], 8) = 0
6929  12:11:01.031665 rt_sigprocmask(SIG_SETMASK, [CHLD], NULL, 8) = 0
6929  12:11:01.031692 rt_sigprocmask(SIG_BLOCK, [CHLD], [CHLD], 8) = 0
6929  12:11:01.031726 rt_sigprocmask(SIG_SETMASK, [CHLD], NULL, 8) = 0
6929  12:11:01.031757 rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0
6929  12:11:01.031803 rt_sigprocmask(SIG_BLOCK, NULL, [], 8) = 0
6929  12:11:01.031841 read(255, "", 4)  = 0
6929  12:11:01.031907 exit_group(0)     = ?
6930  12:11:01.032016 close(255)        = 0
6930  12:11:01.032052 rt_sigprocmask(SIG_SETMASK, [], NULL, 8) = 0

```

Full `strace` output here.

We can see that 6930 does not issue any system calls until 6929 is completely done. It is reasonable to assume that this means 6930 does not run at all until 6929 is done. The `perf` utility would be the ultimate way to prove this.

# Answer
> 26 votes
# Solution 1

### PHP, 32 chars

It sends the header and then it stops. After 3 seconds, the page gets reloaded.

**file a.php**

```
header("Refresh: 3; url=a.php");

```

This can be stopped by terminating the execution of the page before the headers are sent, or simply by killing the browser.

---

# Solution 2

### PHP, 2 pages

Let's consider the two files two different programs. The two files are in the same folder.

**file a.php**

```
header("Location:b.php");

```

**file b.php**

```
header("Location:a.php");

```

Terminating one of the pages before the headers are sent terminates the program (killing the browser works, too).

Here's the same program in

### ASP.NET

**file a.aspx**

```
Response.Redirect("b.aspx")

```

**file b.aspx**

```
Response.Redirect("a.aspx")

```

# Answer
> 19 votes
# sh

```
echo $PWD/$0 | at tomorrow

```

This will work on any Posix-compliant system.

To kill it, delete the file or use `atrm`.

# Answer
> 18 votes
# bash

```
exec "$0"

```

`exec` replaces the shell without creating a new process. This makes sure that there cannot be a second instance.

# Answer
> 15 votes
# Windows Task Scheduler (Native)

C++. A nightmare of COM programming. Meets all challenge requirements.

```
#define _CRT_SECURE_NO_WARNINGS
#include <windows.h>
#include <taskschd.h>
#include <comutil.h>

#pragma comment(lib, "taskschd.lib")
#pragma comment(lib, "comsuppw.lib")

static void timeplus (int seconds, char timestr[30]);

int main () {

    CoInitializeEx(NULL, COINIT_MULTITHREADED);
    CoInitializeSecurity(NULL, -1, NULL, NULL,
        RPC_C_AUTHN_LEVEL_PKT_PRIVACY,
        RPC_C_IMP_LEVEL_IMPERSONATE, NULL, 0, NULL);

    const char *name = "Restarter";

    char path[MAX_PATH + 1];
    GetModuleFileNameA(NULL, path, sizeof(path));
    path[sizeof(path) - 1] = 0; // workaround for xp

    ITaskService *taskman;
    CoCreateInstance(CLSID_TaskScheduler, NULL, CLSCTX_INPROC_SERVER,
        IID_ITaskService, (void **)&taskman);

    taskman->Connect(_variant_t(), _variant_t(), _variant_t(), _variant_t());

    ITaskFolder *root;
    taskman->GetFolder(_bstr_t("\\"), &root);

    // Delete the task.
    root->DeleteTask(_bstr_t(name), 0);

    // pause for 5 seconds to give user a chance to kill the cycle
    fprintf(stderr, "If you want to kill the program, close this window now.\n");
    Sleep(5000);
    fprintf(stderr, "Sorry, time's up, maybe next time.\n");

    // Create the task for 5 seconds from now.
    ITaskDefinition *task;
    taskman->NewTask(0, &task);

    IPrincipal *principal;
    task->get_Principal(&principal);
    principal->put_LogonType(TASK_LOGON_INTERACTIVE_TOKEN);

    ITaskSettings *settings;
    task->get_Settings(&settings);
    settings->put_StartWhenAvailable(VARIANT_TRUE);
    settings->put_DisallowStartIfOnBatteries(VARIANT_FALSE);
    settings->put_StopIfGoingOnBatteries(VARIANT_FALSE);

    ITriggerCollection *triggers;
    task->get_Triggers(&triggers);

    ITrigger *trigger;
    triggers->Create(TASK_TRIGGER_TIME, &trigger);

    char when[30];
    ITimeTrigger *trigger_time;
    trigger->QueryInterface(IID_ITimeTrigger, (void **)&trigger_time);
    trigger_time->put_Id(_bstr_t("TimeTrigger"));
    timeplus(10, when);
    trigger_time->put_StartBoundary(_bstr_t(when));
    timeplus(300, when);
    trigger_time->put_EndBoundary(_bstr_t(when));

    IActionCollection *actions;
    task->get_Actions(&actions);

    IAction *action;
    actions->Create(TASK_ACTION_EXEC, &action);

    IExecAction *action_exec;
    action->QueryInterface(IID_IExecAction, (void **)&action_exec);
    action_exec->put_Path(_bstr_t(path));

    IRegisteredTask *regtask;
    root->RegisterTaskDefinition(_bstr_t(name), task,
        TASK_CREATE_OR_UPDATE, _variant_t(), _variant_t(),
        TASK_LOGON_INTERACTIVE_TOKEN, _variant_t(""),
        &regtask);

    regtask->Release();
    action_exec->Release();
    actions->Release();
    trigger_time->Release();
    trigger->Release();
    triggers->Release();
    settings->Release();
    principal->Release();
    task->Release();
    root->Release();
    taskman->Release();
    CoUninitialize();

}

// outputs current utc time + given number of seconds as
// a string of the form YYYY-MM-DDTHH:MM:SSZ
static void timeplus (int seconds, char timestr[30]) {

    SYSTEMTIME when;
    FILETIME whenf;
    LARGE_INTEGER tempval;

    GetSystemTimeAsFileTime(&whenf);
    tempval.HighPart = whenf.dwHighDateTime;
    tempval.LowPart = whenf.dwLowDateTime;
    tempval.QuadPart += seconds * 10000000LL; // 100 nanosecond units
    whenf.dwHighDateTime = tempval.HighPart;
    whenf.dwLowDateTime = tempval.LowPart;
    FileTimeToSystemTime(&whenf, &when);

    sprintf(timestr, "%04hu-%02hu-%02huT%02hu:%02hu:%02huZ",
        when.wYear, when.wMonth, when.wDay,
        when.wHour, when.wMinute, when.wSecond);

}

```

Compile with MSVC (or MinGW GCC if you have all dependencies).

Program will start and register a one-time task with the Windows task scheduler to start itself 5 seconds later (Control Panel -\> Administrative Tools -\> Task Scheduler to view, task is named "Restarter"). Program will pause for 5 seconds to give you a chance to kill it before it creates the task.

Challenge Requirements:

* **Starts itself again when finishes.** Yes. Task is scheduled just prior to program exit.
* **No more than one instance of the program running at same time.** Yes. Program exits fully and does not run for 5 seconds. It is started by the scheduler.
* **You can ignore any instance that is manually started by user during your cycle.** Yes, as a side-effect of using a constant task name.
* **As long as it is guaranteed that it starts again.** Yes, provided that Task Scheduler is running (it is in a standard Windows configuration).
* **The only way to stop the cycle is to kill the process.** Yes, the process can be killed during the 5 second window while it is running. The program deletes the task prior to the 5 second delay, killing it at this time will not leave a stray task in the scheduler.
* **Your solution should not involve restarting of the environment** Yes.

By the way, if anybody ever wondered why Windows applications used to be so unstable (before the advent of .NET and C#), this is one reason why. The amount of error handling required (had I included it), resource management, and verbosity sets up very error-prone situations if a programmer is even the slightest bit lazy (the above code is extremely lazy).

A much easier and shorter alternative is to invoke schtasks.exe. I have submitted a version with that in a .BAT script as well.

# Answer
> 13 votes
# BBC BASIC - a tribute to Snow Patrol

Emulator at bbcbasic.co.uk

This one's a little different. It prints a verse of the song "Run" and plays an arpeggio of the chords so you can sing along. It was inspired by the fact that the command to execute (and therefore the last line of the program) is of course RUN.

All variables are cleared at the start of the program, so it takes the screen colour left behind by the previous iteration to decide what verse to print next.

```
    5 C=POINT(0,0) MOD 4
   10 COLOUR 129+C
   15 CLS
   20 RESTORE 110+C
   25 READ A$
   30 PRINT A$
   35 FORK = 1 TO 4
   40   RESTORE K+100
   45   READ P
   50   FORM= 1 TO 8
   55     SOUND 1,-15,P,7
   60     SOUND 1,-15,P-20,7
   65   NEXT
   70 NEXT
  101 DATA 100
  102 DATA 128
  103 DATA 136
  104 DATA 120
  110 DATA Light up light up - As if you have a choice - Even if you can not hear my voice - I'll be right beside you dear.
  111 DATA Louder louder - And we'll run for our lives - I can hardly speak - I understand - Why you can't raise your voice to say.
  112 DATA Slower Slower - We dont have time for that - All I want is to find an easier way - To get out of our little heads.
  113 DATA Have heart my dear - We're bound to be afraid - Even if its just for a few days - Makin' up for all of this mess.
  120 RUN

```

**OUTPUT (montage of 4 different screen shots)**

# Answer
> 11 votes
# HTML/JavaScript:

```
<form /><script>document.forms[0].submit()</script>

```

The code triggers the destruction of the page it is running on, then the re-creation of another instance of itself when the browser loads the page anew.

AFAIK, the only way out is to kill the tab the page is running in.

EDIT: as per popular request, a valid HTML5 code:

```
<!doctype html><meta charset=utf-8><title> </title><form></form>
<script>document.forms[0].submit()</script>

```

# Answer
> 10 votes
## C

This program acts like a lot of malware. Just before it closes, it creates a shell script in the /tmp directory. It forks to start the shell script, which lets the original program close and cancel the original PID. After a brief period of time (2 seconds) the shell script starts a new process with the program. For brevity, the program location is hard-wired as '/tmp/neverend/'.

```
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

void rebirth(){
    char t[] = "/tmp/pawnXXXXXX";
    char* pawnfile = mktemp(t);
    if(pawnfile){
        int fd = open(pawnfile, O_RDWR|O_CREAT);
        const char msg[]="sleep 2\n/tmp/neverend\n";
        if(fd>0){
            int n = write(fd, msg, sizeof(msg));
            close(fd);
            pid_t pid = fork();
            if(pid==0){
                char* args[3] = {"bash", pawnfile, NULL};
                execvp(args[0], args);
            }
        }
    }
}

int main(int argc, char* argv[]){
    printf("Starting %s\n", argv[0]);
    atexit(rebirth);
    printf("Exiting %s\n", argv[0]);
}

```

There is only ever one 'neverend' process running at a time. Each new process gets a new PID. The easiest way to kill this is to delete the executable. If you wanted to make it more malignant, you could copy both the executable and the script to make sure there are multiple copies on the program on disk at any time.

# Answer
> 10 votes
## Perl

```
`perl -e"kill 9,$$"|perl $0`

```

The script issues a system command to kill itself, and pipe the result into another instance of itself. The Perl interpreter is used to do the killing, for cross platform reasons.

Stop the madness by deleting the script.

# Answer
> 7 votes
# Atari 8-bit Basic

```
1L.:R.

```

Tokenizes to:

```
1 LIST : RUN

```

Internally it is clearing the internal structures, essentially wiping out the program, before running it again from the listing.

This is fundamentally different from:

```
1L.:G.1

```

Which tokenizes to:

```
1 LIST : GOTO 1

```

This is a basic infinite loop. When you run them, you see the difference in speed (first is slower).

# Answer
> 5 votes
On an IBM Mainframe running z/OS, you run a utility which copies a dataset (file) to another dataset (file). The input is the source of the JCL (Job Control Language) that you have submitted to cause it to run. The output is the Internal Reader (INTRDR). You will also need to ensure that your system does not allow the running of multiple identical jobnames. Good to use a job-class which only has one initiator (place where a JOB can run in batch).

There are no PIDs involved (in z/OS), so fails the challenge set.

You halt the process by draining and/or flushing. If something has gone wrong, by draining and/or flushing, swearing, kicking, attempting a warm-start and finally by a cold-start or hitting the Big Red Button (and shooting the programmer).

I may have exaggerated along the way, but don't try this at work...

Example using SORT. Details on the JOB card are very site-dependant. Site policy may either forbid or prevent the use of INTRDR. A specific class may be required to use the INTRDR. If your site policy forbids its use ***do not use it*** unless you want to take your belongings for a walk in a cardboard box.

Although there are good uses for the INTRDR, ***do not use it for this purpose***. You won't even have a chance to get your box.

```
//jobname JOB rest is to your site standards
//*
//STEP0100 EXEC PGM=SORT
//SYSOUT   DD SYSOUT=*
//SORTOUT  DD SYSOUT=(,INTRDR) minimum required, site may require more
//SYSIN    DD *
  OPTION COPY
//SORTIN   DD DISP=SHR,DSN=YOUR.LIBRARY.WITHJOB(JOBMEMBR)

```

Other utilities are available. A quick program would be easy to do as well, just read a file, write a file.

If you want an example of this going wrong, try: http://ibmmainframes.com/viewtopic.php?p=282414#282414

The traditional way to copy a dataset is to use the IBM utility IEBGENER, as ugoren alludes in their comment.

However, these days, many sites will have IEBGENER "aliased" to ICEGENER. ICEGENER will, if it can, use IBM's DFSORT (or its rival SyncSort) to do a copy, because the SORT products are much more hihgly optimised for IO than IEBGENER is.

I'm just cutting out the middle-man by using SORT.

If you work at an IBM Mainframe site, you know the format of the JOB card that you should use. The minimal JOB card is as I have shown, without the comment. The comment will be important, because you may be supposed to be supplying accounting information, for instance. The jobname will likely have a site-specific format.

Some sites ban, or prevent, the use of the INTRDR. Be aware.

Some sites allow multiple jobs with the same name to run at the same time. Be aware.

Although unless you are a System's Programmer you can't set up such a class, you should look for a class which allows only one initiator. With that, the process is fairly safe - but be absolutely sure about that the class is working as described. Test. Not with this job.

If you are a System's Programmer, you know not to do anything outside of your remit. 'nuff said.

With one job with the same name allowed at the same time and a single initiator, this will be a constant stream of job start/finish next job start/finish - until you fill the spool (another bad thing to do) with the output from thousands of jobs (or run out of job numbers). Watch a JES Console for warning messages.

Basically, don't do this. If you do do it, don't do it on a Production machine.

With a little brushing up, I'll consider another Answer for how to do it on another IBM Mainframe operating system, z/VSE... z/VSE uses JCL. z/OS uses JCL. They are different :-)

# Answer
> 5 votes
# Windows Task Scheduler (.BAT)

Windows batch script. Meets all challenge requirements.

As far as I can see this is the only Windows solution so far that meets all requirements and has no nonstandard dependencies (my other solution is similar but requires compilation).

```
@ECHO OFF
SETLOCAL

schtasks /Delete /TN RestarterCL /F

ECHO Close this window now to stop.
TIMEOUT /T 5

FOR /f "tokens=1-2 delims=: " %%a IN ("%TIME%") DO SET /A now=%%a*60+%%b
SET /A start=%now%+1
SET /A starth=100+(%start%/60)%%24
SET /A startm=100+%start%%%60
SET /A end=%now%+3
SET /A endh=100+(%end%/60)%%24
SET /A endm=100+%end%%%60

schtasks /Create /SC ONCE /TN RestarterCL /RI 1 /ST %starth:~1,2%:%startm:~1,2% /ET %endh:~1,2%:%endm:~1,2% /IT /Z /F /TR "%~dpnx0"

ENDLOCAL

```

Program behaves similarly to my C++/COM answer.

Program will start and register a one-time task with the Windows task scheduler to start itself up to 60 seconds later (Control Panel -\> Administrative Tools -\> Task Scheduler to view, task is named "Restarter"). Program will pause for 5 seconds to give you a chance to kill it before it creates the task.

Makes use of command line Task Scheduler interface `schtasks.exe`. Arithmetic in script is to compute time offsets while keeping the time valid and in HH:MM format.

Challenge Requirements:

* **Starts itself again when finishes.** Yes. Task is scheduled just prior to program exit.
* **No more than one instance of the program running at same time.** Yes. Program exits fully and does not run for ~60 seconds. It is started by the scheduler.
* **You can ignore any instance that is manually started by user during your cycle.** Yes, as a side-effect of using a constant task name.
* **As long as it is guaranteed that it starts again.** Yes, provided that Task Scheduler is running and schtasks.exe is present (both true in default Windows configurations).
* **The only way to stop the cycle is to kill the process.** Yes, the process can be killed during the 5 second window while it is running. The program deletes the task prior to the 5 second delay, killing it at this time will not leave a stray task in the scheduler.
* **Your solution should not involve restarting of the environment** Yes.

Note: Due to limited command line interface, restart time must be specified in minutes and *the task will not restart on laptops without the AC adapter plugged in* (sorry).

# Answer
> 4 votes
# Python (72 bytes)

```
import os
os.system('kill -9 %s && python %s' % (os.getpid(), __file__))

```

Could be make smaller I guess. First, by hardcoding the name of the file (instead of using `__file__`). But here, you can put this code in a file and run it, whatever its name is :)

# Answer
> 4 votes
## Unix shell

I haven't seen many solutions yet that rely on an unrelated program to restart it. But this is exactly what the `at(1)` utility was made for:

```
echo "/bin/sh $0"|at now + 1 minute

```

It's hard to actually catch the program running, since it only runs once per minute and exits so quickly. Fortunately the `atq(1)` utility will show you that it's still going:

```
$ atq
493     Fri Feb 21 18:08:00 2014 a breadbox
$ sleep 60
$ atq
494     Fri Feb 21 18:09:00 2014 a breadbox

```

And `atrm(1)` will allow you to break the cycle:

```
$ atq
495     Fri Feb 21 18:10:00 2014 a breadbox
$ atrm 495
$ atq

```

You can replace `1 minute` with `1 hour`, or `1 week`. Or give it `1461 days` to have a program that runs once every 4 years.

# Answer
> 2 votes
**PowerShell**

I am abusing (and possibly breaking) my own rule.

```
[System.Threading.Thread]::Sleep(-1)

```

It takes infinite amount of time to restart itself.
It can be killed by killing the host process.

Just wait and see ;)

# Answer
> 2 votes
# Visual Base 6 :)

```
Sub Main:Shell "cmd ping 1.1.1.1 -n 1 -w 500>nul&&"""&App.Path &"\"&App.EXEName& """":End Sub

```

To run, create a new project, add a module with this code, set the start-up object to "Sub Main", compile, and then run the executable.

---

## More readable version:

```
Sub Main()
    Call Shell("cmd ping 1.1.1.1 -n 1 -w 3000 > nul && """ & App.Path & "\" & App.EXEName & """")
End Sub

```

# Answer
> 2 votes
# Bash

```
echo -e "$(crontab -l)\n$(($(date "+%M")+1)) $(date '+%H %e %m * /repeat.sh')" | crontab -

```

Save this as repeat.sh in the / directory and give it execute permission. It can be killed by deleting the file

This works by putting an entry in the crontab to run it 1 minute later.

# Answer
> 2 votes
# JavaScript

Without "going to the network" when not necessary :-) JavaScript's event loop scheduling allows us to write programs that fulfill the given requirements very easily:

```
(function program() {
    // do what needs to be done
    setTimeout(program, 100);
})();

```

This "restarts" the `program` function at a 10-times-per-second pace. It is guaranteed by JavaScript's nature that only a single task will be running at the same time, and it does not "restart the environment" as in "reload the page".

# Answer
> 1 votes
# C + MPI Environment

mpifork.c:

```
#include <stdio.h>

main(int argc, char * argv[])
{
    srand(time(NULL));
    int host = rand()%(argc-1)+1;
    FILE * logFile = fopen("mpifork.log", "a");
    if(logFile == NULL){
        fprintf(stderr, "Error: failed to open log file\n");
    } else {
        fprintf(logfile, "Jumping to %s\n", argv[host]);

        char * args[argc+5];
        args[0] = "mpirun";
        args[1] = "-H";
        args[2] = argv[host];
        args[3] = argv[0];
        for(host = 0; host < argc-1; host++) args[host+4] = argv[host+1];
        args[argc+3] = NULL;

        execvp("mpirun", args);
        fprintf(stderr, "exec died\n");
        perror("execvp");
    }
}

```

You must have OpenMPI or some other MPI implementation installed. Compile with

```
mpicc -o mpifork mpifork.c

```

Now that I think about it, there's no reason you have to use mpicc - gcc or whatever compiler will work. You just have to have mpirun.

```
gcc -o mpifork mpifork.c

```

To run it, you should probably include the full path name, and include a list of hosts. For example, I added some entries in /etc/hosts that all pointed to localhost, and ran it like this:

```
/home/phil/mpifork localhost localhost1 localhost2 localhost3 localhost4

```

The executable must be in the same directory on any machine that you want to run this on.

---

Essentially, this takes a list of hosts provided on the command line, selects one of the hosts, and launches the executable on the target host with the same arguments. If everything goes perfectly, mpirun will call itself over and over on different machines (or the same machine if you only provide 'localhost'. The executable itself (mpifork) does terminate - after calling `execvp`, it is no longer executing on the first machine.

If you wanted to be evil, you could instead make this launch on *every* machine, by including the full list of hosts that is provided on the command line in `args`. That would re-spawn a copy of itself on every machine, over and over - a cluster forkbomb.

However, in this form, I'm pretty sure this satisfies the rules.

# Answer
> 1 votes
**HTML / JAVASCRIPT**

HTML FILE a.html

```
<script>window.location = "a.html"</script>

```

# Answer
> 1 votes
## **Bash**

Longer than it has to be, but I'm tired, and don't care :)

```
while true; do sleep 1; done; bash $0;

```

You said that it has to restart itself when it finishes, you didn't specifically say that it had to do so repeatedly, or indefinitely. Also, you said that it should never have two instances running at once... it never will. ;)

There are any great number of ways to do this. My personal favorite, would be to do something like send a packet somewhere distant, and then (via any number of methods), have the response trigger the process.

# Answer
> 1 votes
**Android:** An alarm will restart the Activity after 1 second

```
public class AutoRestart extends Activity
{

@Override
public void onCreate()
{
    finish();
}

@Override
public void onDestroy() {

    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(
            AlarmManager.ELAPSED_REALTIME,
            SystemClock.elapsedRealtime() + 1000,
            restartServicePendingIntent);

    super.onDestroy();
}

}

```

# Answer
> 0 votes
# x86 Assembly

Not entirely sure this fits your criteria as it doesn't spawn a new process, but here it is anyway.

The program will show a message box, allocate some memory, copy its own code section into the allocated memory, and then jump to that location starting the cycle over. It should run until malloc fails.

```
format PE GUI 4.0
entry a

include 'include/win32a.inc'

section '.text' code readable executable

    a:
        push    0
        push    _caption
        push    _message
        push    0
        call    [MessageBoxA]

        push    b-a
        call    [malloc]

        push    b-a
        push    a
        push    eax
        call    [memcpy]

        call    eax
    b:

section '.data' data readable writeable

    _caption db 'Code challenge',0
    _message db 'Hello World!',0

section '.idata' import data readable writeable

    library user,'USER32.DLL',\
        msvcrt,'msvcrt.dll'

    import user,\
        MessageBoxA,'MessageBoxA'

    import msvcrt,\
        malloc,'malloc',\
        memcpy,'memcpy'

```

Compiled with fasm.

# Answer
> 0 votes
# Linux upstart init

Given the strictest reading of the question, I think this is impossible. In essence it is asking for a program to spontaneously start with the help of no other running programs.

There are some `at` and `chron`-based answers, but with the strictest reading, `atd` and `anacron` are supplementary programs which are running all the time, so they may be disqualified.

A related approach, but a little lower level is to use Linux's `init`. As root, add this .conf file to `/etc/init/`:

```
description "forever"

start on runlevel [2345]
stop on runlevel [!2345]

respawn

exec sleep 10

```

Then have `init` re-read its .conf files:

```
sudo telinit 5

```

This will start a `sleep` process which will live for 10 seconds, then exit. `init` will then respawn the `sleep` once it detects the previous one has gone away.

Of course this is still using `init` as a supplementary program. You could argue that `init` is a logical extension of the kernel and will *always* be available in any Linux.

If this is not acceptable, then I guess the next lower-level thing to do would be to create a kernel module which respawns a userspace process (not sure how easy that is). Here it can be argued that the kernel is not a process, and therefore not a program (supplementary). On the other hand, the kernel is a program in its own right, from the point of the CPU.

# Answer
> -1 votes
# TI-BASIC: 5 characters

call it `prgmA`

```
:prgmA

```

---
Tags: popularity-contest
---


title: Infinite Boolean Matrix

text:
# Question
Title: Infinite Boolean Matrix
It's geeky to see a Boolean Matrix animation, but a live one would be better. Echoing only `1`s and `0`s create a program that creates an infinite loop of integer matrix.

* `1`s and `0`s are randomly echoed like an error.
*

# Answer
Like this?

# PHP, ~~28~~ 22

```
for(;;)echo rand(0,1);

```

---

For a better view:

```
<div style="width:800px;margin:0 auto;background-color:black;color:green;">
    <?php for(;;)echo rand(0,1); ?>
</div>

```
> 3 votes

# Answer
### Delphi XE3 (30 28)

```
while 0<1do write(Random(2))

```
> 2 votes

# Answer
## TI-BASIC, 46

A classic, in my opinion.

```
"101010101010101":While 1:Disp Ans,"0"+Ans:End

```
> 0 votes

# Answer
## Perl, 24

```
print-+-(rand>.5)while+1

```
> 0 votes

# Answer
**C# 112** \- **109 Thanks @masterX244**

```
using System;namespace N{class P{static void Main(string[]a){for(;;)Console.Write(new Random().Next(0,2));}}}

```

Without namespace, class name...

**45**

```
for(;;)Console.Write(new Random().Next(0,2));

```

**Uncompressed**

```
using System;namespace N{class P{
        static void Main(string[] a) {
            for (;;)
                Console.Write(new Random().Next(0, 2));
        }
    }
}

```
> 0 votes

---
Tags: code-golf
---


title: Make a golfing language

text:
# Question
Title: Make a golfing language
In this challenge, you get to create a language. Although you have to provide code in other languages, you will only be rated based on the language. Here are the requirements.

1. You must invent a programming language that is Turing complete.
2. You will choose a real (as in existed before this question did) language. It must be a different paradigm then the made up language.
3. You will write a boot strapping compiler. This means you write a program in your new language, that will take code in your new language, and translate it to code in your real language.
4. So people can run it initially, you will provide an interpreter (or compiler) in a real language (which may or may not be written the real language you choose above) to run programs in the new language. This does not need to be golfed.

Note: Your language can't have builtin functions for generating code in the real language. This basically means that if the real language were proprietary, your language wouldn't violate its copyright by making it to easy to generate its code.

Scoring:

Your score is the size of your compiler. Your will find your programs' sizes using `roundup(s*log_2(a))` where s is the number of characters in your program and a is the number of available characters in your language (meaning huge penalties if you use Chinese characters or something.)

Tip: String characters count too, so if you are looking to really shrink how many characters are available, you will need to find a way to represent strings with few characters.

Smallest score wins!

So in summary, you invent a turing-complete language X. Then you implement an interpreter or compiler for it in Y. Finally, you implement a compiler for X in X itself. (Based on a comment from Victor.)

# Answer
## Brainfuckoff -\> Javascript, 527 characters, 3463 points

My language, Brainfuckoff is a brainfuck-derived language with the following changes:

* It has a new instruction `*` which sends everything in input to the output, until the end-of-input is reached.
* It has a new instruction `^` which sends everything following this and before the following backtick to the output.
* It takes a line of the input at a single shot in the start of the program, consuming each char with the `,` instruction.

So, here is a partially-golfed javascript compiler for my language:

```
function bfg(j){
  w=String.fromCharCode;
  r='(function(n){m=[];p=0;c=0;t=n.substring(0,0);';
  for(x=0;x<j.length;x++){
    q=j.charCodeAt(x);
    if(q==91)r+='while(~~m[p]){';
    if(q==93)r+='}';
    if(q==62)r+='p++;';
    if(q==60)r+='p--;';
    if(q==43)r+='m[p]=1+~~m[p];';
    if(q==45)r+='m[p]=-1+~~m[p];';
    if(q==46)r+='t+=String.fromCharCode(~~m[p]);';
    if(q==44)r+='if(c<n.length)m[p]=n.charAt(c++);';
    if(q==94){z=j.indexOf(w(96),x+1);r+='t+='+w(34)+j.substring(x+1,z)+w(34)+';';x=z}
    if(q==42)r+='t+=n.substring(c);c=n.length;'
  }
  return r+'return t})'
}

```

Here is a brainfuck Hello World program:

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

```

Compiling it:

```
program = '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.';
jsprogram = bfg(program);
alert(jsprogram);

```

The output:

```
 (function(n){m=[];p=0;c=0;t=n.substring(0,0);m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];while(~~m[p]){p++;m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];while(~~m[p]){p++;m[p]=1+~~m[p];m[p]=1+~~m[p];p++;m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];p++;m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];p++;m[p]=1+~~m[p];p--;p--;p--;p--;m[p]=-1+~~m[p];}p++;m[p]=1+~~m[p];p++;m[p]=1+~~m[p];p++;m[p]=-1+~~m[p];p++;p++;m[p]=1+~~m[p];while(~~m[p]){p--;}p--;m[p]=-1+~~m[p];}p++;p++;t+=String.fromCharCode(~~m[p]);p++;m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];t+=String.fromCharCode(~~m[p]);m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];t+=String.fromCharCode(~~m[p]);t+=String.fromCharCode(~~m[p]);m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];t+=String.fromCharCode(~~m[p]);p++;p++;t+=String.fromCharCode(~~m[p]);p--;m[p]=-1+~~m[p];t+=String.fromCharCode(~~m[p]);p--;t+=String.fromCharCode(~~m[p]);m[p]=1+~~m[p];m[p]=1+~~m[p];m[p]=1+~~m[p];t+=String.fromCharCode(~~m[p]);m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];t+=String.fromCharCode(~~m[p]);m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];m[p]=-1+~~m[p];t+=String.fromCharCode(~~m[p]);p++;p++;m[p]=1+~~m[p];t+=String.fromCharCode(~~m[p]);p++;m[p]=1+~~m[p];m[p]=1+~~m[p];t+=String.fromCharCode(~~m[p]);return t})

```

Running that:

```
program = '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.';
input = '';
jsprogram = bfg(program);
alert(eval(jsprogram)(input));

```

The output:

```
Hello World!

```

This other brainfuckoff's Hello World is simpler:

```
program = '^Hello World!`'
input = '';
jsprogram = bfg(program);
alert(eval(jsprogram)(input));

```

The output:

```
Hello World!

```

Great, now a compiler of brainfuckoff to javascript written in brainfuckoff (527 characters):

```
^(function(j){w=String.fromCharCode;r='(function(n){m=[];p=0;c=0;t=n.substring(0,0);';for(x=0;x<j.length;x++){q=j.charCodeAt(x);if(q==91)r+='while(~~m[p]){';if(q==93)r+='}';if(q==62)r+='p++;';if(q==60)r+='p--;';if(q==43)r+='m[p]=1+~~m[p];';if(q==45)r+='m[p]=-1+~~m[p];';if(q==46)r+='t+=String.fromCharCode(~~m[p]);'; if(q==44)r+='if(c<n.length)m[p]=n.charAt(c++);';if(q==94){z=j.indexOf(w(96),x+1);r+='t+='+w(34)+j.substring(x+1,z)+w(34)+';';x=z}if(q==42)r+='t+=n.substring(c);c=n.length;'}return eval(r+'return t})')})('`*^')`

```

Compiling the compiler:

```
program = "^(function(j){w=String.fromCharCode;r='(function(n){m=[];p=0;c=0;t=n.substring(0,0);';for(x=0;x<j.length;x++){q=j.charCodeAt(x);if(q==91)r+='while(~~m[p]){';if(q==93)r+='}';if(q==62)r+='p++;';if(q==60)r+='p--;';if(q==43)r+='m[p]=1+~~m[p];';if(q==45)r+='m[p]=-1+~~m[p];';if(q==46)r+='t+=String.fromCharCode(~~m[p]);'; if(q==44)r+='if(c<n.length)m[p]=n.charAt(c++);';if(q==94){z=j.indexOf(w(96),x+1);r+='t+='+w(34)+j.substring(x+1,z)+w(34)+';';x=z}if(q==42)r+='t+=n.substring(c);c=n.length;'}return eval(r+'return t})')})('`*^')`";
jsprogram = bfg(program);
alert(jsprogram);

```

The compiled compiler:

```
(function(n){m=[];p=0;c=0;t=n.substring(0,0);t+="(function(j){w=String.fromCharCode;r='(function(n){m=[];p=0;c=0;t=n.substring(0,0);';for(x=0;x<j.length;x++){q=j.charCodeAt(x);if(q==91)r+='while(~~m[p]){';if(q==93)r+='}';if(q==62)r+='p++;';if(q==60)r+='p--;';if(q==43)r+='m[p]=1+~~m[p];';if(q==45)r+='m[p]=-1+~~m[p];';if(q==46)r+='t+=String.fromCharCode(~~m[p]);'; if(q==44)r+='if(c<n.length)m[p]=n.charAt(c++);';if(q==94){z=j.indexOf(w(96),x+1);r+='t+='+w(34)+j.substring(x+1,z)+w(34)+';';x=z}if(q==42)r+='t+=n.substring(c);c=n.length;'}return eval(r+'return t})')})('";t+=n.substring(c);c=n.length;t+="')";return t})

```

Running the compiled compiler to compile the first Hello World:

```
program1 = "^(function(j){w=String.fromCharCode;r='(function(n){m=[];p=0;c=0;t=n.substring(0,0);';for(x=0;x<j.length;x++){q=j.charCodeAt(x);if(q==91)r+='while(~~m[p]){';if(q==93)r+='}';if(q==62)r+='p++;';if(q==60)r+='p--;';if(q==43)r+='m[p]=1+~~m[p];';if(q==45)r+='m[p]=-1+~~m[p];';if(q==46)r+='t+=String.fromCharCode(~~m[p]);'; if(q==44)r+='if(c<n.length)m[p]=n.charAt(c++);';if(q==94){z=j.indexOf(w(96),x+1);r+='t+='+w(34)+j.substring(x+1,z)+w(34)+';';x=z}if(q==42)r+='t+=n.substring(c);c=n.length;'}return eval(r+'return t})')})('`*^')`";
jsprogram1 = bfg(program1);
input1 = '++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.'
jsprogram2 = eval(jsprogram1)(input1);
input2 = '';
alert(eval(jsprogram2)(input2));

```

The output:

```
Hello World!

```

Calculating the score:

```
roundup(527 * log_2(asciiCharOf('~') - asciiCharOf(' ') + 1))
roundup(527 * log_2(126 - 32 + 1))
roundup(527 * log_2(95))
roundup(527 * 6.5698556083309478416638388523962)
roundup(3462.3139055904095125568430752128)
3463

```

Note: There are indeed some ways to reduce the size of the interpreter in maybe ~20%. But this was already hard enough to do for me.
> 9 votes

# Answer
## Score = (Number too long for an SE post * log\_2(1)) = 0

Given how the score is weighted by the number of characters available in the language, the less the better:

**1.)** My language (X) is called Compressed Unary. It is similar to Unary in that it only has one available character in the language. Unlike Unary, it uses the number "1" instead of "0". It improves on Unary by assigning the operators in a different bit order, with lower values assigned to operations that occur more often. It is proven to be Turing complete in that it can be trivially converted to Brainfuck.

The code is a string of 1s, and the length of the code determines the logic (see the description of Unary from the link above for more details. The encoding is as follows:

```
Brainfuck   Binary
+           (1000)
-           (1001)
>           (1010)
<           (1011)
.           (1100)
,           (1101)
[           (1110)
]           (1111)

```

All the binary is combined from left to right and the resulting number is how many "1"s should be in the source code. This should yield much smaller code that Unary, but will absolutely suck as a golfing language. Much better for code bowling (see the compiler below and you'll see why).

**2.)** I chose C#. It was easy, I could port an existing BF implementation (props to the original author), and given that log\_2(1) is zero, the length of the code doesn't have any effect my score.

**3.)** The source code is too long to include here (stupid 30k character limit), in fact the number is too long to post here (it is 123411 characters in hex notation). The following link will give you the number in hex. You can create the bootstrap compiler simply by typing that many ones in a text file. Like I said, this completely sucks as a golfing language. It's much worse than C# for golfing.

**4.)** Once you type out the source code (I'd include a download link, but it would take *way too long* even on a fast fiber connection), you can run it through the following interpreter:

```
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;

namespace CompressedUnary
{
    class Program
    {
        static void Main(string[] args)
        {
            BigInteger code = new BigInteger(0);
            int next = 0;

            try
            {
                using (FileStream source = new FileStream(args[0], FileMode.Open, FileAccess.Read))
                {
                    next = source.ReadByte();
                    while (next != -1)
                    {
                        if (next != 49)
                        {
                            System.Console.WriteLine("Syntax error.");
                            break;
                        }
                        code += 1;
                        next = source.ReadByte();
                    }
                }
            }
            catch (FileNotFoundException oops)
            {
                Console.WriteLine(oops.Message);
            }

            if (next == -1)
            {
                string processed = PreProcess(code);
                Interpreter runner = new Interpreter(Console.OpenStandardInput(), Console.OpenStandardOutput());
                runner.Run(processed);
            }
            Console.WriteLine("Done");
        }

        static string PreProcess(BigInteger input)
        {
            StringBuilder output = new StringBuilder("");
            BigInteger current;

            while (input > 0)
            {
                BigInteger.DivRem(input, 16, out current);
                switch ((int)current)
                {
                    case 0:
                        output.Append("+");
                        break;
                    case 1:
                        output.Append("-");
                        break;
                    case 2:
                        output.Append(">");
                        break;
                    case 3:
                        output.Append("<");
                        break;
                    case 4:
                        output.Append(".");
                        break;
                    case 5:
                        output.Append(",");
                        break;
                    case 6:
                        output.Append("[");
                        break;
                    case 7:
                        output.Append("]");
                        break;
                }
            }
            return output.ToString();
        }

        enum ILCode : byte
        {
            NextCell = (byte)'>',
            LastCell = (byte)'<',
            Increment = (byte)'+',
            Decrement = (byte)'-',
            Output = (byte)'.',
            Input = (byte)',',
            BeginLoop = (byte)'[',
            EndLoop = (byte)']'
        }

        class Machine
        {
            public int pointer = 0;
            private int cell = 0;
            private readonly byte[] cells;
            private readonly Stack<int> stack = new Stack<int>();

            public Machine(int memory)
            {
                cells = new byte[memory];
            }

            public byte CurrentCell
            {
                get { return cells[cell]; }
                set { cells[cell] = value; }
            }

            public void Increment()
            {
                if (CurrentCell == 255)
                    CurrentCell = 0;
                else
                    CurrentCell++;
                pointer++;
            }

            public void Decrement()
            {
                if (CurrentCell == 0)
                    CurrentCell = 255;
                else
                    CurrentCell--;
                pointer++;
            }

            public void NextCell()
            {
                cell++;
                pointer++;
            }

            public void LastCell()
            {
                cell--;
                pointer++;
            }

            public void BeginLoop()
            {
                stack.Push(pointer);
                pointer++;
            }

            public void EndLoop()
            {
                if (CurrentCell == 0)
                    pointer++;
                else
                    pointer = stack.Pop();
            }
        }

        class Interpreter
        {
            private readonly Stream output;
            private readonly StreamReader reader;
            private readonly Dictionary<byte, Action> actions;
            private readonly Machine machine;

            public Interpreter(Stream ioin, Stream ioout, int memorySize = 30000)
            {
                output = ioout;
                reader = new StreamReader(ioin);
                machine = new Machine(memorySize);
                actions = new Dictionary<byte, Action>
                    {
                        {(byte) ILCode.BeginLoop, machine.BeginLoop},
                        {(byte) ILCode.EndLoop, machine.EndLoop},
                        {(byte) ILCode.Increment, machine.Increment},
                        {(byte) ILCode.Decrement, machine.Decrement},
                        {(byte) ILCode.NextCell, machine.NextCell},
                        {(byte) ILCode.LastCell, machine.LastCell},
                        {(byte) ILCode.Input, InputCurrentByte},
                        {(byte) ILCode.Output, OutputCurrentByte},
                    };
            }

            public void Run(string program)
            {
                byte[] instructions = program.Select(c => (byte)c).Where(b => actions.ContainsKey(b)).ToArray();
                while (machine.pointer < instructions.Length)
                {
                    Action action = actions[instructions[machine.pointer]];
                    action.Invoke();
                }
                byte[] newLine = Environment.NewLine.Select(c => (byte)c).ToArray();
                output.Write(newLine, 0, newLine.Length);
            }

            private void InputCurrentByte()
            {
                byte next = (byte)reader.Read();
                machine.CurrentCell = next;
                machine.pointer++;
            }

            private void OutputCurrentByte()
            {
                output.WriteByte(machine.CurrentCell);
                machine.pointer++;
            }
        }
    }
}

```

**FORE!**
> 5 votes

---
Tags: code-golf, code-challenge
---


# Question
Title: Strange ways to keep an endless high CPU usage
There are some ways which cause an endless high CPU usage such as catching recursion exception. e.g. the following script in Python causes that problem:

```
def main():
    try:
        main()
    except:
        main()

main()

```

This is an obvious and simple example, but there might be some strange ways to arise such problems.

# Answer
## JavaScript

Even JavaScript beginners should understand the code below!

```
// JavaScript for Beginners
// Variables, for loops

// The line below will set a global variable called "x" to 90
// Note: never use this style of code. It is evil!
х = 90;

// The line below will set a local variable called "x" to 90
var x = 90;

for (var х=0; х<10; x++) {
  console.log('JS for beginners: this is iteration #' + х);
}

```

**Warning**

> It produces an infinite loop
> Don't run it in your browser unless you know how to kill the tab/process or restart the machine :)

How does it work?

> There are two kinds of variable names in the code:
> 1. the normal 'x' which can be found on the keyboard
> 2. a cyrillic 'х': http://en.wikipedia.org/wiki/%D0%A5
> 8 votes

# Answer
# Java

This may look like a silly but harmless program that should finish in an instant. However, appearances can be deceiving...

```
public class Cpu {
    public static void main(final String... args) {
        // let's print a bunch of empty lines
        int i = 0; // the loop counter
        while (i < 10) {
            // the unicode representation of a line feed is \u000A  /*/// loop start
            char c = 0x000A;
            System.out.print(c); // print the line feed
            i++; // increment and repeat  /*/// loop end
        }
    }
}

```

And another solution:

```
public class Cpu2 {
    public static void main(final String... args) {
        // now let's add the numbers from 0 to 255
        int sum = 0;
        for (byte i = 0; i < 255; i++) {
            sum += i;
        }
        System.out.println("The sum is: " + sum);
    }
}

```

Spoilers:

> 1. The "\u000A" inside the comment generates an **actual** line break in the source code, so all the instructions in the loop are commented out. Without the "\u000A" (or even without the backslash before "u"), the loop would just run 10 times and finish.
> 2. The 'byte' type is signed, so 'i' never reaches 255, but wraps around from 127 to -128
> 3 votes

# Answer
# JavaScript

```
var i = 0;
while (i < 10) {
  console.log("Hi #" + i + "!");
  // Let the user know we said hi and now     \
  // continue the loop                        \
  i++;
}

```

This looks rather harmless... (run at your own risk)

Spoiler:

> Look at the commenting style. It will never get to 10 because of the escaped line breaks, which hold in comments. The problem would disappear completely if there was a line break after the final comment.
> 3 votes

# Answer
It's the same solution I used in this question, but this time it's 100% fair.

# Bash, 12 bytes

```
:(){ :|:&};:

```

As found on Wikipedia.

**WARNING: harmful code, don't run it on your computer!**

It produces an endless 100% CPU load (until system crashes, but there's nowhere stated that it mustn't be harmful!);
> 2 votes

# Answer
# C++

Try calculating the first 100 weird numbers by brute-force:

```
#include<iostream>
#include<vector>
using namespace std;

vector<int> divisors(int i) {

    vector<int> divs;
    for(int k = 1; k < i; k++)
        if(i%k==0)
            divs.push_back(k);
    return divs;
}

bool u(vector<int>::const_iterator vi, vector<int>::const_iterator end, int s) {

    if(s == 0) return 0;
    if(vi == end) return 1;
    return u(vi + 1, end, s - *vi) & u(vi + 1, end, s);
}

bool t(vector<int>&d, int i) {

    bool b = u(d.begin(), d.end(), i);
    if(b) cout<< i << endl;
    return b;
}

int main() {

    vector<int> divs;
    int n;
    cin>>n;

    for(int i = 2, j = 0; j < n; i++) {
        divs = divisors(i);

        int sum_divs = 0;
        for(int k = 0; k < divs.size(); k++)
            sum_divs += divs[k];

        if(sum_divs > i)
            if(t(divs, i))
                j++;
    }
}

```

I think you will find your CPU usage will spike, although it may not crash your computer.
> 2 votes

# Answer
# Vodoo in java

```
public class W
{
    public static void main(String[]a)
    {
        int o=0,о=o;
        while(o<a.length)
        {
            System.out.println(a[o]);
            о++;
        }
    }
}

```

> cyrillic letters work in java, too :P that o=o isnt a o=o but 2 variables
> 1 votes

# Answer
# EcmaScript 6:

```
z=z=>{while(1)z()};_=i=>(i+=1,i-=1,i++,i--,--i,++i,i<<=2,i>>=2,i+=0|Math.round(1+Math.random())&1|0,z(x=>setInterval(x=>z(x=>new Worker('data:text/javascript,'+_.toSource()),5))));setInterval(x=>z(x=>_(...Array(i=9e3).map((x,z)=>z*3/2*2/4*4e2>>2<<2))),5)

```

This doesn't always use 100% of the CPU, but at least with Firefox it has the added bonus that Firefox keeps using up more and more memory, the whole interface locks up and the only way to stop it is to kill Firefox.
> 0 votes

# Answer
**BASH**

This is a simple bash script and i'm sure it will be down voted for not being "strange" enough, but i found this fun. It's not elegant and it's not some fancy way to do it but it does the job in a fun way. Plus i have not seen anyone attempt to eat CPU usage by hashing out the sha256sum recently. This pipes its output to the file "~/junk" and thus eats up diskspace too (just for the giggles). It spawns itself over and over again. crashed my machine shortly after starting it.

***THIS CODE IS DANGEROUS***

Enjoy!

Name it songthatneverends.sh

```
#!/bin/bash
x=1
exec 1> ~/junk 2>&1

        while [ $x -le 1 ]
                do
                        song="This is the song that never ends, yes it goes on and on my friend. Some people started singing it, not knowing what it was, and they'll continue singing it forever just because..."
                        echo $song
                        $x"_"$song | sha256sum
                        x= $(( $x - 1 ))
                        sh songthatneverends.sh
                done

```
> 0 votes

# Answer
**Ruby**

Evals itself until it can't, then starts over.

```
begin;eval `cat spin.rb`;rescue;`ruby spin.rb`;end

```

*Must be in a file named "spin.rb"*
> 0 votes

# Answer
# CMD 12 bytes (counting the important newline):

```
:a
a&goto a

```

This works because it has to look for the command `a`, and it has to spend time to produce an error message.

Then it goes to `a:` and repeats!

The newline is IMPORTANT and counts as 2 bytes under windows.

Since this is a Windows solution, the byte count has to (unfortunately) be made in Windows' way.

To stop it, close the window or press +c
> 0 votes

# Answer
# DOS Batch

```
%0|%0

```

This is actually another way to code the fork bomb.

# Equivalent in POSIX

```
$0|$0

```

Spoiler:

> It runs the script itself, and attempts to pipe the output to the same script. Another way to write an endless loop of this is simply `%0` or `$0`. The difference is that it doesn't nearly as much strain the CPU because it is simple recursion.
> 0 votes

# Answer
# Javascript:

```
(function(a){a=arguments.callee;try{a();}catch(e){a();}})();

```

How does this work?

This runs itself until it reaches the maximum recursion level. When this happens, the last function exits and runs itself again!

On my CPU, I got all 4 cores around 10-40%, using Opera 12.16.

To use it, simply press `F12` on your keyboard, paste this in the console and done!

To stop, close the console.
> 0 votes

# Answer
## C#

```
using System;
using System.Threading;

// without a program, we wouldn't have much, would we?
class Program
{
    // somehow, houdini always gets out of his locks
    static Guid houdini = Guid.NewGuid();

    // this is the main part
    static void Main()
    {
        // let's make some threads
        Thread[] threads = new Thread[20];
        // all of them
        for (int i = 0; i < threads.Length; i++)
        {
            // new threads are always better than stale ones
            threads[i] = new Thread(DoThing);
            // started threads are better than stopped ones
            threads[i].Start();
        }
    }

    // this does the thing
    static void DoThing()
    {
        // this does it lots of times
        while (true)
        {
            // this lock appears to limit CPU usage
            lock ((object)houdini)
            {
                // this line indicates I cannot think of anything clever to put here
                Thread.SpinWait(1000000);
            }
        }
    }
}

```

**Spoiler:**

> `lock ((object)houdini)` creates a new reference to houdini and locks on that, so each lock gets a different reference, and the locks do not affect the other threads. This is why you should never use a value type for locking.
> 0 votes

---
Tags: popularity-contest
---