title: Make an ASCII table

text:
# Question
Title: Make an ASCII table
We're getting markdown tables! I assume this is what they look like:

```
     data
   data data  data
---------------------
 |                 |
 |                 |
 |                 |
 |                 |

```

Your task is to make a program or function to generate one of these tables. You'll be given input (string, list of lines, list of characters, etc.) containing data, which looks like this:

```
datadata

         data
  data           data
data data  data

```

The data consists of spaces and non-overlapping `data`s. The data will not necessarily form neat stacks (it can float in midair). There is guaranteed to be data on the top and bottom lines, as well as some touching the left side. You can choose if the data is right padded with spaces or not.

The table will always be six characters wider than the data, padded three spaces on the left. The table top is directly below the bottom row of data, and is made up of a line of `-`s.

As for the legs, everyone knows taller tables can support more weight, so they'll need to be one unit tall for every `data` in the input. They will be made up of `|`s, one space in from the sides.

This is , so shortest answer in bytes per language wins!

## Test cases

Input:

```
data

```

Output:

```
   data
----------
 |      |

```

Input:

```
data data data
 data data data

```

Output:

```
   data data data
    data data data
---------------------
 |                 |
 |                 |
 |                 |
 |                 |
 |                 |
 |                 |

```

Input:

```
data

data

```

Output:

```
   data

   data
----------
 |      |
 |      |

```

# Answer
> 10 votes
# Perl 5 `-lpF`, ~~88~~ ~~74~~ 66 bytes

*Because we're allowed to require the input to be padded on the right side, @DomHastings was able to shave 8 bytes off my method while eliminating the need for `List::Util`.*

```
END{printf'-'x(@F+6)."
 |%@{[@F+3]}s"x$q,("|")x$q}s//   /;$q+=y;d;

```

Try it online!

# Answer
> 6 votes
# 05AB1E, ~~31~~ ~~30~~ 28 bytes

```
¬g6+©'-×ªð®×'|1®Í‚ǝIJ'd¢и«.c

```

-1 byte thanks to *@ovs*.

Input as a list of lines, right-padded with spaces to an equal length.

Try it online or verify all test cases.

**Explanation:**

```
¬                  # Get the first line of the (implicit) input-list (without popping)
 g                 # Pop and push its length
  6+               # Add 6
    ©              # Store this value in variable `®` (without popping)
     '-×          '# Pop and create a string of that many "-"
        ª          # Append it to the list of lines
ð®×                # Create a string consisting of `®` amount of spaces
     1             # Push 1
      ®Í           # Push value `®` and decrease it by 2
        ‚          # Pair them together: [1,®-2]
   '|    ǝ        '# Insert a "|" at those (0-based) indices in the spaces-string
          IJ       # Push the input-list, and join it to a single string
            'd¢   '# Count the amount of "d"s in it
               и   # Repeat the legs-string that many times as list
                «  # And merge the two lists together
.c                 # And finally centralize this list, which adds leading spaces where
                   # necessary, and implicitly joins the list by newlines
                   # (after which the result is output implicitly)

```

# Answer
> 5 votes
# APL (Dyalog Unicode), ~~60 57 56 55~~ 41 bytes

```
{3⌽↑(↓'-'⍪⍨' '∘,⍣6⊢⍵),↓(+/∊'d'⍷⍵)6⍴' | '}

```

Try it online!

Input as a character matrix.

-1 byte from ovs.

-14 bytes, following xash's answer.

## Explanation(old)

```
{↑('   '∘,¨↓⍵),(⊂a/'-'),(+/∊'d'⍷⍵)/⊂2⌽'|  |'↑⍨a←6+⊃⌽⍴⍵}
                                      '|  |'                 a set of table legs
                                            ↑⍨               pad to length
                                              a←6+⊃⌽⍴⍵       6 + row size
                                       a←                    store in var a
                                    ⊂2⌽                      rotate 2 steps and wrap
                         (        )/                         replicate that by:
                             'd'⍷⍵                           boolean matrix of occurrences of 'data'
                          +/∊                                sum all the occurrences
                        ,                                    concatenate with
               (⊂a/'-')                                      '-' repeated a times
  ('   '∘,¨↓⍵),                                              and the input padded with 3 spaces on the left
 ↑                                                           convert to matrix(join with newlines)

```

# Answer
> 4 votes
# Ruby 2.7, ~~112~~ ~~98~~ ~~77~~ 74 bytes

*Saved 6 bytes using* `String#count` *method, thanks to Razetime!*
*Saved 3 bytes using literal newline, thanks to Dingus!*

```
->m{m.map{" "*3+_1}<<?-*(6+c=m[0].size)+"
 | #{" "*c} |"*(m*"").count(?d)}

```

Try it online!

* TIO uses an older version of Ruby, while in Ruby 2.7, we've numbered parameters, i.e., `_1`, which saves 2 bytes.

# Answer
> 4 votes
# Japt, ~~30~~ ~~28~~ 27 bytes

Hmm ... thought this would work out much shorter.

Takes input as an array of lines, right-padded with spaces and outputs an array of lines.

```
cU¬èd ô@S+i|i|úUÎÊ+3ÃvÈç-
û

```

Try it or run all test cases

```
cU¬èd ô@S+i|i|úUÎÊ+3ÃvÈç-\nû     :Implicit input of array U
c                                :Concatenate
 U¬                              :  Join U
   èd                            :  Count the "d"s
      ô                          :  Range [0,count]
       @                         :  Map
        S                        :    Space
         +                       :    Append
          i                      :      A space prepended with
           |i                    :        A "|" prepended with
             |ú                  :          A "|" right padded with spaces to length
               UÎÊ+3             :          Length of first element of U plus 3
                    Ã            :End map
                     v           :Modify first element
                      È          :By passing it through the following function
                       ç-        :  Fill with "-"
                         \n      :Reassign to U (saves a byte over having to close all the nested methods)
                           û     :Centre pad each element with spaces to the length of the longest

```

# Answer
> 4 votes
# , 41 bytes

```
0 3|.(' | '$~6,~1#.'d'=,),~'-',~' '&,.^:6

```

Try it online!

### How it works

* `' '&,.^:6` prepend a space to each row 6 times.
* `'-',~` append a new row filled with `-`.
* `1#.'d'=,` count the `d`s in the input.
* `' | '$~6,~` shape  `|`  into dimensions `count 6`, so `count` rows of  `| |`
* `,~` append the leg rows to the tables, filling possible empty space on the right with .
* `0 3|.` shift every row 3 characters to the left.

Or in pictures:

```
data

      data

      data
----------

      data
----------
 |  |

    data
-----------
 |       |

```

# Answer
> 3 votes
# Charcoal, ~~29~~ 25 bytes

```
ＷＳ⊞υι↑№ΣυdＭ←³Ｌθ←Ｆυ↑‖ＯＯＬθυ

```

Try it online! Link is to verbose version of code. Takes newline-terminated rectangular input. Explanation:

```
ＷＳ⊞υι

```

Input the data.

```
↑№ΣυdＭ←³

```

Print the left leg and the `---` at the top of the left leg.

```
Ｌθ

```

Print the middle part of the table.

```
←Ｆυ↑

```

Move the cursor to the top right of the data. The following reflection will then move it to the top left. (Moving here avoids confusion between the use of the arrows as movement and as modifiers for reflection or printing direction.)

```
‖ＯＯＬθ

```

Reflect to complete the right of the table.

```
υ

```

Print the data.

# Answer
> 3 votes
# Python 3.8, ~~113~~ ~~107~~ 95 bytes

Saved ~~6~~ a whopping 18 bytes thanks to Dom Hastings!!!

```
lambda l:['   '+a for a in l]+[(r:=6+len(l[0]))*'-']+''.join(l).count('d')*[' |'+(r-4)*' '+'|']

```

Try it online!

Inputs a list of right-space-padded strings and returns a list of strings.

# Answer
> 3 votes
# Jelly, 36 bytes

```
Ỵ⁶x3¤;ṄƊ€ẈṀ+©3”-xṄṛċ”d®e®’,2¤¥þị⁾| Y

```

Try it online!

Takes input as a single string.

This is disgustingly hacked together, but Jelly's never been particularly good at strings.

## How it works

```
Ỵ⁶x3¤;ṄƊ€ẈṀ+©3”-xṄṛċ”d®e®’,2¤¥þị⁾| Y - Main link. Takes s on the left
Ỵ                                    - Split into a list of lines
       Ɗ€                            - Over each line l:
    ¤                                -   Group together as a nilad:
 ⁶                                   -     " "
  x3                                 -     [" ", " ", " "]
     ;                               -   Prepend to l
      Ṅ                              -   Print
         Ẉ                           - Get the lengths of each line
          Ṁ                          - Take the maximum
           + 3                       - Add 3
            ©                        - Save it to the register, r
              ”-                     - "-"
                x                    - Repeat that many times
                 Ṅ                   - Print
                  ṛ                  - Discard everything and use s
                   ċ”d               - Count occurrences of "d", d
                      ®              - Yield the register, r
                             ¥þ      - Create an d×r grid and to each cell (i, j):
                            ¤        -   Group into a nilad:
                        ®            -     r
                         ’           -     r-1
                           2         -     2
                          ,          -     [r-1, 2]
                       e             -   Is i in [r-1, 2]?
                               ị⁾|   - Index each cell into "| "
                                   Y - Join by newlines

```

# Answer
> 3 votes
# C (gcc), ~~204~~ ~~194~~ ~~187~~ ~~181~~ 174 bytes

*174-byte solution thanks to @ceilingcat.*

```
z,s,i;main(c,v)char**v;{for(;++z<c;)printf("   %s\n",v[z]);for(;c--;)for(s=0;z=v[c][s++];)i+=z=='d';for(;z++<strlen(v[1])+6;putchar(45));for(;i--;)printf("\n |%*c",z-4,'|');}

```

Try it online!

Takes each line of input as a right-padded command line argument.

# Answer
> 2 votes
# Retina, 53 bytes

```
\`.+
   $&
L$`d
$%=
T`p`-
*\0G`
T`-`
%,T1,,-2` `|

```

Try it online! Takes rectangular input. Explanation:

```
\`.+
   $&

```

Pad the input by 3 spaces on each side and print the result.

```
L$`d
$%=

```

Repeat each line by the count of its `d`s.

```
T`p`-

```

Change all the characters to `-`s.

```
*\0G`

```

Print the first line.

```
T`-`

```

Change all the characters to spaces.

```
%,T1,,-2` `|

```

Change the (0-indexed) second and second last characters to `|`s and implicitly print the resulting legs.

# Answer
> 2 votes
# JavaScript (ES6),  ~~105~~  103 bytes

Expects a single string with right-padded lines.

```
s=>s[R='replace'](/^|t/g,c=>o+=`
`+(p=c?' | ':'---')+q[R](/./g,p[0])+p,o=s[R](/.+/g,s=>'   '+(q=s)))&&o

```

Try it online!

### Commented

```
s =>                     // s = input string
s[R = 'replace'](        // replace in s:
  /^|t/g,                //   match the beginning of the string
                         //   and each 't' (of 'data')
  c =>                   //   for each matching character c:
    o +=                 //     append to o:
      `\n` + (           //       a line-feed
        p =              //       followed by p defined as:
          c ?            //         if c is not empty:
            ' | '        //           ' | '
          :              //         else:
            '---'        //           '---'
      )                  //
      + q[R](/./g,       //       followed by each character in q ...
                   p[0]) //       ... replaced with the 1st character of p
      + p,               //       followed by p
  o =                    //   initialize the output string o:
    s[R](                //     replace in s:
      /.+/g, s =>        //       each line s
        '   '            //       with 3 leading spaces
        + (q = s)        //       followed by s, which is copied in q
    )                    //     end of replace()
) && o                   // end of replace(); return o

```

# Answer
> 1 votes
# Perl 5 \+ `-pl055F`, 53 bytes

A different approach to @Xcali's answer. Requires lines to be padded with spaces.

```
$;+=y/d//;say"   $_"}{$\=$\x(6+($#x=@F))."
 | @x |"x$

```

Try it online!

## Explanation

Firstly, `-l055` sets `$\` to `'-'`, `-p` implicitly wraps wraps the code in `while(<STDIN>){...;print;}` and `-F` splits each line of input into chars in `@F`.

In the code, due to the implicit code added by `-p`, for each line of text increment `$;` with the number of `d` in the code then `say` the line with three leading spaces. The `}{` breaks out of the implicit `while` and `$\` is then set to `$\` repeated 6+`@F` (whilst also setting `$#x` to `@F`'s scalar value) times concatenated with a string consisting of: a leading newline, space, pipe (`|`), space, `@x` interpolated, space, pipe, which itself it repeated `$;` times.

`@F`, when used in a scalar context like this, returns the number of elements in `@F` \- which is the number of chars in the line, since each line is space-padded this works fine. `$#x` is a 'magic' variable which contains the last index of `@x` and means that `@x` now contains `@F`+1 empty values. When an array is interpolated into a double-quoted string, its values are printed out with a space between each, so an empty array with `@F`+1 elements interpolated, results in a string consisting of `@F` spaces. This code ends with just `$` because of the `-p`-added code which contains `;` saving another byte.

# Answer
> 1 votes
# Jelly, 38 bytes

```
Ỵ⁶x3¤;Ɱ©ẈṀ+3µ⁶ẋ”|2,-¦Wẋ³ċ”d¤;@”-xWƊ®;Y

```

Try it online!

# Answer
> 1 votes
# Vyxal `ao`, 34 bytes

```
ƛ3Ip…L;G:3+\-*,‹‛ƛ↓□⁋ẎL$I‛ |p‛|
+*

```

Try it Online! Probably not optimal, but beats Jelly :P

`a` flag is for multiline input; `o` forces implicit output even though there are print statements in the code.

```
ƛ3Ip…L;G:3+\-*,‹‛ƛ↓□⁋ẎL$I‛ |p‛|
+*                                # Full program

ƛ     ;                     # For each line in input (`a` flag):
 3Ip                        #   Prepend 3 spaces
    …                       #   Print ^
     L                      #   and return its length

G:                          # Take the maximum length from ^ and duplicate
  3+                        # Add 3 to one copy
    \-*,                    # Print that many `-`s
        ‹                   # Decrement the other maximum length copy for later

            □⁋              # From inputs...
              ẎL            # ...find the number of
         ‛ƛ↓                # ...`data`s (dictionary-compressed)
                $           # Swap number of "data"s for (maximum length - 1)
                 I          # Push that many spaces
                  ‛ |p      # Prepend " |" to ^
                      ‛|\n+ # Append "|\n" to ^ (\n is an actual newline)
 *                          # Repeat as many times as the number of datas to make the legs
                            # `o` flag - implicitly output the legs of the table

```

# Answer
> 0 votes
# Pip, 36 bytes

```
P'-M@P*gWRsX3LXW*4N JgPsX#a+2WR'|WRs

```

Takes lines of input as command-line arguments; or, with the -r flag, as lines of stdin. Lines must be padded with spaces to the same length. Try it online!

### Explanation

Let's break this into two halves: the data + tabletop, and the legs.

```
P'-M@P*gWRsX3
       g       List of input lines
        WR     Wrap each line in
          sX3  Three spaces
     P*        Print each line
    @          Take the first one
 '-M           List containing one hyphen for each character in that line
P              Print (concatenated together by default)

LXW*4N JgPsX#a+2WR'|WRs
       Jg                Join the lines of input into one string
     N                   Count occurrences in that string of
 XW                      Regex matching [a-zA-Z0-9]
   *4                    repeated 4 times
L                        Loop that many times:
             a            First line of input
            #             Length
              +2          Plus 2
          sX              String of that many spaces
                WR'|      Wrap in pipe characters
                    WRs   Wrap in spaces
         P                Print

```

---
Tags: code-golf, ascii-art
---


title: How long will my microwave run for?

text:
# Question
Title: How long will my microwave run for?
Following the theme of strange kitchen appliances, let's talk about my microwave.

# Introduction

My microwave has a keypad that is laid out like this:

```
30  >  15
1   2   3
4   5   6
7   8   9
+/- 0 S/M

```
* I can press the +/- and S/M keys to switch between adding and subtracting minutes or seconds.
* The microwave starts in add minutes mode.
* The 0-9 keys add or subtract 1-10 minutes/seconds to the time (0 adds 10.)
* The 30 and 15 keys always add or subtract 30 or 15 seconds.
* The \> key starts the microwave.
* The time cannot go below 0 seconds.

## Example

If I pressed `0 3 +/- 15 S/M 4 >` I would microwave my food for 12 minutes and 41 seconds:

1. 0: Add 10 minutes
2. 3: Add 3 minutes
3. +/-: Switch to subtract mode
4. 15: Subtract 15 seconds
5. S/M: Switch to seconds
6. 4: Subtract 4 seconds
7. \>: Start the microwave

Other test cases:

* `0 3 +/- 15 S/M 4 S/M 1 S/M +/- 0 S/M 7 -/+ 30 >` = 1101

# The Challenge

Write me a program that takes as input a string of button presses (separator doesn't matter) and outputs how long my microwave will run for (in seconds). This is code-golf, so shortest code in bytes wins!

## Button Codes

These are the button codes your program should accept: (I should be able to input exactly these strings):

* `0 1 2 3 4 5 6 7 8 9` (0 equals 10)
* `30`
* `15`
* `+/-`
* `S/M`
* `>`

# Answer
# PowerShell, 106 86 bytes

Big thanks to both @mazzy and @Julian for saving me an ENORMOUS 20 bytes!!!

```
$s=1
switch -r($args){\d{$t+=$s*(10*!+$_+$_)*(1+59*!$m*(9-ge$_))}-{$s=-$s}s{$m=!$m}}$t

```

Try it online!
> 5 votes

# Answer
# Python 2, ~~112~~ 109 bytes

Reads a list of instructions from STDIN. Prints duration in seconds.

```
t=0;d=1;r=60
for c in input()[:-1]:exec['k=int(c)or+10;t+=k*r**(k<11)*d','d=-d','r^=61'][hash(c)>>62]
print t

```

Try it online!

`hash(c)>>62` maps all the numbers to 0, `+/-` to 1 and `S/M` to -1.
> 4 votes

# Answer
# JavaScript (ES6), 68 bytes

Expects a list of commands. Returns a number of seconds. Assumes that the last command is `>`, as stated in the comments.

```
a=>a.map(c=>1/c?t+=s*(+c||10)*(c>9|a||60):c<','?s=-s:a^=1,t=0,s=1)|t

```

Try it online!

### Commented

```
a =>               // a[] = input array, reused as a flag to figure out
                   //       if we are in 'seconds' mode
a.map(c =>         // for each command c in a[]:
  1 / c ?          //   if c is numerical:
    t +=           //     add to t:
      s *          //       the sign multiplied by
      (+c || 10) * //       either c, or 10 if c is 0
      (            //       multiplied by
        c > 9      //       1 if c is 15 or 30
        | a        //       or we are in seconds mode
        || 60      //       otherwise 60
      )            //
  :                //   else:
    c < ',' ?      //     if c is '+/-':
      s = -s       //       invert the sign
    :              //     else:
      a ^= 1,      //       switch between 'seconds' and 'minutes' mode
                   //       (c is either 'S/M' or '>')
  t = 0,           //   start with t = 0
  s = 1            //   start in 'add' mode
) | t              // end of map(); return t

```
> 4 votes

# Answer
## Batch, 192 bytes

```
@set/at=0,s=1,m=60
:l
@set/pb=
@if "%b%"==">" echo %t%&exit/b
@if %b%==+/- set/as=-s
@if %b%==S/M set/am=60/m
@if %b%==0 set b=10
@if %b% gtr 10 (set/at+=s*b)else set/at+=s*m*b
@goto l

```

Takes newline-terminated input on STDIN, as `>` is tricky to use on the command line. Explanation:

```
@set/at=0,s=1,m=60

```

Initialise the total and sign and minutes flags.

```
:l

```

Start a loop.

```
@set/pb=

```

Read in the next button.

```
@if "%b%"==">" echo %t%&exit/b

```

Output the total and finish if this is the `>` button.

```
@if %b%==+/- set/as=-s
@if %b%==S/M set/am=60/m

```

Update the flags for the `+/-` and `S/M` buttons.

```
@if %b%==0 set b=10

```

`0` counts as `10`.

```
@if %b% gtr 10 (set/at+=s*b)else set/at+=s*m*b
@goto l

```

Update the number of seconds and loop back. Note that non-numeric strings silently evaluate to 0, thus leaving the total undisturbed.
> 4 votes

# Answer
# Charcoal, ~~53~~ 51 bytes

```
≔⁶⁰η≔⁰ζＷη«Ｓθ≡θ>≔⁰η+/-≦±ηS/M≦÷⁶⁰η≧⁺×∨Ｉθχ÷ηＸ↔η⊖Ｌθζ»Ｉζ

```

Try it online! Link is to verbose version of code. Takes input as either space or newline separated (but not both at the same time). Explanation:

```
≔⁶⁰η

```

Start in add minutes mode.

```
≔⁰ζ

```

Start with `0` seconds.

```
Ｗη«

```

Repeat until `>` has been processed.

```
Ｓθ≡θ

```

Input the next button and switch on it.

```
>≔⁰η

```

If this is the start button then clear the mode, allowing the loop to terminate. (If there are at least two button presses, then a byte could be saved by using a different termination condition.)

```
+/-≦±η

```

If this is the `+/-` button then flip between add and subtract mode.

```
S/M≦÷⁶⁰η

```

If this is the `S/M` button then flip between minutes and seconds mode. (I don't get to use  much with binary operators. Both  and  work with unary operators but the deverbosifier always picks .)

```
≧⁺×∨Ｉθχ÷ηＸ↔η⊖Ｌθζ

```

Get the current value, change it to 10 if it is zero, multiply it by the mode, but if the value was greater than 10 then divide by the absolute value of the mode, so that the minute mode is ignored. Edit: Saved 2 bytes by porting this calculation from @tsh's Python answer.

```
»Ｉζ

```

Output the final number of seconds.
> 2 votes

# Answer
# Perl 5 -apl, 81 bytes

```
$f=60;$S=0;$_||=10,/-/?$f=-$f:/S/?$f=60/$f:($S+=$_*$f/($_%15?1:abs$f))for@F;$_=$S

```

Try it online!

```
$f=60;            # starts in plus mode and minute mode (f=multiplying factor)
$S=0;             # reset output sum
$_||=10,          # convert 0 to 10 for current button in $_
/-/?$f=-$f:       # -/+ negates $f
/S/?$f=60/$f:     # S/M toggles $f between 1 and 60 or -1 and -60
($S+=$_*$f        # add button times $f (factor) to sum in $S
/($_%15?1:abs$f)) # force seconds as temporary unit if 15 or 30
for@F;            # for each button in input array @F (due to -a)
$_=$S             # print current sum in $S which is seconds to run
                  # (challenge just said "outputs how long" and I chose
                  # seconds as my unit of time).

```
> 1 votes

# Answer
# Python 3, 112 bytes

```
c=60
t=0
for k in input().split():
	try:t+=c*int(k)/abs(c)**~-len(k)or 10*c
	except:c=(k>'0')*60/c or-c
print(t)

```

Try it online!
> 1 votes

# Answer
# Python 3, 178 bytes

```
l=eval(input());n=0;m=0;d=1;exec(";".join([['n+=15*d','d*=-1','m=1-m','n+=30*d',f"n+=(({x} or 10)*(60-59*m))*d"][[(sum(map(ord,x))%10)//3,4][len(x)<2]]for x in l[:-1]]));print(n)

```

Try it online!

longer than @ovs but should be more portable since it sums up the charcodes, mods by 10 and integer divides by 3 to distinct the inputs.
> 0 votes

# Answer
# 05AB1E, 33 bytes

```
ÎvyÐdigi0T.:¾È59*>*}X*+ë\нai¼ëX(U

```

Input as a list.

Try it online or verify all test cases.

**Explanation:**

```
Î                   # Push 0 and the input-list
 vy                 # Foreach over the items:
   Ð                #  Triplicate the current item
    di              #  Pop one, and if it's an integer:
      gi            #   Pop another, and if it's a single digit:
        0T.:        #    Replace the 0 with 10
            ¾       #    Push the counter_variable
                    #    (the counter_variable is 0 by default)
             È      #    Pop and check if it's is even (1 if even; 0 if not)
              59*   #    Multiply this by 59
                 >  #    Increase it by 1
                  * #    Multiply it to the current integer
       }            #   After the inner-most if-statement
        X*          #   Multiply the value by `X`
                    #   (`X` is 1 by default)
          +         #   And add it to the result
     ë              #  Else (it's not an integer):
      \             #   Discard one of the remaining copies
       н            #   Pop the last one, and push its first character
        ai          #   Pop, and if this is a letter:
          ¼         #    Increase the counter_variable by 1
         ë          #   Else (it's a '+' or '>' instead):
          X(U       #    Negate `X`, and store it as new `X`

```
> 0 votes

# Answer
# JavaScript (Node.js), 68 bytes

```
f=A=>A.map(k=>1/k?t+=k>9?c%59*k:c*k||c*10:c=k>f?60/c:-c,c=60,t=0)&&t

```

Try it online!
> 0 votes

---
Tags: code-golf
---


title: Help me compress this song

text:
# Question
Title: Help me compress this song
in my country we have a children's song which goes like this:

```
Priletela muha na zid, muha na zid, muha na zid.
Priletela muha na zid,
muha na zid.

Pralatala maha na zad, maha na zad, maha na zad.
Pralatala maha na zad,
maha na zad.

Preletele mehe ne zed, mehe ne zed, mehe ne zed.
Preletele mehe ne zed,
mehe ne zed.

Prilitili mihi ni zid, mihi ni zid, mihi ni zid.
Prilitili mihi ni zid,
mihi ni zid.

Prolotolo moho no zod, moho no zod, moho no zod.
Prolotolo moho no zod,
moho no zod.

Prulutulu muhu nu zud, muhu nu zud, muhu nu zud.
Prulutulu muhu nu zud,
muhu nu zud.

```

As you can see, it contains a bit of redundant information. So I was wondering if it could be compressed a bit.

This is code golf — shortest code wins.

# Answer
# 05AB1E, ~~54~~ 52 bytes

Thanks to Kevin Cruijssen for -2 bytes!

```
T"ÿ, 0, 0.
ÿ,
0.
"T.•ý‹¨ΣªßˆTδ}vØ#•.ª'x¡‡žMv=žMyÞ‡}?

```

Try it online!

**Commented**:

```
T                         # push 10
 "ÿ, 0, 0.\nÿ,\n0.\n"     # push string literal "10, 0, 0.\n10,\n0.\n"
  T                       # push 10 again
   .•ý‹¨ΣªßˆTδ}vØ#•       # push compressed string "priletela xmuha na zid"
    .ª                    # sentence case => "Priletela xmuha na zid"
      ‛x¡                 # split on 'x'  => ["Priletela ", "muha na zid"]
         ‡                # replace every digit of 10 with the corresponding list entry in the string literal
                          # this is the first verse
          žM              # push the vowels "aeiou"
            v      }      # for y in vowels:
             =            #   print the last verse without removing it from the stack
              žM          #   push the vowels
                yÞ        #   the infinite list of the vowel y
                  ‡       #   replace every vowel with y
                    ?     # print the last verse without a trailing newline

```

---

more obfuscated and a lot slower 52-byter:

```
•nöðrb•ØTz… ,
«ÅвJT.•ý‹¨ΣªßˆTδ}vØ#•.ª'x¡‡žMv=žMyÞ‡}?

```

Don’t try it online!

```
•nöðrb•              # push compressed integer 211262272027
       Ø             # push the 211262272028th prime 5996494318979 (slow)
        Tz           # push 1/10
          … ,\n      # push string " ,\n"
               «     # concatenate to "0.1 ,\n"
                Åв   # convert the prime into that custom base
                  J  # join from list of chars into a string
                     # this generates the same string as T"ÿ, 0, 0.\nÿ,\n0.\n" above

```
> 13 votes

# Answer
# Ruby 2.7, ~~110~~ ~~105~~ 104 bytes

*Saved five bytes, thanks to Dingus!*
*Saved a byte using Arnauld's finding.*

```
puts z="#{y="Priletela #{$x='muha na zid'},"} #$x, #$x.
#{y}
#$x.","aeiou".chars.map{z.gsub /[aeiu]/,_1}

```

Try it online!

TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves two bytes.
> 8 votes

# Answer
# JavaScript (ES6),  ~~121~~  120 bytes

```
_=>["$&",..."aeiou"].map(v=>`${p=`Priletela ${q='muha na zid'},`} ${q}, ${q}.
${p}
${q}.`.replace(/[aeiu]/g,v)).join`

`

```

Try it online!

### Commented

```
_ =>                            // anonymous function ignoring its input
 [                              //
    "$&",                       // 1st stanza: use "$&" to leave the vowels unchanged
    ..."aeiou"                  // next ones: force all vowels to "a", "e", ..., "u"
  ]                             //
  .map(v =>                     // for each replacement pattern v:
    `${                         //   build the stanza template
      p = `Priletela ${         //     by defining p = "Priletela muha na zid,"
        q = 'muha na zid'       //     and q = "muha na zid"
      },`                       //
    } ${q}, ${q}.\n${p}\n${q}.` //     and using them to build the other parts
    .replace(                   //   update the template:
      /[aeiu]/g,                //     replace each vowel ...
      v                         //     ... with the replacement pattern
                                //     NB: there's no "o" in the template
    )                           //   end of replace()
  ).join`\n\n`                  // join with two line-feeds

```
> 6 votes

# Answer
# Python 2, 122 bytes

```
s="Priletela muha na zid,"
v="aeiou_"
for x in v:
 w=s[10:-1]+".\n";print s,s[10:],w+s+"\n"+w
 for y in v:s=s.replace(y,x)

```

Try it online!
> 6 votes

# Answer
# Wolfram Language (Mathematica), ~~146~~ 134 bytes

```
w="muha na zid";a="Priletela ";s=""<>{a,w,", ",w,", ",w,".
",a,w,",
",w,"."};c=Characters@"aeiou";s<>(StringReplace["

"<>s,c->#]&/@c)

```

Try it online!
> 5 votes

# Answer
# Bash \+ sed, 98 bytes

```
sed -ney/{%/\\n,eiu/aaa,a/e,e/i,i/o,o/u}/\;p<<<"${x=Priletela ${y=muha na zid}}, $y, $y.%$x,%$y.%"

```

Try it online!
> 4 votes

# Answer
# Jelly, 62 bytes

```
3,2µ“muha na zid”Wẋjị⁾ ¶ṭ”,Ɗ⁶;“!b^ṙzḳ“)»j)Y
ØẹµØẹW;y¢)¢W¤;j⁾¶¶

```

Try it online!

## Explanation

```
3,2µ“muha na zid”Wẋjị⁾ ¶ṭ”,Ɗ⁶;“!b^ṙzḳ“)»j)Y   Auxiliary niladic link
3,2                                           [3, 2]
   µ                                     )    For each:
    “muha na zid”W                              ["muha na zid"]
                  ẋ                             Repeat that many times
                   j       Ɗ                    Join with:
                    ị⁾ ¶                          Index with the number into " \n"
                        ṭ”,                       Append that to ","
                            ⁶;                  Prepend a space
                              “!b^ṙzḳ“)»j       Join ["Priletela", "."] with this
                                          Y   Join with a newline

ØẹµØẹW;y¢)¢W¤;j⁾¶¶   Main niladic link
Øẹ                   "aeiou"
  µ      )           For each:
   ØẹW                 ["aeiou"]
      ;                Append the vowel
       y¢              Translate the result of the previous link with this table
          ¢W¤;       Prepend list with result of previous link
              j⁾¶¶   Join with double newlines

```
> 3 votes

# Answer
For a start, this is my attempt in Javascript:

# JavaScript (Node.js), 184 bytes

```
a='aeiou'
x='muha na zid'
y='Priletela'
z=`${y} ${x}, ${x}, ${x}.\n${y} ${x},\n${x}.`
console.log([z].concat(a.split('').map(e=>z.replace(new RegExp('['+a+']', "g"), e))).join('\n\n'))

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 84 bytes

```
.•bKÜ2TÐhrŒ°•'b.•[÷‚rµ₃•™:'c.•AΩJεмF‚•:…fgj…,.
‡DžMŽh’‡1'a‡D'a'e‡D'e'i‡D'i'o‡D'o'u‡»

```

Try it online!
> 2 votes

# Answer
# Red, 150 bytes

```
e: rejoin[a:"Priletela "b:"muha na zid"c:", "b c b d:".^/"a b c"^/"b d]v:
charset w:"aeiou"foreach u w[print e parse e[any[change v u | skip]]]print e

```

Try it online!
> 2 votes

# Answer
# Perl 5 (`-0777p`), 91 bytes

```
s//Priletela muha na zid/;/ /;$_.=", $', $'.
$_,
$'.
";for$i(a,e,i,o,u){say;s/[aeiou]/$i/g}

```

Try it online!
> 2 votes

# Answer
# Jelly, 58 bytes

I feel like `”u”aØẹe?ṙ1Øẹ,y` could be golfed

```
”u”aØẹe?ṙ1Øẹ,y
820Dṃ“!b^ṙzḳ“¢ʋỴM$ƊEⱮ/¥ɦ8»K€YF”.0,48¦ÇƬj⁾¶¶

```

**Try it online!**
> 2 votes

# Answer
# C (gcc), ~~154~~ ~~152~~ 146 bytes

I wrote nonprintables that won't show up on SE in hex using `<kbd>`.

```
i,p[]=L"muha na zid`0x00`Priletela ";main(){for(;i<48;p["`0x14``0x12``0x10``0x0e``0x09``0x06``0x03``0x01`"[i%8]]="aeiou"[i++/8])i%8?:printf("%S%S, %2$S, %2$S.\n%1$S%2$S,\n%2$S.\n\n",p+12,p);}

```

Try it online!

```
#include <stdio.h>

int main(void)
{
    // These are merged together with a raw null byte in the golfed code.
    // I set them to wchar_t (L"") solely because of implicit int, cuz screw
    // Windows and its UTF-16. :P
    char pril[] = "Priletela"; // golfed code has trailing space
    char muha[] = "muha na zid";
    // The golfed code does a different loop pattern where it does one big
    // loop which replaces a char each iteration and prints when i%8==0.
    // However, that is difficult to follow.
    for (int i = 0; i < 6; i++) {
        // Note: golfed code doesn't use positionals on the first two arguments,
        // and it uses %S because they are wchar_t strings.
        //
        // Priletela muha na zid, muha na zid, muha na zid.
        // %1$s      %2$s       , %2$s       , %2$s       .\n
        // Priletela muha na zid,
        // %1$s      %2$s       ,\n
        // muha na zid.
        // %2$s       .\n\n
        printf("%1$s %2$s, %2$s, %2$s.\n%1$s %2$s,\n%2$s\n\n", pril, muha);

        // Replace the vowels one by one.
        // The golfed version loops 8 times since it is one string.
        for (int j = 0; j < 4; j++) {
            // Nope, never y.
            const char vowels[] = "aeiou";
            // Vowel indexes. This is encoded in a binary string in the golfed
            // code, and it is one array because the strings are merged.
            const int pril_lut[] = { 2, 4, 6, 8 };
            const int muha_lut[] = { 1, 3, 6, 9 };
            pril[pril_lut[j]] = vowels[i];
            muha[muha_lut[j]] = vowels[i];
        }
    }
}

```

~~Unless we find a way to kill the printf string, I don't see any other options to make this smaller.~~ I have clearly been proven wrong more than once. :P

-2 bytes thanks to ceilingcat for better variable declaration and looping backwards.

-6 bytes thanks to gastropner for ~~making me eat my words~~ combining the two for loops.
> 2 votes

# Answer
# Vim, 95 bytes

```
iPriletela<esc>3a muha na zid,<esc>r.Ypo<esc>k7f r
k4f Dk4YGoaeiou<esc>:s/./&<C-r>0/g
5Gqrx:,+2s/[aeiu]/<C-r>"/g
2jq4@r

```

Try it online!

This approach leaves two blank lines at the end of the song. If that's not acceptable, add `Vkd` to the end for +3 bytes: Try it online!

### Explanation

```
iPriletela<esc>3a muha na zid,<esc>r.

```

Insert `Priletela`; then append three copies of  `muha na zid,` and replace the last comma with a period.

```
Ypo<esc>

```

Duplicate the line and insert a blank line below the second copy.

```
k7f r<cr>k4f D

```

Replace the seventh space on the second line with a newline. Go back up to the second line and delete from the fourth space to the end of the line. We now have the first verse of the song.

```
k4YGoaeiou<esc>

```

Go up to the first line and yank all four lines. Then insert `aeiou` after the last line.

```
:s/./&<C-r>0/g

```

Replace each letter of `aeiou` with itself followed by the yanked lyrics.

```
5Gqr

```

Go to line 5 (the start of the second verse) and begin recording into macro `r`.

```
x

```

Delete the first character, which is the `a` prepended to the verse.

```
:,+2s/[aeiu]/<C-r>"/g

```

Within this line and the next two (i.e. this verse), replace any of `aeiu` with the character we just deleted.

```
2jq

```

Go down two lines to the start of the next verse. Stop recording the macro.

```
4@r

```

Run the macro four more times, converting the four remaining verses.
> 2 votes

# Answer
# PHP 8, ~~170~~ 166 bytes

This is the JavaScript solution of @jgosar rewritten in PHP and improved.

```
$a='aeiou';$x='muha na zid';$y="Priletela $x,";echo implode("

",array_merge([$z="$y $x, $x.
$y
$x."],array_map(fn($e)=>preg_replace("/[$a]/",$e,$z),str_split($a))));

```

The code is not wrapped on multiple lines for readability but because this way a real newline character embedded in a string uses only one byte vs. two bytes used by the escape sequence `\n`.

Try it online!
> 1 votes

# Answer
# Retina, 70 bytes

```

Pm, m, m.¶Pm,¶m.¶
P
Priletela
m
muha na zid
~(K`vaeiou
L$`.
\T`vo`$&

```

Try it online! Explanation:

```

Pm, m, m.¶Pm,¶m.¶

```

Insert placeholders for the first verse.

```
P
Priletela
m
muha na zid

```

Expand the placeholders.

```
~(`

```

Compose and execute a Retina script.

```
K`vaeiou

```

Create a list of transliteration targets.

```
L$`.
\T`vo`$&

```

Expand each target into a transliteration command that transliterates vowels into the given target and outputs the verse after the transliteration. The resulting script is as follows:

```
\T`vo`v
\T`vo`a
\T`vo`e
\T`vo`i
\T`vo`o
\T`vo`u

```

Here the `v` represents the vowels `aeiou`. The `o` on its own usually means "insert the other set", however this has no effect on the transliteration as the vowels are already present. The exception is the `T`vo`o` command, where the presence of `o` on both sides causes it to be treated as a literal, although this does not affect the expansion either.
> 1 votes

# Answer
# Lua, 150 bytes

Just because Lua doesn't get enough love.

```
a='aeiou'for i=0,5 do print((('pm, m, m.\npm,\nm.\n'):gsub('p','Priletela '):gsub('m','muha
na zid'):gsub('['..(i>0 and a or'_')..']',a:sub(i,i))))end

```

:gsub():gsub():gsub() :-)
> 1 votes

# Answer
# Java (JDK), 161 bytes

```
v->{for(var s:"$0,a,e,i,o,u".split(","))System.out.print(s.format("%s%s, %2$s, %2$s.%n%1$s%2$s,%n%2$s.%n%n","Priletela ","muha na zid").replaceAll("[aeiu]",s));}

```

Try it online!

## Credits
> 1 votes

# Answer
# PHP 7.4, 164 bytes

This is the same as my solution for PHP 8 but it does not surround the value of `$a` (`aeiou`) in apostrophes or quotes and saves 2 bytes. This exploits the fact that before PHP 8, the undefined constants were reported as warning and converted to strings. This behaviour changed in PHP 8, they are now reported as errors and the code does not work any more.

```
$a=aeiou;$x='muha na zid';$y="Priletela $x,";echo implode("

",array_merge([$z="$y $x, $x.
$y
$x."],array_map(fn($e)=>preg_replace("/[$a]/",$e,$z),str_split($a))));

```

In order to hide the warnings, the option `-d error_reporting=0` needs to be added to the command line (or set in `php.ini`).
> 0 votes

# Answer
# Pyth, 76 bytes

```
Ac." zMzÊ(ºZ¾þXGÈ-gÚe¿P"\qJ", "K+\.b
=s[GHJHJHKGH\,bHK)V=d"aeiou":G++\[d\]N

```

Try it online!

---

Python 3.8 translation:

```
import re
b = "\n"

[G, H] = "Priletela qmuha na zid".split("q")
J = ", "
K = "." + b
print(G := "".join([G,H,J,H,J,H,K,G,H,",",b,H,K]))
for N in (d := "aeiou"):
    print(re.sub("[" + d + "]", N, G))

```
> 0 votes

# Answer
# Python 3.8 (pre-release), 138 bytes

```
s="Priletela muha na zid, "
v="aeiou_"
n='\n'
print(n.join([[s+s[10:]+(w:=s[10:-2]+n)+s+n+w,[s:=s.replace(y,x)for y in v]][0]for x in v]))

```

Try it online!

Modified version of answer by xnor using list comprehension. It is not shorter, but it has fewer lines, so I thought I'd post it.
> 0 votes

# Answer
# Vyxal `j`, 68 bytes

```
1→a`10, 0, 0.
10,
0.`₀
«ƛ&…-∪⋎5wµ\Ė⌊ɾ≤«¡\x€Ŀ£¥kV⇩(←a›→a ¥nkV⇩←a iV)W

```

Try it Online!
> 0 votes

# Answer
# JavaScript, 137 bytes

```
o="";for(v of ["$&",..."aeiou"])for(c of`12, 2, 2.
12,
2.

`)o+=+c?[,"Priletela ","muha na zid"][c].replace(/[aeiu]/g,v):c;console.log(o)

```

Try it Online!

## Explanation:

```
o="";                              // Define o
  for(v of ["$&",..."aeiou"])      // Repeat for each vowel + $&
                                      being the RegExp returned value.
    for(c of`12, 2, 2.             // Numeric values will be replaced later on
    12,
    2.

    `)
      o+=                          // Add at the end of o...
        +c?                        // ...if c is numeric (NaN being falsey):
          [,"Priletela ",          // replace it by the index of the array...
          "muha na zid"][c]
            .replace(/[aeiu]/g,v)  // ...and replace every vowel by the current
                                      vovel (or $& which doesn't affect it)
              :c;                  // otherwise, add c
                console.log(o)     // Finally, output o

```
> 0 votes

---
Tags: code-golf, string, kolmogorov-complexity
---


title: Joe Mama or Joe Biden

text:
# Question
Title: Joe Mama or Joe Biden
# Your task

Randomly pick and print "Joe Mama" or "Joe Biden" in as little bytes as possible.

## Rules

* No trailing lines, spaces, or anything else weird like that
* No election fraud! Both "Joe Mama" and "Joe Biden" must have equal chaces of winning

## Prize

The winner will get a spot in https://github.com/Sid220/joe-mama-or-joe-biden, even if that language is already there.

## Example (not code golfed)

```
var joe = Math.random() < 0.5;

if (joe <= 0.5){
  joe = true;
} else{
  joe = false;
}

if (joe == true) {
console.log('Joe Mama');
} else {
  console.log('Joe Biden');
}
```

# Answer
> 5 votes
# HTML/Javascript ~~61~~ ~~60~~ ~~58~~ 49 bytes

```
<script>alert('Joe '+(new Date%2?"Mama":"Biden"))
```
-9 thanks to Makonede (and me being dumb)
-2 thanks to Unmitigated

## HTML/Javascript, 60 bytes

```
<script>alert('Joe '+(new Date()%2?"Mama":"Biden"))</script>

```

-1 thanks to Redwolf Programs

## HTML/Javascript, 61 bytes

```
<script>alert('Joe '+["Mama","Biden"][new Date()%2])</script>

```

Haven't ever submitted anything before so not sure if I did it right

# Answer
> 5 votes
# Vyxal, ~~18~~ ~~17~~ 16 bytes

```
‛ɾ∷«W≤ḂΠǔ«½ǐ℅"Ṅ₴

```

Try it Online!

Explanation:

```
‛ɾ∷               # "Joe"
   «W≤ḂΠǔ«        # "bidenmama"
          ½       # Split in half
           ǐ      # Title Case
            ℅     # Random choice
             "    # Wrap with "Joe"
              Ṅ   # Join by space
               ₴  # Print without newline

```

If trailing newlines were allowed, this could be ~~14~~ 13 bytes: Try it Online!

# Answer
> 1 votes
# PHP, 27 bytes

```
Joe <?=time()%2?Biden:Mama;

```

Try it online!

Not that bad for good ole PHP

NOTE: I kinda disapprove political tones in code golf. If you use my answer in the Git, please do not cite my name

# Answer
> 0 votes
# 05AB1E, 18 bytes

```
'›¸.•GŠ‰[öÂ•#Ωðý™?

```

Could be 1 byte less if trailing newlines are allowed by removing the trailing `?`.

Try it online.

**Explanation:**

```
'›¸                '# Push dictionary string "joe"
   .•GŠ‰[öÂ•        # Push compressed string "biden mama"
                    # Split it on spaces: ["biden","mama"]
             Ω      # Pop and push a random item from this pair
              ðý    # Join the stack with newline delimiter
                ™   # Titlecase each word
                 ?  # Print it without trailing newline

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*) to understand why `'›¸` is `"joe"` and `.•GŠ‰[öÂ•` is `"biden mama"`.

# Answer
> 0 votes
# Gol\>\<\>, 29 bytes

```
x"amaM eoJ"H>
>"nediB eoJ"H
V

```

Try it online!

# Answer
> 0 votes
# MathGolf, 18 bytes

```
ùJoe ûma∞╕╘Ç'n+αwδ

```

Try it online.

**Explanation:**

```
ùJoe               # Push string "Joe"
                   # Push a space character " "
     ûma           # Push string "ma"
        ∞          # Double it to "mama"
         ╕╘Ç       # Push compressed string "bide"
            'n+   '# "Append an "n": "biden"
               α   # Pair the top two values: ["mama","biden"]
                w  # Pop and push a random item
                 δ # Titlecase it
                   # (after which the entire stack joined together is output
                   # implicitly as result)

```

# Answer
> 0 votes
# Charcoal, 16 bytes

```
Joe ‽⪪BidenMama⁵

```

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

```
Joe                 Literal string `Joe `
                    Implicitly print
      BidenMama     Literal string `BidenMama`
     ⪪         ⁵    Split into substrings of length 5
    ‽               Random choice of substring
                    Implicitly print

```

# Answer
> 0 votes
# Retina, 22 bytes

```

Biden
?)`
Mama
^
Joe

```

Try it online! Explanation:

```

Biden

```

Replace the empty input with `Biden`.

```

Mama

```

Replace the empty input with `Mama`.

```
?)`

```

Random choice of one of the two replacements.

```
^
Joe

```

Prefix `Joe`  to the above.

# Answer
> 0 votes
## Batch, 76 bytes

```
@set/ar=%random%%%2
@if %r%==1 (set/p=Joe Biden<nul)else set/p=Joe Mama<nul

```

Alternative approach, also 76 bytes:

```
@set/ar=%random%%%2
@set s=Mama
@if %r%==1 set s=Biden
@set/p=Joe %s%<nul

```

Explanation:

```
@set/ar=%random%%%2

```

Set `r` equal to either `0` or `1` with equal probability.

```
@set s=Mama

```

Set `s` equal to `Mama`.

```
@if %r%==1 set s=Biden

```

But if `r` is `1`, then change `s` to `Biden`.

```
@set/p=Joe %s%<nul

```

Output `s` prefixed by `Joe` and without a trailing newline.

# Answer
> -1 votes
# Python 2, 57 bytes

```
import time
print"Joe "+["Mama","Biden"][time.time()%2<1]

```

Try it online!

# Python 3, 66 bytes

```
import time
print("Joe "+["Mama","Biden"][time.time()%2<1],end='')

```

Try it online!

Assuming no new trailing whitespace allowed

# Answer
> -1 votes
# Python 2, 63 bytes

```
from random import*
print"Joe "+["Mama","Biden"][randint(0,1)],

```

Try it online!

# Answer
> -1 votes
# JavaScript (V8), 46 bytes

```
print(Math.random()<.5?"Joe Mama":"Joe Biden")

```

Try it online!

Good catch of AlanBagel and 2 byte save by arnauld

# JavaScript (V8), 54 bytes

```
console.log("Joe "+(Math.random()<0.5?"Mama":"Biden"))

```

Try it online!

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


# Question
Title: Product over exclusive and inclusive ranges
Inspired by this question by @CᴏɴᴏʀO'Bʀɪᴇɴ.

Taken from the question:

> Your task is simple: given two integers a and b, output ∏\[a,b\]; that is, the product of the range between a and b. You may take a and b in any reasonable format, whether that be arguments to a function, a list input, STDIN, et cetera. You may output in any reasonable format, such as a return value (for functions) or STDOUT. a will always be less than b.
>
> Note that the end may be exclusive or inclusive of b. I'm not picky. ^\_^

The difference for this challenge is we are going to be picky about the range type. Input is a string of the form `[a,b]`, `(a,b]`, `[a,b)`, or `(a,b)` where a `[]` is an inclusive boundary and `()` is an exclusive boundary. Given the explicit boundaries, provide the product of the range. Also the input range will always include at least 1 number, meaning ranges like `(3,4)` are invalid and need not be tested.

## Test cases

```
[a,b) => result
[2,5) => 24
[5,10) => 15120
[-4,3) => 0
[0,3) => 0
[-4,0) => 24

[a,b] => result
[2,5] => 120
[5,10] => 151200
[-4,3] => 0
[0,3] => 0
[-4,-1] => 24

(a,b] => result
(2,5] => 60
(5,10] => 30240
(-4,3] => 0
(0,3] => 6
(-4,-1] => -6

(a,b) => result
(2,5) => 12
(5,10) => 3024
(-4,3) => 0
(0,3) => 2
(-4,0) => -6

```

---

This is a , so the shortest program in bytes wins.

---

## Leaderboard

The Stack Snippet at the bottom of this post generates the catalog from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.

To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:

```
## Language Name, N bytes

```

where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:

```
## Ruby, <s>104</s> <s>101</s> 96 bytes

```

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:

```
## Perl, 43 + 2 (-p flag) = 45 bytes

```

You can also make the language name a link which will then show up in the snippet:

```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes

```

```
var QUESTION_ID=66285,OVERRIDE_USER=44713;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){return e.lang>s.lang?1:e.lang<s.lang?-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
> 10 votes
# LabVIEW, 38 LabVIEW Primitives

"slightly" modified, now sets the ranges by scanning for () and \[\] and adding the index to the numbers.

# Answer
> 8 votes
# Vyxal, ~~24~~, 18 bytes

```
₌≬k+iE₍ht‛(]f=+÷rΠ

```

Try it Online!

I'm actually really proud of this answer, because it uses the new modifier parsing of 2.6.

With syntax highlighting:

## Explained

```
₌≬k+iE₍ht‛(]f=+÷rΠ
₌                  # Apply the following to the same stack:
 ≬                 #   The next 3 elements as a single lambda, taking argument n:
  k+iE             #     eval(n[1:-1]) - the two numbers separated by a comma
₌                  #   and
      ₍ht          #   [n[0], n[-1]] - the range brackets
         ‛(]f=     # Does the first bracket equal "(" and does the last bracket equal "]" - this determines how much to offset the range; because the two numbers in the original input will be passed to Vyxal's range function which acts like python's range() function
              +    # add those offsets: an exclusive range start means the first number needs to be incremented because range() includes the first argument. an inclusive range start means the last number needs to be incremented because range() stops before the last argument.
               ÷r  # push the range between the two numbers + their offsets
                 Π # and take the product

```

# Answer
> 6 votes
## Minecraft 15w35a+, program size 638 total (see below)

Same as my answer here, but modified. Since Minecraft has no string input, I took the liberty of keeping scoreboard input. If that is a problem, consider this answer non-competitive.

This calculates `PI a,b` with inclusive / exclusive specified by the two levers. Input is given by using these two commands: `/scoreboard players set A A {num}` and `/scoreboard players set B A {num}`. Remember to use `/scoreboard objectives add A dummy` before input.

Scored using: `{program size} + ( 2 * {input command} ) + {scoreboard command} = 538 + ( 2 * 33 ) + 34 = 638`.

This code corresponds to the following psuedocode:

```
R = 1
T = A
loop:
  R *= A
  A += 1
  if A == B:
    if A.exclusive:
      R /= T
    if B.exclusive:
      R /= B
    print R
    end program

```

Download the world here.

# Answer
> 5 votes
## Python 2, 72 bytes

```
lambda s:reduce(int.__mul__,range(*eval(s[1:-1]+'+'+`']'in s`))[s<'[':])

```

To extract the numbers we evaluate `s[1:-1]`, the input string with ends removed, which gives a tuple. The idea is to get the `range` of this tuple and take the product.

```
lambda s:reduce(int.__mul__,range(*eval(s[1:-1]))

```

The fudging happens to adjust the endpoints. The upper endpoint is easy, just cut off the first element if the input starts with `(`, done as `[s<'[':]`.

The other endpoint is trickier. Python doesn't have a clean way to conditionally remove the last element of a list because `l[:0]` removes the whole thing. So, we do something weird. We modify the tuple string before it is evaluated to tack on the string `"+True"` or `"+False"` depending on whether s ends in `]` or `)`. The result is that something like `3,7` becomes either `3,7+False` which is `3,7`, or `3,7+True` which is `3,8`.

Alternate, prettier 72:

```
lambda s:eval("reduce(int.__mul__,range((s<'[')+%s+(']'in s)))"%s[1:-1])

```

# Answer
> 3 votes
# Julia 0.4, 75 bytes

```
s->prod((x=map(parse,split(s[2:end-1],",")))[1]+(s[1]<41):x[2]-(s[end]<42))

```

Try it online!

This is an anonymous function that accepts a string and returns an integer. To call it, give it a name, e.g. `f=s->...`.

Ungolfed:

```
function f(s::AbstractString)
    # Extract the numbers in the input
    x = map(parse, split(s[2:end-1], ","))

    # Construct a range, incrementing or decrementing the endpoints
    # based on the ASCII value of the surrounding bracket
    r = x[1]+(s[1] == 40):x[2]-(s[end] == 41)

    # Return the product over the range
    return prod(r)
end

```

# Answer
> 3 votes
# Pyth, 20 bytes

```
*FPW}\)ztW}\(z}FvtPz

```

Try it online: Demonstration or Test Suite

### Explanation:

```
*FPW}\)ztW}\(z}FvtPz   implicit: z = input string
                 tPz   remove the first and last character of z
                v      evaluate, returns a tuple of numbers
              }F       inclusive range
        tW             remove the first number, if
          }\(z            "(" in z
  PW                   remove the last number, if
    }\)z                  ")" in z
*F                     compute the product of the remaining numbers

```

# Answer
> 3 votes
# Ruby, ~~79~~ 77 bytes

```
->s{a,b=s.scan /\-?\d+/;(a.to_i+(s[?[]?0:1)..b.to_i-(s[?]]?0:1)).reduce 1,:*}

```

**~~79 bytes~~**

```
->s{a,b=s.scan(/\-?\d+/).map &:to_i;((s[?[]?a:a+1)..(s[?]]?b:b-1)).reduce 1,:*}

```

**Ungolfed:**

```
-> s {
  a,b=s.scan /\-?\d+/    # Extracts integers from the input string, s
  (
    a.to_i+(s[?[]?0:1).. # Increase start of the range by 1 if s contains `(`
    b.to_i-(s[?]]?0:1)   # Decrease end of the range by 1 if s contains `)`
  ).reduce 1,:*
}

```

**Usage:**

```
->s{a,b=s.scan /\-?\d+/;(a.to_i+(s[?[]?0:1)..b.to_i-(s[?]]?0:1)).reduce 1,:*}["(2,5]"]
=> 60

```

# Answer
> 3 votes
## Seriously, 31 bytes

```
,#d@p@',@s`εj≈`Mi(@)']=+)'(=+xπ

```

Takes input as a string (wrapped in double quotes)

Try it online (input must be manually entered)

Explanation:

```
,#d@p@                             get input, take first and last character off and push them individually
      ',@s`εj≈`Mi                  split on commas, map: join on empty, cast to int; explode list
                 (@)']=+)'(=+      increment start and end if braces are ( and ] respectively (since range does [a,b))
                             xπ    make range, push product

```

# Answer
> 3 votes
# JavaScript (ES6), 68 bytes

```
s=>(f=_=>a>b||a++*f())([a,b,c]=s.match(/-?\d+|]/g),a-=-(s<'['),b-=!c)

```

# Answer
> 2 votes
# Python 3, 104

```
y,r=input().split(',')
t=int(y[1:])+(y[0]<')')
for x in range(t+1,int(r[:-1])+(r[-1]>'[')):t*=x
print(t)

```

Takes input from stdin.

# Answer
> 2 votes
# MATLAB, ~~86~~ 70 bytes

```
s=sscanf(input(''),'%c%d,%d%c');a=s<42;disp(prod(a(1)+s(2):s(3)-a(4)))

```

This also works with **Octave**. You can try online here. I have added the code as a script to that workspace, so you can just enter `productRange` at the prompt, then enter your input, e.g. `'(2,5]'`.

---

So the code first scans the input to extract the brackets and the numbers together:

```
s=sscanf(input(''),'%c%d,%d%c');

```

This returns an array which is made of `[bracket, number, number, bracket]`.

The array is compared with `42`, actually any number between 42 and 90 inclusive will do. This determines which sort of bracket it was, giving a 1 if it is an exclusive bracket, and a 0 if an inclusive bracket.

```
a=s<42;

```

Finally, we display the product of the required range:

```
disp(prod(a(1)+s(2):s(3)-a(4)))

```

The product is of numbers staring with the first number `s(2)` plus the first bracket type `a(1)` (which is a 1 if an exclusive bracket), ranging up to and including the second number `s(3)` minus the second bracket type `a(4)`. This gives the correct inclusive/exclusive range.

# Answer
> 2 votes
# PowerShell, ~~146~~ 104 Bytes

```
param($i)$a,$b=$i.trim("[]()")-split',';($a,(1+$a))[$i[0]-eq'(']..($b,(+$b-1))[$i[-1]-eq')']-join'*'|iex

```

Golfed off 42 bytes by changing how the numbers are extracted from the input. Woo!

```
param($i)                          # Takes input string as $i
$a,$b=$i.trim("[]()")-split','     # Trims the []() off $i, splits on comma,
                                   # stores the left in $a and the right in $b

($a,(1+$a))[$i[0]-eq'(']..($b,(+$b-1))[$i[-1]-eq')']-join'*'|iex
# Index into a dynamic array of either $a or $a+1 depending upon if the first
# character of our input string is a ( or not
# .. ranges that together with
# The same thing applied to $b, depending if the last character is ) or not
# Then that's joined with asterisks before
# Being executed (i.e., eval'd)

```

# Answer
> 2 votes
# Perl 6, 60 bytes

```
{s/\((\-?\d+)/[$0^/;s/(\-?\d+)\)/^$0]/;s/\,/../;[*] EVAL $_}

```

There is a bit of mis-match because the way you would write the `(2,5]` example in Perl 6 would be `2^..5` (`[2^..5]` also works).
So I have to swap `(2` with `[2^`, and `,` with `..`, then I have to `EVAL` it into a Range.

---

usage:

```
# give it a name
my &code = {...}

# the `$ =` is so that it gets a scalar instead of a constant

say code $ = '(2,5)'; # 12
say code $ = '[2,5)'; # 24
say code $ = '(2,5]'; # 60
say code $ = '[2,5]'; # 120

say code $ = '(-4,0)' # -6
say code $ = '[-4,0)' # 24
say code $ = '(-4,0]' # 0
say code $ = '[-4,0]' # 0

say code $ = '(-4,-1)' # 6
say code $ = '[-4,-1)' # -24
say code $ = '(-4,-1]' # -6
say code $ = '[-4,-1]' # 24

# this is perfectly cromulent,
# as it returns the identity of `*`
say code $ = '(3,4)'; # 1

```

# Answer
> 2 votes
## Mathematica, 128 bytes

```
1##&@@Range[(t=ToExpression)[""<>Rest@#]+Boole[#[[1]]=="("],t[""<>Most@#2]-Boole[Last@#2==")"]]&@@Characters/@#~StringSplit~","&

```

This is too long... Currently thinking about a `StringReplace` \+ `RegularExpression` solution.

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

```
s=>eval(`for(n=s.match(/-*\\d+/g),i=n[0],c=s[0]<"["||i;++i<+n[1]+(s.slice(-1)>")");)c*=i`)

```

## Explanation

```
s=>
  eval(`                    // use eval to allow for loop without return or {}
    for(
      n=s.match(/-*\\d+/g), // n = array of input numbers [ a, b ]
      i=n[0],               // i = current number to multiply the result by
      c=s[0]<"["||i;        // c = result, initialise to a if inclusive else 1
      ++i<+n[1]             // iterate from a to b
        +(s.slice(-1)>")"); // if the end is inclusive, increment 1 more time
    )
      c*=i                  // multiply result
  `)                        // implicit: return c

```

## Test

```
var solution = s=>eval(`for(n=s.match(/-*\\d+/g),i=n[0],c=s[0]<"["||i;++i<+n[1]+(s.slice(-1)>")");)c*=i`)
```

```
<input type="text" id="input" value="(5,10]" />
<button onclick="result.textContent=solution(input.value)">Go</button>
<pre id="result"></pre>
```

# Answer
> 2 votes
# TI-Basic, 69 bytes

```
Input Str1
expr("{"+sub(Str1,2,length(Str1)-2
prod(randIntNoRep(min(Ans)+(sub(Str1,1,1)="("),max(Ans)-(sub(Str1,length(Str1),1)=")

```

Output is stored in `Ans` and displayed. Replace `randIntNoRep(` with `seq(I,I,` (+3 bytes) if the calculator does not support it.

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

```
1##&@@ToExpression["Range"<>(#/."("->"[1+"/.")"->"-1]")]&

```

Try it online!

Input a list of characters.

Fairly straightforward. Mathematica uses `[` `]` to introduce arguments, and `Range` is inclusive on both ends.

---

### Wolfram Language (Mathematica), 69 bytes

```
1##&@@ToExpression["Range"<>#~StringReplace~{"("->"[1+",")"->"-1]"}]&

```

Try it online!

Input a string.

# Answer
> 1 votes
# Japt, ~~43~~ 41 bytes

```
[VW]=Uf"\\d+";ÂV+Â('A>Ug¹oÂW+Â('A<UtJ¹r*1

```

Try it online!

# Answer
> 1 votes
# R, ~~102~~ 104 bytes

```
f=function(s){x=scan(t=gsub('\\(|\\[|,|\\)|\\]',' ',s))+c(grepl('^\\(',s),-(grepl('\\)$',s)));prod(x[1]:x[2])}

```

Ungolfed

```
f=function(s){
    # remove delimiting punctuation from input string, parse and return an atomic vector
    x=scan(t=gsub('\\(|\\[|,|\\)|\\]',' ',s)) +
    # add /subtract from the range dependent on the `[)` pre/suf-fixes
    c(grepl('^\\(',s),-(grepl('\\)$',s)))
    # get the product of the appropriate range of numbers
    prod(x[1]:x[2])
}

```

edit to allow negative numbers \[at the expense of 2 more characters

# Answer
> 1 votes
# CJam, 34 bytes

```
r)\(@+"[()]"2/\.#\',/:i.+~1$-,f+:*

```

Try it online

Explanation:

```
r       Read input.
)       Split off last character.
\       Swap rest of input to top.
(       Split off first character.
@       Rotate last character to top.
+       Concatenate first and last character, which are the two braces.
"[()]"  Push string with all possible braces.
2/      Split it into start and end braces.
\       Swap braces from input to top.
.#      Apply find operator to vector elements, getting the position of each brace
        from input in corresponding list of possible braces. The lists of braces
        are ordered so that the position of each can be used as an offset for the
        start/end value of the interval.
\       Swap remaining input, which is a string with two numbers separated by
        a comma, to top.
',/     Split it at comma.
:i      Convert the two values from string to integer.
.+      Element-wise addition to add the offsets based on the brace types.
~       Unwrap the final start/end values for the interval.
1$      Copy start value to top.
-       Subtract it from end value.
,       Build 0-based list of values with correct length.
f+      Add the start value to all values.
:*      Reduce with multiplication.

```

# Answer
> 1 votes
# JavaScript (ES6), 79

As an anonymous method

```
r=>eval("[a,b,e]=r.match(/-?\\d+|.$/g);c=a-=-(r<'@');for(b-=e<'@';a++<b;)c*=a")

```

Test snippet

```
F=r=>eval("[a,b,e]=r.match(/-?\\d+|.$/g);c=a-=-(r<'@');for(b-=e<'@';a++<b;)c*=a")

// TEST
console.log=x=>O.innerHTML+=x+'\n'

;[
 ['[2,5)',24],['[5,10)',15120],['[-4,3)',0],['[0,3)',0],['[-4,0)',24],
 ['[2,5]',120],['[5,10]',151200],['[-4,3]',0],['[0,3]',0],['[-4,-1]',24],
 ['(2,5]',60],['(5,10]',30240],['(-4,3]',0],['(0,3]',6],['(-4,-1]',-6],
 ['(2,5)',12],['(5,10)',3024],['(-4,3)',0],['(0,3)',2],['(-4,0)',-6]
].forEach(t=>{
  r=F(t[0]),k=t[1],console.log(t[0]+' -> '+r+' (check '+k+ (k==r?' ok)':' fail)'))
})
```

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

# Answer
> 1 votes
# Japt, 25 bytes

Ugly as hell!

```
Å¯J q, rÈ°+Uø'()õY-Uø')Ã×

```

Try it (includes all test cases)

# Answer
> 1 votes
# Haskell, 94 bytes

```
f=(\(h:a,_:b)->product[a!h..init b!last b]).span(','/=);c!')'=c!' '-1;c!'('=c!' '+1;c!_=read c

```

Try it online!

# Answer
> 1 votes
# Julia 0.4, 64 bytes

```
s->prod((x=parse(s[2:end-1]).args)[]+(s[1]<41):x[2]-(s[end]<42))

```

Try it online!

Based on Alex A's answer

# Julia 1.0, 69 bytes

```
s->prod((:)(Meta.parse(s[2:end-1]).args+[s[1]<'*',-(s[end]<'*')]...))

```

Try it online!

# Answer
> 1 votes
# Pip, 20 bytes

```
$*VaR^"(][)"['U"+1"]

```

Replit! Or, verify all test cases with this 22-byte version in Pip Classic: Try it online!

### Explanation

Conveniently, `,` is Pip's range operator; it is inclusive on the lower end and exclusive on the upper end. So if we turn the brackets into appropriate tweaks to the numbers, we can use eval to generate the range.

```
$*VaR^"(][)"['U"+1"]
   aR                 In the input, replace each string in
      "(][)"           This string
     ^                 Split into a list of characters
                      with the corresponding string in
            [      ]  this list:
             'U        ( becomes U (increment the following number)
               "+1"    ] becomes +1 (add 1 to the preceding number)
                       [ and ) don't have a corresponding replacement, so they are
                       simply deleted (leaving the numbers unchanged)
  V                   Evaluate the result as a Pip expression
$*                    Fold on multiplication

```

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


title: Test if two numbers are equal

text:
# Question
Title: Test if two numbers are equal
## Challenge

* Input two integers.
    + Integer I/O must be decimal.
* If the integers are equal, output a truthy value.
* Otherwise, output a falsy value.

### Clarifications

* You will never receive non-integer inputs.
* You will never receive an input that is outside the bounds \[-2³¹, 2³¹).

## Rules

* Standard loopholes are disallowed.
* This is . Shortest answer wins, but will not be selected.

# Answer
> 18 votes
# Brachylog, 0 bytes

Try it online!

One number from STDIN and one from command-line arguments.

# Answer
> 17 votes
# brainfuck, ~~45~~ ~~49~~ ~~41~~ ~~37~~ 34 bytes

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

```

Try it online!

Takes the two integers separated by a single null byte. Null bytes are falsy in BF and everything else is truthy, so this prints a single 0x01 byte for truthy and a single 0x00 for falsy.

This is my first time golfing in BF, so feel free to give me suggestions...

### Explanation

```
,[>,]       Read in everything from STDIN until the null byte is reached
>+          Move one space to the right and increment; this will be a flag telling us
            the numbers are still equal
<<[<]>      Move back to the beginning of the input
[           For each character in the input:
  <,          Move to the left and input a character
  [->-<]      Subtract this char from the char at the same spot in the original number
  >[>]        If this is not zero (there is a difference between the two characters)
                move to the hole before the flag
  >           Move one character to the right
              If we're in the hole before the flag this moves us onto the flag;
              the loop runs once more and deposits us two spots to the right
]           Endwhile
            When the while loop finishes we will be one spot to the left of the flag
            or already to the right if the program found a difference between the numbers
            However: we will still be just to the left of the flag for cases like 24 vs 245
,           So we input another byte (the next digit of the second number or 0x00)
[>]         and move past the flag if it's non-zero
>.          Move right (onto the flag or past the flag) and output

```

# Answer
> 13 votes
# ///, 9 bytes

```
//f///t/f

```

Try it online!

Prints a t if they are equal, otherwise prints f.

Since there is no way to take input in ///, it is hard-coded.

```
/NUM1/f//NUM2/t/f

```

**Explanation:**

With example inputs of 12 and 121213. (Should return false.)

1. Input. `/12/f//121213/t/f`
2. Replace other occurrences of the first number with f. `/ff13/t/f`
3. Replace the modified new number with a t. Since the modified string is not f, , f stays the same. `f`.
4. Output. `f`.

With example inputs of 501 and 501. (Should return true.)

1. Input. `/501/f//501/t/f`
2. Replace other occurrences of the first number with f. `/f/t/f`
3. Replace the modified new number with a t. Since the modified string is f,f changes to `t`.
4. Output. `t`.

Credit to @user202729 for coming up with the better approach!

# Answer
> 7 votes
# yup, 16 bytes

I struggled to find an esolang where this was non-trivial (and that was not already covered). I present to you, this:

```
**-{0~-}0~-|0~-#

```

Try it online!

This works as follows:

```
**-{0~-}0~-|0~-#
**                  take two inputs on the stack
  -                 subtract them
   {0~-}0~-         this is "absolute value":
   {   }              while TOS is > 0
    0~-               this is negate:
    0                   push 0                 [TOS, 0]
     ~                  swap                   [0, TOS]
      -                 subtract               [-TOS]
                    thus, this negates positive numbers
        0~-         negate again to get a positive number
                    this maps equal numbers to `0` and unequal numbers to their
                    absolute differences
           |        take ln(TOS). This gives `-Infinity` for equal numbers, and
                    some value >= 0 for other numbers.
            0~-     negate. this gives Infinity for equal numbers, and a number <= 0
                    for unequal numbers
               #    output as number

```

Now, `{...}` is yup's loop and is the closest thing to a condition. It repeats the inside so long as the TOS is positive and defined. Thus, any negative or 0 value is falsey, and any positive value is truthy. Infinity is truthy, being greater than 0.

# Answer
> 6 votes
# Brain-Flak, 26 bytes

Straight from the wiki.
Please don't upvote trivial answers.

```
([{}]{})((){[()](<{}>)}{})

```

Try it online!

# Answer
> 5 votes
# Verbosity, ~~507~~ 503 bytes

```
Include<MetaFunctions>
Include<Output>
Include<Input>
Include<Integer>
Include<Boolean>
Input:DefineVariable<i; 0>
Output:DefineVariable<o; 0>
Boolean:DefineVariable<c; 0>
Integer:DefineVariable<a; Input:ReadEvaluatedLineFromInput<i>>
Integer:DefineVariable<b; Input:ReadEvaluatedLineFromInput<i>>
Boolean:DefineVariable<r; Boolean:ArgumentsAreEqual<c; a; b>>
Boolean:DefineVariable<q; Boolean:LogicalNot<c; r>>
Output:DisplayAsText<o; q>
DefineMain<> [
MetaFunctions:ExecuteScript<MetaFunctions@FILE>
]

```

Try it online!

Saved 4 bytes thanks to Mr. Xcoder

Haha, no-one shall lose to Verbosity! Outputs with a `Boolean<>` wrapper around the result. The `Boolean:LogicalNot` is required due to an ongoing bug with booleans.

The ungolfed version:

```
Include<MetaFunctions>
Include<Output>
Include<Input>
Include<Integer>
Include<Boolean>

Input:DefineVariable<STDIN; 0>
Output:DefineVariable<STDOUT; 0>
Boolean:DefineVariable<constant; 0>

Integer:DefineVariable<FirstInput; Input:ReadEvaluatedLineFromInput<STDIN>>
Integer:DefineVariable<SecondInput; Input:ReadEvaluatedLineFromInput<STDIN>>
Boolean:DefineVariable<result; Boolean:ArgumentsAreEqual<constant; FirstInput; SecondInput>>

Boolean:RedefineVariable<result; Boolean:LogicalNot<constant; result>>

Output:DisplayAsText<STDOUT; result>

DefineMain<> [
    MetaFunctions:ExecuteScript<MetaFunctions@FILE>
]

```

Try it online!

# Answer
> 4 votes
# Retina, 9 bytes

```
^(.+)¶\1$

```

Counts the number of times the first line matches the second.

Try it online!

# Answer
> 4 votes
# Python 3, 10 bytes

```
int.__eq__

```

Try it online!

# Answer
> 4 votes
## Retina, 5 bytes

Byte count assumes ISO 8859-1 encoding.

```
D`
¶$

```

Try it online!

### Explanation

```
D`

```

Deduplicate with the implicit regex `.+`, i.e. if the two lines are identical, clear the second one (the separating linefeed remains though).

```
¶$

```

Try to match a linefeed followed by the end of the string. This is only possible if the first stage cleared the second line, i.e. if the two numbers were equal.

# Answer
> 3 votes
# Japt, 2 bytes

```
¥V

```

Try it online

# Answer
> 3 votes
## Java, 41 36 12 bytes

-4 bytes thanks to @totallyhuman - Changed floats to ints

-1 byte by removing space between second method argument and comma.

-24 by converting the whole program to a lambda (woo).

```
(i,j)->i==j;

```

Takes the form of a java.util.function.BiFunction\< Boolean, Integer, Integer \> using an expression lambda.

# Answer
> 3 votes
# TI-BASIC, 13 bytes

```
Prompt A,B
If A=B
Disp 1
Else
Disp 0

```

Pretty self-explanatory. Prompts for two numbers and prints 1 if they are euqal, 0 otherwise.

# Answer
> 3 votes
# Cascade, ~~5~~ 4 bytes

```
#&
=

```

Turns out I didn't need the second `&` due to wrapping

Try it online!

# Answer
> 3 votes
# Flurry `-nin`, 134 bytes

```
<<>[(<<>()>)<<>[({}){}]>][<><<>[<>{{}}]()>]()()[<><<>()>]>({})[<><<>(){}>[()[<><<>()>]]]{{}{<{}{()[<>{}[<><<>()>]]}>}{{}(<>()){}}()}{}

```

### Run example

```
$ pgm="..." # the program above
$ ./flurry -nin -c $pgm 0 0
1
$ ./flurry -nin -c $pgm 123 45
0
$ ./flurry -nin -c $pgm 123 123
1

```

There is no task that is trivial in every language. Seriously.

Since Flurry's only representation of a number is Church numeral, this program takes only non-negative integers as input. Outputs 1 if two Church numerals represent the same number, 0 otherwise.

Implements the following function:

```
// (n+1-m) * (m+1-n), where a-b gives zero if a < b
// This gives 1 when m==n (both sides of * are 1)
// and 0 otherwise (one side is 0)
main = (\npm. <SK> (m p (succ n)) (n p (succ m))) n pred m

// succ n = n + 1
succ = S<SK>

// pred n = n - 1 (pred 0 = 0); implemented using pair construct
next-pair-helper = \fmn. f n (succ n) = \fm. S f succ = \f. K(S f succ)
= {()[<>{}[<><<>()>]]}
next-pair = \p. <p next-pair-helper>
= {<{}{()[<>{}[<><<>()>]]}>}
pred = \n. n next-pair zero-pair K
= {{}{<{}{()[<>{}[<><<>()>]]}>}{{}(<>()){}}()}

```

# Answer
> 2 votes
# Jelly, 1 byte

```
=

```

Try it online!

**Explanation:**

```
= Takes two arguments and returns a 1 if they are equal, and a 0 if they are not.
  Implicit print.

```

# Answer
> 2 votes
# Ohm, 1 byte

```
E

```

Try it online!

Because `=` is too mainstream.

# Answer
> 2 votes
# OCaml, 3 bytes

```
(=)

```

Brackets are necessary, plain `=` is a syntax error

# Answer
> 2 votes
# sed, 14 bytes

Includes +1 for `-r`

```
s/^(.+),\1$//

```

sed doesn't have truthy/falsy values, so I use the empty string as truty and everything else as falsy. This make sense because `/^$/` is the simplest (fully matching) if statement.

Try it online!

# Answer
> 2 votes
# Haskell, 4 bytes

```
(==)

```

Try it online! (The function has to be named)

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

```
x=>y=>!(x-y)

```

Because `0` is false and all other numbers are true in JavaScript, if `x-y` equals `0`, a not `!` of that `0` will return `true`, and a not `!` of any other number will return false. Two bytes longer than simple comparison `x==y` as shown in @Shaggy's answer.

# Answer
> 2 votes
## MSM, 31 bytes

```
'?ddF',',',.....T',',':'?....':

```

MSM is stack based, so the two input numbers are expected to be on top of the stack, i.e. on the right of the string. MSM has neither numbers nor booleans so we are free to choose a (reasonable) representation:

```
T      True
F      False
123    numbers are just sequences of ascii digits. There's no literal
       representation in MSM source code, so you have to construct them
       digit by digit:  321.. -> 123 (remember: . is concatenation)

```

TIO doesn't support MSM out of the box, so I've included the JS interpreter from the esolang page.

Try it online!

How it works: (I use `a` and `b` for the two numbers on the stack).

Excerpt from the MSM command reference:

```
'   quote, push next char on the stack, even if it is a command
?   skip next command if the two top elements of the stack are equal
,   drop
:   expand string at top of the stack and push each char of it on the stack
.   concatenate two top elements

everything else is pushed

```

Stack trace:

```
' ? d d F ' , ' , ' , . . . . . T ' , ' , ' : ' ? . . . . ' : a b
d d F ' , ' , ' , . . . . . T ' , ' , ' : ' ? . . . . ' : a b ?

```

The next 6 chars are pushed on the stack and concatenated with 5 dots

```
T ' , ' , ' : ' ? . . . . ' : a b ? ,,,Fdd

```

The next 5 chars are pushed on the stack and concatenated with 4 dots

```
' : a b ? ,,,Fdd ?:,,T

```

`:` and the two numbers are pushed

```
? ,,,Fdd ?:,,T : a b

```

Now it gets interesting. If the two numbers are equal, `,,,Fdd` is skipped

```
?:,,T : a b           -- ?:,,T as a whole is not a command, so it's pushed
: a b ?:,,T           -- expand
a b ? : , , T         -- push a b
? : , , T a b         -- a b are still equal, so skip :
, , T a b             -- drop a b
T                     -- MSM stops, output is True

```

If the two numbers are not equal, don't skip `,,,Fdd`, but push it:

```
,,,Fdd ?:,,T : a b
: a b ,,,Fdd ?:,,T    -- expand
a b ,,,Fdd ? : , , T  -- push up to ?
? : , , T a b ,,,Fdd  -- number b is never equal to ,,,Fdd so expand
, , T a b , , , F d d -- drop two dummy values
T a b , , , F         -- push T a b
, , , F T a b         -- drop b a T
F                     -- stop

```

# Answer
> 2 votes
# Cubix, 11 bytes

```
O0O1II-!//@

```

Try it online!

This was harder than expected. Outputs 0 for falsy and 10 for truthy.

# Answer
> 2 votes
# Hexagony, 20 bytes

-4 Bytes thanks to Jo King by using conditional wrapping.

```
?}?".@!\!.!_1/@_-<~.

```

Try it online!

More readable version:

```
   ? } ? "
  . @ ! \ !
 . ! _ 1 / @
_ - < ~ . . .
 . . . . . .
  . . . . .
   . . . .

```

Prints 0 for truthy and 1 for falsy.
There's a no-op at the end to keep it at a sidelength of 4.

It might be possible to reduce the sidelength by one and safe a few more bytes.

---

If I can print 0 for truthy and anything else for falsy, this would be a valid solution aswell:
```
  ? } ?
 / - ! @
" / . . .
 . . . .
  . . .

```

This is basically just subtraction and seems like cheating to me.

# Answer
> 2 votes
# Whitespace, 60 bytes

```
[S S S N
_Push_0][S N
S _Duplicate_0][S N
S _Duplicate_0][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][S S S T  N
_Push_1][S N
S _Duplicate_1][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve][T    S S T   _Subtract][N
T   S N
_If_0_Jump_to_Label_EQUAL][T    N
S T _Print_as_integer][N
N
N
_Exit_program][N
S S N
_Create_Label_EQUAL][S S S T    N
_Push_1][T  N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

Outputs `1`/`0` as truthy/falsey values. 3 bytes could be saved by removing `NNN` if `1`/`01` as truthy/falsey values are allowed.

**Pseudo-code:**

```
Integer i = STDIN as number
Integer j = STDIN as number
If(i == j):
  Call function EQUAL()
Print 0 to STDOUT
Exit program

function EQUAL:
  Print 1 to STDOUT
  Exit automatically with error

```

# Answer
> 2 votes
## Keg, 1 byte(SBCS on Keg wiki)

```
=

```

## Explanation:

```
=# Test whether they are equal

```

# Answer
> 2 votes
## Caboose, 24 bytes

```
print(input()==input());

```

TIO

# Answer
> 2 votes
# Flurry, 30 bytes

```
{}{{}{}}[{}{{{}}}[<>()]](){{}}

```

You can test it with the interpreter:

```
$ for i in {0..5}; do
$   for j in {0..5}; do
$     ./Flurry -nin -c '{}{{}{}}[{}{{{}}}[<>()]](){{}}' $i $j
$   done | xargs
$ done
1 0 0 0 0 0
0 1 0 0 0 0
0 0 1 0 0 0
0 0 0 1 0 0
0 0 0 0 1 0
0 0 0 0 0 1

```

In Flurry, popping from the stack returns the `I` combinator (`λa. a`), which also happens to be the Church numeral representation for the number 1. Thus we can compute `N != M` using the following method:

* Push 0 to the stack.
* Push 1 to the stack `N` times.
* Pop from the stack `M` times and ignore the value.
* Pop from the stack and return the value.

This is how the program works conceptually, but we can combine the first two steps and the second two steps using a few tricks.

* `{{}}` represents the `I` combinator (`1 = I = λa. a`).
* `{{{}}}` is a function that pushes its argument to the stack and returns the `I` combinator (`λa. (push a; λb. b)`)
* `[<>()]` represents zero (`0 = S K = λab. b`).
* By applying the input number to both of these terms, we obtain the expression `n{{{}}}[<>()]`, which has the following semantics:
    + If `n > 1`, push 0 to the stack, followed by `n - 1` ones, and return 1.
    + If `n = 0`, push nothing to the stack and return 0.
* `{{}{}}` is a function that takes an argument `a`, pops a value `b` from the stack, and returns `b<sup>a</sup>`. In this case, `a` and `b` are both guaranteed to be either zero or one, so it effectively returns `0` if `(a, b) == (1, 0)` and `1` otherwise.
* By applying the input number to this term, and to the result of the previous term, we obtain the expression `n {{}{}} [m {{{}}} 0]`, which has the following semantics:
    + If `m = 0`, `[m {{{}}} 0]` pushes nothing and returns 0. Since the stack is empty, `{{}{}}` always pops one, so its return value is always 1. Thus the entire expression is 0 if `n = 0` and 1 otherwise.
    + If `m > 0`, `[m {{{}}} 0]` pushes 0 followed by `n - 1` ones and returns 1. Thus `{{}{}}` always returns the value popped from the stack, and `n {{}{}} 1` pops `n` times and returns the last value popped. The entire expression is 0 if `n = m` and 1 otherwise.

The last step is to take the resulting number (representing whether the values are unequal) and negate it by applying it to `()` and `{{}}`.

# Answer
> 1 votes
# JavaScript (ES6), 10 bytes

```
x=>y=>x==y

```

# Answer
> 1 votes
# 05AB1E, 1 byte

```
Q

```

Try it online!

# Answer
> 1 votes
# Python 2, 15 bytes

```
lambda x,y:x==y

```

Try it online!

# Answer
> 1 votes
# Mathematica, 6 bytes

```
#==#2&

```

# Answer
> 1 votes
# Go, ~~36~~ 32 bytes

*-4 bytes thanks to powelles.*

```
func f(x,y int)bool{return x==y}

```

Try it online!

# Answer
> 1 votes
# Pyth, 2 bytes

```
qE

```

Try it here :)

# Answer
> 1 votes
# GolfScript, 2 bytes

```
~=

```

Try it online!

# Answer
> 1 votes
# Kotlin, ~~39~~ 30 bytes

```
fun f(x:Int,y:Int)=print(x==y)

```

Try it online!

# Answer
> 1 votes
# dc, ~~12~~ 9 bytes

```
[1]sF=F0+

```

Try it online!

# Answer
> 1 votes
## QBIC, 4 bytes

```
?:=:

```

This takes `a` and `b` in from the command line and prints `-1` when equal, `0` when not.

Alternative 4-byter

```
?:-:

```

This prints the result of subtracting `b` from `a` and gives 0 for equals, and any other value else-wise.

# Answer
> 1 votes
# Perl 6, 4 bytes

```
*==*

```

Try it

This creates a WhateverCode lambda, Each `*` represents a parameter

# Answer
> 1 votes
# 09D, 13 bytes

```
310310412D301

```

Outputs 1 if the values are equal, otherwise 0

### Explanation:

```
310310412D301
3                 Read..
 1                ..from I/O (STDIN)
  0               ..to stack
   310            Read 2nd input as above
      4           Apply math function...
       12D        ..isEqual, pop both items and push a 1
                     if they are equal, otherwise push a 0
          3       Read..
           0      ..from stack
            1     ..to I/O (STDOUT)

```

# Answer
> 1 votes
# Braingolf, 4 bytes

```
e1:0

```

Outputs 1 if inputs are equal, otherwise 0

### Explanation:

```
e1:0  Implicit input to stack
e     If last 2 items are equal..
 1    ..push 1 to stack
  :   else
   0  ..push 0 to stack
      Implicit endif
      Implicit output of last item on stack

```

# Answer
> 1 votes
# C, 20 bytes

```
f(a,b){return a==b;}

```

# Answer
> 1 votes
# Lua, 18 bytes

```
a,b=...print(a==b)

```

Try it online!

# Answer
> 1 votes
# Add++, 3 bytes

```
L,=

```

Try it online!

Yay for lambda functions!

# Answer
> 1 votes
# Decimal, 13 bytes

```
81D81D412D301

```

Pretty simple. Ungolfed:

```
81D  ; builtin - read INT to stack
81D  ; builtin - read INT to stack
412D ; compare for equality
301  ; print to STDOUT

```

Try it online!

# Answer
> 1 votes
# Triangular, 6 bytes

```
$.$%=<

```

Try it online!

Formats into this triangle:

```
  $
 . $
% = <

```

Commands executed (without no-ops or directionals): `$$=%`

Pretty simple.

* `$` \- read input as integer
* `=` \- compare top two stack values for equality
* `%` \- print result

# Answer
> 1 votes
# Cubically, ~~8~~ 5 bytes

```
$:$=%

```

Explanation:

```
$      read integer input
 :     set notepad to input
  $    read integer input
   =   compare notepad to input
    %  print notepad

```

Try it online!

# Answer
> 1 votes
# Triangularity, 17 bytes

```
..)..
.I)1.
I=...

```

Try it online!

# Triangularity, 17 bytes

```
..)..
.D@I.
sI=..

```

Try it online!

# Answer
> 1 votes
# Noether, 4 bytes

```
II=P

```

**Try it online!**

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

```
not(variance(Ans

```

Gives `{1}` as truthy value or `{0}` for falsy. -1 bytes thanks to lirtosiast!

# Answer
> 1 votes
# Python 2 - 15 bytes

`lambda a,b:a==b`

Like this:

```
def equality(a, b): Declare a function
    return a == b   Return True if equal, False if not

```

# Answer
> 1 votes
# PowerShell, 36 20 bytes

-16 bytes thanks to @mazzy (Basically their answer!)

```
!($args[0]-$args[1])

```

Try it online!

Simple. Takes arguments from commandline arguments.

# Answer
> 1 votes
# 1+, 10 bytes

```
."."\</<*:

```

This is likely to be ungolfed: tell me if there's a better approach.

**Explanation:**

First, I'll name the two input A and B.

`."."` pushes A, duplicate it, pushes B, duplicate it. So now the stack is: `A A B B`.

`\` rotates the stack, so the stack is now `B A A B`.

`</<*` Pushes `A <= B`, move it to the bottom of the stack, and pushes `B <= A`, then multiply them, as they are both boolean, this is equivalent to the `and` operation.

`:` Outputs the result.

# Answer
> 0 votes
# x86\_64 machine language on Linux, 8 bytes

```
0:   31 c0                   xor    %eax,%eax
2:   39 f7                   cmp    %esi,%edi
4:   0f 94 c0                sete   %al
7:   c3                      retq

```

Try it online!

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

```
=n;

```

Try it online!

Takes command line arguments.
I feel unclean posting an answer to this one..

# Answer
> 0 votes
# Clam, ~~5~~ 4 bytes

```
p:rr

```

## Explanation

```
p    - Print...
  r  - Next input
 :   - Equal to
   r - Next input

```

# Answer
> 0 votes
# C, 19 bytes

```
f(a,b){return a-b;}

```

Try it online!

# C, 18 bytes

```
#define f(a,b) a-b

```

Try it online!

"Truthy" value is 0 and "Falsy" value is anything but.

# Answer
> 0 votes
# APL (Dyalog Classic), ~~5~~ 1 bytes

```
=

```

Try it online!

My first APL answer!

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