title: Convert the Time to a String

text:
# Question
Title: Convert the Time to a String
**Problem**

One day, you boss walks up to you and tells you he needs to know the time. He still insists after you pointing at the clock directly above your head, and confesses he has a severe case of dyscalculia, which causes him to not even be able to see numbers on a clock. While you're still left wondering how someone unable to see numbers can run a company, he tells you to "do something about it", whatever that is.

Your task is now to create a program or function that, given an input time with hours and minutes (seconds are optional)(hours are 24-based), outputs a readable english sentence, that doesn't contain numbers.

It is not necessary to ouput the seconds.

For example, `08:45:15` should output `quarter to nine o'clock AM`

**Test cases**

```
00:00:00 > twelve night
12:00:00 > twelve noon
06:00:00 > six o'clock AM
18:00:00 > six o'clock PM
06:15:00 > quarter past six o'clock AM
18:45:00 > quarter to seven o'clock PM
11:30:00 > half past eleven o'clock AM
13:22:00 > twentytwo minutes past one o'clock PM
17:43:00 > seventeen minutes to six o'clock PM
00:09:00 > nine minutes past twelve o'clock AM

```

**Rules**

Outputting numbers can be both in the form of fortytwo or forty-two, whichever you like best. Standard loopholes are not allowed. Trailing newlines are allowed, but the sentence should be on 1 line.

Input can be in any format you want, for example `HH:MM:SS`, `HH,MM,SS`, `HHMMSS`, `HH/MM/SS`, or any variant without seconds, but you should make the input format clear in your answer. It's not needed to output `one minute` instead of `one minutes`

for minutes ranging from 0 trough 30 (0 and 30 included) you should use `past`, and for the others you should use `to`

Because time is relative, shortest code in bytes wins.

# Answer
# Javascript, ~~384~~ 381 bytes

```
(h,m)=>(o='one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,'.split`,`,o=o.map((x,i)=>i>11?(x||o[i-10])+'teen':x),(a=m>30,t=12,m?(m-30?m%15?((m=a?59-m:m)>=(b=a?19:20)?'twenty'+((m%=b)?o[a?m:m-1]:''):o[a?m:m-1])+' minutes':'quarter':'half')+(a?' to ':' past '):'')+(h%t|m?o[(a?h:(h?h-1:11))%t]+` o'clock ${h>t?'P':'A'}M`:o[11]+(h-t?' night':' noon')))

```

```
f=
(h,m)=>(
    o='one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,'.split`,`,
    o=o.map((x,i)=>i>11?(x||o[i-10])+'teen':x),
    (a=m>30,t=12,
    m?
        (m-30?
            m%15?
                ((m=a?59-m:m)>=(b=a?19:20)?
                    'twenty'+((m%=b)?o[a?m:m-1]:'')
                :o[a?m:m-1])+' minutes'
            :'quarter'
        :'half')+(a?' to ':' past ')
    :'')
    +(h%t|m?
        o[(a?h:(h?h-1:11))%t]+` o'clock ${h>t?'P':'A'}M`
    :o[11]+(h-t?' night':' noon'))
)

document.body.innerHTML = '<pre>' +
'f(00,00) = ' + f(00,00) + '\n' +
'f(12,00) = ' + f(12,00) + '\n' +
'f(06,00) = ' + f(06,00) + '\n' +
'f(18,00) = ' + f(18,00) + '\n' +
'f(06,15) = ' + f(06,15) + '\n' +
'f(18,45) = ' + f(18,45) + '\n' +
'f(11,30) = ' + f(11,30) + '\n' +
'f(13,22) = ' + f(13,22) + '\n' +
'f(17,43) = ' + f(17,43) + '\n' +
'f(00,09) = ' + f(00,09) + '\n' +
'f(23,59) = ' + f(23,59) + '\n' +
'</pre>'
```
> 1 votes

# Answer
# LaTeX, 466 bytes

```
\usepackage{fmtcount,etoolbox}\def\x{\the\numexpr}\def\n[#1]{\numberstringnum{#1}}\def\h[#1]{\ifnumequal{#1}{0}{twelve night}{\ifnumequal{#1}{12}{twelve noon}{\ifnumless{#1}{13}{\n[#1] o'clock AM}{\n[\x#1-12\relax] o'clock PM}}}}\def\m[#1]{\ifnumequal{#1}{15}{quarter}{\ifnumequal{#1}{30}{half}{\n[#1] minutes}}}\newcounter{c}\def\f[#1]#2{\ifnumequal{#2}{0}{\h[#1]}{\ifnumless{#2}{31}{\m[#2] past \h[#1]}{\setcounter{c}{\x60-#2\relax}\m[\thec] to \h[\x#1+1\relax]}}}

```

Just call the macro `\f` as `\f[hour]{minutes}`, here some tests:

```
\begin{document}

\noindent
\textbf{Test cases:} \\ \\
00:00 = \f[00]{00} \\
12:00 = \f[12]{00} \\
06:00 = \f[6]{00} \\
18:00 = \f[18]{00} \\
06:15 = \f[6]{15} \\
18:45 = \f[18]{45} \\
11:30 = \f[11]{30} \\
13:22 = \f[13]{22} \\
17:43 = \f[17]{43} \\

\noindent
\textbf{More test cases:} \\ \\
00:13 = \f[00]{13} \\
12:12 = \f[12]{12} \\
12:15 = \f[12]{15} \\
11:45 = \f[11]{45} \\
11:41 = \f[11]{41} \\

\end{document}

```
> 4 votes

# Answer
# Python 2, 498 bytes

Input comes as function argument. First hour and then minute, both as integer. Result gets printed to the screen.

```
def g(h,m):
 a=lambda x:"twelve one two three four five six seven eigth nine ten eleven".split()[x%12];b=lambda x:a(x)+" o'clock "+["AM","PM"][x>=12]
 if m:
    z=m if m<30else 60-m;print(a(z)if z<13else("twenty"+(a(z-20)if z-20else"")if z>19else"thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split()[z-13])if m%15else"quarter"if m-30else"half")+(" minutes"if m-30and m%15else"")+[" past "+b(h)," to "+b(h+1)][m>30]
 else:print"twelve "+("noon"if h else "night")if h in[0,12]else b(h)

```

Try it online! *(with slightly extended testcases)*

That was a pretty fun golf. Although all those nested ternaries drove me a little bit crazy ^^
I was planning on doing this in Pyth after this, but I don't think that I am mentally able to do this at the moment (or ever).

**Ungolfed:**

```
def ungolfed(h,m):
    toStr=lambda x:"twelve one two three four five six seven eigth nine ten eleven".split()[x%12]
    hour=lambda x:toStr(x)+" o'clock "+["AM","PM"][x>=12]
    minute=lambda x:"twenty"+(toStr(x-20)if x-20else"")if x>19else"thirteen fourteen fifteen sixteen seventeen eighteen nineteen".split()[x-13]

    if m:
        s=""
        if m==30:
            s+="half"
        else:
            if m%15==0:
                s+="quarter"
            else:
                z=m if m<30 else 60-m
                if z<13:
                    s+=toStr(z)
                else:
                    s+=minute(z)
        print s+(" minutes"if m-30and m%15else "")+[" past "+hour(h)," to "+hour(h+1)][m>30]
    else:
        if h in[0,12]:
            print"twelve "+("noon"if h else "night")
        else:
            print hour(h)

```
> 3 votes

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

```
lambda h,m,N='one two three four five six seven eight nine ten eleven twelve thir four _ six seven eigh nine'.split()+['']:m+h%12and((m%15<1and['half','quarter'][m%2]or(lambda T:T<20and N[T-1]+T//13*'teen'or'twenty'+N[T%10-1])([m,60-m][m//31])+' minutes')+[' past ',' to '][m//31])*(m>0)+N[(h-1+m//31)%12]+" o'clock "+'APA'[(h+m//31)//12]+'M'or'twelve n'+['ight','oon'][h//12]

```

Try it online!

Stumbled on this challenge by accident and decided to give it a go.

# Explanation

Handles the edge cases of midnight and noon by using a standard `... and ... or ...` that has become ubiquitous for any Python code-golfer. For these edge cases return `twelve` , followed by night or noon depending on the hour.

In the general case, we build a string representing the minutes. If the minutes is 15 or 45, we start with `quarter`; if it is 30, we start with `half`; otherwise, we determine whether to use itself or 60 minus itself (think of it this way: 5:21 is 21 past 5, but 6:37 is 23 to 7, not 37 to 7). Let `M` denote this number. We build the appropriate number:

* if `M` is less than 20, start with the conversion of itself to letters, minus `teen`.
* if `M` is 20 or more, start with `twenty`.

Then:

* if `M` is less than 20 but more than 12, add `teen`.
* if `M` is 20 or more, add the conversion to letters of its units digit, with nothing being added if its units digit is zero.

If the minutes count was not divisible by 15, we also have to add  `minutes`.

Next, we have to deal with `past` and `to`. This is determined by indexing a list.

If the minutes count is zero, the above string goes to waste. Because `zero` or something similar does not appear in `N`, one might assume that building the string for zero would cause the program to error with an IndexError. But because Python allows negative indices, it doesn't error. When the minutes count is zero, we just don't use the above string.

Next we have to deal with `o' clock`, which is simply done using `%` and our list of text numbers again.

Finally we append `AM` or `PM` depending on the hour.
> 3 votes

# Answer
# Vyxal, 155 bytes

```
1→m?\:/⌊:£t¬[¥h12ḋ:→d÷¬[0→m12←d h¬[‛⟇Ẏ|‛₄⟨]|¥h12%]|¥t15ḋ:→d÷¬[←d h∷[‛ɽ¢|‛»⌈]|¥t:30>[60ε]‛«¦]¥t30≤[‛×Ṡ¥h12Ḋ[12|¥h12%]|‛to¥h12%›]]←m[`o'∵₅`¥h12<‛PAi\M+]WḢ∆ċṄ

```

Takes input as HH:MM.

Try it Online!
> 2 votes

# Answer
## Batch, ~~779~~ ~~774~~ ~~752~~ 749 bytes

```
@echo off
set t=%1
set/ah=%t:~0,2%,m=%t:~3,2%
set p=past
if %m% gtr 30 set p=to&set/am=60-m,h+=1
for %%a in ("one minute.1" quarter.15 half.30)do if %%~xa==.%m% set o=%%~na&goto g
set o=
if %m% gtr 20 set o=twenty-&set/am-=20
for %%a in (one.1 two.2 three.3 four.4 five.5 six.6 seven.7 eight.8 nine.9 ten.10 eleven.11 twelve.12 thirten.13 fourteen.14 sixteen.16 seventeen.17 eighteen.18 nineteen.19 twenty.20)do if %%~xa==.%m% set o=%o%%%~na minutes
:g
if not %m%==0 set o=%o% %p%
set a= AM
if %h% gtr 12 set a= PM&set/ah%%=12
if %h%==0 (echo %o%twelve night)else if %h%==12 (echo %o%twelve noon)else for %%a in (one.1 two.2 three.3 four.4 five.5 six.6 seven.7 eight.8 nine.9 ten.10 eleven.11)do if %%~xa==.%h% echo %o%%%~na o'clock%a%

```

Change the second line to `set t=%1%time%` to default to saying the current time if no time is provided.

Edit: Saved 22 bytes by optimising my `set/a` statements. Saved 3 bytes thanks to @EʀɪᴋᴛʜᴇGᴏʟғᴇʀ.

When I wrote my original version I made the mistake of saying the time as I would actually say it, i.e. o'clock only on exact hours, and midnight and midday instead of twelve night and twelve noon:

```
@echo off
set t=%1
set/a h=%t:~0,2%
set/a m=%t:~3,2%
set p=past
if %m% gtr 30 set p=to&set/a m=60-m&set/a h=h+1
for %%a in ("one minute.1" quarter.15 half.30) do if %%~xa==.%m% set o=%%~na&goto g
set o=
if %m% gtr 20 set o=twenty-&set/a m=%m%-20
for %%a in (one.1 two.2 three.3 four.4 five.5 six.6 seven.7 eight.8 nine.9 ten.10 eleven.11 twelve.12 thirten.13 fourteen.14 sixteen.16 seventeen.17 eighteen.18 nineteen.19 twenty.20) do if %%~xa==.%m% set o=%o%%%~na minutes
:g
set o=%o% %p%
set a= AM
if %h% gtr 12 set a= PM&set/a h=h%%12
if %m%==0 set a= o'clock%a%&set o=
if %h%==0 (echo %o%midnight)else if %h%==12 (echo %o%midday)else for %%a in (one.1 two.2 three.3 four.4 five.5 six.6 seven.7 eight.8 nine.9 ten.10 eleven.11) do if %%~xa==.%h% echo %o%%%~na%a%

```
> 1 votes

# Answer
# Perl 5, ~~367 361~~ 385 Bytes

Garbled

```
use integer;$_=<>;~/(\d+):(\d+)/;@b=(one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve); @x=(@b,thirteen,(map{/fi/?quarter:$_.teen}@b[3..8]),(map{twenty.$_}'',@b[0..8]),half);@y=map{/^q|h/?$_:$_.' minutes'}@x;$s=1-$2/31;$y=abs((-29,0)[$s]+$2%31)-1;$h=$1-$s;print((+-$2?@y[$y].' '.(to,past)[$s].' ':'').@b[$h++%12]." o' clock ".($h%12?(AM,PM)[$h/12]:(night,noon)[$h/12%2]))

```

Formatted and test cases:

```
use integer;
map{
    # capture (implicit $_)
    ~/(\d+):(\d+)/;
    # bare words
    @b=(one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve);
    # construct up to 30
    @x=(@b,thirteen,
       (map{/fi/?quarter:$_.teen}@b[3..8]),
       (map{twenty.$_}'',@b[0..8]),half);
    # quarter/half business
    @y=map{/^q|h/?$_:$_.' minutes'}@x;
    # whether we are to/past
    $s=1-$2/31;
    # num minutes wrapped around
    $y=abs((-29,0)[$s]+$2%31)-1;
    # num hours
    $h=$1-$s;
    #print('$s='.$s."\th=".$h."\th%12=".($h%12)."\n");
    print($_.' > ');
    #minute component
    print((+-$2
          ?@y[$y].' '.(to,past)[$s].' '
          :'')
        # hours
        .@b[$h++%12]
        ." o' clock "
        # Night/Noon
        .($h%12
          ?(AM,PM)[$h/12]
          :(night,noon)[$h/12%2]));
    print "\n"
}
('00:00:00',
 '00:01:00',
 '11:59:00',
 '12:00:00',
 '12:01:00',
 '06:00:00',
 '18:00:00',
 '06:15:00',
 '18:45:00',
 '11:30:00',
 '13:22:00',
 '17:43:00',
 '23:59:59')

```
> 1 votes

# Answer
# C, 478 bytes

```
*w(i){char*p,*n[]={"","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};return i>19?asprintf(&p,"twenty%s",n[i%20]),p:n[i];}main(m,h){scanf("%d%d",&h,&m);m>30?h++:0;printf("%s%s%s%s%s %s\n",m%15?m>30?w(60-m):w(m):m^30?m?"quarter":"":"half",m%15?" minutes":"",m?m>30?" to ":" past ":"",w((h+11)%12+1),h%12||m?" o'clock":"",h%12||m?h>11?"PM":"AM":h?"noon":"night");}

```

## Test Cases

```
$ echo "0 0" | ./a.out
twelve night
$ echo "12 0" | ./a.out
twelve noon
$ echo "6 0" | ./a.out
six o'clock AM
$ echo "18 0" | ./a.out
six o'clock PM
$ echo "6 15" | ./a.out
quarter past six o'clock AM
$ echo "18 45" | ./a.out
quarter to seven o'clock PM
$ echo "11 30" | ./a.out
half past eleven o'clock AM
$ echo "13 22" | ./a.out
twentytwo minutes past one o'clock PM
$ echo "17 43" | ./a.out
seventeen minutes to six o'clock PM
$ echo "0 9" | ./a.out
nine minutes past twelve o'clock AM

```

Try it here.
> 1 votes

---
Tags: code-golf, date, conversion
---


title: Best Rolling Ao5

text:
# Question
Title: Best Rolling Ao5
In speedcubing, an Ao5 (Average of 5) is computed for a set of five times by removing the fastest and slowest times, and then computing the mean of the remaining three times.

A "rolling ao5" is computed for a sequence of at least five times by computing the ao5 for every set of consecutive five times (some sets will overlap). The best rolling ao5 is the lowest time out of all of these.

Related very old and much more involved question: Calculate the average and standard deviation, rubiks cube style

## Input

An array of between 5 and 100 times inclusive, where each time is a number with exactly two decimal places, between 0.01 and 60.00. The array may be given as input in any reasonable format (list, csv string, etc.)

## Output

The best rolling Ao5, where the mean must be rounded to the nearest hundredth and outputted with exactly two decimal places (including trailing zeros).

## Test cases

Input on first line, output on second line.

```
7.16 5.04 4.67 6.55 4.99
5.53

```

```
10.00 10.00 10.00 10.00 10.00 7.00 6.00
9.00

```

```
34.87 33.24 33.31 33.63 27.04 29.14 29.74 31.65 27.42 30.13 28.31 32.50 32.61 36.38 28.60 33.85 28.42 36.00 32.41 35.35 29.47 31.02 28.87 35.08
28.77

```

# Answer
# R, ~~93~~ ~~88~~ ~~86~~ ~~80~~ ~~79~~ 77 bytes

Simple reference solution. Uses `trim` feature of `min` as Giuseppe pointed out.

```
x=scan()
sprintf("%.2f",min(sapply(5:sum(x|1),function(i)mean(x[i-0:4],.2))))

```

-2 bytes by Giuseppe by replacing `length(x)` and cleaning up unnecessary character in sprintf.

Try it online!

## ~~80~~ 78 bytes

Similar answer but with a for loop.

```
x=scan()
a={}
for(i in 5:sum(x|1))a=min(a,mean(x[i-0:4],.2))
sprintf("%.2f",a)

```

Try it online!
> 5 votes

# Answer
# Factor, 72 bytes

```
[ 5 clump [ 3 [1,b] [ < ] kth-objects mean ] map infimum "%.2f"sprintf ]

```

Try it online!

## Explanation:

It's a quotation (anonymous function) that takes a sequence of numbers from the data stack as input and leaves a string on the data stack as output.

* `5 clump` Split a sequence into groups of 5 with overlapping. This is the 'rolling' part.
* `[ ... ] map` Apply a quotation to each element of a sequence, collecting the results into a sequence of the same size.
* `3 [1,b] [ < ] kth-objects` Take the second, third, and fourth elements of a sequence (from a sorted standpoint). This is shorter than trying to sort it and then chop off both ends.
* `mean` Take the mean.
* `infimum` Take the smallest element from a sequence.
* `"%.2f"sprintf` Return the result as a string rounded to two decimal places.
> 5 votes

# Answer
# , ~~86~~ 82 bytes

```
function(x,l=sum(x|1))sprintf("%.2f",min(apply(matrix(x,l+1,5),1,mean,.2)[5:l-5]))

```

Try it online!

R's `mean` function helpfully can be used to calculate a trimmed mean.

Outgolfed by qwr.
> 4 votes

# Answer
# MATL, 20 bytes

```
5YCS6LY)YmX<'%.2f'YD

```

Try it online! Or verify all test cases.

### Explanation

```
        % Implicit input
5YC     % Matrix with sliding blocks of length 5 as columns
S       % Sort each column
6L      % Push [2 1j-1]. When used as an index, this is interpreted as "2:end-1"
Y)      % Index the rows as specified. This removes first and last rows
Ym      % Mean of each column
X<      % Mininum
'%.2f'  % Push this string: format specification, 'sprintf'-style
YD      % Convert to string with specified format
        % Implicit display

```

Direct translation to an anonymous function in Octave (with the Image package):

```
@(x)sprintf('%.2f',min(mean(sort(im2col(x,[1 5]))(2:end-1,:))))

```
> 4 votes

# Answer
# JavaScript (ES6), 97 bytes

```
f=a=>Math.min(([,x,y,z,q]=[a.pop(),...a.slice(-4)].sort((a,b)=>a-b),x+y+z)/3,q?f(a):z).toFixed(2)

```

Try it online!
> 4 votes

# Answer
# Retina 0.8.2, 83 bytes

```
\.

\d+
$*
M!&`\b(1+,){4}1+
%(O`1+
^1+|,|1+$

)M`1{2,3}
O#`
1G`
+`^..?$
0$&
..$
.$&

```

Try it online! Link includes test cases. Explanation:

```
\.

```

Multiply the input by 100.

```
\d+
$*

```

Convert to unary.

```
M!&`\b(1+,){4}1+

```

Extract all overlapping sets of five consecutive values.

```
%(`
)`

```

For each set, ...

```
O`1+

```

... sort in order, ...

```
^1+|,|1+$

```

... delete the fastest and slowest times, ...

```
M`1{2,3}

```

... and take the mean, rounding to nearest, converting to decimal.

```
O#`

```

Sort the means.

```
1G`

```

Take the fastest.

```
+`^..?$
0$&
..$
.$&

```

Divide it by 100.
> 3 votes

# Answer
# Python 2, ~~103~~, ~~89~~, ~~76~~, 73 bytes

Saved **14 bytes** thanks to qwr!

Saved **7 bytes** thanks to okie's suggestion to use a list comprehension.

Saved another **6 bytes** by switching to a `lambda` function.

Saved **3 bytes** after removing the extra brackets and comma and fixing the first slice. Thanks to caird, okie, and att! Also removed a pair of extra parentheses.

```
lambda t:"%.2f"%min(sum(sorted(t[i:i+5])[1:4])/3for i in range(len(t)-4))

```

The program iterates through all the consecutive runs of 5. The runs of 5 are `sorted` and the first and last elements are removed using slicing. The program `sum`s the values remaining in the run and divides by `3` to find the average. Finally, percent formatting is used return the `min` value.

Try it online!
> 3 votes

# Answer
# Jelly, 25 bytes

```
ṡ5ṢṖḊƊ€ÆmṂ×ȷ2+.ḞDṙ-2;”.ṙ2

```

Try it online!

Note to self: add formatting options to my new golfing language to avoid this ^ clownery
> 2 votes

# Answer
# , 30 bytes

```
0j2":[:<./5(3%~1#.1 2 3{/:~)\]

```

Try it online!
> 2 votes

# Answer
# V (vim), 140 bytes

```
o<esc>qq15wlh0y15wO<esc>pj0d3w@qqdk@qqt:s/ /\r/g
<c-o>:.,.4$sor n
:.,.4j
d3w$3bhd$:s/ /+/g
C<c-r>=(<c-r>")/3
<esc>k0@tq@t:%s/^\n
:sor n
{0C<c-r>=printf("%.2f",<c-r>")
<esc>o<esc>d}

```

Try it online!

I was lucky that vim had `printf` for this challenge, I'd finished most of it before I realized the output spec (phew)
> 2 votes

# Answer
# APL (Dyalog Extended), 18 bytes

```
2⍕2⌷⌊⌿3+/↑∧¨5,/⎕÷3

```

Try it online!

Full program. Example with the second testcase:

`⎕÷3` input divided by 3:

```
3.667 3.333 3.333 3.333 3.000 3.333

```

`5,/` groups of 5 adjacent values:

```
┌─────────────────────────┬─────────────────────────┐
│3.667 3.333 3.333 3.333 3│3.333 3.333 3.333 3 3.333│
└─────────────────────────┴─────────────────────────┘

```

`↑∧¨` sort each group and arrange the result in a matrix:

```
3 3.333 3.333 3.333 3.667
3 3.333 3.333 3.333 3.333

```

`3+/` in each row, take sums of 3 adjacent values:

```
9.667 10 10.33
9.667 10 10

```

`⌊⌿` get the minimum for each column:

```
9.667 10 10

```

`2⍕2⌷` select the second value and format with 2 decimal places:

```
10.00

```
> 2 votes

# Answer
# Pari/GP, 109 bytes

This doesn't work on Tio because their version of Pari/GP is apparently too old to have the vital function strsplit(). But it works as advertised on mine, version 2.13.0

```
A(s)=s=[eval(x)|x<-strsplit(s," ")];printf("%.2f",vecmin(vector(#s-4,i,vecsum(vecsort(s[i..i+4])[2..4])/3)))

```

Try it online!
> 2 votes

# Answer
# Wolfram Language (Mathematica), 55 bytes

```
Min@BlockMap[#~TrimmedMean~.2&,#,5,1]~NumberForm~{4,2}&

```

Try it online!

Technical note: the TIO link includes `SetOptions[$Output, FormatType -> OutputForm]` in the header. I am not including this in the score, because it's not necessary in an actual Mathematica notebook: those are in `OutputForm` by default.

## Explanation

`BlockMap[f,#,5,1]` applies `f` to every block of 5 consecutive numbers. Here, `f` is `#~TrimmedMean~.2&`, which takes the mean after dropping the lowest and highest 20%.

We take the minimum of the results, and then `~NumberForm~{4,2}` puts the answer in the required format: at most 4 digits of precision, with 2 digits after the decimal.
> 2 votes

# Answer
# Vyxal, 16 bytes

```
5l⟑sḢṪṁ;g:∆τ⌊3+Ḟ

```

Try it Online!

## How?

```
5l        # apertures, width 5
  ⟑       # map over each:
   s      # - sort
    Ḣ     # - drop head
     Ṫ    # - drop tail
      ṁ   # - average
       ;  # end map
        g # minimum

:       # dup
 ∆τ     # log10
   ⌊    # floor
    3+  # plus 3
      Ḟ # format to that many decimals

```
> 2 votes

# Answer
# JavaScript (Node.js), ~~131~~ ~~128~~ ~~125~~ ~~124~~ ~~154~~  ~~138~~ 120 bytes

```
x=>Math.min(...x[f='slice'](0,-4).map((_,i)=>x[f](i,i+5).sort((a,b)=>a-b)[f](1,4)).map(([a,b,c])=>(a+b+c)/3)).toFixed(2)

```

Too long. Will golf.

# Explanation

```
x=>                              // declare function
    Math.min(...                // smallest of
       x[f='slice'](0,-4)        // slice of last 4 to avoid NaN / undefined, defining f as 'slice' to save bytes
       .map((_,i)=>              // for each, by index (current value doesn't matter for now)
         x[f](i,i+5)             // remember f is slice, so replace each with its chunk of 5 (x is untrimmed, slice doesn't modify original
         .sort((a,b)=>a-b)       // sort numerically
         [f](1,4)                // remove first and last
       ).map(([a,b,c])=>         // for each, taking all 3 elements
         (a+b+c)/3               // take average
       )
     )                           // end of min, so now have smallest
   ).toFixed(2)                  // round + add 0s

```

Try it online!
> 1 votes

# Answer
# Haskell, 106 bytes

```
printf"%.2f".g
g(h:t)|length t<4=99|y<-h:take 4t=min((sum y-maximum y-minimum y)/3)$g t
import Text.Printf

```

Try it online!

The relevant function is `f`, which takes as input the array of times as a list of `Double`s. `f` returns a string representation of the best rolling AoE.

Having to import `Text.Printf` for this seems... *wrong*..., but I couldn't find any shorter way.
> 1 votes

# Answer
# Charcoal, 29 bytes

```
﹪%.2f∕⌊ＥＥ⁻Ｌθ⁴✂θι⁺⁵ι¹⁻Σι⁺⌊ι⌈ι³

```

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

```
           θ                    Input array
          Ｌ                     Length
         ⁻                      Subtract
            ⁴                   Literal 4
        Ｅ                       Map over implicit range
              θ                 Input array
             ✂                  Sliced
               ι                From current index
                ⁺⁵ι¹            Take five consecutive values
       Ｅ                        Map over slices
                      ι         Current slice
                     Σ          Sum
                    ⁻           Subtract
                         ι      Current slice
                        ⌊       Minimum
                       ⁺        Plus
                           ι    Current slice
                          ⌈     Maximum
      ⌊                         Take the minimum
     ∕                          Divide by
                            ³   Literal `3`
﹪%.2f                           Round to two decimal places
                                Implicitly print

```
> 1 votes

# Answer
# Japt v2.0a0, 17 bytes

+4 bytes for the dumb output format :/

```
ã5 ®ÍÅÔÅx÷3Ãrm x2

```

Try it

```
ã5 ®ÍÅÔÅx÷3Ãrm x2     :Implicit input of array
ã5                    :Sub-arrays of length 5
   ®                  :Map
    Í                 :  Sort
     Å                :  Slice off first element (the minimum)
      Ô               :  Reverse
       Å              :  Slice off first element (the maximum)
        x             :  Reduce by addition
         ÷3           :  Divide by 3
           Ã          :End map
            r         :Reduce by
             m        :  Minimum
               x2     :Force to 2 decimal places

```
> 1 votes

# Answer
# Ruby, ~~58~~ 56 bytes

```
->a{"%.2f"%a.each_cons(5).map{|b|b.sort[1,3].sum/3}.min}

```

Try it online!

### Explanation

It's quite straightforward actually:

* get all sets of 5 consecutive elements using `each_cons(5)`
* sort them, then get the 3 elements in the middle to discard min and max
* calculate average
* get minimum average value and format with 2 decimal places
> 1 votes

# Answer
# Red, 153 bytes

```
func[b][head insert at tail to""round/to 100 * first sort
collect[loop(length? b)- 4[keep average copy/part next
sort copy/part b 5 3 b: next b]]1 -2"."]

```

Try it online!
> 1 votes

# Answer
# Perl 5 `-MList::Util=sum,min,max -a`, ~~81~~ 67 bytes

```
printf"%.2f",(min map{sum(@b=@F[$_..$_+4])-min(@b)-max@b}0..@F-5)/3

```

Try it online!
> 0 votes

---
Tags: code-golf, array, floating-point
---


title: Calculate the Mean mean of two numbers

text:
# Question
Title: Calculate the Mean mean of two numbers
disclaimer: the Mean mean is made up by me

Define the arithmetic mean of \\$n\\$ numbers as $$M\_1(x\_1,...,x\_n)=\frac{x\_1+x\_2+...+x\_n}{n}$$ Define the geometric mean of \\$n\\$ numbers as $$M\_0(x\_1,...,x\_n)=\root{n}\of{x\_1x\_2...x\_n}$$ Define the harmonic mean of \\$n\\$ numbers as $$M\_{-1}(x\_1,...,x\_n)=\frac{n}{\frac{1}{x\_2} + \frac{1}{x\_2} + ... + \frac{1}{x\_n}}$$ Define the quadratic mean of \\$n\\$ numbers as $$M\_2(x\_1,...,x\_n)=\root\of{\frac{x\_1^2+x\_2^2+...+x\_n^2}{n}}$$ The Mean mean (\\$M\_M\\$) is defined as follows: Define four sequences (\\$a\_k, b\_k, c\_k, d\_k\\$) as $$a\_0=M\_1(x\_1,...,x\_n),\\b\_0=M\_0(x\_1,...,x\_n),\\c\_0=M\_{-1}(x\_1,...,x\_n),\\d\_0=M\_2(x\_1,...,x\_n),\\ a\_{k+1}=M\_1(a\_k,b\_k,c\_k,d\_k),\\b\_{k+1}=M\_0(a\_k,b\_k,c\_k,d\_k),\\c\_{k+1}=M\_{-1}(a\_k,b\_k,c\_k,d\_k),\\d\_{k+1}=M\_2(a\_k,b\_k,c\_k,d\_k)$$ All four sequences converge to the same number, \\$M\_M(x\_1,x\_2,...,x\_n)\\$.

## Example

The Mean mean of 1 and 2 is calculated as follows: start with $$a\_0 = (1+2)/2 = 1.5, b\_0 = \root\of{1 * 2} = \root\of2 \approx 1.4142,\\ c\_0 = \frac2{\frac1{1}+\frac1{2}} = \frac4{3} \approx 1.3333, d\_0 = \root\of{\frac{1^2+2^2}2} = \root\of{\frac5{2}} \approx 1.5811.$$ Then $$a\_1 = \frac{1.5+1.4142+1.3333+1.5811}4 \approx 1.4571,\\ b\_1 = \root^4\of{1.5\*1.4142\*1.3333\*1.5811} \approx 1.4542,\\ c\_1 = \frac4{\frac1{1.5}+\frac1{1.4142}+\frac1{1.3333}+\frac1{1.5811}} \approx 1.4512,\\ d\_1 = \root\of{\frac{1.5^2+1.4142^2+1.3333^2+1.5811^2}4} \approx 1.4601.$$ The further calculation of the sequences should be clear. It can be seen that they converge to the same number, approximately \\$1.45568889\\$.

## Challenge

Given two positive real numbers, \\$a\\$ and \\$b\\$ (\\$a\<b\\$), calculate their Mean mean \\$M\_M(a,b)\\$.

## Test cases

```
1 1 => 1
1 2 => 1.45568889
100 200 => 145.568889
2.71 3.14 => 2.92103713
0.57 1.78 => 1.0848205
1.61 2.41 => 1.98965438
0.01 100 => 6.7483058

```

# Notes

* Your program is valid if the difference between its output and the correct output is not greater than 1/100000 of the absolute value of the difference between input numbers.
* The output should be a single number.

This is , so the shortest code wins!

# Answer
# Wolfram Language (Mathematica), 52 bytes

```
#//.x_:>N@{M@x,E^M@Log@x,1/M[1/x],M[x^2]^.5}&
M=Mean

```

Try it online!

In my first approach I used these builtins
`Mean` `GeometricMean` `HarmonicMean` and `RootMeanSquare`

Here are some substitutions for saving bytes

`HarmonicMean` --\> `1/Mean[1/x]` by @Robin Ryder (3 bytes saved)
`GeometricMean` --\> `E^Mean@Log@x` by @A. Rex (2 bytes saved)
`RootMeanSquare` --\> `Mean[x^2]^.5` by @A. Rex (4 bytes saved)

finally we can assign `Mean` to `M` (as proposed by @ovs) and save 5 more bytes
> 14 votes

# Answer
# R, ~~70~~ ~~69~~ 67 bytes

```
x=scan();`?`=mean;while(x-?x)x=c((?x^2)^.5,?x,2^?log2(x),1/?1/x);?x

```

Try it online!

-1 byte with better conditioning.
-2 bytes by switching to base 2.

Like some other answers, this uses the expression of the geometric mean as an arithmetic mean on the log scale (here in base 2): $$M\_0(x\_1,\ldots, x\_n) = 2^{M\_1(\log\_2 x\_1,\ldots,\log\_2 x\_n)}.$$

It also uses the fact that \\$\forall k, d\_k\geq a\_k \geq b\_k\geq c\_k\\$, i.e. \\$d\_k=\max(a\_k, b\_k, c\_k, d\_k)\\$. The condition \\$a\_k=b\_k=c\_k=d\_k\\$ is therefore equivalent to \\$d\_k = M\_1(a\_k, b\_k, c\_k, d\_k)\\$, which is what I use in the while loop; this is achieved by abusing the syntax of `while` which only considers the first element when the condition is a vector, hence the order in which the means are stored. (Note that we could also use \\$c\_k\\$ instead since it is the minimum of the four, but we could not use \\$a\_k\\$ or \\$b\_k\\$ in the condition.)

When we exit the while loop, `x` is a constant vector. The final `?x` computes its mean to reduce it to a scalar.
> 10 votes

# Answer
# , 34 bytes

(31 as an expression without the assignment to variable `f`)

```
f=:1{(^.z,%z,*:z,[z=:(+/%#)&.:)^:_

```

Try it online!

For functions `a` and `b`, `a &.: b` ("a under b" (related challenge)) is equivalent to `(b inv) a b` -- apply b, then a, then inverse of b. In this case, geometric/harmonic/quadratic mean is the arithmetic mean "under" logarithm, inversion, and square respectively.
> 6 votes

# Answer
# TI-BASIC, ~~42~~ ~~35~~ 34 bytes

*-1 byte thanks to @SolomonUcko*

```
While max(ΔList(Ans:{mean(Ans),√(mean(Ans²)),mean(Ans^-1)^-1,e^(mean(ln(Ans:End:Ans(1

```

Input is a list of two integers in `Ans`.
Output is stored in `Ans` and is automatically printed out when the program completes.

Formulas used for geometric, harmonic, and quadratic means are based off of user202729's explanation.

**Example:**

```
{1,2
           {1 2}
prgmCDGFB
     1.455688891
{100,200
       {100 200}
prgmCDGFB
     145.5688891

```

**Explanation:**
(Newlines have been added for clarification. They do **NOT** appear in the code.)

```
While max(ΔList(Ans           ;loop until all elements of the current list are equal
                              ; the maximum of the change in each element will be 0
{                             ;create a list containing...
 mean(Ans),                   ; the arithmetic mean
 √(mean(Ans²)),               ; the quadratic mean
 mean(Ans^-1)^-1,             ; the harmonic mean
 e^(mean(ln(Ans               ; and the geometric mean
End
Ans(1                         ;keep the first element in "Ans" and implicitly print it

```

---

**Notes:**

TI-BASIC is a tokenized language. Character count does *not* equal byte count.

`e^(` is this one-byte token.

`^-1` is used for this one-byte token.
I opted for writing `^-1` instead because the token looks like `ֿ¹` when in a code block.

`√(` is this one-byte token.

`ΔList(` is this two-byte token.
> 5 votes

# Answer
# Java 10, ~~234~~ ~~229~~ ~~214~~ ~~211~~ ~~215~~ ~~206~~ ~~203~~ ~~196~~ ~~180~~ 177 bytes

```
a->{for(;a[1]-a[0]>4e-9;){double l=a.length,A[]={0,0,0,1};for(var d:a){A[2]+=d/l;A[3]*=Math.pow(d,1/l);A[0]+=1/d;A[1]+=d*d;}A[0]=l/A[0];A[1]=Math.sqrt(A[1]/l);a=A;}return a[0];}

```

-5 bytes thanks to *@PeterCordes*.
-15 more bytes thanks to *@PeterCordes*, inspired by *@RobinRyder*'s R answer.
+4 bytes because I assumed the inputs are pre-ordered.
-27 bytes thanks to *@OlivierGrégoire*.

Try it online.

**Explanation:**

```
a->{                        // Method with double-array parameter and double return-type
  for(;a[1]-a[0]            //  Loop as long as the difference between the 2nd and 1st items
                >4e-9;){    //  is larger than 0.000000004:
    double l=a.length,      //   Set `l` to the amount of values in the array `a`
           A[]={0,0,0,1};   //   Create an array `A`, filled with the values [0,0,0,1]
    for(var d:a){           //   Inner loop over the values of `a`:
      A[2]+=d/l;            //    Calculate the sum divided by the length in the third spot
      A[3]*=Math.pow(d,1/l);//    The product of the power of 1/length in the fourth spot
      A[0]+=1/d;            //    The sum of 1/value in the first spot
      A[1]+=d*d;            //    And the sum of squares in the second spot
    }                       //   After the inner loop:
                            //   (the third spot of the array now holds the Arithmetic Mean)
                            //   (the fourth spot of the array now holds the Geometric Mean)
    A[0]=l/A[0];            //   Divide the length by the first spot
                            //   (this first spot of the array now holds the Harmonic Mean)
    A[1]=Math.sqrt(A[1]/l); //   Take the square of the second spot divided by the length
                            //   (this second spot of the array now holds the Quadratic Mean)
    a=A;                    //   And then replace input `a` with array `A`
  }                         //  After the outer loop when all values are approximately equal:
  return a[0];}             //  Return the value in the first spot as result

```
> 5 votes

# Answer
# Charcoal, 40 bytes

```
Ｗ‹⌊θ⌈θ≔⟦∕ΣθＬθＸΠθ∕¹Ｌθ∕ＬθΣ∕¹θ₂∕ΣＸθ²Ｌθ⟧θＩ⊟θ

```

Try it online! Link is to verbose version of code. Takes input as an array of numbers. Explanation:

```
Ｗ‹⌊θ⌈θ

```

Repeat while the array contains different values...

```
≔⟦....⟧θ

```

... replace the array with a list of values:

```
∕ΣθＬθ

```

... the mean...

```
ＸΠθ∕¹Ｌθ

```

... the geometric mean...

```
∕ＬθΣ∕¹θ

```

... the harmonic mean...

```
₂∕ΣＸθ²Ｌθ

```

... and the root mean square.

```
Ｉ⊟θ

```

Cast an element of the array to string and implicitly print it.
> 3 votes

# Answer
# Jelly, ~~25~~ 24 bytes

```
Wẋ4¹ÆlÆeƭ²½ƭİ4ƭÆm$€⁺µÐLḢ

```

Try it online!

### Explanation

```
                    µÐL | Repeat until unchanged:
W                       |   Wrap as a list
 ẋ4                     |   Copy list 4 times
                   ⁺    |   Do twice:
                 $€     |     For each copy of the list:
             4ƭ         |     One of these functions, cycling between them:
   ¹                    |       Identity
    ÆlÆeƭ               |       Alternate between log and exp
         ²½ƭ            |       Alternate between square and square root
            İ           |       Reciprocal
               Æm       |    Then take the mean
                       Ḣ| Finally take the first item

```
> 3 votes

# Answer
# Jelly, 24 bytes

```
;µ*Ɱ-;Ø½¤©Æm*İɼ;P½½ƊµÐLḢ

```

Try it online!
> 3 votes

# Answer
# PowerShell, ~~182~~ ~~180~~ 183 bytes

```
$f={$a=$c=$d=$n=0
$b=1
$m=[math]
$args|%{$n++
$a+=$_
$b*=$_
$c+=1/$_
$d+=+$_*$_}
$p=($a/$n),$m::pow($b,1/$n),($n/$c),$m::sqrt($d/$n)|%{$m::round($_,9)}
if($p-ne$p[0]){$p=&$f @p}$p[0]}

```

Try it online!
> 3 votes

# Answer
# 05AB1E, ~~26~~ ~~24~~ 23 bytes

```
Δ©ÅA®.²ÅAo®zÅAz®nÅAt)}н

```

Try it online or see the steps of all test cases.

-1 byte thanks to *@Grimy*.

**23 byter alternative for Geometric mean:**

```
Δ©P®gzm®ÅA®zÅAz®nÅAt)}н

```

Try it online or see the steps of all test cases.

**Explanation:**

```
Δ         # Loop until the list no longer changes:
 ©        #  Store the current list in variable `®` (without popping)
          #  (which is the implicit input-list in the first iteration)
          #  Arithmetic mean:
  ÅA      #   Builtin to calculate the arithmetic mean of the list
          #  Geometric mean:
  ®.²     #   Take the base-2 logarithm of each value in the list `®`
     ÅA   #   Get the arithmetic mean of that list
       o  #   And take 2 to the power of this mean
          #  Harmonic mean:
  ®z      #   Get 1/x for each value x in the list `®`
    ÅA    #   Get the arithmetic mean of that list
      z   #   And calculate 1/y for this mean y
          #  Quadratic mean:
  ®n      #   Take the square of each number x in the list from the register
    ÅA    #   Calculate the arithmetic mean of this list
      t   #   And take the square-root of that mean
  )       #  Wrap all four results into a list
}н        # After the list no longer changes: pop and push its first value
          # (which is output implicitly as result)

```
> 3 votes

# Answer
# x86 machine code (SIMD 4x float using 128-bit SSE1&AVX) 94 bytes

# x86 machine code (SIMD 4x double using 256-bit AVX) 123 bytes

`float` passes the test cases in the question, but with a loop-exit threshold small enough to make that happen, it's easy for it to get stuck in an infinite loop with random inputs.

SSE1 packed-single-precision instructions are 3 bytes long, but SSE2 and simple AVX instructions are 4 bytes long. (Scalar-single instructions like `sqrtss` are also 4 bytes long, which is why I use `sqrtps` even though I only care about the low element. It's not even slower than sqrtss on modern hardware). I used AVX for non-destructive destination to save 2 bytes vs. movaps+op.
In the double version we can still do a couple `movlhps` to copy 64-bit chunks (because often we only care about the low element of a horizontal sum). Horizontal sum of a 256-bit SIMD vector also requires an extra `vextractf128` to get the high half, vs. the slow but small 2x `haddps` strategy for float. The `double` version also needs 2x 8-byte constants, instead of 2x 4-byte. Overall it comes out at close to 4/3 the size of the `float` version.

**`mean(a,b) = mean(a,a,b,b)` for all 4 of these means**, so we can simply duplicate the input up to 4 elements and never have to implement length=2. Thus we can hardcode geometric mean as 4th-root = sqrt(sqrt), for example. And we only need one FP constant, `4.0`.

**We have a single SIMD vector of all 4 `[a_i, b_i, c_i, d_i]`. From that, we calculate the 4 means as scalars in separate registers, and shuffle them back together for the next iteration.** (Horizontal operations on SIMD vectors are inconvenient, but we need to do the same thing for all 4 elements in enough cases that it balances out. I started on an x87 version of this, but it was getting very long and not fun.)

**The loop-exit condition of `}while(quadratic - harmonic > 4e-5)` (or a smaller constant for `double`)** is based on @RobinRyder's R answer, and Kevin Cruijssen's Java answer: quadratic mean is always the *largest* magnitude, and harmonic mean is always the smallest (ignoring rounding errors). So we can check the delta between those two to detect convergence. We return the arithmetic mean as the scalar result. It's usually between those two and is probably the least susceptible to rounding errors.

**Float version**: callable as `float meanmean_float_avx(__m128);` with the arg and return value in xmm0. (So x86-64 System V, or Windows x64 vectorcall, but not x64 fastcall.) Or declare the return-type as `__m128` so you can get at the quadratic and harmonic mean for testing.

Letting this take 2 separate `float` args in xmm0 and xmm1 would cost 1 extra byte: we'd need a `shufps` with an imm8 (instead of just `unpcklps xmm0,xmm0`) to shuffle together and duplicate 2 inputs.

```
    40  address                    align 32
    41          code bytes         global meanmean_float_avx
    42                             meanmean_float_avx:
    43 00000000 B9[52000000]           mov      ecx, .arith_mean      ; allows 2-byte call reg, and a base for loading constants
    44 00000005 C4E2791861FC           vbroadcastss  xmm4, [rcx-4]    ; float 4.0
    45
    46                                 ;; mean(a,b) = mean(a,b,a,b) for all 4 types of mean
    47                                 ;; so we only ever have to do the length=4 case
    48 0000000B 0F14C0                 unpcklps xmm0,xmm0          ; [b,a] => [b,b,a,a]
    49
    50                                 ; do{ ... } while(quadratic - harmonic > threshold);
    51                             .loop:
    52                             ;;; XMM3 = geometric mean: not based on addition.  (Transform to log would be hard.  AVX512ER has exp with 23-bit accuracy, but not log.  vgetexp = floor(lofg2(x)), so that's no good.)
    53                                 ;; sqrt once *first*, making magnitudes closer to 1.0 to reduce rounding error.  Numbers are all positive so this is safe.
    54                                 ;; both sqrts first was better behaved, I think.
    55 0000000E 0F51D8                 sqrtps   xmm3, xmm0                 ; xmm3 = 4th root(x)
    56 00000011 F30F16EB               movshdup xmm5, xmm3                 ; bring odd elements down to even
    57 00000015 0F59EB                 mulps    xmm5, xmm3
    58 00000018 0F12DD                 movhlps  xmm3, xmm5                 ; high half -> low
    59 0000001B 0F59DD                 mulps    xmm3, xmm5                 ; xmm3[0] = hproduct(sqrt(xmm))
    60                             ;    sqrtps   xmm3, xmm3                 ; sqrt(hprod(sqrt)) = 4th root(hprod)
    61                                 ; common final step done after interleaving with quadratic mean
    62
    63                             ;;; XMM2 = quadratic mean = max of the means
    64 0000001E C5F859E8               vmulps   xmm5, xmm0,xmm0
    65 00000022 FFD1                   call     rcx                ; arith mean of squares
    66 00000024 0F14EB                 unpcklps xmm5, xmm3         ; [quad^2, geo^2, ?, ?]
    67 00000027 0F51D5                 sqrtps   xmm2, xmm5         ; [quad,   geo,   ?, ?]
    68
    69                             ;;; XMM1 = harmonic mean = min of the means
    70 0000002A C5D85EE8               vdivps   xmm5, xmm4, xmm0    ; 4/x
    71 0000002E FFD1                   call     rcx                ; arithmetic mean (under inversion)
    72 00000030 C5D85ECD               vdivps   xmm1, xmm4, xmm5    ; 4/.  (the factor of 4 cancels out)
    73
    74                             ;;; XMM5 = arithmetic mean
    75 00000034 0F28E8                 movaps   xmm5, xmm0
    76 00000037 FFD1                   call     rcx
    77
    78 00000039 0F14E9                 unpcklps  xmm5, xmm1           ;     [arith, harm, ?,?]
    79 0000003C C5D014C2               vunpcklps xmm0, xmm5,xmm2      ; x = [arith, harm, quad, geo]
    80
    81 00000040 0F5CD1                 subps    xmm2, xmm1        ; largest - smallest mean: guaranteed non-negative
    82 00000043 0F2E51F8               ucomiss  xmm2, [rcx-8]     ; quad-harm > convergence_threshold
    83 00000047 73C5                   jae     .loop
    84
    85                                 ; return with the arithmetic mean in the low element of xmm0 = scalar return value
    86 00000049 C3                     ret
    87
    88                             ;;; "constant pool" between the main function and the helper, like ARM literal pools
    89 0000004A ACC52738           .fpconst_threshold:   dd 4e-5    ; 4.3e-5 is the highest we can go and still pass the main test cases
    90 0000004E 00008040           .fpconst_4:    dd 4.0
    91                             .arith_mean:               ; returns XMM5 = hsum(xmm5)/4.
    92 00000052 C5D37CED               vhaddps   xmm5, xmm5         ; slow but small
    93 00000056 C5D37CED               vhaddps   xmm5, xmm5
    94 0000005A 0F5EEC                 divps     xmm5, xmm4        ; divide before/after summing doesn't matter mathematically or numerically; divisor is a power of 2
    95 0000005D C3                     ret

    96 0000005E 5E000000           .size:      dd $ - meanmean_float_avx
       0x5e = 94 bytes

```

(NASM listing created with `nasm -felf64 mean-mean.asm -l/dev/stdout | cut -b -34,$((34+6))-`. Strip the listing part and recover the source with `cut -b 34- > mean-mean.asm`)

SIMD horizontal sum and divide by 4 (i.e. arithmetic mean) is implemented in a separate function that we `call` (with a function pointer to amortize the cost of the address). With `4/x` before/after, or `x^2` before and sqrt after, we get the harmonic mean and quadratic mean. (It was painful to write these `div` instructions instead of multiplying by an exactly-representable `0.25`.)

Geometric mean is implemented separately with multiply and chained sqrt. Or with one sqrt first to reduce exponent magnitude and maybe help numerical precision. log is not available, only `floor(log2(x))` via AVX512 `vgetexpps/pd`. Exp is sort of available via AVX512ER (Xeon Phi only), but with only 2^-23 precision.

Mixing 128-bit AVX instructions and legacy SSE is not a performance problem. Mixing 256-bit AVX with legacy SSE can be on Haswell, but on Skylake it just potentially creates a potential false dependency for SSE instructions. I think my `double` version avoids any unnecessary loop-carried dep chains, and bottlenecks on div/sqrt latency/throughput.

**Double version:**

```
   108                             global meanmean_double_avx
   109                             meanmean_double_avx:
   110 00000080 B9[E8000000]           mov      ecx, .arith_mean
   111 00000085 C4E27D1961F8           vbroadcastsd  ymm4, [rcx-8]    ; float 4.0
   112
   113                                 ;; mean(a,b) = mean(a,b,a,b) for all 4 types of mean
   114                                 ;; so we only ever have to do the length=4 case
   115 0000008B C4E37D18C001           vinsertf128   ymm0, ymm0, xmm0, 1       ; [b,a] => [b,a,b,a]
   116
   117                             .loop:
   118                             ;;; XMM3 = geometric mean: not based on addition.
   119 00000091 C5FD51D8               vsqrtpd      ymm3, ymm0     ; sqrt first to get magnitude closer to 1.0 for better(?) numerical precision
   120 00000095 C4E37D19DD01           vextractf128 xmm5, ymm3, 1           ; extract high lane
   121 0000009B C5D159EB               vmulpd       xmm5, xmm3
   122 0000009F 0F12DD                 movhlps      xmm3, xmm5              ; extract high half
   123 000000A2 F20F59DD               mulsd        xmm3, xmm5              ; xmm3 = hproduct(sqrt(xmm0))
   124                                ; sqrtsd       xmm3, xmm3             ; xmm3 = 4th root = geomean(xmm0)   ;deferred until quadratic
   125
   126                             ;;; XMM2 = quadratic mean = max of the means
   127 000000A6 C5FD59E8               vmulpd   ymm5, ymm0,ymm0
   128 000000AA FFD1                   call     rcx                ; arith mean of squares
   129 000000AC 0F16EB                 movlhps  xmm5, xmm3         ; [quad^2, geo^2]
   130 000000AF 660F51D5               sqrtpd   xmm2, xmm5         ; [quad  , geo]
   131
   132                             ;;; XMM1 = harmonic mean = min of the means
   133 000000B3 C5DD5EE8               vdivpd   ymm5, ymm4, ymm0    ; 4/x
   134 000000B7 FFD1                   call     rcx                 ; arithmetic mean under inversion
   135 000000B9 C5DB5ECD               vdivsd   xmm1, xmm4, xmm5    ; 4/.  (the factor of 4 cancels out)
   136
   137                             ;;; XMM5 = arithmetic mean
   138 000000BD C5FC28E8               vmovaps  ymm5, ymm0
   139 000000C1 FFD1                   call     rcx
   140
   141 000000C3 0F16E9                 movlhps     xmm5, xmm1            ;     [arith, harm]
   142 000000C6 C4E35518C201           vinsertf128 ymm0, ymm5, xmm2, 1   ; x = [arith, harm, quad, geo]
   143
   144 000000CC C5EB5CD1               vsubsd   xmm2, xmm1               ; largest - smallest mean: guaranteed non-negative
   145 000000D0 660F2E51F0             ucomisd  xmm2, [rcx-16]           ; quad - harm > threshold
   146 000000D5 77BA                   ja      .loop
   147
   148                                 ; vzeroupper ; not needed for correctness, only performance
   149                                 ; return with the arithmetic mean in the low element of xmm0 = scalar return value
   150 000000D7 C3                     ret
   151
   152                             ; "literal pool" between the function
   153 000000D8 95D626E80B2E113E   .fpconst_threshold:   dq 1e-9
   154 000000E0 0000000000001040   .fpconst_4:    dq 4.0            ; TODO: golf these zeros?  vpbroadcastb and convert?
   155                             .arith_mean:                     ; returns YMM5 = hsum(ymm5)/4.
   156 000000E8 C4E37D19EF01           vextractf128 xmm7, ymm5, 1
   157 000000EE C5D158EF               vaddpd       xmm5, xmm7
   158 000000F2 C5D17CED               vhaddpd      xmm5, xmm5      ; slow but small
   159 000000F6 C5D35EEC               vdivsd     xmm5, xmm4        ; only low element matters
   160 000000FA C3                     ret

   161 000000FB 7B000000           .size:      dd $ - meanmean_double_avx

    0x7b = 123 bytes

```

---

## C test harness

```
#include <immintrin.h>
#include <stdio.h>
#include <math.h>

static const struct ab_avg {
    double a,b;
    double mean;
} testcases[] = {
    {1, 1, 1},
    {1, 2, 1.45568889},
    {100, 200, 145.568889},
    {2.71, 3.14, 2.92103713},
    {0.57, 1.78, 1.0848205},
    {1.61, 2.41, 1.98965438},
    {0.01, 100, 6.7483058},
};

// see asm comments for order of  arith, harm, quad, geo
__m128 meanmean_float_avx(__m128);       // or float ...
__m256d meanmean_double_avx(__m128d);    // or double ...
int main(void) {
    int len = sizeof(testcases) / sizeof(testcases[0]);
    for(int i=0 ; i<len ; i++) {
        const struct ab_avg *p = &testcases[i];
#if 1
        __m128 arg = _mm_set_ps(0,0, p->b, p->a);
        double res = meanmean_float_avx(arg)[0];
#else
        __m128d arg = _mm_loadu_pd(&p->a);
        double res = meanmean_double_avx(arg)[0];
#endif
        double allowed_diff = (p->b - p->a) / 100000.0;
        double delta = fabs(p->mean - res);
        if (delta > 1e-3 || delta > allowed_diff) {
            printf("%f %f => %.9f but we got %.9f.  delta = %g allowed=%g\n",
                   p->a, p->b, p->mean, res, p->mean - res, allowed_diff);
        }
    }

    while(1) {
        double a = drand48(), b = drand48();  // range= [0..1)
        if (a>b) {
            double tmp=a;
            a=b;
            b=tmp; // sorted
        }
//      a *= 0.00000001;
//      b *= 123156;
        // a += 1<<11;  b += (1<<12)+1;  // float version gets stuck inflooping on 2048.04, 4097.18 at fpthreshold = 4e-5

        // a *= 1<<11 ; b *= 1<<11;   // scaling to large magnitude makes sum of squares loses more precision
        //a += 1<<11; b+= 1<<11;   // adding to large magnitude is hard for everything, catastrophic cancellation
#if 1
        printf("testing float %g, %g\n", a, b);
        __m128 arg = _mm_set_ps(0,0, b, a);
        __m128 res = meanmean_float_avx(arg);
        double quad = res[2], harm = res[1];  // same order as double... for now
#else
        printf("testing double %g, %g\n", a, b);
        __m128d arg = _mm_set_pd(b, a);
        __m256d res = meanmean_double_avx(arg);
        double quad = res[2], harm = res[1];
#endif
        double delta = fabs(quad - harm);
        double allowed_diff = (b - a) / 100000.0; // calculated in double even for the float case.
        // TODO: use the double res as a reference for float res
        // instead of just checking quadratic vs. harmonic mean

        if (delta > 1e-3 || delta > allowed_diff) {
            printf("%g %g we got q=%g, h=%g, a=%g.  delta = %g,  allowed=%g\n",
                   a, b, quad, harm, res[0], quad-harm, allowed_diff);
        }
    }

}

```

Build with:

```
nasm -felf64 mean-mean.asm &&
gcc -no-pie -fno-pie -g -O2 -march=native mean-mean.c mean-mean.o

```

Obviously you need a CPU with AVX support, or an emulator like Intel SDE. To compile on a host without native AVX support, use `-march=sandybridge` or `-mavx`

Run: passes the hard-coded test cases, but for the float version, random test cases often fail the `(b-a)/10000` threshold set in the question.

```
$ ./a.out
 (note: empty output before the first "testing float" means clean pass on the constant test cases)
testing float 3.90799e-14, 0.000985395
3.90799e-14 0.000985395 we got q=3.20062e-10, h=3.58723e-05, a=2.50934e-05.  delta = -3.5872e-05,  allowed=9.85395e-09
testing float 0.041631, 0.176643
testing float 0.0913306, 0.364602
testing float 0.0922976, 0.487217
testing float 0.454433, 0.52675
0.454433 0.52675 we got q=0.48992, h=0.489927, a=0.489925.  delta = -6.79493e-06,  allowed=7.23169e-07
testing float 0.233178, 0.831292
testing float 0.56806, 0.931731
testing float 0.0508319, 0.556094
testing float 0.0189148, 0.767051
0.0189148 0.767051 we got q=0.210471, h=0.210484, a=0.21048.  delta = -1.37389e-05,  allowed=7.48136e-06
testing float 0.25236, 0.298197
0.25236 0.298197 we got q=0.274796, h=0.274803, a=0.274801.  delta = -6.19888e-06,  allowed=4.58374e-07
testing float 0.531557, 0.875981
testing float 0.515431, 0.920261
testing float 0.18842, 0.810429
testing float 0.570614, 0.886314
testing float 0.0767746, 0.815274
testing float 0.118352, 0.984891
0.118352 0.984891 we got q=0.427845, h=0.427872, a=0.427863.  delta = -2.66135e-05,  allowed=8.66539e-06
testing float 0.784484, 0.893906
0.784484 0.893906 we got q=0.838297, h=0.838304, a=0.838302.  delta = -7.09295e-06,  allowed=1.09422e-06

```

FP errors are enough that quad-harm comes out less than zero for some inputs.

Or with `a += 1<<11; b += (1<<12)+1;` uncommented:

```
testing float 2048, 4097
testing float 2048.04, 4097.18
^C  (stuck in an infinite loop).

```

**None of these problems happen with `double`.** Comment out the `printf` before each test to see that the output is empty (nothing from the `if(delta too high)` block).

TODO: use the `double` version as a reference for the `float` version, instead of just looking at how they converging with quad-harm.
> 2 votes

# Answer
# Python 3, 152 bytes

```
from math import*
s=sum
def f(*a):l=len(a);return 2>len({*a})and{*a}or f(s(a)/l,l/s(map(pow,a,l*[-1])),exp(s(map(log,a))/l),(s(map(pow,a,l*[2]))/l)**.5)

```

Try it online!

Recursive function `f`, will converge to floating point precision. Works in principle for all lists of positive numbers of *any* size, but is limited by ~~Python's recursion limit~~ a rounding error for some test cases.

---

Alternatively, settling for 9 decimals precision:

# Python 3, 169 bytes

```
from math import*
s=sum
def f(*a):l=len(a);return(2>len({round(i,9)for i in a}))*a[0]or f(s(a)/l,l/s(map(pow,a,l*[-1])),exp(s(map(log,a))/l),(s(map(pow,a,l*[2]))/l)**.5)

```

Try it online!
> 2 votes

# Answer
# C#, 173 bytes

```
double m(int n,params double[]a)=>(n<1?a[0]:m(n-1,a.Sum()/a.Length,Math.Pow(a.Aggregate((t,x)=>t*x),1.0/a.Length),a.Length/a.Sum(x=>1/x),Math.Sqrt(a.Sum(x=>x*x)/a.Length)));

```

Try it online!
> 1 votes

# Answer
# C# (Visual C# Interactive Compiler), 177 bytes

```
double f(double[]g)=>g.All(c=>Math.Abs(c-g[0])<1e-9)?g[0]:f(new[]{g.Sum()/(z=g.Length),Math.Pow(g.Aggregate((a,b)=>a*b),1d/z),z/g.Sum(x=>1/x),Math.Sqrt(g.Sum(x=>x*x)/z)});int z;

```

Thanks to @KevinCruijjsen for pointing out that using floating point precision was causing problems! Would be 163 bytes if doubles were perfectly precise.

Try it online!
> 1 votes

# Answer
# Japt v2.0a0 `-g`, ~~42~~ 38 bytes

```
â ÊÉ?ß[Ux²÷(V=UÊ)¬Ux÷V U×qV V÷Ux!÷1]:U

```

There's got to be a shorter way... This is a monstrosity! Saved 4 bytes thanks to @Shaggy!

Try it
> 1 votes

# Answer
# Clean, 124 bytes

```
import StdEnv
f=avg o limit o iterate\l=let n=toReal(length l)in[avg l,prod l^(1.0/n),n/sum[1.0/x\\x<-l],avg[x*x\\x<-l]^0.5]

```

Try it online!

Performs the operation until the result stops changing.

Hurray for limited precision floating point!
> 1 votes

# Answer
# Pyth, 32 bytes

```
h.Wt{H[.OZ@*FZJlZcJscL1Z@.O^R2Z2

```

Try it online here, or verify all the test cases (bar two, see note below) at once here. Accepts input as a list.

There seem to be some issues with rounding, as certain inputs don't converge correctly when they otherwise should. In particular, test case `0.01 100` gets stuck at values `[6.748305820749738, 6.748305820749738, 6.748305820749739, 6.748305820749738]`, and test case `1.61 2.41` gets stuck at `[1.9896543776640825, 1.9896543776640825, 1.9896543776640827, 1.9896543776640825]` \- note in both cases that the 3rd mean (harmonic mean) differs from the others.

I'm not sure if this problem invalidates my entry, but I'm posting it anyway as it *should* work. If this isn't acceptable, it can be fixed by instering `.RRT` before the `[`, to round each of the means to 10 decimal places, as seen in this test suite.

```
h.Wt{H[.OZ@*FZJlZcJscL1Z@.O^R2Z2)Q   Implicit: Q=eval(input())
                                     Trailing )Q inferred
 .W                              Q   Funcitonal while: While condition is true, call inner. Starting value Q
   t{H                               Condition function: current input H
    {H                                 Deduplicate H
   t                                   Discard first value
                                         Empty list is falsey, so while is terminated when means converge
      [.OZ@*FZJlZcJscL1Z@.O^R2Z2)    Inner function: current input Z
              JlZ                      Take length of Z, store in J
       .OZ                             (1) Arithmetic mean of Z
           *FZ                         Product of Z
          @   J                        (2) Jth root of the above
                     L Z               Map each element of Z...
                    c 1                ... to its reciprocal
                   s                   Sum the above
                 cJ                    (3) J / the above
                            R Z        Map each element of Z...
                           ^ 2         ... to its square
                         .O            Arithmetic mean of the above
                        @      2       (4) Square root of the above
      [                         )      Wrap results (1), (2), (3), and (4) in a list
                                         This is used as the input for the next iteration of the loop
h                                    Take the first element of the result, implicit print

```
> 1 votes

# Answer
# Javascript - 186 bytes

Takes input as an array of numbers. Uses the mean transformations in J42161217's answer to shorten the code.

Try It Online

```
f=(v,l=[m=(w,k=0)=>w.map(x=>k+=x)&&k/w.length,w=>1/m(w.map(x=>1/x)),w=>Math.E**m(w.map(x=>Math.log(x))),w=>m(w.map(x=>x**2))**.5].map(x=>x(v)).sort((a,b)=>a-b))=>l[3]-l[0]>1e-5?f(l):l[0]

```

## Explanation

```
f = (
  v,
  l=[
    m=(w,k=0)=>w.map(x=>k+=x)&&k/w.length,  // m = w => arithmetic mean of values in w
    w=>1/m(w.map(x=>1/x)),                  // w => harmonic mean of values in w
    w=>Math.E**m(w.map(x=>Math.log(x))),    // w => geometric mean of values in w
    w=>m(w.map(x=>x**2))**.5                // w => quadratic mean of values in w
  ].map(x=>x(v))                            // get array of each mean using input v, stored in l
  .sort((a,b)=>a-b)                         // sort the outputs
) =>
  l[3] - l[0] > 1e-5 ?                      // is the difference between the largest
                                            // and smallest means > 1/100000?
    f(l) :                                  // if yes, get the mean mean of the means
    l[0]                                    // if no, arbitrarily return the smallest value
                                            // as close enough

```
> 1 votes

# Answer
# Perl 5, ~~92~~ 72 bytes

```
sub f{@_=map{$m=$_;sum(map$_**$m/@_,@_)**(1/$m)}1,1e-9,-1,2for 1..9;pop}

```

Try it online!

...using some dirty tricks.
> 0 votes

# Answer
# SNOBOL4 (CSNOBOL4), 296 bytes

```
	X =INPUT
	Y =INPUT
	A =(X + Y) / 2.
	P =X * Y
	G =P ^ 0.5
	H =P / A
	Q =(2 * (A ^ 2) - P) ^ 0.5
O	OUTPUT =EQ(Q,A) Q	:S(END)
	M =A
	N =G
	O =H
	P =Q
	A =(M + N + O + P) / 4
	G =(M * N * O * P) ^ 0.25
	H =4 / (1 / M + 1 / N + 1 / O + 1 / P)
	Q =((M ^ 2 + N ^ 2 + O ^ 2 + P ^ 2) / 4) ^ 0.5	:(O)
END

```

Try it online!

Straightforward implementation. Uses a trick from my answer to a related question to golf a bit more.
> 0 votes

# Answer
# Sledgehammer, 15 bytes

so I just posted the winning answer to my own question

```
⡈⠀⣐⢕⠠⢵⠂⡒⡓⠄⠬⢔⣲⣔⢯

```

Take input as a list of two (or more) machine precision integers. Mathematica has all the built-ins you could need for this challenge!

* `FixedPoint` for iterating until done
* `Mean`, `HarmonicMean`, `GeometricMean` and `RootMeanSquare` are the built-ins for all four means necessary

Corresponding Mathematica code:

```
First@FixedPoint[{Mean@#,HarmonicMean@#,GeometricMean@#,RootMeanSquare@#}&,#]&

```

(golfing in Sledgehammer is noticeably different from golfing in Mathematica; replacing the means with shorter expressions is unlikely to help here, although I haven't actually tried)
> 0 votes

# Answer
# Factor, 101 bytes

```
[ [ { mean geometric-mean harmonic-mean quadratic-mean } [ execute ] with map ] to-fixed-point last ]

```

Attempt This Online!
> 0 votes

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


title: Can the  visit all the ?

text:
# Question
Title: Can the  visit all the ?
In this challenge you will be simulating a frog jumping from lily-pad to lily-pad in a pond. A frog's jump distance is uniquely determined by the size of the lily pad it jumps from. So for example there are lily-pads that let a frog jump `1` unit, lily-pads that let a frog jump `2` units etc. A frog can never jump more or less than the allowed amount, nor can it jump out of the pond, but it can jump in either direction.

So we will represent a lily-pad by the number of units it allows a frog to jump. This number is always positive. We will then represent a pond as a list of lily-pads.

Our question is then: If a frog starts on the first lily-pad can they visit every lily-pad in the pond by following the jumping rules?

For example if we have the following pond the answer is yes

```
[2, 3, 1, 4, 1]

[2, 3, 1, 4, 1]

[2, 3, 1, 4, 1]

[2, 3, 1, 4, 1]

[2, 3, 1, 4, 1]

```

However for the following pond the answer is no:

```
[3,2,1,2,1,2]

```

The frog can never reach any lily-pad labeled with a 1.

The frog is allowed to visit the same lily-pad more than once. The following example requires it:

```
[2, 1, 1, 1]

[2, 1, 1, 1]

[2, 1, 1, 1]

[2, 1, 1, 1]

[2, 1, 1, 1]

```

Some lily-pads are dead ends and need to be visited last for example:

```
[2,3,1,1]

```

Here there is nowhere to go from `3` so that has to be the final pad.

## Task

For this task you will take as input a non-empty list of positive integers. You should output one of two distinct values, the first if it a frog can reach every lily-pad the second if not.

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

## Test cases

### Possible

```
[10]
[2,1,1,1]
[3,1,4,2,2,1]
[6,1,1,1,1,1,3]
[2,3,1,1]
[2,2,1,2]
[8,9,1,5,2,5,1,7,4]

```

### Impossible

```
[2,1]
[3,2,1,2,1,2]
[3,2,2,2,2,2]
[3,4,1,2,1,1]
[2,9,1,9]
[3,3,3,1,3,3]

```

# Answer
# Python3, 151 bytes:

```
f=lambda n,s=[0],p=[]:len({*s})==len(n)or any(f(n,s+[t],p+[j])for i in[n[s[-1]],-1*n[s[-1]]]if-1<(t:=(s[-1]+i))<len(n)and p.count(j:=(s[-1],t))<len(n))

```

Try it online!
> 7 votes

# Answer
# JavaScript (ES6), 83 bytes

Returns \\$0\\$ or \\$1\\$.

Given a list of \\$N\\$ entries, this recursively tries all possible paths where each lily-pad may be visited up to \\$N\\$ times.

```
f=(a,i=0,[...b]=a.map(_=>0))=>b.every(v=>v)||a[b[i]++]&&f(a,i+a[i],b)|f(a,i-a[i],b)

```

Try it online!

Or **81 bytes** for this slower version suggested by @tsh:

```
f=(a,i=0,[...b]=a.map(_=>0))=>a[b[i]++]?f(a,i+a[i],b)|f(a,i-a[i],b):b.every(v=>v)

```

Try it online!

### Commented

```
f = (               // f is a recursive function taking:
  a,                //   a[] = input list
  i = 0,            //   i   = current position
  [...b] =          //   b[] = a list keeping track of how many times each
    a.map(_ => 0)   //         lily-pad was visited, initially all 0's
) =>                //
b.every(v => v)     // success if all lily-pads were visited at least once
||                  // otherwise:
a[b[i]++]           //   failed if a[b[i]] is not defined (either if we've
                    //   visited this position too many times, or we're out
                    //   of bounds and b[i] itself is undefined)
                    //   if applicable, increment b[i] afterwards
&&                  // otherwise:
f(a, i + a[i], b) | //   do a recursive call where we go to the right
f(a, i - a[i], b)   //   do a recursive call where we go to the left

```
> 4 votes

# Answer
# 05AB1E, ~~40~~ 37 bytes

```
ā<©+®I-øε®Ã}.āćU©æε®«œεXšü2εR`нsθå]Pà

```

05AB1E lacks recursive methods unfortunately, so we'll have to use a brute-force approach by first generating all possible results before validating them. Unfortunately, this is both extremely slow and pretty long - although it's probably golfable here and there.

Try it online or verify some smaller test cases.

**Explanation:**

Step 1: For each Lilly-pad index, check which other Lilly-pads the frog can jump to (which will always be 0, 1, or 2 other Lilly-pads):

```
ā        # Push a list in the range [1, (implicit) input-length]
 <       # Decrease each by 1 to the range [0, length)
  ©      # Store it in variable `®` (without popping)
   +     # Add it to the input-values at the same positions
®        # Push list `®` again
 I-      # Subtract the input-list at the same positions
    ø    # Create pairs of these two lists
     ε   # Map each pair to:
      ®Ã #  Only keep the values present in list `®`, removing any out-of-bounds
         # indices that are negative or >= the length)
     }.ā # After the map: enumerate the list, pairing each list with its index

```

Try just step 1 online.

Step 2: Using the powerset and permutations builtins, create all possible lists that contain either 1 or 2 of these list-index pairs, and also start with the first Lilly-pad:

```
ć        # Extract head; pop and push remainder-list and first item separately
 U       # Pop this first item, and store it in variable `X`
 ©       # Store the remainder-list as new variable `®` (without popping)
  æ      # Pop and push the powerset of this list
ε        # Map over each powerset-list:
 ®«      #  Merge list `®` to it
   œ     #  Get all permutations of this list
    ε    #  Map over each permutation:
     Xš  #   Prepend item `X` to each

```

Try the first two steps online.

Step 3: Check if there is any inner list for which all overlapping pairs of list-index pairs are valid jumps for the frog:

```
 ü2      #   Pop the list and push its overlapping pairs
   ε     #   Map each pair to:
    R    #    Reverse the pair
     `   #    Pop and push both inner pairs separated to the stack
      н  #    Pop and and only leave the list
     s   #    Swap so the other pair is at the top of the stack
      θ  #    Pop and only leave the index
       å #    Check if this index is in the list
]        # Close all three open maps
 P       # Product to check for each inner-most list if ALL are truthy
  à      # Flattened-max to check if ANY is truthy
         # (which is output implicitly as result)

```
> 4 votes

# Answer
# Charcoal, 49 bytes

```
⊞υ⟦…¹Ｌθ⁰⟧ＦυＦΦＥθ⟦⁻§ι⁰⟦λ⟧λ⟧›⁼§θ§ι¹↔⁻λ§ι¹№υκ⊞υκ¬§⌊υ⁰

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if possible, nothing if not. Explanation:

```
⊞υ⟦…¹Ｌθ⁰⟧Ｆυ

```

Start a breadth-first search having visited the first lily pad while the remaining lily pads are unvisited.

```
ＦΦＥθ⟦⁻§ι⁰⟦λ⟧λ⟧

```

Calculate the result of jumping to each lily pad...

```
›⁼§θ§ι¹↔⁻λ§ι¹№υκ

```

... filtering out those jumps that were the wrong distance or have been seen before, ...

```
⊞υκ

```

... save the resulting position.

```
¬§⌊υ⁰

```

Check whether any of the positions have no unvisited lily pads left.
> 2 votes

# Answer
# Python 3, 96 bytes

```
f=lambda k,x=0,*s:len({*s})==len(k)or-1<x<len(k)>s.count(x)and f(k,x-k[x],x,*s)|f(k,x+k[x],x,*s)

```

Try it online!

Port of my answer to 1D Hopping Array Maze
> 2 votes

---
Tags: code-golf, array, decision-problem, graph-theory
---


title: Knit me an ASCII-Sock

text:
# Question
Title: Knit me an ASCII-Sock
## Introduction

Long story short: a few days ago I accidentally started knitting a sock and the pretty logical structure of the plain stitches lead me to the idea: Why don't we just ASCII-knit a sock?

## Input

The input is an even integer N in the range `[2,30]`.

## Output

The output is a sock, obviously.

## Structure

Because we will only use plain stitches you will only use `v` for a downward stitch and `>` for a stitch to the right. Let me explain the full structure with an example for `N=8`:

```
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvv>>>
vvvvvv>>>>>>
vvvvv>>>>>>>>>
vvvv>>>>>>>>>>>>
vvvv>>>>>>>>>>>>>>>>>>>>>>>>
vvvv>>>>>>>>>>>>>>>>>>>>>>>>>>
vvvv>>>>>>>>>>>>>>>>>>>>>>>>>>
vvvv>>>>>>>>>>>>>>>>>>>>>>>>

```
* The first block is the upper part. It has the width `N` and the height `N*1.5`
* Afterwards the heel begins. You subtract one `v` per row from the right side until you have `N/2` as width. Then you add `N/2` rows with the width `N/2` beneath to finish the downward knits. Note that it gives a total of `N/2 + 1` rows with the width `N/2`

first part:

```
vvvvvvvv    //begin with width N
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv
vvvvvvvv    // N*1.5 times
vvvvvvv     // reduce
vvvvvv
vvvvv
vvvv        // till here
vvvv        // repeat N/2 times
vvvv
vvvv
vvvv

```
* Now the side wards knits begin. You start with the first reduced row, fill `>` till you have the width `N` and add two more. Continue that process including the first row with `N/2` width
* Fill the rows beneath to that level and add `N*1.5` times `>` to that
* Let the outer parts as they are and add on the row beneath the first and over the lase two more `>'s` until it is finished

second part:

```
vvvvvvvv
vvvvvvv>>>  //fill to N and add two >
vvvvvv>>>>>>     //repeat
vvvvv>>>>>>>>>
vvvv>>>>>>>>>>>>   //till here
vvvv>>>>>>>>>>>>>>>>>>>>>>>>       //fill to the row above and add N*1.5 times >
vvvv>>>>>>>>>>>>>>>>>>>>>>>>>>     //add two more '>' than the row above
vvvv>>>>>>>>>>>>>>>>>>>>>>>>>>     //add two more '>' than the row beneath
vvvv>>>>>>>>>>>>>>>>>>>>>>>>

```

## Rules

Trailing new lines are ok.

You can choose between uppercase or lowercase `V` but it has to be consistent.

This is so the shortest code in bytes wins.

## Test cases

```
N=2
vv
vv
vv
v>>>
v>>>>>>

N=4
vvvv
vvvv
vvvv
vvvv
vvvv
vvvv
vvv>>>
vv>>>>>>
vv>>>>>>>>>>>>
vv>>>>>>>>>>>>

N=6
vvvvvv
vvvvvv
vvvvvv
vvvvvv
vvvvvv
vvvvvv
vvvvvv
vvvvvv
vvvvvv
vvvvv>>>
vvvv>>>>>>
vvv>>>>>>>>>
vvv>>>>>>>>>>>>>>>>>>
vvv>>>>>>>>>>>>>>>>>>>>
vvv>>>>>>>>>>>>>>>>>>

N=12
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvvv
vvvvvvvvvvv>>>
vvvvvvvvvv>>>>>>
vvvvvvvvv>>>>>>>>>
vvvvvvvv>>>>>>>>>>>>
vvvvvvv>>>>>>>>>>>>>>>
vvvvvv>>>>>>>>>>>>>>>>>>
vvvvvv>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
vvvvvv>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
vvvvvv>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
vvvvvv>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
vvvvvv>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
vvvvvv>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

```

# Answer
**Pyth - 93 Bytes**

```
J/Q2K"V"P*s*Q1.5+*QKbVJp*+Q_+1NK*+3*3N">";InQ2VJp*JK*+s*2aaNc-J 1 2c-J 1 2+3*Q3">";IqQ2pK*6">

```

Explanation:

```
J/Q2                             sets J to half of input
K"V"                             sets K to "V"
P                                prevents newline after main block of sock
*                                multiply the next 2 items
s*Q1.5                           rounds up input*1.5 (columns in main block)
+                                adds the next 2 item (this item gets multiplied by the previous item)
*QK                              multiplies "V" by input (resulting in each row)
b                                New line
VJ                               For all the numbers 0-((Q/2)-1) (as represented by N)
p                                print
*                                multiply the next 2 items
+Q_+1N                           input + -1*(1+N)
K                                "V"
*+3*3N">"                        3N+3 many ">"'s
;                                ends for statement
InQ2                             if input is not 2
VJ                               For all the numbers 0-((input/2)-1) (as represented by N)
p                                print
*JK                              input/2 many ">"'s
*+s*2aaNc-J 1 2c-J 1 2+3*Q3">"   int(abs(abs(N-((input/2)-1)/2)-((input/2)-1)/2)))+(input*3)+3 many ">"'s
;                                end of for statement
IqQ2                             if input is 2
pK*6">                           print "V" and 6 ">"'s

```

You can try it here!
> 2 votes

# Answer
# Vyxal, 54 bytes

```
1.*(\v*,)½(n-\v*₴n:d+\>*,)½½ʁ(½\v*?T\>*Jnd\>*J:⅛,)¾(¼,

```

Boy oh boy, this is my new favorite answer now.
The satisfaction when I got it down from 79 bytes to 54 bytes was immense.
I bet you can't golf this anymore.
Try it Online!

## Explanation

```
1.*(\v*,)½(n-\v*₴n:d+\>*,)½½ʁ(½\v*?T\>*Jnd\>*J:⅛,)¾(¼,

1.*(\v*,)     <Top part>
1.            Evaluates to 1.5
  *           Times input i
   (    )     Loop (with loop var n)
    \v*,      Repeat "v" n times and print it

½(n-\v*₴n:d+\>*,)     <Diagonal part>
½                     Halve input i
 (              )     Loop (with loop var n)
  n-\v*₴              Repeat "v" i minus n times and print it (without a newline)
        n:d           Duplicate n and double it
           +\>*,      Repeat ">" 2n plus n times

½½ʁ(½\v*?3*\>*Jnd\>*J:⅛,)     <Top half bumpy part>
½½ʁ                           Create range 0 to input i/4
   (                    )     Loop
    ½\v*                      Repeat "v" i/2 times
        ?T\>*J                Repeat ">" 3i times and join it
               nd\>*J:        Repeat ">" 2n times, merge and duplicate it
                      ⅛,      Push it to the global array and print it

¾(¼,                          <Bottom half bumpy part>
¾(                            Loop through the length of the global array
  ¼,                          Pop from the global array (to reverse it)

```
> 4 votes

# Answer
# Mathematica, 104 bytes

```
""<>{t=Table;c=t[{"v"~t~#,">"~t~#2,"
"},#3]&;h=#/2;c[#,0,3h],c[#-i,3i,z={i,h}],c[h,6h+2Min[i-1,h-i],z]}&

```

Unnamed function taking a positive even integer as input and returning a string (with a trailing newline). Note that the newline between the two lines of code above is part of the code. The main work is done by the function `c`, whose ungolfed definition

```
c[#1, #2, #3] = Table[{Table["v", #1], Table[">", #2], "\n"}, #3]

```

creates a table of lists, each one consisting of several `"v"`s in a row followed by several `">"`s followed by a newline. Fortunately, the range `#3` for the outer `Table` can have a variable name, which can be referred to in the expressions `#1` and `#2`; this allows the function `c` to be called with both constant and variable arguments. The rest is just computation, and the string-joining operator `""<>` flattens the nested lists that arise for free.
> 2 votes

# Answer
## Python, 3.5 ~~183~~ 177 bytes

```
n=int(input())
h=n//2
z=h%2
l=['v'*h+'>'*(2*n-h+3*h+i*2)for i in range(1*z+n//4)]
*map(print,['v'*n]*(3*h)+['v'*i+'>'*(3*(n-i))for i in range(h,n)][::-1]+[l,l[:-1]][z]+l[::-1]),

```

*Explanation incoming.*

Try it Online!
> 2 votes

# Answer
## Groovy, 168 bytes

```
{n->h=n/2;z=(int)h%2;l=(0..<1*z+n/4).collect{'v'*h+'>'*(2*n-h+3*h+it*2)};(['v'*n]*(3*h)+(n-1..h).collect{'v'*it+'>'*(3*(n-it))}+(z==0?l:l[0..<-1])+l[-1..0]).join('\n')}

```

This is an unnamed closure. The approach is completely similar to my Python 3.5 answer.

Try it Online!
> 1 votes

# Answer
## Batch, 279 bytes

```
@echo off
set i=for /l %%i in (2,2,%1)do
set v=
%i%call set v=v%%v%%v
%i%echo %v%&echo %v%&echo %v%
%i%call:a
%i%call set v=%%v%%]]]
%i:,2,=,4,%call:c&if %%i lss %1 call set v=%%v%%]]
%i:2,=4,%call:b
exit/b
:a
set v=%v:~1%]]]]]
:b
set v=%v:~0,-2%
:c
echo %v:]=^>%

```

Note: the second line ends in a space. Batch has problems with echoing `>`s in variables so I have to a) use a substitute b) call a subroutine to echo the corrected string. In fact I have three subroutines:

* `a` is used for the heel. One `v` is removed each time and three `>`s are added. Two extra `>`s are added so that the subroutine can fall through into the `b` subroutine.
* `b` is used for the bottom of the foot. Two `>`s are removed each time. The subroutine then falls through into the `c` subroutine.
* `c` prints the current row of the sock, replacing the placeholder character so that the `>`s print properly.

The fourth line handles the width of the leg while the fifth line handles its length. The seventh line handles the length of the foot while the eighth line handles the top half of the foot height by adding two `>>` to each line after printing it. This works for sock sizes that are multiples of 4, and an adjustment is made for other sock sizes so that the longest line does not get repeated.
> 1 votes

# Answer
# dc, 269 bytes

```
1k?d1.5*sadsdsb[[[v]nlb1-dsb0<f]dsfx[]pldsbla1-dsa0<c]dscxldd1-sisb2su[[[v]nlb1-dsbldli-<g]dsgx[[>]nlb1-dsblu+0<t]dstx[]plu2+suli1-dsilddsb2/!>m]dsmxld3*dsdsolidswst[[[v]nlw1-dsw0!>x]dsxx[2-]sa[2+]sy[[>]nlo1-dso0<g]dsgxldltli1+2/<yltli1+2/>adsdsolisw[]plt1-dst0!>f]dsfx

```

All right, well...this is *massive*. It wasn't easy, I'll tell you that much, what with all the register references, comparisons, macros, lack of string manipulation abilities, etc. Nonetheless, I had fun putting this together, and that's all that really matters, right? ;)

Try It Online!
> 1 votes

# Answer
# C (gcc), 185 bytes

```
#define L for(i=0;i<h;i++,p(10,1))
p(c,n){n&&putchar(--n?p(c,n):c);}
f(n,i,k,h){h=n/2;for(k=3;k--;)L p(118,n);L{p(118,n-i-1);p(62,3*i+3);}L{p(118,h);p(62,3*n);p(62,2*(4*i/n?h-i-1:i));}}

```

Try it online!

Mostly boring, except I use a recursive function to print repeated characters.
> 1 votes

# Answer
# PHP, 229 bytes

a quite lazy approach

```
for($m=$n=$p=$argv[1];$i++<$q=$n*1.5;)echo($d=str_pad)("
",$n+1,v);for(;$p-->$n/2;)echo$s="
".$d($d("",$p,v),$m+=2,">");$r=[$s.=$d("",$q,">")];for($k=$n>>2;--$k;)$r[]=$s.=">>";echo join($r),$n&2?"$s>>":"",join(array_reverse($r));

```

prints a leading newline. Run with `-nr`.

**breakdown**

```
// print first part + preparing some variables for later
for($m=$n=$p=$argv[1];$i++<$q=$n*1.5;)echo str_pad("\n",$n+1,v);

// print second part + prepare $s for third part
for(;$p-->$n/2;)echo$s="\n".str_pad(str_pad("",$p,v),$m+=2,">");

// third part: create an array of strings ...
$r=[$s.=str_pad("",$q,">")];
for($k=$n>>2;--$k;)$r[]=$s.=">>";
// ... then print it and its reverse
echo join($r),$n&2?"$s>>":"",join(array_reverse($r));

```
> 0 votes

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


title: We love our weird puzzles, us Brits

text:
# Question
Title: We love our weird puzzles, us Brits
In a few British newspapers there is a game known as Hidato. It is somewhat similar to Sudoku, albeit instead of having 1-9 in a line and block, it's about placing numbers such that they connect in order from `01` all the way up to the highest one, so they are all touching **horizontally, diagonally or vertically**.

Inputs will contain multiple lines separated by `\n`, containing blocks separated by a space, which you can assume to be two characters wide. Each block will be a number, a blank space to be filled (indicated by `--`), or a wall that cannot have numbers in (`XX`).

Your output should match the provided one albeit with empty blocks provided with numbers. **Note that there may not be a unique, or even the existence of, a solution** – some may yield multiple due to their ambiguity, much like Sudoku, and some may be literally unsolvable, in which case you should give a falsey output, but you can assume inputs are formatted as below.

Use a standard header `Language: XX bytes`. Happy golfing!

## Examples

Inputs `01 XX 03`, `01 -- 04`, `01 --`, etc should all return something falsey.

Input:

```
01 -- --
-- XX 05

```

Output:

```
01 03 04
02 XX 05

```

Input:

```
-- 33 35 -- -- XX XX XX
-- -- 24 22 -- XX XX XX
-- -- -- 21 -- -- XX XX
-- 26 -- 13 40 11 XX XX
27 -- -- -- 09 -- 01 XX
XX XX -- -- 18 -- -- XX
XX XX XX XX -- 07 -- --
XX XX XX XX XX XX 05 --

```

Output:

```
32 33 35 36 37 XX XX XX
31 34 24 22 38 XX XX XX
30 25 23 21 12 39 XX XX
29 26 20 13 40 11 XX XX
27 28 14 19 09 10 01 XX
XX XX 15 16 18 08 02 XX
XX XX XX XX 17 07 06 03
XX XX XX XX XX XX 05 04

```

Input:

```
XX XX XX XX -- 53 XX XX XX XX
XX XX XX XX -- -- XX XX XX XX
XX XX 56 -- -- -- 30 -- XX XX
XX XX -- -- -- -- -- -- XX XX
XX -- -- 20 22 -- -- -- -- XX
XX 13 -- 23 47 -- 41 -- 34 XX
-- -- 11 18 -- -- -- 42 35 37
-- -- -- -- 05 03 01 -- -- --
XX XX XX XX -- -- XX XX XX XX
XX XX XX XX 07 -- XX XX XX XX

```

Output:

```
XX XX XX XX 52 53 XX XX XX XX
XX XX XX XX 54 51 XX XX XX XX
XX XX 56 55 28 50 30 31 XX XX
XX XX 26 27 21 29 49 32 XX XX
XX 25 24 20 22 48 45 44 33 XX
XX 13 19 23 47 46 41 43 34 XX
14 12 11 18 04 02 40 42 35 37
15 16 17 10 05 03 01 39 38 36
XX XX XX XX 09 06 XX XX XX XX
XX XX XX XX 07 08 XX XX XX XX

```

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

This is a brute-force solution, it starts at `01` and checks every neighbouring cell checking for empty cells (`--`) or the desired number and following the path to completion or impossibility. If the desired number exists and isn't a neighbour it shortcuts this solution. Takes a few seconds for the largest grid.

This probably isn't particularly interesting, but I thought I'd try my hand at making a solution before looking at the answers linked on Rosetta Code and I enjoyed tackling a slightly more difficult challenge!

Finds all solutions when many exist. The body is a function that accepts a two dimensional array and the footer processes the input to the desired format, and returns the result to the desired format too. Happy to provide more information (and a less golfed implementation if there's interest).

```
f=a=>{F=(D,n,j)=>[Z=[].concat(...D),z=Z.indexOf(j),z>-1&&[x=z%w,y=z/w|0],z>-1&&[[x-1,y-1],[x,y-1],[x+1,y-1],[x-1,y],[x+1,y],[x-1,y+1],[x,y+1],[x+1,y+1]]][n];C=q=>q.map(Q=>Q.slice());w=a[0][L='length'];l=F(a,0).filter(c=>c!='XX')[L];R=[];r=(s,d)=>{let n=`0${+s+1}`.slice(-2);N=F(d,2,n);n>l?R.push(C(d)):~F(d,1,s)?(p=F(d,3,s),p.filter(P=>P==N+'')[L]?r(n,C(d)):!~F(d,1,n)?p.map(I=>{[x,y]=I,(x<0||x>w-1||y<0||y>d[L]-1)||d[y][x]=='--'&&(D=C(d),r(D[y][x]=n,D))}):0):0};r('01',a);return R}

```

Try it online!
> 2 votes

# Answer
# Python3, 860 bytes:

```
R=range
S=lambda x,y:[(X,Y)for X in R(x)for Y in R(y)]
def O(b,x,y,X,Y):
 for A,B in[(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]:
  if-1<(j:=x+A)<X and-1<(k:=y+B)<Y and b[j][k]!='XX':yield(j,k,b[j][k])
def f(b):
 b=[[int(j)if j.isdigit()else j for j in i.split()]for i in b.split('\n')]
 k=S(*(I:=(len(b),len(b[0]))))
 if len(d:=[(x,y)for x,y in k if type(b[x][y])==int])==1:return
 s,e=min(d,key=(_:=lambda x:b[x[0]][x[1]])),max(d,key=_)
 q,a=[(s,{(x,y)for x,y in k if b[x][y]=='--'},b)],[]
 D=[b[x][y]for x,y in d]
 while q:
  (X,Y),W,B=q.pop(0)
  if(X,Y)==e and W==set():return'\n'.join(' '.join(str(j).zfill(2)for j in i)for i in B)
  T=[]
  for x,y,C in O(B,X,Y,*I):
   if C==B[X][Y]+1:q+=[((x,y),W,B)];T=[];break
   if'--'==C and B[X][Y]+1 not in D:
    U=eval(str(B));U[x][y]=B[X][Y]+1
    if U not in a:T+=[((x,y),W-{(x,y)},U)];a+=[U]
  q+=T

```

Try it online!
> 0 votes

---
Tags: code-golf, puzzle-solver
---


title: Put the Hat On the Cat

text:
# Question
Title: Put the Hat On the Cat
Inspired by the upcoming winter bash event

### Objective

Add a hat `^`,`´` or ``` to a single vowel in each word of the input.

### Rules

* The `hat` and the `vowel` must be chosen at random. Each hat has to appear with the same probability (33%) and the vowels must have the same probability within the valid vowels in the word (if the word have 2 valid vowels each must be 50% likely to be chosen) - or the closest that your language has.
* Only `AEIOUaeiou`are considered vowels (sorry `y`)
* Vowels with hats in the input DO NOT interfere with the rules (you can consider it as a consonant)
* If the input has no vowel it won't be modified
* Capitalization must be preserved.

### Examples

`winter` \> `wintér`
`bash` \> `bâsh`
`rhythm` \> `rhythm`
`rng ftw` \> `rng ftw`
`cat in the hat` \> `cât ìn thê hát`
`dès` \> `dès`
`tschüss` \> `tschüss`
`principî` \> `prìncipî`
`PROGRAMMING PUZZLES & code golf` \> `PROGRÂMMING PÚZZLES & codé gòlf`

### Winning

This is so the shortest code wins

# Answer
# Perl 6, 101 bytes

```
~*.words.map: {(my$p=m:ex:i/<[aeiou]>/».to.pick)~~Mu:D??~S/.**{$p}<(/{("\x300".."\x302").pick}/!!$_}

```

Try it

## Expanded:

```
~      # stringify (join with spaces)
*\     # Whatever lambda (input parameter)
.words # split into words

.map:  # for each word

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

    my $p =

    m
    :exhaustive               # all possible matches
    :ignorecase
    /<[aeiou]>/\              # match a vowel

    ».to.pick                 # pick one of the positions

  ) ~~ Mu:D                   # is it defined ( shorter than ｢.defined｣ )

  ??                          # if ｢$p｣ is defined

    ~                         # stringify

    S/
      . ** {$p}               # match ｢$p｣ positions

      <(                      # ignore them
    /{
      ("\x300".."\x302").pick # pick one of the "hats" to add
    }/

  !!                          # if ｢$p｣ is not defined
    $_                        # return the word unchanged
}

```
> 2 votes

# Answer
# Vyxal `S`, 27 bytes

```
⌈:ƛAT:[℅|u];Zƛ÷›[nt3℅767+CṀ

```

Try it Online!

The result of my older answer mixed with emanresu A's answer.

# Vyxal `S`, ~~37~~ ~~35~~ 33 bytes

```
⌈:ƛ≬k∨$cḟ:[℅|u];Zƛ÷›:[768:⇧ṡC℅Ṁ|_

```

Try it Online!

-2 bytes thanks to @Steffan

-2 bytes by inlining the register

I manually generated the diacritics list so this wouldn't have to be scored in UTF-8.

```
⌈:ƛ≬k∨$cḟ:[℅|u];Zƛ÷›:[768:⇧ṡC℅Ṁ|_ # 'S' flag joins the output on spaces
⌈                                  # Split the input on spaces
 :                                 # Duplicate
  ƛ            ;                   # Map the duplicate to...
   ≬    ḟ                          # Find the indexes in the word that satisfy the following condition:
      $c                           # Is the character contained in...
    k∨                             # "aeiouAEIOU"?
         :[   ]                    # If the list is not empty (i.e. the word has vowels)
           ℅                       # Choose a random index from the list
            |                      # Otherwise...
             u                     # Push -1
                Z                  # Zip the mapped list and the word list together
                 ƛ                 # Map the new list of pairs of words and indexes
                  ÷                # Push the word, then the index
                   ›               # Increment the index (0 becomes 1, -1 becomes 0)
                    :[             # If the index is not 0 (i.e. if there is a vowel)
                      768          # Push the charcode of the first diacritic
                         :         # Duplicate
                          ⇧        # Add 2
                           ṡ       # Inclusive range from 768 - 770
                            C      # Unicode value -> character for each number
                              ℅    # Choose a random diacritic
                               Ṁ   # And insert it before the vowel
                                |  # Otherwise...
                                 _ # Pop the duplicated index, leaving the word on the stack

```
> 3 votes

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

Spec doesn't state what Unicode normalisation is allowed. Examples use NFC, but NFD is cheaper.

```
s=>s.replace(/\S+/g,w=>w.replace(x=/[aeiou]/gi,c=>v--?c:c+'̀́̂'[3*r()|0],v=(r=Math.random)()*w.match(x)?.length|0))

```

Attempt This Online! Note: My test does 1000 trials and checks to see if it got the example output. Occasionally it misses for the long ones.

This is basically the same as the old solution, just swapped out the vowel replacement function.

# Old solution (NFC), 159 bytes

```
s=>s.replace(/\S+/g,w=>w.replace(x=/[aeiou]/gi,c=>v--?c:Buffer(c+c).map((n,j)=>j?n+68-4*!(n&12)-!(n&16)+3*r()|0:195),v=(r=Math.random)()*w.match(x)?.length|0))

```

Attempt This Online 2!

## Ungolfed and somewhat explained

In UTF-8, all the accented character are 2 bytes, the first of which is always 195. The second can be calculated from the base letter.

```
char:       A   E   I   O   U   a   e   i   o   u
code:      65  69  73  79  85  97 101 105 111 117
 &12:       0   4   8  12   4   0   4   8  12   4
 &16:       0   0   0   0  16   0   0   0   0  16

with \:   128 136 140 146 153 160 168 172 178 185
with /:   129 137 141 147 154 161 169 173 179 186
with ^:   130 138 142 148 155 162 170 174 180 187

code to \: 63  67  67  67  68  63  67  67  67  68
code to /: 64  68  68  68  69  64  68  68  68  69
code to ^: 65  69  69  69  70  65  69  69  69  70
              |---same---|        |---same---|

```

For most letters, we just increase character code by 67 (for `Aa`, increase by 63, for `Uu` increase by 68), then offset by 0, 1, or 2 to add the hat.

```
s => s.replace(  // replace each word
  /\S+/g,
  w => w.replace(  // replace each vowel
    x = /[aeiou]/gi,
    c => v-- ?            // if this is not the vowel to replace
      c :                     // don't replace
      Buffer(c + c).map(      // otherwise create a Buffer of 2 bytes
        (n, j) => j ?         // map (replace) each byte; if it's the 2nd byte
          n                   // start at n
          + 68                // add 68
          - 4 * !(n & 12)     // subtract 4 if it's 'A' or 'a'
          - !(n & 16)         // subtract 1 if it's not 'U' or 'u'
          + 3 * r() | 0 :     // add randomly 0, 1, or 2 (and floor it)
          195                 // set the first byte to 195
      ),
    v = (r = Math.random)() * w.match(x)?.length | 0  // choose vowel
  )
)

```
> 3 votes

# Answer
# Vyxal `S`, 17 bytes

```
⌈ƛAa[AT›℅3℅767+CṀ

```

Try it Online!

Some tricks stolen from Seggan's answer.

```
⌈ƛ                # Over each word
  Aa[             # If it has a vowel...
     A            # Is each a vowel?
      T           # Indices of vowels
       ℅›         # Choose a random one and increment it
         3℅       # Random choice from [1, 2, 3]
           767+   # Add 767
               C  # Make it a char
                Ṁ # Insert that at the specified index.
                  # (S flag) turn the word list into a sentence

```
> 3 votes

# Answer
## C#, ~~273~~ 267 bytes

```
using System.Linq;A=s=>{var r=new System.Random();var a=s.Split(' ');return string.Join(" ",a.Select(w=>w.Select((c,i)=>"AEIOUaeiou".Any(d=>c==d)?i:-1).Where(x=>x>=0).ToList()).Select((l,i)=>l.Any()?a[i].Insert(l[r.Next(l.Count)]+1,""+(char)r.Next(768,771)):a[i]));};

```

repl.it demo

I really feels like I'm cheating, since I still add hats to already accented vowels created by combining characters. If that is not acceptable, let me know so I can ~~add boilerplate codes~~ declare this answer non-competing.

This thing adds a random character among U+0300 or U+0301 or U+0302, after a random vowel of each input word (if any).

Ungolfed (lambda body only)

```
var r=new System.Random();
// Split sentence to array of words
var a=s.Split(' ');
// Join the (hat-ed) words back to sentence
return string.Join(
    " ",
    // Select an IEnum of list of integers indicating the positions of vowels
    a.Select(w=>
        w.Select((c,i)=>
            // If it's vowel, return position (>=0), else return -1
            "AEIOUaeiou".Any(d=>c==d)?i:-1
        // Filter vowels only
        ).Where(x=>x>=0)
        .ToList()
    // Convert each list of integers to hat-ed words
    ).Select((l,i)=>
        l.Any()
            // Insert "something" into the word...
            ?a[i].Insert(
                // ...at the position after a random vowel in that word...
                l[r.Next(l.Count)]+1,
                // "something" is a random integer in [0x0300, 0x0303), then casted to UTF16 i.e. [U+0300, U+0302]
                ""+(char)r.Next(768,771))
            // List is empty => just return original word
            :a[i]));

```
> 2 votes

# Answer
# Mathematica, 226 bytes

```
Join@@((p=Position[w=#,Alternatives@@(v=Characters@"aeiouAEIOU")];If[p!={},i=#&@@RandomChoice@p;w[[i]]=FromCharacterCode[ToCharacterCode["àèìòùÀÈÌÒÙ"][[#&@@Position[v,w[[i]]]]]+RandomInteger@2]];w)&/@Split[#,{##}~FreeQ~" "&])&

```

Unnamed function taking a list of characters as input and returning a list of characters. Easier-to-read version, slightly ungolfed as well:

```
 1  v = Characters["aeiouAEIOU"];
 2  a = ToCharacterCode["àèìòùÀÈÌÒÙ"];
 3  Join @@ (
 4    (p = Position[w = #, Alternatives @@ v];
 5      If[p != {},
 6        i = First[RandomChoice[p]];
 7        w[[i]] =
 8          FromCharacterCode[
 9            a[[ First[ Position[ v, w[[i]] ] ] ]] + RandomInteger[2]
10          ]
11        ]; w
12    ) &
13  ) /@ Split[#1, FreeQ[{##1}, " "] &] &

```

Line 13 splits the input into words (sublists of characters) at all the spaces; each word is operated on by the function defined by lines 4-12, and the results joined back together again in a single list by line 3.

Line 4 sets `p` to the list of indices indicating which characters of the word `w` are vowels. If there are any vowels (line 5), we make a random choice of one such index `i` (line 6) and then reset that single character of the word to a new character (lines 7-10). Finally we output the (possibly modified) word `w`.

To select the new character, we find where the vowel to be replaced sits in the string `v` and choose the corresponding character code from `a`. But to randomly select the three hats, we take that code and add a random integer between 0 and 2 (line 9) before converting back to a character. (Fortunately the behatted vowels all come in consecutive trios of UTF-8 character codes.)
> 1 votes

# Answer
# Python 3, 170 bytes

```
from random import *
c=choice
print(' '.join([w,w[:i]+c('̀́̂')+w[i:]][i>0]for w in input().split()for i in[c([j+1 for j,x in enumerate(w)if x in 'aeiouAEIOU']or[0])]))

```

Ungolfed:

```
from random import choice
print(' '.join([
                   w,  # Don't modify the word if no vowels were found

                   w[:i] + choice('̀́̂') + w[i:]
               ][i > 0]
               for w in input().split()
                   for i in [choice([j + 1 for j, x in enumerate(w) if x in 'aeiouAEIOU']
                                    or [0])  # choice requires a non-empty sequence
                             ]))

```
> 1 votes

# Answer
# Python 3, 162 bytes

```
from random import*
print(*(w.insert(*choice([(n+1,q)for n,c in enumerate(w)if c in'AEIOUaeiou'for q in'̀́̂']or[(0,'')]))or''.join(w)for*w,in input().split()))

```

Try it online!
> 0 votes

---
Tags: code-golf
---