title: Burning Bridges

text:
# Question
Title: Burning Bridges
***Note:*** *When I refer to a bridge, I mean it in the non-mathematical sense*

## Introduction

You are on a network of islands which are connected by wooden bridges and you want to see if you can burn every bridge in the island network. However, you can only burn a bridge once you've walked over it.

Once a bridge has been burned, it has gone and you cannot go back over it. None of the islands are connected.

Since you are going on a stroll, you cannot swim.

## Challenge

Given a list of the bridges and which islands they connect, output a truthy value if you can burn every bridge and falsey value if you cannot.

## Input

The input will be a list of numbers. A bridge is defined as:

```
X,Y

```

Where are X and Y are integers. Each bridge has an integer number which X and Y refer to.

For example,

```
2,6

```

Means that there is a bridge between the islands 2 and 6.

The input will be a list of these bridges:

```
2,6 8,1 8,2 6,1

```

You may take this a flat array, if you wish.

## Rules

The numbers for the islands will always be positive integers, `n`, where `0 < n < 10`. The island numbers will not always be contiguous.

When you walk over a bridge, you ***must*** burn it.

You will be given a maximum of eight islands. There is no limit on the number of bridges.

Island networks will always connect together. There will always be exactly one connected component.

This is an undirected network. For example, you can go either way across the bridge `1,2`.

## Examples

```
Input > Output
1,2 1,3 1,3 1,4 1,4 2,3 2,4 > Falsey
1,5 1,6 2,3 2,6 3,5 5,6 > Truthy
1,2 1,3 1,4 2,3 2,4 3,4 > Falsey
1,2 > Truthy

```

## Winning

Shortest code in bytes wins.

# Answer
# Python 2,  ~~102 92~~ 43 bytes (40 in Python 3)

Thanks to @Neil for reminding me that you can't have an odd number of vertices with odd degree – and saving 5 bytes.

```
lambda x:sum(x.count(a)%2for a in set(x))<3

```

Try it online!

You can cut it down to 40 bytes in Python 3 (thanks to @shooqie):

```
lambda x:sum(x.count(a)%2for a in{*x})<3

```

A graph has a Eulerian trail iff the number of vertices with odd degree is 0 or 2.

This takes the input as a flat list, as explicitly allowed by the spec.

This assumes all of the islands are connected.
> 6 votes

# Answer
# Mathematica, ~~27~~ 26 bytes

Assuming that it is a connected graph.

```
Tr@Mod[Last/@Tally@#,2]<3&

```

Takes a flat list as input.

Example:

```
In[1]:= Tr@Mod[Last/@Tally@#,2]<3&[{1, 2, 1, 3, 1, 3, 1, 4, 1, 4, 2, 3, 2, 4}]

Out[1]= False

```
> 6 votes

# Answer
# Jelly, 9 bytes

```
Qċ@€%2S<3

```

Try it online!

Port of rogaos's Python answer. If you upvote this answer, please upvote that one too. :)
> 2 votes

# Answer
# Pyth,  ~~14 11~~  10 bytes

```
>3sm%/Qd2{

```

Try it online!

My first Pyth program! I'm sure it could be golfed a great deal.

Thanks to @Rod for saving 1 byte by using `Q` implicitly.

Same general idea as my Python answer.
> 1 votes

---
Tags: code-golf, graph-theory
---


title: How many cardboard digits do I need?

text:
# Question
Title: How many cardboard digits do I need?
I need to prepare digits made of cardboard to display some number (example). I don't know beforehand which number I should display - the only thing I know is that it's not greater than `n`.

How many cardboard digits should I prepare?

Example: `n = 50`

To display any number in the range 0...50, I need the following digits:

1. A zero, for displaying the number 0, or any other round number
2. Two copies of digits 1, 2, 3 and 4, for displaying the corresponding numbers
3. One copy of digits 5, 6, 7 and 8, for the case they appear as least significant digit in the number
4. The digit 9 is never needed, because I can use the inverted digit 6 instead

Total: 13 digits

Test cases (each line is a test case in the format "input; output")

```
0 1
1 2
9 9
11 10
50 13
99 17
100 18
135 19
531 22
1000 27
8192 34
32767 38

```

# Answer
# Jelly, 9 bytes

```
‘ḶDœ|/ḟ9L

```

Try it online!

## How it works

```
‘ḶDœ|/ḟ9L
‘Ḷ         [0,1,...,n]
  D        convert each to list of its digits
   œ|/     fold by multiset union
      ḟ9   remove 9
        L  length

```
> 16 votes

# Answer
# Python 2, 49 bytes

```
lambda n:9*len(`n`)-9+(n*9+8)/10**len(`n`)+(n<10)

```

Try it online!

A clumsy arithmetical formula. Assume that `n` fits within an `int` so that an `L` isn't appended.

Thanks to Neil for saving 5 bytes by pointing out that 9's being unused could be handled by doing `n*9+8` instead of `n*9+9`, so that, say, `999*9+8=8999` doesn't roll over to 9000.
> 7 votes

# Answer
# Haskell, ~~117~~ ~~114~~ ~~108~~ ~~95~~ ~~89~~ ~~88~~ ~~87~~ ~~84~~ ~~82~~ 63 bytes

*6 bytes saved thanks to Laikoni*

*~~1~~ ~~4~~ 6 bytes saved thanks to nimi*

```
g x=sum[maximum[sum[1|u<-show y,d==u]|y<-[0..x]]|d<-['0'..'8']]

```

Try it online!
> 7 votes

# Answer
# Mathematica, 49 bytes

```
Tr@Delete[Max~MapThread~DigitCount@Range[0,#],9]&

```
> 5 votes

# Answer
## Batch, 67 bytes

```
@if %1 geq 10%2 %0 %1 0%2 -~%3
@cmd/cset/a(%1*9+8)/10%2+9*%30+!%30

```

In the standard formulation of this problem, you need separate `6` and `9` digits, but you're not required to display `0`. As the maximum value `n` required increases, the number of required numerals increases every time you reach a repdigit (because you don't quite have enough of that numeral) and every time you reach a power of `10` (when you need an extra zero). In total each power of `10` needs `10` more numerals than the previous one, which can be caluclated as `floor(log10(n))*10`. For values of `n` between powers of 10, the number of intermediate repdigits can then be calculated as `floor(n/((10**floor(log10(n))*10-1)/9))` or alternatively `floor(n*9/(10**floor(log10(n))*10-1))`.

I calculate `floor(log10(n))` by means of the loop on the first line. Each time, `%2` gains an extra `0` and `%3` gains an extra `-~`. This means that `10%2` is `10*10**floor(log10(n))` and `%30` is `floor(log10(n))`.

The duplication of `6` and `9` has two effects: firstly, there are only `9` numerals required for each power of `10`, and secondly the repdigit detection needs to ignore the `9` repdigits. Fortunately as they are one less than a power of 10 this can be achieved by tweaking the formula to result in `floor((n*9+8)/(10**floor(log10(n))*10))`.

Dealing with the zero is reasonably simple: this just requires an extra numeral when `n<10`, i.e. `floor(log10(n))==0`.
> 4 votes

# Answer
## JavaScript (ES6), ~~60~~ 53 bytes

```
f=(n,i=9)=>n>(i%9+1+"e"+(i/9|0))/9-1?1+f(n,-~i):n>9^1

```

A sort of hacky recursive solution. This generates the numbers which require adding a digit:

```
1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 22, 33, 44, 55, 66, 77, 88, 100, 111, 222, ...

```

and then counts how many are less than the input. By a happy miracle, removing the digit `9` actually *removes* several bytes from the function, because the sequence can then be generated like so (assuming integer division):

```
1e1 / 9 = 1, 2e1 / 9 = 2, ..., 8e1 / 9 = 8, 9e1 / 9 = 10, 1e2 / 9 = 11, 2e2 / 9 = 22, ...

```

We do have to take into account the fact that numbers under 10 still require the zero, but this is as simple as adding `n > 9 ? 0 : 1` to the result.

### Test cases

```
let f=(n,i=9)=>n>(i%9+1+"e"+(i/9|0))/9-1?1+f(n,i+1):n>9^1;

[0, 1, 9, 11, 50, 99, 100, 135, 531, 1000, 8192, 32767].map(n => console.log(f(n)));
```
> 4 votes

# Answer
# Mathematica, 83 bytes

```
v=DigitCount;s=v@0;(Table[s[[i]]=v[j][[i]]~Max~s[[i]],{i,10},{j,#}];s[[9]]=0;Tr@s)&

```
> 2 votes

# Answer
# Python 3, 75 bytes

```
lambda n:sum(max(str(j).count(str(i))for j in range(n+1))for i in range(9))

```

Try it online!
> 1 votes

# Answer
# PHP, 60 bytes

```
<?=count(preg_grep('#^100+$|^([0-8])\1*$#',range(0,$argn)));

```

Try it online!
> 0 votes

---
Tags: code-golf, number
---


title: Parse a list of lists into a Sad-List

text:
# Question
Title: Parse a list of lists into a Sad-List
In this challenge, you must parse a list of lists, into a simpler list format.

This challenge is based on my sadflak parser. In my sadflak parser, it has all the () removed, replaced with the sum of the ()s at the start of the list, to make the program run faster.

To parse into a Sad-List, you have to do this (python implementation thing, uses a tuple of tuples):

```
def sadlistfunc(list):
    new-sadlist = [0]
    for i in list:
        if i == ():
            new-sadlist[0]+=1
        else:
            new-sadlist.append(sadlistfunc(i))

```

This is a recursive function. For a list, start a new list, starting with the number of () from the list input, then the rest of this list is sad-list versions of every list that was not a () from the list input, in order. return the list.

## Input:

you may take input in a few different formats:

* you may take it as a list
* you may take it as a tuple
* you may take it as a string

if you take it as a string, you should use some set of brackets, as appear in brain-flak. you may not use characters 1 and 2

just be reasonable

Input will always be inside one list, but your program may assume an implicit list layer outside of the input, i.e. ()()() = (()()()), or it may choose not to. Examples will be with explicit outside list

## output:

may be list or tuple or string, or whatever. you may use whatever reasonable output format, as is the meta consensus.

## Example:

```
(()()()) = [3]
(((()))) = [0,[0,[1]]]
((())()(())) = [1, [1], [1]]
() = invalid input, if the outside bracket is explicit.
((((())())())(())()) = [1, [1, [1, [1]]], [1]]

```

note that input is not strict. these inputs could be:

```
[[],[],[]]
[[[[]]]]
[[[]],[],[[]]]
[]
[[[[[]],[]],[]],[[]],[]]

```

or some other reasonable format

# explained test case:

```
(()()((())())())

```

to "sadify" this, first we count the number of ()

```
 ()()        ()
(    ((())())  )

```

3. then we remove these, and add a 3 at the start

```
(3,((())()))

```

there is one list in this list. we sadify this

```
((())())

```

how many ()?

```
     ()
((())  )

```

1. we remove and add a 1 at the start

```
(1,(()))

```

this has one list in it

```
(())

```

count

```
 ()
(  )

```

remove and add count

```
(1)

```

then we put this back into its list

```
(1,(1))

```

then we put this back into its list

```
(3,(1,(1)))

```

done

This is , so shorter is better

# Answer
# Pyth, 13 bytes

```
L+]/bYyM-b]Yy

```

Test suite.

## How it works

```
L+]/bYyM-b]Yy
L               define a function y with argument b:
   /bY              list 1: count how many [] can be found in b
  ]                         wrap into singleton
        -b]Y        list 2: filter out [] from b
      yM                    apply y (this function) to each
 +                  concatenate the two lists above
            y   apply y to the input

```
> 4 votes

# Answer
# CommonLisp, 49 bytes

```
(defun s(l)(cons(count()l)(mapcar's(remove()l))))

```

take input as list of lists.

Try it online!
> 3 votes

# Answer
# Brachylog, 21 bytes

```
;[[]]x{↰₀}ᵐA&{∋∅}ᶜg,A

```

Try it online!
> 2 votes

# Answer
# Python 2, ~~69~~ ~~46~~ 45 bytes

```
f=lambda l:[l.count([])]+map(f,filter(len,l))

```

Try it online!
> 2 votes

# Answer
## Mathematica, 42 bytes

```
{#~Count~{0},##&@@#~DeleteCases~{0}}&//@#&

```

Avoids explicit recursion by using `//@` (`MapAll`) which maps a function over every node in a tree. This also means that the functions are executed from the leaves upwards. However, it will also be applied to `{}` which get turned into `{0}` in the process. That's why we count and remove `{0}` instead `{}`.
> 2 votes

# Answer
## Retina, 42 bytes

```
+`(({()|}(?<-3>))*)(?!\3){}
1$1
{(1*)
{$.1

```

Try it online!
> 2 votes

# Answer
## Clojure, 59 bytes

```
(fn f[i](conj(map f(remove #{[]}i))(count(filter #{[]}i))))

```

Not much different from the CommonLisp answer. Its `count` and `remove` seem to accept a bit nicer construct, here I had to use sets.
> 2 votes

# Answer
# Actually, 12 bytes

```
;[]@c@;░Q£Mo

```

Try it online!

Takes input as a comma-separated square-bracket list with explicit outer brackers.

Explanation:

```
;[]@c@;░Q£Mo
;[]@c         count the number of empty lists
     @;░      filter out empty lists
        Q£Mo  recurse with filtered list and append result

```
> 2 votes

# Answer
# Jelly, 10 bytes

```
Tịß€;@ċ“”$

```

Try it online!

Takes input as list of lists of lists...

Of course it uses the algorithm the other answers use. ;)
> 1 votes

# Answer
# Haskell, 102 bytes

```
data L=I Int|T[L]deriving Show
(I n:r)#m=r#(n+m)
(x:r)#m=x:r#m
_#m=[I m]
f(T[])=I 1
f(T t)=T$map f t#0

```

Try it online!

Because Haskell is strictly typed, there are no arbitrarily nested lists. As a remedy `data L=I Int|T[L]deriving Show` declares tree-like nested lists with either Ints or empty lists as leafs.

Input is like in the second example format, with an additional constructor `T` before each opening brace: `T[T[T[]],T[],T[T[]]]`. The same goes for the output, with each number being preceded by a constructor `I`. Function `f` performs the *saddening*.

Outputs for the test cases:

```
T [I 3]
T [T [T [I 1],I 0],I 0]
T [T [I 1],T [I 1],I 1]
T [T [T [T [I 1],I 1],I 1],T [I 1],I 1]

```
> 1 votes

# Answer
## Javascript (ES6), 77 bytes

Golfed:

```
let m=a=>!a.length||a.map(m).reduce((b,c)=>(c.length?b.push(c):b[0]++,b),[0])

```

Ungolfed:

```
const traverse = arr => !arr.length || arr
    .map(traverse)
    .reduce(
        (accum, val) => (val.length ? accum.push(val) : accum[0]++, accum),
        [0]
    );

```

## Demo

```
let m=a=>!a.length||a.map(m).reduce((b,c)=>(c.length?b.push(c):b[0]++,b),[0])

o.innerHTML = [
    JSON.stringify(m([[],[],[]])),
    JSON.stringify(m([[[[]]]])),
    JSON.stringify(m([[[]],[],[[]]])),
    JSON.stringify(m([])),
    JSON.stringify(m([[[[[]],[]],[]],[[]],[]]))
].join('\n')
```

```
<pre id=o></pre>
```
> 1 votes

---
Tags: code-golf, array, brain-flak
---


# Question
Title: Get rid of whitespace on otherwise empty lines
Ah, yet another of my selfish uses of this Stack.

Being a Chromebook owner, I'm a frequent user of the Ace IDE, the editor used by Cloud9. It has lots of tools for dealing with excess whitespace, but it notably lacks one: clearing empty lines.

Your mission today is, given an input from a place I can copy-paste to \[`;)`\], output something identical, save all spaces and tabulators on otherwise empty lines.

I'll give some examples, with `#`s representing whitespace characters to be removed.

---

## INPUT 1:

```
if (this.Color !== 'blue') {
##
  this.Color = 'blue';
}

```

## OUTPUT:

```
if (this.Color !== 'blue') {
[empty line]
  this.Color = 'blue';
}

```

---

## INPUT 2:

```
function outputSomething(times) {
  for (var iter = 0; iter < times; iter++) {
    console.log('"# # " represents a tabulator');
    // This is a comment
# #
}}

```

## OUTPUT:

```
function outputSomething(times) {
  for (var iter = 0; iter < times; iter++) {
    console.log('"# # " represents a tabulator');
    // This is a comment
[empty line]
}}

```

---

## INPUT 3:

```
var x = 'Do you prefer spaces or tabs?';
var y = 'I\'m using both here. Sue me.';
# # ####
console.log(x + ' ' + y);

```

## OUTPUT:

```
var x = 'Do you prefer spaces or tabs?';
var y = 'I\'m using both here. Sue me.';
[empty line]
console.log(x + ' ' + y);

```

---

You may process the input however you like. Output wherever, so long as I can copy-paste from it \[`;)`\].

Standard loopholes apply, shortest answer in bytes wins!

# Answer
# Japt, 10 8 6 5 4 bytes

```
mx1R

```

Try it online!

**Explanation**

```
(from the Japt docs)
.m(f,s=""):
Splits this with s, maps each item by f, then rejoins with s.

```

So `mx1R` splits the string by `R` which is a newline, trims the right hand side of each line using `x1` and joins the strings again with a newline.

Saved 2 bytes thanks to ETHproductions.
> 15 votes

# Answer
# Retina, 5 bytes

```
%G`\S

```

Try it online!

A not so obvious approach rewards us with a better score :)

### Explanation

`G` indicates this as a Grep stage, keeping only those lines where a match to the regex given (`\S`, matches non-space characters) can be found. If it wasn't for the starting `%` this would completely remove lines instead of just "emptying" them.

The `%` is a modifier which applies the stage once to each line and then joins the results with newlines: in our case this means that the empty string returned by Grep for whitespace-only lines will become an empty line in the result.
> 23 votes

# Answer
# sed, 6 bytes

```
/\S/!g

```

Try it online!

```
/  /!  # If the line doesn't contain...
 \S    # anything non-whitespace (i.e. the entire line is whitespace)
     g #   replace the pattern space with the hold space which is empty

```
> 18 votes

# Answer
# JavaScript (ES6), 26 bytes

I don't understand why this is getting so many upvotes!

```
s=>s.replace(/^\s+$/gm,``)

```

---

## Try It

```
f=
s=>s.replace(/^\s+$/gm,``)
i.addEventListener("input",_=>o.innerText=f(i.value))
```

```
<textarea id=i></textarea><pre id=o>
```
> 9 votes

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

```
ÇÓ/D

```

Try it online!

Explanation:

```
Ç       " On every line not matching the following regex:
 Ó/     "   a non-whitespace character...
   D    "   Delete the whole line

```

Hexdump:

```
00000000: c7d3 2f44                                ../D

```
> 9 votes

# Answer
# Python 3, ~~63~~ ~~55~~ 36 bytes

```
lambda s:[x.strip()and x for x in s]

```

Input and output are arrays of strings. Join on `'\n'`.

For the original program that I/O's strings:

```
lambda s:'\n'.join(x.strip()and x for x in s.split('\n'))

```

Try it online!

*Saved 8 bytes thanks to @Rod!*
*Saved 19 bytes thanks to @LeakyNun!*
> 7 votes

# Answer
# CJam, ~~18~~ 16 bytes

```
qN/{_" 	"-\e&N}%

```

Note that the string contains 1 space and 1 tab.

Try it online!

**Explanation**

```
q                 e# Read the input
 N/               e# Split it on newlines
   {              e# Apply this block to each line:
    _             e#  Copy the line
     "  "-        e#  Remove all spaces and tabs from the copy
          \       e#  Bring the original to the top of the stack
           e&     e#  Logical AND; returns the original line if the copy is truthy
                  e#    (non-empty), otherwise returns the copy line
             N    e#  Push a newline after the line
              }%  e# (end of block)

```
> 6 votes

# Answer
# Retina, 8 bytes

```
m`^\s+$

```

A really pointless challenge. `m` makes it multiline (ignores newline). `\s` matches both space and tab.

Try it online!
> 5 votes

# Answer
# APL (Dyalog), ~~11~~ 10 bytes

```
'\s+$'⎕R''

```

`⎕R` is an operator which derives a function which replaces stuff. In this case, anything matched by the RegEx is replaced with an empty string.
> 5 votes

# Answer
# Vim, ~~20~~ ~~18~~ ~~16~~ ~~13~~ 10 bytes

I am by no means a Vim expert, but this question needs a Vim answer.

`:%s/^\s*$<cr>`

`<cr>` is a carriage return.

Changelog:

* `:norm` instead of `:normal` (-2 bytes)
* Switching to `*` instead of `+` means we will match already empty lines, but that doesn't matter. And now we can get rid of `\v` (*very magic* option) (-2 bytes)
* New approach: Instead of replacing every line that matches with an empty line, we replace every line that doesn't have a no non-whitespace characters with an empty line. (-3 bytes)
* Actually, a normal replacement is shorter (thanks, @DJMcMayhem) (-3 bytes)
> 5 votes

# Answer
# AWK, ~~12~~ 11 bytes

```
!NF{$0=""}1

```

Try it online!

I was just feeling like AWK should have an answer too

It works by:

1. Checking if there are no fields in the input. AWK by default uses all whitespace as separator between fields
2. If there are no fields, change the input line to an empty string
3. Print the line. As 1 is a truthy value, it runs the default command which is printing the line
> 5 votes

# Answer
# Ruby, 22 bytes

```
->s{s.gsub /^\s+$/,''}

```

Straightforward regex solution
> 4 votes

# Answer
# Java 7, 57 bytes

```
String c(String s){return s.replaceAll("(?m)^\\s+$","");}

```

**Explanation:**

```
String c(String s){     // Method with String parameter and String return-type
  return s.replaceAll(  //  Return the input String after we've replaced
    "(?m)^\\s+$",       //  all lines only containing whitespaces
    "");                //  with empty Strings
                        //    (NOTE: `(?m)` enables multiline regex)
}                       // End of method

```

**Test code:**

Try it here.

```
class M{
  static String c(String s){return s.replaceAll("(?m)^\\s+$","");}

  public static void main(String[]a){
    System.out.println(c("if (this.Color !== 'blue') {\n \t\n  this.Color = 'blue';\n}"));
    System.out.println();
    System.out.println(c("function outputSomething(times) {\n  for (var iter = 0; iter < times; iter++) {\n    console.log('\"# # \" represents a tabulator');\n    // This is a comment\n  \t\n}}"));
    System.out.println();
    System.out.println(c("var x = 'Do you prefer spaces or tabs?';\nvar y = 'I\'m using both here. Sue me.';\n    \t\t\t \nconsole.log(x + ' ' + y);"));
  }
}

```
> 3 votes

# Answer
# Groovy, 31 bytes

```
{it.replaceAll(/\n\s+\n/,"\n")}

```
> 2 votes

# Answer
# Perl 6,  ~~15~~  12 bytes

## 15

```
{S:g/^^\h+$$//}

```

Try it

```
{         # bare block lambda with implicit parameter ｢$_｣

  S       # string replace (implicitly against ｢$_｣)
  :global # globally
  /
    ^^    # match beginning of line
      \h+ # match at least one horizontal whitespace
    $$    # match end of line

  //      # replace with nothing
}

```

---

## 11+1

```
perl6 -pe 's/^^\h+$$//'

```

Largely the same as above.

* `-p` runs the code for every line of input, putting the line into `$_` and printing whatever is left in `$_`.
* `s` replaces in-place, whereas `S` returns the result.
* No need for `:g`/`:global` as `-p` takes care of that.
> 1 votes

# Answer
# Python 2, 26 bytes

```
lambda l:map(str.rstrip,l)

```

Try it online! Inputs and outputs a list of strings.

This takes advantage of the ruling in the comments that trailing whitespace may be removed on non-empty lines.
> 1 votes

# Answer
# C, 168 bytes

```
#define P putchar(*t++)
s;e(char*t){s=0;while(*t>10)if(*t!=32|*t!=9)return 0;else t++,s++;return s;}
r(char*t){while(*t==10)P;if(!*t)return;if(!e(t))while(*t)P;t+=e(t);}

```

**Detailed**

```
#include <stdio.h>

int e (char * t)
{
    int s = 0;

    // till the end of the line
    while (*t!='\0' && *t!='\n')
        // if it's not a space
        if (*t!=' ' || *t!='    ')
            // ignore the line
            return 0;
        else
            // count the space
            t++, s++;

    // return number of spaces
    return s;
}

void r (char * t)
{
    // skip to empty lines
    while (*t != '\0' && *t == '\n') putchar('\n'), t++;

    // stop at end of string
    if (*t == '\0') return;

    // if there is contnet print it
    if (!e(t)) while(*t != '\0') putchar(*t), t++;

    // skip to the end of line
    t += e(t);
}

int main (int argc, char**argv)
{
    if (argc > 1) r(argv[1]);
    putchar('\n');
    return 0;
}

```
> 0 votes

# Answer
## C, 100 bytes

```
c,i,j;f(char*s){for(i=j=c=0;s[i];s[++j]^10?c=s[j]^32:(printf(!c?"\n":"%.*s",j-i+1,s+i),c=0,i=j+1));}

```

See it work online.
> 0 votes

# Answer
# Vim, 13 9 bytes

`:v/\S/le↵`

**Edits:**

* Original answer: `:v/\S/d↵` (based on this vim question on SO).
It deletes empty lines, which isn't the expected behavior.
* Valid answer using vglobal: `:v/\S/norm D↵`
* Now using the left-align ex command instead of `normal D`
> 0 votes

# Answer
# QuadR, 5 bytes

```
\s+$

```

Try it online!

`\s+` replace one or more whitespace chars followed by
`$` end of line

with nothing
> 0 votes

---
Tags: code-golf, string, whitespace
---


title: Turing Machine Simulator

text:
# Question
Title: Turing Machine Simulator
Write a Turing machine simulator.

For simplicity we can assume statuses as integer, symbols as char, blank symbol equals whitespace

5-tuple in the form of current state, input symbol, next state, output symbol, direction (left or right) the order is not mandatory but specify if you swap it

The machine must stop when an unknown state is reached, no other halt condition allowed.

The tape is infinite in both directions and you can always read an empty character.

Input: the initial tape, an initial state and a program. you are free to read the data from anywhere in the format you like

Output: the tape after the execution of the program

Required: an example program that run on top of your simulator

This is a code-colf so the shortest code win.

I'll post an implementation and some example programs in the next few hours.

# Answer
### GolfScript, 92 characters

```
~:m;n\+{:^.n?)>1<]m{2<1$=},.{~2>~^n/~1>[@\+]n*1$%n/~\1$1<+[\1>.!{;" "}*]n*\%@}{;;^0}if}do n-

```

The Turing machine in GolfScript became much longer than intended. Still playing around with different representations of the tape.

First line of the input is the original state, second line the initial tape, followed by an array of transitions (with order current state, input symbol, next state, direction, output symbol).

Example (also available online)

```
> 0
> '101'
> [[0 '0' 0 1 '0']
>  [0 '1' 0 1 '1']
>  [0 ' ' 1 -1 ' ']
>  [1 '0' 2 1 '1']
>  [1 '1' 3 -1 '0']
>  [3 '0' 2 1 '1']
>  [3 ' ' 2 1 '1']
>  [3 '1' 3 -1 '0']]

110

```
> 2 votes

# Answer
# GNU sed with `-r` \- 133 117 111 93 chars

Yes, sed is turing complete. GNU sed and `-r` (extended regexps) is only to save a few characters, it is only a small change to work with POSIX sed.

```
:s
s/^(.*@)(.*)>(.)(.*#\1\3([^@]*@)(..))/\5\2\6>\4/
T
s/(..)l>|r>/>\1/
s/>@/@> /
s/>#/> #/
bs

```

Input format is

```
[initial state]@[non-empty tape with > marking head position]#[state]@[input symbol][next state]@[output symbol][direction l or r]#...

```

The delimiters `@`, `#` and head character `>` cannot be used as a symbol on the tape. State labels cannot contain `@` `>` or `#`.

It will run all of the programs in the input, one per line

Examples:

Marco's anbn program

> Input
>
> ```
> 0@>aaabbb#0@a1@ r#0@ 4@ r#1@a1@ar#1@b1@br#1@ 2@ l#2@b3@ l#2@a5@al#3@b3@bl#3@a3@al#3@ 0@ r#4@ 5@Tr
>
> ```
>
> Output
>
> ```
> 5@    T>  #0@a1@ r#0@ 4@ r#1@a1@ar#1@b1@br#1@ 2@ l#2@b3@ l#2@a5@al#3@b3@bl#3@a3@al#3@ 0@ r#4@ 5@Tr
>
> ```

Marco's Hello! program

> Input
>
> ```
> 0@> #0@ 1@Hr#1@ 2@er#2@ 3@lr#3@ 4@lr#4@ 5@or#5@ 6@!r
>
> ```
>
> Output
>
> ```
> 6@Hello!> #0@ 1@Hr#1@ 2@er#2@ 3@lr#3@ 4@lr#4@ 5@or#5@ 6@!r
>
> ```
> 8 votes

# Answer
So I'm a bit late, but just thought I would leave this here...

## Turing Machine Simulating a Turing Machine: 370 bytes?

Here I'm using the structure Turing used in his 1936 paper. I'm using one symbol = one byte, including m-configs and operations.

```
╔═══════════════╦═══════╦═══════════════════╦═══════════════╗
║    m-config    ║ Symbol ║     Operations      ║ Final m-config ║
╠═══════════════╬═══════╬═══════════════════╬═══════════════╣
║ currentCommand ║ Any    ║ L                   ║ currentCommand ║
║                ║ *      ║ MR                  ║ readCommand    ║
╠----------------╬--------╬---------------------╬----------------╣
║ nextCommand    ║ Any    ║ L                   ║ nextCommand    ║
║                ║ *      ║ E  R  R  R  P* R    ║ readCommand    ║
╠----------------╬--------╬---------------------╬----------------╣
║ readCommand    ║ P      ║ R                   ║ readCommandP   ║
║                ║ M      ║ R                   ║ readCommandM   ║
║                ║ G      ║ R                   ║ readCommandG   ║
║                ║ E      ║ R                   ║ MHPNone        ║
╠----------------╬--------╬---------------------╬----------------╣
║ readCommandP   ║ 0      ║                     ║ MHP0           ║
║                ║ 1      ║                     ║ MHP1           ║
║                ║ e      ║                     ║ MHPe           ║
║                ║ x      ║                     ║ MHPx           ║
║                ║ None   ║                     ║ MHPNone        ║
╠----------------╬--------╬---------------------╬----------------╣
║ readCommandM   ║ R      ║                     ║ MHMR           ║
║                ║ L      ║                     ║ MHML           ║
╠----------------╬--------╬---------------------╬----------------╣
║ readCommandG   ║ 1      ║                     ║ G2<1           ║
║                ║ 2      ║                     ║ G2<2           ║
║                ║ 3      ║                     ║ G2<3           ║
║                ║ 4      ║                     ║ G2<4           ║
║                ║ 5      ║                     ║ G2<5           ║
╠----------------╬--------╬---------------------╬----------------╣
║ G2<1           ║ int(1) ║ L  P@ R  R  R  P* R ║ GTS            ║
║                ║ <      ║                     ║ G21            ║
║                ║ *      ║ E  L                ║ G2<1           ║
║                ║ @      ║ E  L                ║ G2<1           ║
║                ║ Any    ║ L                   ║ G2<1           ║
╠----------------╬--------╬---------------------╬----------------╣
║ G2<2           ║ int(2) ║ L  P@ R  R  R  P* R ║ GTS            ║
║                ║ <      ║                     ║ G22            ║
║                ║ *      ║ E  L                ║ G2<2           ║
║                ║ @      ║ E  L                ║ G2<2           ║
║                ║ Any    ║ L                   ║ G2<2           ║
╠----------------╬--------╬---------------------╬----------------╣
║ G2<3           ║ int(3) ║ L  P@ R  R  R  P* R ║ GTS            ║
║                ║ <      ║                     ║ G23            ║
║                ║ *      ║ E  L                ║ G2<3           ║
║                ║ @      ║ E  L                ║ G2<3           ║
║                ║ Any    ║ L                   ║ G2<3           ║
╠----------------╬--------╬---------------------╬----------------╣
║ G2<4           ║ int(4) ║ L  P@ R  R  R  P* R ║ GTS            ║
║                ║ <      ║                     ║ G24            ║
║                ║ *      ║ E  L                ║ G2<4           ║
║                ║ @      ║ E  L                ║ G2<4           ║
║                ║ Any    ║ L                   ║ G2<4           ║
╠----------------╬--------╬---------------------╬----------------╣
║ G2<5           ║ int(5) ║ L  P@ R  R  R  P* R ║ GTS            ║
║                ║ <      ║                     ║ G25            ║
║                ║ *      ║ E  L                ║ G2<5           ║
║                ║ @      ║ E  L                ║ G2<5           ║
║                ║ Any    ║ L                   ║ G2<5           ║
╠----------------╬--------╬---------------------╬----------------╣
║ G21            ║ int(1) ║ L  P@ R             ║ GTS            ║
║                ║ Any    ║ R                   ║ G21            ║
╠----------------╬--------╬---------------------╬----------------╣
║ G22            ║ int(2) ║ L  P@ R             ║ GTS            ║
║                ║ Any    ║ R                   ║ G22            ║
╠----------------╬--------╬---------------------╬----------------╣
║ G23            ║ int(3) ║ L  P@ R             ║ GTS            ║
║                ║ Any    ║ R                   ║ G23            ║
╠----------------╬--------╬---------------------╬----------------╣
║ G24            ║ int(4) ║ L  P@ R             ║ GTS            ║
║                ║ Any    ║ R                   ║ G24            ║
╠----------------╬--------╬---------------------╬----------------╣
║ G25            ║ int(5) ║ L  P@ R             ║ GTS            ║
║                ║ Any    ║ R                   ║ G25            ║
╠----------------╬--------╬---------------------╬----------------╣
║ GTS            ║ ^      ║ R                   ║ TS             ║
║                ║ Any    ║ R                   ║ GTS            ║
╠----------------╬--------╬---------------------╬----------------╣
║ TS             ║ 0      ║                     ║ RL0            ║
║                ║ 1      ║                     ║ RL1            ║
║                ║ e      ║                     ║ RLe            ║
║                ║ x      ║                     ║ RLx            ║
║                ║ None   ║                     ║ RLNone         ║
╠----------------╬--------╬---------------------╬----------------╣
║ RL0            ║ @      ║ R  R                ║ GTS0           ║
║                ║ Any    ║ L                   ║ RL0            ║
╠----------------╬--------╬---------------------╬----------------╣
║ RL1            ║ @      ║ R  R                ║ GTS1           ║
║                ║ Any    ║ L                   ║ RL1            ║
╠----------------╬--------╬---------------------╬----------------╣
║ RLe            ║ @      ║ R  R                ║ GTSe           ║
║                ║ Any    ║ L                   ║ RLe            ║
╠----------------╬--------╬---------------------╬----------------╣
║ RLx            ║ @      ║ R  R                ║ GTSx           ║
║                ║ Any    ║ L                   ║ RLx            ║
╠----------------╬--------╬---------------------╬----------------╣
║ RLNone         ║ @      ║ R  R                ║ GTSNone        ║
║                ║ Any    ║ L                   ║ RLNone         ║
╠----------------╬--------╬---------------------╬----------------╣
║ GTS0           ║ 0      ║ R  P*  R            ║ readCommand    ║
║                ║ Any    ║ R                   ║ GTS0           ║
╠----------------╬--------╬---------------------╬----------------╣
║ GTS1           ║ 1      ║ R  P*  R            ║ readCommand    ║
║                ║ Any    ║ R                   ║ GTS1           ║
╠----------------╬--------╬---------------------╬----------------╣
║ GTSe           ║ e      ║ R  P*  R            ║ readCommand    ║
║                ║ Any    ║ R                   ║ GTSe           ║
╠----------------╬--------╬---------------------╬----------------╣
║ GTSx           ║ x      ║ R  P*  R            ║ readCommand    ║
║                ║ Any    ║ R                   ║ GTSx           ║
╠----------------╬--------╬---------------------╬----------------╣
║ GTSNone        ║ _      ║ R  P*  R            ║ readCommand    ║
║                ║ Any    ║ R                   ║ GTSNone        ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHP0           ║ ^      ║ R                   ║ Print0         ║
║                ║ Any    ║ R                   ║ MHP0           ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHP1           ║ ^      ║ R                   ║ Print1         ║
║                ║ Any    ║ R                   ║ MHP1           ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHPe           ║ ^      ║ R                   ║ Printe         ║
║                ║ Any    ║ R                   ║ MHPe           ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHPx           ║ ^      ║ R                   ║ Printx         ║
║                ║ Any    ║ R                   ║ MHPx           ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHPNone        ║ ^      ║ R                   ║ PrintNone      ║
║                ║ Any    ║ R                   ║ MHPNone        ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHMR           ║ ^      ║ R  R                ║ MHR            ║
║                ║ Any    ║ R                   ║ MHMR           ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHML           ║ ^      ║ L                   ║ MHL            ║
║                ║ Any    ║ R                   ║ MHML           ║
╠----------------╬--------╬---------------------╬----------------╣
║ Print0         ║ ^      ║ R                   ║ Print0         ║
║                ║ None   ║ P0                  ║ nextCommand    ║
║                ║ Any    ║ E                   ║ Print0         ║
╠----------------╬--------╬---------------------╬----------------╣
║ Print1         ║ ^      ║ R                   ║ Print1         ║
║                ║ None   ║ P1                  ║ nextCommand    ║
║                ║ Any    ║ E                   ║ Print1         ║
╠----------------╬--------╬---------------------╬----------------╣
║ Printx         ║ ^      ║ R                   ║ Printx         ║
║                ║ None   ║ Px                  ║ nextCommand    ║
║                ║ Any    ║ E                   ║ Printx         ║
╠----------------╬--------╬---------------------╬----------------╣
║ Printe         ║ ^      ║ R                   ║ Printe         ║
║                ║ None   ║ Pe                  ║ nextCommand    ║
║                ║ Any    ║ E                   ║ Printe         ║
╠----------------╬--------╬---------------------╬----------------╣
║ PrintNone      ║ ^      ║ R                   ║ PrintNone      ║
║                ║ None   ║                     ║ nextCommand    ║
║                ║ Any    ║ E                   ║ PrintNone      ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHL            ║ ^      ║ R  R                ║ MHL            ║
║                ║ [      ║                     ║ SBL            ║
║                ║ Any    ║ L  P^ R  R  E       ║ nextCommand    ║
╠----------------╬--------╬---------------------╬----------------╣
║ MHR            ║ ^      ║ R  R                ║ MHR            ║
║                ║ ]      ║                     ║ SBR            ║
║                ║ None   ║ P^ L  L  E          ║ nextCommand    ║
╠----------------╬--------╬---------------------╬----------------╣
║ SBR            ║ ]      ║ E  R  R  P]         ║ currentCommand ║
╠----------------╬--------╬---------------------╬----------------╣
║ SBL            ║ ]      ║ R                   ║ SBLE           ║
║                ║ Any    ║ R                   ║ SBL            ║
╠----------------╬--------╬---------------------╬----------------╣
║ SBLE           ║ [      ║                     ║ currentCommand ║
║                ║ None   ║ L                   ║ SBLE           ║
║                ║ Any    ║ E  R  R  P] L       ║ SBLE           ║
╚═══════════════╩═══════╩═══════════════════╩═══════════════╝

```

Here is one of Turing's examples from the paper above for my machine:

```
['<', None, 1, '0', None, 'P', 'e', None, 'M', 'R', None, 'P', 'e', None, 'M', 'R', None, 'P', '0', None, 'M', 'R', None, 'M', 'R', None, 'P', '0', None, 'M', 'L', None, 'M', 'L', None, 'G', '2',
                      '1', None, 'P', 'e', None, 'M', 'R', None, 'P', 'e', None, 'M', 'R', None, 'P', '0', None, 'M', 'R', None, 'M', 'R', None, 'P', '0', None, 'M', 'L', None, 'M', 'L', None, 'G', '2',
                      'e', None, 'P', 'e', None, 'M', 'R', None, 'P', 'e', None, 'M', 'R', None, 'P', '0', None, 'M', 'R', None, 'M', 'R', None, 'P', '0', None, 'M', 'L', None, 'M', 'L', None, 'G', '2',
                      'x', None, 'P', 'e', None, 'M', 'R', None, 'P', 'e', None, 'M', 'R', None, 'P', '0', None, 'M', 'R', None, 'M', 'R', None, 'P', '0', None, 'M', 'L', None, 'M', 'L', None, 'G', '2',
                      '_', None, 'P', 'e', None, 'M', 'R', None, 'P', 'e', None, 'M', 'R', None, 'P', '0', None, 'M', 'R', None, 'M', 'R', None, 'P', '0', None, 'M', 'L', None, 'M', 'L', None, 'G', '2',

             None, 2, '1', None, 'M', 'R', None, 'P', 'x', None, 'M', 'L', None, 'M', 'L', None, 'M', 'L', None, 'G', '2',
                      '0', None, 'G', '3',

             None, 3, '0', None, 'M', 'R', None, 'M', 'R', None, 'G', '3',
                      '1', None, 'M', 'R', None, 'M', 'R', None, 'G', '3',
                      '_', None, 'P', '1', None, 'M', 'L', None, 'G', '4',

             None, 4, 'x', None, 'E', 'E', None, 'M', 'R', None, 'G', '3',
                      'e', None, 'M', 'R', None, 'G', '5',
                      '_', None, 'M', 'L', None, 'M', 'L', None, 'G', '4',

             None, 5, '0', None, 'M', 'R', None, 'M', 'R', None, 'G', '5',
                      '1', None, 'M', 'R', None, 'M', 'R', None, 'G', '5',
                      'e', None, 'M', 'R', None, 'M', 'R', None, 'G', '5',
                      'x', None, 'M', 'R', None, 'M', 'R', None, 'G', '5',
                      '_', None, 'P', '0', None, 'M', 'L', None, 'M', 'L', None, 'G', '2',
        None, '[', '^', None, ']', None]

```

Try it online! (Uses Python 3 as an interpreter) --Edit: I just checked the TIO, and it doesn't seem to actually work right... Try it on your local machine and it should (hopefully) work. It does on mine.
> 8 votes

# Answer
## Python, 101 189 152 142

```
a=dict(zip(range(len(b)),b))
r=eval(p)
i=s=0
while 1:
 c=a.get(i,' ')
 s,m,a[i]=r[s,c]
 if 0==m:exit([x[1]for x in sorted(a.items())])
 i=i+m

```

b and p are the inputs, b is the initial tape, p encodes the rules as (string representation of) a dict from (in-state, in-tape) tuple to (out-state, head move, out-tape) tuple. If move is 0 the program finishes, 1 is move to the right and -1 is move to the left.

```
b="aaba"

p="""{(0, 'a'): (1, 1, 'a'),
      (0, 'b'): (0, 1, 'b'),
      (1, 'a'): (1, 1, 'a'),
      (1, 'b'): (0, 1, 'b'),
      (1, ' '): (1, 0, 'Y'),
      (0, ' '): (0, 0, 'N')}"""

```

This sample program tests if the last letter of the string (before empty tape) is 'a', if so it writes 'Y' at the end of the string (first empty space).

**Edit 1:**

Changed the tape to be represented as a dict, as it seemed the shortest way to write an extensible data structure. The second to last line is mostly transforming it back into readable form for output.

**Edit 2:**

Thanks to Strigoides for a great deal of improvements.

**Edit 3:**

I had unnecessarily made it so 0 as output would leave the place as it is. I removed this as we can always write the output the same as the input.
> 3 votes

# Answer
## APL (110)

(It's not even that short...)

```
0(''⍞){×⍴X←0~⍨⍺∘{x y S T s m t←⍺,⍵⋄S T≡x,⊃⊃⌽y:s,⊂(⊃y){m:(¯1↓⍺)(⍵,⍨¯1↑⍺)⋄(⍺,⊃⍵)(1↓⍵)}t,1↓⊃⌽y⋄0}¨⍵:⍵∇⍨⊃X⋄,/⊃⌽⍺}⎕

```

It reads two lines from the keyboard: the first is the program and the second is the initial tape.

The format is

```
(in-state in-tape out-state movement out-tape)

```

and they should all be on the same line. 'Movement' is 0 to move right and 1 to move left.

Example program (line breaks inserted for clarity, they should be all on one line.)

```
(0 ' ' 1 0 '1')
(0 '1' 0 0 '1')
(1 '1' 1 0 '1')
(1 ' ' 2 1 ' ')
(2 '1' 3 1 ' ')

```

The program adds two unary numbers together, for example:

```
in:  1111 111
out: 1111111

```

Example 2 (adapted from the binary increment program from Marco Martinelli's entry):

```
(0 '0' 0 0 '0')
(0 '1' 0 0 '1')
(0 ' ' 1 1 ' ')
(1 '0' 2 0 '1')
(1 '1' 3 1 '0')
(3 '0' 2 0 '1')
(3 ' ' 2 0 '1')
(3 '1' 3 1 '0')

```
> 3 votes

# Answer
**Postscript ~~(205)~~ ~~(156)~~ ~~(150)~~ (135)**

```
<<
>>begin
/${stopped}def([){add dup{load}${exit}if}def
0 A{1 index{load}${pop( )}if
get{exec}${exit}if}loop
3{-1[pop}loop{1[print}loop

```

This is probably cheating, but the transition table contains code to perform the transitions. And since the tape is represented by a mapping from integers to integers, I've represented states as a mapping from names to dictionaries so the tape and the program coexist in the same anonymous dictionary.

Extra savings by making all state names executable, so they *auto*-load.

Ungolfed with embedded "Hello" program. ~~An extra 52 chars buys a loop to read the tape from stdin.~~ Run with `gsnd -q tm.ps`.

```
%!
<<
    /A<<( ){dup(H)def 1 add B}>>
    /B<<( ){dup(e)def 1 add C}>>
    /C<<( ){dup(l)def 1 add D}>>
    /D<<( ){dup(l)def 1 add E}>>
    /E<<( ){dup(o)def 1 add F}>>
>>begin %ds: int-keys=tape name-keys=prog
0 A %pos state
{ %loop
    1 index{load}stopped{pop( )}if  %pos state tape(pos)
    get    {exec}stopped{exit  }if  %new-pos new-state
} loop
% Loop from tape position 0 to left until left tape end is found
0{                                  %pos
  -1 add                            %new-pos
  dup{load}stopped{exit}if          %new-pos tape(new-pos)
  pop                               %new-pos tape(new-pos)
}loop
% Move to the right and print all chars until right end is hit
{                                   %pos
  1 add                             %new-pos
  dup{load}stopped{exit}if          %new-pos tape(new-pos)
  print                             %new-pos tape(new-pos)
}loop

```

So the table-format is

```
/in-state<<in-tape{dup out-tape def movement add out-state}
           in-tape2{dup out-tape2 def movement2 add out-state2}>>

```

where `in-state` is a name, `in-tape` and `out-tape` are chars (ie. integers, or expressions which yield integers), `movement` is `-1` for left or `1` for right, and `out-state` is an *executable* name. Multiple `in-tape` transition for the same state must be combined as above.
> 3 votes

# Answer
**C (not golfed yet)**

I suppose I can't win with this, still it was fun getting it to work. This is even more true now that it really *does* work. :)

Except it's only infinite in one direction. I suppose it needs a negative tape, too. Sigh....

Negative wasn't so bad. We interleave the two sides as evens and odds. Complication is now it needs to display the tape in *sequential order*, as the file itself is now jumbled. This is a legitimate alteration to make, I think. Turing himself simplified this way.

```
#include<stdio.h>
int main(int c, char**v){
    int min=0,max=0;
    int pos=0,qi;sscanf(v[1],"%d",&qi);
    FILE*tab=fopen(v[2],"r");
    FILE*tape=fopen(v[3],"r+");
    setbuf(tape,NULL);
    do {
        min = pos<min? pos: min;
        max = pos>max? pos: max;
        fseek(tape,(long)(abs(pos)*2)-(pos<0),SEEK_SET);
        int c = fgetc(tape), qt=qi-1,qr;
        fseek(tape,(long)(abs(pos)*2)-(pos<0),SEEK_SET);
        char x = c==EOF?' ':c, xt=x-1,xr,d[2];
        if (x == '\n') x = ' ';
printf("%d '%c' %d (%d)\n", qi, x, pos, (int)ftell(tape));
        while((qt!=qi)||(xt!=x)){
            fscanf(tab, "%d '%c' %d '%c' %1[LRN]", &qt, &xt, &qr, &xr, d);
            if (feof(tab)){
                goto HALT;
            }
printf("%d '%c' %d '%c' %s\n", qt, xt, qr, xr, d);
        }
        qi=qr;
        rewind(tab);
        fputc(xr,tape);
        pos+=*d=='L'?-1:*d=='R'?1:0;
    } while(1);
HALT:
printf("[%d .. %d]:\n", min, max);
    for (pos = min; pos <= max; pos++){
        fseek(tape,(long)(abs(pos)*2)-(pos<0),SEEK_SET);
        //printf("%d ",pos);
        putchar(fgetc(tape));
        //puts("");
    }
    return qi;
}

```

And here's the test-run:

```
522(1)04:33 AM:~ 0> cat bab.tm
0 'a' 0 'b' R
0 'b' 0 'a' R
523(1)04:33 AM:~ 0> echo aaaaa > blank; make tm ; tm 0 bab.tm blank; echo; cat blank
make: `tm' is up to date.
0 'a' 0 (0)
0 'a' 0 'b' R
0 'a' 1 (2)
0 'a' 0 'b' R
0 'a' 2 (4)
0 'a' 0 'b' R
0 ' ' 3 (6)
0 'a' 0 'b' R
0 'b' 0 'a' R
[0 .. 3]:
bbbÿ
babab

```

The program outputs the tape in sequential order, but the file represents the negative and positive sides interleaved.
> 2 votes

# Answer
# Groovy ~~234~~ ~~228~~ ~~154~~ ~~153~~ ~~149~~ ~~139~~ 124

```
n=[:];i=0;t={it.each{n[i++]=it};i=0};e={p,s->a=p[s,n[i]?:' '];if(a){n[i]=a[1];i+=a[2];e(p,a[0])}else n.sort()*.value.join()}

```

Formatted for readability

```
n=[:];
i=0;
t={it.each{n[i++]=it};i=0};
e={p,s->
    a=p[s,n[i]?:' '];
    if(a){
        n[i]=a[1];
        i+=a[2];
        e(p,a[0])
    }else n.sort()*.value.join()
}

```

t is the function that set the tape e is the function that evaluate the program

Example 1 - Print "Hello!" on the tape :)

```
t('')
e([[0,' ']:[1,'H',1],
   [1,' ']:[2,'e',1],
   [2,' ']:[3,'l',1],
   [3,' ']:[4,'l',1],
   [4,' ']:[5,'o',1],
   [5,' ']:[6,'!',1]],0)

```

Example 2 - Leave a T on the tape if the initial string is in the form of anbn, stop otherwise.

```
t('aaabbb')
e([[0,'a']:[1,' ',1],
   [0,' ']:[4,' ',1],
   [1,'a']:[1,'a',1],
   [1,'b']:[1,'b',1],
   [1,' ']:[2,' ',-1],
   [2,'b']:[3,' ',-1],
   [2,'a']:[5,'a',-1],
   [3,'b']:[3,'b',-1],
   [3,'a']:[3,'a',-1],
   [3,' ']:[0,' ',1],
   [4,' ']:[5,'T',1]],0)

```

Example 3 - Increment of a binary number

```
t('101')
e([[0,'0']:[0,'0',1],
   [0,'1']:[0,'1',1],
   [0,' ']:[1,' ',-1],
   [1,'0']:[2,'1',1],
   [1,'1']:[3,'0',-1],
   [3,'0']:[2,'1',1],
   [3,' ']:[2,'1',1],
   [3,'1']:[3,'0',-1]],0)

```

in the examples 1 means move to the right and -1 means move to the left
> 1 votes

---
Tags: code-golf, interpreter
---


title: Block of digits

text:
# Question
Title: Block of digits
Output/print this block of text:

```
1234567890
2468013579
3691470258
4815926037
5049382716
6172839405
7306295184
8520741963
9753108642
0987654321

```

Acceptable formats include:

* Trailing newlines/whitespace
* List of strings
* List of lists of characters
* List of lists of integers

However, list of integers is not acceptable because the last line is not an integer.

This is . Shortest answer in bytes wins. Standard loopholes apply.

# Answer
> 20 votes
## Mathematica, 33 bytes

```
Mod[1##,11]~Mod~10&~Array~{10,10}

```

Try it online! (Using Mathics.)

The cell at 1-based index `(x,y)` has value `((x*y) % 11) % 10`

# Answer
> 11 votes
# Python 2, ~~48~~ 46 bytes

```
n=10
while n:print('00987654321'*n)[n::n];n-=1

```

Try it online!

# Answer
> 9 votes
# Python 2, ~~49~~ 47 bytes

```
n=1
exec"print('01234567890'*n)[n::n];n+=1;"*10

```

Try it online!

# Answer
> 7 votes
# Jelly, 7 bytes

```
⁵×þ`%‘%

```

Try it online!

Uses Martin's algorithm.

# Answer
> 5 votes
# MATL, ~~12~~ 11 bytes

Saved a byte thanks to Luis. I keep forgetting the `&` is a shortcut for duplicating and transposing.

```
10:&*11\10\

```

Try it online!

Using @Martin's algorithm: `x*y % 11 % 10`

**Explanation:**

```
10            % Pust 10 to the stack. Stack: 1
  :           % 1-based range. Stack: [1 2 3 ... 10]
   &          % Duplicate range. Stack: [1 2 3 ... 10],[1 2 3 ... 10]
              % Transpose last range. Stack [1 2 3 ... 10],[1;2;3 ...10]
    *         % Multiply with broadcasting. Stack: [1 2 3 ...;2 4 6...] (10-by-10 array)
     11       % Push 11 to the stack. Stack [1 2 3 ...;2 4 6 ...], 11
       \      % Modulus.
        10    % Push 10 to the stack.
          \   % Modulus
              % Implicit display

```

Same bytecount:

```
10t:&*11\w\

```

# Answer
> 4 votes
## APL (Dyalog), 13 bytes

```
10|11|∘.×⍨⍳10

```

Try it online!

A port of my Mathematica answer.

```
      ∘.×⍨      ⍝ Multiplication table of...
          ⍳10   ⍝ The list from 1 to 10.
   11|          ⍝ mod 11.
10|             ⍝ mod 10.

```

# Answer
> 3 votes
## CJam (17 bytes)

```
A,:)_f{f*Bf%Af%N}

```

Online demo

# Answer
> 2 votes
# Japt, ~~16~~ ~~12~~ 11 bytes

Turns out this was my 200 (undeleted) answer here :)

Looks like this is the same formula Martin spotted.

```
Aõ
£®*X%B%A

```

Test it (`-R` flag for visualisation purposes only)

* 4 bytes saved thanks to Luke pointing out that returning an array of arrays was permissible.

---

## Explanation

```
Aõ    :Generate an array of integers from 1 to 10, inclusive.
£     :Map over each element in the array, returning...
®     :Another map of the same array, which...
*X    :Multiplies the current element of the inner function by the current element of the outer function...
%B    :Modulus 11...
%A    :Modulus 10.
      :Implicit output of resulting 2D array

```

# Answer
> 2 votes
# Javascript (ES6), ~~70 64~~ 56 bytes

```
_=>[...1e9+''].map((_,a,b)=>b.map((_,c)=>-~a*++c%11%10))

```

Saved 4 bytes thanks to Shaggy and 8 bytes thanks to Arnauld.

# Answer
> 2 votes
## Retina, 59 bytes

Byte count assumes ISO 8859-1 encoding.

```

10$*
1
,1$`
,1+
$_¶
(?<=(¶?.+)+)1
$#1$*
1{10}1?

,(1*)
$.1

```

Try it online!

### Explanation

Another implementation of the **... % 11 % 10** algorithm. The fun part of doing it with a regex is that we can take care of both modulo computations at once.

```

10$*

```

Initialise the string to ten `1`s.

```
1
,1$`

```

Replace each of those with a comma, a one, and the prefix in front of that one. This gives `,1,11,...,1111111111`, i.e. a unary range.

```
,1+
$_¶

```

Now replace each of the range elements with the entire string followed by a linefeed. This gives us a 10x10 grid of unary numbers indicating the current column.

```
(?<=(¶?.+)+)1
$#1$*

```

Match each `1` and determine which row it's on by repeating group one that many times. Replace the `1` with that many `1`s. This multiplies the values in each row by the row's 1-based index.

```
1{10}1?

```

Now let's do **mod 11, mod 10** in one step. To do **mod 11**, we'd normally just remove all `1{11}` from the string to be left with the remainders. And then we'd remove `1{10}` after that. But if we just remove ten `1`s plus another if possible, the regex engine's greediness will do **mod 11** for us as long as possible, and if not, then it'll try at least **mod 10**.

```
,(1*)
$.1

```

Finally, we just convert each number to decimal by replacing it with its length.

# Answer
> 2 votes
# 05AB1E, 14 bytes

```
11GTLN*11%T%})

```

Try it online!

Uses Martin's algorithm, as usual.

# Answer
> 2 votes
# Haskell, 43 bytes

```
l=[1..10]
f=[[x*i`mod`11`mod`10|i<-l]|x<-l]

```

# Answer
> 1 votes
# Charcoal, 30 29 19 bytes

```
Ｆχ«ＦχＩ﹪﹪×⁺¹ι⁺¹κ¹¹χ⸿

```

Try it online!

Uses Martin's formula.

* 10 bytes saved thanks to Neil, proving once more that I have still so much to learn...

# Answer
> 1 votes
# Java 8, 84 bytes

```
o->{String r="";for(int x=0,y;++x<11;r+="\n")for(y=0;++y<11;r+=x*y%11%10);return r;}

```

Uses the same algorithm as *@MartinEnder*'s Mathematica answer: 1-indexed `x*y%11%10`.

**Explanation:**

Try it here.

```
o->{                     // Unused Object parameter and String return-type
  String r="";           //  Result-String
  for(int x=0,y;++x<11;  //  Loop (1) from 1 to 11 (exclusive)
      r+="\n")           //    And append a new-line after every iteration
    for(y=0;++y<11;      //   Inner loop (2) from 1 to 11 (exclusive)
      r+=x*y%11%10       //    And append the result-String with `x*y%11%10`
    );                   //   End of inner loop (2)
                         //  End of loop (1) (implicit / single-line body)
  return r;              //  Return result-String
}                        // End of method

```

# Answer
> 1 votes
# Python 2, ~~58~~ 52 bytes

*-6 bytes thanks to offcialaimm.*

Uses Martin's algorithm which I have no understanding of how he came up with it so fast. o0

```
r=range(1,11)
print[[x*y%11%10for y in r]for x in r]

```

Try it online!

# Answer
> 1 votes
# Pyth, 13 bytes

```
mme%*kd11STST

```

Try it here

-1 thanks to KarlKastor.

*Let's duuuuuuupe!*

# Answer
> 1 votes
# , 19 bytes

```
1:10%o%1:10%%11%%10

```

Try it online!

The least "R"-looking bit of R code I have ever written. Uses the same algorithm as Martin Ender's answer (and almost all the other answers as well). `x %o% y` is the same as `outer(x, y)`.

# Answer
> 0 votes
# C (gcc), 70 bytes

```
f(x,y){for(x=0;x++<10;puts(""))for(y=0;y++<10;putchar(x*y%11%10+48));}

```

Try it online!

# Answer
> 0 votes
# Retina, ~~93~~ 85 bytes

```

10$*T
M!&`T+
m`$
;110$*T10$*
1
09876543210
m`(?<=^\1;\1{0,9}(T+))T
C
(?<!C.{108})\S

```

Try it online!

# Answer
> 0 votes
# PHP, 54 bytes

```
for(;9>=$y++||9>=$x+=$y=print"
";)echo($x+1)*$y%11%10;

```

Try it online!

# PHP, 56 bytes

```
for(;$x++<=9;print"
")for($y=0;$y++<=9;)echo$x*$y%11%10;

```

Try it online!

# Answer
> 0 votes
# QBIC, 17 bytes

```
[|?[|?a*b%11%z';

```

This, of course, uses Martin's Method. It translates to this QBasic code.

## Explanation

```
[|               FOR A = 1 to 10 ([ starts a FOR loop, | delimits the list of arguments;
                 a FOR loop with 0 args loops from 1 to 10 by default with increment 1.
  ?              PRINT a newline
   [|            Start a second FOR loop from 1-10, iterator b
     ?           PRINT
      a*b%11%z   the result of Martin's formula.
              '; and suppress newlines/tabs/spaces

```

# Answer
> 0 votes
# C#, 81 bytes

```
_=>{var r="";for(int x=0,y;++x<11;r+="\n")for(y=0;++y<11;r+=x*y%11%10);return r;}

```

Same algorithm as most of the other answers and essentially the C# port of @Kevins Java answer.

# Answer
> 0 votes
# Retina, 79 bytes

```

12345678902468013579369147025848159260375049382716
.*
$&$&
O$^50>`.

.{10}
$&¶

```

Try it online!

# Answer
> 0 votes
# GolfScript, ~~37~~ 24 bytes

```
10,{){\)*11%10%}+10,%}%`

```

Try it online!

-13 thanks to a clever trick Martin Ender suggested.

# Answer
> 0 votes
# C (gcc), 59 bytes

```
f(n,t){for(n=11;++n<121;putchar(t?t%10+48:10))t=n/11*n%11;}

```

Try it online!

# Answer
> 0 votes
## Pyke, 15 bytes

```
TD]UMha*11%`e)P

```

Try it here!

# Answer
> 0 votes
## Pyke, 13 bytes

```
TS F~u0+*i>i%

```

Try it here!

```
TS            -  [1, 2, 3, 4, 5, 6, 7, 8, 9]
   F~u0+*i>i% - for i in ^:
    ~u0+      -     "01234567890"
        *     -    ^ * i
         i>   -   ^[i:]
           i% -  ^[::i]

```

# Answer
> 0 votes
## TECO, 45 bytes

```
1un@i/
/10<@i/01234567890/jl10<qnc0a^t>jtl%n>

```

A (fairly) straightforward implementation of Rod's Python answer.

```
1un           !initialize register n to 1!
@i/<nl>/      !insert a newline!
10<           !loop for 10 rows!
@i/01234567890/  !insert the mysterious string of digits!
j             !move point to start of buffer!
l             !move forward past the newline!
10<           !loop for 10 digits on a line!
qnc           !move point forward by n characters!
0a^t          !print the character at point!
>             !end inner loop!
j             !move point to start of buffer!
t             !print (empty) line!
l             !move to start of digit string!
%n            !increment register n (for next line)!
>             !end outer loop!

```

Using \<ESC\>-terminated inserts and a control character for the ^T command would save another ~~three~~ five bytes, at the expense of readability.

Using Martin's mod-11/mod-10 formula actually makes it longer at 43 bytes using controls for ^A and ^T, mostly because TECO doesn't have a mod operator.

```
0ur10<%run10<qn-10"g-11%n'qn\r0a^Tqr%n>^a
^A>

```

Mod 11 is done in an ongoing fashion by incrementing the number in qn by -11 whenever it exceeds 10. The `qn\r0a^T` sequence inserts the number in the editing buffer as decimal digits, reverses past the last digit, retrieves it from the buffer and types it, essentially doing mod-10.

I expected it to be shorter. Oh, well.

# Answer
> 0 votes
# , 27 bytes

```
1":(10|11|*&>:)"0/~@(i.@9:)

```

Try it online!

Uses the same trick as in Martin Ender's Mathematica answer.

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


title: Fizz-Buzzify a String

text:
# Question
Title: Fizz-Buzzify a String
You will be given a String that only contains letters of the English Alphabet, both lowercase and uppercase (ASCII 65-90 and 97-122). Your task is to output the Fizz-Buzzified version of the String.

### How to Fizz-Buzzify a String?

* Each letter that has an even index in the English alphabet (the alphabet **must** be 1-indexed: `a->1,b->2,...,z->26`) will be turned into `fizz` if it is lowercase and `FIZZ` if it is uppercase (`f -> fizz, F -> FIZZ`).
* Each letter that has an odd index in the English alphabet will be turned into `buzz` if it is lowercase, and `BUZZ` if it is uppercase (`e -> buzz, E -> BUZZ`).
* Let's have an example, to illustrate the algorithm, using the string `CodeGolf` (spaces added for clarity):

```
"C o d e G o l f" ->  "BUZZ buzz fizz buzz BUZZ buzz fizz fizz"
 ^ ^ ^ ^ ^ ^ ^ ^
 1 1 0 1 1 1 0 0       (1 is odd index, 0 is even index)

```
* If it is more convenient for your language, you may also leave *single spaces* between the groups (`fizz, buzz, FIZZ, BUZZ`). Hence, a result like `fizzBUZZbuzzbuzz` can also be returned as `fizz BUZZ buzz buzz`. Other separators are not allowed.

---

# Test Cases:

```
Input  ->  Output

"egg"          ->  "buzzbuzzbuzz"
"CodeGolf"     ->  "BUZZbuzzfizzbuzzBUZZbuzzfizzfizz"
"Reset"        ->  "FIZZbuzzbuzzbuzzfizz"
"ATOM"         ->  "BUZZFIZZBUZZBUZZ"
"yOuArEgReAt"  ->  "buzzBUZZbuzzBUZZfizzBUZZbuzzFIZZbuzzBUZZfizz"

```

---

* Any standard method for I/O can be used.
* Default Loopholes apply.
* You are only allowed to take input in your language's native String type. The same applies for output.
* You can assume that the input will not be empty.
* Shortest code in bytes in every language wins. Good Luck and Fizz-Buzz!

# Answer
# Charcoal, ~~26~~ 24 bytes

```
ＦθＦ⎇﹪℅ι²buzz¦fizz⎇№αι↥κκ

```

Try it online! Originally inspired by @CarlosAlejo. Edit: Saved 2 bytes by looping over the letters of fizz/buzz instead of assigning to a temporary. Explanation:

```
Ｆθ          Loop over the input (i = loop variable)
  Ｆ         Choose and loop over the word (k = loop variable)
   ⎇        Ternary
    ﹪℅ι²    If i has an odd ASCII code
    buzz
    fizz
            Print (implicit)
  ⎇         Ternary
   №αι      If i is an uppercase letter
    ↥κ      Uppercase(k)
     κ      k

```
> 7 votes

# Answer
# C#, 92 bytes

```
using System.Linq;a=>string.Concat(a.Select(x=>x%2<1?x<97?"FIZZ":"fizz":x<97?"BUZZ":"buzz"))

```
> 6 votes

# Answer
# Python 3, ~~73~~ 69 bytes

4 bytes thanks to ovs.

```
lambda s:"".join("fbFBiuIUzzZZzzZZ"[(c<"a")*2+ord(c)%2::4]for c in s)

```

Try it online!
> 5 votes

# Answer
# Java (OpenJDK 8), ~~105~~ ~~100~~ ~~94~~ ~~91~~ 90 bytes

```
s->{for(int i:s.getBytes())System.out.print(i%2<1?i>90?"fizz":"FIZZ":i>90?"buzz":"BUZZ");}

```

Try it online!

Much golfable, very bytes, so Java!

Very golfed by @KevinCruijssen by 9 bytes!
> 4 votes

# Answer
# C (gcc), 75 bytes

```
f(char*s){for(;*s;++s)printf(*s>90?*s%2?"buzz":"fizz":*s%2?"BUZZ":"FIZZ");}

```

Try it online!
> 4 votes

# Answer
# Plain English, ~~820~~ ~~632~~ 610 bytes

Mr. Xcoder suggested eliminating an unneeded error trap, which saved 22 bytes.

```
A fizzy string is a string.
To convert a s string to a z fizzy string:
Clear the z.
Slap a r rider on the s.
Loop.
If the r's source's first is greater than the r's source's last, exit.
Put the r's source's first's target in a b byte.
If the b is not any letter, bump the r; repeat.
Put "FIZZ" in a t string.
If the b is d, put "BUZZ" in the t.
If the b is _, lowercase the t.
Append the t to the z.
Bump the r.
Repeat.
To decide if a b byte is d:
Put the b in a n number.
If the n is odd, say yes.
Say no.
To decide if a b byte is _:
Put the b in a c byte.
Lowercase the c.
If the c is the b, say yes.
Say no.

```

Ungolfed code:

```
A fizzy string is a string.

To convert a string to a fizzy string:
  Clear the fizzy string.
  Slap a rider on the string.
  Loop.
    If the rider's source's first is greater than the rider's source's last, exit.
    Put the rider's source's first's target in a byte.
    If the byte is not any letter, bump the rider; repeat.
    Put "FIZZ" in another string.
    If the byte is odd, put "BUZZ" in the other string.
    If the byte is lower case, lowercase the other string.
    Append the other string to the fizzy string.
    Bump the rider.
  Repeat.

To decide if a byte is odd:
  Put the byte in a number.
  If the number is odd, say yes.
  Say no.

To decide if a byte is lower case:
  Privatize the byte.
  Lowercase the byte.
  If the byte is the original byte, say yes.
  Say no.

```

The Plain English IDE is available at github.com/Folds/english. The IDE runs on Windows. It compiles to 32-bit x86 code.
> 4 votes

# Answer
# Pyth, ~~23~~ 21 bytes

```
smr<d\a@c"fizzbuzz"4C

```

Test suite.
> 3 votes

# Answer
# C#, 97 bytes

```
using System.Linq;s=>string.Concat(s.Select(c=>"fizzbuzzFIZZBUZZ".Substring(c%2*4+(c>96?0:8),2)))

```
> 3 votes

# Answer
## JavaScript (ES6), ~~79~~ 77 bytes

```
s=>s.replace(/./g,c=>['BUZZ','buzz','FIZZ','fizz'][parseInt(c,36)%2*2|c>'Z'])

```

### Test cases

```
let f =

s=>s.replace(/./g,c=>['BUZZ','buzz','FIZZ','fizz'][parseInt(c,36)%2*2|c>'Z'])

console.log(f("egg"        )) // "buzzbuzzbuzz"
console.log(f("CodeGolf"   )) // "BUZZbuzzfizzbuzzBUZZbuzzfizzfizz"
console.log(f("Reset"      )) // "FIZZbuzzbuzzbuzzfizz"
console.log(f("ATOM"       )) // "BUZZFIZZBUZZBUZZ"
console.log(f("yOuArEgReAt")) // "buzzBUZZbuzzBUZZfizzBUZZbuzzFIZZbuzzBUZZfizz"
```
> 3 votes

# Answer
# Jelly, 21 bytes

```
“=%“Ƈ×»ẋ13Œu;$ɓØWiÐ€ị

```

Try it online!
> 3 votes

# Answer
# Charcoal, 40 36 bytes

```
Ｆθ¿№αι¿﹪⌕αι²FIZZ¦BUZZ¿﹪⌕βι²fizz¦buzz

```

Try it online!

Explanation:

```
Ｆθ                                      for every char i in the input:
   ¿№αι                                    if i is found in the uppercase alphabet
       ¿﹪⌕αι²                             if i is an even uppercase char
              FIZZ¦BUZZ                    print "FIZZ" or else "BUZZ"
                       ¿﹪⌕βι²             if i is an even lowercase char
                              fizz¦buzz    print "fizz" or else "buzz"

```

An alternative with the same byte count:

```
ＡfizzφＡbuzzχＦθ¿№αι¿﹪⌕αι²↥φ↥χ¿﹪⌕βι²φχ

```

Try it online! (Verbose version)

* 4 bytes saved thanks to Neil!
> 2 votes

# Answer
## \>\<\>, 68 bytes

```
<vv?("^"$%2:;?(0:i
v\?\"zzif"
v \\"zzub"
v \ "ZZIF"
v  \"ZZUB"
\oooo

```

Try it online, or watch it at the fish playground!

(But look at Aaron's answer which is 13 bytes shorter!)

If you're not familiar with \>\<\>, there's a fish that swims through the code in 2D, and the edges wrap. The symbols `>`, `<`, `^` and `v` set the direction of the fish, `/` and `\` are mirrors that reflect it, and `?` means "do the next instruction if the top thing on the stack is non-zero, otherwise jump over the next instruction".

In the first line, the fish takes a character of input (`i`); if it's -1 for EOF, it halts (`:0(?;`); it gets the charcode mod 2 (`:2%$`); and it pushes a 1 or 0 on the stack depending on whether the charcode is less than or greater than the charcode of "^" (`"^"(`). The next three lines redirect the fish to the right fizz/buzz string, then the last line prints it (one `o` for each character) and sends the fish back to the start.
> 2 votes

# Answer
# \>\<\>, 55 bytes

Based on Not a tree's answer.

```
<v%2$)"^":;?(0:i
 \?v"ZZIF"
~v >"ZZUB"!
^>{:}" "*+ol1=?

```

Instead of representing the 4 possible output in the code, I only represent their capitalized versions and add 32 to the character code to get the small case equivalents.

Try it online !

Modified code for the online interpreter, which pads its codespace with empty cells :

```
<v%2$)"^":;?(0:i
 \?v"ZZIF"
~v >"ZZUB"     !
^>{:}" "*+o l1=?

```
> 2 votes

# Answer
# Perl5, 50+1 bytes

```
perl -nE'say+((FIZZ,BUZZ)x48,(fizz,buzz)x16)[unpack"C*",$_]'

```

Creates a 128-item list that maps ASCII chars to the proper code word.
> 2 votes

# Answer
# 05AB1E, 22 bytes

```
v‘FIZZÒÖ‘#yÇÉèAyåil}J?

```

Try it online!

**Explanation**

```
v                        # for each char y of input string
 ‘FIZZÒÖ‘#               # push the list ['FIZZ','BUZZ']
          yÇÉ            # check if y has an odd character code
             è           # use this to index into the list
              Ayåi       # if y is a member of the lowercase alphabet
                  l}     # convert to lowercase
                    J?   # unwrap from list and print

```

**Alternative 22 byte solution**

```
ÇÉAISå·+‘FIZZÒÖ‘#Dl«èJ

```
> 1 votes

# Answer
# F#, ~~154~~ ~~153~~ 145 bytes

saved ~~1~~ 9 bytes thanks to @Mr. Xcoder

```
let g s=
 Seq.map(fun c->match int c with
|x when x>64&&x<91->if x%2=0 then"FIZZ"else"BUZZ"
|x->if x%2=0 then"fizz"else"buzz")s
|>String.concat""

```

Try it online!
> 1 votes

# Answer
# PHP, 67 bytes

```
for(;$c=$argn[$i++];)echo[FIZZ,BUZZ,fizz,buzz][ord($c)%2+2*($c>Z)];

```

Try it online!
> 1 votes

# Answer
# Mathematica, 134 bytes

```
""<>{(s=Max@ToCharacterCode@#;If[96<s<123,If[EvenQ@s,c="fizz",c="buzz"]];If[64<s<91,If[EvenQ@s,c="FIZZ",c="BUZZ"]];c)&/@Characters@#}&

```
> 1 votes

# Answer
# Java 8, 89 bytes

```
s->s.chars().mapToObj(i->i%2<1?i>90?"fizz":"FIZZ":i>90?"buzz":"BUZZ").collect(joining());

```

It assumes `import static java.util.stream.Collectors.*;`
> 1 votes

# Answer
# Swift 4, ~~144~~ 135 bytes

```
func f(s:String){print(s.map{let d=Int(UnicodeScalar("\($0)")!.value);return d%2<1 ?d>90 ?"fizz":"FIZZ":d>90 ?"buzz":"BUZZ"}.joined())}

```

Un-golfed:

```
func f(s:String){
    print(
        s.map{
            let d=Int(UnicodeScalar("\($0)")!.value)
            return d%2 < 1 ? d > 90 ? "fizz" : "FIZZ" : d > 90 ? "buzz" : "BUZZ"
        }.joined()
    )
}

```

What I am doing is looping over each character in the string. I convert each to its ASCII value, then check to see if it is even or odd, and then check to see if it is upper or lowercase and output the matching value from the loop. I then join all the elements of the resulting array into a single string and print it.

This solution uses Swift 4, so there is no way to easily test it online yet.

Thanks to @Mr.Xcoder for saving me 9 bytes!
> 1 votes

# Answer
## R, ~~150~~ ~~123~~ 108 bytes

```
i=ifelse
cat(i(sapply(el(strsplit(scan(,''),'')),utf8ToInt)>91,i(x%%2,'buzz','fizz'),i(x%%2,'BUZZ','FIZZ')))

```

~~Has to be shorter using ASCII?~~ It was shorter. See edit history for old answer, which used `letters`.

Checks each letter for (1) whether it's capital or not (`>91`) and whether it's a `fizz` or a `buzz`.
> 1 votes

# Answer
# q/kdb+, 48 bytes

**Solution:**

```
raze{@[($)`fizz`buzz x mod 2;(&)x<91;upper]}"i"$

```

**Examples:**

```
q)raze{@[($)`fizz`buzz x mod 2;(&)x<91;upper]}"i"$"egg"
"buzzbuzzbuzz"
q)raze{@[($)`fizz`buzz x mod 2;(&)x<91;upper]}"i"$"CodeGolf"
"BUZZbuzzfizzbuzzBUZZbuzzfizzfizz"
q)raze{@[($)`fizz`buzz x mod 2;(&)x<91;upper]}"i"$"Reset"
"FIZZbuzzbuzzbuzzfizz"
q)raze{@[($)`fizz`buzz x mod 2;(&)x<91;upper]}"i"$"ATOM"
"BUZZFIZZBUZZBUZZ"
q)raze{@[($)`fizz`buzz x mod 2;(&)x<91;upper]}"i"$"yOuArEgReAt"
"buzzBUZZbuzzBUZZfizzBUZZbuzzFIZZbuzzBUZZfizz"

```

**Explanation:**

Fairly straightforward, take the input string, cast into ASCII values, create a list of 1 or 0 depending whether it is odd or even (hint A=65=odd), then use this list to index into a list of `fizz` and `buzz`. Cast this to a string, and then for cases where the input is \<91 (lower than a Z) we apply the `upper` function to get a `FIZZ` or a `BUZZ`.

q is interpreted right to left:

```
raze{@[string `fizz`buzz x mod 2;where x < 91;upper]}"i"$ / ungolfed version
                                                     "i"$ / cast input to ascii values
    {                                               }     / anonymous lambda
     @[                         ;            ;     ]      / apply
                                              upper       / upper-case
                                 where x < 91             / indices where input is less than 91 (ie uppercase)
                         x mod 2                          / returns 0 if even and 1 if odd
              `fizz`buzz                                  / 2 item list, which we are indexing into
       string                                             / cast symbols to strings `buzz -> "buzz"
raze                                                      / raze (merge) list into a single string

```
> 1 votes

# Answer
# Ruby, 61+1 = 62 bytes

Uses the `-p` flag.

```
gsub(/./){k=$&.ord%2*4;$&<?_?"FIZZBUZZ"[k,4]:"fizzbuzz"[k,4]}

```

Try it online!
> 1 votes

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


title: Reindent Java/C/C++/etc. code

text:
# Question
Title: Reindent Java/C/C++/etc. code
Write a program that adds or removes whitespace to format code nicely. Rules for what the code should look like when you're done:

* No line should contain more than one of `{` and `}`.
* A `{` should always be the last thing on a line.
* A `}` should always be the *only* thing on a line (besides whitespace that comes before it).
* The amount of whitespace in front of each line should be a fixed multiple of the current nesting count. (You can use any amount of indentation you want, as long as it doesn't change.)
* No whitespace should be inserted or removed that doesn't contribute to satisfying one of these rules.

The nesting count for the first line is 0. The nesting count of any other line is the nesting count of the previous line, plus one if the previous line contains a `{`, minus one if the current line contains a `}`.

`{` and `}` inside string literals and comments don't count in the above rules. A string literal is text enclosed in single or double quotes, where single or double quotes with an odd number of backslashes immediately before them aren't interpreted as the end of the string literal. A comment is text enclosed in `/*` and `*/`, or text going from `//` to the end of the line. In a line multiple comment start markers, only the first one counts. Comments are not parsed inside string literals.

# Examples

```
    main() {printf("Hello!"); // I don't care about the world...
        }

becomes:

main() {
    printf("Hello!"); // I don't care about the world...
}

int main(){
    puts("a");
        puts("b");
}

becomes:

int main(){
    puts("a");
    puts("b");
}

main()
{ printf("{"); /* }
} */
     printf("}//}"); ///*
    }

becomes:

main()
{
    printf("{"); /* }
} */
    printf("}//}"); ///*
}

int test[] = {1, 2, 3};

becomes:

int test[] = {
    1, 2, 3
}
;

```

# Answer
> 6 votes
## JavaScript (ES6), ~~376~~ ~~373~~ ~~378~~ 393 bytes

This was... quite the challenge...

```
let f =

s=>{F=(i,l=1)=>[a=a.map(([q,y])=>[q,y<i+e?y:y+l]),e+=l]
for(a=b=[];b;s=s[r='replace'](/\/\*(?:(?!\/\*|\*\/)[^])*\*\/|\/\/.+|("|')(?:\\.|(?!\1).)*\1/,(q,_,y)=>a.unshift(b=[q,y])&0))b=l=0
s=s[e=1,r](/[{}](?=.)|.(?=})/g,(c,i)=>F(i)&&c+`
`)[e=0,r](/.+/g,(x,i)=>x[r](/^\s*/,y=>" ".repeat(q=/{/.test(x)?l++:/}/.test(x)?--l:l,F(i,q-y.length))))
a.map(([q,y])=>s=s.slice(0,y)+q+s.slice(-~y))
return s}
```

```
<textarea rows=7 cols=50 oninput=O.innerText=f(value)>    main() {printf("Hello!"); // I don't care about the world...
    }</textarea>
<pre id=O></pre>
```

Let me know if there's anything wrong with the output, though I ~~couldn't find anything~~ can't find anything more.

### Ungolfed version

I golfed the code as I wrote it, so let's see how this goes...

```
function prettify(code) {
  let excerpts = [], extras, level;

  // Extract comments and strings for easy parsing
  // This has to be done recursively because of the nested comments
  for (let done = false; !done; ) {
    done = true;
    code = code.replace(/\/\*(?:(?!\/\*|\*\/)[^])*\*\/|\/\/.+|("|')(?:\\.|(?!\1).)*\1/, (excerpt, _, index) => {
      excerpts.unshift([excerpt, index]);
      done = false;
      return "0";
    });
  }

  // Update the indices of the excerpts when the code is changed
  let adjustIndices = (index, length) => {
    index += extras;
    excerpts = excerpts.map(([string, oldIndex]) => {
      var newIndex = oldIndex;
      if (oldIndex >= index) newIndex += length;
      return [string, newIndex];
    });
    extras += length;
  }

  // Add extra newlines where necessary:
  // - After a { or a } if there isn't one already
  // - Before a } if there isn't one already (note: already-indented '}'s will get an extra newline)
  extras = 0;
  code = code.replace(/[{}](?=.)|.(?=})/g, (char, index) => {
    adjustIndices(index + 1, 1);
    return char + "\n";
  });

  // Remove extra whitespace at the beginning of each line,
  // and the same time apply the necessary number of tabs
  extras = 0;
  level = 0;
  code = code.replace(/.+/g, (line, index) =>
    line.replace(/^\s*/, spaces => {
      let tabs;
      if (line.indexOf('{') > -1)
        tabs = level, level += 1;
      else if (line.indexOf('}') > -1)
        level -= 1, tabs = level;
      else
        tabs = level;

      adjustIndices(index, tabs - spaces.length);
      return "\t".repeat(tabs);
    })
  );

  // Add back in the excerpts
  for ([excerpt, index] of excerpts)
    code = code.slice(0, index) + excerpt + code.slice(index + 1);

  return code;
}
```

```
<textarea rows = 7 cols = 50 oninput = "O.innerText = prettify(this.value)">    main() {printf("Hello!"); // I don't care about the world...
    }</textarea>
<pre id=O></pre>
```

# Answer
> 4 votes
## JavaScript (ES6), ~~260~~ 259 bytes

Parses the input character by character. Uses 4-space indentation.

```
s=>s.replace(/[^]/g,(x,n)=>(p=s[n-1],a=!l&!c&!e,l|x!='/'?a&x=='*'&p=='/'?c=x:!c&!e&x=='"'?(l^=1,x):x==`
`?(i=e=0,x):a&x=='}'?d--&&i?`
`+x:i=x:a&x=='{'?s[i=!++d,n+1]==`
`?x:x+`
`:i?x:x==' '?'':' '.repeat(!c*d*4,i=1)+x:p==x?e=x:!e&p=='*'?(c=0,x):x),d=i=l=c=e=0)

```

This is still a WIP and was basically tested only against the provided examples. If you find any bug, please let me know in the comments.

The state of the parser is fully described by the following variables:

* `d` → current nesting depth
* `i` → flag telling that we're located 'inside' the code (i.e. after the leading spaces of the line)
* `l` → string literal flag
* `c` → block comment flag
* `e` → line comment flag

### Obligatory indented version

```
s => s.replace(
  /[^]/g,
  (x, n) => (
    p = s[n - 1],
    a = !l & !c & !e,
    l | x != '/' ?
      a & x == '*' & p == '/' ?
        c = x
      :
        !c & !e & x == '"' ?
          (l ^= 1, x)
        :
          x == `\n` ?
            (i = e = 0, x)
          :
            a & x == '}' ?
              d-- && i ? `\n` + x : i = x
            :
              a & x == '{' ?
                s[i = !++d, n + 1] == `\n` ? x : x + `\n`
              :
                i ?
                  x
                :
                  x == ' ' ? '' : ' '.repeat(!c * d * 4, i = 1) + x
    :
      p == x ?
        e = x
      :
        !e & p == '*' ? (c = 0, x) : x
  ),
  d = i = l = c = e = 0
)

```

### Test cases

```
let f =

s=>s.replace(/[^]/g,(x,n)=>(p=s[n-1],a=!l&!c&!e,l|x!='/'?a&x=='*'&p=='/'?c=x:!c&!e&x=='"'?(l^=1,x):x==`
`?(i=e=0,x):a&x=='}'?d--&&i?`
`+x:i=x:a&x=='{'?s[i=!++d,n+1]==`
`?x:x+`
`:i?x:x==' '?'':' '.repeat(!c*d*4,i=1)+x:p==x?e=x:!e&p=='*'?(c=0,x):x),d=i=l=c=e=0)

console.log(f(
  `    main() {printf("Hello!"); // I don't care about the world...\n` +
  `        }`
))

console.log(f(
  `int main(){\n` +
  `    puts("a");\n` +
  `        puts("b");\n` +
  `}`
))

console.log(f(
  `main()\n` +
  `{ printf("{"); /* }\n` +
  `} */\n` +
  `     printf("}//}"); ///*\n` +
  `    }`
))

console.log(f(
  `int test[] = {1, 2, 3};`
))
```

---
Tags: code-golf, whitespace, syntax
---


title: efficient farming

text:
# Question
Title: efficient farming
# Introduction

A farmer needs help calculating the least time it will take him to pick his fruit each day.

# Challenge

* This farmer has `X` orchards.
* Each orchard has `Y` fruits in it. If the orchard has no fruits, then it will contain the string "none".
* The farmer has a list, this list contains the fruit he must pick.
* The farmer will only go down the list **in order**
* You must calculate how long it will take the farmer to pick his fruit on each day.

### More on the orchards

* All of the orchards are in a line.
* Each orchard is exactly `1` unit away from the next and previous one.
* The farmer can go up and down the line, but may not jump from one orchard to another

# Input and Output

You will receive an input in the following format:

```
X
*string*
*string*
*string* *string* *string* *string*
*string*
//ect.
Y
*string* *string*
*string* *string*
*string* *string*
*string* *string*
//ect.

```

`X` is the number of orchards

* Everything after `X` and before `Y` is an orchard containing a/some string(s), each string is a different fruit in that orchard.

`Y` is the number of days that the farmer must gather fruit.

* Each day consists of two strings that are different fruits.
* You must find what orchard these strings are in and calculate the difference.

### Input Rules:

1. Each fruit name string will be one word with **no spaces**

### Real Example

Still confused? Maybe this will clear it up:

Input

```
6

none

apple

orange pear pear

none

orange lemon pumpkin

pumpkin lettuce flowers peas

4

peas lettuce

apple orange

apple pumpkin

flowers orange

```

output: `[ 0, 1, 3, 1 ]`

### Explanation

Input:

* `6` the number of orchards
* A set of `6` orchards containing fruit, each orchard on a new line.
* `4` the number of days on the farmers list.
* A set of `4` fruits to compare, each pair of fruits is on a new line.

Output:

* Output an array of the differences between each set of fruits.
* The difference between peas and lettuce is `0`, because they are in the same orchard.
* The difference between apples and oranges is `1` because they are one orchard apart.
* The difference between apples and pumpkins is `3` Because they are three orchards apart.
* The difference between flowers and oranges is `1` because they are one orchard apart.

---

Annotated input/output

```
6 orchards

a none

b apple

c orange pear pear

d none

e orange lemon pumpkin

f pumpkin lettuce flowers peas

--

4 fruits

peas lettuce 0

apple orange 1

apple pumpkin 3

flower orange 1

--

output: [ 0, 1, 3, 1 ]

```

# How To Win

Shortest code in bytes wins.

# Rules

# Disclamer

I submitted this question to the sandbox, but I did not get any feedback on it, so feel free to edit as you see needed.

# Answer
# 176 bytes, Python 3

```
def p(a):l=[b.split()for b in a.split('\n')];X=int(l[0][0]);return[min(y-x for y in range(X)for x in range(y+1)if z[0]in l[x+1]+l[y+1]and z[1]in l[x+1]+l[y+1])for z in l[X+2:]]

```

This can be called by passing in the entire content as a string

```
p("""6
none
apple
orange pear pear
none
orange lemon pumpkin
pumpkin lettuce flowers peas
4
peas lettuce
apple orange
apple pumpkin
flowers orange""")

```

Ungolfed solution

```
def problem(a):
    # this will split on new line, and split each individual line into it's own list
    lines=[b.split()for b in a.split('\n')]
    # get the number of orchards
    X=int(lines[0][0])
    return[
        # get the minimum of all possible differences
        min(y-x # subtract y and x to get the difference
            for y in range(X) # for each orchard, y
                for x in range(y+1) # and each orchard up to y inclusive, x
                    if z[0] in lines[x+1]+lines[y+1] and z[1] in lines[x+1]+lines[y+1]) # if both fruits exist the x and y orchards
        # for every day (z is a list containing 2 fruits as string)
        for z in lines[X+2:]
    ]

```
> 2 votes

# Answer
# Java 10, ~~307~~ ~~298~~ ~~288~~ ~~280~~ ~~273~~ 271 bytes

```
s->{String[]a=s.split("\\d"),o=a[1].split("\n"),f=a[2].split("\n");int r[]=new int[f.length-1],q=-2,d,i,j,z;for(var p:f)if(++q>=0)for(z=d=o.length,i=0;++i<d;)for(j=0;o[i].contains((f=p.split(" "))[0])&++j<z;)r[q]=d=o[j].contains(f[1])?Math.min(i>j?i-j:j-i,d):d;return r;}

```

-19 bytes thanks to *@ceilingcat*.

**Explanation:**

Try it here.

```
s->{                           // Method with String parameter & integer-array return
  String[]a=s.split("\\d"),    //  Split the input on numbers
          o=a[1].split("\n"),  //  List of orchards
          f=a[2].split("\n");  //  List of pairs (later on reused for individual pair of fruits)
  int r[]=new int[f.length-1], //  Result integer-array
      q=-2,d,i,j,z;            //  Some temp integers
  for(var p:f)                 //  Loop `p` over the pairs:
    if(++q>=0){                //   If this isn't the first iteration of the pair-loop
                               //   (the first item is always empty after `.split("\\d")`)
      for(z=d=o.length,i=0;++i<d;)
                               //    Inner loop `i` over the orchards:
        for(j=0;o[i].contains((f=p.split(" "))[0])
                               //     If the current orchard contains the first fruit of the pair:
                &++j<z;)       //      Inner loop `j` over the orchards again:
          r[q]=                //       Add the following to the resulting array:
               d=o[j].contains(f[1])?
                               //       If the current orchard contains the second fruit of the pair:
                 Math.min(     //        Take the minimum of:
                   i>j?i-j:j-i,//         The absolute difference between `i` and `j`
                   d)          //         And the current integer of the array
               :               //       Else:
                d;             //        Leave the current integer unchanged
  return r;}                   //  Return the result array

```
> 0 votes

# Answer
# JavaScript (ES6), 224 bytes

```
a=>(d=a.split('\n')).slice(e=+d[0]+2).map(f=>{p=e;for(g=(q=(t,s=0)=>d.slice(1,e-1).map(b=c=>c.split(' ')).findIndex((x,y)=>y>=t&x.includes(b(f)[s])))(0);++g;g=q(g))for(l=q(0,1);++l;l=q(l,1))p=p<(u=g>l?g-l:l-g)?p:u;return p})

```

Call with `"6\nnone\napple\norange pear pear\nnone\norange lemon pumpkin\npumpkin lettuce flowers peas\n4\npeas lettuce\napple orange\napple pumpkin\nflowers orange"`
> 0 votes

# Answer
# Röda, 118 bytes

```
{A=[head(parseInteger(pull()))|splitMany|enum]pull n;split|{f={|x|A|[_2]if[x in _1]}f a|{|i|f b|abs i-_}_|min}for a,b}

```

Explanation:

```
{
    A=[
        /* Pull line, convert to integer, and read that many lines */
        head(parseInteger(pull()))|
        /* Split all lines to arrays */
        splitMany|
        /* Enumerate, ie. give each line a number */
        enum
    ]
    /* Discard one line */
    pull n;
    /* Split each following line and push words to the stream */
    split|
    /* For each word a, b in the stream: */
    {
        /* Helper function to find lines that contain x */
        f={|x|A|[_2]if[x in _1]}
        /* Push numbers of lines that contain the first word to the stream */
        f a|
        /* For each line number i */
        {|i|
            /* Push numbers of lines that contain the second word to the stream */
            f b|
            /* Push the difference of two line numbers to the stream */
            abs i-_
        }_|
        /* Push the smallest difference to the stream */
        min
    }for a,b
}

```

No TIO link yet, as the TIO version of Röda is outdated.
> 0 votes

---
Tags: code-golf
---


title: Degree of Unsaturation

text:
# Question
Title: Degree of Unsaturation
## Degree of Unsaturation

This is not a particularly hard code puzzle - but I'm interested to see your multiple ways of solving it.

The Degree of Unsaturation is the number of double chemical bonds between atoms, and/or the number rings in a chemical compound.

You will be given the molecular formula of a chemical compound in the form XaYbZc (where a, b and c are the number of atoms of X, Y or Z in the compound) - the formula could be of any length and contain any chemical element in the periodic table (though elements other than C, H, N, F, Cl, Br, I may be ignored as they do not feature in the formula). The compound will contain at least one atom of carbon. You must calculate and display its Degree of Unsaturation.

For example, the compound benzene (pictured below) has a DoU of 4 as it has three double bonds (shown by a double line between atoms), and a single ring (a number of atoms connected in a loop):

As defined by LibreTexts:

> DoU = (2C + 2 + N − X − H ) / 2

Where:

* `C` is the number of carbon atoms
* `N` is the number of nitrogen atoms
* `X` is the number of halogen atoms (`F`, `Cl`, `Br`, `I`)
* `H` is the number of hydrogen atoms

## Test cases:

```
C6H6 --> 4
C9H2O1 --> 0
C9H9N1O4 --> 6
U1Pt1 --> Not a valid input, no carbon
Na2O1 --> Not a valid input, no carbon
C1H1 --> 1.5, although in practice this would be one, but is a part of a compound rather than a compound in entirety.
N1H3 would return 0 - though in practice it isn't an organic compound (in other words it contains no carbon) so the formula wouldn't apply and it isn't a valid input

```

For an explanation of CH see here

**In essence, you must identify if there are any of the above elements (C, H, N, F, Cl, Br, I) in the compound, and if so how many there are. Then, calculate the Degree of Unsaturation using the above formula.**

Only C, H, N, F, Cl, Br, and I are valid inputs for the DoU formula. For the purposes of this puzzle, any other elements may be completely ignored (eg if the compound were C6H6Mn the result would still be 4). If there are none of the above compounds the answer would be zero.

You may assume that all the compounds input are chemically possible, contain at least one atom of carbon, and are known to exist. If the input is invalid, the program may output either 0 or -1, or produce no result.

## Rules

Standard IO rules and loopholes apply. Input must be a standard string, and you can assume the input won't be empty. This is codegolf - so the shortest code in bytes wins.

# Answer
> 2 votes
# Python 3, ~~142 151~~ 148 bytes

```
import re
l=dict(re.findall("(\D+)(\d+)",input()))
m=lambda k:int(l.get(k,0))
print(m("C")and m("C")+1+(m("N")-sum(map(m,"F I H Cl Br".split())))/2)

```

Returns 0 on error.

Thanks to @HyperNeutrino bringing the bytes down.

Try it online!

# Answer
> 2 votes
## JavaScript (ES6), ~~117~~ 112 bytes

Returns `0` for invalid inputs.

```
s=>s.split(/(\d+)/).reduce((p,c,i,a)=>p+[0,k=a[i+1]/2,2*k,-k][n='NCFHIClBr'.search(c||0)+1,s|=n==2,n>2?3:n],1)*s

```

### Test cases

```
let f =

s=>s.split(/(\d+)/).reduce((p,c,i,a)=>p+[0,k=a[i+1]/2,2*k,-k][n='NCFHIClBr'.search(c||0)+1,s|=n==2,n>2?3:n],1)*s

console.log(f("C6H6"))     // --> 4
console.log(f("C9H20"))    // --> 0
console.log(f("C9H9N1O4")) // --> 6
console.log(f("U1Pt1"))    // --> 0 (invalid)
console.log(f("Na2O1"))    // --> 0 (invalid)
console.log(f("C1H1"))     // --> 1.5
console.log(f("N1H3"))     // --> 0 (invalid)
```

## Alternate version, 103 bytes

If the input was guaranteed to be valid -- as the challenge introduction is misleadingly suggesting -- we could just do:

```
s=>s.split(/(\d+)/).reduce((p,c,i,a)=>p+[0,k=a[i+1]/2,2*k,-k][n='NCFHIClBr'.search(c||0)+1,n>2?3:n],1)

```

### Demo

```
let f =

s=>s.split(/(\d+)/).reduce((p,c,i,a)=>p+[0,k=a[i+1]/2,2*k,-k][n='NCFHIClBr'.search(c||0)+1,n>2?3:n],1)

console.log(f("C6H6"))     // --> 4
console.log(f("C9H20"))    // --> 0
console.log(f("C9H9N1O4")) // --> 6
console.log(f("C1H1"))     // --> 1.5
```

# Answer
> 0 votes
# Pip, ~~70~~ 67 bytes

```
`C\d`Na&1+/2*VaR+XDs._R['C'NC`H|F|I|Cl|Br`].s["+2*"'+'-]RXU.XX"+0*"

```

Takes the chemical formula as a command-line argument. Outputs `0` for invalid inputs. Try it online!

### Explanation

Uses a series of regex replacements to turn the chemical formula into a mathematical formula, evals it, and makes a couple tweaks to get the final value.

The replacements (slightly ungolfed version):

```
aR+XDs._R"C ""+2*"R"N "'+R`(H|F|I|Cl|Br) `'-RXU.XX"+0*"

a                    Cmdline arg
 R+XD                 Replace runs of 1 or more digits (\d+)
     s._               with a callback function that prepends a space
                       (putting a space between each element and the following number)
 R"C "                Replace carbon symbol
      "+2*"            with +2* (add 2* the number of carbon atoms to the tally)
 R"N "                Replace nitrogen symbol
      '+               with + (add the number of nitrogen atoms to the tally)
 R`(H|F|I|Cl|Br) `    Replace hydrogen or halogen symbol
                  '-   with - (subtract the number of atoms from the tally)
 RXU.XX               Replace uppercase letter followed by another char ([A-Z].)
       "+0*"           with +0* (cancel out numbers of all other kinds of atoms)

```

We eval the resulting string with `V`. This gives us `2C + N − X − H`. To get the correct value, we make the following adjustments:

```
`C\d`Na&1+/2*V...

             V...  Value of expression calculated above
          /2*      multiplied by 1/2
        1+         plus 1
`C\d`Na            Is carbon in the original formula? (i.e. C followed by a digit)
       &           Logical AND: if no carbon, return 0, otherwise return the formula value

```

# Answer
> 0 votes
# C (gcc), 195 ~~197~~ ~~202~~ bytes

Probably the longest answer.

```
d,c,b,e,n;f(char*a){for(c=d=0;b=*a;d+=e?e-1?b-66?b-67?0:e-2?0:-n:e-3?0:-n:b-67?b-78?b/70*73/b?-n:0:n:(c=2*n):0)e=*++a>57?*a-108?*a-114?0:3:2:1,a+=e>1,n=strtol(a,&a,10);printf("%.1f",c?d/2.+1:0);}

```

Try it online!

Returns 0 on error.

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