title: Crazy 8s Code Golf

text:
# Question
Title: Crazy 8s Code Golf
Create a program that prints all whole numbers inclusively between an interval `(a, b)`, and replaces multiples of 8 in the sequence with random (uniformly distributed, independent of other characters), non-numeric, non-whitespace, printable ASCII characters.

Assume 0 \< a \< b in all cases.

If the number has more than 1 digit, make sure the amount of characters in the replacement matches!

Examples:

```
(1, 16) -> 1 2 3 4 5 6 7 $ 9 10 11 12 13 14 15 n@

(115, 123) -> 115, 116, 117, 118, 119, :F<, 121, 122, 123

(1, 3) -> 1 2 3

```

Non-Examples:

```
(1, 16) -> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

(115, 123) -> 115 116 117 118 119 $ 121 122 123

```

This is code golf, so the shortest code in bytes wins!

**Current Winner:**

Pyke (21 bytes) by muddyfish

**Most Popular:**

Python 2 (119 bytes) by Dennis

# Answer
## Pyke, ~~22~~ 21 bytes

```
h1:Fi8%!I`lV~Kl7T>Hs0

```

Try it here!

Takes input in the form: `higher`, `lower`

```
h1:                   -  range(lower, higher+1, 1)
   F                  - for i in ^:
    i8%               -    i % 8
       !              -   not ^
        I             -  if ^:
         `l           -    len(str(i))
           V          -   repeat V ^ times
            ~K        -        printable_ascii
              l7      -       ^.strip()
                T>    -      ^[10:]
                  H   -     random.choice(^)
                   s0 -    sum(^)

```
> 5 votes

# Answer
# Python 2, 126 bytes

Try it online!

```
import random,string
def f(a,b):
 while b/a:print[a,eval('random.choice(string.printable[10:-6])+'*len(`a`)+"''")][a%8<1];a+=1

```

Many thanks to Flp.Tkc and EasterlyIrk for all of their help!
> 10 votes

# Answer
# Python 2, 119 bytes

```
import random,string
def f(a,b):print`[random.choice(string.printable[10:95])for _ in`a`]`[2+a%8*b::5]or a;a<b<f(a+1,b)

```

Try it online!
> 10 votes

# Answer
## zsh, ~~100~~ 98 bytes

```
for i in {$1..$2};{((i%8))&&<<<$i||<<<`yes 'shuf -e {!..~}|grep "[^0-9]"|head -c1'|head -$#i|zsh`}

```

The two input arguments are passed as command line arguments, and the numbers are output on separate lines.

```
for i in {$1..$2};{   # loop through the range
((i%8))&&             # if the number is not divisible by 8 (i % 8 != 0),
<<<$i||               # output it
<<<`                  # otherwise, output the following:
yes '                 # using `yes' as a golfy loop
shuf -e {\!..\~}      # shuffle the range of printable ASCII (minus space)
|grep "[^0-9]"        # get rid of numbers
|head -c1'            # take the first character
|head -$#i            # obtain a string with that code repeated len(i) times...
|zsh                  # ... and eval it
`}

```
> 6 votes

# Answer
# Mathematica, 96 bytes

```
Range@##/.a_?(8∣#&):>Join[33~(c=CharacterRange)~47,58~c~127]~RandomChoice~⌊Log10@a+1⌋<>""&

```

**Explanation**

For inputs `m` and `n`:

```
Range@##

```

Generate `{m, m + 1, m + 2, ... , n}`

```
/.a_?(8∣#&):>

```

For all numbers that are divisible by 8 (call that `a`), apply this replacement rule:

```
Join[33~(c=CharacterRange)~47,58~c~127]

```

Get a list of all printable ASCII characters, except digits.

```
... ~RandomChoice~⌊Log10@a+1⌋

```

Pseudo-randomly choose `Floor[Log10[a] + 1]` characters from the list, allowing duplicates.

```
<>""

```

Join the characters.
> 5 votes

# Answer
## R, 73 bytes

```
i=scan();x=i[1]:i[2];x[!x%%8]=sample(sapply(c(32:46,58:126),intToUtf8));x

```

Reads input from stdin and replaces replaces numbers divisible by `8` with a uniformly chosen sample of ascii characters in the range `32...47, 58...126`. To draw the random sample we need a vector of characters, unfortunately `intToUtf8()` returns one string rather than a vector so we also have to vectorize it over the range using `sapply`.
> 5 votes

# Answer
# Python 2, 126 bytes

*(one does not simply outgolf Dennis)*

Seeing as I did a lot of work on heather's answer, I thought I'd post my own solutions too.

```
import random,string
def f(a,b):
 while b/a:print[a,eval('random.choice(string.printable[10:-6])+'*len(`a`)+"''")][a%8<1];a+=1

```

This is a function which takes two arguments and prints directly to `STDOUT`.

# 127 bytes

```
import random,string
lambda a,b:[[x,eval('random.choice(string.printable[10:-6])+'*len(`x`)+`''`)][x%8<1]for x in range(a,b+1)]

```

This is an unnamed anonymous function - to use, assign to a variable (such as `f`), and then call with `f(a, b)`. This returns the output as a list.
> 5 votes

# Answer
# Pip, 28 bytes

```
Fia,b+1Pi%8?i{RC@>PA@`\D`}Mi

```

Takes the numbers as command-line arguments and prints a newline-separated list of results. Try it online!

Explanation:

```
                              a,b are cmdline args; PA is string of all printable ASCII
Fia,b+1                       For i in range(a, b+1):
       P                       Print this:
        i%8?i                  If i%8 is truthy (nonzero), i; otherwise:
             {           }Mi   Map this function to the digits of i:
                @>PA           All but the first character of PA (removes space)
                    @`\D`      Find all regex matches of \D (nondigits)
              RC               Random choice from that list of characters
                               The map operation returns a list, which is concatenated
                               before printing

```
> 4 votes

# Answer
# JavaScript (ES6), 114 bytes

```
f=(x,y)=>(x+"").replace(/./g,d=>x%8?d:String.fromCharCode((q=Math.random()*84)+(q>15?43:33)))+(x<y?[,f(x+1,y)]:"")

O.textContent = f(1,200)
```

```
<pre id=O>
```

Those darn built-ins with 23-byte names....
> 4 votes

# Answer
# Bash + apg, ~~64~~, ~~76~~, 73 bytes

EDITS:

* Fixed the "8 8" issue, exclude numeric characters from a set of random chars, +12 bytes
* **-3 bytes**, replaced `$1 $2` with `$@`, thx @pxeger

**Golfed**

```
seq $@|sed "$[(7&(8-$1%8))+1]~8s/.*/a=&;apg -a1 -n1 -Mcsl -m\${#a} -x0/e"

```

**Test**

```
>./crazy8 8 8
$

>./crazy8 115 123
115
116
117
118
119
As_
121
122
123

>./crazy8 1 16
1
2
3
4
5
6
7
"
9
10
11
12
13
14
15
x!

```
> 4 votes

# Answer
# MATL, 26 bytes

```
&:"@8\?@}6Y24Y2X-Xz@VnT&Zr

```

Try it online!

### Explanation

```
&:        % Input a and b (implicit). Push range [a a+1 ... b]
"         % For each k in that range
  @       %   Push k
  8\      %   Modulo 8
  ?       %   If non-zero
    @     %     Push k
  }       %   Else
    6Y2   %     Push string of all printable ASCII chars
    4Y2   %     Push string '0123456789'
    X-    %     Set difference
    Xz    %     Remove space. Gives string of possible random chars
    @Vn   %     Push number of digits of k
    T&Zr  %     Random sample with replacement of that many chars from the string
          % End if, end for each, display (implicit)

```
> 3 votes

# Answer
# Pyth, 24 bytes

```
jm?%d8dsmO-r\~\ jkUT`d}F

```

Try it online!

### Explanation:

```
jm?%d8dsmO-r\~\ jkUT`d}FQ  # Auto-fill variables
                      }FQ  # Splat inclusive range on the input
 m?%d8d                    # Map over each number, if it isn't divisible by 8 return it
       smO          `d     # for each other number, select a character at random for
                             each of it's digits and then flatten into one string
           r\~\            # Printable ASCII excluding space
          -     jkUT       # Setwise difference with numeric values (remove numbers)
j                          # Join with newlines

```
> 3 votes

# Answer
# Perl 6, 60 bytes

```
{map {$_%8??$_!!S:g/./{grep(/\D/,"!".."~").pick}/},$^a..$^b}

```

Explanation:

* `{ map { }, $^a .. $^b }`: A lambda that takes two arguments, generates the list of integers in that range, and returns it with the following transformation applied to each element:
* `$_ % 8 ?? $_ !!`: If the element is not divisible by 8, pass it on unchanged. Otherwise...
* `S:g/./{ }/`: ...replace each character of its string representation with the value generated by this expression:
* `grep(/\D/, "!" .. "~").pick`: Generate the range of characters between `!` and `~` (in Unicode order), filter out digits, and randomly pick one of the remaining characters.
> 2 votes

# Answer
# Inlined version

# Scala, 132 bytes

```
def S(a:Int,b:Int)= a to b map(x=>if(x%8==0)Random.nextInt(((33 to 47)++(58 to 126)).length).toChar.toString else String.valueOf(x))

```

Try it online!

# Scala, 198 bytes

### An improved functional version with immutable state (03-04-2018)

```
  def S(a: Int, b: Int)={
    val c=(33 to 47)++(58 to 126)
    val r = (a to b).toStream.map {case x if x%8==0=>c(Random.nextInt(c.length)).toChar.toString
      case x => String.valueOf(x)}
    r}

```

Try it online!

**A functional style solution in Scala (350 bytes) for the fun of it.**

```
def r(a:Int, b:Int)={
    var l=(33 to 47).toList:::(58 to 126).toList
    l=Random.shuffle(l)
    var x=ListBuffer[String]()
    var k=0
    (a to b).toList.foreach{e=>{
         if(k==l.length){k=0
         l=Random.shuffle(l)}
         if (e.toInt%8==0){x+=l(k).toChar.toString
           k+=1}
         else{x+=e.toString
             k+=1}}}
    x}

```

*Suggestions for improvements are welcomed.*
> 2 votes

# Answer
## Perl, 66 bytes

```
map{$_%8||s%.%do{$_=chr rand 126}until/[!-\/:-~]/;$_%ge;say}<>..<>

```

Run with `-E` flag:

```
perl -E 'map{$_%8||s%.%do{$_=chr rand 126}until/[!-\/:-~]/;$_%ge;say}<>..<>' <<< "8
16"

```

This is pretty straight forward:
-`<>..<>` creates a list of the numbers between the 2 inputs number. And then `map` iterates over it:
-`$_%8||...` : the `...` are executed only if `$_` is a multiple of 8.
-`s%.%xxx%ge` : replace every character with `xxx`.
\- `do{$_=chr rand 126}until/[!-\/:-~]/` pick a random character (from codes 0 to 126) until we get one that satisfies `/[!-\/:-~]/`, ie. one that is printable and is not a digit.
\- `say`: print it.
> 2 votes

# Answer
# Java 10, ~~149~~ 147 bytes (lambda function)

```
b->a->{var r="";for(;a<=b;r+=" ",a++)for(var c:(a+"").split("")){char t=0;for(;t<33|t>126|t>47&t<59;t*=Math.random())t=127;r+=a%8<1?t:c;}return r;}

```

Try it online.

# Java 10, ~~227~~ 225 bytes (full program)

```
interface M{static void main(String[]A){var r="";for(var a=new Long(A[0]);a<=new Long(A[1]);r+=" ",a++)for(var c:(a+"").split("")){char t=0;for(;t<33|t>126|t>47&t<59;t*=Math.random())t=127;r+=a%8<1?t:c;}System.out.print(r);}}

```

Try it online.

**Explanation:**

```
b->a->{          // Method with two integer parameters and String return-type
  var r="";      //  Result-String, starting empty
  for(;a<=b      //  Loop as long as `a` is smaller than or equal to `b`
      ;          //    After every iteration:
       r+=" ",   //     Append a space to the result-String
       a++)      //     And increase `a` by 1
    for(var c:(a+"").split("")){
                 //   Inner loop over the characters of the current number
      char t=0;  //    Random-char, starting at 0
      for(;t<33|t>126|t>47&t<59;
                 //    Loop until `t` is a non-digit printable ASCII char
          t*=Math.random())t=127;
                 //     Set `t` to a random character with a unicode in the range [0,127)
      r+=a%8<1?  //   If the current `a` is divisible by 8:
          t      //    Append the random character
         :       //   Else:
          c;}    //    Append the digit instead
  return r;}     //  Return the result

```
> 2 votes

# Answer
# C, ~~157~~ 115 bytes

```
f(a,b){b-a&&f(a,b-1);if(b%8)printf("%d",b);else for(;b;b/=10){while(isdigit(a=rand()%94+33));putchar(a);}puts("");}

```

Try it online here. Thanks to jxh for golfing 42 bytes.

Ungolfed version:

```
f(a, b) { // recursive function, parameters are implicitly int
    b-a && f(a, b-1); // recurse until a = b
    if(b % 8)            // if the number is a multiple of 8
        printf("%d", b); // simply print it
    else for(; b; b /= 10) { // while b > 0, lop off the last digit
        while(isdigit(a = rand() % 94 + 33)); // generate random characters in ASCII range [33, 127] until one is non-numeric
        putchar(a); // print the character
    }
    puts(""); // print a newline
}

```
> 2 votes

# Answer
# C (gcc), ~~129~~ 119 bytes

```
s(a,r){a&&s(!isdigit(r=rand()%94+33)?putchar(r),a/10:a,0);}f(a,b){b>a&&f(a,b-1);b%8?printf("%d",b):s(b,0);printf(" ");}

```

Try it online!

129 → 119 Use the `%94+33` trick from O.O.Balance

### Ungolfed:

```
s(a,r){
    a&&                                  // Loop recursively on a!=0
    s(!isdigit(r=rand()%94+33)           // Test random selection
      ?putchar(r),a/10                   // Print and reduce a
      :a                                 // Retry random selection
      ,0);                               // Second arg, recurse
}
f(a,b){
    b>a&&                                // Loop recursively on b>a
    f(a,b-1);                            // Reduce b, recurse
    b%8?printf("%d",b)                   // Print non 8's
       :s(b,0);                          // Call s() for 8's
    printf(" ");                         // Space separator
}

```
> 2 votes

# Answer
# APL (Dyalog Extended), 32 bytes

```
{(?84¨⍕⍵)⊇⎕D~⍨'!'…'~'}¨@{0=8|⍵}…

```

Try it online!

Huge thanks to Adám and dzaima for their help. First time using Dyalog Extended!

Explanation:

```
{(?84¨⍕⍵)⊇⎕D~⍨'!'…'~'}¨@{0=8|⍵}…  ⍝ Dyadic 2-train

                               …  ⍝ Tacit range: list of numbers from left arg
                                  ⍝ to right arg inclusive
{(?84¨⍕⍵)⊇⎕D~⍨'!'…'~'}¨@{0=8|⍵}   ⍝ Monadic function applied to above
                        {     }   ⍝ Function definition
                           8|⍵    ⍝ 8 modulo every item in our range
                         0=       ⍝ Transform list into a boolean vector, with
                                  ⍝ 1 where item was equal to zero, 0 otherwise
                      ¨@          ⍝ Applies left function to each item selected
                                  ⍝ by above
{                    }            ⍝ Function definition
              '!'…'~'             ⍝ Range of all printable ASCII chars
          ⎕D~⍨                    ⍝ Remove numeric characters from above
 (    ⍕⍵)                         ⍝ Convert function argument to string
                                  ⍝ (e.g., 123 -> "123")
   84¨                            ⍝ For each character, replace with number 84
                                  ⍝ (number of non-numeric printable ASCII chars)
  ?                               ⍝ Generate random number from 1-84 for each
                                  ⍝ 84 in list
         ⊇                        ⍝ Index the ASCII char list with above random
                                  ⍝ numbers

```
> 2 votes

# Answer
# PHP, 163 bytes

```
$n=range(48,57);$c=array_diff(range(32,126),$n);
foreach(range($a,$b) as $v){if($v%8!=0){echo $v;}
else{for($i=0;$i<strlen($v);$i++){echo chr($c[array_rand($c)]);}}}

```

### Explanation:

* `$n = range(48,57)` These are the ASCII codes for numbers, which are in the middle of special characters (32-47) and other characters (58-126).
* `$c = array_diff(range(32,126), $n)` Using the `$n` array, exclude numeric characters and build an array of acceptable ASCII characters.
* `foreach(range($a,$b) as $v)` Loop over the range of values from `$a` to `$b` (inclusive), as $v inside the loop.
* `if($v % 8 != 0) { echo $v; }` Test for $v being evenly divisible by 8 using the mod operator `%`.
* `else { for($i = 0; $i < strlen($v); $i++) { ... }}` If not evenly divisible by 8, loop enough times for the number of digits in the number and print the characters (in the next step).
* `echo chr($c[array_rand($c)])` Print a single character from the acceptable array of ASCII values in `$c`. `array_rand` returns an index in the array, so we have to get the actual value at that index using `$c[random_key]`.

I could probably make this smaller by creating `$c` differently, and the loop to print the ASCII characters feels clunky so I'll continue to ponder how to shorten that.
> 1 votes

# Answer
## postgresql9.6 251 chars

very long code but postgresql also does it.

```
do language plpgsql $$ begin for n in a..bloop raise info'%',case when 0=n%8then(select array_to_string(array(select*from(select chr(generate_series(33,126)))t where chr!~'\d'order by random()limit floor(log(n))+1),''))else n::text end;end loop;end;$$

```

formatted sql is here:

```
do language plpgsql $$
begin
for n in a..b loop
    raise info '%',
    case when 0 = n % 8 then (
        select array_to_string(array(select * from (
            select chr(generate_series(33, 126))
        ) t where chr !~ '\d' order by random() limit floor(log(n)) + 1), '')
    ) else n::text
    end;
end loop;
end;
$$

```
> 1 votes

# Answer
## QBIC, 79 bytes

```
::[a,b|~c%8=0|[_l!c$||_R33,116|~e>47 and e<58|e=e+z]Z=Z+chr$(e)]\Z=Z+!c$]Z=Z+@

```

Skipping the numbers is a costly affair, here's a version that might also randomly select `0-9` for 20 bytes less:

```
::[a,b|~c%8=0|[len(!c$)|Z=Z+chr$(_r33,126|)]\Z=Z+!c$]Z=Z+@

```

Sample output for `1, 89`

```
1 2 3 4 5 6 7 U 9 10 11 12 13 14 15 M9 17 18 19 20 21 22 23 ^L 25 26 27 28 29 30
31 <U 33 34 35 36 37 38 39 gH 41 42 43 44 45 46 47 aJ 49 50 51 52 53 54 55 1b 57 58 59 60
61 62 63 ,C 65 66 67 68 69 70 71 ]; 73 74 75 76 77 78 79 [B 81 82 83 84 85 86 87 Ix 89

```

Explanation:

```
::        Get inputs 'a' and 'b' from the command line
[a,b|     FOR(c=a; c<=b; c++)
~c%8=0|   IF c is cleanly divisible by 8 THEN
 _l!c$|   Take the length (_l) of the string representation (! ... $) of c
[      |  FOR (d = 1; d<= length(c); d++)
_R33,116| Set e to a random value in the range 33 - 116 (all the printable ascii's - 10)
~e>47     IF e falls between 47
and e<58| and 58 (ASCII code for 0-9) THEN
e=e+z     e = e + 10 (z == 10 in QBIC)
]         END IF
Z=Z+      Add to Z$
chr$(e)]  ASCII character e
\         ELSE if c is not cleanly divisible by 8
Z=Z+!c$   Add to Z the string representation of c
]         NEXT
Z=Z+@     Add a space to Z$ (@ is an implicitly delimited string literal with 1 significant space)

( Z$ is implicitly printed at end of program )

```
> 1 votes

# Answer
# PHP, 130 bytes

```
function($a,$b){for(;$a<=$b;$a++)echo$a%8?$a:(function($l){while($l--)echo chr(($x=rand(44,128))-($x>58?:11));})(strlen($a))," ";}

```

Try it online!

Ungolfed:

```
function c8( $a, $b ) {
    for( ; $a<=$b; $a++ ) {                // loop between a -> b
        echo $a % 8 ? $a :                 // every 8, call anon func instead of value
            (function($l) {
                while( $l-- ) {            // repeat length of value
                    $x = rand( 44, 128 );  // range size is printable chars [33,47][58,127]
                    $x-= $x > 58 ?: 11;    // Subtract one from x. If x was less than or
                                           // equal to 58, subtract a further ten from it
                                           // so that it now falls within the 33-47 range
                    echo chr( $x );        // echo ASCII value
                }
            })( strlen( $a ) )," ";
    }
}

```
> 1 votes

# Answer
# 05AB1E, 17 bytes

```
ŸεD8ÖižQžhK¦.rsg£

```

Takes the input as `highest\nlowest`, and outputs a list.

Try it online or verify all test cases.

**Explanation:**

```
Ÿ                  # Create a list in the range [low (implicit) input, high (implicit) input]
 ε                 # Map each value to:
  D                #  Duplicate the value
   8Öi             #  If it's divisible by 8:
      žQ           #   Push all printable ASCII characters (" " through "~")
        žhK        #   Remove all digits
           ¦       #   Remove the first character (the space)
            .r     #   Randomly shuffle the remaining characters
              s    #   Swap to take the map value again
               g   #   Get its length
                £  #   And leave that many characters from the string
                   # (and implicitly output the resulting list after we're done mapping)

```
> 1 votes

# Answer
# Japt, 20 bytes

```
;òV ®%8?Z:EÅk9ò)öZìl

```

Try it

```
;òV ®%8?Z:EÅk9ò)öZìl     :Implicit input of integers U & V
 òV                      :Range [U,V]
    ®                    :Map each Z
     %8                  :  Modulo 8
       ?Z:               :  If truthy, return Z, else
;         E              :  Printable ASCII
           Å             :  Slice off first character
            k            :  Remove
             9ò          :    Range [0,9]
               )         :  End remove
                 Zì      :  Digit array of Z
                   l     :  Length
               ö         :  Get that many random characters from the string

```
> 1 votes

# Answer
# Forth (gforth), 128 bytes

```
include random.fs
: f 1+ swap do i 8 mod if i . else i 0 <# #s #> 0 do 83 random 33 + dup 47 > 10 * - emit loop ."  "then loop ;

```

Try it online!

### Explanation

Loop from start to end, print number if not multiple of 8, otherwise get the number of digits in the number and print that many random characters followed by a space

### Code Explanation

```
include random.fs          \ include/import the random module
: f                        \ start new word definition
  1+ swap                  \ add 1 to end number, because forth loops are [start, end), and swap order
  do                       \ start counted loop form start to end
    i 8 mod                \ get the remainder of dividing i (loop index) by 8
    if                     \ if true (not 0, therefore not multiple of 8)
      i .                  \ print the index
    else                   \ otherwise
      i 0                  \ convert index to double-length number
      <# #s #>             \ use formatted numeric output to convert number to a string
      0 do                 \ loop from 0 to (string-length - 1)
        84 random          \ get random number between 0 and 83
        33 +               \ add 33
        dup 47 >           \ check if result is larger than 47
        10 * -             \ if it is add 10 to result (results in number in range: 33-47,58-126)
        emit               \ output ascii char corresponding with number
      loop                 \ end inner loop
    ."  "then            \ output a space and then close the if/else
  loop                   \ end the outer loop
;                        \ end the word definition

```

### UnGolfed

I don't usually ungolf my solutions, but this one is long/complicated enough that I think it's needed

```
include random.fs

\ get the length (in digits) of a number
: num-length 0 <# #s #> nip ;

\ check if a number is a multiple of another
: is-multiple mod 0= ;

\ get a random printable non-digit ascii char
: random-char 84 random 33 + dup 47 > 10 * - ;

\ get a "random" string of printable ascii chars the same length as a number
: rand-str num-length 0 do random-char emit loop space ;

\ print numbers from a to b, replacing multiple of 8 with a random ascii string of the same length
: crazy-eights 1+ swap do i 8 is-multiple if i rand-str else i . then loop ;

```
> 1 votes

# Answer
# Kotlin, 136 bytes

```
{r:IntRange->var s=""
for(i in r){for(c in "$i"){var n=java.util.Random().nextInt(83)
if(n>14)n+=10
s+=if(i%8>0)c
else '!'+n}
s+=" "}
s}

```

Try it online!
> 1 votes

# Answer
# Zsh, 67 bytes

```
for i ({$1..$2})((i%8))||i=`tr -dc !-/:-~</*/ur*|head -c$#i`&&<<<$i

```

Try it online!

Feels pretty long, but so are most answers to this one.
> 1 votes

# Answer
# Python 2, 180 Bytes

```
from random import*
def f(a,b):
 for i in range(a,b+1):
  if i%8<1:
   k,i=str(i),''
   for _ in k:i+=choice([chr(j)for j in range(33,48)]+[chr(j)for j in range(57,126)])
  print i

```

EDIT:

Thanks @Flp.Tkc for realising I hadn't read the task properly.

Thanks @Caleb for pointing out I could use a few to reduce the byte count.

Thanks @Dennis for pointing out about the fact that numbers can't be included.

EDIT 2:

The current version could probably be simplified more than it is.
> 0 votes

# Answer
# PowerShell, ~~82~~ 89 bytes

```
$a,$b=$args;$a..$b|%{($_,(-join[char[]](33..47+58..127|random -c "$_".Length)))[!($_%8)]}

```

Try it online!
> 0 votes

# Answer
# Ruby, 80 bytes

```
->a,b{$><<(a..b).map{_1%8<1?_1.to_s.gsub(/./){[*?!..?/,*?:..?~].sample}:_1}*" "}

```

Attempt This Online!
> 0 votes

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


title: Base85 Encoding

text:
# Question
Title: Base85 Encoding
# The Challenge

Write a program that can take an input of a single-line string containing any ASCII printable characters, and output the same string encoded in Base85 (using a big-endian convention). You can assume that the input will always be ≤ 100 characters.

---

# A Guide to Base85

* Four octets are encoded into (usually) five Base85 characters.
* Base85 characters range from `!` to `u` (ASCII 33 - 117) and `z` (ASCII 122).
* To encode, you continuously perform division by 85 on the four octets (a 32-bit number), and add 33 to the remainder (after each division) to get the ASCII character for the encoded value. For example, the first application of this process produces the rightmost character in the encoded block.
* If a set of four octets contains only null bytes, they are encoded as a `z` instead of `!!!!!`.
* If the last block is shorter than four octets, it's padded with null bytes. After encoding, the same number of characters that were added as padding, are removed from the end of the output.
* The encoded value should be preceded by `<~` and followed by `~>`.
* The encoded value should contain no whitespace (for this challenge).

---

# Examples

```
In: easy
Out: <~ARTY*~>

In: test
Out: <~FCfN8~>

In: code golf
Out: <~@rGmh+D5V/Ac~>

In: Programming Puzzles
Out: <~:i^JeEa`g%Bl7Q+:j%)1Ch7Y~>

```

The following snippet will encode a given input to Base85.

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>String.prototype.toAscii85=function(){if(""==this)return"<~~>";for(var r=[],t=0;t<this.length;t+=4){for(var i=(this.substr(t,4)+"\x00\x00\x00").substr(0,4),o=0,n=0;4>n;n++)o=256*o+i.charCodeAt(n);var s=[];for(n=0;5>n;n++){var e=o%85;o=(o-e)/85,s.unshift(String.fromCharCode(e+33))}r=r.concat(s)}var a=4-this.length%4;return 4!=a&&r.splice(-a,a),"<~"+r.join("").replace(/!!!!!/g,"z")+"~>"};</script><style>#in,#out{margin:20px;width:400px;resize:none}</style><input id="in" type="text" value="Base85"><button onclick="$('#out').text($('#in').val().toAscii85())">Submit</button><br><textarea id="out" rows=5 disabled></textarea>
```

# Answer
> 11 votes
# CJam, ~~43~~ ~~39~~ 35 bytes

```
"<~"q4/{:N4Ue]256b85b'!f+}/N,)<"~>"

```

Try it online in the CJam interpreter.

### How it works

```
"<~"      e# Push that string.
q4/       e# Read all input from STDIN and split it into chunks of length 4.
{         e# For each chunk:
  :N      e#   Save it in N.
  4Ue]    e#   Right-pad it with 0's to a length of 4.
  256b85b e#   Convert from base 256 to base 85.
  '!f+    e#   Add '!' to each base-85 digit.
}/        e#
N,)       e# Push the length of the last unpadded chunk, plus 1.
<         e# Keep that many chars of the last encoded chunk.
"~>"      e# Push that string.

```

If the input was empty, `N,)` will apply to the string `"<~"`. Since `N` initially holds a single character, the output will be correct.

We don't have to deal with **z** or pad the encoded chunks to length 5, since the input will contain only printable ASCII characters.

# Answer
> 6 votes
# Python 3, 71 bytes

```
from base64 import*
print(a85encode(input().encode(),adobe=1).decode())

```

I've never golfed in Python, so this is probably sub-optimal.

*Thanks to @ZachGates for golfing off 3 bytes!*

# Answer
> 5 votes
# Pure bash, ~738

Encoder first (something golfed):

```
#!/bin/bash
# Ascii 85 encoder bash script
LANG=C

printf -v n \\%o {32..126};printf -v n "$n";printf -v m %-20sE abtnvfr;p=\<~;l()
{ q=$(($1<<24|$2<<16|$3<<8|$4));q="${n:1+(q/64#378iN)%85:1}${n:1+(q/614125)%85:1
}${n:1+(q/7225)%85:1}${n:1+(q/85)%85:1}${n:1+q%85:1}";};k() { ((${#p}>74))&&ech\
o "${p:0:75}" && p=${p:75};};while IFS= read -rd '' -n 1 q;do [ "$q" ]&&{ print\
f -v q "%q" "$q";case ${#q} in 1|2)q=${n%$q*};o+=($((${#q}+32)));;7)q=${q#*\'\\}
o+=($((8#${q%\'})));;5)q=${q#*\'\\};q=${m%${q%\'}*};o+=($((${#q}+07)));;esac;}||
o+=(0);((${#o[@]}>3))&&{ [ "${o[*]}" = "0 0 0 0" ]&& q=z|| l ${o[@]};p+="${q}";k
o=(); };done;[ "$o" ]&&{ f=0;for((;${#o[@]}<4;)){ o+=(0);((f++));};((f==0))&&[ \
"${o[*]}" = "0 0 0 0" ]&&q=z||l ${o[@]};p+="${q:0:5-f}";};p+="~>";k;[ "$p" ]&&e\
cho "$p"

```

Tests:

```
for word in easy test code\ golf Programming\ Puzzles ;do
    printf "    %-24s %s\n" "$word:" $(./enc85.sh < <(printf "$word"))
  done
    easy:                   <~ARTY*~>
    test:                   <~FCfN8~>
    code golf:              <~@rGmh+D5V/Ac~>
    Programming Puzzles:    <~:i^JeEa`g%Bl7Q+:j%)1Ch7Y~>

```

and decoder now:

```
#!/bin/bash
# Ascii 85 decoder bash script
LANG=C

printf -v n "\%o" {33..117};printf -v n "$n";o=1 k=1;j(){ read -r q||o=;[ "$q" \
]&&[ -z "${q//*<~*}" ]&&((k))&&k= q="${q#*<~}";m+="$q";m="${m%~>*}";};l(){ r=;f\
or((i=0;i<${#1};i++)){ s="${1:i:1}";case "$s" in "*"|\\|\?)s=\\${s};;esac;s="${\
n%${s}*}";((r+=${#s}*(85**(4-i))));};printf -v p "\%03o" $((r>>24)) $((r>>16&255
)) $((r>>8&255)) $((r&255));};for((;(o+${#m})>0;)){ [ "$m" ] || j;while [ "${m:0
:1}" = "z" ];do m=${m:1};printf "\0\0\0\0";done;if [ ${#m} -ge 5 ];then q="${m:0
:5}";m=${m:5};l "$q";printf "$p";elif ((o));then j;elif [ "${m##z*}" ];then pri\
ntf -v t %$((5-${#m}))s;l "$m${t// /u}";printf "${p:0:16-4*${#t}}";m=;fi;}

```

Copy this in `enc85.sh` and `dec85.sh`, `chmod +x {enc,dec}85.sh`, then:

```
for string in 'ARTY*' 'FCfN8' '@rGmh+D5V/Ac' ':i^JeEa`g%Bl7Q+:j%)1Ch7Y' ;do
    printf "    %-42s %s\n" "<~$string~>:" "$(./dec85.sh <<<"<~$string~>")"
  done
    <~ARTY*~>:                                 easy
    <~FCfN8~>:                                 test
    <~@rGmh+D5V/Ac~>:                          code golf
    <~:i^JeEa`g%Bl7Q+:j%)1Ch7Y~>:              Programming Puzzles

./enc85.sh <<<'Hello world!'
<~87cURD]j7BEbo80$3~>
./dec85.sh <<<'<~87cURD]j7BEbo80$3~>'
Hello world!

```

But you could do some stronger test:

```
ls -ltr --color $HOME/* | gzip | ./enc85.sh | ./dec85.sh | gunzip

```

## Reduced to 724 chars:

```
printf -v n \\%o {32..126};printf -v n "$n";printf -v m %-20sE abtnvfr;p=\<~
l(){ q=$(($1<<24|$2<<16|$3<<8|$4))
q="${n:1+(q/64#378iN)%85:1}${n:1+(q/614125)%85:1}${n:1+(q/7225)%85:1}${n:1+(q/85)%85:1}${n:1+q%85:1}"
};k() { ((${#p}>74))&&echo "${p:0:75}" && p=${p:75};};while IFS= read -rd '' -n 1 q;do [ "$q" ]&&{
printf -v q "%q" "$q";case ${#q} in 1|2)q=${n%$q*};o+=($((${#q}+32)));;7)q=${q#*\'\\}
o+=($((8#${q%\'})));;5)q=${q#*\'\\};q=${m%${q%\'}*};o+=($((${#q}+07)));;esac;}||o+=(0)
((${#o[@]}>3))&&{ [ "${o[*]}" = "0 0 0 0" ]&&q=z||l ${o[@]};p+="${q}";k
o=();};done;[ "$o" ]&&{ f=0;for((;${#o[@]}<4;)){ o+=(0);((f++));}
((f==0))&&[ "${o[*]}" = "0 0 0 0" ]&&q=z||l ${o[@]};p+="${q:0:5-f}";};p+="~>";k;[ "$p" ]&&echo "$p"

```

# Answer
> 3 votes
## Python 2, ~~193~~ 162 bytes

```
from struct import*
i=raw_input()
k=4-len(i)%4&3
i+='\0'*k
o=''
while i:
 b,=unpack('>I',i[-4:]);i=i[:-4]
 while b:o+=chr(b%85+33);b/=85
print'<~%s~>'%o[k:][::-1]

```

This is my first code golf, so I'm sure there's something wrong with my approach. I also wanted to actually implement base85 rather than just call the library function. :)

# Answer
> 3 votes
# Octave, ~~133~~ 131 bytes

Thanks to @ojdo for suggesting I take input from argv rather than stdin, saving me 2 bytes.

```
function g(s) p=mod(-numel(s),4);s(end+1:end+p)=0;disp(['<~' dec2base(swapbytes(typecast(s,'uint32')),'!':'u')'(:)'(1:end-p) '~>'])

```

### Ungolfed:

```
function g(s)             %// function header
p=mod(-numel(s),4);       %// number of missing chars until next multiple of 4
s(end+1:end+p)=0;         %// append p null characters to s
t=typecast(s,'uint32');   %// cast each 4 char block to uint32
u=swapbytes(t);           %// change endian-ness of uint32's
v=dec2base(u,'!':'u');    %// convert to base85
w=v'(:)'(1:end-p);        %// flatten and truncate resulting string
disp(['<~' w '~>']);      %// format and display final result

```

I've posted the code on ideone. The standalone function doesn't require and `end` statement, but because ideone has the function and the calling script in the same file it requires a separator.

I still haven't been able to figure out how to get `stdin` to work on ideone. If anyone knows, I'm still interested, so please drop me a comment.

Sample output from ideone:

```
easy
<~ARTY*~>
test
<~FCfN8~>
code golf
<~@rGmh+D5V/Ac~>
Programming Puzzles
<~:i^JeEa`g%Bl7Q+:j%)1Ch7Y~>

```

# Answer
> 2 votes
# Matlab, 175 bytes

```
s=input('','s');m=3-mod(numel(s)-1,4);s=reshape([s zeros(1,m)]',4,[])';t=char(mod(floor(bsxfun(@rdivide,s*256.^[3:-1:0]',85.^[4:-1:0])),85)+33)';t=t(:)';['<~' t(1:end-m) '~>']

```

Example:

```
>> s=input('','s');m=3-mod(numel(s)-1,4);s=reshape([s zeros(1,m)]',4,[])';t=char(mod(floor(bsxfun(@rdivide,s*256.^[3:-1:0]',85.^[4:-1:0])),85)+33)';t=t(:)';['<~' t(1:end-m) '~>']
code golf
ans =
<~@rGmh+D5V/Ac~>

```

# Answer
> 2 votes
# PHP, 181 Bytes

```
foreach(str_split(bin2hex($argn),8)as$v){for($t="",$d=hexdec(str_pad($v,8,0));$d;$d=$d/85^0)$t=chr($d%85+33).$t;$r.=str_replace("!!!!!",z,substr($t,0,1+strlen($v)/2));}echo"<~$r~>";

```

Online Version

Expanded

```
foreach(str_split(bin2hex($argn),8)as$v){
    for($t="",$d=hexdec(str_pad($v,8,0));$d;$d=$d/85^0)
      $t=chr($d%85+33).$t;
    $r.=str_replace("!!!!!",z,substr($t,0,1+strlen($v)/2));
}
echo"<~$r~>";

```

# Answer
> 1 votes
# PHP, 171 bytes

```
foreach(unpack('N*',str_pad($argn,($m=4-($l=strlen($argn))%4&3)+$l,"\0"))as$c){for($a=$c?'':z;$c|0;$c/=85)$a=chr($c%85+33).$a;$b.=$a;}echo'<~',$m?substr($b,0,-$m):$b,'~>';

```

Try it online!

# Answer
> 1 votes
## JavaScript, 314 Bytes

```
a=>(g="<~",h="~>",r=[],t=0,[...a].map((d,h)=>{if(0==h%4){for(n=0,o=0,f=0,s=[],e=0;4>n;)o=256*o+(a.substr(t,4)+"\0\0\0").substr(0,4).charCodeAt(n),n++;for(;5>f;)e=o%85,o=(o-e)/85,s.unshift(String.fromCharCode(e+33)),f++;r=[...r,...s],t+=4}}),d=4-a.length%4,4!=d&&r.splice(-d,d),g+r.join("").replace(/!!!!!/g,"z")+h)

```

This is my first code golf :)

### Try It‽

```
<h2>Type Below</h2><input oninput='document.querySelector("p").innerText = (a=>(g="<~",h="~>",r=[],t=0,[...a].map((d,h)=>{if(0==h%4){for(n=0,o=0,f=0,s=[],e=0;4>n;)o=256*o+(a.substr(t,4)+"\0\0\0").substr(0,4).charCodeAt(n),n++;for(;5>f;)e=o%85,o=(o-e)/85,s.unshift(String.fromCharCode(e+33)),f++;r=[...r,...s],t+=4}}),d=4-a.length%4,4!=d&&r.splice(-d,d),g+r.join("").replace(/!!!!!/g,"z")+h))(this.value)'><p>Stuff will go here...</p>
```

# Answer
> 0 votes
# PowerShell, ~~169~~ ~~165~~ ~~162~~ 160 bytes

```
$ofs=''
"<~$($args-replace'.{1,4}',{$v=$_
&{0..3|%{$n=256*$n+"$v"[$_]}
0..4|%{$r=[char]($n%85+33)+$r;$n-=$n%85;$n/=85}
$r[0..$v.Length]-replace'!!!!!','z'}})~>"

```

Try it online!

# Answer
> 0 votes
# Ruby, ~~128~~ 114 bytes

```
$_="<~#{$_.gsub(/.{1,4}/){$&.ljust(4,?\0).unpack1("L>").digits(85).reverse.map{(_1+33).chr}.join[..$&.size-5]}}~>"

```

Attempt This Online!

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


title: Construct a Gaussian Matrix

text:
# Question
Title: Construct a Gaussian Matrix
Gaussian blur is a method used for blurring images smoothly. It involves creating a matrix which will be used by convolving it with the pixels of an image. In this challenge, your task is to construct that matrix used in Gaussian blur. You will take an input *r* which will be the radius of the blur and an input *σ* which will be the standard deviation in order to construct a matrix with dimensions (2 *r* \+ 1 × 2 *r* \+ 1). Each value in that matrix will have an (*x*, *y*) value that depends on its absolute distance in each direction from the center and will be used to compute *G*(*x*, *y*) where the formula *G* is:

$$G(x,y)=\frac{1}{2 \cdot \pi \cdot \sigma ^ 2} e ^ {-\frac{x^2+y^2}{2\cdot \sigma ^2}} $$

For example, if *r* = 2, we want to generate a 5 x 5 matrix. First, the matrix of (*x*, *y*) values is

```
(2, 2) (1, 2) (0, 2) (1, 2) (2, 2)
(2, 1) (1, 1) (0, 1) (1, 1) (2, 1)
(2, 0) (1, 0) (0, 0) (1, 0) (2, 0)
(2, 1) (1, 1) (0, 1) (1, 1) (2, 1)
(2, 2) (1, 2) (0, 2) (1, 2) (2, 2)

```

Then, let *σ* = 1.5 and apply *G* to each (*x*, *y*)

```
0.0119552 0.0232856 0.0290802 0.0232856 0.0119552
0.0232856 0.0453542 0.0566406 0.0453542 0.0232856
0.0290802 0.0566406 0.0707355 0.0566406 0.0290802
0.0232856 0.0453542 0.0566406 0.0453542 0.0232856
0.0119552 0.0232856 0.0290802 0.0232856 0.0119552

```

Normally in image blurring, this matrix would be normalized by taking the sum of all the values in that matrix and dividing by it. For this challenge, that is not needed and the raw values calculated by the formula is what the output should be.

## Rules

* This is so the shortest code wins.
* The input *r* will be a nonnegative integer and *σ* will be a positive real number.
* The output must represent a matrix. It can be formatted as a 2d array, a string representing a 2d array, or something similar.
* Floating-point inaccuracies will not be counted against you.

## Test Cases

```
(r, σ) = (0, 0.25)
2.54648

(1, 7)
0.00318244 0.00321509 0.00318244
0.00321509 0.00324806 0.00321509
0.00318244 0.00321509 0.00318244

(3, 2.5)
0.00603332 0.00900065 0.0114421  0.012395 0.0114421 0.00900065 0.00603332
0.00900065  0.0134274 0.0170696 0.0184912 0.0170696  0.0134274 0.00900065
 0.0114421  0.0170696 0.0216997  0.023507 0.0216997  0.0170696  0.0114421
  0.012395  0.0184912  0.023507 0.0254648  0.023507  0.0184912   0.012395
 0.0114421  0.0170696 0.0216997  0.023507 0.0216997  0.0170696  0.0114421
0.00900065  0.0134274 0.0170696 0.0184912 0.0170696  0.0134274 0.00900065
0.00603332 0.00900065 0.0114421  0.012395 0.0114421 0.00900065 0.00603332

(4, 3.33)
0.00339074 0.00464913 0.00582484 0.00666854 0.00697611 0.00666854 0.00582484 0.00464913 0.00339074
0.00464913 0.00637454 0.00798657  0.0091434 0.00956511  0.0091434 0.00798657 0.00637454 0.00464913
0.00582484 0.00798657  0.0100063  0.0114556   0.011984  0.0114556  0.0100063 0.00798657 0.00582484
0.00666854  0.0091434  0.0114556   0.013115  0.0137198   0.013115  0.0114556  0.0091434 0.00666854
0.00697611 0.00956511   0.011984  0.0137198  0.0143526  0.0137198   0.011984 0.00956511 0.00697611
0.00666854  0.0091434  0.0114556   0.013115  0.0137198   0.013115  0.0114556  0.0091434 0.00666854
0.00582484 0.00798657  0.0100063  0.0114556   0.011984  0.0114556  0.0100063 0.00798657 0.00582484
0.00464913 0.00637454 0.00798657  0.0091434 0.00956511  0.0091434 0.00798657 0.00637454 0.00464913
0.00339074 0.00464913 0.00582484 0.00666854 0.00697611 0.00666854 0.00582484 0.00464913 0.00339074

```

# Answer
# Mathematica, ~~60~~ ~~54~~ 50 bytes

Thanks @GregMartin for 4 bytes!

```
Array[s=2#2^2;E^(-{##}.{##}/s)/π/s&,1+2{#,#},-#]&

```

Takes r and sigma as input, returns the matrix (exact numbers).

**Built-in version (58 bytes)**

```
GaussianMatrix[{##},Standardized->1<0,Method->"Gaussian"]&

```

Of course, Mathematica has a built-in for this, too, but it's too long.
> 8 votes

# Answer
# MATL, 20 bytes

```
_G&:U&+iUE/_Ze5MYP*/

```

Try it online!

### Explanation

```
_     % Take input r implicitly. Negate
G     % Push r again
&:    % Binary range: [-r -r+1 ... r]
U     % Square, elementwise
&+    % Matrix of all pairwise additions
i     % Take input σ
U     % Square
E     % Multiply by 2. Gives 2σ^2
/     % Divide
_     % Negate
Ze    % Exponential
5M    % Push 2σ^2 again
YP    % Push pi
*     % Multiply
/     % Divide. Display implicitly

```
> 7 votes

# Answer
# Octave, 45 bytes

```
@(r,s)exp((x=-(-r:r).^2/2/s^2)+x')/2/s^2/pi

```
> 6 votes

# Answer
# Octave, 49 bytes

```
@(r,q)1./((Q=2*q^2)*pi*e.^(((x=(-r:r).^2)+x')/Q))

```

Try It Online!
> 5 votes

# Answer
# Python, 88 bytes

```
lambda r,s:[[.5/3.14/s/s/2.72**((x*x+y*y)/2/s/s)for x in range(-r,r+1)]for y in range(-r,r+1)]

```

Uses the rule where you may hardcode 3.14 and 2.72 at 1 byte cost each.
> 5 votes

# Answer
# Perl 6, 71 bytes

```
->\r,\σ{map ->\y{map ->\x{exp((x*x+y*y)/-2/σ/σ)/2/pi/σ/σ},-r..r},-r..r}

```

Technically this may be more than 71 bytes if encoded and saved to a file, but I couldn't resist naming the "sigma" input with an actual Greek sigma. It could be renamed to any plain-ASCII letter if one wanted.
> 2 votes

# Answer
# SAS Macro Language, 296 bytes

Probably a much more efficient way to do this but it works :)

This code prints out the resulting dataset.

```
%macro G(r,s);%let l=%eval(2*&r+1);%let pi=%sysfunc(constant(pi));data w;array a[*] t1-t&l;%do i=-&r %to &r;%do j=-&r %to &r;%let t=%sysfunc(sum(&j,&r,1));a[&t]=%sysevalf(1/(2*&pi*&s**2)*%sysfunc(exp(-(%sysfunc(abs(&j))**2+%sysfunc(abs(&i))**2)/(2*&s**2))));%end;output;%end;proc print;run;%mend;

```
> 2 votes

# Answer
## Haskell, 59 bytes

```
r#s|i<-[-r..r]=[[exp(-(x*x+y*y)/2/s/s)/2/pi/s/s|x<-i]|y<-i]

```

Usage example:

```
1#7

[[3.1824449424224664e-3,3.2150851187016326e-3,3.1824449424224664e-3],
 [3.2150851187016326e-3,3.2480600630999047e-3,3.2150851187016326e-3],
 [3.1824449424224664e-3,3.2150851187016326e-3,3.1824449424224664e-3]]

```
> 2 votes

# Answer
# Python 2.7, 167 bytes

A very simple solution:

```
from __future__ import division;from math import*;r,s=input();s*=2*s;R=range(-r,r+1);print"\n".join("\t".join(str(pow(e,-(x*x+y*y)/s)/(pi*s))[:9]for x in R)for y in R)

```

Try it here!

Ungolfed:

```
from __future__ import division
from math import *
r,s = input()                         # Take input
s *= 2*s                              # Set s = 2*s^2; simplifies the expression
R = range(-r,r+1)                     # Range object; used twice

                                   # G(x,y)             # Stripped
print "\n".join("\t".join(str(pow(e,-(x*x + y*y)/s)/(pi*s))[:9] for x in R) for y in R)

```
> 1 votes

# Answer
# JavaScript (Node.js), ~~260~~ ~~229~~ ~~212~~ 208 bytes

```
(r,σ)=>{t=[];z=[];σ*=σ;b=r*-1;y=r;a=2*r++;while(y!=b-1){x=b;while(r>x){z.push(x,y);x++}y--}for(i=0;i<z.length;i+=2){x=z[i];y=z[i+1];t.push(1/(2*Math.PI*σ)*Math.pow(Math.E,(-1*x**2+y**2)/(2*σ)))}return t}

```

Attempt This Online!

How?

```
(r,σ)=>{t=[];z=[];σ*=σ;b=r*-1;y=r;a=2*r++;while(y!=b-1){x=b;while(r>x){z.push(x,y);x++}y--}for(i=0;i<z.length;i+=2){x=z[i];y=z[i+1];t.push(1/(2*Math.PI*σ)*Math.pow(Math.E,(-1*x**2+y**2)/(2*σ)))}return t} : main function
        t=[];z=[]; : Define empty arrays
                  σ*=σ; : set σ to σ squared
                       a=2*r+1;b=r*-1;y=r; : set variables for looping
                                          while(y!=b-1){ : open while loop for y's
                                                        x=b; : reset x value
                                                            while(r+1>x){ : open while loop for x's
                                                                         z.push(x,y); : push xy values to array z
                                                                                x++} : increment x and close loop
                                                                                y--} : decrement y and close loop
                                                                                for(i=0;i<z.length;i+=2){ : open for loop based off length of array z
                                                                                x=s(z[i]);y=s(z[i+1]); : retrieve x and y values from z
                                                                                t.push(....)} : push results to array t +closes for loop
                                                                                1/(2*Math.PI*σ)*Math.pow(Math.E,(-1*x**2+y**2)/(2*σ)) : Gaussian function
                                                                                return t} : returns the results and closes the main function

```
> 1 votes

# Answer
# , 39 bytes

```
{{(^-a%~1#.*:>{@(,&<)~i:x)%o.a=.+:*:y}}

```

Attempt This Online!

```
{{(^-a%~1#.*:>{@(,&<)~i:x)%o.a=.+:*:y}}
{{                                   }} NB. direct definition
                           o.a=.+:*:y   NB. π * (a = 2σ²)
  (^-a%~1#.*:>{@(,&<)~i:x)              NB. computes the eʸ portion
                      i:x               NB. range [-n..n]
              {@(,&<)~                  NB. cartesian product, creates a grid of boxed pairs
             >                          NB. unbox
           *:                           NB. square the pairs
        1#.                             NB. sum¹ the pairs
     a%~                                NB. divide each sum by a, x f~ y -> y f x
    -                                   NB. negate
   ^                                    NB. eʸ
                          %             NB. division

```

See common use 3 for sum¹. The DD allows a non-tacit definition, which helps implement the function directly, but I am working on refactoring this.
> 1 votes

---
Tags: code-golf, math, matrix
---


title: M_ss_ng Lette_s

text:
# Question
Title: M_ss_ng Lette_s
Given this list of all the words in english and a string with s\_me missi\_g lett\__s, find one way to fill in the letters. Do note that some words on the list contain special characters (`! & ' , - . /`) and numbers

# Input:

This list and a string with missing letters.

The input sentence can contain or be missing any of these characters: `! & ' , - . / 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z`. An underscore is used to mark a missing character. All missing characters have a possible solution.

# Output:

One possible solution with all the missing letters fixed. Words split at a space . Case sensitive, includes words with `! & ' , - . /`

# Test Cases

Input: `a string with s_me missi_g lett__s`

All possible outputs: `a string with [same, seme, sime, some] missing letters`

Output Example: `a string with same missing letters`

Input: `A_ 6-po_nt A/_ ada__er`

All possible outputs: `[A., A1, A4, A5, AA, AB, AF, AG, AH, AI, AY, AJ, AK, AM, AO, AP, AQ, AS, AT, AU, AV, AW, Ax, AZ] 6-point [A/C, A/F, A/O, A/P, A/V]`

Output Example: `A. 6-point A/C adapter`

Input: `A_M AT&_ platform_s scyth_'s hee_hee_ he-_e! 2_4,5_t`

All possible outputs: `[A&M, AAM, ABM, ACM, ADM, AFM, AGM, AIM, ALM, APM, ARM, ASM, ATM, AUM, AVM] AT&T platform's scythe's hee-hee! he-he! 2,4,5.t`

Output example: `A&M AT&T platform's scythe's hee-hee! he-he! 2,4,5-t`

SemicolonSeperatedValue for first possible output:

```
a string with s_me missi_g lett__s;a string with same missing letters
A_ 6-po_nt A/_ ada__er;A. 6-point A/C adapter
A_M AT&_ platform_s scyth_'s hee_hee_ he-_e! 2_4,5_t;A&M AT&T platform's scythe's hee-hee! he-he! 2,4,5-t

```

# Scoring

As this is , shortest solution in bytes wins.

# Answer
> 3 votes
# Jelly,  ~~18 25 20~~  19 bytes

...noticed a bug during write-up, cost 7 to fix naively, then saved 5 with another approach to fix it.

```
LÞṗ⁹ḲL¤K€ḟ”_⁼œ&ʋ@ƇṪ

```

A dyadic Link accepting a list of lists of characters on the left (words) and a list of characters on the right (string) which returns a list of characters.

**Try it online!**
...using a hugely restricted word list due to incredible inefficiency (although it could be far worse!)

### How?

```
LÞṗ⁹ḲL¤K€ḟ”_⁼œ&ʋ@ƇṪ - Link: words, W; string, S
 Þ                  - sort (W) by:
L                   -   length (this is so we get final results which will match
                                in length when we use Ṫ at the end of the Link)
      ¤             - nilad followed by link(s) as a nilad:
   ⁹                -   chain's right argument (S)
    Ḳ               -   split on spaces
     L              -   length
  ṗ                 - Cartesian power (all ways of making that number of words)
       K€           - join €ach with spaces
                 Ƈ  - filter keep those for which:
               ʋ@   -   last four links as a dyad with swapped arguments:
          ”_        -     literal '_' character
         ḟ          -     filter discard (remove all '_'s from S)
             œ&     -     (S) multi-set intersection (current value)
            ⁼       -     equal? (S without '_'s == multi-set intersection?)
                  Ṫ - head (last result)

```

# Answer
> 2 votes
# Python 2, ~~96~~ ~~105~~ ~~99~~ 101 bytes

```
lambda p,W:' '.join([w for w in W if all(map(lambda c,d:c in['_',d]and d,s,w))][0]for s in p.split())

```

Try it online!

`W` is the list of words which is set up separately; I'm using the `unix words` file on TIO, which doesn't contain `platform's` or `scythes's`.

Added 2 bytes for Shaggy.

# Answer
> 2 votes
# C (gcc), ~~232~~ 226 bytes

* -23 bytes from @ceilingcat
* +17 bytes for required header file

Like the other submissions, I used `/usr/share/dict/words`; change the first argument to select another wordlist and the second argument to specify the size (the function itself just needs an array of strings as the dictionary.) On a non-matched word with a `_`, the original word is returned.

```
#import<string.h>
*g(s,t,u,v,w)char*s,**t,*u,*v,*w;{for(w=index(s,95)?0:s;(v=*t)&&!w;w=*u+*v?0:*t,t++)for(u=s;*u==95|*v==*u&&*v++&&*u++;);s=w?:s;}h(s,t,c,u)int*s,*t,*c,*u;{for(u=s;c=strtok(u," ");u=0)printf(" %s"+!!u,g(c,t));}

```

Try it online!

# Answer
> 2 votes
# Java 10, 127 bytes

```
L->s->{for(var x:s.split(" "))for(var w:L)if(w.matches(x.replace(".","\\.").replace("_","."))){System.out.print(w+" ");break;}}

```

Try it online (also uses the `/usr/share/dict/words` TIO word-library, which doesn't contain `platform's` or `scyth's`, but the lambda-function works with any kind of list String-List provided).

**Explanation:**

```
L->s->{                   // Method with String-List & String parameters and no return-type
  for(var x:s.split(" ")) //  Loop over the parts of the input-String, split by spaces
    for(var w:L)          //   Inner loop over the words
      if(w.matches(x.replace(".","\\.")
                          //    Escape all dots
                    .replace("_","."))){
                          //    Replace all underscores with regex-dots
                          //    And if the current word matches it:
        System.out.print(w+" ");
                          //     Print the word, plus a space
        break;}}          //     And stop the inner loop

```

# Answer
> 1 votes
# Clean, ~~174~~ 171 bytes

```
import StdEnv,Text
$l=join" "o map(hd o filter(\w=any((==)w)l)o@o split"_")o split" "
@[h:t]|t>[]=[h<+c<+v\\c<-['0'..'9']++['a'..'z']++['A'..'Z']++['!&\',-./'],v<- @t]=[h]

```

Try it online!

TIO link uses the dictionary in `/usr/share/dict/words` but it'll work with any list of words.

# Answer
> 1 votes
# 05AB1E (legacy), 27 bytes

```
#εD'_åiUʒX‚ζεD'_åsË~}P}Ω]ðý

```

Can definitely be golfed a bit more, but this will do for now.

First input is the string, second a list of words. If multiple words are possible, it picks a random one.

Assumes the sentence always contains at least a single space. If this is not allowed, the `#` has to be replaced with `ð¡`.

Uses the legacy version because the zip-builtins work on strings, whereas these have to be character-lists in the new version of 05AB1E. In the new version, the `ʒX‚ζεD'_åsË~}P}` would have been 1 byte longer because of that: `ʒSXS‚ζε'_åyË~}P}`.

Try it online (with a small sample dictionary list).

**Explanation:**

```
#                   # Split the (implicit) first input-String on spaces
 ε                  # Map over each word:
  D                 #  Duplicate the current word
   '_åi            '#  If the word contains an underscore:
       U            #   Pop the copy and store it in variable `X`
        ʒ           #   Filter over the (implicit) second input-list of words:
         X‚         #    Pair `X` with the current word
           ζ        #    Zip/transpose, swapping rows/columns with spaces as default
                    #    filler if the strings are of unequal length
            ε       #    Map over each pair of characters
             D      #     Duplicate it
              '_å  '#     Check if the pair contains an underscore
             s      #     Swap to get the map-value again
              Ë     #     Check that both characters are the same
                 ~  #     Check that either of these were truthy
            }P      #    After the map: check if all pairs were truthy
        }Ω          #   After the filter: pop and push a random valid word
                    #  (implicit else: use the unmodified word from the duplicate)
 ]                  # Close both the if-statement and map
  ðý                # And join the list by spaces
                    # (after which the result is output implicitly)

```

# Answer
> 1 votes
# Husk, 22 bytes

```
wm`₁⁰w²
ḟoΛ='_żμ?'_³=⁰

```

Try it online!

For each word in query text, goes through all words in the dictionary substituting matching characters for `'_'`. If, after doing this, the word is only `'_'`s, then it matched at all non-`'_'` characters, so it's a valid replacement.

<pre><code> ḟoΛ='_żμ?'_³=⁰     # helper function:
                    # finds word in arg2 that matches arg1
                    # except at '_' characters.
ḟ                   # get first element that satisfies
 oΛ='_              # all elements are equal to '_'
                    # of
       żμ           # zip togethter arg2 and arg1 with
         ?   =⁰     # if they're equal
            ³       # then arg 2
          '_        # otherwise '_'

wm`₁⁰w²             # main program:
w                   # join with spaces
 m   w²             # map arg2 split on spaces
  `₁⁰               # using helper function with arg1
```
</code></pre>

# Answer
> 0 votes
# Ruby, 53 bytes

```
->d,s{s.gsub(/\S+/){d.grep(/#{$&.tr ?_,?.}/)[0]||_1}}

```

Attempt This Online!

---
Tags: code-golf, string, natural-language, word-puzzle
---


title: Solve a jigsaw puzzle

text:
# Question
Title: Solve a jigsaw puzzle
A jigsaw puzzle consists of (usually rectangular-ish) pieces. On each side of a piece, there is either an edge or a *connector* (a term I made up). A connector is either a tab sticking out (outie) or a slot facing inwards (innie). Two pieces can be joined if the outie tab can fit into the innie slot. The goal is to assemble all the pieces into a single unit.

To turn it into a computational problem, we'll assume that the jigsaw puzzle is a perfect rectangular grid of pieces, and instead of having innies and outies, we'll use corresponding positive integers, which I'll call "connector IDs". In other words, two pieces can put next to each other if they have the same number on their adjacent side.

## The challenge

As input, take in a series of lines of 5 positive integers. The first number indicates the ID of the piece; the next four represent the nature of the pieces' top, right, bottom, and left sides respectively. One symbol of your choice should be reserved to represent an edge.

* The piece IDs will always start at 0 or 1 (your choice) and increase by 1 for each successive line; in other words, the piece ID is equal to the line number. If you want, you can omit the piece ID from the input format (so there are only 4 integers per line).
* You can assume the set of connector IDs will either be \\$\\{0,1,\ldots,m-1\\}\\$ or \\$\\{1,2,\ldots,m\\}\\$ for some positive integer \\$m\\$ -- your choice.

Output, in some reasonable format, a grid of piece IDs such that every adjacent piece in a column/row has the same number on their neighboring side and all the side corresponding to edges are on the edge of the grid. There is no rotation allowed. (If there are multiple solutions, you can output any valid solution.)

## Example

In this illustration, I will represent each piece as the following:

```
/.1.\
0 0 2
\.3./

```

Where the number in the center is the piece ID and the numbers on the edges are the identifiers for the type of edge/connector. In this example, I'll use `0` to indicate an edge side.

Suppose we had the 3 by 3 jigsaw puzzle

```
/.0.\ /.0.\ /.0.\
0 1 2 2 7 3 3 4 0
\.3./ \.1./ \.5./
/.3.\ /.1.\ /.5.\
0 2 1 1 8 6 6 5 0
\.4./ \.4./ \.5./
/.4.\ /.4.\ /.5.\
0 3 2 2 9 3 3 6 0
\.0./ \.0./ \.0./

```

(Note that the same connector ID can appear on multiple neighboring sides.) This could be represented as the input

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

```

We would then expect an output like

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

```

Standard loopholes are forbidden. Since this is , the shortest program wins.

# Answer
# Python3, 210 bytes:

```
def f(m,c=[]):
 if(C:=len(c))==9:yield[c[i:i+3]for i in range(0,9,3)];return
 for i in{*m}-{*c}:
  t=[]
  if C%3>0:t+=[m[c[-1]][1]==m[i][3]]
  if C>3:t+=[m[c[C-3]][2]==m[i][0]]
  if all(t):yield from f(m,c+[i])

```

Try it online!
> 1 votes

# Answer
# Python3, 866 bytes:

```
y=[[int(i)for i in l.split()]for l in x.split('\n')]
u=[]
w=lambda z:[p for p in y if p[1:3]==z and not any(p in s for s in u)]
k=False
o=True
d=lambda z,g:z.append(g)
d(u,w([0,0]))
def v(x,t):
    for i in range(len(x[0])):
        e=x[0][i]
        if len(x)==1:
            d(u,t+[e])
            if c():return o
            u.pop()
        else:
            if v(x[1:],t+[e]): return o
    return k
def c():
    a=u[-1];b=[]
    if len(a)==1 and a[0][3:]==[0,0]:return o
    if a[0][4]!=0:
        d(b,w([0,a[0][4]]))
        if b[-1]==[]:return k
    for i in range(1,len(a)):
        d(b,w([a[i-1][3],a[i][4]]))
        if b[-1]==[]:return k
    if a[-1][3] != 0:
        d(b,w([a[-1][3],0]))
        if b[-1]==[]:return k
    return v(b,[])
c();m=0;f=[]
for r in u:
    if m<len(r):[d(f[i],r[i][0])for i in range(m)];d(f,[r[-1][0]]);m+=1
    else:[d(f[i+(m-len(r))],r[i][0])for i in range(len(r))]
for g in f:g.reverse()
print('\n'.join([' '.join([str(i)for i in g])for g in f]))

```

Try It Online

here(tio) is simple program to construct test cases
> 1 votes

---
Tags: code-golf
---


title: Make a Strawpoll

text:
# Question
Title: Make a Strawpoll
> Moderator note: https://strawpoll.me has officially shut down, and the linked API no longer appears to work or provide data. Therefore, new answers cannot actually do the task and so the challenge has been closed to prevent any new answers.

Strawpolls are great, and we use them in chat all the time for getting opinions on things. But they're kinda annoying to make since you need a webbrowser to make them, and everyone knows that I access PPCG only through SE APIs and curl. So I want you to write some code that uses Strawpoll's API to make a strawpoll with the given options.

## Specs

Take as input a list in any reasonable format of options as strings, and a title which is also a string. Then use the API to make a strawpoll with that title and those options and output the url.

Multiples should not be allowed, duplicate checking should be enforced, and captchas should not be necessary.

# Example

```
"My Awesome Poll"
["option 1", "I like pies", "I also like cakes"]

```

Output: http://strawpoll.me/7275997

This is , so shortest code in **bytes** wins!

# Answer
> 3 votes
# Factor, ~~257~~ 262 bytes

```
TUPLE: p title options dupcheck ;
[ command-line rest [ first ] [ rest ] bi "normal" p boa >json "https://strawpoll.me/api/v2/polls" <post-request> "application/json" "Content-Type" set-header http-request nip json> id>> 10 base> "http://strawpoll.me/" prepend ]

```

Expects a name as the first command-line arg, then options after that.

Requires `com-auto-use`.

Ungolfed:

```
TUPLE: poll
  title options dupcheck ;

: post-json ( post-data url -- response data )
  <post-request>
    "application/json" "Content-Type" set-header
  http-request ;

: strawpoll-main ( -- )
  command-line rest [ first ] [ rest ] bi "normal" poll boa
  >json "https://strawpoll.me/api/v2/polls" post-json nip
  json> id>> 10 base> "http://strawpoll.me/" prepend print ;

```

# Answer
> 1 votes
# Ruby 2.2.4 + HTTParty: 129 bytes

Anonymous function; returns a string with the strawpoll URL. Remember to install the HTTParty gem before running.

```
->q,a{require'httparty';s="http%s://strawpoll.me/%s"
s%[p,HTTParty.post(s%[?s,"api/v2/polls"],body:{title:q,options:a},verify:p)["id"]]}

```

If the URL can be returned with `https://` instead of `http://`, 126 bytes:

```
->q,a{require'httparty';s="https://strawpoll.me/%s"
s%HTTParty.post(s%"api/v2/polls",body:{title:q,options:a},verify:p)["id"]}

```

# Answer
> 1 votes
# Python, 145 bytes

```
lambda t,o:post('https://api.strawpoll.com/v3/polls',json={"title":t,"poll_options":[{"value":x}for x in o]}).json()["url"]
from requests import*

```

A function which takes in a string for the title and *set* of strings for the options and returns the URL. I am not including an ATO/TIO link because you aren't able to do requests from those platforms.

In the intervening years since this question was asked, the original strawpoll API has become defunct, so I'm using the newer API, which is unfortunately more verbose.

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


# Question
Title: Resource for generating shortest regex given a list of strings
I'm looking for a program such that, given a finite list of strings, can find short regexes to match exactly all of them and nothing else.

Since there are multiple languages that express regexes differently, there can correspondingly be multiple regex generators. Each answer must discuss regex generation in one langauge only (or a family of languages for which there is a direct correspondence between regexes in each of them).

# Answer
> 6 votes
The Machine Learning Lab at the University of Trieste, Italy, wrote a web app to solve this exact problem, available at: Automatic Generation of Regular Expressions from Examples based on "genetic programming" and published a paper about it. Based on the fact that it had to come from the Machine Learning Lab of a university in Italy, and was worth publishing a paper about, it is probably a pretty hard problem to solve. Doesn't sound like the type of question for Code Golf SE, but I'm new here, so I wouldn't be the expert on that.

# Answer
> 0 votes
I would approach this problem by searching for common subsequences in each pair of strings in the list, and then building regular expressions that include those subsequences. This would be somewhat like the Re-Pair algorithm, but it would build a grammar from a set of strings instead of one string.

For instance, these strings:

`["red wolf", "red fox", "gray wolf", "gray fox"]`

could be combined into two regular expressions:

`"red (wolf|fox)", "gray (wolf|fox)"`

which can be combined into one regular expression:

`"(red|gray) (wolf|fox)"`

But this problem is probably NP-complete, since it is similar to the smallest grammar problem.

---
Tags: tips, regular-expression
---


title: Prime number checksum

text:
# Question
Title: Prime number checksum
Given a message, append checksum digits using prime numbers as weights.

---

A checksum digit is used as an error-detection method.
Take, for instance, the error-detection method of the EAN-13 code:
The checksum digit is generated by:

* Multiplying each digit in the message alternating by `1` and `3` (the weights)
* Summing it up
* Calculating the difference between the nearest multiple of 10 (Maximum possible value) and the sum

E.g:

```
1214563 -> 1*1 + 2*3 + 1*1 + 4*3 + 5*1 + 6*3 + 3*1 = 46
50 - 46 = 4

```

Although the EAN-13 code can detect transposition errors (i.e. when two adjacent bits are switched, the checksum will be different) it can't detect an error when two bits with the same weight are swapped.
E.g.: `163` -\> checksum digit `8`, `361` -\> checkdum digit `8`

Using a prime checksum, with the first weight being the first prime number, the second weight being the second prime number, etc., errors can be detected when *any* two bits are swapped. Because the primes act as weights, you have an extra factor, *the length of the message `l`*:

1. Multiply each digit in the message by the `n`th prime (First digit times the first prime, second digit times the second prime, etc.)
2. Sum it up
3. Calculate the sum of each prime up to the `l`th prime multiplied by `9` plus `1` (Maximum possible value)
4. Subtract the second sum by the first sum

E.g.:

```
1214563 -> 1*2 + 2*3 + 1*5 + 4*7 + 5*11 + 6*13 + 3*17 = 225
9*(2+3+5+7+11+13+17) + 1 -> 523
523 - 225 = 298

```

## Rules

* Take a decimal string, leading zeros are prohibited
* Output the checksum digits
* Standard Loopholes apply
* This is , the shortest answer wins!

## Examples

```
[In]:  213
[Out]: 69

[In]:  89561
[Out]: 132

[In]:  999999
[Out]: 1

[In]:  532608352
[Out]: 534

```

# Answer
# sclin, 26 bytes

```
_9+""Q $P""zip *0\+ fold1+

```

Try it here!

I didn't like how my old language lin was turning out, so I've spent a bunch of time reworking/re-implementing it in Scala! So far it's very very WIP, but it works.

For testing purposes (use `-i` flag if running locally):

```
[2 1 3].
_9+""Q $P""zip *0\+ fold1+

```

## Explanation

Prettified version:

```
_ 9+ dup $P () zip * 0 \+ fold 1+

```

Assuming input digit list *x*,

* `_ 9+` i.e. `-x + 9`
* `dup $P () zip` truncate infinite list of primes to *x*'s length (more literally, zip *x* to primes but only keep primes)
* `*` (vectorized) multiply
* `0 \+ fold` sum
* `1+` increment
> 6 votes

# Answer
# Fig, \\$13\log\_{256}(96)\approx\\$ 10.701 bytes

```
}S*-x9tFmC@pL

```

Try it online!

-1 character thanks to Seggan
> 5 votes

# Answer
# Mathematica, ~~32~~ 29 bytes

```
(9-#).Prime@Range@Length@#+1&

```

View it on Wolfram Cloud!

*-3 bytes thanks to Roman!*

Accepts input as a list of decimal digits.
> 5 votes

# Answer
# Vyxal, 8 bytes

Thanks to Steffan for removing the flag!

```
9ε:ẏǎ*∑›

```

Try it Online!

**Explanation:**

```
9ε:ẏǎ*∑› # whole program

9ε       # absolute of n-9 (vectorized)
  :ẏ     # push range of the list length
    ǎ    #  and convert into primes
     *   # multiplication (vectorized)
      ∑  # sum the result
       › # and increment it

```
> 4 votes

# Answer
# Ruby `-rprime`, ~~74~~ ~~60~~ 33 bytes

-27 bytes (!) thanks to south

```
->d{d.zip(Prime).sum{_2.*9-_1}+1}

```

Attempt This Online!

In Ruby `Prime` is enumerable so you can `zip` with the prime numbers without calling `Prime.each` or `.take`.
> 3 votes

# Answer
# Nibbles, 13 bytes (26 nibbles)

```
+~+!$|,~==,|,$~%@$2~*- 9

```

Nibbles has no prime number builtins, so 7.5 bytes (15 nibbles) are used here to construct the infinite list of primes:

```
|,~==,|,$~%@$2  # infinite list of primes:
|               # filter
 ,~             # the infinite list of integers by
      |  ~      #   list of falsy elements of
           @    #   itself
          % $   #   modulo
       ,$       #   1..each integer
     ,          #   has a length
   ==           #   equal to
             2  #   two

```

Once this is done, it's another 5.5 bytes (11 nibbles) to subtract each input digit from 9, zip by multiplication with the primes, and add 1 to the sum.

```
   !$           # zip the input digits
      LOP       # with the list of primes (see above)
          ~     # using the function
            - 9 #   subtract each digit from 9
           *    #   and multiply by each prime
  +             # now get the sum
+~              # and add 1

```
> 3 votes

# Answer
# , 16 bytes

```
1+1#.p:@i.@#*9-]

```

Accepts a list of digits.

Attempt This Online!

```
1+1#.p:@i.@#*9-]
             9-] NB. 9 - each item of input
     p:@i.@#     NB. list of primes, input length(#)->range 0..n-1(i.)->nth prime(p:)
            *    NB. element-wise multiplication
  1#.            NB. sum¹
1+               NB. increment

```

See common use 3 for sum¹.
> 3 votes

# Answer
# JavaScript (ES6), 64 bytes

Expects either a string or an array of digit characters.

```
f=(s,i=n=0)=>s[i]?(P=x=>n%x--?P(x):x?0:9-s[i++])(n++)*n+f(s,i):1

```

Try it online!

### Commented

```
f = (              // f is a recursive function taking:
  s,               //   s = input string
  i =              //   i = pointer in s
  n = 0            //   n = prime candidate
) =>               //
s[i] ?             // if s[i] is defined:
  ( P = x =>       //   P is a helper recursive function taking
                   //   x = n - 1 and testing whether n is prime
    n % x-- ?      //   if x does not divide n (decrement x afterwards):
      P(x)         //     do recursive calls until it does
    :              //   else:
      x ?          //     if x is not 0:
        0          //       n is composite: return 0
      :            //     else:
        9 - s[i++] //       n is prime: return 9 - s[i] and increment i
  )(n++)           //   initial call to P with x = n, then increment n
  * n              //   multiply the result by n
  + f(s, i)        //   add the result of a recursive call to f
:                  // else:
  1                //   stop the recursion and add 1 to the final result

```
> 2 votes

# Answer
# Factor \+ `math.primes math.unicode`,  ~~48~~  47 bytes

```
[ dup length nprimes dup Σ 9 * 1 + -rot v. - ]

```

Takes input as a sequence of integers (digits).

Try it online!

```
        ! { 1 2 1 4 5 6 3 }
dup     ! { 1 2 1 4 5 6 3 } { 1 2 1 4 5 6 3 }
length  ! { 1 2 1 4 5 6 3 } 7
nprimes ! { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 }
dup     ! { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 } { 2 3 5 7 11 13 17 }
Σ       ! { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 } 58     (sum)
9       ! { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 } 58 9
*       ! { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 } 522
1       ! { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 } 522 1
+       ! { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 } 523
-rot    ! 523 { 1 2 1 4 5 6 3 } { 2 3 5 7 11 13 17 }
v.      ! 523 225        (dot product)
-       ! 298

```
> 2 votes

# Answer
# 05AB1E, 8 bytes

```
9αā<Ø*O>

```

Try it online!

## Explanation

```
9αā<Ø*O>
9α        Get the absolute difference between 9 and each item in the list - call this X
  ā       Push [1..length(a)] without popping
   <      Decrement each
    Ø     Push nth (zero-indexed) prime fore ach
     *    Multiply each by the corresponding item in X
      O   Sum
       >  Increment

```
> 2 votes

# Answer
# Python 2, 122 bytes

```
lambda n:sum(map(lambda x,y:(9-x)*y,map(int,n),[i for i in range(2,len(n)**2)if all(i%m for m in range(2,i))][:len(n)]))+1

```

Try it online!

Accepts a string as input (ex: "12345")

Restructures the checksum equation as `sum((9-d)*p)+1`, where `d` is the input as a list of digits and `p` is a list of the first `len(d)` primes.
> 2 votes

# Answer
# Raku, 40 bytes

```
{1+sum (9 X-.comb)Z*grep &is-prime,^∞}

```

Try it online!

* `grep &is-prime, ^∞` is an infinite, lazy sequence of prime numbers.
* `9 X- .comb` is a list of nine minus each digit in the input number.
* `Z*` zips those sequences together with multiplication.
* `1 + sum ...` adds those products together and adds 1.
> 2 votes

# Answer
# PARI/GP, 27 bytes

```
a->1+primes(#a)*[9-x|x<-a]~

```

Attempt This Online!
> 2 votes

# Answer
# C (clang), ~~99~~ ~~93~~ 75 bytes

-4 bytes thanks to c--

```
i,d;f(*t,*r){for(*r=i=1;*t;*r-=(*t++-57)*i)for(d=2;d>1;)for(d=++i;i%--d;);}

```

Try it online!

Ungolfed and commented

```
int primecs(char* text)
{
    // start then result at one
    int result = 1;

    // first prime number
    int prime = 1;

    // loop until we get to the end of the string
    while (*text != 0)
    {
        // calculate the next prime number
        int div = 2;
        while (div != 1)
        {
            // set the divisor to the current value of prime
            div = prime;

            // increment prime;
            prime++;

            // loop until mod(prime, div) = 0
            while (prime % div != 0)
                div--;
        }

        // add the results;
        result += (prime * 9) - ((*text - '0') * prime);

        // move to next character
        text++;
    }
    return result;
}

```
> 2 votes

# Answer
# Excel, ~~148~~ ~~147~~ 138 bytes

Saved 1 byte thanks to jdt

If anybody has a shorter way to get a list of primes in Excel, I would love to have it.

```
=LET(s,SEQUENCE(2^10),t,TRANSPOSE(s+1),n,SEQUENCE(LEN(A1)),SUM((9-MID(A1,n,1))*INDEX(FILTER(s,MMULT(-(IF(s>t,MOD(s,t))=0),s+1)=0),n+1))+1)

```

Excel does not have a built-in for producing a list of the first *n* primes. About 80 bytes of this solution is just generating that list. The 84 byte formula below outputs the primes up to 1024. Change the `2^10` based on how much memory you have available and you can get a longer list.

---

**Here is the part that creates the list of prime numbers:**

```
=LET(s,SEQUENCE(2^10),t,TRANSPOSE(s+1),FILTER(s,MMULT(-(IF(s>t,MOD(s,t))=0),s+1)=0))

```

Let's break down that chonker first. After that, the rest is fairly straightforward. Here's the easy bits:

* `s,SEQUENCE(2^10)` just makes an array from 1 to 1024.
* `t,TRANSPOSE(s+1)` transposes that array and adds 1 to each element.

---

**Now it gets more complicated.**

```
FILTER(s,MMULT(-(IF(s>t,MOD(s,t))=0),s+1)=0)

```
* `IF(s>t,MOD(s,t))` creates a 2D array that's filled with either the result of `MOD(s,t)` or, if `s<=t`, it's just `FALSE`.
* `-(IF(~)=0)` turns that array into a series of `TRUE` or `FALSE`. Note that `FALSE` from the previous step does not equal `0` because it's not considered a number yet. Once we have that T/F table, we use the unary `-` to convert `TRUE` to `-1` and `FALSE` to `0`.
* `MMULT(-(IF(~)=0),s+1)` multiplies that 1/0 matrix with the same values that we see in `t`. I have to go re-read how `MMULT()` works every time I use it so I'm not going to try to explain matrix math here because I'm not good at it. Because \[magic\], the values at all the prime indices will be 0.
    + Note: The magic isn't perfect so the value `1` is also included in that list because, mathematically, it could be prime. However, we have decided to *define* prime numbers to not include 1. See more over at math.SE. We could remove it from this results list but it costs less bytes to just skip over it later.
* `FILTER(s,MMULT(~)=0)` returns all the values from `s` where the corresponding value in the `MMULT()` was `0` since those are the primes (and also 1).

Now we have a neat list of all the prime numbers from 1 to 2^10 or whatever value your memory allows.

OK, if we used `LET()` to rename everything in that `FILTER()` function to just `p` (which costs 4 more bytes than *not* renaming it), then the original function looks like this:

```
=LET(s,SEQUENCE(2^10),t,TRANSPOSE(s+1),p,FILTER(s,MMULT(-(IF(s>t,MOD(s,t))=0),s+1)=0),n,SEQUENCE(LEN(A1)),SUM((9-MID(A1,n,1))*INDEX(p,n+1))+1)

```

---

**When we take out the bits we already know about in the formula above, it looks like this:**

```
=LET(s,~,t,~,p,~,n,SEQUENCE(LEN(A1)),SUM((9-MID(A1,n,1))*INDEX(p,n+1))+1)

```

Here are the last few pieces:

* `n,SEQUENCE(LEN($A1))` creates an array 1 to the length of the input.
* `(9-MID($A1,n,1))` extracts each digit from the input and subtracts it from 9.
* `*INDEX(p,n+1)` multiplies that result by the *n*th term from our prime list (shifted up by 1 to correct for the `1` at the beginning).
* `SUM(~)+1` adds up all those results and adds 1.

---

**Here's the final result:**
> 2 votes

# Answer
# Jelly,  ~~11 10~~  8 bytes

```
9_ḋJÆN$‘

```

A monadic Link that accepts a list of integers and yields the checksum value as an integer.

**Try it online!**

### How?

```
9_ḋJÆN$‘ - Link: list of integers, A
9        - nine
 _       - subtract A (vectorises) -> Remainders = [9-A1, 9-A2, ...]
      $  - last two links as a monad - f(A):
   J     -   range of length (A) -> [1,2,3,4,5,...,length(A)]
    ÆN   -   nth prime -> Primes = [2,3,5,7,11,...,length(A)th-Prime]
  ḋ      - (Remainders) dot product (Primes) = (9-A1)*2 + (9-A2)*3 + ...
       ‘ - increment -> checksum

```
> 1 votes

# Answer
# Charcoal, 36 bytes

```
≔¹η≔¹ζＦＳ«≦⊕ζＷ⊙…²ζ¬﹪ζλ≦⊕ζ≧⁺×ζ⁻⁹Ｉιη»Ｉη

```

Try it online! Link is to verbose version of code. Explanation:

```
≔¹η

```

Start with a checksum of `1`.

```
≔¹ζ

```

Start looking for prime numbers greater than `1`.

```
ＦＳ«

```

Loop over the input digits as a string.

```
≦⊕ζ

```

Increment the candidate prime number.

```
Ｗ⊙…²ζ¬﹪ζλ

```

While it has a nontrivial proper divisor...

```
≦⊕ζ

```

... increment the candidate prime number.

```
≧⁺×ζ⁻⁹Ｉιη

```

Account for the contribution of this digit to the checksum.

```
»Ｉη

```

Output the final checksum.

34 bytes using the newer version of Charcoal on ATO:

```
≔¹ηＷ‹ＬυＬθ«≦⊕η¿⬤υ﹪ηκ⊞υη»Ｉ⊕Σ×υ⁻⁹Ｉ⪪θ¹

```

Attempt This Online! Link is to verbose version of code. Explanation:

```
≔¹η

```

Start looking for prime numbers greater than `1`.

```
Ｗ‹ＬυＬθ«

```

Repeat until sufficient prime numbers have been obtained.

```
≦⊕η

```

Increment the candidate prime number.

```
¿⬤υ﹪ηκ

```

If it is not evenly divided by any prime number found so far, ...

```
⊞υη

```

... add the prime number to the predefined empty list.

```
»Ｉ⊕Σ×υ⁻⁹Ｉ⪪θ¹

```

Calculate the incremented dot product of the list of prime numbers with the digits of the 9's complement of the input number.
> 1 votes

# Answer
# Pyth, 17 bytes

```
hs*Vm-9vdz.fP_Zlz

```

Try it online!

### Explanation

```
h                    add one to
 s                   the sum of
  *V                 the vectorized multiplication of
    m-9vdz               9-d where d is each digit of the input
          .fP_Zlz        the first n primes where n is the length of the input

```
> 1 votes

# Answer
# Python, 116 bytes

Takes input a decimal number as a string, while using a recursive function to calculate the first `n` primes and the proposed equation of user `GotCubes`.

```
f=lambda n,i=1,p=1:n*[0]and p%i*[i]+f(n-p%i,i+1,p*i*i)
c=lambda s:sum(y*(9-x)for x,y in zip(map(int,s),f(len(s))))+1

```

Attempt This Online!
> 1 votes

# Answer
# GeoGebra, 73 bytes

```
n={
InputBox(n
l=IterationList(NextPrime(a),a,{2},Length(n)-1
1+Sum(9l-nl

```

Input is comma separated digits in the Input Box

Try It On GeoGebra!
> 1 votes

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


title: MD5 Hello, World!

text:
# Question
Title: MD5 Hello, World!
MD5 checksums are relatively easy to crack. For this challenge you will create two separate programs, the first one writing `Hello, World!` and the second one writing `Goodbye Cruel World!` but with the source code having identical MD5 hashes.

* The source code of both programs must not be identical.
* The programs can use the same or different languages.
* Trailing newlines are allowed, but the programs cannot write anything else to the output.
* Shortest combined byte code wins.

The following TIO can be used to calculate the MD5 hashes for your programs.

# Answer
> 18 votes
## Python, ~~360 + 360 = 720 bytes~~ ~~206 + 206 = 412 bytes~~ 201 + 201 = 402

Hi, my two cents. This answer is inspired by this blog by Nat McHugh.

A short introduction to explain the idea behind the code.

### MD5 hash collision and exploitation.

MD5 works with blocks of 64 bytes. If two blocks (with a length multiple of 64 bytes) A & B have the same hash, then appending the same contents C to both will keep the same hash.

*hash(A) = hash(B) -\> hash(A + C) = hash(B + C)*

Exploiting this simple principle is possible to get two different files with the same MD5.

There are several attacks to generate MD5 collision, here we are interested in attacks for files having **identical prefixes**.

These are the steps of the attack:

1. Define an arbitrary prefix with any content and length.
2. Pad the prefix to the next 64-byte block.
3. Compute collision blocks based on the prefix. The differences between the blocks are predetermined by the attack.
4. Concatenate the prefix with each of the two blocks to get two different sequences: the hash is the same for the two sequences despite the differences.
5. Add any arbitrary identical suffix to the sequences: the hash will remain the same for the two sequences.

The final structure of the two files will be the following:

| GOOD FILE |  | EVIL FILE |
| --- | --- | --- |
| Prefix
\[n * 64 bytes\] | = | Prefix
\[n * 64 bytes\] |
| Collision A
\[128 bytes\] |  | Collision B
\[128 bytes\] |
| Suffix
\[any length\] | = | Suffix
\[any length\] |

In the end, the files are almost identical, except for a few bits.

For the exploitation, we use an approach called **data exploit**: run code that looks for differences and displays one content or the other (typically trivial since differences are known in advance).

In particular, we use FastColl to generate the two collision blocks, given the prefix. Each collision block needs two MDS blocks (so it is 128 bytes long). This is the difference mask for the two collision blocks:

```
................
...X............
.............XX.
...........X....
................
...X............
.............XX.
...........X....

```

Looking at the difference mask, the 20th byte is the first byte that shows a difference (each . represents one byte). So, we can use this information to trigger a different behavior in the two files. Knowing the expected value of the 20th byte in the collision block, we can create an if based on this value.

Look at the following example showing two collision blocks (courtesy of https://github.com/corkami/collisions):

```
00:  37 75 C1 F1-C4 A7 5A E7-9C E0 DE 7A-5B 10 80 26  7u┴±─ºZτ£α▐z[►Ç&
10:  02 AB D9 39-C9 6C 5F 02-12 C2 7F DA-CD 0D A3 B0  ☻½┘9╔l_☻↕┬⌂┌═♪ú░
20:  8C ED FA F3-E1 A3 FD B4-EF 09 E7 FB-B1 C3 99 1D  îφ·≤ßú²┤∩○τ√▒├Ö↔
30:  CD 91 C8 45-E6 6E FD 3D-C7 BB 61 52-3E F4 E0 38  ═æ╚Eµn²=╟╗aR>⌠α8  \
40:  49 11 85 69-EB CC 17 9C-93 4F 40 EB-33 02 AD 20  I◄àiδ╠↨£ôO@δ3☻¡
50:  A4 09 2D FB-15 FA 20 1D-D1 DB 17 CD-DD 29 59 1E  ñ○-√§· ↔╤█↨═▌)Y▲    ................
60:  39 89 9E F6-79 46 9F E6-8B 85 C5 EF-DE 42 4F 46  9ë₧÷yFƒµïà┼∩▐BOF    ...X............
70:  C2 78 75 9D-8B 65 F4 50-EA 21 C5 59-18 62 FF 7B  ┬xu¥ïe⌠PΩ!┼Y↑b {    .............XX.
                                                                          ...........X....
                                                                          ................
00:  37 75 C1 F1-C4 A7 5A E7-9C E0 DE 7A-5B 10 80 26  7u┴±─ºZτ£α▐z[►Ç&    ...X............
10:  02 AB D9 B9-C9 6C 5F 02-12 C2 7F DA-CD 0D A3 B0  ☻½┘╣╔l_☻↕┬⌂┌═♪ú░    .............XX.
20:  8C ED FA F3-E1 A3 FD B4-EF 09 E7 FB-B1 43 9A 1D  îφ·≤ßú²┤∩○τ√▒CÜ↔    ...........X....
30:  CD 91 C8 45-E6 6E FD 3D-C7 BB 61 D2-3E F4 E0 38  ═æ╚Eµn²=╟╗a╥>⌠α8
40:  49 11 85 69-EB CC 17 9C-93 4F 40 EB-33 02 AD 20  I◄àiδ╠↨£ôO@δ3☻¡   /
50:  A4 09 2D 7B-15 FA 20 1D-D1 DB 17 CD-DD 29 59 1E  ñ○-{§· ↔╤█↨═▌)Y▲
60:  39 89 9E F6-79 46 9F E6-8B 85 C5 EF-DE C2 4E 46  9ë₧÷yFƒµïà┼∩▐┬NF
70:  C2 78 75 9D-8B 65 F4 50-EA 21 C5 D9-18 62 FF 7B  ┬xu¥ïe⌠PΩ!┼┘↑b {

```

In the first collision block, the value of the 20th byte is 0x39, while in the second 0xB9. We can exploit this difference by writing something like this:

```
if collision_block[20] = 0x39 then:
    do a good thing
else:
    do a bad thing

```

This is the idea used in the code to create the two source files with the same MD5 hash, but different behavior.

## References:

\[1\] https://natmchugh.blogspot.com/2014/10/how-i-made-two-php-files-with-same-md5.html?m=1

\[2\] https://github.com/corkami/collisions

## Files generated for this answer

These are two files with the same md5 hash:

```
MD5 (good.py) = 120909f9a5185bcbd7ef716d6c1f3787
MD5 (evil.py) = 120909f9a5185bcbd7ef716d6c1f3787

```

`good.py`

```
#coding: L1
# coding: L1
print('%s World!'%('Hello','Goodbye Cruel')['Z'>"""úzžù
WjmEò÷Sïå#nî˜ê-Z<fi #ûòûûîðŒ    ‡k×T,qK=®=ˆÄ†ä7vÒ2¯áWü§›(0ã¢dÞåÅA4æø+tÐWOLeÁí-Åéòå«·Ùµë0š4zgqß?Í…fÿ¦¼Ôh¨îx"""[19]])

```

`evil.py`

```
# coding: L1
print('%s World!'%('Hello','Goodbye Cruel')['Z'>"""úzžù
WjmEò÷Sïå#nî˜ê-Z<fi #ûòûûîðŒ    ‡k×T,qK=®=ˆÄ†ä7öÒ2¯áWü§›(0ã¢dÞåÅA4Žæø+tÐWOLeÁí-Åéòå«·Ùµë0š´ygqß?Í…fÿ¦¼Ôè¨îx"""[19]])

```

If you run `good.py`, you get:

```
>> python good.py
Hello World!

```

while for `evil.py`:

```
>> python evil.py
Goodbye Cruel World!

```

The length of the two files is the same, i.e., 201 bytes.

Note that, due to the presence of non-ASCII characters in the Python code, I cannot guarantee that a copy and paste of the above text can reproduce the results. So, here is the C code to create the two files:

```
#include <stdio.h>

// The number of bytes for the prefix and for the collision block
// must be 64 and 128 respectively to generate an MD5 collision
#define N_PREFIX_BYTES 64
#define N_COLLISION_BYTES 128

#define BYTE_TYPE unsigned char

void write_binary_file(
    char *filepath,
    BYTE_TYPE *prefix,
    BYTE_TYPE *collision,
    BYTE_TYPE *suffix,
    size_t prefix_nbytes, size_t collision_nbytes, size_t suffix_nbytes
){
    FILE *ptr;

    ptr = fopen(filepath, "wb");
    fwrite(prefix, sizeof(BYTE_TYPE), prefix_nbytes, ptr);
    fwrite(collision, sizeof(BYTE_TYPE), collision_nbytes, ptr);
    fwrite(suffix, sizeof(BYTE_TYPE), suffix_nbytes, ptr);
    fclose (ptr);
}

int main(){
    size_t n_suffix_bytes;
    char *code_filepaths[2] = {"good.py", "evil.py"};
    unsigned long tot_len=0, curr_len=0;

    // Here the initial and final part of the output code;
    // mind that the prefix must have a length of 64 bytes.
    // The idea here is to take advantage of the slightly
    // difference between the two collission blocks to generate
    // different outputs in the two programs.
    BYTE_TYPE source_code_prefix[N_PREFIX_BYTES] = "# coding: L1\nprint('%s World!'%('Hello','Goodbye Cruel')['Z'>\"\"\"";
    // As you can see, the output code is in Python language.
    //
    // The different output string is created choosing its initial part
    // between the elements of a tuple two strings ('Hello','Goodbye Cruel').
    // In particular, the index is a condition on the first different character
    // between the two collision blocks, i.e., the 20th.
    // If this characher is less than 'Z', the condition is True,
    // (i.e. it is equivalent to 1), so the second element of the
    // tuple is selected; otherwise the condition
    // is False (0), so the first element of the tuple is selected
    // To recap, this is the ungolfed sketch of the code:
    //  is_evil = 'Z' > collision_block[19]
    //  initial_part = ('Hello','Goodbye Cruel')[is_evil]
    //  print('%s World!'%initial_part)
    BYTE_TYPE source_code_suffix[9] = "\"\"\"[19]])";

    // You can put one this two binary blocks between source_code_prefix and source_code_suffix
    // and get the same MD5 hash, even if the two blocks are slightly different
    BYTE_TYPE collision_blocks[2][N_COLLISION_BYTES] = {
        {
            0xfa, 0x7a, 0x9e, 0x18, 0xf9, 0x0a, 0x57, 0x6a, 0x11, 0x6d, 0x45, 0xf2, 0xf7, 0x53, 0xef, 0xe5,
            0x23, 0x6e, 0xee, 0x8f, 0x98, 0xea, 0x2d, 0x15, 0x5a, 0x16, 0x3c, 0x66, 0x69, 0x20, 0x23, 0xfb,
            0xf2, 0xfb, 0xfb, 0xee, 0xf0, 0x8c, 0x09, 0x87, 0x6b, 0x02, 0xd7, 0x54, 0x18, 0x10, 0x2c, 0xad,
            0x71, 0x4b, 0x3d, 0xae, 0x3d, 0x88, 0xc4, 0x86, 0xe4, 0x19, 0x37, 0x76, 0xd2, 0x32, 0xaf, 0x15,
            0x1c, 0xe1, 0x0c, 0x57, 0xfc, 0xa7, 0x9b, 0x1b, 0x28, 0x30, 0xe3, 0xa2, 0x64, 0xde, 0xe5, 0xc5,
            0x41, 0x34, 0x1e, 0x0e, 0xe6, 0xf8, 0x18, 0x2b, 0x74, 0x0b, 0xd0, 0x57, 0x4f, 0x4c, 0x65, 0xc1,
            0xed, 0x2d, 0xc5, 0xe9, 0xf2, 0xe5, 0xab, 0xb7, 0xd9, 0xb5, 0xeb, 0x30, 0x9a, 0x34, 0x7a, 0x67,
            0x71, 0xdf, 0x3f, 0xcd, 0x85, 0x1e, 0x66, 0xff, 0xa6, 0xbc, 0xd4, 0x68, 0xa8, 0xee, 0x08, 0x78
        },
        {
            0xfa, 0x7a, 0x9e, 0x18, 0xf9, 0x0a, 0x57, 0x6a, 0x11, 0x6d, 0x45, 0xf2, 0xf7, 0x53, 0xef, 0xe5,
            0x23, 0x6e, 0xee, 0x0f, 0x98, 0xea, 0x2d, 0x15, 0x5a, 0x16, 0x3c, 0x66, 0x69, 0x20, 0x23, 0xfb,
            0xf2, 0xfb, 0xfb, 0xee, 0xf0, 0x8c, 0x09, 0x87, 0x6b, 0x02, 0xd7, 0x54, 0x18, 0x90, 0x2c, 0xad,
            0x71, 0x4b, 0x3d, 0xae, 0x3d, 0x88, 0xc4, 0x86, 0xe4, 0x19, 0x37, 0xf6, 0xd2, 0x32, 0xaf, 0x15,
            0x1c, 0xe1, 0x0c, 0x57, 0xfc, 0xa7, 0x9b, 0x1b, 0x28, 0x30, 0xe3, 0xa2, 0x64, 0xde, 0xe5, 0xc5,
            0x41, 0x34, 0x1e, 0x8e, 0xe6, 0xf8, 0x18, 0x2b, 0x74, 0x0b, 0xd0, 0x57, 0x4f, 0x4c, 0x65, 0xc1,
            0xed, 0x2d, 0xc5, 0xe9, 0xf2, 0xe5, 0xab, 0xb7, 0xd9, 0xb5, 0xeb, 0x30, 0x9a, 0xb4, 0x79, 0x67,
            0x71, 0xdf, 0x3f, 0xcd, 0x85, 0x1e, 0x66, 0xff, 0xa6, 0xbc, 0xd4, 0xe8, 0xa8, 0xee, 0x08, 0x78
        }
    };

    // The number of bytes in the suffix can vary, depending on
    // the code needed to make the source file meaningful
    n_suffix_bytes=sizeof(source_code_suffix) / sizeof(BYTE_TYPE);

    // Write good and evil files. The only thing different is the collision block
    tot_len=0;
    for(int i=0; i<2; ++i){
        write_binary_file(
            code_filepaths[i],
            source_code_prefix, collision_blocks[i], source_code_suffix,
            N_PREFIX_BYTES, N_COLLISION_BYTES, n_suffix_bytes
        );

        curr_len = N_PREFIX_BYTES + N_COLLISION_BYTES + n_suffix_bytes;
        tot_len += curr_len;

        printf("\nBytes in %s: %lu", code_filepaths[i], curr_len);
    }
    printf("\nTotal length: %lu\n", tot_len);

    return(0);
}

```

You can download all the previous files from this Github repo.

**Update 1** Thanks to xnor and Arnauld for the comment and suggestions to improve the answer.

**Update 2** Refactor the code and improve of some bits

---
Tags: code-golf, hello-world, cryptography
---