title: Do you know that language?

text:
# Question
Title: Do you know that language?
## Task:

Your challenge is, given previous submissions and itself as input, output the language that they're written in, in the following format:

Say the first program is in Ruby. It must output `1`, because Ruby is the `1`st language used in this challenge. An example program is:

```
a=gets
puts 1

```

When given itself as input, it returns `1`.

The next program might be in Python. It must output `2`, because Python is the `2`nd language used in the challenge. An example program is:

```
print(1 if input()[0]=="a"else 2)

```

Given the first submission, it outputs `1`, and given itself it outputs `2`.

You're allowed to repeat languages, though you're not allowed to submit an answer in the previous answer's language.

For example, if the third program is in Ruby, it must output `1` given the first program and itself (because Ruby is the `1`st language used), and given the second program it must output `2`.

---

## Rules:

* If there are `n` answers currently in the challenge, there must be at least `floor(n / 3)` different languages. Any submission that breaks this rule is disqualified.
* No two "neighbouring answers" (e.g. answer `n` and answer `n+1`) cannot use the same language.
* Different versions of a language do not count as different languages (so `Python 2 == Python 3`).
* Answers must take previous submissions in full as input.
* The first submission must take input.
* You are not allowed to submit multiple answers in a row.
* "Repeat answers" (answers that have the exact same code as a previous submission) are not allowed.
* Answers are not allowed to go over the allocated byte-count of that answer - see "Allocated Byte-count" for more details.

---

## Allocated Byte-count:

For each answer number `n`, the allocated byte-count for that answer is `45 + 5n`.

---

## Answer formatting:

Format your answer like so:

```
# {answer no.}, {language}
{program}
This prints:
- `1` in answer(s) {all answers using 1st language, with links}
- `2` in answer(s) {all answers using 2nd language, with links}
...
{optional explanation}

```

For the answer lists, do this:

```
- `1` in answers [1]({link to answer}), [3]({link to answer})...

```

---

## Scoring:

The first answer to survive after 7 days without any valid submissions after that is declared the winner.

# Answer
> 4 votes
# 26. \>\<\> (language 12), 164 bytes

My first ever program in \>\<\>! It's 156 characters, but 164 bytes in UTF-8.

```
^$|(?![⊂⍴])[⊂-⍴]|\B=|{}
{:}&1+&=?v
      .&0/
v+!?='>'i41i
v+?='y'i47
v+?=' 'i12
v+?=' 'i24
v4
v6
v7
v8
v9
va
  v?(0:i
v1
n;\b1laa*)?+
/"^mwfPes{'tc"i2&01.;

```

This prints:

* `1` with answers , , , , and 14 (Retina).
* `2` with answer  (Brain-Flak).
* `3` with answer  (APL).
* `4` with answers , 12, and 15 (Javascript).
* `5` with answers  and  (R).
* `6` with answers 10, 17, 20, 22, and 25 (Bash).
* `7` with answers 11 and 19 (Mathematica).
* `8` with answer 13 (Python).
* `9` with answer 16 (Perl).
* `10` with answers 18, 21, and 23 (C/C++).
* `11` with answer 24 (Zsh).
* `12` with this answer (\>\<\>).

Try it online!

Explanation:

The first line is simply answer #5. It does nothing but send the instruction pointer to the bottom line. `/` turns the fish right, and the characters `^mwfPes{'tc` are put on the stack. A single character of input is read (`i`). (Let's call this character `C` for exposition.) 2 is put in the register (`2&`). Then we jump to the beginning of the second line (line 1) (`01.`).

This line compares `C` to each character on the stack. A copy of `C` is kept on the bottom of the stack. `{` rotates the stack so `C` is on top; `:` duplicates it; `}` rotates the copy back to the bottom. We increment the register (`&1+&`) until a match is found. (So if `C` is "c", the register holds 3 when the match is found; if `C` is "t", the register holds 4, and so on.) Then we jump to the first character of the line number in the register (`0&.`).

Lines 3 through 13 deal with what to do when `C` is c, t, ', {, etc., respectively. The instruction pointer is moving backwards when we jump; it lands on the first character of the given line, but after a jump it advances a tick before executing, so it begins executing from the end of the line going backward. Each line pushes the appropriate language number on the stack, then sends the fish down to the `n` instruction, which prints it out.

`^` is the most complicated case, because of my own dastardliness with the first line of this answer. Line 13 reads input until EOF. Then it directs down to line 15, which compares the length of the stack (`l`) to 100 (`aa*`). If it is longer (`)?`), we add `+` `b` and `1` to get 12, this language; otherwise, 1 remains on top of the stack.

# Answer
> 25 votes
## 1. Retina, 0 bytes

Try it online!

The empty program prints `1` when given empty input (i.e. itself), because it counts how often the empty regex matches the input (which is always `1+length(input)`).

# Answer
> 13 votes
# 2. Brain-Flak, 22 bytes

```
{<>(())(<>)}{}(<>{}())

```

Try it online!

This checks the top of the stack and puts a one on the opposite stack if it is non-zero. It then increments and returns the opposite stack. This makes it return 1 for the empty program and 2 for anything else.

Since stacks in Brain-Flak default to zero, an empty program will have a zero on the top of the stack while any other program (except programs which end in null characters) will have a truthy value. This means we can run a very simple if program on the input stack.

```
{      (<>)}{}              #If not zero
 <>(())                     #Push one to the other stack
              (<>{}())      #Switch to other stack and increment by one

```

# Answer
> 9 votes
# 3. APL, 7 bytes

```
' {'⍳⊃⍞

```

Explanation:

```
      ⍞  read from the keyboard
     ⊃   first item of list, or space if empty
' {'⍳    index into the string ' {', giving N+1 (=3) if not found

```

# Answer
> 8 votes
# 10. Bash (+coreutils) \[language 6\], ~~44~~, 74 bytes

**Fixed Version** (returns the language id)

```
expr substr "1234151516" $(expr index "365f8dc0eb" `md5sum|cut -c12`) 1 #G

```

Note: this expects the trailing newline, after the input program text

# Answer
> 7 votes
## 9. Retina (language 1), 20 bytes

```
$|}\{|[:'][^]']|,\b1

```

Try it online!

Like plannapus, I decided to go for a rewrite to switch things up a bit, which also ended up shortening the code considerably (a modification of my last answer to account for plannapus's latest would have ended up around 32 bytes, I think).

### Explanation

Like my other answers, this just counts the number of various regex matches, but goes about it much more efficiently:

* `$` matches the end of the string. This always works, even if there's a match going all the way to the end of the string, so this gives us a baseline of `1` for all inputs.
* `}\{` finds a single match in the second program (Brain-Flak), bringing the count there up to `2`. The backslash isn't necessary for escaping but it prevents this part of the regex from matching itself.
* `[:'][^]']` is pretty fancy actually. The only purpose is to count the two `'` in the APL program (language 3) and the three `:` in the JavaScript program (language 4), but we need to prevent this part from matching itself. So we also ensure that the next character is neither `'`, nor `]` (because those don't appear after the ones we *do* want to match, but they do appear in this program here).
* The `'` from the previous part already causes one match in the R programs, so we need three more. The substring `,1` appears in both of them three times, and in no other programs. We match it by adding a tautological wordboundary in between with `,\b1` to prevent it from matching itself again.

# Answer
> 7 votes
# 18. C (language 10), 121 bytes

This is the C89 or C90 standard. It works with either clang or gcc on Try It Online.

```
main(n){char*v=" ^{ s ePfwm",b[999],*c;gets(b);c=strchr(v,*b);n=strlen(b);printf("%d",n?c?c-v:n>99?4:n>60?5:n>15?1:3:1);}

```

This prints:

* `1` with answers , , , , and 14 (Retina).
* `2` with answer  (Brain-Flak).
* `3` with answer  (APL).
* `4` with answers , 12, and 15 (Javascript).
* `5` with answers  and  (R).
* `6` with answers 10 and 17 (Bash).
* `7` with answer 11 (Mathematica).
* `8` with answer 13 (Python).
* `9` with answer 16 (Perl).
* `10` with this answer (C).

Here is a bash driver that runs it with all 18 answers on Try it online!

Ungolfed equivalent (646 bytes):

```
#include <string.h>
#include <stdio.h>
int main(){
    char *v=" ^{ s ePfwm", b[999];
    gets(b); /* buffer overrun if more than 998 characters in the input.
                could be a problem if we get to 191 answers */
    char *c = strchr(v, b[0]); /* Find first character of input in v, or null */
    int n = strlen(b);
    if (!n) {
        printf("1");
    } else if (c) {
        printf("%d", c-v); /* Index of first character of input in v */
    } else if (n > 99) {
        printf("4");
    } else if (n > 60) {
        printf("5");
    } else if (n > 15) {
        printf("1");
    } else {
        printf("3");
    }
    return 0;
}

```

# Answer
> 6 votes
## 5. Retina (language 1), 23 bytes

```
^$|(?![⊂⍴])[⊂-⍴]|\B=|{}

```

Try it online! (Tests all possible inputs.)

Counts the matches of various things in the input:

* `^$` matches the input string, i.e. the first answer once.
* `{}` matches itself, which there are two of in the second program, and one in this one.
* `(?![⊂⍴])[⊂-⍴]` matches characters with code points 8834 to 9076, *exclusive*, which finds three matches in the third program. We use the negative lookahead to avoid the ends of the range being matched in this program.
* `\B=` matches a `=` that *isn't* preceded by a word character. This matches four of the `=` in the fourth program, and doesn't match the `=` in this program.

# Answer
> 5 votes
## 7. Retina (language 1), 27 bytes

```
^$|(?![⊂⍴])[⊂-⍴]|\B=|{}|\b5

```

Try it online! (Tests all possible inputs.)

A minor modification of the fifth answer. `\B=` already finds 4 matches in the sixth answer, and `\b5` finds another without matching any other answers.

# Answer
> 4 votes
# 4, JavaScript (ES6), 32 bytes

```
s=>s?s[0]==`{`?2:s[0]==`s`?4:3:1

```

Outputs 1 for an empty input, 2 if the input starts with a `{`, 4 if it starts with an `s` and 3 otherwise..

# Answer
> 4 votes
# 11. Mathematica \[language 7\], 53 bytes

```
Position[Characters@"^{'sceP",#&@@#][[1,1]]/._@__->1&

```

Unnamed function taking a list of characters as its argument and outputting a positive integer. Simply branches on the first letter of the input, using its position in the string `"^{'sceP"` to decide on the output. This gives the right answer for all previous submissions except the initial empty Retina program and the most recent Retina answer; both of these spit errors, but the output is repaired by the rule `/._@__->1` which transforms any unevaluated function to `1`.

# Answer
> 4 votes
# 16. Perl (language 9), 94 bytes

```
while(<>){print substr("1234151516748149",index("0F=POmS6D4e_XWVH",chr(47+length($_)%70)),1);}

```

Try it online! (checks all answers). Outputs "1234151516748149"

This prints:

* 1 with answers 1, 5, 7, 9 and 14 (Retina).
* 2 with answer 2 (Brain-Flak).
* 3 with answer 3 (APL).
* 4 with answers 4, 12 and 15 (Javascript).
* 5 with answers 6 and 8 (R).
* 6 with answer 10 (Bash).
* 7 with answer 11 (Mathematica).
* 8 with answer 13 (Python).
* 9 with this answer (Perl).

The program checks input length and maps it to the current language distribution.

# Answer
> 3 votes
# 6. R (language 5), 61 bytes

```
cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1))

```

Checks what is the first character of the input and choose output accordingly.

This thus prints:

* `1` with answers  and  (Retina).
* `2` with answer  (Brain-Flak).
* `3` with answer  (APL).
* `4` with answer  (Javascript).
* and `5` with this answer.

Usage:

```
> cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1))

1
> cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1))
{<>(())(<>)}{}(<>{}())
2
> cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1))
' {'⍳⊃⍞
3
> cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1))
s=>s?s[0]==`{`?2:s[0]==`s`?4:3:1
4
> cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1))
^$|(?![⊂⍴])[⊂-⍴]|\B=|{}
1
> cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1))
cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1))
5

```

# Answer
> 3 votes
# 8. R (language 5), 76 bytes

```
c=which(c("","{","'","s","c")==substr(readline(),1,1));ifelse(length(c),c,1)

```

Checks the first letter of the input, and compares it with a vector containing (in that order) the empty string, `{`, `'`, `s` and `c`. It then outputs the index of the match (R indexing is 1-based) or 1 if there is no match.

Same concept as answer n° but prevents answer n° from matching it.

This prints:

* `1` with answers ,  and  (Retina).
* `2` with answer  (Brain-Flak).
* `3` with answer  (APL).
* `4` with answer  (Javascript).
* and `5` with answer  and this answer (R).

If I'm not mistaken, the byte-count allowance for this answer was 94 bytes.

# Answer
> 3 votes
# 12. Javascript (language 4), 117 bytes

Note: I changed a character to correct a mistake in this one.

```
c=>c?c[0]=='e'?6:c[0]=='$'||c[0]=='^'?1:c[0]=='c'&&c.length>80?4:c[0]=='P'?7:c[0]=='c'?5:c[0]=='{'?2:c[0]=='s'?4:3:1;

```

Checks the first letter of the input, if it's c, checks the length of the input.

Outputs:

* 1 for answers 1, 5, 7, 9
* 2 for answer 2
* 3 for answer 3
* 4 for answer 4 and this answer
* 5 for answers 6, 8
* 6 for answer 10
* 7 for answer 11

# Answer
> 3 votes
# 13. Python (language 8), 110 bytes

**Note:** This answer was altered 6 hours after posting, at the recommendation of the OP.

```
from hashlib import*;print("1234151516748"["a5e1f936cd78b".index(sha256(input().encode()).hexdigest()[34])])#N

```

This is the same idea as answer 10 (in bash), but in Python 3. (This approach can work for at most 3 more entries before we run out of hex digits.)

This prints:

* `1` with answers , , , and  (Retina).
* `2` with answer  (Brain-Flak).
* `3` with answer  (APL).
* `4` with answers  and 12 (Javascript).
* `5` with answers  and  (R).
* `6` with answer 10 (Bash).
* `7` with answer 11 (Mathematica).
* `8` for this answer (Python).

Try it online! for: Answer 1, Answer 2, Answer 3, Answer 4, Answer 5, Answer 6, Answer 7, Answer 8, Answer 9, Answer 10, Answer 11, Answer 12, or this answer.

# Answer
> 3 votes
# 24. Zsh (language 11), 142 bytes

My previous answer #18 in C still works unmodified for all the subsequent entries (demo). So let's mix it up a little.

```
typeset -A p
p=("[\$^]*|'\[*" 1 '{*' 2 "' *" 3 '?=>*' 4 'c?[wt]*' 5 'e*' 6 'P*' 7 'f*' 8 'w*' 9 'm*' 10 'ty*' 11)
echo ${p[(k)$1]:-1} #@<`w&X{

```

The purpose of the comment at the end is to match the length of answers 21 and 23, and ensure that no single character of the sha256 or sha384 hashes is unique for every answer so far, using the characters checked by Lyth's C++ answers. ;-)

This prints:

* `1` with answers , , , , and 14 (Retina).
* `2` with answer  (Brain-Flak).
* `3` with answer  (APL).
* `4` with answers , 12, and 15 (Javascript).
* `5` with answers  and  (R).
* `6` with answers 10, 17, 20, and 22 (Bash).
* `7` with answers 11 and 19 (Mathematica).
* `8` with answer 13 (Python).
* `9` with answer 16 (Perl).
* `10` with answers 18, 21, and 23 (C/C++).
* `11` with this answer (Zsh).

Try it online!

# Answer
> 2 votes
## 14. Retina (language 1), 39 bytes

```
'[ ⍳]|}\{|[o@:][^]'c@:]|^c|,\b1|1\d|$

```

Try it online! (Tests all valid inputs.)

# Answer
> 2 votes
# 15. Javascript (language 4), 108 bytes

**Golfed**

```
t=>({24:2,86:3,5:4,73:5,68:5,74:7,4:6,79:4,1:8,67:4})[[...t].reduce((r,c,i)=>r*i^c.charCodeAt(0),0)&0x5F]||1

```

# Answer
> 2 votes
# 17. Bash (+coreutils +openssl) (language 6), 103 bytes

**Golfed**

```
expr substr 69418476151514321 $(expr index 2PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1 #x

```

Uses the same technique as my answer #10, but with *Base64* encoded dictionary, instead of *Hex*.

I've put together the following data file for testing:

```
6 17 expr substr 69418476151514321 $(expr index 2PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1 #x
9 16 while(<>){print substr("1234151516748149",index("0F=POmS6D4e_XWVH",chr(47+length($_)%70)),1);}
4 15 t=>({24:2,86:3,5:4,73:5,68:5,74:7,4:6,79:4,1:8,67:4})[[...t].reduce((r,c,i)=>r*i^c.charCodeAt(0),0)&0x5F]||1
1 14 '[ ⍳]|}\{|[o@:][^]'c@:]|^c|,\b1|1\d|$
8 13 from hashlib import*;print("1234151516748"["a5e1f936cd78b".index(sha256(input().encode()).hexdigest()[34])])#N
4 12 c=>c?c[0]=='e'?6:c[0]=='$'||c[0]=='^'?1:c[0]=='c'&&c.length>80?4:c[0]=='P'?7:c[0]=='c'?5:c[0]=='{'?2:c[0]=='s'?4:3:1;
7 11 Position[Characters@"^{'sceP",#&@@#][[1,1]]/._@__->1&
6 10 expr substr "1234151516" $(expr index "365f8dc0eb" `md5sum|cut -c12`) 1 #G
1 09 $|}\{|[:'][^]']|,\b1
5 08 c=which(c("","{","'","s","c")==substr(readline(),1,1));ifelse(length(c),c,1)
1 07 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{}|\b5
5 06 cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1))
1 05 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{}
4 04 s=>s?s[0]==`{`?2:s[0]==`s`?4:3:1
3 03 ' {'⍳⊃⍞
2 02 {<>(())(<>)}{}(<>{}())
1 01

```

**Test**

```
for i in `seq 17`
do
  echo -n `cat lchain|sed -n $i'{p;q}'|cut -c1`=\>
  cat lchain|sed -n $i'{p;q}'|cut -c6-|\
  expr substr 69418476151514321 $(expr index 2PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1 #x
done

6=>6
9=>9
4=>4
1=>1
8=>8
4=>4
7=>7
6=>6
1=>1
5=>5
1=>1
5=>5
1=>1
4=>4
3=>3
2=>2
1=>1

```

# Answer
> 2 votes
# 19. Mathematica (language 7), 96 bytes

```
Position[ToCharacterCode@StringSplit@";NRU$ Q B [1: =L J, 5% 3 # >",Mod[Length@#,59,33]][[1,1]]&

```

Unnamed function taking a list of characters as input and returning an integer:

* `1` with answers , , , , and 14 (Retina).
* `2` with answer  (Brain-Flak).
* `3` with answer  (APL).
* `4` with answers , 12, and 15 (Javascript).
* `5` with answers  and  (R).
* `6` with answers 10 and 17 (Bash).
* `7` with answer 11 and this answer (Mathematica).
* `8` with answer 13 (Python).
* `9` with answer 16 (Perl).
* `10` with answer 18 (C).

So far all the lengths of answers are distinct, and they're even distinct modulo 59—hence can be detected by which integer in the range 33, 34, ..., 91 they're congruent to (mod 59). These are all printable ASCII characters, encoded by the string `";NRU$ Q B [1: =L J, 5% 3 # >"`; using `ToCharacterCode@StringSplit@` turns this string into a list of ten lists of integers in that range, and `Position[...,Mod[Length@#,59,33]][[1,1]]` finds which of the ten sublists matches the modified length of the input.

# Answer
> 1 votes
# 20. Bash (+coreutils +openssl) (language 6), 121 byte

**Golfed**

```
expr substr 67A69418476151514321 $(expr index 7042PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1| dc -e16i?p #u

```

The same method as my answer #17 (which in turn is based on my original answer #10).

As we have 10 distinct languages now, I've switched to hexadecimal position encoding.

**Data**

```
6 20 expr substr 67A69418476151514321 $(expr index 7042PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1| dc -e16i?p #u
7 19 Position[ToCharacterCode@StringSplit@";NRU$ Q B [1: =L J, 5% 3 # >",Mod[Length@#,59,33]][[1,1]]&
A 18 main(n){char*v=" ^{ s ePfwm",b[999],*c;gets(b);c=strchr(v,*b);n=strlen(b);printf("%d",n?c?c-v:n>99?4:n>60?5:n>15?1:3:1);}
6 17 expr substr 69418476151514321 $(expr index 2PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1 #x
9 16 while(<>){print substr("1234151516748149",index("0F=POmS6D4e_XWVH",chr(47+length($_)%70)),1);}
4 15 t=>({24:2,86:3,5:4,73:5,68:5,74:7,4:6,79:4,1:8,67:4})[[...t].reduce((r,c,i)=>r*i^c.charCodeAt(0),0)&0x5F]||1
1 14 '[ ⍳]|}\{|[o@:][^]'c@:]|^c|,\b1|1\d|$
8 13 from hashlib import*;print("1234151516748"["a5e1f936cd78b".index(sha256(input().encode()).hexdigest()[34])])#N
4 12 c=>c?c[0]=='e'?6:c[0]=='$'||c[0]=='^'?1:c[0]=='c'&&c.length>80?4:c[0]=='P'?7:c[0]=='c'?5:c[0]=='{'?2:c[0]=='s'?4:3:1;
7 11 Position[Characters@"^{'sceP",#&@@#][[1,1]]/._@__->1&
6 10 expr substr "1234151516" $(expr index "365f8dc0eb" `md5sum|cut -c12`) 1 #G
1 09 $|}\{|[:'][^]']|,\b1
5 08 c=which(c("","{","'","s","c")==substr(readline(),1,1));ifelse(length(c),c,1)
1 07 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{}|\b5
5 06 cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1))
1 05 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{}
4 04 s=>s?s[0]==`{`?2:s[0]==`s`?4:3:1
3 03 ' {'⍳⊃⍞
2 02 {<>(())(<>)}{}(<>{}())
1 01

```

**Test (output)**

```
./test
6=>6
7=>7
A=>10
6=>6
9=>9
4=>4
1=>1
8=>8
4=>4
7=>7
6=>6
1=>1
5=>5
1=>1
5=>5
1=>1
4=>4
3=>3
2=>2

```

# Answer
> 1 votes
# 23. C (gcc) (language 10), 142 bytes

```
main(c){int d[256]={0};while((c=getchar())!=EOF)d[c]++;printf("%d",d[88]?9:d[119]?5*d[123]:d[35]?d[38]?7:8-d[96]:d[48]?4:d[60]?2:1+d[158]*2);}

```

Try it online!

* `1` with answers , , , , and 14 (Retina).
* `2` with answer  (Brain-Flak).
* `3` with answer  (APL).
* `4` with answers , 12, and 15 (Javascript).
* `5` with answers  and  (R).
* `6` with answers 10, 17, 20 and 22 (Bash).
* `7` with answer 11 and 19 (Mathematica).
* `8` with answer 13 (Python).
* `9` with answer 16 (Perl).
* `10` with answer 18, 21 and this answer (C).

This program counts number of different characters (in ASCII, so multi-byte UTF-8 characters get split into several entries) and then follows a carefully designed decision tree, basing on the number of occurrences of this or that character.

The decision tree is unchanged from #21 (yay!). I'm not allowed to post exactly same code, so we're back to pure C with minor modifications.

# Answer
> 0 votes
# 21. C++ (gcc) (language 10 as a variant of C), 142 bytes

```
main(){int K,d[256]{0};while((K=getchar())!=EOF)d[K]++;printf("%d",d[88]?9:d[119]?5*d[123]:d[35]?d[38]?7:8-d[96]:d[48]?4:d[60]?2:1+d[158]*2);}

```

Try it online!

* `1` with answers , , , , and 14 (Retina).
* `2` with answer  (Brain-Flak).
* `3` with answer  (APL).
* `4` with answers , 12, and 15 (Javascript).
* `5` with answers  and  (R).
* `6` with answers 10, 17 and 20 (Bash).
* `7` with answer 11 and 19 (Mathematica).
* `8` with answer 13 (Python).
* `9` with answer 16 (Perl).
* `10` with answer 18 and this answer (C).

This program counts number of different characters (in ASCII, so multi-byte UTF-8 characters get split into several entries) and then follows a carefully designed decision tree, basing on the number of occurrences of this or that character.

**Trivia**: letter K was not used until this entry. Letters I, E, Y, j, k, q, z remain unused.

# Answer
> 0 votes
# 22. Bash (+coreutils) \[language 6\], ~~123~~, 131 bytes

EDIT: Published a wrong version at first, should be fixed now.

**Golfed**

```
expr substr 6A67A69418476151514321 $(expr index i3xFepQsAalyIvtqPY7ZN+ \\`openssl sha256 -binary|base64|cut -c10`) 1| dc -e16i?p #L

```

The same technique as my answers #20, #17 and #10.

**Data**

```
6 22 expr substr 6A67A69418476151514321 $(expr index i3xFepQsAalyIvtqPY7ZN+ \\`openssl sha256 -binary|base64|cut -c10`) 1| dc -e16i?p #L
A 21 main(){int K,d[256]{0};while((K=getchar())!=EOF)d[K]++;printf("%d",d[88]?9:d[119]?5*d[123]:d[35]?d[38]?7:8-d[96]:d[48]?4:d[60]?2:1+d[158]*2);}
6 20 expr substr 67A69418476151514321 $(expr index 7042PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1| dc -e16i?p #u
7 19 Position[ToCharacterCode@StringSplit@";NRU$ Q B [1: =L J, 5% 3 # >",Mod[Length@#,59,33]][[1,1]]&
A 18 main(n){char*v=" ^{ s ePfwm",b[999],*c;gets(b);c=strchr(v,*b);n=strlen(b);printf("%d",n?c?c-v:n>99?4:n>60?5:n>15?1:3:1);}
6 17 expr substr 69418476151514321 $(expr index 2PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1 #x
9 16 while(<>){print substr("1234151516748149",index("0F=POmS6D4e_XWVH",chr(47+length($_)%70)),1);}
4 15 t=>({24:2,86:3,5:4,73:5,68:5,74:7,4:6,79:4,1:8,67:4})[[...t].reduce((r,c,i)=>r*i^c.charCodeAt(0),0)&0x5F]||1
1 14 '[ ⍳]|}\{|[o@:][^]'c@:]|^c|,\b1|1\d|$
8 13 from hashlib import*;print("1234151516748"["a5e1f936cd78b".index(sha256(input().encode()).hexdigest()[34])])#N
4 12 c=>c?c[0]=='e'?6:c[0]=='$'||c[0]=='^'?1:c[0]=='c'&&c.length>80?4:c[0]=='P'?7:c[0]=='c'?5:c[0]=='{'?2:c[0]=='s'?4:3:1;
7 11 Position[Characters@"^{'sceP",#&@@#][[1,1]]/._@__->1&
6 10 expr substr "1234151516" $(expr index "365f8dc0eb" `md5sum|cut -c12`) 1 #G
1 09 $|}\{|[:'][^]']|,\b1
5 08 c=which(c("","{","'","s","c")==substr(readline(),1,1));ifelse(length(c),c,1)
1 07 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{}|\b5
5 06 cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1))
1 05 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{}
4 04 s=>s?s[0]==`{`?2:s[0]==`s`?4:3:1
3 03 ' {'⍳⊃⍞
2 02 {<>(())(<>)}{}(<>{}())
1 01

```

**Test Run**

```
./test
6=>6
A=>10
6=>6
7=>7
A=>10
6=>6
9=>9
4=>4
1=>1
8=>8
4=>4
7=>7
6=>6
1=>1
5=>5
1=>1
5=>5
1=>1
4=>4
3=>3
2=>2
1=>1

```

# Answer
> 0 votes
# 25. Bash (language 6), 169 bytes

The same technique as my answers #22, #20, #17 and #10.

Sorry @Qwerp-Derp ! ;) I promise this is the last one :)

**Golfed**

```
{ echo -n 'addsomesalt?';cat; }|expr substr 6BA6A67A69418476151514321 $(expr index 1W0TC4YrKwRGAJupDqn7Xlcog \\`openssl sha256 -binary|base64|cut -c40`) 1| dc -e16i?p #8

```

**Data**

> Note that newlines are encoded as \n for answer #24

```
6 25 { echo -n 'addsomesalt?';cat; }|expr substr 6BA6A67A69418476151514321 $(expr index 1W0TC4YrKwRGAJupDqn7Xlcog \\`openssl sha256 -binary|base64|cut -c40`) 1| dc -e16i?p #8
B 24 typeset -A p\np=("[\$^]*|'\[*" 1 '{*' 2 "' *" 3 '?=>*' 4 'c?[wt]*' 5 'e*' 6 'P*' 7 'f*' 8 'w*' 9 'm*' 10 'ty*' 11)\necho ${p[(k)$1]:-1} #@<`w&X{
A 23 main(c){int d[256]={0};while((c=getchar())!=EOF)d[c]++;printf("%d",d[88]?9:d[119]?5*d[123]:d[35]?d[38]?7:8-d[96]:d[48]?4:d[60]?2:1+d[158]*2);}
6 22 expr substr 6A67A69418476151514321 $(expr index i3xFepQsAalyIvtqPY7ZN+ \\`openssl sha256 -binary|base64|cut -c10`) 1| dc -e16i?p #L
A 21 main(){int K,d[256]{0};while((K=getchar())!=EOF)d[K]++;printf("%d",d[88]?9:d[119]?5*d[123]:d[35]?d[38]?7:8-d[96]:d[48]?4:d[60]?2:1+d[158]*2);}
6 20 expr substr 67A69418476151514321 $(expr index 7042PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1| dc -e16i?p #u
7 19 Position[ToCharacterCode@StringSplit@";NRU$ Q B [1: =L J, 5% 3 # >",Mod[Length@#,59,33]][[1,1]]&
A 18 main(n){char*v=" ^{ s ePfwm",b[999],*c;gets(b);c=strchr(v,*b);n=strlen(b);printf("%d",n?c?c-v:n>99?4:n>60?5:n>15?1:3:1);}
6 17 expr substr 69418476151514321 $(expr index 2PtgBOlrvfDVC8ZHL `openssl md5 -binary|base64|cut -c2`) 1 #x
9 16 while(<>){print substr("1234151516748149",index("0F=POmS6D4e_XWVH",chr(47+length($_)%70)),1);}
4 15 t=>({24:2,86:3,5:4,73:5,68:5,74:7,4:6,79:4,1:8,67:4})[[...t].reduce((r,c,i)=>r*i^c.charCodeAt(0),0)&0x5F]||1
1 14 '[ ⍳]|}\{|[o@:][^]'c@:]|^c|,\b1|1\d|$
8 13 from hashlib import*;print("1234151516748"["a5e1f936cd78b".index(sha256(input().encode()).hexdigest()[34])])#N
4 12 c=>c?c[0]=='e'?6:c[0]=='$'||c[0]=='^'?1:c[0]=='c'&&c.length>80?4:c[0]=='P'?7:c[0]=='c'?5:c[0]=='{'?2:c[0]=='s'?4:3:1;
7 11 Position[Characters@"^{'sceP",#&@@#][[1,1]]/._@__->1&
6 10 expr substr "1234151516" $(expr index "365f8dc0eb" `md5sum|cut -c12`) 1 #G
1 09 $|}\{|[:'][^]']|,\b1
5 08 c=which(c("","{","'","s","c")==substr(readline(),1,1));ifelse(length(c),c,1)
1 07 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{}|\b5
5 06 cat(switch(substr(readline(),1,1),"{"=2,"'"=3,"s"=4,"c"=5,1))
1 05 ^$|(?![⊂⍴])[⊂-⍴]|\B=|{}
4 04 s=>s?s[0]==`{`?2:s[0]==`s`?4:3:1
3 03 ' {'⍳⊃⍞
2 02 {<>(())(<>)}{}(<>{}())
1 01

```

**Test Output**

```
6=>6
B=>11
A=>10
6=>6
A=>10
6=>6
7=>7
A=>10
6=>6
9=>9
4=>4
1=>1
8=>8
4=>4
7=>7
6=>6
1=>1
5=>5
1=>1
5=>5
1=>1
4=>4
3=>3
2=>2
1=>1

```

---
Tags: classification, answer-chaining
---


title: Find the shortest Golomb rulers

text:
# Question
Title: Find the shortest Golomb rulers
Golomb rulers are sets of non-negative integers such that no two pairs of integers in the set are the same distance apart.

For example, `[0, 1, 4, 6]` is a Golomb ruler because all distances between two integers in this set are unique:

```
0, 1 -> distance 1
0, 4 -> distance 4
0, 6 -> distance 6
1, 4 -> distance 3
1, 6 -> distance 5
4, 6 -> distance 2

```

For the sake of simplicity in this challenge (and since translation is trivial), we **impose** that a Golomb ruler **always contains the number `0`** (which the previous example does).

Since this set is of length `4`, we say that this is a Golomb ruler of *order* `4`. The biggest distance in this set (or element, since `0` is always in the set) is `6`, therefore we say that this is a Golomb Ruler of *length* `6`.

## Your task

Find Golomb rulers of *order* `50` to `100` (inclusive) that have as small *lengths* as you can find. The rulers you find need not be optimal (see below).

### Optimality

A Golomb ruler of order `N`, is said to be optimal if there is no other Golomb ruler of order `N` which has a smaller length.

Optimal Golomb rulers are known for orders less than 28, though finding and proving optimality is harder and harder as the order increases.

Therefore, it is not expected that you find the optimal Golomb ruler for any of the orders between `50` and `100` (and even less expected that you can prove they are optimal).

There are no time limits in the execution of your program.

### Baseline

The list below is the list of lengths of Golomb rulers from `50` to `100` (in order) evaluated with a naïve search strategy (Thanks to @PeterTaylor for this list):

```
[4850 5122 5242 5297 5750 5997 6373 6800 6924 7459 7546 7788 8219 8502 8729 8941 9881 10199 10586 10897 11288 11613 11875 12033 12930 13393 14046 14533 14900 15165 15687 15971 16618 17354 17931 18844 19070 19630 19669 20721 21947 22525 23290 23563 23880 24595 24767 25630 26036 26254 27218]

```

The sum of all those lengths is **`734078`**.

### Scoring

Your score will be the sum of the lengths of all your Golomb rulers between `50` and `100`, divided by the sum of the lengths of Golomb rulers between `50` and `100` in the baseline: `734078`.

In case you did not find a Golomb ruler for a specific order, you shall compute your score the same way, using the double of the length in the baseline for that specific order.

The answer with the lowest score wins.

In case of a tie, the lengths of the biggest order where the two answers differ are compared, and the shortest one wins. In case both answers have the same lengths for all orders, then the answer that was posted first wins.

# Answer
## C#, 259421/734078 ~= 0.3534

### Methods

I finally found a more-or-less readable explanation of the projective field method (Singer's method) in *Constructions of Generalised Sidon Sets*, although I still think it can be improved slightly. It turns out to be more similar to the affine field method (Bose's method) than the other papers I read had communicated.

This assumes knowledge of finite fields. Consider \\$q = p^a\\$ is a prime power, and let \\$F(q)\\$ be our base field.

The affine field method works over \\$F(q^2)\\$. Take a generator \\$g\_2\\$ of \\$F(q^2)\\$ and a non-zero element \\$k\\$ of \\$F(q)\\$ and consider the set $$\\{a : g\_2{}^a - k g\_2 \in F\_q\\}$$ Those values form a modular Golomb ruler mod \\$q^2 - 1\\$. Further rulers can be obtained by multiplying modulo \\$q^2 - 1\\$ by any number which is coprime with the modulus.

The projective field method works over \\$F(q^3)\\$. Take a generator \\$g\_3\\$ of \\$F(q^3)\\$ and a non-zero element \\$k\\$ of \\$F(q)\\$ and consider the set $$\\{0\\} \cup \\{a : g\_3{}^a - k g\_3 \in F\_q\\}$$ Those values form a modular Golomb ruler mod \\$q^2 + q + 1\\$. Further rulers can be obtained by modular multiplication in the same way as for the affine field method.

Note that these methods between them give the best known values for every length greater than 16. Tomas Rokicki and Gil Dogon are offering a $250 reward for anyone who beats them for lengths 36 to 40000. Therefore anyone who beats this answer is in for a monetary prize.

### Code

The C# isn't very idiomatic, but I need it to compile with an old version of Mono. Also, despite the argument checking, this is not production quality code. I'm not happy with the types, but I don't think there's a really good solution to that in C#. Maybe in F# or C++ with insane templating.

```
using System;
using System.Collections.Generic;
using System.Linq;

namespace Sandbox {
    class Program {
        static void Main(string[] args) {
            var winners = ComputeRulerRange(50, 100);
            int total = 0;
            for (int i = 50; i <= 100; i++) {
                Console.WriteLine("{0}:\t{1}", i, winners[i][i - 1]);
                total += winners[i][i - 1];
            }
            Console.WriteLine("\t{0}", total);
        }

        static IDictionary<int, int[]> ComputeRulerRange(int min, int max) {
            var best = new Dictionary<int, int[]>();

            var naive = Naive(max);
            for (int i = min; i <= max; i++) best[i] = naive.Take(i).ToArray();

            var finiteFields = FiniteFields(max * 11 / 10).OrderBy(x => x.Size).ToArray();

            // The projective plane method generates rulers of length p^a + 1 for prime powers p^a.
            // We can then look at subrulers for a reasonable range, say down to two prime powers below.
            for (int ppi = 0; ppi < finiteFields.Length; ppi++) {
                // Range under consideration
                var field = finiteFields[ppi];
                int q = field.Size;
                int subFrom = Math.Max(min, ppi >= 2 ? finiteFields[ppi - 2].Size : 1);
                int subTo = Math.Min(max, q + 1);
                if (subTo < subFrom) continue;

                int m = q * q + q + 1;
                foreach (var ruler in ProjectiveRulers(field)) {
                    for (int sub = subFrom; sub <= subTo; sub++) {
                        var subruler = BestSubruler(ruler, sub, m);
                        if (subruler[sub - 1] < best[sub][sub - 1]) best[sub] = subruler;
                    }
                }
            }

            // Similarly for the affine plane method, which generates rulers of length p^a for prime powers p^a
            for (int ppi = 0; ppi < finiteFields.Length; ppi++) {
                // Range under consideration
                var field = finiteFields[ppi];
                int q = field.Size;
                int subFrom = Math.Max(min, ppi >= 2 ? finiteFields[ppi - 2].Size : 1);
                int subTo = Math.Min(max, q);
                if (subTo < subFrom) continue;

                int m = q * q - 1;
                foreach (var ruler in AffineRulers(field)) {
                    for (int sub = subFrom; sub <= subTo; sub++) {
                        var subruler = BestSubruler(ruler, sub, m);
                        if (subruler[sub - 1] < best[sub][sub - 1]) best[sub] = subruler;
                    }
                }
            }

            return best;
        }

        static int[] BestSubruler(int[] ruler, int sub, int m) {
            int[] expand = new int[ruler.Length + sub - 1];
            for (int i = 0; i < ruler.Length; i++) expand[i] = ruler[i];
            for (int i = 0; i < sub - 1; i++) expand[ruler.Length + i] = ruler[i] + m;

            int best = m, bestIdx = -1;
            for (int i = 0; i < ruler.Length; i++) {
                if (expand[i + sub - 1] - expand[i] < best) {
                    best = expand[i + sub - 1] - expand[i];
                    bestIdx = i;
                }
            }

            return expand.Skip(bestIdx).Take(sub).Select(x => x - ruler[bestIdx]).ToArray();
        }

        static IEnumerable<int[]> ProjectiveRulers(FiniteField field) {
            var q = field.Size;
            var fq3 = PowerField.Create(field, 3);
            var m = q * q + q + 1;
            var g = fq3.Generators.First();

            // Define the set T<k> = {0} \union {a \in [q^3-1] : g^a - kg \in F(q)} for 0 != k \in F(q)
            // This could alternatively be T<k> = {0} \union {log_g(b - kg) : b in F(q)} for 0 != k \in F(q)
            // Then T<k> % (q^2 + q + 1) gives a Golomb ruler.
            // For a given generator we seem to get the same ruler for every k.
            var t_k = new HashSet<int>();
            t_k.Add(0);
            var ga = fq3.One;
            for (int a = 1; a < fq3.Size; a++) {
                ga = ga * g;
                if (fq3.Convert(ga + g) < q) t_k.Add(a % m);
            }

            // TODO: optimise by detecting duplicates
            for (int s = 1; s < m; s++) {
                if (Gcd(s, m) == 1) yield return t_k.Select(x => x * s % m).OrderBy(x => x).ToArray();
            }
        }

        static IEnumerable<int[]> AffineRulers(FiniteField field) {
            var q = field.Size;
            var fq2 = PowerField.Create(field, 2);
            var m = q * q - 1;
            var g = fq2.Generators.First();

            // Define the set T<k> = {0} \union {a \in [q^2-1] : g^a - kg \in F(q)} for 0 != k \in F(q)
            // Then T<k> % (q^2 - 1) gives a Golomb ruler.
            var t_k = new HashSet<int>();
            var ga = fq2.One;
            for (int a = 1; a < fq2.Size; a++) {
                ga = ga * g;
                if (fq2.Convert(ga + g) < q) t_k.Add(a % m);
            }

            // TODO: optimise by detecting duplicates
            for (int s = 1; s < m; s++) {
                if (Gcd(s, m) == 1) yield return t_k.Select(x => x * s % m).OrderBy(x => x).ToArray();
            }
        }

        static int Gcd(int a, int b) {
            while (a != 0) {
                var t = b % a;
                b = a;
                a = t;
            }

            return b;
        }

        static int[] Naive(int size) {
            if (size == 0) return new int[0];
            if (size == 1) return new int[] { 0 };

            int[] ruler = new int[size];
            var diffs = new HashSet<int>();
            int i = 1, c = 1;
            while (true) {
                bool valid = true;
                for (int j = 0; j < i; j++) {
                    if (diffs.Contains(c - ruler[j])) { valid = false; break; }
                }

                if (valid) {
                    for (int j = 0; j < i; j++) diffs.Add(c - ruler[j]);
                    ruler[i++] = c;
                    if (i == size) return ruler;
                }

                c++;
            }
        }

        static IEnumerable<FiniteField> FiniteFields(int max) {
            bool[] isComposite = new bool[max + 1];
            for (int p = 2; p < isComposite.Length; p++) {
                if (!isComposite[p]) {
                     FiniteField baseField = new PrimeField(p); yield return baseField;
                    for (int pp = p * p, pow = 2; pp < max; pp *= p, pow++) yield return PowerField.Create(baseField, pow);
                    for (int pq = p * p; pq <= max; pq += p) isComposite[pq] = true;
                }
            }
        }
    }

    public abstract class FiniteField {
        private Lazy<FiniteFieldElement> _Zero;
        private Lazy<FiniteFieldElement> _One;

        public FiniteFieldElement Zero { get { return _Zero.Value; } }
        public FiniteFieldElement One { get { return _One.Value; } }
        public IEnumerable<FiniteFieldElement> Generators {
            get {
                for (int _g = 1; _g < Size; _g++) {
                    int pow = 0;
                    FiniteFieldElement g = Convert(_g), gpow = One;
                    while (true) {
                        pow++;
                        gpow = gpow * g;
                        if (gpow == One) break;
                        if (pow > Size) {
                            throw new Exception("Is this really a field? " + this);
                        }
                    }
                    if (pow == Size - 1) yield return g;
                }
            }
        }

        public abstract int Size { get; }
        internal abstract FiniteFieldElement Convert(int i);
        internal abstract int Convert(FiniteFieldElement f);

        internal abstract bool Eq(FiniteFieldElement a, FiniteFieldElement b);
        internal abstract FiniteFieldElement Negate(FiniteFieldElement a);
        internal abstract FiniteFieldElement Add(FiniteFieldElement a, FiniteFieldElement b);
        internal abstract FiniteFieldElement Mul(FiniteFieldElement a, FiniteFieldElement b);

        protected FiniteField() {
            _Zero = new Lazy<FiniteFieldElement>(() => Convert(0));
            _One = new Lazy<FiniteFieldElement>(() => Convert(1));
        }
    }

    public abstract class FiniteFieldElement {
        internal abstract FiniteField Field { get; }

        public static FiniteFieldElement operator -(FiniteFieldElement a) {
            return a.Field.Negate(a);
        }

        public static FiniteFieldElement operator +(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != b.Field) throw new ArgumentOutOfRangeException("b");
            return a.Field.Add(a, b);
        }

        public static FiniteFieldElement operator *(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != b.Field) throw new ArgumentOutOfRangeException("b");
            return a.Field.Mul(a, b);
        }

        public static bool operator ==(FiniteFieldElement a, FiniteFieldElement b) {
            if (Equals(a, null)) return Equals(b, null);
            else if (Equals(b, null)) return false;

            if (a.Field != b.Field) throw new ArgumentOutOfRangeException("b");
            return a.Field.Eq(a, b);
        }

        public static bool operator !=(FiniteFieldElement a, FiniteFieldElement b) { return !(a == b); }

        public override bool Equals(object obj) {
            return (obj is FiniteFieldElement) && (obj as FiniteFieldElement).Field == Field && this == (obj as FiniteFieldElement);
        }

        public override int GetHashCode() { return Field.Convert(this).GetHashCode(); }

        public override string ToString() { return Field.Convert(this).ToString(); }
    }

    public class PrimeField : FiniteField {
        private readonly int _Prime;
        private readonly PrimeFieldElement[] _Featherweight;

        internal int Prime { get { return _Prime; } }
        public override int Size { get { return _Prime; } }

        public PrimeField(int prime) {
            if (prime < 2) throw new ArgumentOutOfRangeException("prime");

            // TODO A primality test would be nice...

            _Prime = prime;
            _Featherweight = new PrimeFieldElement[Math.Min(prime, 256)];
        }

        internal override FiniteFieldElement Convert(int i) {
            if (i < 0 || i >= _Prime) throw new ArgumentOutOfRangeException("i");
            if (i >= _Featherweight.Length) return new PrimeFieldElement(this, i);
            if (Equals(_Featherweight[i], null)) _Featherweight[i] = new PrimeFieldElement(this, i);
            return _Featherweight[i];
        }

        internal override int Convert(FiniteFieldElement f) {
            if (f == null) throw new ArgumentNullException("f");
            if (f.Field != this) throw new ArgumentOutOfRangeException("f");

            return (f as PrimeFieldElement).Value;
        }

        internal override bool Eq(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            if (b.Field != this) throw new ArgumentOutOfRangeException("b");

            return (a as PrimeFieldElement).Value == (b as PrimeFieldElement).Value;
        }

        internal override FiniteFieldElement Negate(FiniteFieldElement a) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            var fa = a as PrimeFieldElement;
            return fa.Value == 0 ? fa : Convert(_Prime - fa.Value);
        }

        internal override FiniteFieldElement Add(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            if (b.Field != this) throw new ArgumentOutOfRangeException("b");

            return Convert(((a as PrimeFieldElement).Value + (b as PrimeFieldElement).Value) % _Prime);
        }

        internal override FiniteFieldElement Mul(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            if (b.Field != this) throw new ArgumentOutOfRangeException("b");

            return Convert(((a as PrimeFieldElement).Value * (b as PrimeFieldElement).Value) % _Prime);
        }

        public override string ToString() { return string.Format("F({0})", _Prime); }
    }

    internal class PrimeFieldElement : FiniteFieldElement {
        private readonly PrimeField _Field;
        private readonly int _Value;

        internal override FiniteField Field { get { return _Field; } }
        internal int Value { get { return _Value; } }

        internal PrimeFieldElement(PrimeField field, int val) {
            if (field == null) throw new ArgumentNullException("field");
            if (val < 0 || val >= field.Prime) throw new ArgumentOutOfRangeException("val");

            _Field = field;
            _Value = val;
        }
    }

    public class PowerField : FiniteField {
        private readonly FiniteField _BaseField;
        private readonly FiniteFieldElement[] _Polynomial;

        internal FiniteField BaseField { get { return _BaseField; } }
        internal int Power { get { return _Polynomial.Length; } }
        public override int Size { get { return (int)Math.Pow(_BaseField.Size, Power); } }

        public PowerField(FiniteField baseField, FiniteFieldElement[] polynomial) {
            if (baseField == null) throw new ArgumentNullException("baseField");
            if (polynomial == null) throw new ArgumentNullException("polynomial");
            if (polynomial.Length < 2) throw new ArgumentOutOfRangeException("polynomial");
            for (int i = 0; i < polynomial.Length; i++) if (polynomial[i].Field != baseField) throw new ArgumentOutOfRangeException("polynomial[" + i + "]");

            // TODO Check that the polynomial is irreducible over the base field.

            _BaseField = baseField;
            _Polynomial = polynomial.ToArray();
        }

        internal override FiniteFieldElement Convert(int i) {
            if (i < 0 || i >= Size) throw new ArgumentOutOfRangeException("i");

            var vec = new FiniteFieldElement[Power];
            for (int j = 0; j < vec.Length; j++) {
                vec[j] = BaseField.Convert(i % BaseField.Size);
                i /= BaseField.Size;
            }

            return new PowerFieldElement(this, vec);
        }

        internal override int Convert(FiniteFieldElement f) {
            if (f == null) throw new ArgumentNullException("f");
            if (f.Field != this) throw new ArgumentOutOfRangeException("f");

            var pf = f as PowerFieldElement;
            int i = 0;
            for (int j = Power - 1; j >= 0; j--) i = i * BaseField.Size + BaseField.Convert(pf.Value[j]);
            return i;
        }

        internal override bool Eq(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            if (b.Field != this) throw new ArgumentOutOfRangeException("b");

            var fa = a as PowerFieldElement;
            var fb = b as PowerFieldElement;
            for (int i = 0; i < Power; i++) if (fa.Value[i] != fb.Value[i]) return false;
            return true;
        }

        internal override FiniteFieldElement Negate(FiniteFieldElement a) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            return new PowerFieldElement(this, (a as PowerFieldElement).Value.Select(x => -x).ToArray());
        }

        internal override FiniteFieldElement Add(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            if (b.Field != this) throw new ArgumentOutOfRangeException("b");

            var fa = a as PowerFieldElement;
            var fb = b as PowerFieldElement;
            var vec = new FiniteFieldElement[Power];
            for (int i = 0; i < Power; i++) vec[i] = fa.Value[i] + fb.Value[i];
            return new PowerFieldElement(this, vec);
        }

        internal override FiniteFieldElement Mul(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            if (b.Field != this) throw new ArgumentOutOfRangeException("b");

            var fa = a as PowerFieldElement;
            var fb = b as PowerFieldElement;

            // We consider fa and fb as polynomials of a variable x and multiply modulo (x^Power - _Polynomial).
            // But to keep things simple we want to manage the cascading modulo.
            var vec = Enumerable.Repeat(BaseField.Zero, Power).ToArray();
            var fa_xi = fa.Value.ToArray();
            for (int i = 0; i < Power; i++) {
                for (int j = 0; j < Power; j++) vec[j] += fb.Value[i] * fa_xi[j];
                if (i < Power - 1) ShiftLeft(fa_xi);
            }

            return new PowerFieldElement(this, vec);
        }

        private void ShiftLeft(FiniteFieldElement[] vec) {
            FiniteFieldElement head = vec[vec.Length - 1];
            for (int i = vec.Length - 1; i > 0; i--) vec[i] = vec[i - 1] + head * _Polynomial[i];
            vec[0] = head * _Polynomial[0];
        }

        public static FiniteField Create(FiniteField baseField, int power) {
            if (baseField == null) throw new ArgumentNullException("baseField");
            if (power < 2) throw new ArgumentOutOfRangeException("power");

            // Since the field is cyclic, there is only one finite field of a given prime power order (up to isomorphism).
            // For most practical purposes that means that we can pick any arbitrary monic irreducible polynomial.
            // We can abuse PowerField to do polynomial multiplication in the base field.
            var fakeField = new PowerField(baseField, Enumerable.Repeat(baseField.Zero, power).ToArray());
            var excluded = new HashSet<FiniteFieldElement>();
            for (int lpow = 1; lpow <= power / 2; lpow++) {
                int upow = power - lpow;
                // Consider all products of a monic polynomial of order lpow with a monic polynomial of order upow.
                int xl = (int)Math.Pow(baseField.Size, lpow);
                int xu = (int)Math.Pow(baseField.Size, upow);
                for (int i = xl; i < 2 * xl; i++) {
                    var pi = fakeField.Convert(i);
                    for (int j = xu; j < 2 * xu; j++) {
                        var pj = fakeField.Convert(j);
                        excluded.Add(-(pi * pj));
                    }
                }
            }

            for (int p = baseField.Size; true; p++) {
                var pp = fakeField.Convert(p) as PowerFieldElement;
                if (!excluded.Contains(pp)) return new PowerField(baseField, pp.Value.ToArray());
            }
        }

        public override string ToString() {
            var sb = new System.Text.StringBuilder();
            sb.AppendFormat("GF({0}) with primitive polynomial x^{1} ", Size, Power);
            for (int i = Power - 1; i >= 0; i--) sb.AppendFormat("+ {0}x^{1}", _Polynomial[i], i);
            sb.AppendFormat(" over base field ");
            sb.Append(_BaseField);
            return sb.ToString();
        }
    }

    internal class PowerFieldElement : FiniteFieldElement {
        private readonly PowerField _Field;
        private readonly FiniteFieldElement[] _Vector; // The version of Mono I have doesn't include IReadOnlyList<T>

        internal override FiniteField Field { get { return _Field; } }
        internal FiniteFieldElement[] Value { get { return _Vector; } }

        internal PowerFieldElement(PowerField field, params FiniteFieldElement[] vector) {
            if (field == null) throw new ArgumentNullException("field");
            if (vector == null) throw new ArgumentNullException("vector");
            if (vector.Length != field.Power) throw new ArgumentOutOfRangeException("vector");
            for (int i = 0; i < vector.Length; i++) if (vector[i].Field != field.BaseField) throw new ArgumentOutOfRangeException("vector[" + i + "]");

            _Field = field;
            _Vector = vector.ToArray();
        }
    }
}

```

### Results

Unfortunately adding the rulers would take me about 15k characters past the post size limit, so they're on pastebin.
> 8 votes

# Answer
# Python 3, score 603001 / 734078 = 0.82144

Naive search combined with Erdős–Turan construction:

$$2pk + (k^2\bmod p),\\, k \in \[0, p-1\]$$

For odd primes *p* this gives an asymptotically optimal golomb ruler.

```
def isprime(n):
    if n < 2: return False
    if n % 2 == 0: return n == 2
    k = 3
    while k*k <= n:
         if n % k == 0: return False
         k += 2
    return True

rulers = []
ruler = []
d = set()
n = 0
while len(ruler) <= 100:
    order = len(ruler) + 1
    if order > 2 and isprime(order):
        ruler = [2*order*k + k*k%order for k in range(order)]
        d = {a-b for a in ruler for b in ruler if a > b}
        n = max(ruler) + 1
        rulers.append(tuple(ruler))
        continue

    nd = set(n-e for e in ruler)
    if not d & nd:
        ruler.append(n)
        d |= nd
        rulers.append(tuple(ruler))
    n += 1

isuniq = lambda l: len(l) == len(set(l))
isruler = lambda l: isuniq([a-b for a in l for b in l if a > b])

assert all(isruler(r) for r in rulers)

rulers = list(sorted([r for r in rulers if 50 <= len(r) <= 100], key=len))
print(sum(max(r) for r in rulers))

```
> 5 votes

# Answer
# Mathematica, score 276235/734078 \< 0.376302

```
ruzsa[p_, i_] := Module[{g = PrimitiveRoot[p]},
  Table[ChineseRemainder[{t, i PowerMod[g, t, p]}, {p - 1, p}], {t, 1, p - 1}] ]

reducedResidues[m_] := Select[Range@m, CoprimeQ[m, #] &]

rotate[set_, m_] := Mod[set - #, m] & /@ set

scaledRuzsa[p_] := Union @@ Table[ Sort@Mod[a b, p (p - 1)],
  {a, reducedResidues[p (p - 1)]}, {b, rotate[ruzsa[p, 1], p (p - 1)]}]

manyRuzsaSets = Join @@ Table[scaledRuzsa[Prime[n]], {n, 32}];

tryGolomb[set_, k_] := If[Length[set] < k, Nothing, Take[set, k]]

Table[First@MinimalBy[tryGolomb[#, k] & /@ manyRuzsaSets, Max], {k, 50, 100}]

```

The function `ruzsa` implements a construction of a Golobm ruler (also called a Sidon set) found in *Imre Z. Ruzsa. Solving a linear equation in a set of integers. I. Acta Arith., 65(3):259–282, 1993*. Given any prime `p`, this construction yields a Golomb ruler with `p-1` elements contained in the integers modulo `p(p-1)` (that's an even stronger condition than being a Golomb ruler in the integers themselves).

Another advantage of working in the integers modulo `m` is that any Golomb ruler can be rotated (the same constant added to all elements modulo `m`), and scaled (all elements multiplied by the same constant, as long as that constant is relatively prime to `m`), and the result is still a Golomb ruler; sometimes the largest integer is decreased significantly by doing so. So the function `scaledRuzsa` tries all of these scalings and records the results. `manyRuzsaSets` contains the results of doing this construction and scaling for all of the first 32 primes (chosen a bit arbitrarily, but the 32nd prime, 131, is well larger than 100); there are nearly 57,000 Golomb rulers in this set, which takes a good several minutes to compute.

Of course, the first `k` elements of a Golomb ruler themselves form a Golomb ruler. So the function `tryGolomb` looks at such a ruler made from any of the sets computed above. The last line `Table...` selects the best Golomb ruler it can, of every order from `50` to `100`, from all the Golomb rulers found in this way.

The lengths found were:

```
{2241, 2325, 2399, 2578, 2640, 2762, 2833, 2961, 3071, 3151, 3194, 3480, 3533, 3612, 3775, 3917, 4038, 4150, 4237, 4368, 4481, 4563, 4729, 4974, 5111, 5155, 5297, 5504, 5583, 5707, 5839, 6077, 6229, 6480, 6611, 6672, 6913, 6946, 7025, 7694, 7757, 7812, 7969, 8139, 8346, 8407, 8678, 8693, 9028, 9215, 9336}

```

I was originally going to combine this with two other constructions, those of Singer and of Bose; but it seems that Peter Taylor's answer has already implemented this, so presumably I would simply recover those lengths.
> 3 votes

---
Tags: math, code-challenge, number, number-theory
---


title: The meta-polyglot quine

text:
# Question
Title: The meta-polyglot quine
In my time on PPCG, I've noticed that quine problems and polyglot problems are quite popular. Also, meta-solutions to problems, that is, scripts which generate a program which is the solution to a problem, tend to get a lot of positive feedback from the community. Therefore, I have created this challenge, which implements these three ideas.

Your task then, reader and enthusiast, is to create as short as possible a script which can run in two languages A and B to generate quines for A and B. When your program is run in language A, it should generate a program that is a quine in language B **but not in language A** and vice versa. The languages A and B can be different version of the same language, provided you keep in mind that the generated quines should only work in one of the versions.
Keep in mind that the standard loopholes should be considered closed and only proper quines are allowed.
Good luck, fewest characters wins!

# Answer
> 5 votes
# CJam 0.6.6 dev / GolfScript, ~~15~~ ~~14~~ 12 bytes

```
"0$p"0$~a:n;

```

*Thanks to @jimmy23013 for golfing off 2 bytes!*

Rest to be updated.

### Verification

Since the submission involves significant whitespace, it's best to compare hexdumps.

```
$ xxd -g 1 mpquine
0000000: 22 60 30 24 7e 22 30 24 7e 4e 4d 3a 6e 3b        "`0$~"0$~NM:n;
$
$ cjam mpquine | tee quine.gs | xxd -g 1
0000000: 22 60 30 24 7e 22 60 30 24 7e 0a                 "`0$~"`0$~.
$ golfscript quine.gs | xxd -g 1
0000000: 22 60 30 24 7e 22 60 30 24 7e 0a                 "`0$~"`0$~.
$ cjam quine.gs | xxd -g 1
0000000: 22 60 30 24 7e 22 60 30 24 7e                    "`0$~"`0$~
$
$ golfscript mpquine | tee quine.cjam | xxd -g 1
0000000: 22 60 30 24 7e 22 60 30 24 7e                    "`0$~"`0$~
$ cjam quine.cjam | xxd -g 1
0000000: 22 60 30 24 7e 22 60 30 24 7e                    "`0$~"`0$~
$ golfscript quine.cjam | xxd -g 1
0000000: 22 60 30 24 7e 22 60 30 24 7e 0a                 "`0$~"`0$~.

```

## CJam

CJam prints `"`0$~"0$~` and a trailing linefeed. Try it online!

The generated program prints `"`0$~"0$~` with the trailing linefeed in GolfScript (Try it online!), but without the linefeed in CJam (Try it online!).

### How the metaquine works

```
"`0$~"         e# Push that string on the stack.
      0$~      e# Push a copy and evaluate it:
               e#   `     Inspect the string, pushing "\"`0$~\"".
               e#    0$   Push a copy.
               e#      ~  Evaluate, pushing "`0$~".
               e# Both "\"`0$~\"" and "`0$~" are now on the stack.
         NM    e# Push "\n" and "".
           :n; e# Map print over the elements of "" (none) and pop the result.
               e# "\"`0$~\"", "`0$~", and "\n" are now on the stack, and the
               e# characters they represent will be printed implicitly.

```

### How the quine works

```
"`0$~"          # Push that string on the stack.
      0$~       # As in CJam.
         <LF>   # Does nothing.
                # "\"`0$~\"" and "`0$~" are now on the stack, and the characters
                # they represent will be printed implicitly, plus a linefeed.

```

Unlike GolfScript, CJam doesn't print a trailing linefeed by default, so this is not a quine in CJam.

## GolfScript

GolfScript prints `"`0$~"0$~`, without trailing whitespace. Try it online!

The generated program prints `"`0$~"0$~` without trailing whitespace in CJam (Try it online!), but GolfScript appends a linefeed (Try it online!).

### How the metaquine works

```
"`0$~"0$~       # As in CJam.
         NM     # Unrecognized token. Does nothing.
           :n   # Store the top of the stack – "`0$~" – in the variable n. n holds
                # "\n" by default. When the program finishes, the interpreter
                # prints n implicitly, usually resulting in a trailing linefeed.
                # By redefining n, it will print "0$~" instead.
             ;  # Pop the string from the stack so it won't be printed twice.

```

### How the quine works

```
"`0$~"0$~      e# Works as in GolfScript.

```

Unlike CJam, GolfScript will append a linefeed to the contents of the stack, so this is not a quine in GolfScript.

# Answer
> 8 votes
## CJam / Fission, 22 bytes

```
"'!+OR'")5-"{'_'~}_~";

```

Try it in CJam. Try it in Fission.

In CJam, this prints the standard Fission quine:

```
'!+OR"

```

Try the Fission quine.

In Fission, this prints a `"`-less variant of the standard CJam quine:

```
{'_'~}_~

```

Try the CJam quine.

This also works for 22 bytes (printing the same quines):

```
"& *NQ!":)R"{'_'~}_~";

```

### Explanation

In CJam:

```
"'!+OR'"    e# Push this string.
)           e# Pull off the last character.
5-          e# Subtract 5, turning ' into ".
"{'_'~}_~"  e# Push this string.
;           e# And discard it again.

```

So at the end of the program, the stack contains the string `"'!+OR"` and the character `"`, both of which are implicitly printed.

In Fission, program flow starts at the `R` with a right-going atom. `'"` just changes the atoms mass, `)`, `5` and `-` are ignored for various reasons. Then the atom enters print mode at the `"` and prints `{'_'~}_~`. `;` destroys the atom and terminates the program.

# Answer
> 6 votes
# Clojure / Common Lisp, 274 bytes

```
(defmacro t []"((fn [s] (print (list s (list (quote quote) s)))) (quote (fn [s] (print (list s (list (quote quote) s))))))")(if '()(print(let[s clojure.string/replace](.toUpperCase(s(s(s(s(s(t)"fn""lambda")"[s]""(s)")"(quote ""'")"e)""e")")))))""))))"))))(eval '(princ(t))))

```

Some spaces added for readability

```
(defmacro t []"((fn [s] (print (list s (list (quote quote) s))))
     (quote (fn [s] (print (list s (list (quote quote) s))))))")
(if '()(print(let[s clojure.string/replace](.toUpperCase
    (s(s(s(s(s(t)"fn""lambda")"[s]""(s)")"(quote ""'")"e)""e")")))))""))))"))))
    (eval '(princ(t))))

```

Basically defines a macro which returns a quine in Clojure. Clojure requires parameters for macro definition provided as vector (`[]`) whereas Common Lisp (thankfully) just ignores it. After that we differ 2 languages by evaluating `'()` which equals to `nil` and thus falsey in Common Lisp and is `true` in Clojure. Then we do string manipulations using Clojure which Common Lisp doesn't even try to evaluate as it goes in another `if` branch. Clojure on the other hand tries to check if another branch is at least correct before executing so had to use `eval` there to both be correct in Clojure and output correct string in Common Lisp.

Note: just returning two different string might probably be shorter but then it won't be different to a polyglot challenges about outputing different strings in different languages. ¯\\\_(ツ)\_/¯

Clojure original source run: https://ideone.com/SiQhPf

Common Lisp original source run: https://ideone.com/huLcty

Clojure output : `((LAMBDA (S) (PRINT (LIST S (LIST 'QUOTE S)))) '(LAMBDA (S) (PRINT (LIST S (LIST 'QUOTE S)))))`

Common Lisp output : `((fn [s] (print (list s (list (quote quote) s)))) (quote (fn [s] (print (list s (list (quote quote) s))))))`

Clojure output run in Common Lisp: https://ideone.com/T1DF7H

Vice versa: https://ideone.com/Fezayq

# Answer
> 4 votes
# Jelly / GolfScript, ~~18~~ 16 bytes

```
0000000: 3a 6e 22 ff cc cc 22 7d 7f fe 22 3a 6e 60 ff 3b  :n"..."}..":n`.;

```

### Verification

Testing all involved programs with the exact byte streams can only be done locally.

```
$ LANG=en_US # Latin-1. Jelly doesn't care about the exact encoding,
$            # as longs as it's not UTF-8.
$
$ xxd -g 1 mpquine
0000000: 3a 6e 22 ff cc cc 22 7d 7f fe 22 3a 6e 60 ff 3b  :n"..."}..":n`.;
$
$ jelly f mpquine | tee quine.gs | xxd -g 1
0000000: 22 3a 6e 60 22 3a 6e 60                          ":n`":n`
$ golfscript quine.gs | xxd -g 1
0000000: 22 3a 6e 60 22 3a 6e 60                          ":n`":n`
$ jelly f quine.gs 2> /dev/null | xxd -g 1
$
$ golfscript mpquine | tee quine.jelly | xxd -g 1
0000000: ff cc cc                                         ...
$ jelly f quine.jelly | xxd -g 1
0000000: ff cc cc                                         ...
$ golfscript quine.jelly | xxd -g 1
0000000: 0a

```

## Jelly

With Jelly's code page, the program looks as follows.

```
:n"”ṘṘ"}
“":n`”;

```

This prints (Try it online!)

```
":n`":n`

```

which is a quine in GolfScript (Try it online!), but a parser error in Jelly (Try it online!).

## GolfScript

In Latin-1, the program looks as follows, with an unprintable DEL character between `}` and `þ`.

```
:n"ÿÌÌ"} þ":n`ÿ;

```

This prints (Try it online!)

```
ÿÌÌ

```

or, visualized with Jelly's code page,

```
”ṘṘ

```

which is a quine in Jelly (Try it online!), but only prints a linefeed in GolfScript (Try it online!).

# Answer
> 3 votes
# JavaScript / C 278 bytes

At a staggering 278 bytes:

```
//\
console.log('int main(){char*A="int main(){char*A=%c%s%c;printf(A,34,A,34);}";printf(A,34,A,34);}');/*
int main(){puts("A='A=;B=String.fromCharCode(39);console.log(A.slice(0,2)+B+A+B+A.slice(2));';B=String.fromCharCode(39);console.log(A.slice(0,2)+B+A+B+A.slice(2));");}//*/

```

The C quine:

`int main(){char*A="int main(){char*A=%c%s%c;printf(A,34,A,34);}";printf(A,34,A,34);}`

The JavaScript quine:

`A='A=;B=String.fromCharCode(39);console.log(A.slice(0,2)+B+A+B+A.slice(2));';B=String.fromCharCode(39);console.log(A.slice(0,2)+B+A+B+A.slice(2));`

# Answer
> 3 votes
# Befunge / Fission, 35 bytes

```
"$TQ-#'">,#-:#2_@;"+1_@#`+66:,g0:"L

```

Try it in Befunge | Try it in Fission

In Befunge this produces the Fission quine:

```
'!+OR"

```

In Fission this produces the Befunge quine:

```
:0g,:66+`#@_1+

```

# Answer
> 1 votes
# Python / Retina, ~~70~~ ~~65~~ ~~64~~ 66 bytes

I used the same strategy I used in my previous Python / Retina polyglot.

```
#
print"\nS`((.+))"*2+"\n\n"
#?
#_='_=%r;%_\n';_
#?;
#;print _%
#

```

**Try in Python** | **Try in Retina**

`#` is a comment in Python, so it simply prints the Retina quine in Python. In Retina, the first stage (2 lines) does nothing, because no `#` will be found in the input. The next stage replaces nothing with the basis of the Python quine. The third stage replaces each semicolon with the `#print _%` piece. The last stage removes all `#`'s.

---

**Quine in Retina:**

```

S`((.+))
S`((.+))

```

**Quine in Python:**

```
_='_=%r;print _%%_\n';print _%_

```

The quines used may be seen in this challenge. The Retina quine is an error in Python, and the Python quine has no output in Retina.

# Answer
> 1 votes
# Python 3 / Python 2, 62 bytes

```
_='_=%r;print(_%%_['+'~'*-~int(-1/2)+'int(-1/2):])';print(_%_)

```

Try it in Python 2, Python 3.

Based on the Python quine here. The distinguishing factor between the two versions is what they do with `int(-1/2)`: in Python 2, `/` is integer division (rounding down), with a result of `-1`; in Python 3, `/` is floating point division (`-0.5`), which `int` truncates to `0`.

We build a string `_` in three parts. `'_=%r;print(_%%_['` and `'int(-1/2):])'` are always the same. The interesting part is `'~'*-~int(-1/2)`:

* In Python 2, `-~int(-1/2)` is `0`, and the tilde is not added to the string;
* In Python 3, `-~int(-1/2)` is `1`, and the tilde is added to the string.

Thus, Python 2 outputs the Python 3 quine

```
_='_=%r;print(_%%_[int(-1/2):])';print(_%_[int(-1/2):])

```

and Python 3 outputs the Python 2 quine

```
_='_=%r;print(_%%_[~int(-1/2):])';print(_%_[~int(-1/2):])

```

In each version, the expression inside `[ :]` evaluates to `0`, which makes the slice include the entire string, whereas in the wrong language it evaluates to `-1`, which makes the slice include only the last character, truncating the output so it's not a full quine.

# Answer
> 1 votes
# Brain-Flak, brainfuck ~~4617~~ 4009 bytes

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

```

Try it online!

Try it online!

Explanation is on its way I am still golfing this

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


title: Lever Simulator 2015

text:
# Question
Title: Lever Simulator 2015
### Why a Simulator?

Kids these days don't have the time nor the ambition to actually go and stack boxes on the see-saw or play around with balancing physical objects. This leaves lots of room in the software market for a Lever Simulator which will, according to my models, sell like mad!

### Programming Help Wanted

I've filed the patent for such a game (pending), but need an expert programmer to write the game-logic for me. From my understanding, it is standard practice to compensate programmers based on the **size in bytes** of the final program. As such I will be awarding this lucrative contract to the lowest bidder.

### Specification

A lever is a series of boxes or empty spaces that is balanced by a fulcrum. Each box has a particular weight **one** through **nine** and spaces have no weight. As you know, a box's weight on the lever is directly proportional to how far that box is from the fulcrum. A box of weight `4` that is on the third space from the fulcrum will contribute `12` effective units of force to that side of the lever.

I need a program that, given an input lever, will output whether the lever will skew toward the left, the right, or be perfectly balanced.

### I/O Guidelines

* You will write for me a program.
* The input will contain one line of text.
* The input will come from `stdin` or as one command-line string.
* Boxes will represented by the characters '`1`' through '`9`'. These characters represent their respective weights. An empty space will be represented by a space ''. The fulcrum will be represented by a caret '`^`'.

A sample input lever could look like: `8 2^ 941`

This lever is perfectly balanced: `(4*8) + 0 + 0 + (1*2) == 0 + (2*9) + (3*4) + (4*1) == 34`

* There will be no leading nor trailing spaces. There will be no trailing newline.
* No need to handle malformed input, input will always have exactly one fulcrum, and only numbers and spaces.
* The output will indicate whether the lever is left-heavy, right-heavy, or balanced.
* Your program must have exactly 3 possible outputs that could result from a well-formed input. You can choose what these are.
* The output must either be print to `stdout` or be the return code of the program.

### Test cases

Here I use `L`,`R`,`B` to mean left-heavy, right-heavy, balanced:

1. Input: `11 ^9` Output: `B`
2. Input: `321^ 12` Output: `L`
3. Input: `9^ 1` Output: `R`

(If anyone has some "trickier" test cases, feel free to edit them in).

### Bibliography

Not-necessarily-inspired-by, but related to Balance a set of weights on a seesaw

# Answer
> 7 votes
## Python 2, 69 bytes

```
lambda s:cmp(sum(ord(c)%16*(i-s.find('^'))for i,c in enumerate(s)),0)

```

The modulus `ord(c)%16` extracts the value of a digit character while getting 0 for space. For each character, its torque contribution is computed as its weight times the signed distance to the pivot `i-s.find('^')`, and these are summed and compared to 0, producing one of `-1,0,1`. The character `^` is computed to have weight 14, but that doesn't matter because it's on the pivot.

An 18-byte Pyth port by Maltysen:

```
._s.e*-kxz\^%Cb16z

```

For the Python code, if a full program is required, here's 79 bytes. The idea is to start the index `i` shifted by `s.find('^')`, and have it count down.

```
s=raw_input()
t=0;i=s.find('^')
for c in s:t-=ord(c)%16*i;i-=1
print cmp(t,0)

```

# Answer
> 16 votes
# Javascript ES6, 62 Bytes

```
s=>Math.sign([...s].reduce((p,c,i)=>p+~~c*(i-s.indexOf`^`),0))

```
* `-1` if left is heavier
* `0` if balanced
* `1` if right is heavier

Ungolfed:

```
s=>
  Math.sign(                     // output sign of weight of lever
    [...s].reduce((p,c,i)=>      // split and reduce input
      p+~~c*(i-s.indexOf`^`),0)) // add weights of all elements
                                 //   (elements left of pivot are negatively weighted)

```

Test runs (assigning anonymous function to `f`):

```
>> f("11   ^9")
<< 0

>> f("321^  12")
<< -1

>> f("9^         1")
<< 1

```

---

* **-11 bytes:** changed output from `R B L` to `-1 0 1`
* **-3 bytes:** changed `e.split``` to `[...e]` (thanks @Vɪʜᴀɴ)
* **-33 bytes:** changed algorithm to use negative weights rather than splitting at pivot
* **-9 bytes:** removed pivot check (apparently, `~~'^'` evaluates to `0`...)
* **-2 bytes:** made function anonymous (thanks @cᴏɴᴏʀ-obʀɪᴇɴ)

# Answer
> 5 votes
## APL, ~~39~~ 30 bytes

```
{×+/(10|⍵⍳⍨∊⍕¨⍳9)×(⍳⍴⍵)-⍵⍳'^'}

```

After rereading the rules, I've changed this to output `-1` `0` `1` instead of `L` `B` `R`, saving nine bytes.

Try it here.

# Answer
> 5 votes
# Japt, 22 bytes

**Japt** is a shortened version of **Ja**vaScri**pt**. Interpreter

```
U¬r@X+~~Y*(Z-Ub'^),0 g

```

Returns `-1` for `L`, `0` for `B`, and `1` for `R`.

### How it works

```
Uq r@X+~~Y*(Z-Ub'^),0 g
                         // Implicit: U = input string
Uq r@              ,0    // Reduce the input by this function, starting at 0:
     X+~~Y*              //  Return the previous value, plus the current value times
           (Z-Ub'^)      //   the current index minus the index of "^" in U.
                      g  // Take the sign of the resulting number.
                         // Implicit: output last expression

```

# Answer
> 4 votes
## Haskell, ~~116~~ ~~96~~ ~~82~~ 76 bytes

```
 f x=signum$sum$zipWith(*)[-length(fst$span(<'^')x)..]$(`mod`16).fromEnum<$>x

```

Output is `0` for balanced, `-1` for left-heavy and `1` for right-heavy.

Usage example: `f "321^ 12"` -\> `-1`

How it works: find the part before the `^`. Multiply the input string and the list of weights which starts at `- length-of-first-part`. The `^` has a weight of 0 and doesn't add to the sum. I'm using @xnor's mod 16 trick to convert digits/spaces to integer values. If the sum is negative (positive), the lever is left-heavy (right-heavy) and balanced if the sum is 0.

# Answer
> 4 votes
# TeaScript, 23 bytes ~~25~~

I tried writing a Pyth answer but that went horribly :\

```
$²xd»l+~~i*(a-xi`^`),0©

```

That `²` looks so out of place but it saves 1 byte, so I'll be keeping it.

Try it online!

Test all cases

For the output scheme I've chosen:

* `-1` if Left is heavier than Right (`L`)
* `0` if Left is as heavy as Right (`B`)
* `1` is Left is less heavy than Right (`R`)

### Ungolfed && Explanation

This uses maps and reduces to get the job done.

```
$C(xd(#l+~~i*(a-xi`^`),0))

              // Implicit: x = input
$C(           // Compare...
  xd(#        // Reduce...
    l+          // Pending weight...
    ~~i         // Current weight -> int times...
    (a-         // Total length minus...
    xi`^`       // Fulcrum location
  ,0)
)             // Implicit: Output result

```

# Answer
> 4 votes
# Pyth, 20 bytes

```
._s*V-Rxz\^Uzm.xsd0z

```

Test suite

`-1` for left-biased, `0` for balanced, `1` for right-biased.

How it works:

```
._s*V-Rxz\^Uzm.xsd0z
                        z = input()
                        Weights:
             m     z    Map over z
              .x        try:
                sd           cast charater to int
                  0     except: 0
                        Lever arm:
           Uz           range(len(input()))
     -Rxz\^             Subtract index of caret from each value.
   *V                   Vectorized multiplication.
  s                     Sum.
._                      Take sign and print.

```

# Answer
> 4 votes
# pb, ~~349~~ 329 bytes

```
^w[B!94]{>}w[B!0]{vb[T]^t[T+1]>}vb[46]<w[B!0]{<}b[1]vvb[46]^^t[X]w[X!0]{<b[T-X]}^w[B!0]{w[B=32]{b[48]}>}w[X!0]{<t[B-48]vb[B*T]^}w[B!0]{vt[B]vb[1]>^w[B!46]{>}vvb[B+T]^w[B=0]{<}b[0]^b[0]^>}vb[0]vvt[B]<w[B!0]{<}t[B+T]^>[T]w[X!0]{b[10]<}<[T]w[X!0]{b[16]>}vw[B=0]{>}t[B]b[0]w[B=0]{>}t[T-B]b[0]^<[X-T]t[B]<[X]>w[B!0]{b[0]>}<[X]^b[T+66]

```

This was a tricky one. pb was not designed to be good at this kind of thing. ~~It doesn't even have *multiplication*.~~ But hey, it works.

> **Ed. note:** Did I just say pb has no multiplication? What? pb definitely definitely has multiplication. I *designed and implemented* this language, I should know that it has multiplication built in and I don't have to do some silly looped addition. Fixing that (as well as doing some creative rearranging now that I could approach that part of the problem from \[almost literally\] a different angle) saves me 20 bytes. Embarrassing.

The hardest part was, after getting the sums of (weight\*distance) for each side, actually determining which letter to print. pb doesn't have `>` or `<` operators, just `==` and `!=`. There's no easy way to tell which value is larger. I can't even subtract and compare with 0... unless I do something really silly.

* Find the sum of the two sums.
* Go that far to the right, on a line that's not being used for anything.
* Until reaching X=0, go left and place 'L's.
* Place a 'B' at X=0.
* Go left by the sum of the two sums.
* Until reaching X=0, go right and place 'R's.

Then, you simply go to X=(left side - right side), and there's your answer! Delete everything on that line to clean up, and then print the value that was found at (0, 0).

...But there's a slightly shorter way. Instead of using 'L', 'B' and 'R', use those values - 'B' and add 'B' back on when printing. That way, you don't ever have to place 'B' at X=0, you just leave it as the 0 it already was. The only problem is that once you do this, the program becomes very goofy in watch mode. `'L'-'B'==76-66==10=='\n'`. Everything seems to be working fine, until suddenly a huge number of newlines are printed and it's impossible to keep track of what's going on :D In pbi's regular execution mode, though, everything works fine because the newlines are deleted before anything is printed to the console.

```
^w[B!94]{>}                 # Find the fulcrum

w[B!0]{                     # Starting at the fulcrum and going right:
    vb[T]^                    # Store the T below each character of input
    t[T+1]                    # Increment T
    >
}

vb[46]                      # Put a '.' at the end of the values below the input

<w[B!0]{<}                  # Go to the space below the fulcrum
b[1]                        # Put a 1 (So the fulcrum will be represented as '.' later)
vvb[46]^^                   # Put a 46 two spaces below it

t[X]                        # Store the current X value in T
w[X!0]{<                    # Until reaching the beginning of the input:
    b[T-X]                    # Put T - (the current X value) below each byte
}

^w[B!0]{                    # For each byte of input:
    w[B=32]{b[48]}            # Set spaces to '0'
    >
}

w[X!0]{<                    # For each byte of input:
    t[B-48]                   # Set T to the value of the number (fulcrum becomes '.')
    vb[B*T]^                  # Multiply the value below by T
}

# This has nothing to do with the input, except that it's the right length:
w[B!0]{                     # For every byte of input:
    v                         # Go to the value below it
    t[B]                      # Store it in T
    vb[1]>^                   # Put a flag below it
    w[B!46]{>}                # Go to the next '.' value
    vvb[B+T]                  # Add T to whatever is two spaces below the '.'
                              # This will cause the sum for the right side of
                              # the fulcrum to be 46 too high. This is why 46
                              # was left below the fulcrum earlier: both sums
                              # will be off by the same amount.
    ^w[B=0]{<}                # Go back to the flag
    b[0]^b[0]                 # Erase the flag and the value above it
    ^>
}

vb[0]                       # Erase the stray '.'
vvt[B]<w[B!0]{<}t[B+T]      # Get the sum of the two sums
^>[T]                       # Go right that far
w[X!0]{b[10]<}              # Head back to X=0, leaving 'L'-'B' the whole way
<[T]                        # Go left the same amount as before
w[X!0]{b[16]>}              # Head back to X=0, leaving 'R'-'B' the whole way
vw[B=0]{>}                  # Find the sum from left of the fulcrum
t[B]b[0]                    # Save it to T and erase it from the canvas
w[B=0]{>}                   # Find the other sum
t[T-B]b[0]                  # Subtract it from T and erase it from the canvas
^<[X-T]                     # On the line that was just prepared, go to X=T
t[B]                        # Save the value of that space to T
<[X]>w[B!0]{b[0]>}          # Erase the entire visible part of that line
<[X]^b[T+66]                # Print (the value read from that line)+'B' at (0, 0)

```

# Answer
> 3 votes
# , 22 chars / 38 bytes

```
МŴ⟬ïĊ⇀$+˜_*(ã-ïÿ⍘^),0⸩

```

`Try it here (Firefox only).`

# Answer
> 3 votes
## Perl 5, 72 bytes

```
@_=split//,<>;($i)=grep$_[$_]eq'^',0..@_;$j+=$_*($k++-$i)for@_;say$j<=>0

```

# Answer
> 3 votes
# ~~MATLAB 91, 57, 55~~ Octave, 50 bytes

I did not expect to golf this further, but switching to Octave made it possible to save 5 additional bytes! Wow, this one took time...

```
@(x)(s=mod(+x,16))*[1-(i=find(s>9)):nnz(x)-i]'*inf

```

It outputs `-Inf, NaN, Inf` for `L, B, R` respectively.

**Test suite!**

**Explanation:**

This is definitely a hard-to-read code, but I'll try to explain as well as I can. I will switch between code block explanation and text.

```
@(x)                 % Anonymous function that takes a string x as input
           +x        % Convert the string into a numeric array,
                     % where each character is represented by its ASCII-value
       mod(+x,16)    % Takes this string modulus 16, to make spaces (ASCII 32) equal 0
    (s=mod(+x,16))   % Assigns this numeric array to s, thanks to Octave's awesome
                     % inline variable assignment possibility
    (s=mod(+x,16))*  % Multiply s by the vector inside the brackets

```

Let's look at what's going on inside the brackets:

```
[1-(i=find(s>9)):nnz(x)-i]
      find(s>9)             % The only value in the vector s that's larger than 9,
                            % after the modulus is ^, (it's now 14)
   (i=find(s>9))            % Assign the position of `^` to the index variable i

```

This one is a bit tricky:

```
[1-(i=find(s>9)):nnz(x)-i]

```

The numbers on each side of the ladder must be multiplied by the distance from the caret. If we use negative numbers on the left side, and positive numbers on the right side we can simply sum the vector to see which side is heaviest.

Suppose the input string is: `'321^ 12'`. We want the following: `3*(-3)+2*(-2)+1*(-1)+1*3+2*4`. The vector we made inside the brackets starts at `1-i`, which in this case is `-3`, since the caret is in the 4th position. It goes up to `nnz(x)-i` in increments of one. We can use `nnz(x)` instead of `numel(s)`, because `x` is a string containing no zeros.

Therefore:

```
[1-(i=find(s>9)):nnz(x)-i]
ans =
  -3  -2  -1   0   1   2   3   4

```

Now, we could do element-wise multiplication `s.*[...]`, and take the sum of this. But, since we have two vectors, we can also mutliply `s` by the transposed of `[...]` and calculate the sum using matrix multiplication:

```
(s=mod(+x,16))*[1-(i=find(s>9)):nnz(x)-i]'

```

This gives us either a negative number, meaning the left side is heavier, a zero, meaning it's balanced, or a postive numbers, meaning the right side is heavier. Instead of using the naive approach of `sign(...)`, we multiply it by `inf`, which will give us either `-Inf` or `Inf` for left and right respectively. We get `NaN` for `0*inf`, since it's undefined.

This gives us three distinct values for the three possible outcomes.

# Answer
> 2 votes
# JavaScript, 146 bytes

```
s=>{a=[0,0];d=s.split`^`;for(j=0;j<2;j++)for(i=0;i<d[j].length;i++)a[j]+=d[j][i]*(j==0?d[j].length-i:i+1);alert(a[0]==a[1]?'B':a[0]>a[1]?'L':'R')}

```

Pretty massive.

Demo.

# Answer
> 2 votes
## PowerShell, ~~83~~ 73 Bytes

```
param($b)$i=-$b.indexOf('^');[char[]]$b|%{$x+=$i++*"$_"};[math]::Sign($x)

```

Thanks to TessellatingHeckler for the golf.

Uses essentially the same algorithm as the below older code, but here we iterate through the characters in the input string one at a time rather than iterating through the index, which saves a handful of bytes. Still throws the same spectacular error message when the algorithm reaches `^` \- doesn't affect STDOUT.

---

### Previous

```
param($a)1..$a.length|%{$x+=+"$($a[$_-1])"*($_-$a.indexof('^')-1)};[math]::Sign($x)

```

Uses the same awesome algorithm as Dendrobium's excellent answer, and thus uses the same output of `-1 / 0 / 1` if the input is `left-heavy / balanced / right-heavy`.

Ugh. Long because of a casting ~~quirk~~ feature that PowerShell has. Most pertinent here is how `char` multiplied by `int` functions. Taking an array-index of a `string` results in a `char` object. PowerShell converts the `char` to its corresponding ASCII value (rather than literal value) before multiplication. So, something like `$a='012'[0];[int]$a*2` results in `96`.

That means we need to re-cast it back as a string. However, simply doing `string` times `int` gives us a `string` repeated that many times. For example, `$a='0';$a*2` would result in `00`.

This means we need to cast the `char` back as a `string` before *re*-casting as `int`, then multiplication can happen, before we add it into our accumulator `$x`.

Couple that with the lengthy way to iterate through a string, and the .NET call to output the sign, and we get a pretty long piece of code.

<sub>NB - This will throw a spectacular error when it reaches `^` in the string, stating that it can't convert it to an `int`. Doesn't affect STDOUT.</sub>

# Answer
> 2 votes
# Ruby, ~~111~~ 108 bytes

```
->s{l,r=s.split'^';v=->x{x.chars.map.with_index{|c,i|c.to_i*(i+1)}.reduce:+};%w(B L R)[v[l.reverse]<=>v[r]]}

```

## Explanation

Sums up weighted value of each number on each side. Then it uses the ruby spaceship operator to provide a 1,0,-1 of equality/inequality of the two sides, which is the index of an array with the correct output.

# Answer
> 1 votes
## Python 3, ~~196~~ 114 bytes

```
r=0
I=list(input())
p=I.index("^")
i=0
for E in I:
 if E.isdigit():r+=int(E)*(p-i)
 i+=1
print('BLR'[(r>0)-(r<0)])

```

Regular code:

```
total = 0

inp=list(input())
ful_index=inp.index("^")

i=0
for num in inp:
    if num.isdigit(): total += int(num) * (ful_index - i)
    i+=1

print('BLR'[(total>0)-(total<0)])

```

Explanation:

1. Generates a list of numbers + the fulcrum from `stdin`.
2. For every number, adds the distance from the fulcrum times the number to the variable to the total (numbers on the left will be negative and numbers on the right will be positive).
3. Prints the correct letter depending on the result (B if equal, L if more than zero, and R if less than zero).

Huge thanks to @ThomasKwa for trimming 82 bytes (more than 40%) off!

# Answer
> 1 votes
# C, 140 139 138 134 100 bytes

Return:

* 1 = LEFT
* 2 = BALANCED
* 0 = RIGHT

```
k;main(int x,char**a){char*n=a[1],*g=n;for(;*n^94;++n);for(;*g;++g)k+=(*g&15)*(n-g);return!k?2:k>0;}

```

Run:

```
./see-saw "11   ^9"
echo $?
2

```

As we have ASCII:

```
SPACE = 0x20
    0 = 0x30 ... 9 = 0x39

```

We get:

```
0x20 & 0x0f = 0
0x30 & 0x0f = 0
0x31 & 0x0f = 1
0x32 & 0x0f = 2
... etc.

```

Then sum by factor distance to `^`.

# Answer
> 1 votes
# CJam, 29 bytes

```
l_'^#\"^ "'0er'0f-_,,@fm.*:+g

```

Try it online

Result is `-1` for left-heavy, `0` for balanced, `1` for right-heavy.

This seemed a bit lengthy, but I tried a bunch of alternatives, and they all ended up between 29 and 33 bytes. One problem is that I couldn't find a way of converting the string to values that would automatically result in 0 for the spaces. So I ended up explicitly replacing the spaces with '0 characters, which obviously adds to the length of the code.

Alternatives tried:

* Splitting string at '^, reversing the 1st one, and then calculating the weighted value for both.
* Using the `ee` operator to add the index to the list of values.
* Instead of subtracting the caret position from each index, calculate the dot product without the subtraction, and then subtract caret position times string length from the result.

Explanation:

```
l         Get input.
_'^#      Copy and find caret position.
\         Swap input back to top.
"^ "'0er  Replace caret and spaces with '0.
'0f-      Subtract '0 from all characters, to get integer values.
_,,       Build index array with same length.
@         Rotate caret position to top.
fm        Subtract it from all indices.
.*        Calculate element wise product of two vectors.
:+        Add up the element products to get dot product.
g         Signum.

```

# Answer
> 1 votes
# SpecBAS - 140 bytes

```
1 INPUT b$: LET t=0,p=POS("^",b$),l$="RBL"
2 FOR i=1 TO LEN b$
3 IF b$(i) IN ["1" TO "9"] THEN INC t,(p-i)*VAL b$(i)
4 NEXT i
5 TEXT l$(2+SGN t)

```

`t` is a running total, the values are negative when character position is more than the carat position. At the end it sees if total is negative, zero or positive and prints the corresponding character of R, B or L.

I could shave a few bytes off by just outputting -1, 0 or 1 like some of the other answers.

# Answer
> 1 votes
# Java, 83 bytes

```
l->{int s=0,l=0;for(char c:l)if(l<1)s-=c-48;else s+=c-48;return s<0?-1:(s>0?1:0));}

```

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


title: A boring version of yourself

text:
# Question
Title: A boring version of yourself
# A boring version of yourself

Have you ever dreamed of a boring version of you which types the text you just typed ?

No ? Because that's exactly what I'm challenging you to do !

The program needs to check how many time it took for the user to input a text at program launch and then retype the text again using the same period of time (approximatively).

Here's my Python3 implementation with additional information :

```
import time

start = time.time()
userInput = input("Cool human input :")
endHuman = time.time() - start
duration =  endHuman / len(userInput)
start = time.time()
print("Boring robot input : ", end="")
for i in userInput:
  print(i, end="")
  time.sleep(duration)
end = time.time() - start
print()
print(endHuman, "vs", end)

```

This is a code-challenge so be creative !

Here are the rules :

* User **must** input the initial text, no program args
* Text input length is \> 0 (No need to check)
* The sleep duration between each letter is not imposed, it can be (timeTookByUser / numberOfLetters) like in my implementation, it can be random (as long as the total time is approximatively equal), it can sleep for the total time at first and then print all (but it's not fun).
* The "robot timer" must stop when the last letter is typed by the robot, you can't print everything and then sleep and end the program.
* As long as the robot prints the text passed in input, you can print other stuff (additional informations etc..)
* You don't **have to** use the console, you can input the text using a graphical text input and render it letter by letter using DELs but you will have to specify it in your answer
* Be creative !

# Answer
# Bash + linux utilities, 37

This will measure the time taken to enter each character (including backspaces) and play back verbatim. Use `^C` or `^D` to end user input.

```
script -qta -csed\ d
scriptreplay -ta

```

Creates a temporary files `typescript` and `a` in the current directory.
> 6 votes

# Answer
# MATLAB / Octave, 38 bytes

```
tic;x=input('','s');pause(toc);disp(x)

```

Starts a timer (`tic`) and prompts the user for input. Then the program pauses for however long it took for the user to input the text (`toc`) and prints out the input text.
> 3 votes

# Answer
# MATL, ~~7~~ 5 bytes

*2 bytes saved thanks to @Luis*

```
jZ`Y.

```

This solution will determine how long the user takes to enter the input and then wait that same amount before printing the user's input back to them all at once.

Unfortunately doesn't work online since the online interpreters don't support interactive input.

**Explanation**

```
        % Implicitly start the timer
j       % Grab user input as a string (will prompt the user)
Z`      % Stop the timer and return the elapsed time in seconds
Y.      % Pause for this many seconds
        % Implicitly display the user-input string

```
> 2 votes

# Answer
# Python 3.5, 61 bytes

```
from time import*
s,i=time(),input()
sleep(time()-s)
print(i)

```
> 0 votes

---
Tags: popularity-contest
---