title: DNA Encode a String

text:
# Question
Title: DNA Encode a String
## Challenge

You must write an encoder (and a separate decoder) which takes a string as input and outputs the string encoded in the *style* of a strand of DNA.

## DNA

DNA is made up of four types of nucleotide:

* Adenine (A)
* Thymine (T)
* Cytosine (C)
* Guanine (G)

Adenine and thymine pair up together to make `AT` or `TA`. Similarly, cytosine and guanine pair up together to make `CG` or `GC`.

Let's call these pairs *units*. This means that your encoded string is only allowed to contain the four units AT, TA, CG and GC.

This means that:

```
ATTAGACG

```

Would be invalid because it contains the unit GA, which is impossible.

Similarly,

```
TAGCGCCGATA

```

Is invalid because the final A does not have a thymine to pair up with.

## Example

You must encode the following example text and use its encoded length as part of your score:

> I have a friend who's an artist and has sometimes taken a view which I don't agree with very well. He'll hold up a flower and say "look how beautiful it is," and I'll agree. Then he says "I as an artist can see how beautiful this is but you as a scientist take this all apart and it becomes a dull thing," and I think that he's kind of nutty. First of all, the beauty that he sees is available to other people and to me too, I believe. Although I may not be quite as refined aesthetically as he is ... I can appreciate the beauty of a flower. At the same time, I see much more about the flower than he sees. I could imagine the cells in there, the complicated actions inside, which also have a beauty. I mean it's not just beauty at this dimension, at one centimeter; there's also beauty at smaller dimensions, the inner structure, also the processes. The fact that the colors in the flower evolved in order to attract insects to pollinate it is interesting; it means that insects can see the color. It adds a question: does this aesthetic sense also exist in the lower forms? Why is it aesthetic? All kinds of interesting questions which the science knowledge only adds to the excitement, the mystery and the awe of a flower. It only adds. I don't understand how it subtracts.

## Bounty

If you answer this challenge in the language DNA#, I will offer a 100 to 200 rep bounty.

## Rules

Your encoder and decoder programs *must* work for any string supplied. Therefore, your encoder must produce a genuine encoding and your decoder should not simply hardcode the example text.

You must support all printable ASCII characters:

```
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

```

If you can support more characters, that is acceptable.

## Scoring

Your score is how long in characters (not units) the encoded version of the above text plus the length in bytes of your decoder and your encoder.

## Winning

The program with the lowest score wins.

# Answer
> 6 votes
## Pyth, 5152 + 21 + 23 = 5196 bytes

### Encoder

```
sm@c4s_B"ATCG"djC.ZQ4

```

Try it here

### Decoder

```
.ZCimxc4s_B"ATCG"dcQ2 4

```

Try it here (Input too long to link, put output of first in quotes in the input box)

Compresses the input and converts it from base 256 into an integer. Then converts into a sequence of base 4 numbers and chooses from `['AT', 'CG', 'GC', 'TA']`

# Answer
> 5 votes
**DNA#** **: 10216 + 852 + 384 = 11452 bytes**

This is not exactly tested, as I haven't gotten a hold of a working interpreter... There are probably mistakes

I use a simple brute force approach so far where each character is read in, then broken up into 2 bit blocks with `AT = 00; TA = 01; CG = 10; GC = 11`. The sample text is 1277 ASCII characters, and it takes 4 codes (2 bits) to encode each 8 bit char: 1277 * 4 * 2 = **10216 bytes**

# Encoder

**852 bytes - line form**

```
GCGCGCTAATATATTAATTAATTAATTAATTAATTAATTAATTATACGCGCGATATTAATATGCATGCCGCGGCTACGATATGCCGCGATATATTAATTAATTAATTAATTAATTAATTAATTATACGCGCGATTAATATATTAATTAATTAATTAATTAATTAATTAATTAATTATACGCGCGATTAATTAATTAATGCATGCGCTAATATATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATATATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATGCATGCATCGGCCGGCTAATATATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATCGATATATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATGCATGCATCGGCCGGCTAATATATTAATTAATTAATTAATATATCGATCGATCGATCGATGCATGCATCGGCCGATATGCATATATGCATATGCATGCATGCATCGGCTAATTAATATTAATATGCATGCCGCGCGATATGCCGCGTACGATGCCGCGATGCATGCTATAATATATATCGCGATATATATGCTAATCGGCCGATTAATTAATTAATTAATGCCGATATATCGCGATATTAATATGCATGCCGCGATATGCTAATCGGCCGATATGCTAATCGGCCGGCCGATGCATGCGCCGATGCATGCGCGCGCCG

```

**224 bytes - symbol form:**

```
,[>++++++++*=X>:=<<X[/=<X>++++++++*=X+>+++++++++*=X+++<<[>+++++++++++++++++++>-------------------<<-][>----------------->+++++++++++++++++<<-][>++++>----<<-]>.>.<<<-[+>:=<<X/=<X*=<X<<-=>>X>>[-]++++</=>X>:=<<X>[-]>[-]]<<]<<,]

```

and with variable names and some messy comments...

```
DNA# dna encoder

a = input              //get first char
[                      //for each char
    b = 64             //divisor to get first 2 bits
    c = a              //initialize as a
    [                  //while c != 0
        c /= b
        d = 65         //first print char
        e = 84         //second print char
        c              //select c
        [              //if c > 0 (3,2,1)
            d + 19
            e - 19
            c - 1
        ]
        [              //if c > 1 (3,2)
            d - 17
            e + 17
            c - 1
        ]
        [              //if c > 2 (3)
            d + 4
            e - 4
            c - 1
        ]              //c is now 0 (hopefully)
        print d
        print e
        b - 1
        [              //if b is not 1 (last 2 bits)
            b + 1      //reset b
            c = a      //trash top 2 bits (modulus algorithm)
            c /= b
            c *= b
            a -= c
            c = 0      //reset c
            c + 4
            b /= c     //b >> 2
            c = a      //copy a again for next 2 bits
            d = 0      //get a 0 value so we don't loop
        ]
        c              //select c (0 if done with char: exit loop and get next char)
    ]
    a = input          //get next char
]
```

# Decoder

**384 bytes - line form**

```
GCGCGCGCGCTAATATATATATTAATTAATTAATTAGCTAATATATTAATTAATTAATTAATTAATTAATTAATTAATTATACGCGCGATTAATTAATTAATGCATGCATGCTATAATATATATATATCGCGGCTAATATATTAATGCATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAATTAGCCGGCTAATATATTAATGCATCGATCGATCGATCGATCGATCGGCCGGCTAATATATTAATGCATTAATTAATTAATTAGCCGATTAATTAATTAATTAATATTACGATGCCGCGATGCGCGCGCGCATATATATATCGGCCGATGCGCATATGCGCCG

```

**99 bytes - symbol form**

```
,,[>>++++[>+++++++++*=X+++<<<-=>>>X[>+<+++++++++++++++++++][>+<------][>+<++++]++++>*=<X<,,>>-]<.<]

```

var names...

```
DNA# dna decoder

,
,                  /* read second char into a*/
[                  /* for each set of 4 pairs */
    c = 4          /* loop iterator */
    [
        a - 84     /* if pair was AT (65,84): don't increment b */
        [
            b + 1
            a + 19 /* if pair was TA (84,65): increment b once */
        ]
        [
            b + 1
            a - 6  /* if pair was CG (67,71): increment b twice */
        ]
        [
            b + 1
            a + 4  /* if pair was GC (71,67): increment b three times */
        ]
        a = 4
        b *= a     /* shift b up 2 bits */
        a,,        /* get next char (skip one) */
        c - 1      /* decrement loop iterator: exit loop on 0 */
    ]
    b
    print          /* output b in ASCII */
    a              /* select a (next char) */
]                  /* end if next char is 0 (null terminated string) */
```

If anyone finds a mistake or is able to run the web interpreter feel free to tell me how wrong I am :P

# Answer
> 3 votes
## Python 2, ~~10216~~ 5152 + ~~72~~ 98 + ~~122~~ ~~110~~ 139 = ~~10410~~ ~~10398~~ 5389

### Encoder:

```
import zlib
lambda s:''.join('ACGTTGCA'[ord(c)>>b&3::4]for c in zlib.compress(s)for b in(0,2,4,6))

```

### Decoder:

```
import zlib
lambda s:zlib.decompress(''.join(chr(int(''.join([str('ACGT'.index(s[i+j]))for j in(6,4,2,0)]),4))for i in xrange(0,len(s),8)))

```

# Answer
> 3 votes
## JavaScript (ES6), ~~10216~~ 8520 + ~~85~~ 129 + ~~97~~ 147 = ~~10398~~ 8796

### Encoder:

```
s=>s.replace(/..?.?/g,b=>"9876543210".replace(/./g,b=>'ACGT'[b=r>>b*2&3]+'TGCA'[b],r=0,[...b].map(c=>r=r*96+127-c.charCodeAt())))

```

### Decoder:

```
s=>s.replace(/../g,c=>'ACGT'.search(c[0])).replace(/.{10}/g,b=>String.fromCharCode(...[9216,96,1].map(n=>parseInt(b,4)/n%96^127).filter(n=>n^127)))

```

Works by packing up to three printable ASCII characters into 20 nucleotides, thus saving 16.6% on average. The characters are mapped from 95 to 1 to shorten the decoder, as it can then use `^127` to floor the division and restore the character code. Excess nucleotides get decoded into 127 which needs to be skipped. The encoder could be 1 byte shorter and the decoder 7 bytes shorter in Firefox 30-57 (note that these are incompatible with the above):

```
s=>s.replace(/..?.?/g,b=>"9876543210".replace(/./g,b=>'ACGT'[b=r>>b*2&3]+'TGCA'[b],r=0,[...b].map(c=>r=r*96+c.charCodeAt()-31)))

s=>s.replace(/../g,c=>'ACGT'.search(c[0])).replace(/.{10}/g,b=>String.fromCharCode(...(for(n of[9216,96,1])if(n=parseInt(b,4)/n%96|0)n+31)))

```

# Answer
> 3 votes
## Javascript (ES6), ~~6138~~ 6038 bytes

These functions will encode and decode any printable ASCII characters as required by the challenge rules. They are however using a static Huffman code which is optimized for the example text. They should work pretty well on any other English text, as long as there aren't too many capital letters, digits or miscellaneous symbols. But they will perform poorly on a random input.

*Edit: saved 94 bytes by rethinking the decoder logic and including all hints provided by Neil*

### Encoder (~~305~~ 281 bytes)

```
s=>(n=0,C={},` e|ahinost|cdlr|.Ibfmuwy|',gpv|"k|;?ATqx|FHW|j|:`.split`|`.map((g,i)=>([...g].map(c=>C[c]=('00'+(n++).toString(2)).slice(-i-3)),n*=2)),s=s.replace(/./g,c=>C[c]||(524160|c.charCodeAt()).toString(2)),s.length&1&&(s+=0),s.replace(/../g,c=>'ATCG'[c=+`0b${c}`]+'TAGC'[c]))

```

### Decoder (~~391~~ 315 bytes)

```
s=>(n=N=0,C={},` e|ahinost|cdlr|.Ibfmuwy|',gpv|"k|;?ATqx|FHW|j|:`.split`|`.map((g,i)=>([...g].map(c=>(C[j=i+3]=(C[j]||{}))[n++]=c),n*=2)),s=s.replace(/../g,c=>''+((x='ATCG'.search(c[0]))>>1)+(x&1)),eval(`for(r='';N<s.length-1;){for(i=j=0;!(f=C[j]&&C[j][i])&&j++<19;i+=+s[N++]+i);r+=f||String.fromCharCode(i&127)}`))

```

### DNA sequence (5442 bytes)

Below is the DNA sequence which is generated for the example text.

```
GCTATAATATCGCGCGTAGCGCATATCGATTAATATTACGGCGCCGTATACGATCGGCGCTAGCATTAGCTAATCGGCATTAGCCGATCGTAATATCGATGCCGATTAATGCATGCTAATGCTAATGCTAATATTAATTAGCCGGCCGATTATATAATCGTAATTAATGCATTAGCATATTACGCGTACGGCCGATATGCATCGATCGCGTAATGCGCCGGCATCGGCCGATTAATATTAGCGCATTACGATGCGCTAATATGCCGCGTATATACGCGGCATCGCGATGCTATAATTATAGCCGATTAGCGCGCATTATAATATTAATGCGCTATACGTAATCGTAATTAGCTAATGCTATAATCGCGATGCGCCGATTAGCATGCGCTACGATGCCGCGATGCCGATGCATTACGCGATATGCGCGCGCTAATGCGCCGATGCATTACGATATATCGGCATTACGATCGGCCGATGCCGTAGCGCTACGATTAATATTACGGCGCCGATCGATGCCGCGATGCCGTAATATCGATGCGCTAGCATTAATCGCGTAGCTACGATGCGCCGCGGCATTAATTAATTAGCGCTACGATTATACGATGCCGCGATTACGGCATTATAATGCCGTACGCGTACGGCTAGCGCCGTAGCATATATTACGCGCGATATGCTAATGCGCCGTAGCGCCGCGATATCGATGCGCTAGCATTACGCGGCGCCGATGCATTACGATATATCGTAGCCGCGGCATCGTAATGCCGCGATATGCGCGCTACGCGCGTATAGCATATCGCGTAATTAATCGCGTAGCTAGCATCGATGCGCCGCGGCTATAATATCGTAATCGATTAATTAGCATATCGTACGTACGCGTACGCGTACGCGATTATACGTAATTAGCATTAATCGTAATCGATTATACGATGCCGCGATTACGGCATTATAATGCCGTACGCGTACGGCTAGCGCCGTAGCATATATCGCGTATATACGCGTAATATGCTAATCGATGCTACGGCCGTACGCGATTAGCTAGCATTAGCATCGATTAATCGTAATATCGATATCGTACGGCATGCATTATAGCCGCGTACGCGTACGCGATTATAATCGTAGCGCTACGTAATTATAATCGCGGCTAATCGATTAATGCATTACGATATATCGTAGCCGGCTAATGCATGCTAATATTAATTAGCCGGCCGATTACGCGCGATTACGGCATTACGGCTAATTAGCATATTACGTAATATCGATATCGGCGCGCATGCCGATGCATATATCGCGTATATACGTAGCGCGCTATAGCCGTAGCGCCGCGATATCGATGCGCTAGCATTACGCGCGATCGCGTATATACGTAGCGCGCCGGCATTATAATCGCGCGTATAATATTATAATGCGCCGATCGTAATTAGCGCTACGGCATGCGCTAGCATTAATTACGGCCGATTAGCGCCGTACGCGCGCGGCCGGCGCTAATATTAGCGCGCCGATGCTACGTACGTACGCGATTAATTACGGCCGATTAATGCATTACGATGCGCATCGATCGCGTATAATCGATGCTACGATCGCGTAGCATGCTATAGCTACGATCGCGTATATAATCGCGATATCGCGTAATTAATCGTAATGCATCGATTACGCGTAATATCGTAGCGCATTAATTACGGCATATCGTACGGCTACGATATCGATCGCGCGATATTAATTATAATCGCGTAGCATCGATGCGCTACGTACGATGCGCTAGCCGATATCGATTAATTAGCCGGCCGATCGCGCGATATTAGCATATTAATTATATAATTAATTAGCCGTAATTACGCGCGATGCTACGATGCCGATTACGATGCGCGCATATGCCGCGATATGCGCGCTATACGATCGCGTATACGATGCCGTAGCGCTAATCGCGATGCTATAATTAGCATATCGTAGCTACGATTAGCCGATCGCGATTACGGCATTAATTAGCGCGCATGCCGTATACGCGCGATCGATTAATCGTAATTACGTAATGCCGGCCGGCATGCCGTACGGCCGATTAATATGCATGCTAATCGCGTACGCGTACGCGGCATCGTACGATGCATTAGCTACGATTAATCGTAATATCGCGTAATATGCTAATCGATGCTAATGCTAATGCTAATATTACGCGCGATCGGCATCGATGCCGATTAATGCGCTAGCGCCGGCGCATCGTACGGCATGCATCGTATAATTAATTATAATCGCGTAATTACGGCATTATAATGCCGTACGCGGCCGGCATTAATTACGGCCGATTAATATTACGGCGCCGATCGATGCCGCGATGCCGTAGCTAATATTAGCGCCGCGCGCGATTATAATCGCGTAATTAATCGCGTAGCATATTAATTATAATGCTAGCATATTAGCGCATCGATGCTATAATTAATCGTAATCGATGCCGATGCCGTACGGCATCGCGATGCCGATCGATGCATCGTAATATCGTACGGCTAATTAGCATGCTAATATCGCGTATAATCGATGCTAGCGCATTAATTAGCTAATTAGCATCGATCGCGTATATAATTAGCATATCGCGTAATTAATCGTAATGCATGCCGCGATATGCTATAATTATACGCGATGCCGTAGCATTATAGCATATGCTAGCATATCGTAGCCGCGTACGTAGCATCGATCGCGTATAATCGATCGGCATTAGCATTACGATCGTAATATGCATGCCGATCGCGTATAATGCCGTAATGCGCCGTAATTATAATCGCGTAATTATACGCGATGCCGATGCGCTAGCCGATTACGCGGCATCGTATAATTACGGCCGATTAATCGGCTATAATGCTAATATGCGCATCGATTACGTAGCCGTATACGCGGCCGTAGCGCATCGATGCCGCGTATATACGCGGCATCGCGATTAATGCATTAATGCATATATTATATAATGCGCCGATTAATATCGATATGCTACGATCGCGTAGCATGCTATAGCTAGCCGCGATATGCTATAATTAGCATATTATAATTAGCATATGCTATATAGCCGATCGTAATATGCGCATTATAATATGCGCGCGCGCTAGCATGCATGCTAATATGCTACGATCGCGTAGCATGCTATAGCTACGATTAATCGCGATTATAATCGCGGCTAATCGATCGGCCGGCTAGCATATTATAGCCGTATACGCGATTAGCGCGCATCGATTAATCGCGATTAATATGCCGTAATTATACGATCGGCGCTAATGCTAGCATATTACGCGATGCCGTAGCGCGCATATATCGCGTATAATGCCGTAATGCGCCGATCGTAATATCGTACGATCGTACGATATTACGGCATTATAATGCCGTACGCGGCCGGCATATCGTATAATATCGTAGCCGATTAATGCATTACGATATGCCGTAATTATAGCTACGGCCGATATCGGCGCATCGGCTAATATGCGCATGCGCCGTAATTATAATCGCGTAATATGCATGCCGGCCGTAGCATCGATCGTACGCGGCATGCGCATGCTACGCGCGGCCGTAGCATCGTAGCGCATCGATTAATGCATTAATGCATATATCGCGTATAATCGATGCGCTAGCCGTACGATCGGCATTACGTACGTAATGCATGCCGCGATATGCGCGCTACGCGCGTAATTACGGCCGCGTATACGCGCGATTATAATCGCGCGTATAATATCGCGTATAATCGATCGGCTAATTACGATCGATGCATGCATCGATTACGTAGCATTATAATCGCGTAATTACGGCGCCGATCGATGCCGCGATGCCGTAATATTAGCGCCGTAATTACGATGCGCCGATTACGGCCGATTACGTAGCATTAATTACGTACGGCCGTAGCATCGATCGCGCGATATATCGTATATATATACGTATAATCGGCTATAATATTACGTAGCCGTAATGCTACGCGCGCGTAATTATATAATATATGCGCTAGCATTACGATGCATATGCATGCCGCGTATAATTAATATGCTATAATATTACGCGTAATATGCATGCGCTAATTAGCATCGTACGTACGCGTACGTAGCGCGCTATAGCGCCGATATATGCTATAATATGCCGATATCGCGATGCGCATCGATCGCGTATATAATCGCGATATGCATGCGCATCGTACGGCTATATAATCGATCGGCATCGATGCCGATCGTAATCGTAATTATAATCGCGTAATTATACGCGATGCATTAATTACGTAGCTAATATTACGCGGCTAATATTAATCGGCGCTAGCCGTAATATCGATATGCGCGCCGTAGCATCGTACGTACGCGTACGCGATTAGCGCGCGCGCGCCGATTATAGCCGATATGCATCGATCGCGTATATACGCGTAATATCGATTACGTACGCGTATAATGCTAATGCTATACGATTAATCGTATAGCCGTAATCGATTAATGCATTAATGCATATATATGCGCGCGCTATACGCGTACGCGATATGCATGCCGATCGCGTATAATCGATGCATTAATTAGCTAATTAGCATCGATGCTAGCCGATGCATGCGCATTAATGCGCGCCGTAATTAGCGCGCGCATCGGCGCTACGATTACGCGTAATATGCTATAATATTAATATGCATGCTAATCGCGTACGCGTACGCGGCTAGCGCCGTAATTAGCGCCGCGGCATTACGATATTAGCGCTACGGCATGCGCTAGCCGTAATTAATTACGGCCGATTACGTAGCCGCGATGCCGTAATGCATGCTAATGCATGCGCGCCGCGATTAGCGCGCATGCCGTAATGCATGCTAATGCTAATATGCGCATCGATGCCGCGTATATACGCGGCATCGCGATCGCGTATAATCGATCGTACGGCATGCATTATAGCCGGCATTAATTAGCGCTACGGCGCATTAGCTATACGATATGCTAGCGCGCTAATTAATTAATATGCGCCGATGCCGGCATATCGTATAGCCGGCGCATCGATCGCGCGATATTATAATCGCGTAATATTAGCGCGCCGGCTACGTACGCGCGATGCGCATATTATAGCCGCGGCGCATCGATCGCGTATAATCGATGCCGATGCCGGCCGTACGCGATGCCGTAGCCGGCATATCGATGCGCTAGCATTATAATCGCGTAATATCGTAGCTAATTAATTAATTACGGCCGATTAATATTACGGCGCCGATCGATGCCGCGATGCCGTAGCTAATATTACGCGGCTAATATCGATTAGCGCATTAGCTACGATTAATCGGCGCTAGCCGTAGCTAATATTACGCGCGATCGGCGCATATGCGCGCCGATCGCGATTAGCATCGGCGCTAGCATGCCGTACGTACGCGTAATTAGCCGGCCGATTATACGATGCCGCGATATGCTATAATATCGTAGCCGTAGCTACGCGCGGCATCGCGTATACGCGCGCGTAGCTAAT

```

### Demo

The snippet below includes some demonstration code.

```
let e =
s=>(n=0,C={},` e|ahinost|cdlr|.Ibfmuwy|',gpv|"k|;?ATqx|FHW|j|:`.split`|`.map((g,i)=>([...g].map(c=>C[c]=('00'+(n++).toString(2)).slice(-i-3)),n*=2)),s=s.replace(/./g,c=>C[c]||(524160|c.charCodeAt()).toString(2)),s.length&1&&(s+=0),s.replace(/../g,c=>'ATCG'[c=+`0b${c}`]+'TAGC'[c]))

let d =
s=>(n=N=0,C={},` e|ahinost|cdlr|.Ibfmuwy|',gpv|"k|;?ATqx|FHW|j|:`.split`|`.map((g,i)=>([...g].map(c=>(C[j=i+3]=(C[j]||{}))[n++]=c),n*=2)),s=s.replace(/../g,c=>''+((x='ATCG'.search(c[0]))>>1)+(x&1)),eval(`for(r='';N<s.length-1;){for(i=j=0;!(f=C[j]&&C[j][i])&&j++<19;i+=+s[N++]+i);r+=f||String.fromCharCode(i&127)}`))

function encode() {
  var txt, dna;

  if(txt = document.getElementsByTagName('textarea')[0].value) {
    dna = e(txt);
    document.getElementsByTagName('textarea')[0].value = '';
    document.getElementsByTagName('textarea')[1].value = dna;
    document.getElementsByTagName('div')[0].innerHTML = 'DNA length: ' + dna.length + ' (' + (dna.length / txt.length).toFixed(2) + ' nucleotides per character)';
  }
}

function decode() {
  var txt, dna;

  if(dna = document.getElementsByTagName('textarea')[1].value) {
    txt = d(dna);
    document.getElementsByTagName('textarea')[0].value = txt;
    document.getElementsByTagName('textarea')[1].value = '';
    document.getElementsByTagName('div')[0].innerHTML = 'Text length: ' + txt.length;
  }
}
```

```
textarea {font-size:10px;font-family:Arial;width:400px;height:70px}
```

```
<textarea>I have a friend who's an artist and has sometimes taken a view which I don't agree with very well. He'll hold up a flower and say "look how beautiful it is," and I'll agree. Then he says "I as an artist can see how beautiful this is but you as a scientist take this all apart and it becomes a dull thing," and I think that he's kind of nutty. First of all, the beauty that he sees is available to other people and to me too, I believe. Although I may not be quite as refined aesthetically as he is ... I can appreciate the beauty of a flower. At the same time, I see much more about the flower than he sees. I could imagine the cells in there, the complicated actions inside, which also have a beauty. I mean it's not just beauty at this dimension, at one centimeter; there's also beauty at smaller dimensions, the inner structure, also the processes. The fact that the colors in the flower evolved in order to attract insects to pollinate it is interesting; it means that insects can see the color. It adds a question: does this aesthetic sense also exist in the lower forms? Why is it aesthetic? All kinds of interesting questions which the science knowledge only adds to the excitement, the mystery and the awe of a flower. It only adds. I don't understand how it subtracts.</textarea><br>
<button onclick="encode()">Text -> DNA</button><button onclick="decode()">DNA -> Text</button><br><textarea></textarea><div></div>
```

# Answer
> 2 votes
# Python 3, 15324 + 122 + 211 = 15657 bytes

This is a very wasteful method which converts each character to a three digit number and, for each of those three digits, assigns it a two unit code.

## Encoder, 122 bytes

```
u='AAAATTTCCGTTTTAAAGGCATCGTCGCGGTAGCAGCGCC'
o=''
for i in o.join("%03d"%ord(i)for i in input()):o+=u[int(i)::10]
print(o)

```

*See the encoded version of the example text **here***

## Decoder, 211 bytes

```
u=['ATAT','ATTA','ATCG','ATGC','TATA','TACG','TAGC','CGCG','CGGC','GCGC']
l=input()
I=u.index
s=''
for j in[l[i:i+12]for i in range(0,len(l),12)]:s+=chr(int(str(I(j[:4]))+str(I(j[4:8]))+str(I(j[-4:]))))
print(s)

```

# Answer
> 2 votes
# Ruby, 97 + 96 + 5152 = 5345 bytes

Encoder program requires the flags `-nrzlib`.

```
Zlib::Deflate.deflate($_).bytes{|b|('%04s'%b.to_s(4)).chars{|c|$><<"ATTACGGC"[2*c.to_i,2]}}

```

Decoder program requires the flags `-przlib`.

```
gsub(/../){"ATTACGGC".index($&)/2}
gsub(/..../){$&.to_i(4).chr}
$_=Zlib::Inflate.inflate$_

```

# Answer
> 1 votes
# Python 2, 12770 + 204 + 271 = 13245

**Encoder:**

```
from itertools import*
D=[''.join(p)for p in permutations('AT TA CG GC'.split())]
e=lambda x:''.join('AT'+D[c-32]if c<56else'TA'+D[c-56]if c<80else'CG'+D[c-80]if c<104else'GC'+D[c-104]for c in map(ord,x))

```

**Decoder:**

```
from itertools import*
D=[''.join(p)for p in permutations('AT TA CG GC'.split())]
n=D.index
d=lambda x:''.join(chr(n(c[2:])+32)if'AT'==c[:2]else chr(n(c[2:])+56)if'TA'==c[:2]else chr(n(c[2:])+80)if'CG'==c[:2]else chr(n(c[2:])+104)for c in map(''.join,zip(*[iter(x)]*10)))

```

Every character is encoded to a 10-character (5 unit) string, with the first unit indicating what quarter of the printable character string it belongs to, and the last four indicating what character in that quarter is represented.

Try it here.

# Answer
> 1 votes
# PHP, 5106 + 297 + 161 = 5564

encoder

```
$t=str_replace("=","",base64_encode((gzdeflate($_GET["e"]))));$c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";$e=["AT","TA","CG","GC"];$n="";foreach(str_split($t)as$b){$p=str_pad(base_convert(strpos($c,$b),10,4),3,"0",STR_PAD_LEFT);$n.=$e[$p[0]].$e[$p[1]].$e[$p[2]];}echo $n;

```

decoder

```
$e=["AT"=>0,"TA"=>1,"CG"=>2,"GC"=>3];$a=str_split(strtr($_GET["d"],$e),3);$o="";foreach($a as $v)$o.=$c[base_convert($v,4,10)];echo gzinflate(base64_decode($o));

```

# Answer
> 1 votes
# Node.js (5.6.0), 5104 + 125 + 122 = 5351

I was originally working in JavaScript, but Node.js provides compression much more easily. Thanks Neil for helping trim out 5 bytes on the encoder!

**Encoder (125 bytes):**

```
s=>[...require('zlib').deflateRawSync(s)].map(a=>('000'+a.toString(4)).slice(-4).replace(/./g,b=>'ATCG'[b]+'TAGC'[b])).join``

```

**Decoder (122 bytes):**

```
s=>require('zlib').inflateRawSync(Buffer(s.replace(/../g,a=>'ATCG'.search(a[0])).match(/..../g).map(a=>parseInt(a,4))))+''

```

**DNA Sequence (5104 bytes):**

```
TATATATATATATAATGCATCGTACGATGCCGGCTACGGCATGCATATATATGCATGCGCGCTAATTATATATACGATCGATCGGCCGTAGCATGCATATCGTAGCGCATCGATATATTACGTAGCTAGCATATGCCGCGATATCGTATAGCCGCGATCGCGGCCGTAATATGCGCGCTAATATCGGCATGCTACGATCGATGCATGCCGGCATTAATTACGCGTATACGTATAGCTAATTAATTATAATCGCGCGATTAGCCGGCGCGCGCTAGCGCTAATTAGCGCCGCGTATATAGCCGATCGTATACGTAATCGGCATTAATATCGATCGTAGCATCGGCTATACGGCTAATCGATGCGCCGTATAATTAATTATAATGCCGGCCGATATGCATGCATATTATACGGCCGCGCGTATAATGCATCGATTAGCCGTACGCGTAATTAGCTATACGTAATCGTACGTAGCCGCGTATACGTAATATATCGCGTAATTATAATCGATCGGCTACGCGCGGCGCCGATATGCTAGCATCGATCGTAATATGCTAATCGTATACGTATATACGTACGCGATCGGCATGCATGCATCGCGGCTATACGTACGGCCGATATGCATTAGCATATCGTAGCTAATCGATGCGCCGGCGCATATCGATCGATGCGCTAATATGCCGATTAATGCCGTAGCTATACGCGATCGTATAATGCGCGCATCGATGCATGCCGTAATTACGCGGCTACGATTACGCGTACGATGCTATAGCTACGCGTAATTAATTAGCTAGCATCGGCCGATTACGGCCGCGGCTACGTAGCATGCTAATCGCGTAATTATAGCGCCGGCGCATGCTAGCATGCTAATCGCGATGCTAATTAATCGTAATTACGCGCGCGCGTAATCGGCCGCGATGCCGCGTATAATTACGTAATGCCGTATAGCTAATCGATGCCGCGTACGCGGCGCTACGATGCCGCGATATCGCGTACGATCGTAGCTAGCATATTAATATTATAGCCGGCCGCGTAGCATGCATCGCGATTATATACGCGCGGCGCATGCTATAATTAATTAATGCTAATTAATCGCGATGCCGCGCGGCCGATTACGCGCGTAGCCGTATACGTAGCATCGGCGCATCGGCCGCGTAGCTATAATGCGCCGGCTAATCGGCTACGGCATATTAATGCCGCGATCGATCGTACGGCGCTATAATGCCGGCCGCGTAGCCGCGTATAATTAATGCCGATTAATCGCGGCGCTATATAATATATTATAGCGCGCATTATATAGCGCCGATGCTAGCGCTATACGGCGCTACGTAATTATAATATTATATAGCATGCTAGCCGCGATTATAGCATCGATGCTAATGCTACGCGCGCGTACGCGGCTACGATTAATTAGCTAATCGATATATGCTACGATTATATACGGCCGTAATTACGCGCGTAGCCGCGTAATGCCGTAGCATATCGTACGATATATTATACGGCGCTAATTACGCGATCGCGCGATTACGATCGTAGCATTAGCCGTAATTAATATATTATAGCATTAGCATTACGCGATCGCGGCATCGCGCGTAATGCTATAGCATCGCGGCTATAGCCGTAGCTATATAATGCATGCCGGCGCTAGCTAGCGCATATATTACGGCATATGCATTAGCGCATGCCGATATGCTACGATATCGGCTAGCCGATCGTATACGCGATCGGCCGCGTATAATCGCGCGGCGCTACGTATAGCTACGCGCGTAATTATAGCGCCGGCATTACGCGATATATGCCGTAGCATGCCGGCCGCGATTAGCCGCGTAATATATATTACGCGTAGCTAGCTAATTACGGCTACGGCTATAGCCGGCCGATTATAATTAATATTACGGCCGCGGCTATAGCATATATATGCGCATGCATTACGATTATATAGCATGCATATATCGATATCGTAATCGATTATAATATTATACGATCGCGCGATTACGATTATATACGTATAGCATATTAGCTACGTATAGCATTATAGCATATATGCTAGCTAGCCGGCTAATTAATATATGCCGCGATATATATGCGCATTAGCATGCCGATCGCGTAGCGCATCGATTAGCATATCGGCATGCGCGCCGTAATGCTAATGCTATATAATCGCGCGGCGCGCCGGCCGGCGCCGGCATATGCATATATATGCCGGCATGCATGCCGATTATATAGCGCGCCGCGTATATAGCCGCGATGCCGGCATTAGCATCGGCATCGCGGCTAGCGCATCGATCGTACGTACGTATAATTAGCATATCGCGCGCGGCATGCCGCGATTACGTAGCTAGCATTAATATATATCGATTAGCGCATGCTAATATATGCCGATATATATATTATAGCCGATCGGCGCATTATAGCCGATTAATTAATCGCGATTACGTACGGCATTATATACGTATACGCGCGTATAGCGCATATATTAATATCGATATGCGCGCATTATATATAGCCGATTACGTAATGCCGGCGCCGCGATGCATTAATCGATGCTAATATATTATACGTAATATCGGCTACGCGTATAGCATATATTACGCGATTACGATCGGCGCGCGCGCATGCTAGCATATCGATGCGCGCCGTAGCCGATCGCGCGGCATTAGCATGCGCTATAATCGATATATATTAGCCGATCGTATACGGCTACGCGCGTAATGCATTAGCCGTAGCATGCCGATTATAGCATATCGCGGCGCATATCGCGGCTACGGCATTAATCGATTATAATCGATGCATTAGCGCCGTAATGCCGATCGATTAGCATCGCGGCTATACGATCGGCTATAGCATTAATATATATTATACGCGGCATATATTAGCGCATTAGCTACGTAATATGCGCCGATTATACGGCCGGCATGCGCTACGGCATATTAGCCGCGTAATCGTACGCGATATTACGCGCGTAATGCCGTAGCGCATCGGCATATATCGCGATGCTACGTAATGCATGCATGCTAATCGATGCCGCGATCGATGCGCTAGCATCGTATAATATCGGCTAATCGTATACGTATATATAGCGCGCTATACGTAATGCCGGCTATATACGGCCGGCGCATGCGCATATGCATCGGCTAATTACGCGATCGTACGATCGATATATGCTACGGCGCGCATATCGGCTAGCCGCGCGCGGCCGGCTAATGCCGCGCGATATCGGCGCTATACGGCCGTACGATGCCGCGCGATATCGATGCTATAATTACGCGTAATCGATATGCGCTAGCGCCGATCGTATAGCTACGTAGCGCATTACGGCATGCTACGCGGCATGCATTAATCGGCCGATCGGCGCCGTAGCTACGATATCGTACGGCGCCGGCGCATTAGCTAGCGCGCGCGCCGCGGCATGCTATAATATTACGTACGCGTACGTAATATTAGCATGCATTAATTAGCCGGCATTATAGCTACGCGTACGCGATGCATTATACGTAGCGCTAGCATCGCGCGCGCGTATATAATGCCGCGTATACGATTAGCTATAGCCGGCCGCGCGGCTAGCATGCCGATCGATGCTAATCGGCCGTAATTACGATATTATATATATATATAGCTAGCGCATGCCGTACGGCCGTACGGCATATATTAATTAATTATAGCGCTAGCTACGATTATAGCTATATAGCTACGTAATCGCGGCATCGTAATCGGCGCTAGCCGCGATGCTAGCCGATCGCGGCCGGCCGCGTAATATGCCGGCGCCGTAATGCCGATCGTATATACGGCATCGCGGCCGCGATGCATGCCGATATCGTACGCGATATCGCGGCTATAGCCGATATCGTATACGCGTAATGCGCATGCTACGATATGCCGCGCGTATATAGCCGATCGGCCGCGTAATATTATAATCGGCATGCATATGCGCCGCGCGTACGGCGCTAATATCGCGCGATTAATTAATATATATTAGCATCGCGATGCGCATTATAATGCTACGCGGCGCCGGCGCCGATCGTATATAATGCCGGCCGCGATATATTAGCTATACGCGCGCGCGGCGCGCTACGCGTATAGCGCGCATATCGATATTAGCATGCTAATCGTAGCATGCATATCGTATACGCGCGATGCGCCGCGATGCATCGGCGCGCGCATGCCGGCGCGCGCCGCGCGGCATTATACGTAATCGTAGCGCGCGCCGATATGCTAATTAGCGCCGCGTAGCATGCTACGGCCGCGGCCGGCCGGCGCGCCGCGGCGCATATCGCGGCATCGCGGCTAATATCGCGATGCCGCGCGGCGCCGATCGTAGCTAGCTAGCGCGCATCGATATATATGCGCGCATGCCGCGTAGCTAGCGCATCGTAATTATAGCATCGCGCGCGGCATCGCGGCGCGCGCTAATTACGTAGCGCTACGCGATTACGCGATTAATGCGCGCCGGCATCGGCATTAGCGCATGCATTATATATATACGCGCGTACGGCGCTACGATATCGCGGCTATAATATGCTAGCGCCGCGATATATCGGCGCATCGTAATATGCGCTAATATATTAGCGCTAATATGCATCGGCATCGATCGGCTACGTATAATATGCGCGCGCATATATCGATATTAGCCGCGTACGTATACGTACGTATATAATGCTAATGCGCATTATAGCCGATTACGTACGATATGCGCGCATTAATCGTATATAGCTATACGATCGCGGCTATACGATATGCTAGCCGTATAGCGCTAGCATATATTAATATCGGCATATGCTAGCGCCGGCCGCGGCTATATACGGCATGCGCGCTACGGCGCTACGCGCGGCGCGCCGTATAATTATACGCGTAGCCGGCGCATATATCGGCCGTAGCCGGCATATGCGCATCGGCGCTAGCTATAGCTAATGCGCTAGCTACGTATACGTAGCCGTAATGCGCCGATGCGCATTAGCATGCTAGCCGCGCGTATACGTACGTATACGATCGCGCGGCGCTATACGCGGCGCCGTACGATGCGCGCCGATATGCATATCGATATATCGGCATGCGCTATACGTAGCATGCATGCATGCTATACGTACGATGCGCGCGCGCGCATATATTA

```

---
Tags: string, code-challenge, compression
---


# Question
Title: Look-and-say sequence: roman numerals edition
# Challenge description

We've had a few challenges involving the Look-and-say sequence. Quick reminder:

* The sequence starts with `1`,
* Subsequent terms of this sequence are generated by enumerating each group of repeating digits in the previous term,

So the first few terms are:

```
1        "one"
11       "one one" (we look at the previous term)
21       "two ones"
1211     "one two, one one"
111221   "one one, one two, two ones"
312211   "three ones, two twos, one one"

```

Now let's do the same thing, but use Roman Numerals instead. We start with `I` and follow the same rules (we apply the digit-counting rule to characters instead, so we read `IVX` as `one one, one five, one ten` instead of `one four, one ten` or some other way):

```
I           "one"
II          "one one"
III         "two ones" = "II" + "I"
IIII        "three ones" = "III" + "I"
IVI         "four ones" = "IV" + "I"
IIIVII      "one one, one five, one one"
IIIIIVIII   "three ones, one five, two ones" = ("III" + "I") + ("I" + "V") + ("II" + "I")

```

Given a positive integer `N`, either:

* Output first `N` numerals of this sequence (any reasonable separator is fine, as well as `["I", "II", "III", ...]`
* Output `N`th term of this sequence (it may be 0-indexed).

Remember to make your code as short as possible, since this is a challenge!

EDIT: I believe that there is always one standard/preferred way of expressing integers as roman numerals, (like `95` -\> `XCV` instead of `VC`). Couple of Roman numeral converters I found online corroborate my opinion. If in doubt, use an online converter, as listing all the possible edge-cases and specific rules of writing Roman numerals is not the point of this challenge.

EDIT2: @PeterTaylor and @GregMartin pointed out that only numbers less or equal to `5` appear in the sequence, so you don't have to worry about the ambiguity of Roman numerals (numbers `1` \- `8` are `I`, `II`, `III`, `IV`, `V`, `VI`, `VII`, and `VIII`)

# Answer
# Perl, 49 bytes

Includes +1 for `-p`

Run with the 0-based index on STDIN, e.g.

```
ecce.pl <<< 14

```

`ecce.pl`:

```
#!/usr/bin/perl -p
s,(.)\1*,$&/$1%182 .$1,eg for($_=/$/)x$`;y;19;IV

```

Magic formulas are so magic.

Normally I would use `($_=//)x$'` to make the loop control one byte shorter, but scoring on this site gives that a handicap of 2 so it ends up 1 byte longer. On older perls you can drop the space before `for`. Some versions of perl force you to add a final `;` to close the transliteration. But what is given above is the code that works on my system.

## Explanation

Working backwards from solution to code:

The string transformations we need:

```
I     -> II
II    -> III
III   -> IIII
IIII  -> IVI
IIIII -> VI

V     -> IV
VV    -> IIV

```

Each replacement ends with the repeated character. I will get a sequence of the same characters using regex `/(.)\1*/`, so this can be done by appending `$1`. The part before the `->` is in `$&`. With that I still need:

```
I     -> I
II    -> II
III   -> III
IIII  -> IV
IIIII -> V

V     -> I
VV    -> II

```

Write `I` as `1` and `V` as 9:

```
1     -> 1
11    -> 11
111   -> 111
1111  -> 19
11111 -> 9

9     -> 1
99    -> 11

```

By dividing the part before `->` by the repeated digit this becomes:

```
1     -> 1
11    -> 11
111   -> 111
1111  -> 19
11111 -> 9

1     -> 1
11    -> 11

```

So now the original repeated `V` is not an exception anymore. So I want an expression that makes this happen:

```
1     -> 1
11    -> 11
111   -> 111
1111  -> 19
11111 -> 9

```

And this can be done by a simple modulo 182:

```
1     % 182 = 1
11    % 182 = 11
111   % 182 = 111
1111  % 182 = 19
11111 % 182 = 9

```

(this even gets `IIIIII` to `VI` right though it isn't needed here)

All that is left is initializing the working variable to `1` for index 0, repeat this transformation in a loop and at the end replace `1` by `I` and `9` by `V`

`1`, `9` and `182` is the only parameter combination for which this simple formula works.
> 18 votes

# Answer
# Mathematica, ~~113~~ ~~90~~ 83 bytes

*Thanks to Martin Ender for suggestions that reduced the length by over 25%!*

Showing off the high-level commands in Mathematica.

```
Nest[Flatten[Characters@{RomanNumeral@#,#2}&@@@Reverse@@@Tally/@Split@#]&,{"I"},#]&

```

A pure function, taking an argument N and outputting the Nth element of this (0-indexed) sequence, as a list of characters. Spread out a bit:

```
Nest[
  Flatten[
    Characters @ {RomanNumeral@#,#2}& @@@
      Reverse @@@ Tally /@ Split@ #
    ]& ,
  {"I"}, #]&

```

The outer `Nest` iterates the middle four-line function, starting on `{"I"}`, N times. Line 4 splits the character list of the input Roman numeral into runs of like characters, counts each run with `Tally`, and puts the counts before the characters they're counting. Line 3 renders the counts as Roman numerals, then splits those Roman numerals up into lists of characters. The `Flatten` command reduces the whole list-of-lists to a one-dimensional list.

Here's the initial version:

```
Nest[
  "" <> Flatten[{RomanNumeral@#[[1]], #[[2]]} & /@
    (Reverse@#[[1]] & /@
      Tally /@
        Split@Characters@#)] &,
  "I", #] &

```
> 10 votes

# Answer
## CJam (33 30 bytes)

```
"I"{e`{(4md1$^'I*\'V*@}%e_}ri*

```

Online demo

Key to the correctness of the implementation is the following theorem:

### If the first generation is `I`, no run length is ever greater than five

Lemma: if the first generation is `I`, no string ever contains `VVV`. Proof is by contradiction. Suppose that there is a first index `n` for which the `n`th generation contains `VVV`. If that `VVV` breaks down as `(a)V VV` then the conversion from the previous generation is bad: it should have been `(a+5)V`. So it must be `VV V(d)`, and the previous generation contained `VVVVV`, contradicting the choice of `n`.

Now, suppose there is a first index `m` for which the `m`th generation contains `...IIIIII...`. Note that there can be no digits other than `I` and `V` in the string, because no previous generation has had a run of nine `I`s or nine `V`s. At most four of the `I`s come from a run of `I`s in the previous string, so the corresponding section of the previous string must be `...IIIVV...` giving `... IIII IIV ...`. Since the `VV` in generation `m-1` doesn't come from `VVVVV` (see lemma), the second `V` must be a run-length of digit `I`, so in generation `m-1` we have `...IIIVVI...`. And since we want the initial `I`s to give `IIII` and not `IVI` or `VI`, it is preceded either by the start of the string or by a `V`.

If we have `(...V)?IIIVVI...` in generation `m-1`, what do we have in generation `m-2`? We've already observed that the `VV` of gen. `m-1` must be parsed as `(a)V V(I)`.

Suppose we take `a=2`: `(...V)?I IIV VI...` Actually it must be `...VI IIV VI...`, although that leading `V` might be part of `IV`; so in the previous generation we have either `(...V)? IIII VV IIIII...` or `(...V)? IIIII VV IIIII`. Either way we run into trouble with `VVIIIII`: the second `V` must be a run-length, but then `...VI IIII...` requires a following (run-length, digit) pair with the same digit.

So it must be `a=1`: `(...V)?II IV VI...`. Since generation `m` is the first with a run of six `I`s, that must be `(...V)? II IV VI...`, so that generation `m-2` is `(...V)? I V IIIII...`. `...VIVIIIII...` is impossible: however we choose to interpret the second `V` we end up with two consecutive (run-length, digit) pairs with the same digit.

Therefore generation `m-2` must be `^IVIIIII...`, parsed as `^IV IIII I(V)...` or `^IV III II(V)...`. These give respectively generation `m-3` as `^V III V ...` or `^V II VV...`.

But if we look at the start of the strings beginning with the first one that starts with `V`, we get a cycle:

```
    VI IV I...
    IV III IV ...
    II IV IVI ...
    IIII IV II IV ...

```

and so no generation ever starts with either `VIIIV` or `VIIVV`. We must conclude that there is no such `m`.

### Dissection

```
"I"          e# Initial generation
{            e# Loop...
  e`         e#   Run-length encode
  {          e#   Foreach [run-length char] pair...
    (        e#     Extract the run-length r
    4md1$^   e#     Get the number of Vs and the number of Is
             e#     The number of Vs is r/4 ; the number of Is is (r%4)^(r/4)
    'I*\'V*@ e#     Repeat strings the appropriate number of times and reorder
  }%
  e_         e#  Flatten to a simple string
}ri*         e# ... n times, where n is taken from stdin

```
> 8 votes

# Answer
# Python 3, 195 bytes

There's a lot of bytes wasted on the roman numerals, so there's likely some golfing to be done there.

Thanks to @El'endiaStarman, @Sherlock9 and @Shooqie

```
import re
def f(x,r=""):
 for v,i in(5,"V"),(4,"IV"),(1,"I"):a,x=divmod(x,v);r+=i*a
 return r
s="I"
for i in[0]*int(input()):print(s);s=re.sub(r'(.)\1*',lambda m:f(len(m.group()))+m.group()[0],s)

```

**Ideone it!**
> 6 votes

# Answer
## R, ~~110~~ 107 Bytes

`as.roman` combined with `rle` makes this easy. Scoping abuse and built in cat behavior of `<<-` saves a few bytes.

```
x="I"
replicate(scan(),{r=rle(strsplit(x,"")[[1]])
x<<-paste(rbind(paste(as.roman(r$l)),r$v),collapse="")})

```

Takes in N from console. Outputs first 2 to N terms of sequence (which I believe is within spec...)

```
 [1] "II"
 [2] "III"
 [3] "IIII"
 [4] "IVI"
 [5] "IIIVII"
 [6] "IIIIIVIII"
 [7] "VIIVIIII"
 [8] "IVIIIIVIVI"
 [9] "IIIVIVIIVIIIVII"
[10] "IIIIIVIIIVIIIIVIIIIIVIII"
[11] "VIIVIIIIIVIVIIVVIIVIIII"
[12] "IVIIIIVVIIVIIIVIIIIIVIIIIVIVI"
[13] "IIIVIVIIIVIIIIVIIIIIVVIIVIVIIVIIIVII"
[14] "IIIIIVIIIVIIIIIVIVIIVVIIIVIIIIVIIIVIIIIVIIIIIVIII"
[15] "VIIVIIIIIVVIIVIIIVIIIIIVIIIIIVIVIIVIIIIIVIVIIVVIIVIIII"
[16] "IVIIIIVVIIIVIIIIVIIIIIVVIIVVIIVIIIVIIIIVVIIVIIIVIIIIIVIIIIVIVI"
[17] "IIIVIVIIIVIIIIIVIVIIVVIIIVIIIIIVIIIIVIIIIIVIVIIIVIIIIVIIIIIVVIIVIVIIVIIIVII"
[18] "IIIIIVIIIVIIIIIVVIIVIIIVIIIIIVIIIIIVVIIVIVIIVVIIVIIIVIIIIIVIVIIVVIIIVIIIIVIIIVIIIIVIIIIIVIII"
[19] "VIIVIIIIIVVIIIVIIIIVIIIIIVVIIVVIIIVIIIIVIIIVIIIIIVIIIIVIIIIIVVIIVIIIVIIIIIVIIIIIVIVIIVIIIIIVIVIIVVIIVIIII"
[20] "IVIIIIVVIIIVIIIIIVIVIIVVIIIVIIIIIVIIIIIVIVIIVIIIIIVVIIVIVIIVVIIIVIIIIVIIIIIVVIIVVIIVIIIVIIIIVVIIVIIIVIIIIIVIIIIVIVI"
[21] "IIIVIVIIIVIIIIIVVIIVIIIVIIIIIVIIIIIVVIIVVIIVIIIVIIIIVVIIIVIIIIVIIIVIIIIIVIIIIIVIVIIVVIIIVIIIIIVIIIIVIIIIIVIVIIIVIIIIVIIIIIVVIIVIVIIVIIIVII"
[22] "IIIIIVIIIVIIIIIVVIIIVIIIIVIIIIIVVIIVVIIIVIIIIIVIIIIVIIIIIVIVIIIVIIIIIVIVIIVIIIIIVVIIVVIIVIIIVIIIIIVIIIIIVVIIVIVIIVVIIVIIIVIIIIIVIVIIVVIIIVIIIIVIIIVIIIIVIIIIIVIII"
[23] "VIIVIIIIIVVIIIVIIIIIVIVIIVVIIIVIIIIIVIIIIIVVIIVIVIIVVIIVIIIVIIIIIVVIIVIIIVIIIIVVIIIVIIIIIVIIIIVIIIIIVVIIVVIIIVIIIIVIIIVIIIIIVIIIIVIIIIIVVIIVIIIVIIIIIVIIIIIVIVIIVIIIIIVIVIIVVIIVIIII"
[24] "IVIIIIVVIIIVIIIIIVVIIVIIIVIIIIIVIIIIIVVIIVVIIIVIIIIVIIIVIIIIIVIIIIVIIIIIVVIIIVIIIIVIIIIIVIVIIIVIIIIIVVIIVIVIIVVIIIVIIIIIVIIIIIVIVIIVIIIIIVVIIVIVIIVVIIIVIIIIVIIIIIVVIIVVIIVIIIVIIIIVVIIVIIIVIIIIIVIIIIVIVI"
[25] "IIIVIVIIIVIIIIIVVIIIVIIIIVIIIIIVVIIVVIIIVIIIIIVIIIIIVIVIIVIIIIIVVIIVIVIIVVIIIVIIIIIVIVIIVVIIVIIIVIIIIIVVIIIVIIIIVIIIVIIIIIVIIIIIVVIIVVIIVIIIVIIIIVVIIIVIIIIVIIIVIIIIIVIIIIIVIVIIVVIIIVIIIIIVIIIIVIIIIIVIVIIIVIIIIVIIIIIVVIIVIVIIVIIIVII"

```
> 4 votes

# Answer
# Perl 6, 62 bytes

```
{("I",{S:g/(.)$0*/{<I II III IV V>[$/.chars-1]~$0}/}...*)[$_]}

```

Anonymous function that accepts a zero-based index.

Makes use of the fact that roman numbers higher than 5 aren't needed, because the only groups of repeating digits that can occur, are:

```
I     -> II
II    -> III
III   -> IIII
IIII  -> IVI
IIIII -> VI

V     -> IV
VV    -> IIV

```

(try it online)
> 1 votes

# Answer
# JavaScript (ES6), 107

Recursive function returning the Nth term 0 based

```
f=(n,r='I')=>n?f(n-1,r.match(/I+|V+/g).map(x=>((n=x.length)-4?'VIII'.slice(n<5,1+n%5):'IV')+x[0]).join``):r

```

**Test**

```
f=(n,r='I')=>n?f(n-1,r.match(/I+|V+/g).map(x=>((n=x.length)-4?'VIII'.slice(n<5,1+n%5):'IV')+x[0]).join``):r

function update() {
  O.textContent=f(I.value)
}

update()
```

```
<input id=I value=25 type=number oninput='update()'><pre id=O></pre>
```
> 1 votes

---
Tags: code-golf, sequence, roman-numerals
---


title: Convert string to number

text:
# Question
Title: Convert string to number
# Task

The task is to convert a string to a number. It must accept the string via stdin and output the number via stdout.

You convert a string to a number by replacing each letter of the string by its index (mind that you don't need to replace it with the index, that's just an example. You are allowed to replace it with anything you like, as long as the output is decodable) in the following list (you don't *need* to convert any other characters):

Characters: `abcdefghijklmnopqrstuvwxyz1234567890` (the input will only either be lowercase letters, or/and a number).

Additionally, you must make the output decodable, so if you have output `0` for input `a`, and somebody inputs `bl`, then the output will be something like `111`. This is not decodable since the program might interpret it as `bbb` or `lb` or `bl`. You might make it decodable by making sure the the number that each character outputs always has a length of 2. Any other way of making sure your output is decodable *is* allowed, but you must explain how one would decode the output in your answer.

Standard loopholes are not allowed. This is code golf, so shortest code wins!

EDIT: By decodable, just to clarify, I mean that you can convert the output back into the input. Your program doesn't need to feature decoding features, only encoding.

# Examples

```
Input    Output
a        00
ab       0001
1        26

```

# Answer
## Pyth, 1 byte

```
C

```

Try it here!

Converts a string to a number

Decode with the following Python code:

```
def decode(x):
    rest, char = divmod(x, 256)
    if rest < 256: return chr(rest)+chr(char)
    return decode(rest)+chr(char)

```
> 4 votes

# Answer
## C ~~69~~ ~~61~~ ~~52~~ 62 Bytes

```
i;char v[99];main(){gets(v);while(v[i])printf("%.3d",v[i++]);}

```

Now taking input from stdin, each character code is 3 digits.

a.exe thisisatest

116104105115105115097116101115116
> 2 votes

# Answer
## Ruby, ~~97~~ ~~37~~ 44 bytes

```
lambda{|s|s.chars.map{|c|c.upcase.ord}.join}

```

Take the ordinal of each character in `s` converted to uppercase (to ensure 2 chars per number for ordinals)
> 1 votes

# Answer
## PowerShell v2+, ~~42~~ 32 bytes

```
-join([char[]]$args[0]|%{$_-38})

```

Takes input `$args[0]`, treats it as a `char`-array, sends it into a loop, and each loop cast the `char` as an `int` (implicit) minus `38`. Those are all encapsulated in parens and `-join`ed into one string. That string is left on the pipeline and printing is implicit.

The lowest ASCII point of `abcdefghijklmnopqrstuvwxyz0123456789` is `0`, with `48`. The highest is `z` with `122`. By subtracting `38` from each code point, we're guaranteed distinct two-digit number for each input character.

### Examples

```
PS C:\Tools\Scripts\golfing> .\convert-string-to-number.ps1 'ab'
5960

PS C:\Tools\Scripts\golfing> .\convert-string-to-number.ps1 'ppcg'
74746165

PS C:\Tools\Scripts\golfing> .\convert-string-to-number.ps1 'error404'
6376767376141014

PS C:\Tools\Scripts\golfing> .\convert-string-to-number.ps1 'abcdefghijklmnopqrstuvwxyz0123456789'
596061626364656667686970717273747576777879808182838410111213141516171819

```
> 1 votes

# Answer
# Bash + coreutils, 20

```
od -vbAn|tr -d ' \n'

```

The index of each character in the ASCII table is given in octal by `od`, which ensures each octal number for each input character is exactly 3 digits long (padded with leading zeros as necessary). `tr` removes the whitespace.

Decoding would be performed by grouping output into groups of 3 digits and then conversion from octal back to ASCII.
> 1 votes

# Answer
# S.I.L.O.S, ~~63~~ ~~60~~ 55 bytes

```
loadLine
b=256
lbla
c=get b
printIntNoLine c
b+1
if c a

```

Prints ASCII value.

Try it online!
> 1 votes

# Answer
# Python 3, 86 bytes

I appear to have misunderstood what the question allows... Either way, this exactly matches the test cases given.

```
print(''.join('%02d'%'abcdefghijklmnopqrstuvwxyz0123456789'.index(i)for i in input()))

```

**Ideone it!**
> 1 votes

# Answer
# GS2, 1 byte

Byte 14, which, in CP437, is .

Try it online!

Decoding is possible: get all matches of the regex `(1..|..)` and map them from decimal ASCII code points to ASCII characters.
> 1 votes

---
Tags: code-golf, conversion
---


title: Variable Prime "Twins"

text:
# Question
Title: Variable Prime "Twins"
I am 2/3 twins with my brother, i.e. born on the same day of the same month but twelve years later. When I was 5, he was 17, both primes; the last pair of ages we can reasonably count on is \[71, 83\] with both of us being alive and able to celebrate this coincidental jubilee.

## Task

Create a code that

* takes two integers as input: the difference between the counter and the "twin" as a positive integer **k** (well yes, I'm the younger) and the upper bound as a positive integer **u** (runtime consideration)
* and gives output as an array or list of all **i** numbers lower than or equal *u* for which both *i* and *i+k* are primes. The output does not need to be sorted.

## Test Cases

```
12, 1000 -> [5, 7, 11, 17, 19, 29, 31, 41, 47, 59, 61, 67, 71, 89, 97, 101, 127, 137, 139, 151, 167, 179, 181, 199, 211, 227, 229, 239, 251, 257, 269, 271, 281, 337, 347, 367, 389, 397, 409, 419, 421, 431, 449, 467, 479, 487, 491, 509, 557, 587, 601, 607, 619, 631, 641, 647, 661, 727, 739, 757, 761, 797, 809, 811, 827, 907, 929, 941, 971, 997]
2, 999 -> [3, 5, 11, 17, 29, 41, 59, 71, 101, 107, 137, 149, 179, 191, 197, 227, 239, 269, 281, 311, 347, 419, 431, 461, 521, 569, 599, 617, 641, 659, 809, 821, 827, 857, 881]
3, 1500 -> [2]
30, 1500 -> [7, 11, 13, 17, 23, 29, 31, 37, 41, 43, 53, 59, 67, 71, 73, 79, 83, 97, 101, 107, 109, 127, 137, 149, 151, 163, 167, 181, 193, 197, 199, 211, 227, 233, 239, 241, 251, 263, 277, 281, 283, 307, 317, 337, 349, 353, 359, 367, 379, 389, 401, 409, 419, 431, 433, 449, 457, 461, 479, 491, 541, 547, 557, 563, 569, 571, 577, 587, 601, 613, 617, 631, 643, 647, 653, 661, 709, 727, 739, 743, 757, 797, 809, 823, 827, 829, 853, 857, 877, 881, 907, 911, 937, 941, 947, 953, 967, 983, 991, 1009, 1019, 1021, 1031, 1033, 1039, 1061, 1063, 1087, 1093, 1123, 1151, 1163, 1171, 1187, 1193, 1201, 1229, 1249, 1259, 1277, 1289, 1291, 1297, 1399, 1409, 1423, 1429, 1451, 1453, 1459, 1481, 1493]

```

## Edit

Since I failed to specify the upper bound, both inclusive and exclusive solutions are welcome.

## Edit No. 2

The challenge ends on 1st September, one week from the start.
Looks like we have a winner but in case of a tie popularity is the tie-breaker; in this case the "second" will be compensated via bounty.

# Answer
# Jelly, ~~8~~ 7 bytes

```
+ÆR©_f®

```

Try it online!

### Explanation

```
+          add the upper bound and the difference
 ÆR        find all primes up to that number
   ©       save that in the register
    _      subtract the difference from each
     f®    remove anything not in the original prime list

```
> 5 votes

# Answer
# Brachylog, ~~27~~ 23 bytes

```
:1f
hS,?tye.:S+:.L*$pL,

```

Try it online!

Verify all testcases.

### Predicate 0 (main predicate)

```
:1f                     Find all solutions of predicate 1
                        given Input as Input,
                        Unify Output with the set of all solutions.

```

### Predicate 1 (auxiliary predicate)

```
hS,?tye.:S+:.L*$pL,

hS                      the first element of Input is S,
   ?tye.                Output is an element between 0 and
                        the last element of Input,
       .:S+:.L          The list [Output+S,Output] is L,
             L*$pL      The product of L, prime-factorized, is still L

```
> 6 votes

# Answer
# 05AB1E, 9 bytes

Code:

```
LDpÏDI+pÏ

```

Uses the **CP-1252** encoding. Try it online!.
> 5 votes

# Answer
## Pyke, 10 bytes

```
S#_PiQ+_P&

```

Try it here!

```
S#         - filter(range(input_2), V) as i
  _P       -   is_prime(i)
         & -  ^ & V
    iQ+    -    i + input_1
       _P  -   is_prime(^)

```

Also 10 bytes:

```
S#_DP.IQ-P

```

Try it here!
> 4 votes

# Answer
# Octave, ~~34~~ 33 bytes

```
@(k,u)(a=primes(u))(isprime(a+k))

```
> 4 votes

# Answer
# MATL, 8 bytes

*Credit to @alephalpha for his approach, which helped me save 3 bytes*

```
Zqti+Zp)

```

Try it online!

```
Zq    % Take input implicitly. Vector of primes up to that. Call this vector A
ti+   % Duplicate, take second input, add element-wise. Call this vector B
Zp    % Vector containing true for prime numbers in B
)     % Use as an index into A. Display implicitly

```
> 4 votes

# Answer
# Python 3, ~~114~~ ~~92~~ 90 bytes

*Thanks to @Dennis for -2 bytes*

```
def f(k,u):
 i=P=1;l={0}
 while i<u+k:l|={P%i*i};P*=i*i;i+=1
 return{i-k for i in l}&l-{0}

```

A function that takes input via argument and returns an unsorted set. This is exclusive with respect to the upper bound.

This uses the method in @xnor's answer here to find primes.

Try it on Ideone

**How it works**

*Prime finding*

We first initialise a test value `i` and a product `P` as `1`, and a list of primes `l` as the set containing `0`. Then, a `while` loop that tests all values of `i` in the range `[1, u+k-1]` for primality is executed. The idea is that by multiplying `P` by `i^2` at the end of each iteration, `P` takes the value `(i-1)!^2` while testing `i`, i.e the product of the integers `[1, i+1]` squared. The actual primality test is then performed by calculating `P mod i`; if this returns zero, then `i` cannot be prime since this implies that `i` is divisible by at least one of the values that make up the product. If this returns `1`, then `i` must be prime since it is not divisible by any of the values in the product. If `i` is prime, it is appended to `l`, and if not, `0` is appended. The squaring of the product prevents false identification of `4` as prime, and is useful here since it guarantees that only `0` or `1` will be returned, allowing the choice of the value to be appended to be made by simply multiplying the result by `i`.

*Identification of 'twin' primes*

We now create a furter set, containing all the elements of `l-k`, element-wise. The intersection of this set and `l` is then found using `&`, which leaves a set containing only the elements common to both sets. A number `i` is only in both sets if both `i` and `i+k` are prime, meaning that this leaves the desired output. However, if `k` is prime, `0` will be present in both sets, meaning that this must be removed before returning.
> 4 votes

# Answer
# R, 98 bytes

```
function(k,u){v=c();for(i in 1:u)if(sum(i%%(1:i)==0)==2&&sum((i+k)%%(1:(i+k))==0)==2){v=c(v,i)};v}

```

**Ungolfed :**

```
function(k,u)
v=c()                                                    #Empty vector

for(i in 1:u)
    if(sum(i%%(1:i)==0)==2&&sum((i+k)%%(1:(i+k))==0)==2) #If both i and i+k only have
                                                         #2 divisors such as the rest of the
                                                         #euclidian division is 0
                                                         #(i.e., they're both prime) :
        v=c(v,i)
v

```
> 3 votes

# Answer
## CJam, 17 bytes

Either as a full program:

```
q~{_mp\W$+mp&},p;

```

Try it online!

Or as an unnamed block:

```
{:X;{_mp\X+mp&},}

```

Try it online!
> 3 votes

# Answer
# Java 7, ~~185~~ 175 bytes

```
import java.util.*;List c(int k,int u){List l=new ArrayList();for(int i=1;++i<u;)if(p(i)&p(i+k))l.add(i);return l;}boolean p(int n){for(int i=2;i<n;)n=n%i++<1?0:n;return n>1;}

```

**Ungolfed & test code:**

Try it here.

```
import java.util.*;
class M{
  static List c(int k, int u){
    List l = new ArrayList();
    for(int i = 1; ++i < u; ){
      if(p(i) & p(i+k)){
        l.add(i);
      }
    }
    return l;
  }

  static boolean p(int n){
    for(int i = 2; i < n; ){
      n = n % i++ < 1
           ? 0
           : n;
    }
    return n>1;
  }

  public static void main(String[] a){
    System.out.println(c(12, 1000));
    System.out.println(c(2, 999));
    System.out.println(c(3, 1500));
    System.out.println(c(30, 1500));
  }
}

```

**Output:**

```
[5, 7, 11, 17, 19, 29, 31, 41, 47, 59, 61, 67, 71, 89, 97, 101, 127, 137, 139, 151, 167, 179, 181, 199, 211, 227, 229, 239, 251, 257, 269, 271, 281, 337, 347, 367, 389, 397, 409, 419, 421, 431, 449, 467, 479, 487, 491, 509, 557, 587, 601, 607, 619, 631, 641, 647, 661, 727, 739, 757, 761, 797, 809, 811, 827, 907, 929, 941, 971, 997]
[3, 5, 11, 17, 29, 41, 59, 71, 101, 107, 137, 149, 179, 191, 197, 227, 239, 269, 281, 311, 347, 419, 431, 461, 521, 569, 599, 617, 641, 659, 809, 821, 827, 857, 881]
[2]
[7, 11, 13, 17, 23, 29, 31, 37, 41, 43, 53, 59, 67, 71, 73, 79, 83, 97, 101, 107, 109, 127, 137, 149, 151, 163, 167, 181, 193, 197, 199, 211, 227, 233, 239, 241, 251, 263, 277, 281, 283, 307, 317, 337, 349, 353, 359, 367, 379, 389, 401, 409, 419, 431, 433, 449, 457, 461, 479, 491, 541, 547, 557, 563, 569, 571, 577, 587, 601, 613, 617, 631, 643, 647, 653, 661, 709, 727, 739, 743, 757, 797, 809, 823, 827, 829, 853, 857, 877, 881, 907, 911, 937, 941, 947, 953, 967, 983, 991, 1009, 1019, 1021, 1031, 1033, 1039, 1061, 1063, 1087, 1093, 1123, 1151, 1163, 1171, 1187, 1193, 1201, 1229, 1249, 1259, 1277, 1289, 1291, 1297, 1399, 1409, 1423, 1429, 1451, 1453, 1459, 1481, 1493]

```
> 2 votes

# Answer
# PARI/GP, 39 bytes

```
k->u->[x|x<-primes([1,u]),isprime(x+k)]

```
> 2 votes

# Answer
# Mathematica, 43 bytes

```
(Prime@Range@PrimePi@#2+#)~Select~PrimeQ-#&

```

Generate all primes less than or equal to the upper bound. Add the difference of ages to the result. Select prime numbers among them. Subtract the difference of ages to the result.
> 2 votes

# Answer
# Swift, 142 bytes

```
func f(a:Int,b:Int)->Array<Int>{let p={(n:Int)->Int in([Int]()+(2..<n)).filter{n%$0<1}.count}
return([Int]()+(2...b)).filter{p($0)+p($0+a)<1}}

```
> 2 votes

# Answer
# Perl 6,  ~~39~~  37 bytes

```
->\k,\u{grep {($_&$_+k).is-prime},2..u}

```

```
->\k,\u{grep {($_&$_+k).is-prime},^u}

```

## Explanation:

```
-> \k, \u {

  # find all the values
  grep

  # where
  {
    # ｢all｣ junction of the two values
    ( $_   &   $_ + k ) # ｢ all( $_, $_ + k ) ｣

    # autothread a method call against the junction
    .is-prime
  },

  # from the values up to (and excluding) ｢u｣
  ^ u # short for ｢ 0 ..^ u ｣
  # for inclusive use ｢ 2 .. u ｣

}

```
> 2 votes

# Answer
# S.I.L.O.S, 205 bytes

```
GOTO b
funce
n = p
p - 1
f = 1
lbla
f * p
f % n
p - 1
if p a
return
lblb
readIO
s = i
readIO
i - 2
lblc
i + 1
p = i
GOSUB e
F = f
p = i
p + s
GOSUB e
F * f
if F g
GOTO h
lblg
printInt i
lblh
i - 2
if i c

```

Try it online!

Primalty test by Wilson's theorem.
> 2 votes

# Answer
## Javascript (ES6), ~~90~~ ~~83~~ ~~80~~ 75 bytes

```
(k,u)=>(r=n=>n++<u+k?r(P[P.every(i=>n%i)*n]=n):P.filter(n=>P[n+k]))(1,P=[])

```

Example:

```
let F =
(k,u)=>(r=n=>n++<u+k?r(P[P.every(i=>n%i)*n]=n):P.filter(n=>P[n+k]))(1,P=[])

console.log(F(2, 999))
```
> 1 votes

# Answer
# Actually, 12 bytes

Input is `u` then `k`. Golfing suggestions welcome. Try it online!

```
╖R`;p@╜+p*`░

```

**Ungolfing:**

```
╖              Store k in register 0.
 R             Range [1..u]
  `       `░   Start a function f and push values i of the range where f(i) is truthy.
   ;p@         Duplicate i, check if i is prime, and swap with the other i.
      ╜+p      Push k, add to i, check if i+k is prime.
         *     Multiply the two if results together.
                 Similar to logical AND. 1 if both are true, else 0.

```
> 1 votes

# Answer
# R, 104 bytes

Unlike the other R solution posted, this one takes input from stdin.

```
s=scan();sapply(1:s[2],function(i){j=i+s[1];if((all(i%%(3:i-1)!=0)|i==2)&all(j%%(3:j-1)!=0))cat(i," ")})

```

Ungolfed:

```
s=scan();        # Read from stdin
sapply(1:s[2],   # For i from 1 to u,
    function(i){     # apply this function:
        j=i+s[1];                # Define i+k
        if((all(i%%(3:i-1)!=0)   # Test if i is prime
           | i==2)               # (i is prime if i==2)
           & all(j%%(3:j-1)!=0)) # Test if i+k is prime
        cat(i," ")               # If i and i+k are prime, print i
    }
)

```
> 1 votes

# Answer
# Pyth, 13 bytes

```
f&P_TP_+ThQSe

```

A program that takes input of a list of the form `[k, u]` and prints a list.

Try it online

**How it works**

```
f&P_TP_+ThQSe  Program. Input: Q
           Se  1-indexed range up to Q[1], yielding [1, 2, 3, ..., u]
f              Filter that, using variable T, by:
  P_T           T is prime
 &              and
     P_+ThQ     T+Q[0], i.e. T+k, is prime
               Implicitly print

```
> 1 votes

---
Tags: code-golf, primes
---