title: Weird grading system

text:
# Question
Title: Weird grading system
Weirdo Incorporates have a weird way of grading their staffs by the number of days they were present in the office:

```
  0 -  13 : F
 14 - 170 : E
171 - 180 : D
181 - 294 : C
295 - 300 : B
301 - 365 : A

Note: The range is inclusive (i.e. 0-13 means 0 days and 13 days both will evaluate
as grade 'F').

```

# Objective:

Write a program/function that outputs/returns the grade of an employee for the number of days \[within inclusive range of 0-365\] attended by the employee.

# Rules:

* You may take input as a string or a number but must output as a string/alphabet (You may choose either lower or upper-case.)
* Standard loopholes apply.
* This is , so the shortest program in bytes wins!

# Test cases:

```
12  => F
15  => E
301 => A
181 => C

```

# Scoreboard:

```
var QUESTION_ID=142243,OVERRIDE_USER=8478;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){var F=function(a){return a.lang.replace(/<\/?a.*?>/g,"").toLowerCase()},el=F(e),sl=F(s);return el>sl?1:el<sl?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

# Answer
# Jelly,  ~~18 17 15~~  14 bytes

```
NịØAx“A©r½ɗÇ‘¤

```

A monadic link taking a number and returning a character.

**Try it online!** or see all input-output pairs.

### How?

```
NịØAx“A©r½ɗÇ‘¤ - Link: number, d
N              - negate d
             ¤ - nilad followed by link(s) as a nilad:
  ØA           -   uppercase alphabet yield = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
     “A©r½ɗÇ‘  -   code-page indices = [65,6,114,10,157,14]
    x          -   times = 'A'x65+'B'*6+'C'x114+'D'x10+'E'*157+'F'*14
 ị             - index into (1-indexed & modular - hence the negation to allow all Fs
                                                   to be together at one end)

```
> 4 votes

# Answer
# Javascript (ES6), 51 bytes

```
n=>"ABCDEF"[(n<14)+(n<171)+(n<181)+(n<295)+(n<301)]

```

## Alternative solutions (longer):

~~53~~ 52 bytes (-1 byte thanks to @Arnauld)

```
n=>"FEDCBA"[n>300?5:n>294?4:n>180?3:n>170?2:+(n>13)]

```

~~55~~ 53 bytes (-2 bytes thanks to @Neil)

```
n=>"AFEDCB"[[14,171,181,295,301].findIndex(m=>n<m)+1]

```

55 bytes

```
n=>"FEDCBA"[[13,170,180,294,300].filter(m=>n>m).length]

```

## Example code snippet:

```
f=
n=>"ABCDEF"[(n<14)+(n<171)+(n<181)+(n<295)+(n<301)]
console.log(f(12))
console.log(f(15))
console.log(f(301))
console.log(f(181))
```
> 12 votes

# Answer
# TI-Basic, 40 bytes

```
sub("FEDCBA",sum(Ans≥{0,14,171,181,295,301}),1

```
> 7 votes

# Answer
# , 31 bytes

```
'FEDCBA'{~13 170 180 294 300&I.

```

Try it online!

## Explanation

```
'FEDCBA'{~13 170 180 294 300&I.  Input: n
          13 170 180 294 300     Constant array [13, 170, 180, 294, 300]
                            &I.  Use it with interval index to find which of
                                 the intervals (-∞, 13], (13, 170], (170, 180],
                                 (180, 294], (294, 300], (300, ∞) n can be inserted at
        {~                       Index into
'FEDCBA'                         This string and return that char

```
> 6 votes

# Answer
# Python 3, 50 bytes

Thanks to @jferard for -4 bytes.

```
lambda n:chr(70-sum(n>ord(x)for x in"\rª´ĦĬ"))

```

Try it online!

# Python 3, 54 bytes

```
lambda n:chr(70-sum(n>x for x in[13,170,180,294,300]))

```

Try it online!

Saved 2 bytes thanks to @mathmandan, and indirectly thanks to @JonathanFrech.

# Python 2, 56 bytes

```
lambda n:"ABCDEF"[sum(n<x for x in[14,171,181,295,301])]

```

Try it online!
> 6 votes

# Answer
# C, ~~62~~ 61 bytes

*Thanks to @Jonathan Frech for saving a byte!*

```
f(n){putchar(70-(n<14?0:n<171?1:n<181?2:n<295?3:n<301?4:5));}

```

Try it online!

# C, 57 bytes

```
#define f(n)70-(n<14?0:n<171?1:n<181?2:n<295?3:n<301?4:5)

```

Try it online!

# C (gcc), 54 bytes

```
f(n){n=70-(n<14?0:n<171?1:n<181?2:n<295?3:n<301?4:5);}

```

Try it online!

# C (gcc), 50 bytes

*Using @Herman Lauenstein's solution.*

```
f(n){n=65+(n<14)+(n<171)+(n<181)+(n<295)+(n<301);}

```

Try it online!
> 4 votes

# Answer
# Japt, ~~23~~ 21 bytes

```
'Gc-[#ªT#´D294L*3]è<U

```

Try it

---

## Explantion

Implicit input of integer `U`.

```
'Gc-

```

Subtract from the codepoints of the (single character) string `G` ...

```
è<U

```

The count of elements less than `U` ...

```
[#ªT#´D294L*3]

```

In the array of 170 (), 0 (`T`), 180 (), 13 (`D`), 294 (literal) & 300 (`L*3`), so formatted and ordered to avoid the use of delimiting commas. `0` could be removed (subtracting from the codepoint of `F` instead) but then a comma would need to be added or `C*F` (12\*15) used for `180`, ultimately saving no bytes.
> 3 votes

# Answer
# , ~~50~~ 44 bytes

```
LETTERS[6-sum(scan()>c(13,170,180,294,300))]

```

Try it online!

same as the javascript answer, but uses R's vectorization and LETTERS builtin to come in a tiny bit shorter.

Thanks to rturnbull for shaving off those last 6 bytes.
> 3 votes

# Answer
# Kotlin, 56 bytes

```
{v->'F'-listOf(13,170,180,294,300).filter{it<v}.count()}

```

Try it online!

## Beautified

```
{ v->
    // Count the grades passed, then subtract that from F
    'F' - listOf(13,170,180,294,300)
            .filter { it < v }
            .count()
}

```

## Test

```
var x:(Int)->Char =
{v->'F'-listOf(13,170,180,294,300).filter{it<v}.count()}

fun main(args: Array<String>) {
    println(x(12))
    println(x(15))
    println(x(301))
    println(x(181))
}

```
> 3 votes

# Answer
# Python 2, 77 bytes

```
lambda n:chr(70-sorted(_*(n>(0,13,170,180,294,300)[_])for _ in range(6))[-1])

```

Try it online!
> 2 votes

# Answer
# Recursiva, ~~49~~ 30 bytes

```
Y(++++<a301<a295<a181<a171<a14

```

Try it online!

Allow me to answer my own question in my own language. :D

* saved 19 bytes by using technique from @Herman Lauenstein's amazing JS answer

# Explanation:

```
Y(++++<a301<a295<a181<a171<a14
      <a301<a295<a181<a171<a14 calculate true/false for all the conditions
  ++++                         sum up all the conditions to obtain n which can be either 0,1,2,3,4 or 5
 (                             yield upper-case Alphabet
Y                              Get n-th element

```
> 2 votes

# Answer
# Perl 5, 47 + 1 (-p) = 48 bytes

```
$_=((F)x14,(E)x157,(D)x10,(C)x114,(B)x6)[$_]||A

```

Try it online!
> 2 votes

# Answer
# Pyke, 28 bytes

```
G6<13T17*180T30*294]5FhQ>)s@

```

Try it here!

# Explanation

```
G6<13T17*180T30*294]5FhQ>)s@ - Full program. T is the constant for 10.

G                            - The lowercase alphabet.
 6<                          - With the letters after the index 6 trimmed.
   13                        - The literal 13.
     T17*                    - The integer 170, composed by 17 * 10, to save whitespace.
         180                 - The literal 180.
            T30*             - The integer 300, composed by 30 * 10.
                294          - The literal 294.
                   ]5        - Create a list of 5 elements.
                     FhQ>)   - For each element in the list.
                      h      - Increment.
                       Q     - The input.
                        >    - Is smaller ^^ than ^? Yields 1 for truthy and 0 for falsy.
                         )s  - Close loop and sum.
                           @ - Get the index in the alphabet substring explained above.

```
> 2 votes

# Answer
# Jelly, 19 bytes

```
“n-'‘+⁹;“ỌẠÇ‘ð>SịØA

```

Try it online!

Footer executes all test-cases and formats the output.
> 1 votes

# Answer
# Pyth, 30 bytes

```
@GtlfgTQmCdc"\r ª ´ & , m"d

```

The site doesn't seem to show the character with code point 1, so you need to insert a character with code point 1 before the `&`, `,`, and `m` at the end

(Replace all `1`s with character with code point 1):

```
@GtlfgTQmCdc"\r ª ´ 1& 1, 1m"d

```
> 1 votes

# Answer
# Pyth, 25  ~~26~~  bytes

```
@<G6sgRQ[13*17T180*30T294

```

**Verify all the test cases.**

# Explanation

```
@<G6sgRQ[13*17T180*30T294 - Full program.

  G                       - The lowercase alphabet.
 < 6                      - With the letters after the index 6 trimmed. We will call "S".
        [                 - Initialise a list literal.
         13               - The literal 13.
           *17T           - The integer 170, composed by 17 * 10, so save whitespace.
               180        - The literal 180.
                      294 - The literal 294.
                  *30T    - The integer 300, composed by 30 * 10.
     gRQ                  - For each element, return 1 if is is ≥ the input. 0 otherwise.
    s                     - Sum.
@                         - Get the index into S of ^.
                          - Output implicitly.

```
> 1 votes

# Answer
# Ly, 74 bytes

```
n(14)L["F"o;]p(171)L["E"o;]p(181)L["D"o;]p(195)L["C"o;]p(301)L["B"o;]"A"o;

```

Try it online!

A simple if-chain approach. I doubt it can be made much shorter.
> 1 votes

# Answer
# Bash, 55 bytes

```
echo obase=16\;10 $[$1<{14,171,181,295,301}]|tr \  +|bc

```

Try it online or Verify test cases.
> 1 votes

# Answer
# Java 8, 55 bytes

```
n->n<14?'F':n<171?'E':n<181?'D':n<295?'C':n<301?'B':'A'

```

Try it here.

Alternative **57 bytes**:

```
n->(char)(n<14?70:n<171?69:n<181?68:n<295?67:n<301?66:65)

```

Try it here.

Alternative **60 bytes**:

```
n->"FEDCBA".charAt(n<14?0:n<171?1:n<181?2:n<295?3:n<301?4:5)

```

Try it here.

Maybe some kind of formula can be find to get 0-5 in a shorter way than `n<14?0:n<171?1:n<181?2:n<295?3:n<301?4:5` using the last approach. Still investigating this.
> 1 votes

# Answer
# Excel, 53 bytes

Sum of conditions, then returns the required ASCII character:

```
=CHAR((A1<14)+(A1<171)+(A1<181)+(A1<295)+(A1<301)+65)

```

Alternative solutions:

Summing conditions, return string index (63 bytes):

```
=MID("ABCDEF",(A1<14)+(A1<171)+(A1<181)+(A1<295)+(A1<301)+1,1)

```
> 1 votes

# Answer
# PowerShell, 59 bytes

```
(,'F'*14+,'E'*157+,'D'*10+,'C'*114+,'B'*6+,'A'*65)["$args"]

```

Try it online!

Similar-ish to Jonathan Allen's Jelly answer, in that we're constructing an array of all the letters concatenated together, then indexing into that array with the input `$args`.
> 1 votes

# Answer
# Rabbit~, 50 bytes

(Noncompeting, postdates question. I just finished the interpreter(yay) and wanted to try and solve something. This is also my first code golf thing ever)

```
=>FEDCBA$<({.0-\_-^\-&^?n&&}_}\>\{{\>:.¤})Ð"ỤṅỌrḲA

```

It basically takes the differences from one grade to the next 14,157,10,114,6,65 (encoded as `ỤṅỌrḲA`) and subtracts from the input. If a negative number is found it stops progressing along the 'FEDCBA' sequence and outputs the letter.

### Small explanation of this beautiful piece of syntax

Rabbit~ uses a grid based memory with one or several carets you can move around; this solution uses 2.

```
=>FEDCBA$<({.0-\_-^\-&^?n&&}_}\>\{{\>:.¤})Ð"ỤṅỌrḲA - Full program.

  FEDCBA                                           - Load bytes into grid
                                          Ð"ỤṅỌrḲA - Load bytes 14,157,10,114,6,65 into second line of data grid
=                                                  - Read input
 >       <      _ ^   ^     _  >   >               - Move caret (most instructions read from the grid below the active caret)
        $                                          - Create a new caret
          (                              )         - Loop
           {.0             } }   {{     }          - Conditional statement checking if value at caret == 0 then move active caret to next grade else print and quit
              -  -  -                              - Subtract
               \   \          \ \                  - Cycle active caret
                     &   &&                        - Bitwise and to see if number is negative
                       ?n                          - Get negative sign bit
                                    :.             - Print value at caret as character
                                      ¤            - Terminate program

```
> 1 votes

# Answer
# Jotlin, ~~48~~ 41 bytes

```
{v->'F'-l(13,170,180,294,300).f{a<v}.l()}

```

Whole program:

```
var x:(Int)->Char =
{v->'F'-l(13,170,180,294,300).f{a<v}.l()}

println(x(12))
println(x(15))
println(x(301))
println(x(181))

```

Ported my previous Kotlin answer here.
> 1 votes

# Answer
# K (oK), 30 bytes

**Solution:**

```
"FEDCBA"@0 14 171 181 295 301'

```

Try it online!

**Explanation:**

Index into the correct bucket:

```
"FEDCBA"@0 14 171 181 295 301' / the solution
         0 14 171 181 295 301' / bin (') input in a bucket
"FEDCBA"@                      / index (@) into "FEDCBA"

```
> 1 votes

# Answer
# , 37 34 bytes

```
aFEDCBA5äh113äh9äh156äh13ähÀ|vyVp

```

Try it online!

Hexdump:

```
00000000: 3133 4146 1b31 3536 4145 1b39 4144 1b31  13AF.156AE.9AD.1
00000010: 3133 4143 1b35 4142 1b36 3441 411b eec0  13AC.5AB.64AA...
00000020: 7c76 7956 70                             |vyVp

```

Basic idea:

* Print `FEDCBA`, create 5 copies of B, 113 copies of C etc. resulting in the string `FFFFFFFFFFFFFEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEDDDDDDDDDCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCBBBBBA` (There is probably a more efficient way to do this)
* Go to `n`th column (`n` is the first argument), copy a single character and replace the entire string with it.
> 1 votes

# Answer
# 05AB1E, 19 bytes

```
•5r¥[‚=€®•3ô›_ASsÏ¤

```

Try it online!
> 1 votes

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

```
{chr(65+[+] "\rª´ĦĬ".ords »>»$_)}

```
> 1 votes

# Answer
# Stax, 18 bytes

```
5"«µħĭ",+|oH-VA@]

```

Run and debug online!

## Explanation

Bytes counted in CP437.

```
5"«µħĭ",+|oH-VA@]
5            -        5 minus the result of the following
 "«µħĭ"                   [14, 171, 181, 295, 301]
        ,+                Append input
          |oH             Index of last element if the array were to be sorted
              VA@]    Letter in the alphabet with the given index

```
> 1 votes

# Answer
# Excel, 49 bytes

`=MID("FEDCBA",MATCH(A1,{0;14;171;181;295;301}),1)`

just taking advantage of the MATCH function's default match type behaviour but i'm sure there's a shorter answer

if someone has more experience with excel, please comment any ways i can improve this answer!
> 1 votes

# Answer
# C#, 110 bytes

```
x=>{if(x<14)return"F";if(x<171)return"E";if(x<181)return"D";if(x<295)return"C";if(x<301)return"B";return"A";};

```

Try it online
> 0 votes

# Answer
# Thunno, 19 bytes

```
"\rª´ĦĬ"O>S70_C

```

Attempt This Online!

Uses the same method as quite a few other answers.

#### Explanation

```
"\rª´ĦĬ"O>S70_C    # Implicit input
"\rª´ĦĬ"O          # Push the list [13, 170, 180, 294, 300]
         >         # Check if the input is greater than these numbers
          S        # Sum the resulting list
           70_     # Subtract the sum from 70
              C    # And this codepoint into a character
                   # Implicit output

```
> 0 votes

---
Tags: code-golf, number, decision-problem, classification
---


title: What's the best die to roll?

text:
# Question
Title: What's the best die to roll?
The "standard" polyhedral game dice have 4, 6, 8, 10, 12 and 20 sides. (Yes, I know that there are two 10-sided dice which together make a d100, but we're ignoring that right now.)

If I want to generate a random number between 1 and \\$n\\$ where \\$n\\$ is not one of those sides, I have a couple of options.

One option is to pick a die with more sides than my maximum and just re-roll if the result is larger than I want. For example, if I want a number between 1 and 7, I can roll the 8-sided die: if it's between 1 and 7, that's great; if it's 8, I can just re-roll until it is between 1 and 7.

Re-rolling is a bit of a pain though, but if your number \\$n\\$ is a factor of one of the die's side counts, you can just double-count some of the faces. Specifically, if your number is \\$n\\$, you can choose an \\$(n\times m)\\$-sided die, roll it, and then take the result modulo \\$m\\$. For example, if you want to generate a number between 1 and 3, then you can roll a six-sided die: if the result is between 1 and 3, you are done; if it's greater than 3, just subtract 3 to get the result.

We can even use both at once! For example, if I want to generate a number from 1 to 9, I can use a 20-sided die to generate a number from 1 to 18 with Method 1. 18 is a multiple of 9, so I can use Method 2 to get a number from 1 to 9.

So there are multiple ways to roll certain numbers. How do we decide which is best? Well, I have a couple of criteria I use:

* First, I count the number of dead faces where we would have to re-roll. The method with fewer dead faces is better.
* If the dead faces are equal, then the method using the die with fewer faces is better.

# Task

Your task is to take a set of integers representing the polyhedral dice, and an integer representing the size of a range to generate a random int on (range from 1 to \\$n\\$).

You should output which polyhedral die in the input set has the best method as described above.

You may take the set in any reasonable format, including a strictly ascending or descending list. The size of the range will always be at most equal to the maximum of the set and at least 1.

This is , so the goal is to minimize the size of your source code as measured in bytes.

# Test cases

```
set = {4,6,8,10,12,20}
1 -> 4
2 -> 4
3 -> 6
4 -> 4
5 -> 10
6 -> 6
7 -> 8
8 -> 8
9 -> 10
10 -> 10
11 -> 12
12 -> 12
13 -> 20
14 -> 20
19 -> 20
20 -> 20
set = {12,16}
5 -> 16
set = {3,5}
2 -> 3

```

# Answer
> 6 votes
# , 9 bytes

```
0{]/:>,.|

```

Try it online!

* `]/:` Set of dice sorted by...
* `>,.|` 2 number list for each dice consisting of `<is dice less than the input>, <modulus>`. The first number will sort all dice that are too low to make the requested number after those that are big enough, and the 2nd number will prioritize those with fewer dead faces.
* `0{` Take the first.

# Answer
> 5 votes
# C (gcc), <sup>~~68~~ \\$\cdots\\$ ~~55~~</sup> 48 bytes

```
d;f(a,n)int*a;{d=*a?f(a+1,n)<n|*a%n<d%n?*a:d:0;}

```

Try it online!

*Saved ~~3~~ ~~7~~ 13 bytes thanks to a discussion with Peter Cordes!!!*
*Saved 7 bytes thanks to att!!!*

Inputs \\$n\\$ and a pointer to a zero-terminated (because pointers in C carry no length info) descendingly-sorted array of integers representing the dice.
Returns the best die for \\$n\\$.

# Answer
> 3 votes
# Python 3, ~~34~~ ~~56~~ ~~55~~ 40 bytes

```
lambda x,y:min((z<x,z%x,z)for z in y)[2]

```

Takes a strictly ascending list.

# Answer
> 3 votes
# 05AB1E, 7 bytes

```
@ÏΣ¹%}н

```

Try it online or verify all test cases.

**Explanation:**

```
@        # Check if the values in the second (implicit) input-list are >= the
         # first (implicit) input-integer
 Ï       # Only keep those values from the second (implicit) input-list
  Σ  }н  # Get the minimum by:
  Σ  }   #  Sort by,
      н  #  and pop and push the first element afterwards
   ¹%    #   Modulo the current value by the first input-integer
         # (after which the result is output implicitly)

```

# Answer
> 3 votes
# Jelly, 6 bytes

```
<;%ɗÞḢ

```

Try it online!

```
   ɗÞ       Sort by...
<             less than (return 0 if the set element is greater or equal to the range size)
 ;            concatenated with
  %           modulus.
     Ḣ      Get the first element.

```

The same algorithm as Jonah's answer in J.

# Answer
> 3 votes
# Coconut, 24 bytes

A curried function taking the integer first, then the set of dice.

```
x->min$(key=->(_<x,_%x))

```

Try it online!

# Answer
> 2 votes
# MATL, ~~12~~ 10 bytes

```
ti&\g/&X<)

```

Inputs are an ascending numerical vector and a number.

Try it online! Or verify all test cases.

### How it works

Consider inputs `[4,6,8,10,12,20]`, `5`.

```
ti     % Implict input. Duplicate, then take second input
       % STACK: [4 6 8 10 12 20], 5
&\     % Two-output modulus: gives modulus, then quotient
       % STACK: [4 6 8 10 12 20], [4 1 3 0 2 0], [0 1 1 2 2 4]
g      % Convert to logical
       % STACK: [4 6 8 10 12 20], [4 1 3 0 2 0], [0 1 1 1 1 1]
/      % Divide, element-wise
       % STACK: [4 6 8 10 12 20], [inf 1 3 0 2 0]
&X<    % Index (1-based) of first minimizing entry
       % STACK: [4 6 8 10 12 20], 4
)      % Use as index. Implicit display
       % STACK: 10

```

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

Expects `(list)(integer)`.

```
a=>n=>a.sort((x,y)=>x<n|-(y<n)||x%n-y%n||x-y)[0]

```

Try it online!

### Commented

```
a =>             // a[] = die list
n =>             // n = target integer
a.sort((x, y) => // for each pair (x, y) from a[] to be sorted:
  x < n |        //   move away x if it's less than n
  -(y < n)       //   move away y if it's less than n
                 //   (if both values are invalid, y is moved away
                 //   but it actually doesn't matter)
  ||             //   or:
  x % n - y % n  //   move away the value which is higher modulo n
  ||             //   or:
  x - y          //   move away the highest value
)[0]             // end of sort(); return the leading entry

```

---

# JavaScript (ES10), 47 bytes

This version was suggested by @KevinCruijssen. It assumes that the list is given in ascending order and that the sort is stable (which used to depend on the implementation but is a requirement since ECMAScript 2019).

Expects `(list)(integer)`.

```
a=>n=>a.filter(v=>v>=n).sort((x,y)=>x%n-y%n)[0]

```

Try it online!

# Answer
> 2 votes
# , ~~67~~ ~~33~~ 27 bytes

```
\(s,n)s[order(s<n,s%%n)[1]]
```

Attempt This Online!

Change of approach after looking at other answers.

# Answer
> 2 votes
# Factor, 48 bytes

```
[| s n | s [ n < ] reject [ n mod ] infimum-by ]

```

Attempt This Online!

* `s [ n < ] reject` Remove elements of the set that are less than n.
* `[ n mod ] infimum-by` Find the element that is smallest modulo n.

# Answer
> 2 votes
# Wolfram Language (Mathematica), 32 bytes

```
nFirst@*SortBy[n>#||#~Mod~n&]

```

Try it online!

# Answer
> 2 votes
# Vyxal, 7 bytes

```
µ⁰₍<%;h

```

Try it Online!

## How?

```
µ⁰₍<%;h
µ    ;  # Sort by:
 ⁰      #   Push second input
  ₍     #   Apply both of the next two commands, and wrap the results into a list:
   <    #     Less than...
    %   #     And modulo
        #   This would produce [a < b, a % b], where a is the current item and b is the second input.
      h # First element (this is acting as a minimum-by)

```

# Answer
> 1 votes
# Retina 0.8.2, ~~65~~ 42 bytes

```
\d+
$*
sO^$`¶(?<=^(1+).+?)\1+(1*)
$2
r`1\G

```

Try it online! Takes input on separate lines, but link is to test suite that splits on comma for convenience. Target value comes first followed by the list of dice in ascending order. Explanation:

```
\d+
$*

```

Convert to unary.

```
sO^$`¶(?<=^(1+).+?)\1+(1*)
$2

```

Sort the dice that are as least as large as the target value in order of their remainder when divided by the target value, then reverse the list of those dice so that the desired die is at the very end. (Dice that are too small remain at the start of the list.)

```
r`1\G

```

Convert the desired die to decimal.

# Answer
> 1 votes
# Charcoal, 19 bytes

```
≔Φη¬‹ιθηＩ§η⌕﹪ηθ⌊﹪ηθ

```

Try it online! Link is to verbose version of code. Takes the list of dice in ascending order. Explanation:

```
≔Φη¬‹ιθη

```

Remove dice that are too small.

```
Ｉ§η⌕﹪ηθ⌊﹪ηθ

```

Output the first die with the smallest remainder.

# Answer
> 1 votes
# Pyth, ~~10~~ 8 bytes

```
ho%NQ-EU

```

Try it online!

Accepts an integer and an ascending list on separate lines of STDIN

```
     -EU  # Remove all elements in the range 0 to (input integer) from the input list
 o%NQ     # Order by (element) modulo (input integer)
h         # Take the first element

```

The sort should be stable since it's implemented using Python's `sorted` method.

# Answer
> 1 votes
# Desmos, 41 bytes

```
f(l,n)=L[A=A.min][1]
L=l[l>=n]
A=mod(L,n)

```

Surprisingly golfy

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 0 votes
# PARI/GP, 40 bytes

```
f(s,i)=vecsort([[d<i,d%i,d]|d<-s])[1][3]
```

Attempt This Online!

# Answer
> 0 votes
# Zsh, 60 bytes

```
D=`<&0`
for d;for ((i=D;i<=d;i+=D))a[1+d-i]=$d
<<<${${a}[1]}

```

Try it online!

Takes possible dice as a strictly descending list of arguments, takes our target die on stdin.

```
D=`<&0`                     # read in our goal $D
for d;                      # for every possible die (pre-sorted descending)
    for ((i=D;i<=d;i+=D))   # for each multiple of our goal up to the die size
        a[1 + d - i]=$d     # save the die size to a[1 + num_dead_faces]
<<<${${a}[1]}               # output the first non-empty element

```

# Answer
> 0 votes
# Arturo, 32 bytes

```
$[s,n]->minimum--s@0..n-1=>[&%n]

```

Try it

---
Tags: code-golf, number-theory, random
---


title: Build a Compiler Bomb

text:
# Question
Title: Build a Compiler Bomb
# Introduction

You're probably familiar with zip bombs, XML bombs, etc. Put simply, they are (relatively) small files which produce enormous output when interpreted by naïve software. The challenge here is to abuse a compiler in the same way.

# Challenge

Write some source code which occupies 512 bytes or less and which compiles into a file which occupies the most possible space. Largest output file wins!

# Rules

OK, so there are a few important clarifications, definitions and restrictions;

* The output of the compilation must be an ELF file, a Windows Portable Executable (.exe), or virtual bytecode for the JVM or .Net's CLR (other types of virtual bytecode are also likely to be OK if asked for). **Update: Python's .pyc / .pyo output also counts**.
* If your language-of-choice can't be compiled directly into one of those formats, transpilation followed by compilation is also allowed (**Update: you can transpile multiple times, just so long as you never use the same language more than once**).
* Your source code can consist of multiple files, and even resource files, but the summed size of all these files must not exceed 512 bytes.
* You cannot use any other input than your source file(s) and the standard library of your language-of-choice. Static linking standard libraries is OK when it's supported. Specifically, no third party libraries or OS libraries.
* It must be possible to invoke your compilation using a command or series of commands. If you require specific flags when compiling, these *count towards your byte limit* (e.g. if your compile line is `gcc bomb.c -o bomb -O3 -lm`, the `-O3 -lm` part (7 bytes) will be counted (note the initial leading space isn't counted).
* Preprocessors are permitted *only if* they are a standard compilation option for your language.
* The environment is up to you, but in the interests of making this verifiable, please stick to recent (i.e. available) compiler versions and operating systems (and obviously specify which you're using).
* It must compile without errors (warnings are OK), and crashing the compiler doesn't count for anything.
* What your program actually *does* is irrelevant, though it can't be anything malicious. It doesn't even have to be able to start.

# Example 1

The C program

```
main(){return 1;}

```

Compiled with `Apple LLVM version 7.0.2 (clang-700.1.81)` on OS X 10.11 (64-bit):

```
clang bomb.c -o bomb -pg

```

Produces a file of 9228 bytes. The total source size is 17+3 (for the `-pg`) = 20 bytes, which is easily within size limit.

# Example 2

The Brainfuck program:

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

```

Transpiled with awib to c with:

```
./awib < bomb.bf > bomb.c

```

Then compiled with `Apple LLVM version 7.0.2 (clang-700.1.81)` on OS X 10.11 (64-bit):

```
clang bomb.c

```

Produces a file of 8464 bytes. The total input here is 143 bytes (since `@lang_c` is the default for awib it didn't need to be added to the source file, and there are no special flags on either command).

Also note that in this case, the temporary bomb.c file is 802 bytes, but this counts towards neither the source size nor the output size.

# Final Note

If an output of more than 4GB is achieved (perhaps if somebody finds a turing complete preprocessor), the competition will be for the *smallest source* which produces a file of at least that size (it's just not practical to test submissions which get *too* big).

# Answer
# C, (14 + 15) = 29 byte source, 17,179,875,837 (16 GB) byte executable

Thanks to @viraptor for 6 bytes off.

Thanks to @hvd for 2 bytes off and executable size x4.

This defines the `main` function as a large array and initialises its first element. This causes GCC to store the entire array in the resulting executable.

Because this array is bigger than 2GB, we need to provide the `-mcmodel=medium` flag to GCC. The extra 15 bytes are included in the score, as per the rules.

```
main[-1u]={1};

```

Don't expect this code to do anything nice when run.

Compile with:

```
gcc -mcmodel=medium cbomb.c -o cbomb

```

---

It took me a while to get round to testing @hvd's suggestion - and to find a machine with enough juice to handle it. Eventually I found a old non-production RedHat 5.6 VM with 10GB RAM, 12GB swap, and /tmp set to a large local partition. GCC version is 4.1.2. Total compile time about 27 minutes.

> **Due to the CPU and RAM load, I recommend against doing this compile on any remotely production-related machine**.
> 502 votes

# Answer
# Python 3, 13 byte source, 9,057,900,463 byte (8.5GiB) .pyc-file

```
(1<<19**8,)*2

```

**Edit**: Changed the code to the version above after I realized the rules say output size beyond 4GiB doesn't matter, and the code for this one is ever so slightly shorter; The previous code - and more importantly the explanation - can be found below.

---

# Python 3, 16 byte source, \>32TB .pyc-file (if you have enough memory, disk space and patience)

```
(1<<19**8,)*4**7

```

Explanation: Python 3 does constant folding, and you get big numbers fast with exponentation. The format used by .pyc files stores the length of the integer representation using 4 bytes, though, and in reality the limit seems to be more like `2**31`, so using just exponentation to generate one big number, the limit seems to be generating a 2GB .pyc file from an 8 byte source. (`19**8` is a bit shy of `8*2**31`, so `1<<19**8` has a binary representation just under 2GB; the multiplication by eight is because we want bytes, not bits)

However, tuples are also immutable and multiplying a tuple is also constant folded, so we can duplicate that 2GB blob as many times as we want, up to at least `2**31` times, probably. The `4**7` to get to 32TB was chosen just because it was the first exponent I could find that beat the previous 16TB answer.

Unfortunately, with the memory I have on my own computer, I could test this only up to a multiplier of 2, ie. `(1<<19**8,)*2`, which generated a 8.5GB file, which I hope demonstrates that the answer is realistic (ie. the file size isn't limited to 2\**32=4GB).

Also, I have no idea why the file size I got when testing was 8.5GB instead of the 4GB-ish I expected, and the file is big enough that I don't feel like poking around it at the moment.
> 226 votes

# Answer
# C#, about 1 min to compile, 28MB output binary:

```
class X<A,B,C,D,E>{class Y:X<Y,Y,Y,Y,Y>{Y.Y.Y.Y.Y.Y.Y.Y.Y y;}}

```

Adding more Y's will increase the size exponentially.

An explanation by Pharap as per @Odomontois' request:

This answer is abusing inheritance and type parameters to create recursion. To understand what's happening, it's easier to first simplify the problem. Consider `class X<A> { class Y : X<Y> { Y y; } }`, which generates the generic class `X<A>`, which has an inner class `Y`. `X<A>.Y` inherits `X<Y>`, hence `X<A>.Y` also has an inner class `Y`, which is then `X<A>.Y.Y`. This then also has an inner class `Y`, and that inner class `Y` has an inner class `Y` etc. This means that you can use scope resolution (`.`) ad infinitum, and every time you use it, the compiler has to deduce another level of inheritance and type parameterisation.

By adding additional type parameters, the work the compiler has to do at each stage is further increased.

Consider the following cases:
In `class X<A> { class Y : X<Y> { Y y;} }` type param `A` has a type of `X<A>.Y`.
In `class X<A> { class Y : X<Y> { Y.Y y;} }` type param `A` has a type of `X<X<A>.Y>.Y`.
In `class X<A> { class Y : X<Y> { Y.Y.Y y;} }` type param `A` has a type of `X<X<X<A>.Y>.Y>.Y`.
In `class X<A,B> { class Y : X<Y,Y> { Y y;} }` type param `A` is `X<A,B>.Y` and `B` is `X<A,B>.Y`.
In `class X<A> { class Y : X<Y> { Y.Y y;} }` type param `A` is `X<X<A,B>.Y, X<A,B>.Y>.Y` and `B` is `X<X<A,B>.Y, X<A,B>.Y>.Y`.
In `class X<A> { class Y : X<Y> { Y.Y.Y y;} }` type param `A` is `X<X<X<A,B>.Y, X<A,B>.Y>.Y, X<X<A,B>.Y, X<A,B>.Y>.Y>.Y` and `B` is `X<X<X<A,B>.Y, X<A,B>.Y>.Y, X<X<A,B>.Y, X<A,B>.Y>.Y>.Y`.

Following this pattern, one can only imagine1 the work the compiler would have to do to to deduce what `A` to `E` are in `Y.Y.Y.Y.Y.Y.Y.Y.Y` in the definition `class X<A,B,C,D,E>{class Y:X<Y,Y,Y,Y,Y>{Y.Y.Y.Y.Y.Y.Y.Y.Y y;}}`.

1 You could figure it out, but you'd need a lot of patience, and intellisense won't help you out here.
> 222 votes

# Answer
> If an output of more than 4GB is achieved (perhaps if somebody finds a turing complete preprocessor), the competition will be for the smallest source which produces a file of at least that size (it's just not practical to test submissions which get too big).

"Template Haskell" allows Haskell code to be generated at compile-time using Haskell, and is hence a turing complete pre-processor.

Here's my attempt, parameterised by an arbitrary numerical expression `FOO`:

```
import Language.Haskell.TH;main=print $(ListE .replicate FOO<$>[|0|])

```

The magic is the code inside the "splice" `$(...)`. This will be executed at compile time, to generate a Haskell AST, which is grafted on to the program's AST in place of the splice.

In this case, we make a simple AST representing the literal `0`, we replicate this `FOO` times to make a list, then we use `ListE` from the `Language.Haskell.TH` module to turn this list of ASTs into one big AST, representing the literal `[0, 0, 0, 0, 0, ...]`.

The resulting program is equivalent to `main = print [0, 0, 0, ...]` with `FOO` repetitions of `0`.

To compile to ELF:

```
$ ghc -XTemplateHaskell big.hs
[1 of 1] Compiling Main             ( big.hs, big.o )
Linking big ...
$ file big
big: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /nix/store/mibabdfiaznqaxqiy4bqhj3m9gaj45km-glibc-2.21/lib/ld-linux.so.2, for GNU/Linux 2.6.32, not stripped

```

This weighs in at 83 bytes (66 for the Haskell code and 17 for the `-XTemplateHaskell` argument), plus the length of `FOO`.

We can avoid the compiler argument and just compile with `ghc`, but we have to put `{-# LANGUAGE TemplateHaskell#-}` at the beginning, which bumps the code up to 97 bytes.

Here are a few example expressions for `FOO`, and the size of the resulting binary:

```
FOO         FOO size    Total size    Binary size
-------------------------------------------------
(2^10)      6B          89B           1.1MB
(2^15)      6B          89B           3.6MB
(2^17)      6B          89B           12MB
(2^18)      6B          89B           23MB
(2^19)      6B          89B           44MB

```

I ran out of RAM compiling with `(2^20)`.

We can also make an infinite list, using `repeat` instead of `replicate FOO`, but that prevents the compiler from halting ;)
> 145 votes

# Answer
# C++, 250 + 26 = 276 bytes

```
template<int A,int B>struct a{static const int n;};
template<int A,int B>const int a<A,B>::n=a<A-1,a<A,B-1>::n>::n;
template<int A>struct a<A,0>{static const int n=a<A-1,1>::n;};
template<int B>struct a<0,B>{static const int n=B+1;};
int h=a<4,2>::n;

```

This is the Ackermann function implemented in templates. I'm not able to compile with `h=a<4,2>::n;` on my little (6GB) machine, but I did manage `h=a<3,14>` for a 26M output file. You can tune the constants to hit your platform's limits - see the linked Wikipedia article for guidance.

Requires `-g` flag to GCC (because it's all the debug symbols that actually consume any space), and a larger-than-default template depth. My compile line ended up as

```
g++ -ftemplate-depth=999999 -g -c -o 69189.o 69189.cpp

```

### Platform information

```
g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
Linux 3.13.0-46-generic #79-Ubuntu SMP x86_64 GNU/Linux

```
> 92 votes

# Answer
Here's my C answer from 2005. Would produce a 16TB binary if you had 16TB RAM (you don't).

```
struct indblock{
   uint32_t blocks[4096];
};

struct dindblock {
    struct indblock blocks[4096];
};

struct tindblock {
    struct dindblock blocks[4096];
};

struct inode {
    char data[52]; /* not bothering to retype the details */
    struct indblock ind;
    struct dindblock dint;
    struct tindblock tind;
};

struct inode bbtinode;

int main(){}

```
> 68 votes

# Answer
# ASM, 61 bytes (29 bytes source, 32 bytes for flags), 4,294,975,320 bytes executable

```
.globl main
main:
.zero 1<<32

```

Compile with `gcc the_file.s -mcmodel=large -Wl,-fuse-ld=gold`
> 67 votes

# Answer
# Plain old C preprocessor: 214 bytes input, 5MB output

Inspired by my real-world preprocessor fail here.

```
#define A B+B+B+B+B+B+B+B+B+B
#define B C+C+C+C+C+C+C+C+C+C
#define C D+D+D+D+D+D+D+D+D+D
#define D E+E+E+E+E+E+E+E+E+E
#define E F+F+F+F+F+F+F+F+F+F
#define F x+x+x+x+x+x+x+x+x+x

int main(void) { int x, y = A; }

```

Experiments show that each level of `#define`s will (as expected) make the output approximately ten times larger. But since this example took more than an hour to compile, I never went on to "G".
> 34 votes

# Answer
# Java, 450 + 22 = 472 bytes source, ~1GB class file

## B.java (golfed version, warning during compilation)

```
import javax.annotation.processing.*;@SupportedAnnotationTypes("java.lang.Override")public class B extends AbstractProcessor{@Override public boolean process(java.util.Set a,RoundEnvironment r){if(a.size()>0){try(java.io.Writer w=processingEnv.getFiler().createSourceFile("C").openWriter()){w.write("class C{int ");for(int i=0;i<16380;++i){for(int j=0;j<65500;++j){w.write("i");}w.write(i+";int ");}w.write("i;}");}catch(Exception e){}}return true;}}

```

## B.java (ungolfed version)

```
import java.io.Writer;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.TypeElement;

@SupportedAnnotationTypes("java.lang.Override")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class B extends AbstractProcessor {
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        if (annotations.size() > 0) {
            try (Writer writer = processingEnv.getFiler().createSourceFile("C").openWriter()) {
                writer.write("class C{int ");
                for (int i = 0; i < 16380; ++i) {
                    for (int j = 0; j < 65500; ++j) {
                        writer.write("i");
                    }
                    writer.write(i + ";int ");
                }
                writer.write("i;}");
            } catch (Exception e) {
            }
        }
        return true;
    }
}

```

## Compilation

```
javac B.java
javac -J-Xmx16G -processor B B.java

```

## Explanation

This bomb uses Annotation Processors. It needs 2 compile passes. The first pass builds the processor class `B`. During the second pass the processor creates a new source file `C.java`, and compiles it to a `C.class` with a size of `1,073,141,162` bytes.

There are several limitations when trying to create a big class file:

* Creating identifiers longer than about 64k results in: `error: UTF8 representation for string "iiiiiiiiiiiiiiiiiiii..." is too long for the constant pool`.
* Creating more than about 64k variables/functions results in: `error: too many constants`
* There is also a limit of about 64k for the code size of a function.
* There seems to be a general limit (bug?) in the java compiler of about 1GB for the `.class` file. If I increase `16380` to `16390` in the above code the compiler never returns.
* There is also a limit of about 1GB for the `.java` file. Increasing `16380` to `16400` in the above code results in: `An exception has occurred in the compiler (1.8.0_66). Please file a bug ...` followed by a `java.lang.IllegalArgumentException`.
> 30 votes

# Answer
## C, 26 byte source, 2,139,103,367 byte output, valid program

```
const main[255<<21]={195};

```

Compiled using: `gcc cbomb.c -o cbomb` (gcc version 4.6.3, Ubuntu 12.04, ~77 seconds)

I thought I'd try to see how large I could make a valid program without using any command line options. I got the idea from this answer: https://codegolf.stackexchange.com/a/69193/44946 by Digital Trauma. See the comments there as to why this compiles.

How it works: The `const` removes the write flag from the pages in the segment, so main can be executed. The `195` is the Intel machine code for a return. And since the Intel architecture is little-endian, this is the first byte. The program will exit with whatever the start up code put in the eax register, likely 0.

It's only about 2 gig because the linker is using 32 bit signed values for offsets. It's 8 meg smaller than 2 gig because the compiler/linker needs some space to work and this is the largest I could get it without linker errors - ymmv.
> 28 votes

# Answer
# Boo, 71 bytes. Compile time: 9 minutes. 134,222,236 byte executable

```
macro R(e as int):
 for i in range(2**e):yield R.Body
x = 0
R 25:++x

```

Uses a macro `R` (for Repeat) to cause the compiler to multiply the increment statement an arbitrary number of times. No special compiler flags are needed; simply save the file as `bomb.boo` and invoke the compiler with `booc bomb.boo` to build it.
> 22 votes

# Answer
# Kotlin, 90 bytes source, 177416 bytes (173 KB) compiled JVM binary

```
inline fun a(x:(Int)->Any){x(0);x(1)}
fun b()=a{a{a{a{a{a{a{a{a{a{a{println(it)}}}}}}}}}}}

```

Technically, you could make this even longer by nesting the expression further. However, the compiler crashes with a `StackOverflow` error if you increase the recursion.
> 18 votes

# Answer
# C++, 214 bytes (no special compile options needed)

```
#define Z struct X
#define T template<int N
T,int M=N>Z;struct Y{static int f(){return 0;}};T>Z<N,0>:Y{};T>Z<0,N>:Y{};T,int M>Z{static int f(){static int x[99999]={X<N-1,M>::f()+X<N,M-1>::f()};}};int x=X<80>::f();

```

It's a fairly straightforward two-dimensional template recursion (recursion depth goes as the square-root of total templates emitted, so won't exceed platform limits), with a small amount of static data in each one.

Generated object file with `g++ 4.9.3 x86_64-pc-cygwin` is 2567355421 bytes (2.4GiB).

Increasing the initial value above 80 breaks the cygwin gcc assembler (too many segments).

Also, `99999` can be replaced by `9<<19` or similar for increased size without changing the source code... but I don't think I need to use any more disk space than I already am ;)
> 16 votes

# Answer
# Scala - 70 byte source, 22980842 byte result (after jar)

```
import scala.{specialized => s}
class X[@s A, @s B, @s C, @s D, @s E]

```

This produces 95 (about 59,000) specialized class files, which pack into a jar of about 23 MB. You can in principle keep going if you have a filesystem that can handle that many files and enough memory.

(If the jar command must be included, it's 82 bytes.)
> 7 votes

# Answer
## C, 284 bytes + 2 for the `-c` in `gcc bomb.c -o bomb.o -c`; output: 2 147 484 052 bytes

```
#define a 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
#define b a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a
#define c b,b,b,b,b,b,b,b,b,b,b,b,b,b,b,b
#define d c,c,c,c,c,c,c,c,c,c,c,c,c,c,c,c
#define e d,d,d,d,d,d,d,d,d,d,d,d,d,d,d,d
#define f e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e
__int128 x[]={f,f,f,f,f,f,f,f};

```
> 5 votes

# Answer
# Swift for wasm, 7 byte source, 6326162 byte (6.3MB) wasm file

Not winning, but I'm adding this answer for its sheer absurdity:

```
print()

```

The Swift compiler does almost no dead code stripping (at least when compiling for wasm), so you get the entire standard library. The arguments to the print statement, any loops or recursion I added, etc barely seemed to matter. However, removing the print statement entirely shrunk the code size by a noticeable amount.

For reference, I used the wasm file generated by https://swiftwasm.org/, which seems to be using Swift 5.6 at the time of writing.
> 5 votes

# Answer
# C, 54 bytes, ridiculously large executable

```
#include <inttypes.h>
uint64_t main[(uint64_t)~0]={~0};

```

Not exactly *original*, but much more devastating.

### Inline but not portable version

```
unsigned long long main[~0ull]={~0};

```

I am NOT going to sacrifice my laptop just for this.

### Explanation

`uint64_t`, `unsigned long long`, they're both unsigned 64-bit integers.
The tilde (`~`) is the bitwise NOT operator in C (it flips the bits of a value).
`(uint64_t)0` is `0000000000000000000000000000000000000000000000000000000000000000` in binary.
By applying the bitwise NOT operator, we get a... big number (\\$2^{64}-1\\$).

### Credits

Big thanks to user Digital Trauma for his original implementation. This answer is really just an expansion from that.
> 4 votes

# Answer
# Julia, 22 bytes (in memory)

```
0:9^9 .|>i->@eval 2^$i

```

Try it online!

It's quite easy to make a compilation bomb in Julia, it can easily happen accidentally. Here we use the fact that `a^i` has some trickery when `i` is a litteral integer, that allows `a^2` to be turned into `a*a`, and `a^-1` into `inv(a)`. It means that there is a new compiled method of `litteral_pow` being compiled for each `i`. I'm pretty sure this would be at least 4GB but I don't know how to check it. This is only compiled in memory and not saved in a file though

# Julia, 114 bytes (output in a `.ji` file)

```
using Pkg
pkg"generate A"
write("A/src/A.jl","module A
!(::Val{x}) where x=x
.!Val.(1:9^9)end")
pkg"dev A"
using A

```

(can't) Try it online! Try `A` online!

To save compiled code to a file, the function must be in a package, therefore we create a package `A` that has the culprit (the function `!`). `Val(i)` is of type `Val{i}`, so a new method is compiled for each `i`. The output file will be in `~/.julia/compiled/<version>/A/xxx.ji` In my testing, each additional method adds at least 150 bytes (and growing, 182MB for 1M methods), which means 25M would be enough

in Julia 1.7, +2 bytes because `pkg"dev ./A"` is needed

# Julia, 117 bytes (without writing files)

this is basically the same as the above, but with the files already there. This is slightly longer because of the uuid needed in `Project.toml` (this is taken care of in `pkg"generate A"`)

**file structure**

```
A
├── src
│   └── A.jl
├── Project.toml
└── a.jl

```

**Project.toml**, 52 bytes

```
name="A"
uuid="8945f399-ba5e-44d3-9e17-ab2f7e467331"

```

**src/A.jl**, 47 bytes

```
module A
!(::Val{x}) where x=x
.!Val.(0:9^9)end

```

Try it online!

**a.jl**, 7 bytes

```
using A

```

**command line options** (in the `A` folder), +11 bytes

```
julia --project=. a.jl

```
> 4 votes

# Answer
# Myxal 0.7.1, 46 source bytes + 2 bytes flag = 48 bytes, 2.042 MB compiled

```
~~~~~~~y¢aaaa¢bbbb¢cccc¢dddd¢eeee¢ffff¢gggg¢hh

```

Simple node alias recursion bomb. Adding more aliases make the JVM complain of a too large main method.

```
~~~~~~~y # A bunch of filter modifiers on the element 'y'
¢a       # Alias that to 'a'
aaa¢b    # 3 'a's = 'b' and so on...
bbb¢c
ccc¢d
ddd¢e
eee¢f
fff¢g
ggg¢h
h        # Run that final 'h'

```

Compiled with the `-O` flag to disable optimization, which also disables shrinking for some reason.
> 4 votes

# Answer
# Boo, way more than you can expect from this

```
macro R(e as int):for i in range(9**e):yield R.Body
x = 0
R 99:++x

```
> 3 votes

# Answer
# Rust, 42 bytes, 1.31 GB executable

```
fn main(){print!("{:?}",[0u8;9999999999])}

```

Does not require any specific compilation flags, you can just compile with `rustc cbomb.rs`.
Arrays of the format `[x; s]` where `x` is `Copy` and `s` has type `usize` and both have a value known at compile time are constructed during compilation and embedded in the binary, though the final executable is smaller than I would expect from this and I do not know what mechanism does that.
I couldn't make the size much larger than this on my laptop without LLVM or the linker crashing from non-language limitations.

# Rust, 42 bytes, 18(?) EB executable (on a 64-bit system)

```
fn main(){print!("{:?}",[0u8;usize::MAX])}

```

The array would have a size of 18 EB, but the final executable would probably be smaller. I can't afford this much RAM and storage space, so I haven't been able to test this. Maybe you can if you are in the future.
> 3 votes

# Answer
PHP 7.1:

```
const X="x",Y=X.X.X.X.X.X.X.X,Z=Y.Y.Y.Y.Y.Y.Y.Y,A=Z.Z.Z.Z.Z.Z.Z.Z,B=A.A.A.A.A.A.A.A,C=B.B.B.B.B.B.B.B,D=C.C.C.C.C.C.C.C,E=D.D.D.D.D.D.D.D,F=E.E.E.E.E.E.E.E,G=F.F.F.F.F.F.F.F;

```

`.` is the concatenation operator, and PHP's compiler will try to do constant folding where possible, so it will construct a huge string and store it in PHP's internal bytecode. (I think you can get this written to a file with newer versions.) This is only as efficient as a classic XML entity bomb unfortunately. You'd need a few more repetitions to get to the gigabyte range.

The interesting part is that by default the worst that'll happen is seeing an error like:

```
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 50331680 bytes) in Command line code on line 1

```

PHP's web-orientedness means it has a memory limit by default!
> 2 votes

# Answer
**Dlang** (ldc compiler)

command to build `ldc -c t.d`

GBS is count of gigabytes;

code of t.d:

```
import std;
enum GBS = 1;
void main(){
    static foreach(i; 0..2* GBS){
        mixin(text(q{static immutable a}, i,q{ = uint.max.BigInt << uint.max;}));
        mixin(text(q{a}, i, q{.writeln;}));
    }
}

```
> 2 votes

---
Tags: code-challenge, busy-beaver, compile-time
---


title: Friend, or Foe?

text:
# Question
Title: Friend, or Foe?
## Task

Provide two programs/functions `A` and `B` (not necessarily in the same language) with the following properties:

* Either program, when given its own source code as input, produces an accepting output.
* Either program, when given the *other* program's source code as input, produces a rejecting output.

It doesn't matter what happens when you provide either program with an input that is not `A` or `B`. Accepting or rejecting is defined as per here:

* output truthy/falsy using your language's convention (swapping is allowed), or
* use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.

Both programs must use the same method of output. Additionally, if you use truthy/falsy and they are swapped for one program, they must be swapped for both programs.

If you decide to write a function instead of a full program, you must do so for both programs.

## Scoring

Your score is the sum of the byte counts of both programs. This is code golf, so the lowest score wins.

# Answer
> 12 votes
# Jelly, 1 byte

##### Program A, 1 byte

##### Program B, 0 bytes

##### Outputs

Falsy = accepting; truthy = rejecting

##### Explanation

* The string  (program A) is truthy as it is a non-empty string
* The string  (program B) is falsy as it is an empty string
* In Jelly, an empty program just outputs exactly what was input. So program B produces a truthy output when program A is inputted, and a falsy output when it is given itself as input
* In Jelly,  is the logical NOT operator. It outputs a falsy output (`0`) when a truthy input is given, but a truthy output (`1`) when a falsy input is given. Therefore, it produces a falsy output when given itself as input, and a truthy output when program B is inputted

# Answer
> 10 votes
# APL (Dyalog Unicode), ~~10~~ ~~7~~ 6 bytes

Anonymous tacit prefix functions, returning  for true and  for false.

### A: `⊣/⊢`

is an identity function, and returns the given source as-is

`⊣/` returns the leftmost character (lit. left-identity reduction), i.e.  when given A's source and  when given B's source.

### B: `⊢/⊣`

is an identity function, and returns the given source as-is

`⊢/` returns the rightmost character (lit. right-identity reduction), i.e.  when given A's source and  when given B's source.

Try it online!

# Answer
> 9 votes
# Retina 0.8.2, 2 bytes

Program A:

```
A

```

Program B:

```
B

```

Explanation: Each program counts the number of `A`s or `B`s in the input respectively, which will be truthy for itself and falsy for the other program.

# Answer
> 5 votes
# Pip, ~~6~~ 5 bytes

* -1 thanks to DLosc

Outputs 0 for truthy and 1 for falsy.

### Program A, 2 bytes

```
+q

```

### Program B, 3 bytes

```
1-q

```

### Test cases

### Explanation

`+q` forces the input into an integer. `+q` evaluates to 0, and `1-q` evaluates to 1.

`1-q` subtracts the input from 1, once again forcing it into an integer. `+q` will therefore be 1, and `1-q` will therefore be 0.

# Answer
> 4 votes
# Python 2, 16 + 15 = ~~49~~ ~~46~~ ~~44~~ ~~40~~ 31 bytes

crossed out 44 is still regular 44 :(

I don't think there's a optimal way to golf this.

`-1` for Truthy, `0` for Falsy

## Program A

```
0
print~-input()

```

Input A

Input B

## Program B

```
1
print-input()

```

Input A

Input B

-2 bytes thanks to Jiři

-9 thanks to tsh by changing the version.

# Answer
> 4 votes
# , ~~26~~ 24 bytes

### Program A, 12 bytes

```
\(x)x<"\\(y"

```

Attempt This Online!

### Program B, 12 bytes

```
\(z)z>"\\(y"

```

Attempt This Online!

Two anonymous functions differing by the name of the variable. We then check whether the function text (essentially the variable name) is smaller or bigger (lexicographically) than the beginning of the function (`\` escaped and `(`) with `y` appended.

# Answer
> 3 votes
# JavaScript (ES6), 2x7 = 14 bytes

Both functions return a Boolean value.

A: `s=>s>{}`

B: `S=>S<{}`

Try it online!

# Answer
> 3 votes
# Vyxal, 4 bytes

### Program A, 2 bytes

```
0c

```

### Program B, 2 bytes

```
1c

```

### Test cases

### Explanation

`0c` checks whether `0` is in the input, and `1c` checks whether `1` is in the input.

# Answer
> 3 votes
# Zsh, 6 + 6 = 12 bytes

```
grep A

```

Attempt This Online!

```
grep B

```

Attempt This Online!

Output is via exit code.

# Answer
> 3 votes
# \>\<\>, 10 bytes

```
0"i=n;

```

And

```
1io;

```

Try it

## Explanation

First we push a 0 or a 1. This is useless, but identifies the programs.

Then we push the string `"0=n;0"` (because strings wrap around). This means the `0` or `1` character code will be the last character on the stack.

We get the first character of the output program, and print if they are equal we print 1, otherwise 0.

The second program is similar except we can just print the first character of the first program so we can skip the `=` to save 1 byte.

# Answer
> 3 votes
# Motorola MC14500B Machine Code, 3 bytes

Outputs `0` for truthy and `1` for falsy.

### Program A, 1.5 bytes

```
118

```

Disassembled:

```
1    ; Read input from the I/O pin into RR.
1    ; Read input from the I/O pin into RR.
8    ; Output RR to the I/O pin.

```

### Program B, 1.5 bytes

```
428

```

Disassembled:

```
4    ; Read input from the I/O pin and store (RR AND (NOT INPUT)) into RR.
2    ; Read input from the I/O pin and store (NOT INPUT) into RR.
8    ; Output RR to the i/O pin.

```

### Explanation

Program A outputs the second bit of input, which is 0 for Program A and 1 for Program B.

Program B outputs the complement of the second bit of input, which is 1 for Program A and 0 for Program B.

# Answer
> 3 votes
# Haskell, 21 bytes

#### function A, 11 bytes

`even.length`

#### function B, 10 bytes

`odd.length`

# Answer
> 3 votes
# Brachylog, 2 bytes

```
0

```

Try it online!

```
1

```

Try it online!

With inspiration from Neil's Retina answer. Both full programs succeed on themselves and fail on each other. Each program unifies the input (and output) with the single numeric literal in the body, which matches the syntax for providing numbers as input.

# Answer
> 2 votes
# Brainbool, 6 bytes

A: `1,.`
B: `,+.`

A with A input
A with B input
B with B input
B with A input

**A explanation:**

```
1 this is comment used for "1" input
, reads character
. and print it back

```

**B explanation:**

```
, reads character; also it is used as "0" input
+ negates the value
. print the value

```

# Answer
> 2 votes
# MATL (both programs), score 4

Program A: `oo`

Program B: `I\`

Each program with itself as input outputs a *truthy* result, specifically a numeric array containing *positive integers*. Each program with the other as input outputs a *falsy* result, specifically a numeric arrray containing *at least a zero entry*. See truthy/falsy criteria in MATL, or use this truthy/falsy test.

### How it works

Program A:

```
o  % Implicit input. Convert codepoints to numbers. Gives numeric vector
o  % Modulo 2 of each entry. Implicit display

```

Program B:

```
I  % Push 3
\  % Implicit input. Modulo (3, of code points). Gives numeric vector. Implicit display

```

# Answer
> 2 votes
# Desmos, 34 bytes

### Program A, 17 bytes

```

A(l)=\{l[2]=65\}

```

### Program B, 17 bytes

```

B(l)=\{l[2]=66\}

```

Input is a list of character codepoints, and output is `1` for truthy (accepting) and `undefined` for falsey (rejecting).

This is just the first strategy I thought of; there might be better ways out there.

Try It On Desmos!

Try It On Desmos! - Prettified

# Answer
> 2 votes
# 05AB1E, ~~6~~ 4 bytes

* -2 thanks to Kevin Cruijssen

### Program A, ~~3~~ 2 bytes

### Program B, ~~3~~ 2 bytes

### Test cases

### Explanation

checks whether `0` is in the input, and  checks whether `1` is in the input.

# Answer
> 2 votes
# Java 19 using exit codes, 146 (73 + 73)

```
interface A{static void main(String[]a){System.exit(a[1].charAt(0)%65);}}

```

```
interface B{static void main(String[]a){System.exit(a[1].charAt(0)%66);}}

```

Run it with variations of:

```
cat A.java | xargs java B
echo $?

```

# Java 19 using standard out, 158 (79 + 79) bytes

```
interface A{static void main(String[]a){System.out.print(a[1].charAt(0)==65);}}

```

```
interface B{static void main(String[]a){System.out.print(a[1].charAt(0)==66);}}

```

Run it with variations of:

```
cat A.java | xargs java A

```

# Answer
> 2 votes
# brainfuck, 7 bytes

Outputs `,` for truthy and `F` for falsy.

### Program A, 3 bytes

```
,F.

```

### Program B, 4 bytes

```
F,,.

```

### Test cases

### Explanation

Program A retrieves and prints the first byte of input, and Program B retrieves and prints the second byte of input. An `F` char (no-op) is inserted into each program in the opposite position of which the program prints out (so that Program A's F is the second char and Program B's F is the first char).

# Answer
> 2 votes
# , 11+12 = 23 bytes

**prog a (11 bytes)**

```
scan(,'')>F

```

prog a with itself as input = `TRUE`
prog a with prog b as input = `FALSE`

**prog b (12 bytes)**

```
!scan(,'')>F

```

prog a with prog a as input = `FALSE`
prog a with itself as input = `TRUE`

# Answer
> 2 votes
# x86\_32 machine code, 6 bytes

Takes input in ESI (interpreted as a uint8\_t \*), and outputs to AL `0xAC` for truthy and `0x46` for falsy.

Try it online!

### Function A, 3 bytes

```
08049001 <a>:
 8049001:   ac                      lodsb
 8049002:   46                      inc esi
 8049003:   c3                      ret

```

### Function B, 3 bytes

```
08049005 <b>:
 8049005:   46                      inc esi
 8049006:   ac                      lodsb
 8049007:   c3                      ret

```

### Explanation

Function A copies the first byte of input to AL with `lodsb`. Function B copies the second byte of input to AL by first incrementing ESI before executing `lodsb`.

When Function A is run with itself or Function B is run with itself, the first/second byte (respectively) is copied to AL, which in both cases ends up being `0xAC`.

When Function A is run with B or Function B is run with A, the opposite byte (`0x46`) is copied to AL.

# Answer
> 2 votes
# Thue, 39 + 39 bytes

```
a::=b
b::=~1
c::=:::
A::=d
d::=~0
::=
c

```

True False

```
A::=B
B::=~1
C::=:::
a::=D
D::=~0
::=
C

```

True False

Has an additional newline (actually two) because of TIO implementation issue.

Truthy = `11` or `1\n1` depending on the implementation, in this case, `1\n1\n`

Falsy = `0`

# Answer
> 1 votes
# POSIX Shell + Utilities, 8+9=17 bytes

```
$ cat ff?; echo; wc -c ff?
cmp $0 -
cmp $0 -
 9 ff1
 8 ff2
17 total
$ ./ff1 < ff1; echo $?
0
$ ./ff1 < ff2; echo $?
1
$ ./ff2 < ff1; echo $?
1
$ ./ff2 < ff2; echo $?
0

```

Some cmp implementations would allow dropping the  `-`, for a score of 6+7=13 bytes.

# Answer
> 1 votes
# Charcoal, 6 bytes

Program A:

```
№ＳA

```

Program B:

```
№ＳB

```

Explanation: Each program counts the number of `A`s or `B`s in the input respectively, which will be truthy for itself and falsy for the other program.

# Answer
> 1 votes
# sed, 35 bytes

### Program A, 17 bytes

```
s/s.*/1/;s/;.*/0/

```

### Program B, 18 bytes

```
;s/s.*/0/;s/;.*/1/

```

### Test cases

### Explanation

Program B starts with `;` to distinguish it from Program A.

Program A replaces lines starting with `s` with `1`, and replaces lines starting with `;` with `0`.

Program B replaces lines starting with `s` with `0`, and replaces lines starting with `;` with `1`.

# Answer
> 1 votes
# gbz80 machine code functions, 8 bytes

(Registers and flags will be referred to in lowercase letters, and the functions in uppercase letters.)

These functions require that the function to test is pointed to by `hl`. Their truthiness is output in the `z` flag: true is a match, false is a non-match.

## Function A, 4 bytes:

```
3e 3e be c9

```

Disassembly:

```
ld a, $3e ; 3e is the opcode of "ld a, d8"
cp [hl]
ret

```

## Function B, 4 bytes:

```
00 af be c9

```

Disassembly:

```
nop
xor a ; set a to 0
cp [hl]
ret

```

We're just checking the first byte of the function using two different ways to set `a` to a constant.

# Answer
> 1 votes
# PUBERTY, 241 bytes

Outputs `0` for truthy and `I` for falsy.

### Program A, 118 bytes

```
0
It is May 1, 1000, :: PM.q is in his bed, bored.His secret kink is t.Soon the following sounds become audible.oh yes

```

### Program B, 123 bytes

```
I
0
It is May 1, 1000, :: PM.q is in his bed, bored.His secret kink is t.Soon the following sounds become audible.oh oh yes

```

### Explanation

Both start with no-ops for simple processing. This answer works in the same way as my brainfuck answer. Program A prints out the first char of input (not including newlines, which are required for the input to be registered) and Program B prints out the second.

# Answer
> 1 votes
# GNU sed, 10 bytes

## Program A: 5 bytes

```
/a/q1

```

## Program B: 5 bytes

```
/b/q1

```

Run with `sed -nf <program_filename> <input_filename>` Both programs output via their exit code, where 0 is accepting (or "friend") and 1 is rejecting (or "foe").

By default, `sed` outputs with exit code 0. However, the `q` command in GNU sed can terminate with a different exit code. Program A searches the input text for the letter `a` (which exists in Program A but not Program B). If it's present, then we terminate early with exit code 1. If not, we terminate at the end with the default exit code of 0. Program B does the exact same thing, except that it searches for letter `b` instead of `a`.

# Answer
> 1 votes
# TI-Basic, 8 bytes

### Program A, 5 bytes

```
6-length(Ans

```

### Program B, 3 bytes

```
length(Ans

```

Both programs take input from `Ans` as a string. Both output `2` for truthy and `4` for falsy.

# Answer
> 1 votes
# Thunno, \\$1\log\_{256}(96)\approx\\$ 0.82 bytes

Port of Lecdi's Jelly answer. Falsy = accepting; Truthy = rejecting.

### Program A, \\$1\log\_{256}(96)\approx\\$ 0.82 bytes

```
!

```

### Program B, 0 bytes

### Test cases

### Explanation

`!` is the operator for logical `not`.

# Answer
> 0 votes
# Jelly, 8 bytes

### Program A, 4 bytes

```
0ŒṘe

```

### Program B, 4 bytes

```
1ŒṘe

```

### Test cases

### Explanation

`0ŒṘe` checks whether 0 is in the input, and `1ŒṘe` checks whether 1 is in the input.

# Answer
> 0 votes
# Python 3, 36 bytes

```
print(''<input())

```

Try it online!

```

print(''==input())

```

Try it online!

# Answer
> 0 votes
# Python 3, ~~44~~ 40 bytes

## A, 20 bytes

```
print('['in input())

```

## B, 20 bytes too

```
print(']'in input())

```

A, when input A

A, when input B

B, when input A

B, when input B

What I really like about this one, is that you can change 1 character and get the other program.

# Answer
> 0 votes
# SussyLang, 88 bytes

Outputs `0` for truthy and `3` for falsy.

### Program A, 44 bytes

```
pensus
sus 112
sussyballs
imposter
sussybaka

```

### Program B, 44 bytes

```
sus 115
pensus
sussyballs
imposter
sussybaka

```

### Test cases

### Explanation

Program A takes the first character and subtracts 112 ('p'); Program B takes 115 ('s') and subtracts the first character.

# Answer
> 0 votes
# Pyt, 6 bytes

**Program A**

```
0
=

```

Try it online!

**Program B**

```
1
=

```

Try it online!

# Answer
> 0 votes
# C (gcc) and Python 3, ~~31 + 21 = 52~~ 28 + 21 = 49 bytes

\*-2 bytes by following @ceilingcat's suggestion, and -1 more by using `<'p'` rather than `=='m'` in C.

C:

```
main(){exit(getchar()<'p');}

```

Try It Online!

If there's a difference between the first character of input and `'m'`, the program returns `0`; otherwise it returns `1`.

Python 3:

```
print(input()[0]>'m')

```

Try It Online

If the ascii code for the first character of input is more than the one for `'m'` (which `p` is but `m` isn't), the program prints `True`; otherwise it prints `False`.

# Answer
> 0 votes
# Python, 20 bytes

### Program A, 10 bytes

```
"$".__gt__

```

### Program B, 10 bytes

```
'$'.__lt__

```

Attempt This Online! Link includes all four test cases.

Function which takes a string, returning `True` for friend and `False` for foe.

#### How?

Python string comparison works character by character.

When comparing `$` to `"$".__gt__`, only `$` and `"` are compared.
Similarly, when comparing `$` to `'$'.__lt__`, only `$` and `'` are compared.

In ASCII values, `" < $ < '`.

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


# Question
Title: Generate all possible equations with 10 characters
Nerdle is a Wordle variant, in which instead of words, the answers are equations. Each equation entered in the game must be a valid one.

Examples: `13³-1=2196`, `(1/1)²*8=8`, `(((3)))²=9`

The task is to generate and output to a .txt file, one equation per line, all possible 10 character equations that could be an answer for the game (specifically the Maxi Nerdle) as fast as possible (note that the code should be limited to 100KB to avoid hardcoding).

**The possible symbols for a Maxi Nerdle equation are:**

* 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, +, -, \*, /, ², ³, ), (, =

**The rules that make an equation a possible answer to the game, besides being mathematically true, are:**

* There are no leading zeros
* There are no lone zeros (There can't be a `+0` in the equation, for example)
* There are no operators in sequence, that is, +, -, \*, / can't be adjacent to each other (`+++----1=1`, for example)
* The right-hand side of the equation must be a non-negative integer
* Operations must be explicit, that is, `9(10-8)=18` is not valid, for example, as there should be a * between 9 and (
* There can only be one `=` symbol

Also note that commutativity doesn't apply. If the order of the numbers changes, it must be treated as a different equation.

**Expected output**

For 10 characters long equations with the Maxi Nerdle symbols, there should be 2,177,017 equations. They can be viewed here (this was generated in 1 hour with a simple Python script).

**Score**

As this is a challenge, the score will be based on the time taken to run it on my computer (Windows 10). Here are my specs:

* Intel(R) Core(TM) i5-9300H CPU 2.40GHz
* 8 GB RAM with 2667 MHz speed

Please include instructions for how to compile/run your code.

# Answer
> 2 votes
# C, about 6.3 seconds on my M1 MacBook Pro

Here's a start. I think there is a lot more optimisation to do here.

All credit for the recursive descent parser to @Henrik. I have lightly modified it to operate on doubles instead of ints, and to calculate 2nd and 3rd powers.

* Compile with `cc -O3 nerdle.c -o nerdle`
* Run as `time ./nerdle`. Generates a file `nerdle.txt` in the current directory.

On MacOS, the default `cc` is clang. `-O3` sped up runtime by a factor of 4, over default optimisation. This should compile just as well with gcc.

The `gen_*()` functions recursively generate all valid expressions. Then these are evaluated with a recursive descent parser, and output if mathematically true.

I have taken care to output the results in the same order as NerdleMaxi.txt, so they may easily be verified with `diff` / `cmp`.

This code is not pretty, and would benefit from a good deal of deodorising.

```
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>

char * expressionToParse;
FILE *fp;

char peek()
{
    return *expressionToParse;
}

char get()
{
    return *expressionToParse++;
}

double expression();

double number()
{
    double result = get() - '0';
    while (peek() >= '0' && peek() <= '9')
    {
        result = 10*result + get() - '0';
    }
    return result;
}

double factor()
{
    if (peek() >= '0' && peek() <= '9')
        return number();
    else if (peek() == '(')
    {
        get(); // '('
        double result = expression();
        get(); // ')'
        return result;
    }
    else if (peek() == '-')
    {
        get();
        return -factor();
    }
    return 0; // error
}

double expon()
{
    double result = factor();
    while (peek() == 's' || peek() == 'c')
        if (get() == 's')
            result *= result;
        else
            result *= (result * result);
    return result;
}

double term()
{
    double result = expon();
    while (peek() == '*' || peek() == '/')
        if (get() == '*')
            result *= expon();
        else
            result /= expon();
    return result;
}

double expression()
{
    double result = term();
    while (peek() == '+' || peek() == '-')
        if (get() == '+')
            result += term();
        else
            result -= term();
    return result;
}

static void gen_nz_digit(int level, int br_level, char * buf, int ndigits);
static void gen_digit(int level, int br_level, char * buf, int ndigits);
static inline void gen_oper(int level, int br_level, char * buf, int ndigits);
static inline void gen_squared(int level, int br_level, char * buf, int ndigits);
static inline void gen_cubed(int level, int br_level, char * buf, int ndigits);
static inline void gen_open(int level, int br_level, char * buf, int ndigits);
static inline void gen_close(int level, int br_level, char * buf, int ndigits);
static inline void gen_equals(int level, int br_level, char * buf, int ndigits);

static void
gen_nz_digit (int level, int br_level, char * buf, int ndigits)
{
    int i;

    if (level >= 8) {
        return;
    }

    int next_level = level + 1;

    for (i = 1; i < 10; i++) {
        buf[level] = '0' + i;
        gen_equals(next_level, br_level, buf, 0);
        gen_digit(next_level, br_level, buf, 1);
        gen_oper(next_level, br_level, buf, 0);
        gen_squared(next_level, br_level, buf, 0);
        gen_cubed(next_level, br_level, buf, 0);
        if (br_level > 0) {
            gen_close(next_level, br_level, buf, 0);
        }
    }
}

static void
gen_digit (int level, int br_level, char * buf, int ndigits)
{
    int i;

    if (level >= 8) {
        return;
    }
    if (ndigits >= 4) {
        return;
    }

    int next_level = level + 1;

    for (i = 1; i < 10; i++) {
        buf[level] = '0' + i;
        gen_equals(next_level, br_level, buf, 0);
        gen_digit(next_level, br_level, buf, ndigits + 1);
        gen_oper(next_level, br_level, buf, 0);
        gen_squared(level +1, br_level, buf, 0);
        gen_cubed(next_level, br_level, buf, 0);
        if (br_level > 0) {
            gen_close(next_level, br_level, buf, 0);
        }
    }
    buf[level] = '0';
    gen_equals(next_level, br_level, buf, 0);
    gen_digit(next_level, br_level, buf, ndigits + 1);
    gen_oper(next_level, br_level, buf, 0);
    gen_squared(level +1, br_level, buf, 0);
    gen_cubed(next_level, br_level, buf, 0);
    if (br_level > 0) {
      gen_close(next_level, br_level, buf, 0);
    }

}

static inline void
gen_oper (int level, int br_level, char * buf, int ndigits)
{
    if (level >= 7) {
        return ;
    }

    int next_level = level + 1;

    buf[level] = '-';
    gen_nz_digit(next_level, br_level, buf, 0);
    gen_open(next_level, br_level, buf, 0);

    buf[level] = '+';
    gen_nz_digit(next_level, br_level, buf, 0);
    gen_open(next_level, br_level, buf, 0);

    buf[level] = '*';
    gen_nz_digit(next_level, br_level, buf, 0);
    gen_open(next_level, br_level, buf, 0);

    buf[level] = '/';
    gen_nz_digit(next_level, br_level, buf, 0);
    gen_open(next_level, br_level, buf, 0);
}

static inline void
gen_squared (int level, int br_level, char * buf, int ndigits)
{
    if (level >= 8) {
        return;
    }

    int next_level = level + 1;

    buf[level] = 's';
    if (level >= 3) {
        gen_equals(next_level, br_level, buf, 0);
    }
    gen_oper(next_level, br_level, buf, 0);
    if (br_level > 0) {
        gen_close(next_level, br_level, buf, 0);
    }
}

static inline void
gen_cubed (int level, int br_level, char * buf, int ndigits)
{
    if (level >= 8) {
        return;
    }

    int next_level = level + 1;

    buf[level] = 'c';
    if (level >= 2) {
        gen_equals(next_level, br_level, buf, 0);
    }
    gen_oper(next_level, br_level, buf, 0);
    if (br_level > 0) {
        gen_close(next_level, br_level, buf, 0);
    }
}

static inline void
gen_open (int level, int br_level, char * buf, int ndigits)
{
    if (level >= 7) {
        return;
    }

    int next_level = level + 1;
    buf[level] = '(';
    br_level++;
    gen_nz_digit(next_level, br_level, buf, 0);
    gen_open(next_level, br_level, buf, 0);
}

static inline void
gen_close (int level, int br_level, char * buf, int ndigits)
{
    if (level >= 8) {
        return;
    }

    int next_level = level + 1;

    buf[level] = ')';
    br_level--;
    gen_equals(next_level, br_level, buf, 0);
    gen_oper(next_level, br_level, buf, 0);
    gen_squared(next_level, br_level, buf, 0);
    gen_cubed(next_level, br_level, buf, 0);
    if (br_level > 0) {
        gen_close(next_level, br_level, buf, 0);
    }
}

static inline int
int_len (int n) {
    if (n < 10) {
        return 1;
    } else if (n < 100) {
        return 2;
    } else if (n < 1000) {
        return 3;
    } else if (n < 10000) {
        return 4;
    } else if (n < 100000) {
        return 5;
    } else {
        return 6;
    }
}

static inline void
gen_equals (int level, int br_level, char * buf, int ndigits)
{
    double result;
    double int_part;
    double frac_part;

    if (br_level > 0) {
        return;
    }
    buf[level] = '\0';
    expressionToParse = buf;
    result = expression();
    frac_part = modf(result, &int_part);
    if (frac_part == 0) {
        int rhs = (int)int_part;
        if (rhs >= 0) {
            if (level + int_len(rhs) == 9) {
            char out_str[20];
        char *ptr = out_str;
        char tmp_str[20];
        strcpy(out_str, buf);
        while (NULL != (ptr = strchr(ptr, 's'))) {
            strcpy(tmp_str, ptr + 1);
            sprintf(ptr, "²%s", tmp_str);
        }
        ptr = out_str;
        while (NULL != (ptr = strchr(ptr, 'c'))) {
            strcpy(tmp_str, ptr + 1);
            sprintf(ptr, "³%s", tmp_str);
        }

            fprintf(fp, "%s=%d\n", out_str, rhs);
            }
        }
    }
}

int
main (int argc, char ** argv)
{
    fp = fopen("nerdle.txt", "w");
    char buffer[20] = "";
    gen_nz_digit(0, 0, buffer, 0);
    gen_open(0, 0, buffer, 0);
    fclose(fp);
}

```

---
Tags: math, game, fastest-code
---