# Question
Title: Find five friends to eat chicken with Paul
Paul is one of your Belgian acquaintances, and he would like you to create a program that **outputs at least one of the following five strings**:

```
12496=>14288=>15472=>14536=>14264

14264=>12496=>14288=>15472=>14536

14536=>14264=>12496=>14288=>15472

15472=>14536=>14264=>12496=>14288

14288=>15472=>14536=>14264=>12496

```

It represents the friends he's most proud of, and he would like to eat with them. Paul also thinks that the number 6 is perfect, and that is the only number worth using. So **you cannot use any other digit than "6"** in your code (0 to 5 and 7 to 9 are forbidden). Your program cannot take any inputs. The output can contain garbage before and/or after the string but should contain at least one of the above strings.

For example this is a valid output :

```
220frefze
f**14288=>15472=>14536=>14264=>12496**fczfe fz**15472=>14536=>14264=>12496=>14288**zfe
fzehth

```

I "ligthly" hinted in the question as how I expect this to be resolved, but how knows ? Maybe there is a better way... Hope you have fun.

This is code-golf : lowest score in bytes wins.

# Answer
# 05AB1E, ~~18~~ 17 bytes

```
•w[•Y·FDÑ¨O})„=>ý

```

Try it online!

**Explanation**

```
•w[•                # base 214 encoding of 12496
    Y·F             # loop 2*2 times
       D            # duplicate top of stack
        Ñ           # push divisors
         ¨          # remove the last element (itself)
          O         # sum
           }        # end loop
            )       # wrap in list
             „=>ý   # join list on "=>"

```

In short, we calculate each number as `f(n+1) = sum(divisors(f(n)) - f(n)`
> 12 votes

# Answer
## Pyke, 16 bytes

```
wヰw$VDlsh)J"=>

```

Try it here!

```
wヰ             -  12496
  w$            -   4
    V    )      -  repeat ^:
     D          -   duplicate(^)
      l         -     factors(^)
       s        -    sum(^)
        h       -   ^ + 1
          J     - v.join(^)
           "=>  -  "=>"

```

Anytime a string literal is at the end of a program, it swaps it with the token just before it, saving 1 byte in cases such as this. Pyke's `factors` function doesn't include the number itself nor 1. If numbers were allowed, 1 byte could be saved by replacing `w$` with `4`

## Pyke, 21 bytes

```
uバ㟐㱰㣈㞸J"=>

```

Try it here!

Create a list of the numbers required and joins them. Not very interesting apart from the trick with the strings.
> 5 votes

# Answer
# MATLAB, 44 bytes

```
['','=>@EBIJ=@>DDIJ=A@C>IJ=@A?BIJ=@>B@'-6-6]

```

**Try it online!**

I haven't found a pattern in the numbers (and it would be hard to use the pattern to anything anyways, since I can't use numbers), so I'll just go for the naive approach.

`'=>@EBIJ=@>DDIJ=A@C>IJ=@A?BIJ=@>B@'` is the string `'12496=>14288=>15472=>14536=>14264'` when 12 is added to the ASCII-values. Now, input that string, subtract `6+6`, and concatenate with the empty string `''` to convert it to a character array.
> 4 votes

# Answer
# JavaScript (ES6), 57 bytes/47 (UTF-8) characters

*Thanks to user5090812 for 10 B save*

```
_=>[...'バ㟐㱰㣈㞸'].map(a=>a.charCodeAt()).join`=>`

```

## Explanation

First we create an array and fill it with the characters in the string `バ㟐㱰㣈㞸`. Then we loop over the string (`a` has the value of the current element) and we change the character into its character code. Then we join all values in the array by `=>`.

## Old: 67 bytes

```
_=>[6,6,6,6,6].map((_,a)=>`バ㟐㱰㣈㞸`.charCodeAt(a)).join`=>`

```

### Explanation

First we create an array of length 5. Then we change the values of the array at each index for the character code of the character at that same index in the string `バ㟐㱰㣈㞸`, which are the numbers of all of Paul's friends in order. When we got that, we join the array together, and we use `=>` as separator.

## Usage

To use it, simply run this:

```
f=_=>[...'バ㟐㱰㣈㞸'].map(a=>a.charCodeAt()).join`=>`;alert(f())

```

## Output

```
12496=>14288=>15472=>14536=>14264

```
> 3 votes

# Answer
## Ruby, 36 bytes (26 characters)

```
p"バ㟐㱰㣈㞸".unpack("U*")*"=>"

```

Because, why not. Boring as hell.

## older version - 53 bytes

```
p %w(jol mld oim n6b mke).map{|x|x.to_i ~-6*~-6}*'=>'

```

Explanation: encoding the numbers in base 25 gives the 5 six-free strings, to decode them I only have to represent the number 25 using only 6: (6-1)*(6-1) =\> ~-6*~-6
> 3 votes

# Answer
# Perl 6, ~~63~~ 59 bytes

~~```
{$/=6;$/--;join "=>",<JOL MLD OIM N6B MKE>».parse-base($/*$/)}

```~~
```
{join "=>",<JOL MLD OIM N6B MKE>».parse-base(--($_=6)*$_)}

```

Decodes the numbers from base 25, because that's the only base supported by `.parse-base` (2 to 36) where none of them have invalid digits.

*Thanks to Neil for -3 bytes.*

# Perl 6, ~~82~~ 75 bytes

~~```
{my \a="BXS".parse-base(6*6);join "=>",(a,{sum grep $_%%*,^$_}...^{$_==a if $++})}

```~~
```
{my \a="BXS".parse-base(6*6);join "=>",({$/=$_//a;sum grep $/%%*,^$/}...a)}

```

Decodes the number `15472` in base 36, and then generates the sequence by calculating each number as the sum of proper divisors of the previous number.

# Perl 6, 69 bytes (47 characters) - noncompeting

```
{"{١٢۴۹6}=>{١۴۲۸۸}=>{١۵۴۷۲}=>{١۴۵۳6}=>{١۴۲6۴}"}

```

Doesn't use any of the forbidden ASCII digits, uses Unicode digits from the Arabic-Indic block instead (2 bytes each)! The `{ }` string interpolations make sure they're parsed as Perl 6 number literals, and then stringified to their ASCII representations.

Okay, this is cheating - that's why I didn't use it as my main answer... :)
> 3 votes

# Answer
# Jelly, ~~5~~ 4 bytes

```
ȷṗȷỌ

```

Prints all five strings. Takes advantage of the fact that "garbage" output is allowed and buries the five strings in **103003** characters of output.

### How it works

```
ȷṗȷỌ  Main link. No arguments.

ȷ     Set the return value to 1000.
 ṗȷ   Cartesian power; form all arrays of length 1000 that consist of integers in
      [1, ..., 1000].
   Ọ  Unordinal; convert all integers to characters.

```
> 3 votes

# Answer
# C, ~~94~~ ~~84~~ 77 Bytes

Stoopid simple. Special thanks @Neil

```
g(){char*m="!mnpuryzmpnttyzmqpsnyzmpqoryzmpnrp";for(;*++m;)putchar(*m-66+6);}

```

~~f(){printf("%d=\>%d=\>%d=\>%d=\>%d",'~'*'r'-'d','~'*'d'-'h','~'*'r'-'L','~'*'z'+'d','~'\*'t'-'P');}~~
> 2 votes

# Answer
# PHP, ~~73~~ ~~63~~ 60 bytes

```
for(;$c="|`*X6H-$*@"[$i];)echo!!$i&++$i?"=>".!!6:"",ord($c);

```

Run with `-nr`.

a little less lazy: took string as list of `=>1(ascii)(ascii)`
i.e.: `124`,`96`,`=>1`,`42`,`88`,`=>1`,`54`,`72`,`=>1`,`45`,`36`,`=>1`,`42`,`64`;
print `=>1` by string index, append ascii code

**breakdown**

```
            # loop through string with index $i
for(;$c="|`*X6H-$*@"[$i];)echo
            # string ascii values: 124,96,42,88,54,72,45,36,42,64
    !!$i        # true if $i>0
    &++$i       # odd if (old) $i is 0,2,4,6,8
                # -> true for 2,4,6,8
        ?"=>".!!6   # if true, print "=>1"
        :"",        # else print nothing
    ord($c);    # print ascii value

```
> 1 votes

# Answer
## C++, 92 bytes

```
#include <cstdio>
int main(){for(char c:"UVX]ZabUXV\\abUYX[VabUXYWZabUXVZX")putchar(c-6*6);}

```
> 1 votes

# Answer
# PHP, 53 bytes

```
<?=join('=>',unpack('v*',gzinflate('�`p������s')));

```

Hex dump:

```
00000000: 3c3f 3d6a 6f69 6e28 273d 3e27 2c75 6e70  <?=join('=>',unp
00000010: 6163 6b28 2776 2a27 2c67 7a69 6e66 6c61  ack('v*',gzinfla
00000020: 7465 2827 bb60 70c1 bcc0 e684 c50e 7300  te('.`p.......s.
00000030: 2729 2929 3b                             ')));

```

Output:

```
12496=>14288=>15472=>14536=>14264

```

Explanation:

Each of the five-digit integer sections is encoded as an unsigned short little endian, then concatenated together and the result is gzipped. This happens to produce a byte steam that has no offending digit characters, which is then hard-coded into a string. To extract, un-gzip the stream, unpack the two-byte shorts, interpret each as a string, and join with `>=`.
> 1 votes

# Answer
# Java 8, 134 bytes

Golfed:

```
()->{String s="";for(String a:new String[]{"JOL","MLD","OIM","N6B","MKE"}){if(!s.isEmpty())s+=("=>");s+=Long.valueOf(a,25);}return s;}

```

Ungolfed, full program:

```
import java.util.function.*;

public class FindFiveFriendsToEatChickenWithPaul {

  public static void main(String[] args) {
    System.out.println(toString(() -> {
      String s = "";
      for (String a : new String[] { "JOL", "MLD", "OIM", "N6B", "MKE" }) {
        if (!s.isEmpty()) s += ("=>");
        s += Long.valueOf(a, 25);
      }
      return s;
    }));

  }

  private static String toString(Supplier<String> s) {
    return s.get();
  }

}

```
> 1 votes

# Answer
## Batch, 191 bytes

```
@set/as=n=66*(66+66+66+6*6)+66/6+66/6+6,u=6/6
@call:t
@call:t
@echo %s: ==^>%
@exit/b
:t
@call:c
:c
@for /l %%i in (%u%,%u%,%n%)do @set/an-=%%i*!(%n%%%%%i)
@set/an=-n
@set s=%s% %n%

```

I estimate that it would take a minimum of 32 bytes to calculate each number using only `6`s plus another 32 to print them all out, which is already 192 bytes, so I'm winning by computing the amicable chain. Also, I think five `%`s in a row is a record for me. Also, neat Batch trick: the `%n%` is substituted before the `for` loop is evaluated, so the loop calculates all the factors of `n`, and subtracts them from `n`, thus resulting in the negation of the desired result.
> 1 votes

# Answer
# Jelly, 12 bytes

```
“<ọ’ÆṣÐĿj“=>

```

Prints the fourth string and nothing else.

Try it online!

### How it works

```
“<ọ’ÆṣÐĿj“=>  Main link. No arguments.

“<ọ’          Yield the 1-based indices of '<' and 'ọ' in Jelly's code page, i.e.,
              [61, 222], and convert the array from base 250 to integer.
              This yields 15472.
      ÐĿ      Iteratively call the link to the left until the results are no longer
              unique and return the array of all unique results.
    Æṣ        Compute the proper digit sum of the previous value (initially 15472).
        j“=>  Join, separating by the string "=>".

```
> 1 votes

# Answer
## Python 2, ~~78~~ 72 bytes

```
print''.join(chr(ord(x)-6-6)for x in'=@>DDIJ=A@C>IJ=@A?BIJ=@>B@IJ=>@EB')

```

**Edit** \- Thanks to Stewie Griffin for saving 6 bytes!

Also, another solution would be to output all the possible permutations. OP says garbage is fine.

```
from itertools import permutations
print str(list(permutations(''.join(str(x)+'.'for x in range(int('9'*5)).replace(',','').replace('\'','')
# also 9 and 5 need to be converted using ord and chr

```

There is too much redundancy in converting from `int` or `list` to `str`. I guess this would be easier in some esoteric languages, but I know none of them.
> 0 votes

---
Tags: code-golf, restricted-source
---


# Question
Title: All squares that match a wildcard sequence
This was inspired by part of the 2016 ARML competition Team Problem #6.

Here's the challenge:

You're given a "wildcard sequence", which is a sequence of digits and another character. A string matches this wildcard sequence by the following pseudocode:

```
w = wildcard
s = string
# s matches w iff
for all 0 >= i > wildcard.length, w[i] == '?' or s[i] == w[i]

```

Where '?' is a character of your choice.

In terms of regex, just imagine the `'?'` to be `'.'`.

The challenge is to find all square numbers (the requirement is up to 1 million) whose decimal string representations match this wildcard sequence. The "wildcard character" can be any ASCII character of your choice, as long as it isn't a digit, obviously.

For example, `4096` matches `4**6` and `4*9*` but `4114` does not match either.

## Input

Input will be given as a sequence matching the regex `[0-9?]+`. This can be a string, a character array, or a byte array of the characters in ASCII.

## Output

Output will be a whatever-you-want-delimited list/set/array of numbers which are perfect squares and match the wildcard sequence.

## Examples of valid inputs:

```
1234567*90
1234567?90
1234567u90
['1', '2', '3', '4', '5', '6', '7', '*', '9', '0']
[49, 50, 51, 52, 53, 54, 55, 42, 57, 48]
[1, 2, 3, 4, 5, 6, 7, '*', 9, 0]

```

## Examples of valid outputs:

```
[1, 4, 9]
1 4 9
1, 4, 9
1-4-9

```

etc.

## Specifications

* You may not use builtins for finding a list of squares in a certain range
* Standard Loopholes Apply
* You must be able to handle up to 1 000 000 (1 million)
* If provided with the input `1******`, it is correct to print `[1000000]`. It is also correct to print `[1000000, 1002001, 1004004, 1006009, 1008016, 1010025, ...]`
* Wildcard sequences will never start with the wildcard character; that is, they will always match strings of the same length.

## Test Cases

```
4**6  ->  [4096, 4356]
1**1  ->  [1521, 1681]
1**  ->  [100, 121, 144, 169, 196]
9****9  ->  [908209, 915849, 927369, 935089, 946729, 954529, 966289, 974169, 986049, 994009]
9*9***  ->  [919681, 929296]
1**0*  ->  [10000, 10201, 10404, 10609, 12100, 14400, 16900, 19600]
9***4  ->  [91204, 94864, 97344]

```

## Winning

Shortest (valid) (working) submission by February 14th, tie-break by earliest submission winning.

# Answer
# 05AB1E, 22 bytes

Probably plenty of room for improvement here.
Any non-digit is okay as wildcard.

```
3°LnvyS¹)ø€Æ0QPyg¹gQ&—

```

Try it online!

Explanation to come after further golfing.
> 0 votes

# Answer
# Mathematica, 44 bytes

```
Print@@@IntegerDigits[Range@1*^3^2]~Cases~#&

```

The input is a list of digits with a `_` (no quotes) as a wildcard. e.g. `{4, _, _, 6}`

**Explanation**

```
Range@1*^3

```

Generate list `{1, 2, 3, ... , 1000}`

```
... ^2

```

Square it. (list of all squares from 1 to 1,000,000)

```
IntegerDigits[ ... ]

```

Split each square into a list of digits.

```
... ~Cases~#

```

Find the ones that match the pattern specified by the input.

```
Print@@@ ...

```

Print them.
> 1 votes

# Answer
# Brachylog, 23 bytes

```
@e:{@$|,}a#0:{c.~^#I,}f

```

Try it online!

### Explanation

```
@e                        Split into a list of characters
  :{@$|,}a                Replace each digit char by the corresponding digit, and each things
                            that are ot digits into variables
          #0              All elements of the resulting list must be digits
            :{       }f   Output is the result of finding all...
              c.            ...concatenations of those digits which...
               .~^#I,       ...result in a number which is the square of an integer #I

```

### Different input format, 13 bytes

Depending on what your consider valid as input, you could do this:

```
#0:{c.~^#I,}f

```

Try it online!

which is basically the second part of the answer above, with a list as input containing digits and variables where the wildcards are.

I don't consider this valid though because there are only 26 variable names in Brachylog (the uppercase letters), so this would not work if you had more than 26 wilcards.
> 1 votes

# Answer
# Ruby, 54 bytes

Function that takes a string argument. Try it online.

```
->s{(0..1e3).map{|i|"#{i**2}"[/^#{s.tr ?*,?.}$/]}-[p]}

```
> 1 votes

# Answer
# Perl 6, ~~30~~ 26 bytes

*Thanks to @b2gills for -4 bytes!*

~~```
{grep /^<$_>$/,map * **2,^1e4}

```~~
```
{grep /^<$_>$/,(^1e4)»²}

```

Uses the dot as wildcard character, so that the input can be used as a regex:

```
{                            }   # a lambda
                         ^1e4    # range from 0 to 9999
               map * **2,        # square each value
 grep /      /,                  # filter numbers that match this regex:
        <$_>                     #   lambda argument eval'ed as sub-regex
       ^    $                    #   anchor to beginning and end

```

Try it online.

A variant that accepts the asterisk as wildcard (as suggested by a previous revision of the task description) would be 42 bytes:

```
{grep /^<{.trans("*"=>".")}>$/,(^1e4)»²}

```
> 1 votes

# Answer
# JavaScript (ES6), ~~68~~ 66 bytes

**EDIT:** Updated my solution below after being inspired by JungHwan Min's answer. It is now ES6 compliant.

Takes input in the format `'1..4'` where `.` is the wildcard.

Instead of iterating to 1e6 and square rooting this one iterates to 1e3 and squares.

```
p=>[...Array(1e3)].map((_,n)=>''+n*n).filter(n=>n.match(`^${p}$`))

```

```
F=p=>[...Array(1e3)].map((_,n)=>''+n*n).filter(n=>n.match(`^${p}$`))

const update = () => {
  console.clear();
  console.log(F(input.value));
}

submit.onclick = update;
update();
```

```
<input id="input" type="text" value="9....9" style="width: 100%; box-sizing: border-box" /><button id="submit">submit</button>
```

# JavaScript (ES7), ~~71~~ 69 bytes

```
p=>[...Array(1e6).keys()].filter(n=>n**.5%1?0:(''+n).match(`^${p}$`))

```

Creates an array of numbers from 0 to 1e6 then filters it by numbers that are square and match the pattern.

It is horrendously slow because it always iterates to 1e6.

```
F=p=>[...Array(1e6).keys()].filter(n=>n**.5%1?0:(''+n).match(`^${p}$`))

const update = () => {
  console.clear();
  console.log(F(input.value));
}

submit.onclick = update;
update();
```

```
<input id="input" type="text" value="9....9" style="width: 100%; box-sizing: border-box" /><button id="submit">submit</button>
```
> 0 votes

# Answer
# Perl, 42 45 38 bytes

EDIT: clarification by Alex, we can use the period as wildcard character which shaves off the y// operation.

```
perl -pe 's|.*|@{[grep/^$&$/,map$_*$_,1..1e3]}|'

```

EDIT: solution that uses the asterisk as wildcard character and expects the wildcard sequence on STDIN

```
perl -pe 'y/*/./;s|.*|@{[grep/^$&$/,map$_*$_,1..1e3]}|'

```

This one leaves undoubtedly a lot of room for improvement, it's pretty straightforward. The wildcard expression is expected as command line argument, with the period wildcard character (what else?).

```
say"@{[grep/^$ARGV[0]$/,map$_*$_,1..1e3]}"

```
> 0 votes

# Answer
## Batch, 109 bytes

```
@for /l %%i in (0,1,999)do @set/aj=%%i*%%i&call copy nul %%j%%.%%j%%$>nul
@for %%s in (%1.%1$)do @echo %%~ns

```

Uses `?` as the wildcard. Works by creating 1000 files. The name of the file is the square number, and the extension of the file is the square number with a `$` suffixed. This is because Batch's pattern matching counts trailing `?`s as optional, so `1?` will match both `1` and `16`; the `$` therefore forces the match to be exact. However, we don't want to output the `$`, so we just output the file name only without extension.
> 0 votes

# Answer
# Python 3 - ~~98~~ 97 bytes

```
import re;print(re.findall(r"\b"+input()+r"\b",("\n".join([str(x*x) for x in range(1,1001)]))))

```

Requires input like '4..6'.
> 0 votes

# Answer
# k - 28 characters

```
{s(&:)($:s:s*s:!1001)like x}

```

Uses `?` as the wildcard character. The `like` function uses `?` as a wildcard, and this function makes a list of the first 1001 squares (to be inclusive to 1M), casts them all to strings, and then checks where they match the pattern.

```
    {s(&:)($:s:s*s:!1001)like x} "1??"
100 121 144 169 196

```
> 0 votes

# Answer
# bash + Unix utilities, 33 bytes

```
dc<<<'0[2^pv1+lax]dsax'|grep ^$1$

```

This uses '.' as the wildcard character.

The dc program prints the square numbers in an infinite loop:

```
0     Push 0 on the stack.

[     Start a macro (called a).

2^    Square the number at the top of the stack.

p     Print the number at the top of the stack, followed by a newline.

v     Replace the number at the top of the stack (a square number) with its square root.

1+    Increment the number at the top of the stack.

lax   Run the macro again (looping).

]     End of the macro.

dsax  Store the macro in register a and run it.

```

The dc output is piped to grep, which prints just the squares that match the required pattern.

This works when I run it on an actual Linux or OS X system (but it doesn't work at TIO, probably because the dc program tries to recurse forever, and I suspect TIO runs out of stack space for the recursion and/or has a problem with the never-ending pipe).
> 0 votes

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


title: Hack the elections

text:
# Question
Title: Hack the elections
You're a professional hacker and your boss has just ordered you to help a candidate win an upcoming election. Your task is to alter the voting machines data to boost the candidate's results.

Voting machines store voting results as two integers : the number of votes for your candidate (`v1`) and the number of votes for their opponent (`v2`).

After weeks of research, you have found a security hole in the system and you can increase the value of `v1` by an integer `x`, and decrease the value of `v2` by the same `x`. But there is a constraint, you have to keep the security hash code constant:

* security hash code : `(v1 + v2*2) modulo 7`

Also, the value for `x` must be minimal so your changes can go unnoticed.

Your program should accept as input `v1` and `v2` ; it should output the optimal value for `x` so `v1>v2`.

There are some cases for which you cannot hack the results; you don't have to handle them (this might lead to problems with your boss, but that's another story).

**Test cases**

```
100,123 --> 14
47,23 --> 0
40,80 --> 21
62,62 --> 7
1134,2145 --> 511

```

# Answer
> 21 votes
# Python 2, 30 bytes

```
lambda u,t:max(0,(t-u)/14*7+7)

```

`u` is our votes, `t` is their votes.

# Answer
> 20 votes
## Python 2, 30 bytes

```
lambda a,b:max((b-a)/14*7+7,0)

```

# Answer
> 13 votes
## Mathematica, 22 bytes

```
0//.x_/;2x<=#2-#:>x+7&

```

Pure function with arguments `#` and `#2`. Hits maximum recursion depth if the discrepancy is more than `7*2^16 = 458752`.

## Explanation

```
0                       Starting with 0,
 //.                    repeatedly apply the following rule until there is no change:
    x_                    if you see an expression x
      /;                    such that
        2x<=#2-#            2x <= #2-# (equivalently, #+x <= #2-x)
                :>        then replace it with
                  x+7       x+7 (hash is preserved only by multiples of 7)
                     &  End the function definition

```

# Answer
> 7 votes
# Jelly, 9 bytes

```
IH:7‘×7»0

```

Try it online!

### How it works

```
IH:7‘×7»0  Main link. Argument: [v1, v2]

I          Increments; compute [v2 - v1].
 H         Halve the result.
  :7       Perform integer division by 7.
    ‘      Increment the quotient.
     ×7    Multiply the result by 7.
       »0  Take the maximum of the product and 0.

```

# Answer
> 6 votes
# Actually, 13 bytes

```
7;;τ((-\*+0kM

```

Try it online!

Uses the same `max((b-a)/14*7+7,0)` formula that xnor and orlp use.

Explanation:

```
7;;τ((-\*+0kM
7;;            3 copies of 7
   τ           double one of them
    ((-        bring the inputs back to the top, take their difference
       \*+     integer divide by 14, multiply by 7, add 7
          0kM  maximum of that and 0

```

# Answer
> 6 votes
## Groovy, 41 ~~37~~ bytes

```
{x,y->[Math.floor((y-x)/14)*7+7,0].max()}

```

This is an unnamed closure. Thanks to `xnor` and `orlp` for the formula and `James holderness` for pointing out a bug.

The previous solution used `intdiv()` for integer division but it behaves differently from `//` used in python.

Try it here!

# Answer
> 5 votes
# Haskell, ~~30~~ 24 bytes

```
a#b=max 0$div(b-a)14*7+7

```

An infix operator taking the number of votes of your preferred candidate first. Uses the same logic as the other answers of rounding with `/14*7+7`.

# Answer
> 4 votes
# J, 15 bytes

```
0>.7+7*14<.@%~-

```

Kinda interesting, I was working on a problem and I thought I had a solution but as it turns out I was wrong. Oh well. Try it online! Here's the result:

```
   f =: 0>.7+7*14<.@%~-
   tests =: 123 100 ; 23 47 ; 80 40 ; 62 62 ; 2145 1134
   (,. f/ each) tests
┌─────────┬───┐
│123 100  │14 │
├─────────┼───┤
│23 47    │0  │
├─────────┼───┤
│80 40    │21 │
├─────────┼───┤
│62 62    │7  │
├─────────┼───┤
│2145 1134│511│
└─────────┴───┘

```

# Answer
> 4 votes
# CJam, ~~13~~ ~~12~~ 15 bytes

* Saved a byte thanks to Martin Ender.
* Added 3 bytes thanks to Martin Ender.
* Changed `]` to `[` thanks to ETHproductions.

```
q~\-Ed/m[)7*0e>

```

Blatantly stole orlp and xnor's methods.

Input is the two numbers separated by a space: `100 123`

Explanation:

```
q~\-Ed/m])7*0e>
q~\-            e# Input two numbers, swap and subtract them.
    E           e# Push 0xE (15)
     d/m]       e# Float divide and take the floor.
         )7*    e# Increment and multiply by 7.
            0e> e# Max of this and 0.

```

# Answer
> 4 votes
# Excel VBA, <sub>~~24~~</sub> 17 Bytes

Immediates window function that takes input from cells `A1` and `B1` and outputs to the VBE immediates window.

```
?([A1-B1]\14)*7+7

```

**Subroutine Version, 43 Bytes**

takes input `b, c` as variant\integer and prints to the VBE immediates window

```
Sub a(b,c):Debug.?Int((c-b)/14)*7+7:End Sub

```

# Answer
> 3 votes
# Julia 0.5, 26 bytes

```
v\w=max(fld(w-v,14)*7+7,0)

```

Try it online!

# Answer
> 3 votes
# Japt, 14 bytes

```
V-U /2+7 f7 w0

```

Run it here!

Thank you ETHproductions for shaving off 3 bytes!

# Answer
> 3 votes
# PHP, ~~41~~ 39 bytes

```
    <?=7*max(0,1+($argv[2]-$argv[1])/14|0);

```

takes input from command line arguments; run with `-r`.

~~7~~ 5 extra bytes just to handle $a\>$b :-/

# Answer
> 3 votes
# 05AB1E, 9 bytes

```
-14÷>7*0M

```

Try it online!

**Explanation**

```
-          # push difference of inputs
 14÷       # integer divide by 14
    >      # increment
     7*    # times 7
       0   # push 0
        M  # take max

```

Or a corresponding function with same byte-count operating on a number-pair

```
Î¥14÷>7*M

```

Try it online!

# Answer
> 2 votes
# Dyalog APL, 14 bytes

Takes `v1` as right argument and `v2` as left argument.

```
0⌈7×1+(⌊14÷⍨-)

```

`0 ⌈` the maximum of zero and

`7 ×` seven times

`1 + (`...`)` one plus...

the floor of

`14 ÷⍨` a fourteenth of

`-` the difference (between the arguments)

TryAPL online!

# Answer
> 2 votes
# Befunge, 19 bytes

```
777+:&&\-+\/*:0`*.@

```

Try it online!

This relies on a slightly different formula to that used by orlp and xnor, since the Befunge reference interpreter has different rounding rules to Python. Befunge also doesn't have the luxury of a `max` operation.

The basic calculation looks like this:

```
x = (v2 - v1 + 14)/14*7
x = x * (x > 0)

```

Examining the code in more detail:

```
7                     Push 7                                      [7]
 77+:                 Push 14 twice.                              [7,14,14]
     &&               Read v1 and v2 from stdin.                  [7,14,14,v1,v2]
       \-             Swap the values and subtract.               [7,14,14,v2-v1]
         +            Add the 14 that was pushed earlier.         [7,14,14+v2-v1]
          \/          Swap the second 14 to the top and divide.   [7,(14+v2-v1)/14]
            *         Multiply by the 7 that was pushed earlier.  [7*(14+v2-v1)/14 => x]
             :        Make a copy of the result                   [x,x]
              0`      Test if it's greater than 0.                [x,x>0]
                *     Multiply this with the original result.     [x*(x>0)]
                 .@   Output and exit.

```

# Answer
> 2 votes
# Go, 36 bytes

`func(a,b int)int{return(b-a)/14*7+7}`

Try it online!

# Answer
> 2 votes
# JavaScript (ES6), 31 bytes

```
(a,b,c=(b-a)/14|0)=>c>0?c*7+7:0

```

```
f=(a,b,c=(b-a)/14|0)=>c>0?c*7+7:0
document.write(f(1134,2145))
```

# Answer
> 2 votes
# Java 8, 31 bytes

`(a,b)->b<a?0:(a=(b-a)/2)+7-a%7;`

This is a lambda expression assignable to `IntBinaryOperator`.

a is your candidate's votes, b is your opponent's.

java rounds down for division with positive integers, so `+7-a%7` is used to bump up the value to the next multiple of 7.

# Answer
> 1 votes
## Ruby, ~~26~~ 27 bytes

```
->a,b{[(b-a)/14*7+7,0].max}

```

Basically the same as xnor's and orlp's Python solution, ~~with a twist (no need to add 7, because of negative modulo, saves 1 byte in ruby, don't know about python)~~

No twist, the twist was just a bad case of cognitive dissonance. Forget it. Really. :-)

# Answer
> 1 votes
# Noodel, 16 bytes

```
⁻÷14ɲL×7⁺7ḋɲl⁺÷2

```

Pulled equation from xor and orlp answers, but since *Noodel* does not have a max capability had to work around that.

Try it:)

### How it works

```
⁻÷14ɲL×7⁺7       # The equation...
⁻                # v2 - v1
 ÷14             # Pops off the difference, then pushes on the (v2 - v1)/14
    ɲL           # Applies lowercase which for numbers is the floor function.
      ×7         # Multiplies that by seven.
        ⁺7       # Then increments it by seven.

          ḋɲl⁺÷2 # To relate with the other answers, this takes the max between the value and zero.
          ḋ      # Duplicates what is on the top of the stack (which is the value just calculated).
           ɲl    # Pops off the number and pushes on the magnitude (abs value).
             ⁺   # Add the abs to itself producing zero if the number came out negative (which means we are already winning).
              ÷2 # Divides the result by two, which will either be zero or the correct offset.

```

# Answer
> 1 votes
# Scala, 31 bytes

```
(a,b)=>Math.max((b-a)/14*7+7,0)

```

The ternary version is 2 bytes longer

# Answer
> 1 votes
# Pyth, 16 bytes

```
MtS+0[+7*7/-HG14

```

Try it here!

---
Tags: code-golf, arithmetic
---


title: Find the identity sandpile

text:
# Question
Title: Find the identity sandpile
This question is about abelian sandpiles. Read this previous challenge and watch this numberphile video to learn more.

---

An abelian sandpile of size *n* by *n* is a grid containing the number 0, 1, 2 and 3 (representing the number of grains of sand). Adding two sandpiles works by first adding element by element, and then *toppling* any element that goes above 3. The order in which you topple doesn't matter, the end result is the same. When a cell topples its number decreases by 4, and each of its direct neighbors increases by 1. This can cause a chain reaction. If a cell is on the edge of the grid, any grains that fall off the grid while toppling disappear.

For example, I'm adding two 3 by 3 sandpiles (giving a rather extreme chain reaction):

```
3 3 3   1 2 1   4 5 4    4 6 4    6 2 6    6 3 6    2 5 2    4 1 4    4 2 4    0 4 0    2 0 2    2 1 2
3 3 3 + 2 1 2 = 5 4 5 -> 6 0 6 -> 2 4 2 -> 3 0 3 -> 5 0 5 -> 1 4 1 -> 2 0 2 -> 4 0 4 -> 0 4 0 -> 1 0 1
3 3 3   1 2 1   4 5 4    4 6 4    6 2 6    6 3 6    2 5 2    4 1 4    4 2 4    0 4 0    2 0 2    2 1 2

```

**In this challenge we're interested in a subset of all possible *n* by *n* sandpiles.** This subset contains any sandpile that you can get by adding an arbitrary sandpile to the all-3s *n* by *n* sandpile. For example, just above we saw that `212 | 101 | 212` is in the subset, because we got it by adding something to the all-3 sandpile.

Now this subset has an interesting element: the *identity* element. If you take this element and add it to *any other element in the **subset***, the sum is unchanged. In other words, this sandpile acts like a *zero* of this subset. It just so happens that `212 | 101 | 212` is the zero element for the subset of 3 by 3. For example:

```
2 2 2   2 1 2   4 3 4    0 5 0    2 1 2    2 2 2
2 2 2 + 1 0 1 = 3 2 3 -> 5 2 5 -> 1 6 1 -> 2 2 2
2 2 2   2 1 2   4 3 4    0 5 0    2 1 2    2 2 2

```

Now this is your challenge: **given *n*, find the identity element of the subset of the *n* by *n* grid**. Output it by assigning a unique color with sufficient contrast of your choice to each of `0, 1, 2, 3` and outputting an n by n image. **Your code must be able to produce the 50 by 50 case in under a minute on a reasonable modern PC.**

---

For example, the 500 by 500 identity element:

Here is blue = 3, green = 2, red = 1, white = 0. But you don't have to use this color scheme in your answer.

# Answer
> 3 votes
# Octave, ~~120~~ 113 bytes

```
function a=W(a);while nnz(b=a>3);a+=conv2(b,[t=[0 1 0];!t;t],'same')-b*4;end;end;@(n)imagesc(W((x=ones(n)*6)-W(x)))

```

Thanks to JungHwan Min for providing a link to the reference paper in his Mathematica answer.
Thanks to Stewie Griffin saved me 7 bytes `[any(any(x)) -> nnz(x)]`

Here two function is used:

1.`f`: for stabilization of a matrix
2. An anonymous function that takes `n` as input and shows the identity matrix.

Try It On rextester! for generation of a 50 * 50 matrix

Elapsed time for computation of the matrix: `0.0844409 seconds`.

**Explanation:**

Consider a function `f` that stabilizes a matrix the task of finding the identity is simply

`f(ones(n)*6 - f(ones(n)*6)`.

that `ones(n)*6` means a n\*n matrix of 6.

so for `n=3`:

```
M = [6 6 6
     6 6 6
     6 6 6];

```

The result will be `f(M-f(M))`

For stabilization function 2D convolution used to speed the task; In each iteration we make a binary matrix `b` with the same size of the input matrix and set it to 1 if corresponding element of the input matrix is \>3. Then we apply a 2D convolution of the binary matrix with the following mask

```
0 1 0
1 0 1
0 1 0

```

representing four direct neighbors .
Result of convolution is added to the matrix and 4 times the binary matrix subtracted from it.

The loop continued until all element of the matrix are \<= 3

**Ungolfed version**:

```
function a=stabilize(a)
    mask = [t=[0 1 0];!t;t];
    while any(any(b=a>3))
        a+=conv2(b,mask,'same')-b*4;
    end
end
n= 50;
M = ones(n)*6;
result = stabilize(M-stabilize(M));
imagesc(result);

```

# Answer
> 9 votes
# Mathematica, ~~177~~ ~~157~~ ~~135~~ 133 bytes

```
Colorize[f=BlockMap[⌊{l={0,1,0},1-l,l}#/4⌋~Total~2+#[[2,2]]~Mod~4&,#~ArrayPad~1,{3,3},1]&~FixedPoint~#&;k=Table[6,#,#];f[k-f@k]]&

```

Takes a number `n`. The output is the identity sandpile. 0 is black, 1 is light gray, 2 is magenta, and 3 is blue-gray.

Sadly, Mathematica does not have a builtin for this...

Uses the algorithm stated in Scott Corry and David Perkinson's paper.

Takes 91.7 seconds on my 5-year-old laptop to calculate the 50x50 identity sandpile. I am confident that a reasonable modern desktop computer is more than 50% faster. (I also have a way faster code at the end).

**Explanation**

```
f= ...

```

Define function `f` (the input is a sandpile matrix): a function that ...

```
BlockMap[ ... ]~FixedPoint~#&

```

... repeats the `BlockMap` operation until the output does not change. `BlockMap` operation: ...

---

```
#~ArrayPad~1

```

... pad the input array with one layer of 0 ...

```
{3,3},1

```

... partition it into 3x3 matrices, with offset 1 ...

```
⌊{l={0,1,0},1-l,l}#/4⌋~Total~2+#[[2,2]]~Mod~4&

```

... and for each partition, add the number of sand grains toppled onto the center cell and the center cell value mod 4.

i.e. the output of `f` is the stabilized version of the input.

---

```
k=Table[6,#,#]

```

Define `k` as an *n* by *n* array of 6s.

```
f[k-f@k]]

```

Compute f(k - f(k)).

```
Colorize[ ... ]

```

Apply colors to the result.

**Faster version (142 bytes)**

```
Colorize[r=RotateLeft;a=ArrayPad;f=a[b=#~a~1;b+r[g=⌊b/4⌋,s={0,1}]+g~r~-s+r[g,1-s]+r[g,s-1]-4g,-1]&~FixedPoint~#&;k=Table[6,#,#];f[k-f@k]]&

```

Same code, but uses built-in list rotation instead of `BlockMap`. Computes n=50 in 4.0 seconds on my laptop.

# Answer
> 1 votes
# Python 3 + Numpy + PIL, ~~385~~ ~~370~~ 364 bytes

```
import numpy as q,PIL.Image as w
n=int(input())
z=n,n
def r(p):
 while len(p[p>3]):
  for x,y in q.ndindex(z):
   if p[x,y]>3:
    p[x,y]-=4;p[x-1,y]+=x>0;p[x,y-1]+=y>0
    if~-n>x:p[x+1,y]+=1
    if~-n>y:p[x,y+1]+=1
s=q.full(z,6)
t=s.copy()
r(t)
i=s-t
r(i)
w.fromarray(q.uint8(q.array(q.vectorize(lambda x:[x//1*65]*3,otypes=[object])(i).tolist()))).save('i.png')

```

Takes input on STDIN. Outputs the image as greyscale to `i.png`. Black corresponds to 0, dark grey to 1, light grey to 2, and white to 0.

Uses the formula `I = R(S - R(S))`, where `I` is the identity element, `S` is the matrix filled with sixes, and `R` is the reduction function.

I could probably save some bytes by switching to Python 2 and doing `from numpy import*`, but (1) I don't have Numpy installed on Python 2 and (2) the program wasn't terminating with `from numpy import*`.

Ungolfed:

```
import numpy as np
from PIL import Image

# Compute the identity element

n = int(input('Size of the sandpile: '))

def reduce_pile(sandpile):
  while any(element >= 4 for element in np.nditer(sandpile)):
    for x, y in np.ndindex((n, n)):
      if sandpile[x, y] >= 4:
        sandpile[x, y] -= 4
        if x > 0: sandpile[x - 1, y] += 1
        if y > 0: sandpile[x, y - 1] += 1
        if x < n - 1: sandpile[x + 1, y] += 1
        if y < n - 1: sandpile[x, y + 1] += 1

s = np.full((n, n), 6, dtype=np.int32)
s_prime = np.copy(s)

reduce_pile(s_prime)

identity = s - s_prime
reduce_pile(identity)

# Output it to identity.png as an image

colours = [[255, 255, 255], [255, 0, 0], [0, 255, 0], [0, 0, 255]]
img_array = np.vectorize(lambda x: colours[x], otypes=[object])(identity)
img_array = np.array(img_array.tolist(), dtype=np.uint8)

img = Image.fromarray(img_array)
img.save('identity.png')

```

---
Tags: code-golf, graphical-output, cellular-automata
---


title: Hex Dump your Source Code

text:
# Question
Title: Hex Dump your Source Code
When code-golfing there will be times where you need a Hex Dump of your code, usually because you've used unprintable characters. So, why not make a program that Hex Dumps itself?

## The Challenge

This challenge is to, given no input, output a Hex Dump of your source code in the following formatting:

```
0000: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0010: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0020: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0030: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................

```

Or, for example, if your program was `print("SomeString"):rep(123)`

```
0000: 70 72 69 6e 74 28 5c 22 53 6f 6d 65 53 74 72 69  print("SomeStrin
0010: 6e 67 5c 22 29 3a 72 65 70 28 31 32 33 29        g"):rep(123)

```

## Specifics

The hex dump is split into rows of three parts, each row representing 16 bytes of your source code.

The first part is the memory address. It specifies where the current row starts in your code. Written as a 2 Byte Hexadecimal number, followed by a `:`, then a space.

The Second, is the Hex Dump itself. This is 16 bytes of your Source Code, written in Hexadecimal form separated by spaces. This should be an accurate byte representation using your code's encoding.

Lastly, after a two space gap, is the code itself. This is simply 16 characters of your code, with Non printable characters written as `.`

## Notes

* This *is* a challenge, so Standard Quine Rules apply.
* And this is challenge too, so Standard Loopholes apply.
* As shown in the second example, do not write bytes after EOF, instead use whitespace.
* Trailing whitespace is fine.
* Inbuilts to Hex dump, if you happen to have one in this specific format, are not banned but are frowned upon.
* Non printable characters refer to any character that, represented as only a single byte, cannot be represented as a single spaced glyph. For UTF-8, this means `0-31`, `128-255`. For the Jelly Codepage, as all characters can be represented as a single spaced glyph, there are no Non printable characters.

# Answer
> 3 votes
# , 39 bytes

```
ñi241"qp:%!xxd
Î4x
Íøø / &
f&3i ÿ

```

Try it online!

Note that normally V uses the latin1 encoding, where this is 36 bytes (which is what TIO says) but this submission is using UTF-8 where it is 39 bytes.

This is pretty much just a modification of the V-quine template I wrote about.

# Answer
> 8 votes
# Perl, 81 bytes

```
#!perl -l
$_=q($%+=print"00$%0: @{[unpack'(H2)*']}  $_"for"\$_=q($_);eval"=~/.{16}/g);eval

```

Counting the shebang as one. Having the code length be a multiple of 16 saves quite a bit on formatting. Using `eval` to reassign `$_` to itself borrowed from ais523.

**Output:**

```
0000: 24 5f 3d 71 28 24 25 2b 3d 70 72 69 6e 74 22 30  $_=q($%+=print"0
0010: 30 24 25 30 3a 20 40 7b 5b 75 6e 70 61 63 6b 27  0$%0: @{[unpack'
0020: 28 48 32 29 2a 27 5d 7d 20 20 24 5f 22 66 6f 72  (H2)*']}  $_"for
0030: 22 5c 24 5f 3d 71 28 24 5f 29 3b 65 76 61 6c 22  "\$_=q($_);eval"
0040: 3d 7e 2f 2e 7b 31 36 7d 2f 67 29 3b 65 76 61 6c  =~/.{16}/g);eval

```

Try it online!

# Answer
> 5 votes
# Perl \+ xxd + cut, 61 bytes

```
$_=q(open F,"|xxd -g1|cut -c5-";print F"\$_=q($_);eval");eval

```

Try it online!

This is a universal quine constructor in Perl + a call to `xxd` and `cut` to do the hexdumping. None of the programs in question have a builtin to do a hexdump in the format in the question; however, `xxd -g1` comes very close and so it's possible to use `cut` to trim the output into the correct shape.

The universal quine constructor is `$_=q("\$_=q($_);eval");eval`, which creates a copy of its own source code in memory, and can be modified to perform arbitrary operations on it. In this case, I use `open "|"` and `print` to pipe the input into external programs, `xxd` which does the bulk of the hexdumping work and `cut` which changes it into the required format.

# Answer
> 3 votes
# JavaScript (ES6) ~~229~~ ~~219~~ 162 bytes

*Thanks to @Neil for saving a lot of bytes*

## Note

Quite a few people think accessing the source code of a function the way I do it is cheating, but according to @Dennis, it's fine. As such, I'll leave my answer here.

## Code

```
f=_=>([...c=`f=`+f].map(d=>d.charCodeAt()[t=`toString`](16)).join` `+` `.repeat(46)).match(/.{48}/g).map((s,i)=>`00${i[t](16)}0: `+s+c.substr(i*16,16)).join`\n`

```

## Usage

```
f()

```

Simply call the function with no arguments.

## Output

```
0000: 66 3d 5f 3d 3e 28 5b 2e 2e 2e 63 3d 60 66 3d 60 f=_=>([...c=`f=`
0010: 2b 66 5d 2e 6d 61 70 28 63 3d 3e 63 2e 63 68 61 +f].map(c=>c.cha
0020: 72 43 6f 64 65 41 74 28 29 5b 74 3d 60 74 6f 53 rCodeAt()[t=`toS
0030: 74 72 69 6e 67 60 5d 28 31 36 29 29 2e 6a 6f 69 tring`](16)).joi
0040: 6e 60 20 60 2b 60 20 60 2e 72 65 70 65 61 74 28 n` `+` `.repeat(
0050: 34 36 29 29 2e 6d 61 74 63 68 28 2f 2e 7b 34 38 46)).match(/.{48
0060: 7d 2f 67 29 2e 6d 61 70 28 28 73 2c 69 29 3d 3e }/g).map((s,i)=>
0070: 60 30 30 24 7b 69 5b 74 5d 28 31 36 29 7d 30 3a `00${i[t](16)}0:
0080: 20 60 2b 73 2b 63 2e 73 75 62 73 74 72 28 69 2a  `+s+c.substr(i*
0090: 31 36 2c 31 36 29 29 2e 6a 6f 69 6e 60 5c 6e 60 16,16)).join`\n`

```

# Answer
> 2 votes
## Ruby, ~~128~~ 112 bytes

```
eval b='7.times{|y|$><<"%04x:"%y*=16;c=("eval b="+(a=39.chr)+b+a)[y,16];c.chars{|x|$><<" %x"%x.ord};puts"  "+c}'

```

Without trailing newline.

Thanks primo for the idea of aligning to 16-byte boundary.

## Output

```
0000: 65 76 61 6c 20 62 3d 27 37 2e 74 69 6d 65 73 7b  eval b='7.times{
0010: 7c 79 7c 24 3e 3c 3c 22 25 30 34 78 3a 22 25 79  |y|$><<"%04x:"%y
0020: 2a 3d 31 36 3b 63 3d 28 22 65 76 61 6c 20 62 3d  *=16;c=("eval b=
0030: 22 2b 28 61 3d 33 39 2e 63 68 72 29 2b 62 2b 61  "+(a=39.chr)+b+a
0040: 29 5b 79 2c 31 36 5d 3b 63 2e 63 68 61 72 73 7b  )[y,16];c.chars{
0050: 7c 78 7c 24 3e 3c 3c 22 20 25 78 22 25 78 2e 6f  |x|$><<" %x"%x.o
0060: 72 64 7d 3b 70 75 74 73 22 20 20 22 2b 63 7d 27  rd};puts"  "+c}'

```

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


title: Decode MD5, Brute Force

text:
# Question
Title: Decode MD5, Brute Force
# The Challenge

Create a program that brute-force\* decodes the MD5-hashed string, given here: `92a7c9116fa52eb83cf4c2919599c24a` which translates to `code-golf`

# The Rules

1. You may *not* use any built-in functions that decode the hash for you if the language you choose has such.
2. You may *not* use an online service to decode the hash for you.
3. This is code-golf, the program that accomplishes the task in the shortest amount of *characters* wins.

**Good luck. May the brute-force be with you.**

*Brute-Force definition: looping from `a`-`zzz..` including `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=[]\;',./~!@#$%^&*()_+{}|:"`<>?` in a string, hashing it, and testing it against the hash given until the correct string that has been hashed has been found. Print the string to the program's output stream.

# Answer
> 5 votes
## Haskell, 101 characters

```
import Data.Hash.MD5
main=interact$ \m->head.filter((==m).md5s.Str)$iterate([' '..'~']:)[]>>=sequence

```

Use it like so:

```
& ghc -O2 -o brute 42043-BruteForce.hs
& echo -n c-g | md5
bc098aea57599de26c8f17a9edbd492e
& echo -n bc098aea57599de26c8f17a9edbd492e | ./brute
c-g

```

This requires the common package `MissingH`.

# Answer
> 4 votes
# PHP (155)

```
<?$a=[];function r($s){for($c=32;$c<127;$c++){$k=$s+chr($c);md5($k)=="92a7c9116fa52eb83cf4c2919599c24a"?die($k):array_push($a,$k)}r(array_shift($a))}r('');

```

Ungolfed:

```
<?
$a=[];
function r($s){
    for($c=32;$c<127;$c++){
        $k=$s+chr($c);
        md5($k)=="92a7c9116fa52eb83cf4c2919599c24a" ? die($k) : array_push($a,$k);
    }
    r(array_shift($a));
}
r('');

```

What it does is define an empty array $a, which will be our operations-to-do-later array. r is a recursive function and $s is the current string we're working with. We begin with an empty string, and loop through all the characters noted above, which are ASCII 32 to 127, and checking them all. While that happens, all of those are pushed onto the end of the array. Then, when all of the 1-length strings are done and all of them are put into the array, we now call r again with the first element in the array. Then, $s will be set to ASCII 32, and it will loop through 2 character strings that start with that character, checking them all and putting them at the end of the array. Since they are at the end, the next call to r will check ASCII 33 rather than them, since it is now the first one in the array. This prevents an infinite loop from occuring where it checks one ASCII 32 and then 2 ASCII 32's and then 3 ASCII 32's... etc.

# Answer
> 3 votes
# Python (182 characters)

```
import sys,string as c,hashlib as h,itertools as i
m=sys.stdin.read()
j=''.join
print(next(j(v)for n in i.count()for v in i.product(*n*(c.printable,))if h.md5(j(v)).hexdigest()==m))

```

Example:

```
$ echo -n Hi! | md5sum
5360706c803a759e3a9f2ca54a651950  -
$ echo -n 5360706c803a759e3a9f2ca54a651950 | python2.7 decode.py
Hi!

```

The `itertools` module does most of the work, with `.count()` responsible for gradual escalation. The nested generator expression is filtered until we get a match on the MD5 hash.

# Answer
> 0 votes
# bash - about 105 characters, not the greatest at golfing bash scripts!

Requires `makepasswd` and `openssl`.

```
until [ "$Y" = "$3" ]
do
    X=($(makepasswd --string=$1 --chars=$2))
    Y=($(echo -n $X | md5sum))
done
echo $X

```

You use it by supplying three arguments: *./reverse-md5 character-set length-of-password md5-hash-to-match*, e.g.:

```
$ ./reverse-md5 'ab' 4 54a8723466e5d487247f3d93d51c66bc
abba

```

Hoorah, have found the name of an obscure Swedish pop band!

Note that this is a directed attack in that you have some idea of the characters used and the length of the password.

So you could use the script in a directed attack as follows to complete the challenge:

```
$ ./reverse-md5 'cdefglo-' 9 92a7c9116fa52eb83cf4c2919599c24a
[wait a long time]
code-golf

```

Or as a brute force attack, run in parallel like this:

```
$ for L in `seq 1 20` ; do ./reverse-md5 '!"#$%&()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{|}~' $L 92a7c9116fa52eb83cf4c2919599c24a & done
[wait a really long time!]
code-golf

```

Which, depending on the hardware, may give you an answer faster than going sequentially from `'!'` to `'~~~...'`

# Answer
> 0 votes
# Hassium, 138 Bytes

```
use Math;func main(){d=["laptop","code-golf"];p="312f91285e048e09bb4aefef23627994";foreach(l in d){if(Math.hash("md5",l)==p)println(l);}}

```

Expanded: http://HassiumLang.com/Hassium/index.php?code=77bf67650e57549addd25daf7503db06

# Answer
> 0 votes
# Perl, 75 + 18 = 93 bytes

This program contains nonprintable characters, so here's a hexdump:

```
00000000: 245f 3d31 3b73 7c30 2a28 2e29 7c24 263d  $_=1;s|0*(.)|$&=
00000010: 7e79 3d20 2d7e 3d21 2d7e 203d 722e 3178  ~y= -~=!-~ =r.1x
00000020: 2124 317c 6520 7768 696c 6520 6d64 3528  !$1|e while md5(
00000030: 245f 296e 6527 92a7 c911 6fa5 2eb8 3cf4  $_)ne'....o...<.
00000040: c291 9599 c24a 273b 7361 79              .....J';say

```

This program requires the command line argument `-MDigest::MD5=md5` (an 18 byte penalty, 17 for the argument and 1 for the space separating it from the other arguments).

## Explanation

Here's the program with whitespace and comments added and the binary string replaced with `'…'`:

```
$_ = 1;                     # $_ is the string to check; start at '1'
s|0*(.)|                    # replace a string of leading 0s plus 1 character
  $& =~ y= -~=!-~ =r        # by rotating 1 printable ASCII character forward
  . 1 x !$1                 # and appending a 1 if the replaced section ends in 0
|e                          # (the previous two lines are a Perl expression)
    while md5($_) ne '…';   # while it has the wrong md5
say                         # print out the value of $_ we found

```

The basic trick here is that although we want to check from shortest to longest, there's no particular reason to check the characters in ASCIIbetical order. As a result, we check in the order from `1` to `~` then  to `0`. To do this, we repeatedly increment the first character after the leading 0s, and reset the leading 0s back to leading 1s (which we can do by incrementing every character up to and including the character after the leading 0s). If the string consists entirely of 0s, we need to append a new 1 to the end; we do this via checking to see if the string consists entirely of 0s via seeing if the last matched character in the regex is `0` (as the `0*` match is greedy, this will only happen if there are no non-`0` characters in the string).

The reason `1` and `0` are picked as the first and last character in the range is that a) they don't need quoting (the string `"1"` can be written as `1` because Perl doesn't really distinguish between strings and integers), and b) that Perl has a very short way (`!`) of checking a single-character string for equality with `0` (Perl has three falsey values: `undef`, `""`, and `"0"`, with all other values being truthy).

Note that we have no reason to translate the MD5 hash in question into hexadecimal; it's specified in the question, and so we can pack it into binary ourselves and just compare the binary representations directly. Perl's builtin for producing an md5 hash in binary has a shorter name than the hexadecimal equivalent, and the binary representation takes up half the space in the source, so this is a win in two different ways.

## Verification

I tested the program with the hash of the string `abc` inserted into the source code rather than the hash of the string `code-golf`, and it found the correct answer in 1.3 seconds. (It's unlikely to be able to reverse the hash of `code-golf` in a reasonable length of time, due to the need to check a substantial subset of the printable ASCII range.)

---
Tags: code-golf, hashing
---


title: Split arrays and programs in half

text:
# Question
Title: Split arrays and programs in half
## Introduction

You have been tasked to write a program that splits a rectangular integer array evenly in half (for whatever reason). This task is computationally intensive, but luckily you have a dual-core machine to perform the calculations. To maximize the benefits of parallelism, you decide to split the program evenly in half and let each core run one of the parts independently of the other.

## Input and output

Your input is a rectangular 2D array of nonnegative integers of size at least **1×1**, taken in any reasonable format. A *splitting* of such an array is obtained by splitting each horizontal row into a prefix and a suffix (either of which may be empty). For a splitting to be valid, two adjacent rows must be split at the same index or adjacent indices. For example, consider the array

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

```

This is a valid splitting:

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

```

This is also a valid splitting:

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

```

This is not a valid splitting:

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

```

Your output shall be the minimum value of

```
abs(sum_of_prefixes - sum_of_suffixes)

```

over all valid splittings of the input.

## Rules and scoring

You shall write **two** programs (either full programs or functions) in the same language, which must not have any shared code between them. Let's call them **P1** and **P2**. Program **P1** takes the input array, and outputs *something*. Program **P2** takes this something as input, and outputs the answer of the above task for the input array.

Your score is the **maximum** of the byte counts of **P1** and **P2**, lower score being better.

Some clarifications:

* You can write two full prorgams, one function and one full program, or two functions.
* In the case of two full programs, the entire output of **P1** is fed to **P2** as input, as in the Unix pipeline `P1 | P2`. The programs must function correctly if compiled/interpreted from two separate source files.
* If either program is a function, it is converted to a full program by adding the necessary boilerplate code, and the above rule is applied to it. In particular, two functions cannot use shared auxiliary functions, shared import statements, or shared global variables.

## Test cases

```
[[1]] -> 1
[[4,5],[8,3]] -> 4
[[8],[11],[8],[10],[4]] -> 1
[[5,7,0,9,11,2,1]] -> 7
[[146,194,71,49],[233,163,172,21],[121,173,14,302],[259,169,26,5],[164,30,108,37],[88,55,15,2]] -> 3
[[138,2,37,2],[168,382,33,77],[31,199,7,15],[192,113,129,15],[172,88,78,169],[28,6,97,197]] -> 7
[[34,173,9,39,91],[169,23,56,74,5],[40,153,80,60,28],[8,34,102,60,32],[103,88,277,4,2]] -> 0
[[65,124,184,141],[71,235,82,51],[78,1,151,201],[12,24,32,278],[38,13,10,128],[9,174,237,113]] -> 2
[[164,187,17,0,277],[108,96,121,263,211],[166,6,57,49,73],[90,186,26,82,138],[173,60,171,265,96]] -> 8

```

# Answer
> 3 votes
## Haskell, 102 bytes

Function 1 (102 bytes):

```
l=length
[]#i=[[]]
(r:s)#i=id=<<[(splitAt j r:)<$>s#j|j<-[i-1..i+1],j>=0,j<l r]
f r=(r#)=<<[0..l$r!!0]

```

Function 2 (90 bytes):

```
g::[[([Int],[Int])]]->Int
g a=minimum$map(\(x,y)->abs$sum(sum<$>x)-sum(sum<$>y))$unzip<$>a

```

Missing boilerplate for F1 to make it a full program, including the hardcoded integer array to check:

```
main = print $ f [[164,187,17,0,277],[108,96,121,263,211],[166,6,57,49,73],[90,186,26,82,138],[173,60,171,265,96]]

```

and for F2:

```
main = print . g . read =<< getContents

```

Now you can call `runhaskell f1.hs | runhaskell f2.hs` which outputs `8`.

How it works: `f` takes a list of list of integers.

```
f r = (r#)=<<[0..l$r!!0]          -- for each index [0 .. length r] call # with
                                  -- the first parameter being r and
                                  -- collect the results in a single list

[]#i=[[]]                         -- base case. If the list of lists is empty, stop
(r:s)#i                           -- else let r be the first list, s all others
           j<-[i-1..i+1],         -- foreach possible index j for the next line
                 j>=0,j<l r       --    (skipping out of range indices)
     (splitAt j r:)<$>            -- split the current line at j into a pair of
                                  -- lists and prepend it to every element of
                      s#j         -- a recursive call with s and j
id=<<                             -- flatten into a single list

```

Now we have a list of all possible splits, for example the first one and a random one from the middle

```
[([],[164,187,17,0,277]),                  [([164,187],[17,0,277]),
 ([],[108,96,121,263,211]),                 ([108,96],[121,263,211]),
 ([],[166,6,57,49,73]),                     ([166],[6,57,49,73]),
 ([],[90,186,26,82,138]),                   ([90,186],[26,82,138]),
 ([],[173,60,171,265,96])]                  ([173,60,171],[265,96])]

```

Function `g` takes such a list and

```
                    unzip<$>a       -- turn every pair of lists into a list of pairs
  map(\(x,y)->                      -- foreach such pair
      abs$sum(sum<$>x)-sum(sum<$>y) -- calculate the score
minimum                             -- and find the minimum

```

Note: the second function can be golfed a little bit more, but it doesn't change the score.

---
Tags: code-challenge, array, optimization
---


title: Diff compression

text:
# Question
Title: Diff compression
For this challenge, you need to compress a diff. **A diff is some data that represents the difference between two strings.** For this challenge, you need to provide one or more programs that can:

1. Input `A` and `B`, and output a diff, `C`
2. Input `A` and `C`, and output `B`
3. Input `B` and `C`, and output `A`

**The goal is to make the diff, `C`, as small as possible.** The diff can be anything: a string, a number, a blob of data. We just care about the size (number of bytes).

I have 50 test cases that can found on Github. Each test case consists of two space-separated URLs which point to the 2 files you need to diff. (These test cases originated from PPCG members' Github profiles. Thanks all!)

All three tasks above should take under a minute to run on a reasonably powered computer (for each test case).

Your score is equal to the total size (in bytes) of all 50 diffs, lower is better. Hardcoding diffs in your program is not allowed (I reserve the right to change the test cases to prevent hardcoding). Builtins that produce a diff (like `diffutils`) are not allowed.

# Answer
Is my answer valid?

```
set f [open commits.txt]
while {![eof $f]} {scan [gets $f] %s\ %s a b; puts [string compare $a $b]}
close $f

```

testable on: http://www.tutorialspoint.com/execute\_tcl\_online.php?PID=0Bw\_CjBb95KQMNmd4QkxvQUFsTnM
> 0 votes

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


# Question
Title: Convert numbers to symbols without string or char literals
Read infinitely from stdin, and convert every number to the corresponding symbol on a US qwerty keyboard.

No string or character literals anywhere are permitted.

E.g. if the input is `117758326`, the output is `!!&&%*#@^`.

Letters and symbols that aren't on numbers are left alone; `11g2;;'1g2311hh21930` turns into `!!g@;;'!g@#!!hh@!(#)`

Shortest code, in bytes, wins.

For those who don't have a US qwerty keyboard, use the following as a guide:

```
1 -> !
2 -> @
3 -> #
4 -> $
5 -> %
6 -> ^
7 -> &
8 -> *
9 -> (
0 -> )

```

# Answer
## C, 90 bytes

The line between a character and an integer literal is a very fine one in C.

```
a[]={8,0,31,2,3,4,61,5,9,7};main(d){for(;~(d=getchar());)putchar(d>47&d<58?a[d-48]+33:d);}

```
> 5 votes

# Answer
## Perl - 74 57 42

Update thanks to core1024's comment:

```
s/\d/chr 33+(8,0,31,2..4,61,5,9,7)[$&]/eg

```

Run with:

```
perl -p program_name.pl

```

---

Update thanks to manatwork's comment:

```
say s/\d/chr@{[8,0,31,2,3,4,61,5,9,7]}[$&]+33/erg while<>

```

Test with:

```
perl -E 'say s/\d/chr@{[8,0,31,2,3,4,61,5,9,7]}[$&]+33/erg while<>'

```

---

Old attempts:

```
say s/[1234567890]/chr qw(41 33 64 35 36 37 94 38 42 40)[$&]/erg while(<>)

```

Using `qw` counts as a string literal though.

Test:

```
perl -E 'say s/[1234567890]/chr qw(41 33 64 35 36 37 94 38 42 40)[$&]/erg while(<>)'

```

Another way: Perl 40 - I think this counts as a string literal as well.

```
say tr/1234567890/!@#$%^&*()/r while(<>)

```

Test with:

```
perl -E 'say tr/1234567890/!@#$%^&*()/r while(<>)'

```
> 3 votes

# Answer
# JavaScript (ES6) - ~~79~~ ~~76~~ 87

*Edit* \- bloated out by 11 chars after it was pointed out that it failed the "non-numbers are left alone" rule (thanks @soktinpk)

*Warning* \- you'll need to reload your browser after you run it since it's following the "Read infinitely from stdin" bit...

```
(f=x=>f(alert(+(p=prompt())+1?String.fromCharCode([8,0,31,2,3,4,61,5,9,7][p]+33):p)))()

```

Note that I've interpreted `prompt` as `stdin` & `alert` as `stdout`

Tested in Firefox console.
> 2 votes

# Answer
# Pyth, 43

```
W1sm?C+33@[8Z31 2 3 4 61 5tT7)vd}Cdr48 58dw

```

Uses 33+table lookup, instead of straight table lookup. No translate function here, just a normal map. Note that Z=0 and tT=9.
> 1 votes

# Answer
## Scala, 106 bytes

```
def f{println(readLine.map{c=>try{(Seq(8,0,31,2,3,4,61,5,9,7)(c.toInt-48)+33).toChar}catch{case _=>c}});f}

```

Pretty-printed:

```
def f {
  println(readLine.map { c =>
    try {
      (Seq(8,0,31,2,3,4,61,5,9,7)(c.toInt - 48) + 33).toChar
    } catch {
      case _ => c
    }
  })
  f
}

```
> 1 votes

# Answer
# pyg-i (68)

Here is a solution in pyg-i, a fork of pyg I created:

```
while 1:P(Ip().t(dict(Z(R(48,58),(41,33,64,35,36,37,94,38,42,40)))))

```

The python 3 equivalent would be this:

```
while 1:print(input().translate(dict(zip(range(48,58),(41,33,64,35,36,37,94,38,42,40)))))

```

Or, with a little cheating, it can be done in 50 bytes. Note that this is a *bytes* literal, not a string literal:

```
while 1:P(Ip().t(dict(Z(R(48,58),b"(!@#$%^&*("))))

```
> 0 votes

# Answer
# CoffeeScript (70)

**Update**: This may be seen as reading between the lines, but while strings and characters aren't allowed, regexs are. (I just converted the regex to a string).

```
alert prompt().replace /\d/g, (t)->([]+/!@#$%^&*()/)[1...-1][(+t+9)%10]

```

Or (for infinite)

```
loop alert prompt().replace /\d/g, (t)->([]+/!@#$%^&*()/)[1...-1][(+t+9)%10]

```

The normal version (in case regex isn't allowed):

```
alert prompt().replace(/\d/g, (t) ->String.fromCharCode(([]+4133643536+3794384240).match(/\d{2}/g)[t]))

```

Test it out here.

But, according to the problem statement,

> Read **infinitely** from stdin

That will probably hang your browser eventually, but here it is (just prepend `loop`, extra 5 bytes, to the code):

```
loop alert prompt().replace(/\d/g, (t) ->String.fromCharCode(([]+4133643536+3794384240).match(/\d{2}/g)[t]))

```
> 0 votes

# Answer
# Befunge 98 - 119 bytes

This is also with the STRN fingerprint, that allows "S" to stand for a ***convert integer to string*** instruction.

```
v>0 NRTS 4( >&S v         >$a,v
5 )!@#$%^&*(    >:1       w1  v
7^       p<     ^,g1--3*77<
>*1-:30p80^ ^                 <

```
> 0 votes

# Answer
**Haskell, 89**

```
f 50=64
f 54=94
f 55=38
f 56=42
f 57=40
f 48=41
f x|x<48||x>57=x|0<1=x-16
g=map$chr.f.ord

```

tests:

Prelude\> g "11g2;;'1g2311hh21930"

"!!g@;;'!g@#!!hh@!(#)"

Prelude\> g "117758326"

"!!&&%\*#@^"
> 0 votes

# Answer
# CJam - 32

```
qA,s26063649909601297730 95b:cer

```

Try it at http://cjam.aditsu.net/

**Explanation:**

`q` reads the whole input
`A,` creates the array \[0 1 ... 9\] (A=10)
`s` converts to string, obtaining "0123456789"
`95b` converts the previous big number to an array of base-95 digits, which are the ASCII codes of the 10 symbols we want
`:c` converts the ASCII codes to characters, obtaining the string `")!@#$%^&*("`
`er` transliterates "0123456789" to ")!@#$%^&\*(" in the input string
> 0 votes

# Answer
# tcl, 156

```
proc x n {format %c $n}
while 1 {puts [string map "1 [x 33] 2 [x 64] 3 [x 35] 4 [x 36] 5 [x 37] 6 [x 94] 7 [x 38] 8 [x 36] 9 [x 40] 0 [x 41]" [gets stdin]]}

```

testable on http://www.tutorialspoint.com/execute\_tcl\_online.php?PID=0Bw\_CjBb95KQMRE4tMlc3cmJhNG8
> 0 votes

# Answer
**PYTHON: 166 86**

Not better than the current answers, but the shortest Python solution I can think of as of yet.

(thanks to pseudonym117 for helping me shorten this significantly)

```
def g(s):
 d=')!@#$%^&*('
 g=''
 for c in s:
  try:g+=d[int(c)]
  except:g+=c
 yield g

```
> -1 votes

---
Tags: code-golf, restricted-source
---


title: XOR two monochrome images

text:
# Question
Title: XOR two monochrome images
## Challenge:

Take input of two black and white (monochrome) images and xor each pixel of the first, with each pixel of the second, add them to a new image and output the new image.

## Some clarifications:

Size of pictures does not matter. Extension/Image format doesn't matter. You can make it take input any extension and output any extension, as long as the extension is used to store digital images. You can also use graphics to draw the output in eg: a picturebox if you wish. Otherwise, save the output as a file. Input can be taken as a path to the image, or url.

One thing you can't do however, is I/O arrays, eg. of triplets(R,G,B).

Do NOT tamper with alpha. It should not be xored, it should be 255 (max value) for every pixel.

## What do you mean xor each pixel?

You don't have to do it this way, but one way to xor two pixels is to take their RGB values and xor R1 with R2, G1 with G2, B1 with B2, and take the result, which is your new color

Since we have only two colors, obviously when the colors are the same the result would be (0,0,0) and when they are different (white is 255,255,255 and black is 0,0,0) in this case, the result would be 255,255,255.

Thus when two pixels are different, the result is a white pixel, else a black pixel

## Example I/O:

---

Input 1: Input 2:

---

Output:

---

This is so shortest code wins.

# Answer
> 20 votes
# The Fx Expression Language (ImageMagick), ~~8~~ 4 bytes

EDITS

* Simplified to `u!=v`, -4 bytes

As "Fx Expression Language" is apparently Turing complete, I've re-profiled my answer to it (was Unix Shell + Image Magick).

**Golfed**

```
u!=v

```

*Fx* does not support bitwise *XOR* nor bitwise *NOT*, so I've used `!=` instead (which works just fine for the pure BW images).

```
u=> stands for "first image in list"
v=> "second image in list"

```

Input and output are implicit (controlled by the interpreter).

**Usage**

ImageMagick *convert* utility, serves as the "Fx Expression Language" interpreter, when invoked with `-fx`, as illustrated below:

```
convert $1 $2 -fx u!=v $3

```

The arguments are:

1. Input image *A*
2. Input image *B*
3. Output image *O* (A^B).

**Sample output**

```
convert a.png b.png -fx u!=v o.png

```

# Answer
> 15 votes
# Mathematica, ~~37~~ ~~34~~ 15 bytes

*Thanks to Ian Miller for cutting the number of bytes by more than half!*

```
ImageDifference

```

In the end, there's always a builtin. This function takes two images as input and outputs an image; it does something more complicated for color images, but for black-and-white it's exactly XOR.

Previous submissions:

*Thanks to JungHwan Min for saving 3 bytes!*

```
Image[BitXor@@Chop[ImageData/@#]]&

```

Unnamed function that takes an ordered pair of images (of compatible dimensions) as input, and returns a displayed image. `ImageData` gets only the pixel data without all the wrappers/metadata; unfortunately it returns real numbers, so `Chop` is needed to help treat them as integers. `BitXor` does exactly what it says on the tin (and threads over nested lists), and `Image` turns the resulting RGB back into an image.

Original submission, which took an ordered pair of URLs or filenames a input:

```
Image[BitXor@@(#~Import~"Data"&/@#)]&

```

# Answer
> 10 votes
# Java, 336 335 328 bytes

```
import static javax.imageio.ImageIO.*;import java.io.*;public class M{static void main(String[]y)throws Exception{java.awt.image.BufferedImage a=read(new File("a.png"));for(int i=0,j;i<a.getHeight();i++)for(j=0;j<a.getWidth();)a.setRGB(j,i,a.getRGB(j,i)^read(new File("b.png")).getRGB(j++,i));write(a,"png",new File("c.png"));}}

```

## Ungolfed:

```
import static javax.imageio.ImageIO.*;

import java.io.*;

class M {
    public static void main(String[]y) throws Exception {
        java.awt.image.BufferedImage a = read(new File("a.png"));
        for (int i = 0, j; i < a.getHeight(); i++)
            for (j = 0; j < a.getWidth(); ) a.setRGB(j, i, a.getRGB(j, i) ^ read(new File("b.png")).getRGB(j++, i));
        write(a, "png", new File("c.png"));
    }
}

```

# Answer
> 9 votes
# Python, ~~64~~ ~~60~~ 57 bytes

I'm new to golfing so have some mercy!

```
from cv2 import*
r=imread;lambda a,b:imshow('c',r(a)^r(b))

```

Thanks to @Blender and @FlipTack for saving me 7 bytes!

# Answer
> 8 votes
# MATL, 10 bytes

```
YiiYiY~1YG

```

### Explanation

This is basically the same answer, as the existing Octave solution: It takes the file names or URLs of both images as inputs and displays the result on the screen.

```
Yi    % Read first image from the URL or filename (implicit input)
i     % Get the second URL or filename as input
Yi    % Read that second image
Y~    % XOR the two images
1     % Push 1 (needed to make YG act as imagesc)
YG    % Display result using the MATLAB imagesc function

```

### Usage

```
>> matl
 > YiiYiY~1YG
 >
> 'https://i.stack.imgur.com/UbbfM.png'
> 'https://i.stack.imgur.com/YyZG2.png'

```

# Answer
> 7 votes
# Octave, ~~43~~ ~~38~~ 34 bytes

```
@(a,b)imshow(imread(a)~=imread(b))

```

Thanks to flawr saved me 5 bytes.

Thanks to Luis Mendo saved me 4 bytes suggested to use `a~=b` instead of `xor(a,b)`.

A function that takes as input file name of the two input images `a,b` and shows the result.

Previous answer that writes to a file:

```
@(a,b,c)imwrite(imread(a)~=imread(b),c)

```

A function that takes as input file name of the two input images `a,b` and file name of the output image `c`.

Usage:

```
#two test images that used in the question
#https://i.stack.imgur.com/UbbfM.png
#https://i.stack.imgur.com/YyZG2.png
A = "UbbfM.png";
B = "YyZG2.png";
C = "out.png";
(@(a,b,c)imwrite(imread(a)~=imread(b),c))(A,B,C)

```

Result is saved in `out.png`

# Answer
> 7 votes
# Processing, ~~124~~ ~~118~~ 117 bytes

```
void m(PImage a,PImage q){for(int i=0,j;i<400;i++)for(j=0;j<400;point(i,j++))stroke((a.get(i,j)^q.get(i,j))<9?0:-1);}

```

Usage:

> **Note:** this code can support images up to `400px` (with modifications can support upto 999 for the same bytecount). Any "leftover" space will be coloured black, so for best results, the image size should be the same size as the dimensions in the code (also the `size()` needs to be changed with the updated dimensions)

```
m(loadImage("http://i.imgur.com/a0M6o9e.png"),loadImage("http://i.imgur.com/bP1TsjQ.png"));

```

```
m(loadImage("https://i.stack.imgur.com/UbbfM.png"),loadImage("https://i.stack.imgur.com/YyZG2.png"));

```

### Ungolfed

```
void Q106945(PImage a,PImage q){     // takes two images as input
  for(int i=0,j;i<400;i++)           // looping through the x-coordinates
    for(j=0;j<400;point(i,j++))      // looping through the y-coordinates
      stroke((a.get(i,j)^q.get(i,j))<9?0:-1);
/*
Here we have to colour the point according to the xor. So we do a simple
a.get(i,j)^q.get(i,j). But since the alpha gets xored, instead of outputting white, this
outputs a colour with alpha 0 (completely invisible). So to fix this I have a ternary that
checks the value and changes the colour accordingly. At the end of all this, the third
statement of the for-loop with j gets triggered since all this code is in this for-loop.
Now we draw a point over the coordinate with the colour we have chosen before.
*/
}

```

# Answer
> 7 votes
## JavaScript (ES6), 253 bytes

**\- ~~12~~ 20 bytes saved by Ismael Miguel**
**\- 2 bytes saved by user2428118**

Expects already loaded images, takes the last input's size as output size and returns a canvas element.

```
(i,j)=>(c=i=>{with(document.createElement(C='canvas')){({width,height}=i);return getContext`2d`}},g=i=>(x=c(i),x.drawImage(i,0,0),x.getImageData(0,0,1e4,1e4)),a=g(i),b=g(j).data,d=a.data,d.forEach((e,i)=>d[i]=i%4>2?e:e^b[i]),x.putImageData(a,0,0),x[C])

```

```
let func = (i,j)=>(c=i=>{with(document.createElement(C='canvas')){({width,height}=i);return getContext`2d`}},g=i=>(x=c(i),x.drawImage(i,0,0),x.getImageData(0,0,1e4,1e4)),a=g(i),b=g(j).data,d=a.data,d.forEach((e,i)=>d[i]=i%4>2?e:e^b[i]),x.putImageData(a,0,0),x[C])

window.onload =_=>{
  document.body.appendChild(func(img1, img2));
}
```

```
<img id="img1" crossOrigin="anonymous" src="https://dl.dropboxusercontent.com/s/nnfkzpvabk77pnl/UbbfM.png">
<img id="img2" crossOrigin="anonymous" src="https://dl.dropboxusercontent.com/s/58euf43vcb9pvpa/YyZG2.png">
```

**Ungolfed**

```
(i, j) => (
  c = i => { // an helper to create a canvas object with the input's dimension
    with(document.createElement(C='canvas')) {
      ({width, height}=i); // set the canvas size
      return getContext`2d`
    }
  },
  g = i => ( // an helper to get an ImageData object from an Image
    x = c(i),
    x.drawImage(i, 0, 0),
    x.getImageData(0, 0, 1e4, 1e4) // 1e4 x 1e4 px should be big enough
                                   // (bigger might not be supported by the browser)
  ),
  a = g(i),
  b = g(j).data,
  d = a.data,
  d.forEach((e, i) => {    // loop through all rgba values
    d[i] = i % 4 > 2       // we need to special handle the alpha channel
      ? e :                // keep the alpha of the first input
      e ^ b[i]             // xor the rgb values
  }),
  x.putImageData(a, 0, 0), // put that back on the last context we created
  x[C]                     // return its canvas
}

```

**Could be even further golfed (220 bytes) with a fixed 300\*150px size (all remaining is transparent black)** as in the Processing answer

```
(c=i=>document.createElement(C='canvas').getContext('2d'),g=i=>(x=c(i),x.drawImage(i,0,0),x.getImageData(0,0,1e4,1e4)),a=g(i),b=g(j).data,d=a.data,d.forEach((e,i)=>d[i]=i%4>2?e:e^b[i]),x.putImageData(a,0,0),x[C])

```

```
let func = (i,j)=>(c=i=>document.createElement(C='canvas').getContext('2d'),g=i=>(x=c(i),x.drawImage(i,0,0),x.getImageData(0,0,1e4,1e4)),a=g(i),b=g(j).data,d=a.data,d.forEach((e,i)=>d[i]=i%4>2?e:e^b[i]),x.putImageData(a,0,0),x[C])

window.onload =_=>{
  document.body.appendChild(func(img1, img2));
}
```

```
<img id="img1" crossOrigin="anonymous" src="https://dl.dropboxusercontent.com/s/nnfkzpvabk77pnl/UbbfM.png">
<img id="img2" crossOrigin="anonymous" src="https://dl.dropboxusercontent.com/s/58euf43vcb9pvpa/YyZG2.png">
```

# Answer
> 3 votes
## Perl, 260 bytes

251 bytes of code + 9 bytes for `-MImager`.

```
($i,$j)=map{new Imager(file,pop)}0,1;$p=getpixel;for$x(0..$i->getwidth()-1){$i->setpixel(x=>$x,y=>$_,color=>[map{($j->$p(%t)->rgba)[$c++%3]^$_?0:255}($i->$p(%t=(x=>$x,y=>$_,type=>'8bit'))->rgba)[0..2]])for 0..$i->getheight()-1}$i->write(file=>'a.png')

```

I'm not sure Perl is the best language for this challenge, but I wanted to know what was the image of @orlp's comment. And it makes me use a little bit of those graphic modules, that's a good thing. And I enjoyed coding it!

A more readable version:

```
use Imager;
$img1 = new Imager( file => $ARGV[1] );
$img2 = new Imager( file => $ARGV[0] );

for $x ( 0 .. $img1->getwidth()-1 ) {
    for $y ( 0 .. $img1->getheight()-1 ) {
    ($r1, $g1, $b1) = $img1->getpixel( x => $x, y => $y, type => "8bit" )->rgba();
    ($r2, $g2, $b2) = $img2->getpixel( x => $x, y => $y, type => "8bit" )->rgba();
    $r = $r1 ^ $r2 ? 0 : 255 ;
    $g = $g1 ^ $g2 ? 0 : 255 ;
    $b = $b1 ^ $b2 ? 0 : 255 ;
    $img1->setpixel( x => $x, y => $y , color => [ $r, $g, $b] );
    }
}
$img1->write( file => 'a.png' )

```

You'll need to install Imager if you want to try it, but it's quite simple: just run `(echo y;echo) | perl -MCPAN -e 'install Imager'` in your terminal.

# Answer
> 3 votes
# LÖVE2D, 199 bytes

```
u,c=... i=love.image.newImageData a=math.abs X=i(u)Y=i(c)Z=i(X:getDimensions())Z:mapPixel(function(x,y)r,g,b=X:getPixel(x,y)R,G,B=Y:getPixel(x,y)return a(r-R),a(g-G),a(b-B)end)Z:encode("png","Z")

```

Simple enough, takes two image files on the command line, outputs a file called "Z" to the Love directory. Also works for full colour images!

# Answer
> 2 votes
# J, 54 bytes

```
load'bmp'
'o'writebmp~256#.255*~:&*&((3#256)#:readbmp)

```

Takes two arguments where each is the path to an input image in `bmp` format. Each image is read as a matrix of 24-bit RGB integers and parsed into a triplet of 8-bit RGB values, the sign of each is taken, and the two matrices are XOR'd together. The result is then scaled by 255, converted back from a triplet of base 256 numbers into an integer, and written to an output `bmp` file named `o`.

# Answer
> 2 votes
# C#, 233 bytes

```
using System.Drawing;class C{static void Main(){Bitmap
a=new Bitmap("a"),b=new Bitmap("b");for(int
x=0,y=0;;)try{a.SetPixel(x,y,a.GetPixel(x,y)==b.GetPixel(x,y)?Color.Black:Color.White);x++;}catch{if(x<1)break;x=0;++y;}a.Save("c");}}

```

Thanks to Unknown6656 for the tip that command line arguments are not necessary. The program now reads from files "a" and "b" and writes to file "c" in the same format as "a". Off by one error fixed too.

It sets each pixel to black if the colour is the same, otherwise white.

To save bytes, it catches out of bounds exceptions, rather than checking the Width and Height properties of the Bitmaps. Each time x goes out of bounds it is reset to 0, and y is incremented. When y goes out of bounds, x is 0 and the loop breaks to save the image and quit.

Example compile using csc and run using mono:

```
csc xor.cs

mono xor.exe

```

# Answer
> 2 votes
# C, 189 bytes

```
#include<stdio.h>
s,t[9];
#define o(f,p)int*f=fopen(p,"ab+");
#define f(p,q,r)o(a,p)o(b,q)o(c,r)fscanf(a,"%*s %*d %*d %n",&s);for(fwrite(t,1,fread(t,1,s,b),c);s=~getc(a);putc(~s^getc(b),c))

```

Operates on PBM images. Call `f(a, b, out)` with the names of both input files and the output file.

Assumptions:

* Both input image headers are identical (whitespace included), and are less than `9 * sizeof(int)` characters.
* We're on a nice OS that flushes and closes leaked files.
* `EOF == -1`

**Ungolfed and explained:** (backslashes omitted)

```
// Scratch variable and "big enough" buffer
s, t[9];

// Opens a file in read/append binary mode
#define o(f,p)int*f=fopen(p,"ab+");

#define f(p, q, r)

    // Open the three file pointers a, b, c from the paths p, q, r
    o(a, p)
    o(b, q)
    o(c, r)

    // Read from a to locate the end of the PBM header
    fscanf(a, "%*s %*d %*d %n", &s);

    for(
        // Read the header from b into the buffer,
        // then write it back from the buffer to c
        fwrite(t, 1, fread(t, 1, s, b), c);

        // Loop condition: get the next byte from a
        // and check for EOF with a bitwise-not
        // (Assumes that EOF == -1)
        s = ~getc(a);

        // Loop increment: get the next byte from b,
        // flip s back, xor and write to c
        putc(~s ^ getc(b), c)

    ) // Snatch the semicolon from the call syntax :)

```

---

# C (spec-bending), 149 bytes

```
#include<stdio.h>
t[7];
#define o(f,p,u)int*f=fopen(p,"ab+");u(t,1,7,f);
#define f(p,q,r)o(a,p,fread)o(b,q,fread)o(c,r,fwrite)putc(getc(a)^getc(b),c)

```

Still uses PBM files, but now:

* The image has to be one pixel high and 8 pixels wide or less, because PBM packs 8 pixels in a byte.
* The header has to be 7 bytes (e.g. `P4 8 1` with a trailing space).

Both files are seeked forwards while filling `t` with their header, then the last bytes are read, xor'd and written back. Takes advantage of `fread` and `fwrite` having similar parameter lists to factor all three operations on the header behind the same macro.

# Answer
> 2 votes
## R, 45 bytes

```
p=png::readPNG;plot(as.raster(+(p(a)!=p(b))))

```

`a`and `b` represent the file names of the two image files.

Example:

```
a <- "YyZG2.png"
b <- "UbbfM.png"
p=png::readPNG;plot(as.raster(+(p(a)!=p(b))))

```

Output:

# Answer
> 2 votes
# Processing, 82 bytes

```
void x(PImage a,PImage b){int x=b.width;b.blend(a,0,0,x,x,0,0,x,x,32);set(0,0,b);}

```

Abuses Processing's extensive drawing functions to avoid actually doing any XORing. Blends the two images together with `DIFFERENCE` mode and draws them to the screen.

### Usage

```
x(loadImage("http://i.imgur.com/a0M6o9e.png"),loadImage("http://i.imgur.com/bP1TsjQ.png"));

```

### Ungolfed

```
void xor(PImage a, PImage b) {
  int x = a.width;
  b.blend(a, 0, 0, x, x, 0, 0, x, x, DIFFERENCE);
  set(0, 0, b);
}

```

# Answer
> 1 votes
# Clojure, 300 bytes

```
(ns s(:import[java.io File][java.awt.image BufferedImage][javax.imageio ImageIO]))(defn -main[](let[a(ImageIO/read(File."a.png"))](doseq[i(range(.getHeight a))j(range(.getWidth a))](.setRGB a j i(bit-xor(.getRGB a j i)(.getRGB(ImageIO/read(File."b.png")) j i))))(ImageIO/write a"png"(File."c.png"))))

```

Blatant rip-off of the Java answer. I didn't know how to do the challenge, but was curious how well the Java solution translated into Clojure. It was pretty straightforward. The ungolfed code is actually kind of pretty.

This was the first code-golf challenge I've done that included imports. There's probably a way to optimize them to save some bytes.

Ungolfed:

```
(ns bits.golf.bit-or-picts
  (:import [java.io File]
           [java.awt.image BufferedImage]
           [javax.imageio ImageIO]))

(defn -main []
  (let [^BufferedImage a (ImageIO/read (File. "a.png"))
        ^BufferedImage b (ImageIO/read (File. "b.png"))]
    (doseq [i (range (.getHeight a))
            j (range (.getWidth a))]
      (.setRGB a j i
                (bit-xor (.getRGB a j i)
                         (.getRGB b j i))))
    (ImageIO/write a "png" (File. "c.png"))))

```

# Answer
> 1 votes
## PHP, ~~246~~ 243 bytes

I can probably golf this down more.

```
$o=imagecreatetruecolor($w=max(imagesx($a=($i=imagecreatefrompng)($argv[1])),imagesx($b=$i($argv[2]))),$h=max(imagesy($a),imagesy($b)));for(;$k<$w*$h;)imagesetpixel($o,$x=$k%$w,$y=$k++/$w,($t=imagecolorat)($a,$x,$y)^$t($b,$x,$y));imagepng($o);

```

Run it from the command line like this:

```
php -d error_reporting=0 -r "$o=imagecreatetruecolor($w=max(imagesx($a=($i=imagecreatefrompng)($argv[1])),imagesx($b=$i($argv[2]))),$h=max(imagesy($a),imagesy($b)));for(;$k<$w*$h;)imagesetpixel($o,$x=$k%$w,$y=$k++/$w,($t=imagecolorat)($a,$x,$y)^$t($b,$x,$y));imagepng($o);" "https://i.stack.imgur.com/UbbfM.png" "https://i.stack.imgur.com/YyZG2.png" > output.png

```

# Answer
> 0 votes
# Node.js, ~~156~~ 135 bytes

```
(a,b)=>(f=require('fs')).writeFile(a+b,((s=f.readFileSync)(a)+'').replace(/\d+$/,(c,d)=>[...c].map((e,f)=>+!(e^(s(b)+b)[f+d])).join``))

```

Input and output image files should be in the PBM (P1) format, where the first line is `P1 [width] [height]`, and the second line is the b/w ascii values without spaces.

Here's a the input images followed by the xor output (32x32 pixels):

---
Tags: code-golf, graphical-output, image-processing
---


title: Can you Meta Quine?

text:
# Question
Title: Can you Meta Quine?
Similar to other quine puzzles (more specifically, this one), write a program that produces the source for itself.

**Here's the new twist:** The code produced should *NOT* be identical to the source. Rather, it should output a different program that will create the first.

The challenge linked to above achieved that by jumping between two languages. I'm thinking this one would be done in **just one language**, but the two (or more) versions of the source should be significantly different (see rules below). With this constraint, single character answers would be disallowed, thus requiring a little more thought be put into a final submission.

---

**RULES**

1. Your code must be produced in just one language. (Multiple submissions, one for each language is perfectly acceptable.)
2. Your different code versions must be syntactically distinct. In other words, if you were to draw out an abstract syntax tree for your code, there should be at least one node different.
    * Supplying an **AST** will not be necessary, but if you feel inclined to provide one for each of your programs, it *would* help in judging.
3. You may produce as many iterations as you wish, as long as they all remain syntactically distinct. (More will help your score, see below.)

---

**SCORING**

Your final score will be the mean length of all your programs, divided by the number of programs.

Example 1:

> A (source for B) = 50 characters
> B (source for A) = 75 characters
> Final Score = **31.25**

Example 2:

> A (source for B) = 50 characters
> B (source for C) = 75 characters
> C (source for A) = 100 characters
> Final Score = **25**

# Answer
## Python, 0 (limit of (68+3 *n* )/(16*n*))

If two abstract syntax trees are different if they have different constants,

```
r='r=%r;n=(0x%XL+1)%%0x10...0L;print r%%(r,n)';n=(0xF...FL+1)%0x10...0L;print r%(r,n)

```

there are 16*n* programs of length at most 68+3n, giving asymptotic score of 0.

If you want programs with variable structure, we can implement a binary adder on *n* bits. Here, there are 2*n* programs of length *O*( *n*2). Goes in a cycle due to dropped carry bit.

```
s="""
print 's='+'"'+'"'+'"'+s+'"'+'"'+'"'
n=lambda m:reduce(lambda (s,c),y:(s+(c^y,),c&y),m,((),1))[0]
print s[:112]
t=n(t)
print "t=(%s,)+(0,)*%s"%(t[0],len(t)-1)
for i in range(len(t)-1):
    print i*' '+'for i in range(2):'
    print ' '+i*' '+['pass','t=n(t)'][t[i+1]]
print s[113:-1]
"""

print 's='+'"'+'"'+'"'+s+'"'+'"'+'"'
n=lambda m:reduce(lambda (s,c),y:(s+(c^y,),c&y),m,((),1))[0]
print s[:112]
t=(0,)+(0,)*10
for i in range(2):
 t=n(t)
 for i in range(2):
  t=n(t)
  for i in range(2):
   t=n(t)
   for i in range(2):
    t=n(t)
    for i in range(2):
     pass
     for i in range(2):
      t=n(t)
      for i in range(2):
       pass
       for i in range(2):
        pass
        for i in range(2):
         pass
         for i in range(2):
          t=n(t)
t=n(t)
print "t=(%s,)+(0,)*%s"%(t[0],len(t)-1)
for i in range(len(t)-1):
    print i*' '+'for i in range(2):'
    print ' '+i*' '+['pass','t=n(t)'][t[i+1]]
print s[113:-1]

```
> 38 votes

# Answer
## C++, score of 0.734194

The following source code prints a meta quine of order 999 to the console (explanation below):

```
#define X 1*(1+1)
#include<iostream>
#include<vector>
#define Q(S)auto q=#S;S
Q( \
  main() \
  { \
      using namespace std; \
      cout<<"#define X 1"; \
      int x=X==2?1000:X-1; \
      vector<int> factors; \
      for ( int p = 2; p <= x; ++p) \
      { \
        while ( x % p == 0 ) \
        { \
          factors.push_back( p ); \
          x /= p; \
        } \
      } \
      for ( int factor : factors ) \
      { \
        cout<<"*(1"; \
        for ( int i=1;i<factor;++i) \
          cout<<"+1"; \
        cout<<")"; \
      } \
      cout<<"\n#include<iostream>\n#include<vector>\n#define Q(S)auto q=#S;S\nQ("<<q<<")"; \
  })

```

The only line that changes is the first line. The value of `X` will be 1000, 999, 998, ..., 3, 2 and then it will start again. However, in order to get different syntax trees every time, `X` is represented in terms of its prime factorization, where every prime is written as a sum of `1`s. The ASTs are different, because the prime factorization of integers is different for every value.

The program will print itself, except that the first line is changed and the backslashes, line breaks and indentations that are within `Q(...)` will be removed.

The following program calculates the score of my answer:

```
#include <iostream>

const int n = 1000;

int getProgramLength( int n )
{
  int sum = 442;
  for ( int p = 2; p*p <= n; ++p )
  {
    while ( n % p == 0 )
    {
      sum += 2 * ( 1 + p );
      n /= p;
    }
  }
  if ( n > 1 )
    sum += 2 * ( 1 + n );
  return sum;
}

int main()
{
  int sum = 0;
  for ( int i = 2; i <= n; ++i )
    sum += getProgramLength( i );
  std::cout << (double)sum/(n-1)/(n-1) << '\n';
}

```

It printed 0.734194 to the console. Obviously, 1000 can be replaced by larger integers and the score will approach 0 as its limit. The mathematical proof involves Riemann's Zeta function is somewhat convoluted. I leave it as an exercise to the reader. ;)
> 6 votes

# Answer
# Perl, score of 110.25

I have to admit, I'm not very good with quines. I'm 100% certain that there is room for improvement. The solution is based off of the same principle of the Element solution below.

The first program is 264 characters.

```
$s='$a=chr(39);print"\$s=$a$s$a;";$s=reverse$s;for(1..87){chop$s}$s=reverse$s;print$s;$f++;if($f==0){$a=chr(39);print"\$s=$a$s$a;$s"}';$a=chr(39);print"\$s=$a$s$a;";$s=reverse$s;for(1..87){chop$s}$s=reverse$s;print$s;$f++;if($f==0){$a=chr(39);print"\$s=$a$s$a;$s"}

```

The second program is 177 characters.

```
$s='$a=chr(39);print"\$s=$a$s$a;";$s=reverse$s;for(1..87){chop$s}$s=reverse$s;print$s;$f++;if($f==0){$a=chr(39);print"\$s=$a$s$a;$s"}';if($f==0){$a=chr(39);print"\$s=$a$s$a;$s"}

```

I'm working on the AST for this entry (and the Element entry).

---

# Element, score of 47.25

The first program is 105 characters.

```
\ \3\:\$\'\[\\\\\`\(\`\]\#\2\1\'\[\(\#\]\`\ \3\:\$\'\[\\\\\`\(\`\]\#\` 3:$'[\\`(`]#21'[(#]` 3:$'[\\`(`]#`

```

The second program is 84 characters.

```
\ \3\:\$\'\[\\\\\`\(\`\]\#\2\1\'\[\(\#\]\`\ \3\:\$\'\[\\\\\`\(\`\]\#\` 3:$'[\\`(`]#`

```

I'm sure that there is a lot of room for improvement.

In the first program there is one string (in which every character is escaped, despite a lot of redundancy) followed by executable parts A and B. Part A does several things: prints the string and escapes out of every character, prints the last half of the string (which is the source for part B), and then prevents the part B that follows it from doing anything.

The second program is the same string followed by part B. Part B is based off of a simple quine; it prints a string preceded by an escaped version of it. This means it prints the string, and both parts A and B.
> 4 votes

# Answer
## VBA: (251+216)/2/2 = 116.75

**251**

```
Sub a()
r=vbCrLf:c="If b.Lines(4, 4) = c Then"&r &"b.InsertLines 8, d"&r &"b.DeleteLines 4, 4"&r &"End If":d="b.InsertLines 6, c"&r &"b.DeleteLines 4, 2"
Set b=Modules("Q")
If b.Lines(4, 4) = c Then
b.InsertLines 8, d
b.DeleteLines 4, 4
End If
End Sub

```

**216**

```
Sub a()
r=vbCrLf:c="If b.Lines(4, 4) = c Then"&r &"b.InsertLines 8, d"&r &"b.DeleteLines 4, 4"&r &"End If":d="b.InsertLines 6, c"&r &"b.DeleteLines 4, 2"
Set b=Modules("Q")
b.InsertLines 6,c
b.DeleteLines 4,2
End Sub

```

This is run in **MSAccess** to make use of the `Module` object. The module is named `"Q"` for golfing. The difference in syntax comes from the `If ... Then` missing from the shorter version.
> 3 votes

# Answer
## JavaScript, ~~84.5~~ ~~64~~ 61

Two programs, both length ~~169~~ ~~128~~ 122.

```
(function c(){alert(/*
2/*/1/**/);return ('('+c+')()').replace(/\/([/\*])/,function(m,a){return a=='*'?'/\/':'/\*'});
})()

```

Before I golfed it, for your viewing pleasure:

```
(function c() {
    var r = /\/([/\*])/;
    var f = function(m, a) { return a === '*' ? '/\/' : '/\*' };
    var p = '(' + c + ')();';
    p = p.replace(r, f);
    /* This is just a comment!
    console.log('Quine, part two!'); /*/
    console.log('Quine, part one!'); /**/
    return p;
})();

```

Returns the new program and outputs the current part! ~~I could probably make it shorter without the function regex, but... I don't want to.~~
> 2 votes

# Answer
# J - (24+30)/2 / 2 = 13.5 pts

Note that strings in J are not the backslash-escaped, but quote-escaped à la Pascal: `'I can''t breathe!'`.

```
30$(,5#{.)'''30$(,5#{.)'         NB. program 1, 24 char
'30$(,5#{.)''''''30$(,5#{.)'''   NB. program 2, 30 char

```

Program 1 has AST `noun verb hook noun` and program 2 has AST `noun`. Program 2 is a quoted version of program 1, which will just return program 1 when run, so this method can't be extended to three copies that easily :P

Program 1 operates by taking a copy of the code portion of the source, with a quote appended at the front, and adding five of those quotes to the end (`(,5#{.)`). Then, it cyclically takes 30 characters from this 16-character string, which gives exactly Program 2 as a result.
> 2 votes

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