title: Happy Rounded Pi Day

text:
# Question
Title: Happy Rounded Pi Day
To celebrate Rounded Pi Day, you must take advantage of today's date to make a program that takes in a circle's diameter and outputs its circumference by multiplying the diameter by 3.1416, where 3.1416 must be obtained using today's date.

```
Input 3
Output 9.4248
etc.

```

Does not take the date as input. You do not have to use all components of the date but the digits of pi must come from formatting a Date object or using a date object to obtain it. The answers so far look good.

Not sure what else to specify. All the answers so far meet what I was expecting.

My constraint was that you must use components of the date to come up with Pi. You can of course use the components, multiply by 0 then add 3.1416, but that's boring and wastes precious chars!

Shortest code wins!

# Answer
# 05AB1E, ~~16~~ 13 bytes

```
žfžežg¦¦J*4°/

```

Try it online.

Unfortunately a bug with floats makes this a byte longer :/

Thanks to Adnan for golfing off 3 bytes.

## Explanation

```
žfžežg¦¦J*4°/
žfžežg         push month day year
      ¦¦       slice off the first two chars from the year (2016 -> 16)
        J      join them together into a number
         *     multiply by input
          4°/  divide by 1e4

```
> 8 votes

# Answer
# C, 32 bytes

```
#define f(d)d*time(0)/464083315.

```

If losing a little more accuracy is fine, I can get it down to about 29 bytes being still accurate to 4 digits past the decimal (as of the time of this posting):

```
#define f(d)d*time(0)/46408e4

```
> 19 votes

# Answer
# AppleScript, ~~122~~ 120 bytes

```
set a to current date
(display dialog""default answer"")'s text returned*(month of a+day of a*.01+year of a*1e-4 mod.01)

```

### Variable a

Variable a is a date object. I call all of my date information off of it.

### Month, day, and year

The month, day, and year calls actually return an object that normally returns a string. To properly use it as a number, I have surrounded it on both sides with mathematical operations to automatically cast it to a number.

### 1e-4

`1e-4` is a byte shorter than `.0001`.

### mod.01

`.` acts as a separator to the AppleScript autocorrect. By using this, I can use modulo and *still* keep it a byte for myself.

### No return statement/log

The last value calculated automatically is returned by the program. I output the number calculated via the return box.

And here's a gif of it running!
> 14 votes

# Answer
# Mathematica + coreutils, 20 bytes

```
<<"!date +%m.%d%y"#&

```

Luckily, Mathematica interprets the output of an external command as an expression. In this case the output is a valid float, so that multiplication with the function argument `#` is implied.
> 13 votes

# Answer
## Lua, ~~30~~ 27 Bytes

```
print(...*os.date"%m.%d%y")

```

Multiply the first command-line argument by the current date in format `mm.ddyy`, which is actually `03.1416`.
> 12 votes

# Answer
## Bash + bc, ~~25~~ 20 bytes

```
date +%m.%d%y\*$1|bc

```

Thanks to manatwork for saving five bytes.

Usage:

```
$ ./pi-round.sh 3
9.4248

```
> 9 votes

# Answer
## PowerShell v2+, ~~46~~ ~~28~~ 25 bytes

```
$args[0]*(Date -F "M.dy")

```

Pretty straightforward. Takes input `$args[0]` and multiplies it by the date formatted as `M.dy` (the `Get-` is implied). Note that this may take a long time to run on v2 as it iterates possible substitutions for `Date` (e.g., checking your `%PATH%` environment variable, etc.) before settling on `Get-Date`.
> 6 votes

# Answer
# R 3.2.4, ~~55~~ ~~51~~ 47 bytes

**edit** I realized I could use `scan` thanks @FryAmTheEggMan. Reduced 4 bytes thanks to @MickyT.

```
scan()*as.numeric(format(Sys.Date(),'%m.%d%y'))

```

First attempt at a golf. Happy pi day!
> 6 votes

# Answer
# Pyth, 19 bytes

```
*Qvs[.d4\..d5>2`.d3

```

Try it here!
Only works at 2016-03-14 of course.

## Explanation

```
*Qvs[.d4\..d5>2`.d3   # Q = input

     .d4              # current month
        \.            # dot between month and day
          .d5         # current day of the month
             >2`.d3   # last 2 digits of the year
   s[                 # concat everything into a string
  v                   # eval -> convert to float
*Q                    # multiply with input to get the circumference

```
> 5 votes

# Answer
# GNU Awk, 23 characters

```
$0*=strftime("%m.%d%y")

```

Sample run:

```
bash-4.3$ awk '$0*=strftime("%m.%d%y")' <<< 3
9.4248

```
> 5 votes

# Answer
# PHP, ~~45~~ ~~26~~ ~~25~~ 24 bytes

Uses Windows-1252 encoding

```
<?=$argv[1]*date(~‘Ñ•†);

```

Run like this:

```
echo '<?=$argv[1]*date(~‘Ñ•†);' | php -- 3

```
* Saved 19 bytes by using `date()` instead of `DateTime::format`
* Saved a byte by using the echo tag
* Saved a byte by using ISO-8859 encoding and negating the format string, so no need for double quotes. Might mess up your terminal a bit when running it from CLI, but works.
> 5 votes

# Answer
# JavaScript, ~~41~~ 39 characters

This uses a proprietary **Firefox-only** method.

```
d=>new Date().toLocaleFormat`%m.%d%y`*d

```

Thanks to:

* Ismael Miguel for the template string suggestion (-2 characters).

Sample run (Firefox Web Console):

```
> (d=>new Date().toLocaleFormat`%m.%d%y`*d)(3)
9.4248

```

Note: this will fail in Firebug Console. Seems that Firebug performs some expansion on the template string, transforming ``%m.%d%y`` into ``%__fb_scopedVars(m).d%y`` before passing it to the code.
> 4 votes

# Answer
# Python 2, 58 chars

```
import time
print float(time.strftime("%m.%d%y"))*input()

```

Try it!

Explanation:

```
import time                                   # Import time time module
print                                         # Print the following
      float(                                  # Cast to float
            time.strftime("%m.%d%y"))         # Format the time as MM.DDYY
                                     *input() # Multiply by input

```
> 4 votes

# Answer
## Ruby, 40 bytes

```
->n{n*Time.new.strftime('%m.%d%y').to_f}

```
> 3 votes

# Answer
## Mathematica, 54

```
.0001FromDigits[Now@{"Month","Day","YearShort"},100]#&

```
> 2 votes

# Answer
# SpecBAS, 39 bytes

```
1 INPUT n: ?n*VAL DATE$(TIME,"mm.ddyy")

```

Nothing out of the ordinary. Formats date as a string then multiplies the input by the `VAL` (value) of that string.
> 2 votes

# Answer
# Vitsy + coreutils, 19 bytes

```
'y%d%.m%+ etad',W*N

```

Explanation:

```
'y%d%.m%+ etad',W*N
'y%d%.m%+ etad'       Push 'date +%m.%d%y' to the stack.
               ,      Execute as shell.
                W     Grab input from STDIN and eval it.
                 *    Multiply the top two items
                  N   Output as a number.

```

Cannot be run in safe mode, as this uses the Runtime's exec method.
> 2 votes

# Answer
## Python 3, ~~74~~ 54 bytes

using the time module instead of datetime like Loovjo's Answer

```
import time
lambda n:n*float(time.strftime('%m.%d%y'))

```

**previous solution**

```
from datetime import*
lambda n:n*float(datetime.now().strftime('%m.%d%y'))

```
> 2 votes

# Answer
## Pyke, ~~16~~ 15 bytes, ASCII encoding

```
C867wä%J"bT4^/*

```

Explanation:

```
C867            - b,c,d = year, day, month
    wä          - a = base_96("ä") - 100
      %         - a = a%b
       J"       - a = "".join([a,c,d])
         b      - b = base(a, 10)
          T4^   - a = 10^4
             /  - a = a/b
              * - imp_print(a*eval_or_not(input))

```

or 11 bytes (non-competitive), (adds string singles, 2 digit year, string sumables)

```
C856\.R3sb*

```

Explanation:

```
C856        - a,b,c = 2d_year, day, month
    \.      - d = "."
      R3    - a,b,c = b,c,a
        s   - a = sum(a,b,c)
         b  - a = base(a, 10)
          * - imp_print(a*eval_or_not(input))

```
> 2 votes

# Answer
## Oracle 11g, ~~50~~ 49 bytes

```
SELECT &n*to_char(sysdate,'MM.DDYY')FROM dual;

```

one less byte, thanks to @MickyT
> 2 votes

# Answer
# APL, 19 bytes

```
⎕×0.01⊥⌽⍎2⌽8↑2↓⍕⎕TS

```

`⎕TS` is `2016 3 14 12 34 56 789` i.e. March 14rd, 2016 right before 12:35 pm
make into string, i.e. `'2016 3 14 12 34 56 789'`
`8↑2↓` drop first two (`'20'`) then take next eight (`'16 3 14 '`)
`2⌽` rotate two characters, giving `' 3 14 16'`
make into numbers (`3 14 16`)
reverse the list, giving `16 14 3`
`0.01⊥` evaluate in base ¹⁄₁₀₀, = 16 × 0.01² + 15 × 0.01¹ + 3 × 0.01⁰ = 0.0016 + 0.15 + 3 = 3.1416
`⎕×` multiply with input

or

```
⎕×1E¯4⊥⌽⍎2⌽7↑2↓⍕⎕TS

```

`⎕TS` is `2016 3 14 12 34 56 789`, i.e. March 14rd, 2016 right before 12:35 pm
make into string, i.e. `'2016 3 14 12 34 56 789'`
`7↑2↓` drop first two (`'20'`) then take next seven (`'16 3 14'`)
`2⌽` rotate two characters, giving `' 3 1416'`
make into numbers (`3 1416`)
reverse the list, giving `1416 3`
`1E¯4⊥` evaluate in base ¹⁄₁₀₀₀₀, = 1416 × 0.01¹ + 3 × 0.01⁰ = 0.1416 + 3 = 3.1416
`⎕×` multiply with input
> 2 votes

# Answer
## Google Sheets, 13 bytes

Bytes are calculated with one byte per character, zero bytes per cell except for the designated input cell, two bytes. The equals sign to start a formula is not counted. (I don't know if this is standard, please correct me if I am wrong.)

Run snippet to see the code.

```
table {
  empty-cells: show;
}
table,
th,
td {
  border: 1px solid black;
}
```

```
<table border="1">
  <tr>
    <th></th>
    <th>1</th>
    <th>2</th>
    <th>3</th>
  </tr>
  <tr>
    <td>A</td>
    <td><input></td>
    <td style="text-align:right">3.1416</td>
    <td style="font-family:'Ubuntu Mono',monospace">=<span style="color:rgb(257,142,29)">A1</span>*<span style="color:rgb(126,55,148)">A2</span>
    </td>
  </tr>
</table>
```

This works because you can define your own date formats in Google Sheets. I made it so that it is `<month>.<day><year>`.
> 2 votes

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

Saved 2 bytes thanks to dev-null!

```
x=>x*((a=new Date).getMonth()+1+"."+a.getDate()+(a.getYear()-100))

```

Anonymous function. Some uses:

```
f(1)    == 3.1416
f(5)    == 15.708
f(f(2)) == 19.73930112

```
> 1 votes

# Answer
# Tcl/Tk, 58 bytes

```
puts [expr {[gets stdin]*[clock f [clock se] -f %N.%d%g]}]

```

(That's a complete program. If you want to cheat and remove the explicit `puts` statement then it's only 51 bytes -- you'd have to start tclsh and type/paste the following in directly, though:)

```
expr {[gets stdin]*[clock f [clock se] -f %N.%d%g]}

```
> 1 votes

# Answer
# MATL, 17 bytes

```
Z'2$'mm.ddyy'XOU*

```

**Try it online!**

```
Z'              % get current date and time as float
2$'mm.ddyy'XO   % format as a string with custom format
U               % convert to number
*               % multiply by implicit input

```
> 1 votes

# Answer
# Java 114 bytes

```
public double p(double d){
  return (d*Double.parseDouble(new SimpleDateFormat("MM.ddyy").format(new Date())));
}

```
> 1 votes

# Answer
# Racket, 112 characters

```
(define d(seconds->date(current-seconds)))(*(read)(+(date-month d)(*(date-day d).01)(*(-(date-year d)2e3)1e-4)))

```

Reads the number from input in standard reader syntax.
> 1 votes

# Answer
# TI-84 Basic, 30 bytes

*Works on TI-83/84 calculators; E is the scientific notation token and ~ is the negative token.*

```
Prompt D:getDate:D(Ans(2)+E~4Ans(1)-.2+.01Ans(3

```

**Test Case**

```
D=?3
          9.4248

```
> 1 votes

# Answer
# R 48 bytes

```
d*as.double(format(Sys.Date(),format="%m.%d%y"))

```
> 1 votes

# Answer
# TI-BASIC, ~~16~~ ~~13~~ 9 bytes

```
Xround(π,1+min(getDate

```

We round `π` to a number of decimal places equal to the minimum of `{month,day,year}`, and then multiply it by the input.

This is a function that takes input through X. Store it to one of the Y-variables, for example `Y1`, and then call like `Y1([number])` on the homescreen.
> 1 votes

# Answer
# VBScript, 88 bytes

```
D=Date
MsgBox(WScript.Arguments(0)*(Month(D)+CDbl("."+CStr(Day(D))+CStr(Year(D)-2000))))

```

I can probably save some bytes by using an input box instead. Call it like `argument_name arg`.
> 0 votes

# Answer
# Mouse-2002, 45 bytes

```
&MONTH 10000*&DOM 100*+&YEAR 2000-+0.0001*?*!

```

Sample use:

```
> &MONTH 10000*&DOM 100*+&YEAR 2000-+0.0001*?*!
5
15.708

```

Explanation:

* We're going to take the current month, day and year and turn them to a decimal.
* First, we need to add `3 * 10000`, `14 * 100` and `2016 - 2000`, to get one number we can work with.
* Next, we'll need to multiply this integer (`31416`) by `0.0001` to get `3.1416`.
* Then, we'll ask for a number as input `?`, multiply by `3.1416` and print the result.
> 0 votes

# Answer
# Groovy, 41 characters

```
{it*(new Date().format('M.dyy')as float)}

```

Sample run:

```
groovy:000> ({it*(new Date().format('M.dyy')as float)})(3)
===> 9.424799680709839

```
> 0 votes

# Answer
# Julia, 40 bytes

```
d->(float)(strftime("%m.%d%y",time()))*d

```

Sample run:

```
julia> (d->(float)(strftime("%m.%d%y",time()))*d)(3)
9.4248

```
> 0 votes

# Answer
# jq, 36 bytes

```
(now|strftime("%m.%d%y")|tonumber)*.

```

Sample run:

```
bash-4.3$ jq '(now|strftime("%m.%d%y")|tonumber)*.' 3
9.4248

```

On-line test
> 0 votes

# Answer
# FORTH, 64 bytes

```
: p time&date 100 mod -rot 100 * + 100 * + 4 roll * 10000 / . ;

```

The result is rounded to the nearest integer. Usage: `10 p` prints 31
> 0 votes

# Answer
# Factor, ~~120~~ ~~151~~ ~~80~~ ~~84~~ 76 bytes

Holy cats, I love this language.

```
now "%m.%d" strftime now "%Y" strftime 2 tail append [ string>number ] bi@ *

```

Point-free, so expects the number on the stack:

```
(scratchpad) : roundpi ( n -- i ) now "%m.%d" strftime now "%Y" strftime 2 tail append [ string>number ] bi@ * ;
(scratchpad) 3 roundpi print
9.454800000000001

```

Translation of: Mouse.
> 0 votes

---
Tags: code-golf, arithmetic, date, pi
---


title: Roman-style date formatting

text:
# Question
Title: Roman-style date formatting
Today (March 15) is the Ides of March, best known for being the date that Julius Caesar was assassinated.

What's “Ides”? Well, the ancient Romans didn't simply number the days of month from 1 to 31 like we do. Instead, they had a more complex system of counting backwards to the Kalends, Nones, or Ides.

## Challenge

Write, in as few bytes as possible, a program that will display the current date (on the Gregorian calendar, in the local timezone) using the abbreviated Roman-style convention described below. Your program should work until at least the end of 2037.

## Roman dates

### Months of the year

These should look familiar to you: Ianuarius, Februarius, Martius, Aprilis, Maius, Iunius, Iulius (Quintilis), Augustus (Sextilis), September, October, November, December.

Your program is to abbreviate all months to three letters, using the classical Latin alphabet (all caps, with J=I and U=V). That is, `IAN`, `FEB`, `MAR`, `APR`, `MAI`, `IVN`, `IVL`, `AVG`, `SEP`, `OCT`, `NOV`, `DEC`.

### Special dates of the month

* **Kalendis**, or the **Kalends** (abbr. `KAL`) is the first day of each month.
* **Idibus**, or the **Ides** (abbr. `ID`) is the **15th** day of March, May, July, or October; but the **13th** day of the other eight months.
* **Nonas**, or the **Nones** (abbr. `NON`) is 8 days before the Ides (5th or 7th of the month)

### Other days of the month

Other days of the month are numbered by counting **backwards** and **inclusively** to the next reference date (Kalends, Ides, or Nones). Notation is `AD` (abbreviation for **ante diem**, no relation to Jesus of Nazareth) followed by the appropriate **Roman numeral**.

**Exception**: Write `PR` (for **pridie**) instead of `AD II` for the day before Kalends, Nones, or Ides.

### The leap day

In leap years, *two* days (February 24 and 25 in modern reckoning) are given the date `AD VI KAL MAR`. (You do not need to distinguish the two days in your program.) February 14-23 are `AD XVI KAL MAR` through `AD VII KAL MAR` as in non-leap years. Feb 26 = `AD V KAL MAR`, Feb 27 = `AD IV KAL MAR`, Feb 28 = `AD III KAL MAR`, and Feb 29 = `PR KAL MAR`, offset by one from the corresponding dates in non-leap years.

## Example

In March, the output of your program should be:

* On March 1: `KAL MAR`
* On March 2: `AD VI NON MAR`
* On March 3: `AD V NON MAR`
* On March 4: `AD IV NON MAR`
* On March 5: `AD III NON MAR`
* On March 6: `PR NON MAR`
* On March 7: `NON MAR`
* On March 8: `AD VIII ID MAR`
* ...
* On March 13: `AD III ID MAR`
* On March 14: `PR ID MAR`
* On March 15: `ID MAR`
* On March 16: `AD XVII KAL APR`
* ...
* On March 30: `AD III KAL APR`
* On March 31: `PR KAL APR`

# Answer
> 6 votes
# Tcl/Tk, 675 bytes

Well, I suppose I could crunch it more, but this is it for now...

```
set a {y m d}
rename proc p
p r {n {s ""}} {foreach {v d} {10 X 5 V 1 I} {while {$n>=$v} {set s $s$d;incr n -$v}};string map {VIIII IX IIII IV} $s}
p y y {expr !($y%100?$y%4:$y%400)}
p i $a {expr {($m in {3 5 7 10})?15:13}}
p n $a {expr [i $y $m $d]-8}
p k $a {expr $m==2?29+($d>24&&[y $y]):$m<8?31+$m%2:32-$m%2}
p N {} {clock f [clock se] -f {%Y %N %e}}
p M m {lindex {IAN FEB MAR APR MAI IVN IVL AVG SEP OCT NOV DEC IAN} $m-1}
p d $a {foreach f {n i k} n {NON ID KAL} mo {0 0 1} {if {$d<=[$f $y $m $d]} break}
string map {{AD I } {} {AD II } {PR }} "AD [r [expr [$f $y $m $d]+1-$d]] $n [M [expr $m+$mo]]"}
p p $a {if {$d==1} {puts "KAL [M $m]"} {puts [d $y $m $d]}}
p {*}[N]

```

**How it works**

The first thing is to collect today's date as a list: year, month, day. Everything works over that. The first of the month is a simple special case; we handle that separately.

All remaining cases work like this:

1. Find the future reference day's date in (5,7,13,15,days-in-month)
2. Get the abbreviation corresponding to that reference (`NON`, `ID`, `KAL`)
3. For Kalends we increment the month by one
4. Assemble the date string as:
"AD \<days-in-roman-numerals\> \<abbreviated-reference-day\> \<abbreviated-month-name\>"
5. Apply a text replace to correct `AD I` and `AD II`.

The first step is done with a function lookup table for each of the Nones, Ides, and Kalends. Nones and Ides are straight-forward subtraction and lookup, respectively. Computing the **Kalends** is only a little more complicated (notice the trick with leap-February's day number.):

* February → 28 days + (it's a leap year AND day \> 24)
* January..July → 30 days + (it's January, March, May or July)
* August..December → 31 days - (it's September or November)

The days is a simple difference: (reference\_day - todays\_day + 1)

Computing the **leap year** is done with a somewhat unusual arrangement of the standard formula so that it could be crunched better (removing braces and parentheses from the `expr` command).

Converting decimal to **Roman numerals** is a simple table-driven approach, stripped to use only ones, fives, and tens since we don't need to print the year in Roman numerals (domain is \[1,39\]).

Almost everything else is application of lookup tables.

**A note on Tcl and reducing bytes**

The first two lines of the script eat bytes by simply being shorter than spelling out `proc f {y m d}` for all instances.

Single-letter proc names and variables, of course:

```
    r := decimal→roman(n)    i := ides(y,m,d)        M := month-abbreviation(month)
    y := is-leap(year)       n := nones(y,m,d)       d := date→roman(y,m,d) [d ≠ 1]
    N := today → (y,m,d)     k := kalends(y,m,d)     p := date→roman(y,m,d) [∀d]

```

**Testing for dates other than today**

Change the very last line from `p {*}[N]` to

```
p {*}$argv

```

and run the program with the date desired:

```
% tclsh roman.tcl 2016 2 25
AD VI KAL MAR

```

Enjoy!

# Answer
> 2 votes
(I will not give myself the checkmark, even though I have the shortest submission so far.)

# Python 3: 390 bytes

```
import time
y,m,d=time.localtime()[:3]
d-=(y%4==0)*(m==2)*(d>24)
i=13+2*(m in (3,5,7,10))
n=i-8
k=29+(0,3,0,3,2,3,2,3,3,2,3,2,3)[m]
a,R={1:(0,'KAL'),d>1:(n-d,'NON'),d>n:(i-d,'ID'),d>i:(k-d,'KAL')}[1]
a+=1
A={1:'',2:'PR '}.get(a,'AD '+a//10*'X'+('','I','II','III','IV','V','VI','VII','VIII','IX')[a%10]+' ')
if d>i:m=m%12+1
M='IFMAMIIASONDAEAPAVVVECOENBRRINLGPTVC'[m-1::12]
print(A+R+' '+M)

```

# Explanation

```
y,m,d=time.localtime()[:3]

```

Gets the current date: `y`=year, `m`=month, and `d`=day.

To test the program with dates other than the current date, simply replace this line with something else.

```
d-=(y%4==0)*(m==2)*(d>24)

```

If this is February 25-29 of a leap year, subtract 1 from the date. From this point on, we can treat February as if it's a non-leap year.

Note that, because the challenge rules don't require correct behavior in the year 2100, I used the simple 4-year Julian leap-year rule instead of the Gregorian 400-year cycle.

```
i=13+2*(m in (3,5,7,10))

```

Ides of the current month.

```
n=i-8

```

Nones of the current month.

```
k=29+(0,3,0,3,2,3,2,3,3,2,3,2,3)[m]

```

One more than the number of days in the current month, equivalent to the Kalends of the *next* month.

```
a,R={1:(0,'KAL'),d>1:(n-d,'NON'),d>n:(i-d,'ID'),d>i:(k-d,'KAL')}[1]

```

`a` is the number of days until the next reference date and `R` is its abbreviation. This expression takes advantage of the fact that if the same key is specified multiple times in the same `dict` literal, only the last one counts.

```
a+=1

```

Adjustment for inclusive counting.

```
A={1:'',2:'PR '}.get(a,'AD '+a//10*'X'+('','I','II','III','IV','V','VI','VII','VIII','IX')[a%10]+' ')

```

Stringify the count `a` to the next reference date.

* If 1, use no prefix
* If 2, use the prefix `PR`
* If 3 or higher, use the prefix `AD` \+ Roman numeral + space

There's probably a shorter way to do the Roman numerals, but I'm too lazy to find it.

```
if d>i:m=m%12+1

```

If after the Ides, increment the month for display.

```
M='IFMAMIIASONDAEAPAVVVECOENBRRINLGPTVC'[m-1::12]

```

Get the month name.

```
print(A+R+' '+M)

```

Finally, print the date.

---
Tags: code-golf, date, roman-numerals
---


title: Calculate the volume of an object

text:
# Question
Title: Calculate the volume of an object
You can determine the volume of objects based on a given set of dimensions:

* The volume of a sphere can be determined using a single number, the radius (`r`)
* The volume of a cylinder can be determined using two numbers, the radius (`r`) and the height (`h`)
* The volume of a box can be determined using three numbers, the length (`l`), width (`w`) and the height (`h`)
* The volume of an irregular triangular pyramid can be determined using four numbers, the side lengths (`a, b, c`) and the height (`h`).

The challenge is to determine the volume of an object given one of the following inputs:

* A single number `(r)` or `(r, 0, 0, 0)` =\> `V = 4/3*pi*r^3`
* Two numbers `(r, h)` or `(r, h, 0, 0)` =\> `V = pi*r^2*h`
* Three numbers `(l, w, h)` or `(l, w, h, 0)` =\> `V = l*w*h`
* Four numbers `(a, b, c, h)` =\> `V = (1/3)*A*h`, where `A` is given by Heron's formula: `A = 1/4*sqrt((a+b+c)*(-a+b+c)*(a-b+c)*(a+b-c))`

**Rules and clarifications:**

* The input can be both integers and/or decimals
* You can assume all input dimensions will be positive
* If Pi is hard coded it must be accurate up to: `3.14159`.
* The output must have at least 6 significant digits, except for numbers that can be accurately represented with fewer digits. You can output `3/4` as `0.75`, but `4/3` must be `1.33333` (more digits are OK)
    + How to round inaccurate values is optional
* Behaviour for invalid input is undefined
* Standard rules for I/O. The input can be list or separate arguments

This is code golf, so the shortest solution in bytes win.

**Test cases:**

```
calc_vol(4)
ans =  268.082573106329

calc_vol(5.5, 2.23)
ans =  211.923986429533

calc_vol(3.5, 4, 5)
ans =  70

calc_vol(4, 13, 15, 3)
ans =  24

```

---

Related, but different.

# Answer
> 4 votes
# MATL, ~~57~~ ~~53~~ ~~51~~ 44 bytes

```
3^4*3/YP*GpG1)*YP*GpG0H#)ts2/tb-p*X^3/*XhGn)

```

Input is an array with 1, 2, 3 or 4 numbers.

**Try it online!**

### Explanation

Instead of using nested `if` loops, which is expensive in terms of bytes, this computes four possible results for any input, and then picks the appropriate result depending on input length.

When computing the results, even though only one of them needs to be valid, the others cannot give errors. This means for example that indexing the fourth element of the input is not allowed, because the input may have less than four elements.

```
                    % take input implicitly
3^4*3/YP*           % compute a result which is valid for length-1 input:
                    % each entry is raised to 3 and multiplied by 4/3*pi
G                   % push input
pG1)*YP*            % compute a result which is valid for length-2 input:
                    % product of all entries, times first entry, times pi
G                   % push input
p                   % compute a result which is valid for length-3 input:
                    % product of all entries
G                   % push input
0H#)ts2/tb-p*X^3/*  % compute a result which is valid for length-4 input:
                    % shorter version of Heron's formula applied on all
                    % entries except the last, times last entry, divided by 3
Xh                  % collect all results in a cell array
G                   % push input
n)                  % pick appropriate result depending on input length
                    % display implicitly

```

# Answer
> 8 votes
# Vitsy, 49 bytes

I thought you handed this one to me on a plate, but I found an unresolved bug to work around. Didn't hurt me, though.

```
lmN
3^43/*P*
2^*P*
**
v:++2/uV3\[V}-]V3\*12/^v*3/

```

Basically, with the input being a certain length for different functions, you spoon feed me my method syntax for doing this stuff. So, yay, success!

Explanation, one line at a time:

```
lmN
l   Get the length of the stack.
 m  Go to the line index specified by the top item of the stack (the length).
  N Output as a number.

3^43/*P*
3^
          Put to the power of 3.
  43/*    Multiply by 4/3.
      P*  Multiply by π

2^*P*
2^     Put to the second power.
  *    Multiply the top two items.
   P*  Multiply by π

**
**     Multiply the top three items of the stack.

v:++2/uV3\[V}-]V3\*12/^v*3/
v                            Save the top item as a temp variable.
 :                           Duplicate the stack.
  ++                         Sum the top three values.
    2/                       Divide by two.
      u                      Flatten the top stack to the second to top.
       V                     Capture the top item of the stack (semiperimeter)
                             as a permanent variable.
        3\[   ]              Do the stuff in the brackets 3 times.
           V}-               Subtract the semiperimeter by each item.
               V             Push the global var again.
                3\*          Multiply the top 4 items.
                   12/^      Square root.
                       v*    Multiply by the temp var (the depth)
                         3/  Divide by three.

```

Input is accepted as command line arguments in the exact reverse as they appear in the question, with no trailing zeroes.

Try it online!

As an aside, here's something that's currently in development.

### Java w/ Vitsy Package

Note that this package is work in progress; this is just to show how this will work in the future (documentation for this is not yet uploaded) and it is *not* golfed, and is a literal translation:

```
import com.VTC.vitsy;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;

public class Volume {
    public static void main(String[] args) {
        Vitsy vitsyObj = new Vitsy(false, true);
        vitsyObj.addMethod(new Vitsy.Method() {
            public void execute() {
                vitsyObj.pushStackLength();
                vitsyObj.callMethod();
                vitsyObj.outputTopAsNum();
            }
        });
        vitsyObj.addMethod(new Vitsy.Method() {
            public void execute() {
                vitsyObj.push(new BigDecimal(3));
                vitsyObj.powerTopTwo();
                vitsyObj.push(new BigDecimal(4));
                vitsyObj.push(new BigDecimal(3));
                vitsyObj.divideTopTwo();
                vitsyObj.multiplyTopTwo();
                vitsyObj.pushpi();
                vitsyObj.multiplyTopTwo();
            }
        });
        vitsyObj.addMethod(new Vitsy.Method() {
            public void execute() {
                vitsyObj.push(new BigDecimal(2));
                vitsyObj.powerTopTwo();
                vitsyObj.multiplyTopTwo();
                vitsyObj.pushpi();
                vitsyObj.multiplyTopTwo();
            }
        });
        vitsyObj.addMethod(new Vitsy.Method() {
            public void execute() {
                vitsyObj.multiplyTopTwo();
                vitsyObj.multiplyTopTwo();
            }
        });
        vitsyObj.addMethod(new Vitsy.Method() {
            public void execute() {
                vitsyObj.tempVar();
                vitsyObj.cloneStack();
                vitsyObj.addTopTwo();
                vitsyObj.addTopTwo();
                vitsyObj.push(new BigDecimal(2));
                vitsyObj.divideTopTwo();
                vitsyObj.flatten();
                vitsyObj.globalVar();
                vitsyObj.push(new BigDecimal(3));
                vitsyObj.repeat(new Vitsy.Block() {
                    public void execute() {
                        vitsyObj.globalVar();
                        vitsyObj.rotateRight();
                        vitsyObj.subtract();
                    }
                });
                vitsyObj.globalVar();
                vitsyObj.push(new BigDecimal(3));
                vitsyObj.repeat(new Vitsy.Block() {
                    public void execute() {
                        vitsyObj.multiplyTopTwo();
                    }
                });
                vitsyObj.push(new BigDecimal(1));
                vitsyObj.push(new BigDecimal(2));
                vitsyObj.divideTopTwo();
                vitsyObj.powerTopTwo();
                vitsyObj.tempVar();
                vitsyObj.multiplyTopTwo();
                vitsyObj.push(new BigDecimal(3));
                vitsyObj.divideTopTwo();
            }
        });
        vitsyObj.run(new ArrayList(Arrays.asList(args)));
    }
}

```

# Answer
> 5 votes
# C, ~~100~~ 97 bytes

```
#define z(a,b,c,d) d?d*sqrt(4*a*a*b*b-pow(a*a+b*b-c*c,2))/12:c?a*b*c:3.14159*(b?a*a*b:4/3.*a*a*a)

```

edit 1: remove unnecessary decimal `.`, thanks Immibis!

# Answer
> 4 votes
# JavaScript ES6, <sub>~~129~~ ~~126~~ ~~125~~ ~~116~~ ~~114~~</sub> 90 bytes

Saved lots of bytes (9) with a wonderful formula, thanks to Stewie Griffin! Since input must be nonzero, `variable?` will suffice for a defining-check.

```
with(Math){(a,b,c,h,Z=a*a)=>h?sqrt(4*Z*b*b-(D=Z+b*b-c*c)*D)/4:c?a*b*c:b?PI*Z*b:4/3*PI*Z*a}

```

## Test it out!

```
with(Math){Q = (a,b,c,h,Z=a*a)=>h?sqrt(4*Z*b*b-(D=Z+b*b-c*c)*D)/4:c?a*b*c:b?PI*Z*b:4/3*PI*Z*a}
console.log = x => o.innerHTML += x + "<br>";

testCases = [[4], [5.5, 2.23], [3.5, 4, 5], [4, 13, 15, 3]];
redo = _ => (o.innerHTML = "", testCases.forEach(A => console.log(`<tr><td>[${A.join(", ")}]` + "</td><td> => </td><td>" + Q.apply(window, A) + "</td></tr>")));
redo();
b.onclick = _ => {testCases.push(i.value.split(",").map(Number)); redo();}
```

```
*{font-family:Consolas,monospace;}td{padding:0 10px;}
```

```
<input id=i><button id=b>Add testcase</button><hr><table id=o></table>
```

# Answer
> 3 votes
## PowerShell, ~~165~~ 161 bytes

```
param($a,$b,$c,$h)((($h/12)*[math]::Sqrt(($a+$b+$c)*(-$a+$b+$c)*($a-$b+$c)*($a+$b-$c))),(($a*$b*$c),((($p=[math]::PI)*$b*$a*$a),($p*$a*$a*$a*4/3))[!$b])[!$c])[!$h]

```

So ... Many ... Dollars ... (31 of the 161 characters are `$`, for 19.25% of the code) ... but, saved 4 bytes thanks to Stewie Griffin!

We take in four inputs, and then progressively index into pseudo-ternary statements based on them in reverse order. E.g., the outside `(..., ...)[!$h]` tests whether the fourth input is present. If so, the `!$h` will equal `0` and the first half is executed (the volume of an irregular triagonal pyramid). Otherwise, `!$h` with `$h = $null` (as it's uninitialized) will equal `1`, so it goes to the second half, which itself is a pseudo-ternary based on `[!$c]` and so on.

This is likely close to optimal, since the supposedly-shorter formula that (e.g.) Cᴏɴᴏʀ O'Bʀɪᴇɴ is using is actually 2 bytes longer in PowerShell thanks to the lack of a `^` operator ... The only real savings comes from `(1/3)*(1/4)*A*$h` golfing to `A*$h/12`, and setting `$p` later to save a couple bytes instead of the lengthy `[math]::PI` call.

# Answer
> 3 votes
**Haskell, ~~114~~ ~~109~~ ~~107~~ ~~101~~ 99 bytes**

```
v[r]=4/3*pi*r^3
v[r,h]=pi*r^2*h
v[x,y,z]=x*y*z
v[a,b,c,h]=h/12*sqrt(4*a^2*b^2-(a^2+b^2-c^2)^2)

```

Takes a list of numbers and returns a volume. Call it like

```
v[7]

```

for a sphere, etc. The function is polymorphic for any type that implements `sqrt` (so, basically `Float` or `Double`).

It's not going to win any contests for brevity. But note how *readable* it is. Even if you don't really know Haskell, you can tell what it does quite easily. Haskell's pattern matching syntax makes it really easy to define strange functions that do something totally different depending on the shape of the input.

# Answer
> 1 votes
## CJam, ~~67~~ 66 bytes

```
q~0-_,([{~3#4*P*3/}{~\_**P*}{:*}{)\a4*(a\[1W1]e!..*+::+:*mq*C/}]=~

```

I will work on shortening it soon. Try it online!

Explanation to come.

# Answer
> 1 votes
## Seriously, ~~65~~ ~~59~~ 55 bytes

```
`kd@;Σ½╗"╜-"£Mπ╜*√*3@/``kπ``ª*╦*``3;(^/4*╦*`k,;lD(E@i(ƒ

```

Try it online!

### Explanation

This one is a doozy. I'm going to break the explanation into multiple parts.

Main body:

```
`...``...``...``...`k,;lD(E@i(ƒ
`...``...``...``...`k            push 4 functions to a list
                     ,;lD        push input, len(input)-1
                         (E      get the function at index len(input)-1
                           @i(   flatten the input list
                              ƒ  execute the function

```

Function 0:

```
3;(^/4*╦*
3;(^       push 3, r^3
    /      divide (r^3/3)
     4*    multiply by 4 (4/3*r^3)
       ╦*  multiply by pi (4/3*pi*r^3)

```

Function 1:

```
ª*╦*
ª     r^2
 *    multiply by h (r^2*h)
  ╦*  multiply by pi (pi*r^2*h)

```

Function 2:

```
kπ  listify, product (l*w*h)

```

Function 3 (21 bytes; nearly half the program length!)

```
kd@;Σ½╗"╜-"£Mπ╜*√*3@/
kd@                    listify, dequeue h, bring [a,b,c] back on top
   ;Σ½                       dupe, sum, half (semiperimeter)
      ╗                push to register 0
       "╜-"£M          map: push s, subtract (s-x for x in (a,b,c))
             π         product
              ╜*√      multiply by s, sqrt (Heron's formula for area of the base)
                 *3@/  multiply by h, divide by 3 (1/3*A*h)

```

# Answer
> 1 votes
# Matlab, 78 bytes

```
@(a,b,c,d)pi*a^2*(4/3*a*~b+b*~c)+a*b*c*~d+d/12*(4*a^2*b^2-(a^2+b^2-c^2)^2)^.5;

```

Quite sure it can't get any shorter than this. `~b`, `~c` and `~d`, are `0` if each of the dimensions are non-zero. A formula with a zero dimension will just give zero. That way, each of the formulas can simply be summed. No `if` and `else` required.

Call it like this (or try it online here):

```
g=@(a,b,c,d)pi*a^2*(4/3*a*~b+b*~c)+a*b*c*~d+d/12*(4*a^2*b^2-(a^2+b^2-c^2)^2)^.5;

g(4,0,0,0)
ans =  268.082573106329

g(5.5,2.23,0,0)
ans =  211.923986429533

g(3.5,4,5,0)
ans =  70

g(4,13,15,3)
ans =  24

```

# Answer
> 0 votes
# Python ~~3~~ 2, ~~127~~ ~~119~~ 116 bytes

Credit to somebody and Mego for all their help with golfing. Credit also to Cᴏɴᴏʀ O'Bʀɪᴇɴ and Josh as I borrowed parts of their answers for this one.

```
def v(a,b,c,d):z=a*a;P=3.14159;print filter(int,[max(0,(4*z*b*b-(z+b*b-c*c)**2))**.5*d/12,a*b*c,P*z*b,P*z*a*4/3])[0]

```

**Ungolfed:**

```
def v(a, b, c, d):
    z = a*a
    p = 3.14159
    s = filter(int,[max(0,(4*z*b*b-(z+b*b-c*c)**2))**.5*d/12,a*b*c,P*z*b,P*z*a*4/3])
    print s[0]

```

# Answer
> 0 votes
## Mathematica, 114 (103)

**Pure function: 114**

```
Which[(l=Length@{##})<2,4.Pi/3#1^3,l<3,#1^2.Pi#2,l<4,#1#2#3,l<5,(4#1^2#2^2-(#1^2+#2^2-#3^2)^2)^.5#4/12]~Quiet~All&

```

Ungolfed:

```
fun = Which[
  (l = Length@{##}) < 2,
    4. Pi/3 #1^3,
  l < 3,
    #1^2 Pi #2,
  l < 4,
    #1 #2 #3,
  l < 5,
    (4 #1^2 #2^2 - (#1^2 + #2^2 - #3^2)^2)^.5 #4/12
]~Quiet~All &

```

Usage:

```
fun[4]
268.083
fun[5.5, 2.23]
211.924
fun[3.5, 4, 5]
70.
fun[4, 13, 15, 3]
24.

```

**If named functions are allowed: 103**

```
f[r_]:=4.Pi/3r^3
f[r_,h_]:=r^2.Pi h
f[l_,w_,h_]:=l w h
f[a_,b_,c_,h_]:=(4a^2b^2-(a^2+b^2-c^2)^2)^.5h/12

```

Usage:

```
f[4]
268.083
f[5.5, 2.23]
211.924
f[3.5, 4, 5]
70.
f[4, 13, 15, 3]
24.

```

# Answer
> 0 votes
# Factor, 783 bytes

Well, this took forever.

```
USING: arrays combinators io kernel locals math math.constants math.functions quotations.private sequences sequences.generalizations prettyprint ;
: 1explode ( a -- x y ) dup first swap 1 tail ;
: 3explode ( a -- b c d ) 1explode 1explode 1explode drop ;
: spr ( r -- i ) first 3 ^ 4 3 / pi * swap * ;
: cyl ( r -- i ) 1explode 1explode drop 2 ^ pi swap * * ; : cub ( v -- i ) 1 [ * ] reduce ;
: A ( x a -- b d ) reverse dup dup dup 0 [ + ] reduce -rot 3explode neg + + -rot 3explode - + 3array swap 3explode + - 1array append 1 [ * ] reduce sqrt .25 swap * ;
: ilt ( a -- b c  ) V{ } clone-like dup pop swap A 1 3 / swap pick * * ;
: volume ( v -- e ) dup length { { [ 1 = ] [ spr ] } { [ 2 = ] [ cyl ] } { [ 3 = ] [ cub ] } { [ 4 = ] [ ilt ] } [ "bad length" throw ] } cond print ;

```

Call `{ array of numbers } volume` .

---
Tags: code-golf, math, arithmetic, geometry
---


title: Naïve Markov Chain Word Generation

text:
# Question
Title: Naïve Markov Chain Word Generation
There are many ways to generate random words. You can take random syllables from a set, you can use n-tuples, *probably* neural networks (what can't they do?), alternating between consonants and vowels, etc. The method this challenge is based off of is by far the worst. It uses a Markov chain to generate random words. If you are familiar Markov chains, you probably know why this method is so terrible.

If you want to read about Markov chains, click here.

Your program will take an input one or more words and generate a single random word, through the method of a weighted Markov chain. Since that probably makes sense to no one but me, here is an explanation through the use of a picture of the Markov chain with the input of `abba`:

(All edge weights are the same for all pictures) Your program will output the path through a Markov chain based on the input text. As you can see, there is a 1/2 chance it will output `a`, 1/8 chance of `aba`, 1/16 chance of `abba`, 1/32 chance of `ababa`, etc.

Here are some other example Markov chains:

`yabba dabba doo`

`wolfram`

`supercalifragilisticexpialidocious`

If you want more examples, use this. (I worked way too hard on it)

Details of challenge:

* Input can be taken as a list of strings, or as a space, comma, or newline separated string
* You may assume that all the words will be entirely lowercase with no punctuation (ASCII 97-122)
* You may write either a program or a function
* To test, you could probably input the examples and see if all inputs line up with the Markov chains

This is , so your program is scored in bytes.

Let me know if any part of this is unclear, and I will try to make it make more sense.

# Answer
> 5 votes
# Pyth, ~~38~~ 32 bytes

```
VQJK1FZacN1k XKH]Z=KZ;WJ=JO@HJpJ

```

Thanks to FryAmTheEggman for 5 bytes! To be honest I started writing Python answer when I noticed somebody posted a very similiar one so I decided to challenge myself with something new so I rewrote my answer (which was basically Pietu's answer) in Pyth.

Input is an array of strings `["Mary" , "had" , "a" , "little"]`

# Answer
> 4 votes
# Python 2, ~~138~~ 133 bytes

```
from random import*
M={}
for w in input():
 P=p=1
 for k in list(w)+[""]:M[p]=M.get(p,[])+[k];p=k
while P:P=choice(M[P]);k+=P
print k

```

Takes in an array of string such as `["yabba", "dabba", "doo"]`.

Example outputs with that input:

```
do
ya
dabbbbbbbaba
do
ya
yaba
da
dabba
yabbababbababbbbababa
do

```

I also want to highlight this result.

```
stidoupilioustialilisusupexpexpexpicexperagilidoupexpexpilicalidousupexpiocagililidocercagidoustilililisupialis

```

# Answer
> 2 votes
# Ruby, 112 107 101 99

Input is stdin, newline-seperated strings.

QPaysTaxes helped a lot with golfing it down!

```
M={}
while gets
k=''
$_.each_char{|c|M[k]||=[];M[k]<<c;k=c}
end
k=''
print k=M[k].sample while M[k]

```

# Answer
> 1 votes
# Matlab, 160 bytes

Takes input as a cell array of strings, like `{'string1','string2','string3'}`.

```
s=input('');n=[];l=96;for i=1:numel(s);n=[n 96 double(s{i}) 123];end
while(l(end)<123);p=n(find(n==l(end))+1);l=[l p(randsample(nnz(p),1))];end
char(l(2:end-1))

```

This reads the words, and converts them to a vector of ASCII values, with a 96 to mark the start of a word, and a 123 to represent the end of a word. To construct a random word, start with a 96. The search for all the integers that follow 96 in the vector, and take a random sample from those to pick the next letter. Repeat this, looking for all the integers that follow the current one, until 123 is reached, which signals the end of the word. Convert it back to letters, and display.

The input `{'yabba','dabba','doo'}` produces results like `da`. Here are the results of ten runs: `yabababbbababa`,`da`,`doo`,`doooooo`,`ya`,`da`,`doooo`,`ya`,`do`,`yaba`.

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


title: Replace alias to form phrases

text:
# Question
Title: Replace alias to form phrases
Inspired by the *C*-directive `#define`.

### Challenge

Given one phrase with some alias, and one array with each alias text. Output the initial phrase replacing each alias with its respective text.

An alias is defined by one sharp `#` followed by its index in the array (the index may start at zero or one). Alias can contains another alias inside its text, and you must resolve all them (maybe recursively). You can assume the alias will never run into an infinite-loop. Alias won't have leading zeroes (`#02` is not alias at index `2`, it is alias at index `0` followed by the text `2`).

You can assume the array will not pass 20 items in length.

You can write a program, or a function or even a `#define`*-it would be nice :)*

You can also use another input-method that fits better for your language.

### Example

```
phrase: "#0 & #3"
array: [
    "Programming #1",
    "Puzzles",
    "Code",
    "#2 Golf"
]
output: "Programming Puzzles & Code Golf"

```

Step by step:

```
0> "#0 & #3"
1> "Programming #1 & #2 Golf"
2> "Programming Puzzles & Code Golf"

```

Since this is , shortest answer in bytes wins!

### Another samples

```
phrase: "#0!"
array: [
    "We are #1",
    "#2",
    "#3",
    "#4 !",
    "graduating"
]
output: "We are graduating !!"

```

---

```
phrase: "##0#1#0#21#3#4"
array: [
    "a",
    "m",
    "z",
    "n",
    "g"
]
output: "#amaz1ng"

```

---

```
phrase: "##1#23"
array: [
    "WEIRD",
    "0 C",
    "AS"
]
output: "WEIRD CAS3"

```

---

```
phrase: "#1#7#6y#4#7#10s#7b#11#0#0#11r#7#0h#6#5#2#5#9#4."
array: [
    "t",
    "#12#3",
    "#11ga#3",
    "#0#10v#11",
    "#0h#10#8g",
    "#7#8",
    "a#8",
    " ",
    "n",
    "o",
    "i",
    "e",
    "P#9s#10"
]
output: "Positive anything is better than negative nothing."

```

The examples above used Array with index starting at zero.

# Answer
> 4 votes
# JavaScript (ES6) 58

Recursive function

```
f=(s,h,r=s.replace(/#(1?\d)/g,(_,x)=>h[x]))=>r==s?r:f(r,h)

```

*Test*

```
f=(s,h,r=s.replace(/#(1?\d)/g,(_,x)=>h[x]))=>r==s?r:f(r,h)

// Version without default parameters, same length but using a global
// f=(s,h)=>(r=s.replace(/#(1?\d)/g,(_,x)=>h[x]))==s?r:f(r,h)

console.log=x=>O.textContent+=x+'\n'

;[
  ['##1#23',['WEIRD','0 C','AS']],
  ["#0!",["We are #1","#2","#3","#4 !","graduating"]],
  ["##0#1#0#21#3#4",["a","m","z","n","g"]],
  ["##0#1#0#21#13#4",["a","m","z","","g","","","","","","","","","n"]],
  ["#1#7#6y#4#7#10s#7b#11#0#0#11r#7#0h#6#5#2#5#9#4.",
    ["t","#12#3","#11ga#3","#0#10v#11","#0h#10#8g","#7#8","a#8"," ","n","o","i","e","P#9s#10"]
  ],
  ["#0 & #3",["Programming #1","Puzzles","Code","#2 Golf"]]
].forEach(t=>{
  var a=t[0],b=t[1]
  console.log(a+' ['+b+']\n -> '+f(a,b))
})
```

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

# Answer
> 2 votes
# Julia, ~~112~~ ~~107~~ 66 bytes

```
f(s,x)=(r=replace(s,r"#1?\d",m->x[1+parse(m[2:end])]))==s?s:f(r,x)

```

This is a recursive function that accepts a string an an array and returns a string. It uses 0-based indexing.

We begin by constructing a string *r* as the input string *s* with all matches of the regular expression `#1?\d` replaced with the element of *x* corresponding to 1 + the integer parsed out of the match. If this is equal to *s*, we return *s*, otherwise we recurse, passing *r* as the string.

# Answer
> 2 votes
# Mathematica, 74 bytes

```
FixedPoint[#~StringReplace~a&,a=0;a=Reverse["#"<>ToString@a++->#&/@#2];#]&

```

Not too complicated. Most of it is just dedicated to creating the indices.

# Answer
> 1 votes
# C, ~~269~~ 232

```
#define f(p,a,l)char*n,o[999],i=0,c,x;for(strcpy(o,p);o[i];)o[i]==35&isdigit(o[i+1])?c=o[i+1]-48,c=isdigit(o[i+2])&c?10*c+o[i+2]-48:c,n=a[c<l?c:c/10],x=strlen(n),memmove(o+i+x,o+i+2+c/10,strlen(o+i)),i=!memmove(o+i,n,x):++i;puts(o);

```

As requested, a single `#define` solving the problem! C macros can't be recursive, so the problem had to be solved iteratively. The macro takes 3 arguments; the phrase `p`, the array `a`, and the length of the array `l`. ~~I only stripped whitespace from my ungolfed solution; I know there are a few more characters I can save, but I don't think it will get me below 200. This will definitely not be a competitive solution.~~ Solution is fully golfed. Ungolfed solution in the form of a function below:

```
f(char*p,char**a,int l){
  char o[999]={0},i=0;
  strcpy(o,p);
  while(o[i]){
    if(o[i]=='#'&&isdigit(o[i+1])){
      int c = o[i+1]-'0';
      if(isdigit(o[i+2])&&c)
        c=10*c+o[i+2]-'0';
      if(c>=l)
        c/=10;
      char *n=a[c];
      memmove(o+i+strlen(n),o+i+2+c/10,strlen(o+i));
      memmove(o+i,n,strlen(n));
      i=0;
    }else{
      i++;
    }
  }
  puts(o);
}

```

And test code:

```
void test(char *phrase, char **array, int length) {
  f(phrase, array, length);
}

main() {
  const char *t1[] = {
    "Programming #1","Puzzles","Code","#2 Golf"
  };
  test("#0 & #3", t1, 4);

  const char *t2[] = {
    "We are #1","#2","#3","#4 !","graduating"
  };
  test("#0!", t2, 5);

  const char *t3[] = {
    "a","m","z", "n","g"
  };
  test("##0#1#0#21#3#4", t3, 5);

  const char *t4[] = {
    "WEIRD","0 C","AS"
  };
  test("##1#23", t4, 3);

  const char *t5[] = {
    "t","#12#3","#11ga#3","#0#10v#11","#0h#10#8g","#7#8","a#8"," ","n","o","i","e","P#9s#10"
  };
  test("#1#7#6y#4#7#10s#7b#11#0#0#11r#7#0h#6#5#2#5#9#4.", t5, 13);
}

```

EDIT: Worked some golfing magic. It's as about as short and unreadable as I think it can get.

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


# Question
Title: Calculating dehydration synthesis results
Disclaimer: This challenge is *extremely* scientifically inaccurate. ;)

Given an input of a list of molecules, output what the result would be if they were to all combine via dehydration synthesis, if possible.

For the purposes of this challenge, although this description is inaccurate, a dehydration reaction between two molecules is performed as follows:

1. Remove `OH` (one oxygen and one hydrogen atom) from either of the two molecules.
2. Remove `H` (a single hydrogen atom) from the other one.
3. Combine the two molecules into one.

For instance, combining two `C<sub>6</sub>H<sub>12</sub>O<sub>6</sub>` molecules via dehydration synthesis would result in `C<sub>12</sub>H<sub>22</sub>O<sub>11</sub>`. Note that there are two less `H`s and one less `O` in the product than in the reactants. (These missing parts would form `H<sub>2</sub>O`, hence "dehydration," but that's irrelevant to this challenge.)

An example of molecules that cannot be combined via dehydration synthesis is `C<sub>6</sub>H<sub>12</sub>O<sub>6</sub>` \+ `CO<sub>2</sub>`. The required amount of hydrogen and oxygen is present, but neither `OH` nor `H` can be taken from the `CO<sub>2</sub>`.

The format of the input for each molecule is a list of atoms concatenated. An atom is always a single capital letter, possibly followed by a single lowercase letter (you don't have to handle atoms like `Uuo`). Atoms may also have integers ≥ 2 after them, representing how many of them there are; if this number is not present, it is assumed to be 1. Atoms will never be repeated within the same molecule.

Input may be provided as either an array/list/etc. of strings, or a single string separated by any non-alphanumeric character. Output must be a single string, but the output for "invalid input" (i.e. a list of molecules that cannot be combined via dehydration synthesis) may be any string containing at least one non-alphanumeric character (to distinguish from valid output). The order of the atoms in the output does not matter.

Since this is , the shortest code in bytes will win.

Test cases (invalid output is represented here by an asterisk `*`):

```
In                                                Out
------------------------------------------------------------------
C6H12O6 C6H12O6 C6H12O6 C6H12O6 C6H12O6 C6H12O6 | C36H62O31
CHO5 CH2 CH2 CH2 CH2 CH2                        | C6H
CHO4 CH2 CH2 CH2 CH2 CH2                        | *
H H H CH3O3                                     | C
H H H CH4O2                                     | *
C6H12O6 ABCDELMNOP C6H12O6                      | *
HO HO HO H3                                     | <empty string>
HgO4 C6H12O6                                    | *
HgHO4 C6H12O6                                   | HgH11O9C6
PdZnXeRaHO KrArKRbFH                            | PdZnXeRaKrArKRbF

```

# Answer
# Python (337 336 chars)

```
import re
i=input().split()
a,d,o,e=[],{},"",len(i)-1
for b in i:a.append(dict(re.findall(r"([A-Z][a-z]*)(\d*)",b)))
a=[{b:int(c[b])if c[b]else 1for b in c}for c in a]
for b in a:
 for c in b:d[c]=c in d and d[c]+b[c]or b[c]
 if"H"not in b:d["-"]=0
d["H"]-=2*e;d["O"]-=e
for b in d:o+=b+(str(d[b])if d[b]-1else"")if d[b]else""
print(o)

```

Here is an example of how to use this program:

```
sh3.14$ python dehydrate.py <-Run the program
C6H12O6 HgHO4               <-Input
O9H11C6Hg                   <-Output

```

Try it!
> 1 votes

# Answer
# Pyth (95 chars)

After seeing tiny, unreadable programs in CJam, Jelly, and Pyth, I decided to learn a golfing language, and because I am familiar with Python, I learned Pyth. Here is my code to solve this question:

```
FNQ aY.dm.Dd0:N"([A-Z][a-z]*)(\d*)"4;FNYFkN XkH|s@Nk1; X"O"HJ-1lQ; X"H"H*2J;FNHI@HNpNI>@HN1p@HN

```

The method that I have used to combine the molecules is similar to the one that I have used above implemented in Python. Here is a breakdown of that happens, statement by statement, character by character.

```
FNQ                                  For N in Q (input):
        m                             Map (same as python map())
         .Dd0                          Function for removing first element
             :N"([A-Z][a-z]*)(\d*)"4;  Get array of matches & groups
      .d                              Convert to dict
    aY                                Append to Y (pre-defined as an array)

FNY                                  For N in Y:
   FkN                                For K in N:
       XkH                             Increment/set H[k] (H pre-defined as a dict) to the following value
          |s@Nk1;                       if N[k] is null, then 1; else int(N[k])

 X"O"HJ-1lQ;                         Decrement H["O"] by length of Q - 1, and set J to length of Q - 1

 X"H"H*2J;                           Decrement H["H"] by 2 * J

FNH                                  For N in H:
   I@HN                               If H[N] (!= 0):
       pN                              Print N
         I>@HN1                       If H[N] > 1:
               p@HN                    Print H[N]

```

Test it! Note: The spaces in the code are for suppressing outputs.
> 1 votes

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