title: Find the center

text:
# Question
Title: Find the center
Given a string of ASCII characters, output the character that is in the middle. If there is no middle character (when the string has an even length), output the ASCII character whose ordinal is the floored average of the two center characters. If the string is empty, an empty string should be output.

Test cases:

```
12345 => 3

Hello => l

Hiya => q

(empty input) => (empty output)

```

Shortest program in characters wins. (Not bytes.)

# Leaderboard

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

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

```
## Language Name, N characters

```

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

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

```

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

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

```

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

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

```

```
<style>body { text-align: left !important} #answer-list { padding: 10px; width: 290px; float: left; } #language-list { padding: 10px; width: 290px; float: left; } table thead { font-weight: bold; } table td { padding: 5px; }</style><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="language-list"> <h2>Shortest Solution by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr> </thead> <tbody id="languages"> </tbody> </table> </div> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr> </thead> <tbody id="answers"> </tbody> </table> </div> <table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr> </tbody> </table><script>var QUESTION_ID = 64599; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 47556; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER; } function commentUrl(index, answers) { return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER; } function getAnswers() { jQuery.ajax({ url: answersUrl(answer_page++), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { answers.push.apply(answers, data.items); answers_hash = []; answer_ids = []; data.items.forEach(function(a) { a.comments = []; var id = +a.share_link.match(/\d+/); answer_ids.push(id); answers_hash[id] = a; }); if (!data.has_more) more_answers = false; comment_page = 1; getComments(); } }); } function getComments() { jQuery.ajax({ url: commentUrl(comment_page++, answer_ids), method: "get", dataType: "jsonp", crossDomain: true, success: function (data) { data.items.forEach(function(c) { if (c.owner.user_id === OVERRIDE_USER) answers_hash[c.post_id].comments.push(c); }); if (data.has_more) getComments(); else if (more_answers) getAnswers(); else process(); } }); } getAnswers(); var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/; var OVERRIDE_REG = /^Override\s*header:\s*/i; function getAuthorName(a) { return a.owner.display_name; } function process() { var valid = []; answers.forEach(function(a) { var body = a.body; a.comments.forEach(function(c) { if(OVERRIDE_REG.test(c.body)) body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>'; }); var match = body.match(SCORE_REG); if (match) valid.push({ user: getAuthorName(a), size: +match[2], language: match[1], link: a.share_link, }); else console.log(body); }); valid.sort(function (a, b) { var aB = a.size, bB = b.size; return aB - bB }); var languages = {}; var place = 1; var lastSize = null; var lastPlace = 1; valid.forEach(function (a) { if (a.size != lastSize) lastPlace = place; lastSize = a.size; ++place; var answer = jQuery("#answer-template").html(); answer = answer.replace("{{PLACE}}", lastPlace + ".") .replace("{{NAME}}", a.user) .replace("{{LANGUAGE}}", a.language) .replace("{{SIZE}}", a.size) .replace("{{LINK}}", a.link); answer = jQuery(answer); jQuery("#answers").append(answer); var lang = a.language; lang = jQuery('<a>'+lang+'</a>').text(); languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang.toLowerCase(), user: a.user, size: a.size, link: a.link}; }); var langs = []; for (var lang in languages) if (languages.hasOwnProperty(lang)) langs.push(languages[lang]); langs.sort(function (a, b) { if (a.lang_raw > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) return -1; return 0; }); for (var i = 0; i < langs.length; ++i) { var language = jQuery("#language-template").html(); var lang = langs[i]; language = language.replace("{{LANGUAGE}}", lang.lang) .replace("{{NAME}}", lang.user) .replace("{{SIZE}}", lang.size) .replace("{{LINK}}", lang.link); language = jQuery(language); jQuery("#languages").append(language); } }</script>
```

# Answer
# Pyth, 15 bytes

```
Cs.O@R/lz2_BCMz

```

Demonstration

Starting with "Hiya" as input:

```
              z    "Hiya"                                      Input
            CM     [72, 105, 121, 97]                          Character values
          _B       [[72, 105, 121, 97], [97, 121, 105, 72]]    Pair with reversal
      /lz2         2                                           Halfway index
    @R             [121, 105]                                  That element in each
  .O               113.0                                       Average
 s                 113                                         Floor
C                  "q"                                         Cast to character
                   q                                           Print implicitly

```

Note that this crashes with an error on empty input, and prints nothing to STDOUT, which is a valid way to output an empty string by code-golf defaults.
> 9 votes

# Answer
# Brainf\***, 61 bytes

# Chinese, 16 characters

This requires the input is in the ASCII range 1-127 and is null-terminated. It deletes pairs of characters from the start and end of the string until there are one or two characters remaining. If there are two, it adds them together, then divides by 2, rounding down. The remaining character is printed.

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

```

Try it on this interpreter.

Dissection:

```
,[>,]         Get the null terminated input
<<<           Move to the second last character
[             While there are at least 3 characters
  [<]>           Move to the first character
  [-]            Delete it
  >[>]<          Move to the last character
  [-]            Delete it
  <<<            Move the the third last character
]
>              Move to the second last character
[              If there are two characters remaining
  [->+<]         Add the two characters together
  >[-[-<+<]>>]   Divide the character by 2 rounding down
  <[>]<[>]<<     Move to before the character to exit the if loop
]
>.             Print the remaining character

```

* Given each instruction could be compressed to 3 bits and encoded in UTF-32, the whole program could technically be expressed in 6 characters.

**EDIT:** And thanks to Jan Dvorak for introducing me to Chinese, which compresses this into 16 characters, on par with Dennis' CJam answer.

```
蜐蕈帑聿纂胯箩悚衅鹊颂鹛拮拮氰人

```
> 9 votes

# Answer
# CJam, 16 bytes

```
q:i_W%.+_,2/=2/c

```

Try it online!

### How it works

```
q                e# Read all input.
 :i              e# Cast each character to integer.
   _W%           e# Push a reversed copy.
      .+         e# Perform vectorized addition.
        _,2/     e# Get the length, divided by 2.
            =    e# Select the corresponding sum.
             2/c e# Divide by 2 and cast to character.

```
> 6 votes

# Answer
# TeaScript, 23 bytes ~~25 30 31 33~~

```
²(x[t=xn/2]c+xv[t]c)/2)

```

Uses @isaacg's idea of reversing the string.

Try it online

Test all of the cases

## Ungolfed && Explanation

TeaScript is still JavaScript so it functions a lot like JavaScript too.

```
C((x[t=xn/2]c+xv[t]c)/2)

C((           // Char code to char
   x[t=xn/2]c // Floored center
   +          // Add to
   xv[t]c     // Ceil'd center
  ) / 2)      // Divide by 2

```
> 6 votes

# Answer
## Python 3, ~~61~~ ~~59~~ ~~57~~ 55 bytes

I try not to golf with languages I work in, but this isn't too evil.

*Thanks to @xsot for 2 bytes!*

```
lambda x:chr((ord(x[len(x)//2])+ord(x[~len(x)//2]))//2)

```

The full program is 59 bytes:

```
x=input()
l=len(x)//2
print(chr((ord(x[l])+ord(x[~l]))//2))

```

Try it here.
> 6 votes

# Answer
# 8086 machine code + DOS, 31 bytes

Hexdump:

```
BA 1E 01 B4 0A CD 21 8B F2 46 8A 1C D0 EB 8A 50
01 72 06 74 08 02 10 D0 EA B4 02 CD 21 C3 FF

```

Assembly source code (can be assembled with tasm):

```
    .MODEL TINY

    .CODE
    org 100h

    MAIN PROC

    mov dx, offset buf
    mov ah, 10      ; DOS function "read string"
    int 21h

    mov si, dx
    inc si          ; si now points to the length of the string
    mov bl, [si]    ;
    shr bl, 1       ; divide the length by 2
    mov dl, [si+bx+1] ; load the middle char
    jc calc_done    ; if length was odd - done
    jz output_done  ; if length was zero - exit
    add dl, [si+bx] ; add the other middle char
    shr dl, 1       ; divide by 2
calc_done:
    mov ah, 2       ; DOS function "output char"
    int 21h
output_done:
    ret

buf db 255          ; maximum bytes to input

    MAIN ENDP
    END MAIN

```

There is some delicate usage of the FLAGS register here. After it shifts the length of the string right by 1 bit (which is equivalent to division by 2), two flags store additional information:

* Carry flag: contains the bit that was shifted out. If the bit is 1, the length was odd.
* Zero flag: shows whether the result is zero. If the carry flag is 0 and the zero flag is 1, the length was zero, and nothing should be printed.

Normally, the flags should be checked immediately, but here I use the fact that the `mov` instruction doesn't change flags. So they can be examined after loading the middle char.
> 6 votes

# Answer
# Matlab, ~~39~~ 37 bytes

`floor((end+[1,2])/2)` returns the middle two indices of the string if the length is even, and returns the middle indice twice if the length is odd.

`mean` just returns the mean of those values and `char` automatically floors it.

```
@(s)char(mean(s(floor(end/2+[.5,1]))))

```
> 5 votes

# Answer
# Husk, 11 bytes

```
c½S¤+öc→←½↔

```

Try it online!

# Explanation

Delicious, delicious combinators all the way down. `ö` is "compose these four functions", `¤` is "apply the first argument to the results of applying the second argument to two additional arguments separately", `S` is "apply this function (which should take two arguments) to `S`'s third argument and to the result of applying `S`'s second argument to its third". Therefore,

```
   Function       Type                Semantics
     öc→←½        [TChar]->TInt       ASCII code of middle (floored) char in string
   ¤+öc→←½        [TC]->[TC]->TI      Sum of ASCII codes of middle of two strings
  S¤+öc→←½↔       [TC]->TI            Sum of ASCII codes of the middle of a string and its reverse
c½S¤+öc→←½↔       [TC]->TC            ASCII character represented by half the above, QEF

```

Edited to add: Strictly speaking, this fails slightly to conform to the problem specification, which requests a string in the case of an empty input and a character in other cases.

Due to Husk's strict typing, it's just not possible to define a function/program that can return either of two types. I chose to return a single character in all cases, and for Husk, the most reasonable choice for a single character to represent the empty string is `'(space)'` because that's the "default" value (and in fact, that's why this program returns it; the default value is used when taking the last () item of an empty list).

I could have also reasonably chosen to return strings of zero or one characters, which would fail the specification in the other direction, but I didn't because it adds four bytes: `Ṡ&ö;c½S¤+öc→←½↔`, with the `;` converting the character to a one-character string, another `ö` to explicitly compose the needful, and a `Ṡ&` to shortcut in the case of falsy input.
> 5 votes

# Answer
# Prolog, 111 bytes

**Code**

```
p(X):-atom_codes(X,L),length(L,N),I is N//2,J is(N-1)//2,nth0(I,L,A),nth0(J,L,B),Q is(A+B)//2,writef('%n',[Q]).

```

**Explained**

```
p(X):-atom_codes(X,L),       % Convert to list of charcodes
      length(L,N),           % Get length of list
      I is N//2,             % Get mid index of list
      J is(N-1)//2,          % Get 2nd mid index of list if even length
      nth0(I,L,A),           % Get element at mid index
      nth0(J,L,B),           % Get element at 2nd mid index
      Q is(A+B)//2,          % Get average of elements at mid indices
      writef('%n',[Q]).      % Print as character

```

**Examples**

```
>p('Hello').
l

>p('Hiya').
q

```
> 4 votes

# Answer
# , 73 bytes

```
function(x,y=utf8ToInt(x),n=sum(1|y))if(n)intToUtf8(mean(y[n/2+c(1,.5)]))

```

Try it online!

Many thanks to @ngm for coming up with this non-recursive idea - allowed to golf 20 bytes.

Old solution:

### , ~~101~~ 95 bytes

```
"!"=function(x,n=sum(1|x))"if"(n<3,mean(x),!x[-c(1,n)])
try(intToUtf8(!utf8ToInt(scan(,""))),T)

```

Try it online!

Recursive solution. Corrected one issue at the price of 2 bytes:

* added `try(expr, silent = TRUE)` to properly manage the case where the input is empty.

thanks Giusppe for 4 bytes !
> 4 votes

# Answer
# , ~~44~~ 34 bytes

Crossed out 44 is still regular 44 :(

```
ise.eJ;2/m[(\($L;dJ{#\#+2/c}L;?o];

```

Bytes wasted on:

* Checking if the input's length is even/odd
* Getting the middle character(s)
> 3 votes

# Answer
# JavaScript (ES6), 83 bytes ~~89 91~~

*Saved 2 bytes thanks to @Cᴏɴᴏʀ O'Bʀɪᴇɴ*

*Saved 6 bytes thanks to @ETHproductions*

```
s=>String.fromCharCode((s[~~(t=s.length/2-.5)][q='charCodeAt']()+s[0|t+.9][q]())/2)

```

JavaScript's not too good at all this string char code.
> 3 votes

# Answer
# C++14, 56 bytes

```
[](auto s){int l=s.size();return(s[(l-1)/2]+s[l/2])/2;};

```

Anonymous lambda taking string as an argument and returning int as char code. For `""`, it returns `0`. Not sure how exactly the input and output should look like (is not specified in the question).

Ungolfed, with usage

```
#include <string>
int main()
{
    auto lmbd = [](auto str)
    {
        int len = str.size();
        return (str[(len - 1) / 2] + str[len / 2]) / 2;
    };

    std::cout << (char) lmbd("Hiya"s) << std::endl; // outputs q
}

```
> 3 votes

# Answer
## Minkolang 0.13, ~~23~~ 20 bytes

```
$oI2$%d$z,-Xz3&+2:O.

```

Try it here.

### Explanation

```
$o        Read in the whole stack as characters
I2$%      Push I,2, then pop them and push I//2,I%2
d$z       Duplicate top of stack (I%2) and store in register (z)
,-X       <not> the top of stack, subtract, and dump that many off the top of stack
z3&       Retrieve value from register and jump 3 spaces if this is not zero
   +2:    Add and then divide by 2
O.        Output as character and stop.

```
> 2 votes

# Answer
# , 23 chars

```
a=ïꝈ/2,ϚĎ((ïüa+ᴙïüa)/2)

```

`Try it here (Firefox only).`

Thanks to @ETHProductions for the idea!
> 2 votes

# Answer
# Japt, ~~40~~ ~~29~~ ~~23~~ ~~21~~ 20 bytes

*Saved 4 bytes thanks to @ןnɟuɐɯɹɐןoɯ*

Now only half the original length! I love code golf. :-D

```
UcV=K*Ul)+Uw cV)/2 d

```

Works properly on the empty string. Try it online!

### How it works

```
          // Implicit: U = input string, K = 0.5
Uc        // Take the char-code at position
 V=K*Ul   //  V = 0.5 * length of U
+         //  (auto-floored), plus
Uw cV     //  the char-code at position V (auto-floored) in the reversed string,
/2 d      //  divide by 2, and turn back into a character (auto-floored).
          // Implicit: output last expression

```

As you can see, it uses a lot of auto-flooring. (Thanks, JavaScript!) Suggestions welcome!
> 2 votes

# Answer
# Go, ~~166~~ ~~156~~ 153 bytes

Go may not be the best language for golfing... but I love it, so so much, and I'm learning it, so there.

This implementation accepts blank (`\n`) input and **will probably break with non-ASCII/ASCII-extended input.** However, OP has not specified input/output encoding thus ASCII is all I've explicitly supported.

*Edit*: turns out `if`/`else` *is* shorter than `switch`. Now I know, I suppose.

Golfed:

```
package main;import ."fmt";func main(){a:="";_,_=Scanln(&a);if b:=len(a);b>0{x:=b/2;if b%2==0{Printf("%c",(a[x]+a[x+1])/2)}else{Println(string(a[x]))}}}

```

Ungolfed:

```
package main # everything in go is a package.

import . "fmt" # the dot allows for absolute package method references
# (think "from string import *" in python)

func main() {
    a := ""
    _, _ = Scanln(&a) # a pointer to a
    if b := len(a); b > 0 { # if statements allow local assignment statements
        x := b / 2
        if b%2 == 0 { # modulo 2 is the easiest way to test evenness
#in which case, average the charcodes and print the result
            Printf("%c", (a[x]+a[x+1])/2)
        } else {
# else just find the middle character (no rounding needed; integer division in Go always results in an integer)
            Println(string(a[x]))
        }
    }
}

```
> 2 votes

# Answer
# C#, 77 bytes

```
s=>{int n=s.Length;return n<1?' ':(char)(n%2>0?s[n/2]:(s[n/2-1]+s[n/2])/2);};

```

It doesn't actually return a string, and you'll get a space character if the input string is empty because the function must always return a value. 2 more bytes would be needed to return a string.

Full program with test cases:

```
using System;

namespace FindTheCenter
{
    class Program
    {
        static void Main(string[] args)
        {
            Func<string,char>f= s=>{int n=s.Length;return n<1?' ':(char)(n%2>0?s[n/2]:(s[n/2-1]+s[n/2])/2);};   //77 bytes
            Console.WriteLine(f(""));
            Console.WriteLine(f("Hello"));
            Console.WriteLine(f("Hiya"));
        }
    }
}

```

---

Alternatively, a full program which reads user input and prints the center of the entered string:

# C#, 144 bytes

```
using C=System.Console;class P{static void Main(){var s=C.ReadLine();int n=s.Length;C.Write(n<1?' ':(char)(n%2>0?s[n/2]:(s[n/2-1]+s[n/2])/2));}}

```

Again, it uses the same trick of printing a space character, which the user will not notice, and not an empty string, otherwise the solution is 2 bytes longer.
> 2 votes

# Answer
## Vim, ~~38~~ ~~24~~ 23 keystrokes

Because vim has a built in function to find the middle *line* but not the middle *char*, we split every character on a separate line first using `substitute`, find the middle line, then delete everything after and before it.

```
:s/\./\0\r/g<cr>ddMjdGkdgg

```

If you want to run this, beware of `.vimrc` files which may change the behavior of `.` (magic regex) and `g` (gdefault). Note that it actually saves me 3 keystrokes on my machine :)

## Previous answer

```
:exe 'norm '.(virtcol('$')/2).'|d^ld$'

```

Takes a one line buffer as input, updates the current buffer with the middle character. I thought there would have been a shortcut for this in vim!

Note: a potentially shorter solution seems to cause an infinite loop... If someone has an idea: `qq^x$x@qq@qp` (12 keystrokes) - it works with `<c-c>` after the last `@q`...
> 2 votes

# Answer
# Excel, ~~122~~ 79 bytes

Actually @Sophia Lechner's answer now:

```
=IFERROR(CHAR(CODE(MID(A8,LEN(A8)/2+.5,1))/2+CODE(MID(A8,LEN(A8)/2+1,1))/2),"")

```

---

-5 bytes from initial solution thanks to @Taylor Scott.

```
=IFERROR(IF(ISODD(LEN(A1)),MID(A1,LEN(A1)/2+1,1),CHAR((CODE(MID(A1,LEN(A1)/2,1))+CODE(MID(A1,LEN(A1)/2+1,1)))/2)),"")

```

12 bytes needed for Empty String.
> 2 votes

# Answer
# Haskell, 87 bytes

A nice recursive solution is possible here:

```
import Data.Char
f[]=[]
f[c]=[c]
f[c,d]=[chr(ord c+div(ord d-ord c)2)]
f(c:s)=f$init s

```
> 2 votes

# Answer
# Jelly, 7 bytes

```
JÆṁị¹Æm

```

Try it online!

Takes input as a list of codepoints. Outputs a single codepoint.

## How it works

```
JÆṁị¹Æm - Main link. Takes a string S on the left
J       - Indices of S
 Æṁ     - Median
    ¹   - Yield S
   ị    - Index into S
     Æm - Get their arithmetic mean

```

The `Æṁ` median atom returns the mean of the two central elements if the list has an even list. When the list is the indices of `S` (i.e. `[1, 2, ..., len(S)]`), this will always be half the sum of an odd and an even integer, so the result will be \\$x + \frac 1 2, x \in \mathbb N\\$.

When indexing with non-integers such as \\$x + \frac 1 2\\$, Jelly instead uses the pair \\$\[x, x+1\]\\$ to index, which, in this case, results the two central characters if the list length is even.
> 2 votes

# Answer
# Vyxal `K`, 8 bytes

```
‡ḢṪ↔Ṫtṁ⌊

```

Try it Online!

Explanation:

```
          # 'K' flag - Strings are inputted as a list of ordinal values
‡ḢṪ↔      # Remove the first and last elements elements of the list until empty, returning intermittent values
    Ṫt    # Remove all but the second to last element of the list
      ṁ   # Take the average of the middle character(s)
       ⌊  # Floor
          # 'K' flag - Output numbers as characters

```
> 2 votes

# Answer
# Mathematica, ~~118~~ 99 chars

```
Floor
If[#=="","",FromCharacterCode[%@Mean@#[[Ceiling[l=Length@#/2];;%[l+1]]]&@ToCharacterCode@#]]&

```

Mma character code manipulation is *pricey*...
> 1 votes

# Answer
## \>\<\>, 24 + 3 (for -s) = 27 bytes

```
l1+l4(*9$.~{~
;
o;
+2,o;

```

Old solution (Doesn't work for empty input):

```
l3(?v~{~
?vo;>l2=
;>+2,o

```

Both take input on the stack through `-s`. Both are 24 bytes.

Try it online here.
> 1 votes

# Answer
# VBA, 130 Bytes

```
Function a(q)
h=Len(q):a=Mid(q,(h)/2,2)
If h Mod 2=0 Then:a=Chr((Asc(Left(a,1))+Asc(Right(a,1)))\2):Else:a=Right(a,1)
End Function

```

> Finds the Middle 2 Characters.
> If number of Characters is Odd then get the Right of the Middle 2 which will be the true middle as we rounded down.
> If not sum the ASCII `asc()` values of the 2 Characters divided by 2 and return the ASCII Character `chr()` based on that value.

I think I can golf away one of the `asc()` calls, but couldn't get it to work shorter.
> 1 votes

# Answer
# K, 40 bytes

```
{(*|r;`c$_(+/r:2#l_x)%2)@l=_l:-1+(#x)%2}

```
> 1 votes

# Answer
# pb, 83 bytes

```
^<b[1]>>>w[B!0]{<w[B!0]{t[B]<b[T]>>}<b[0]<b[0]<[X]>>}w[B=0]{<}t[B]<[X]t[B+T]vb[T/2]

```

While there are at least 3 characters in the input string, the first and last are removed. This leaves either 1 character (should be printed unmodified) or 2 (should be averaged and printed). To handle this, the first and last characters of the string are added together and divided by two. If there was only one character, `(a+a)/2==a`. If there was two, `(a+b)/2` is the character that needs to be printed. pb "borrows" Python's expression evaluation (`def expression(e): return eval(e, globals())`) so this is automatically floored.

Handling empty input costs me 5 bytes. Specifically, `<b[1]>` on the first line. Earlier, when I said "string", that was a total lie. pb doesn't have strings, it has characters that happen to be close to each other. Looking for the "last character of a string" just means moving the brush to the left until it hits a character. When no input is provided, the "while there are at least 3 characters" loop is skipped entirely and it starts looking for the last character. Without that `<b[1]>`, it would keep looking forever. That code puts a character with a value of 1 at (-1, -1) specifically to be found when the input is empty. After finding the "last character" of the string the brush assumes the first one is at (0, -1) and goes there directly, finding a value of 0. `(1+0)/2` is 0 in pb, so it prints a null character.

> But monorail, that's still printing! The challenge specification says `(empty input) => (empty output)`! Isn't printing a null character cheating? Also, this is unrelated, but you are smart and handsome.

Thanks, hypothetical question-asker. Earlier, when I said "print", that was a total lie. In pb, you don't really print values, you just place them on the canvas. Rather than "a way to output", it's more accurate to imagine the canvas as an infinitely large 2D array. It allows negative indices in either dimension, and a lot of programming in pb is really about making sure the brush gets to the location on the canvas that you want it. When the program finishes executing, anything on the canvas with non-negative X and Y coordinates is printed to the appropriate location on the console. When the program begins, the entire canvas is filled with values of 0. In order to not have to print an infinite number of lines, each with an infinite number of null bytes, each line of output is only printed up to the last nonzero character, and lines are only printed up to the last one with a nonzero character in it. So putting a `0` at (0, 0) is still an empty output.

**Ungolfed:**

```
^<b[1]>                # Prevent an infinite loop on empty input

>>w[B!0]{              # While there are at least 3 chars of input:

    <w[B!0]{              # Starting at the second character:
            t[B]<b[T]>>         # Copy all characters one position to the left
                                # (Effectively erasing the first character)
    }

    <b[0]<b[0]            # Delete both copies of the last character

    <[X]>>                # Get in place to restart loop
}

w[B=0]{<}                 # Go to last character of remaining string
t[B]<[X]t[B+T]            # Find it plus the first character
vb[T/2]                   # Divide by 2 and print

```
> 1 votes

# Answer
## CoffeeScript, ~~104~~ 103 bytes

```
f=(x)->((y=x.length)%2&&x[y//2]||y&&String.fromCharCode (x[y/=2][z='charCodeAt']()+x[y-1][z] 0)//2)||''

```
> 1 votes

# Answer
# Ruby, ~~43~~ ~~42~~ 41 bytes

```
->a{s=a.size;puts s<1?'':s%2<1??q:a[s/2]}

```

**42 bytes**

```
->a{s=a.size;puts s==0?'':s%2<1??q:a[s/2]}

```

**43 bytes**

```
->a{s=a.size;puts s==0?'':s%2<1?'q':a[s/2]}

```

**Usage:**

```
->a{s=a.size;puts s<1?'':s%2<1??q:a[s/2]}['12345']
=> 3

```
> 1 votes

# Answer
# Java 7, 152 bytes

```
String c(String s){char[]a=s.toCharArray();int l=a.length,x,y;return l<2?s:""+(l%2>0?a[l/2]:(char)((x=a[l/2])>(y=a[(l/2)-1])?y+((x-y)/2):x+((y-x)/2)));}

```

**Ungolfed & test cases:**

Try it here.

```
class M{
  static String c(String s){
    char[] a = s.toCharArray();
    int l = a.length,
            x,
            y;
    return l < 2
            ? s
            : "" + (l%2 > 0
                     ? a[l/2]
                     : (char)((x = a[l/2]) > (y = a[(l/2)-1])
                                ? y + ((x-y)/2)
                                : x + ((y-x)/2)));
  }

  public static void main(String[] a){
    System.out.println(c("12345"));
    System.out.println(c("Hello"));
    System.out.println(c("Hiya"));
    System.out.println(c(""));
    System.out.println(c("x")); // Additional test case that will fail on some other answers
  }
}

```

**Output:**

```
3
l
q
(empty output)
x

```
> 1 votes

# Answer
# PHP, ~~147~~ 93 bytes

Credits and special thanks to Jörg Hülsermann for golfing my answer 54 bytes down!

```
<?=($l=strlen($s=$argv[1]))%2?$s[($l-1)/2]:chr(floor((ord($s[$l/2])+ord($s[$l/2-1]))/2));

```

### Previous version:

```
$s=$argv[1];$l=strlen($s);echo($l%2!=0?substr($s,$n=($l-1)/2,-$n):chr(floor(abs((ord($x=substr($s,$l/2-1,1))-ord(substr($s,$l/2,1)))/2))+ord($x)));

```

Testing code:

```
$argv[1] = 'Hiya';
$s=$argv[1];
$l=strlen($s);
echo($l%2!=0?substr($s,$n=($l-1)/2,-$n):chr(floor(abs((ord($x=substr($s,$l/2-1,1))-ord(substr($s,$l/2,1)))/2))+ord($x)));

```

Test online

~~I have the feeling that this can be improved, but not enough time for it...~~
> 1 votes

# Answer
# Seriously, ~~22~~ 20 bytes

```
,O3 >WXXaXa3 >WXkæ≈c

```

Thanks @Mego for being great at your language

Try it online or whatever
> 0 votes

# Answer
# C (gcc), ~~54~~ 51 bytes

-3 bytes thanks to vazt.

Returns a NULL char for empty strings.

```
l;f(char*s){l=strlen(s);s+=l/2;s=*s+s[l%2-!!l]>>1;}

```

Try it online!
> 0 votes

# Answer
# Excel VBA, ~~101~~ 81 bytes

Immediate window function that takes input from cell `[A1]` and outputs to the VBE immediate window

```
l=[Len(A1)]/2:s=[A1]&" ":If l Then?Chr((Asc(Mid(s,l+.5))+Asc(Mid(s,l+1)))\2)Else?

```
> 0 votes

# Answer
# Lua, 128 bytes

```
p=...i=math.ceil(#p/2)s=string b=s.byte a=p:sub(i,i)io.write(#p==0 and""or#p/2%1~=0 and a or s.char((b(a)+b(p:sub(i+1,i+1)))/2))

```

Try it online!
> 0 votes

# Answer
# 05AB1E, ~~11~~ 15 bytes

```
Dg≠iÇÂ)øDg;èO;ç

```

+4 bytes to fix an input of length 1.

Try it online or verify all test cases.

**Explanation:**

```
Dg              # Duplicate the input, and get it's length
  ≠i            # If this length is not exactly 1:
    Ç           #  Convert each letter to its ordinal value
                #   i.e. 'Hiya' → [72,105,121,97]
     Â          #  Bifurcate (short for Duplicate and Reverse)
                #   [72,105,121,97] → [72,105,121,97] and [97,121,105,72]
      )         #  Wrap both lists in a list
                #   [72,105,121,97] and [97,121,105,72] → [[72,105,121,97],[97,121,105,72]]
       ø        #  Zip the lists with each other, creating pairs
                #   i.e. [[72,105,121,97],[97,121,105,72]]
                #    → [[72,97],[105,121],[121,105],[97,72]]
        Dg      #  Duplicate it, and get it's length
                #   i.e. [[72,97],[105,121],[121,105],[97,72]] → 4
          ;     #  Halve this length
                #   i.e. 4 → 2
           è    #  Index (0-indexed) it in the pairs
                #   i.e. [[72,97],[105,121],[121,105],[97,72]] and 2 → [121,105]
            O   #  Take the sum of the indexed pair
                #   i.e. [121,105] → 226
             ;  #  Halve it
                #   i.e. 226 → 113.0
              ç #  Convert it from this ordinal value to a character
                #   i.e. 113.0 → 'q'
                # (Implicit else: output the 1-char input itself)

```

**Old 11 bytes version which works for all given test cases, but fails for inputs of length 1:**

```
ÇÂ)øDg;èO;ç

```

Try it online or verify all test cases.
> 0 votes

# Answer
# Japt, 15 bytes

```
cUÊz)dUÔcUÊz¹cz

```

Try it
> 0 votes

# Answer
# 05AB1E, 5 bytes

```
ÅsÅAï

```

Try it online! Beats all other answers. Takes input as a list of codepoints, and outputs as a codepoint.

```
ÅsÅAï  # full program
  ÅA   # mean of...
Ås     # middle(s) of...
       # implicit input...
    ï  # as an integer
       # implicit output

```
> 0 votes

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

```
lambda s:chr(ord(s[(l:=len(s)//2)])+ord(s[~l])>>1)

```

Try it online!

Based on @lirtosiast's answer. Errors out on empty strings and thus the interpreter writes to `stderr`... So *technically* no output? O:)

Side note: The parentheses around `l:=len(s)//2` are needed because, we are inside brackets `[]` and Python's parser thinks that the colon is part of a slice? Shouldn't that be a bug since the walrus operator `:=` is a seperate token?
> 0 votes

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


title: Peter is a picky eater!

text:
# Question
Title: Peter is a picky eater!
There is a boy named Peter. Peter is a picky eater and doesn't like to eat the same kind of cookie again on the same day.

Peter gets a present, The present is a box of cookies! The box contains \\$K\\$ types of cookies. Also, it contains different amount of each type of cookie.

Peter, being the picky eater he is, Wants to eat \\$n\\$ cookies, on each \\$n^{th}\\$ day. Also, he does not want to eat more than 1 cookie of the same kind on any given day.

i.e. He eats \\$1\\$ cookie on the \\$1^{st}\\$ day, \\$2\\$ cookies on the \\$2^{nd}\\$ day and so on.

If there is no possible way for Peter to eat \\$n\\$ cookies at day \\$n\\$, he gives up and dumps the box. He also dumps the box if it becomes empty.

Find the maximum number of days that the box will last for Peter.

## Input

\\$K\\$ Positive Integers, specifying the number of cookies for each different kind.

## Output

An Integer corresponding to how many days Peter keeps the box.

## Test Cases

```
INPUT -> OUTPUT
1 2 -> 2
1 2 3 -> 3
1 2 3 4 4 -> 4
1 2 3 3 -> 3
2 2 2 -> 3
1 1 1 1 -> 2
11 22 33 44 55 66 77 88 99 -> 9
10 20 30 40 50 60 70 80 -> 8
3 3 3 3 3 3 3 3 3 3 3 -> 7
3 3 3 3 3 3 3 3 3 -> 6
9 5 6 8 7 -> 5
1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10 10 10 -> 35
1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10 -> 32

```

Gist for test cases

This is so the shortest code wins.

# Answer
> 15 votes
# Perl 5, ~~79~~ ~~77~~ ~~76~~ ~~75~~ ~~69 (rip)~~ ~~68~~ ~~64~~ 62 bytes

Credit to **@Lynn** for improving my answer by 4 bytes (68 to 64) and the explanation about the comma operator in scalar context here https://docstore.mik.ua/orelly/perl2/prog/ch03\_18.htm

Thanks **@Nahuel Fouilleul** for the tip using anonymous functions to save 2 bytes (64 to 62) but if it's not allowed I'll revert back

```
sub{$^=0;++$^while(@_=sort{$b-$a}@_),!grep--$_[$_]<0,0..$^;$^}

```

**Test Cases Here:** Try it online!

### Expanded:

```
sub {                       # Declare subroutine
    $^ = 0;                 # Set scalar caret variable to 0 (you can put this variable right next to if statements and for loops etc)
    ++$^ while              # Pre increment caret while the condition below is true
        (                   # Bracket used so that you can declare/reassign values in a conditional
            @_ = sort {     # Sort the default array and store result back to default array
                $b - $a     # Sort from greatest to least (scalar variables a and b are default variables that come with sort)
            }@_             # Add the default array as a parameter for the sort
        ),                  # End of bracket (in scalar context like in this solution it will only grab the right most argument of the array so the while loop is entirely dependent on the condition below)
        !grep               # Only save values if the below statement is true for each item in default array then reverse the boolean (will return false if the size of the array after grep is greater than 0)
            --$_[$_] < 0,   # Check whether the pre decrement of item (default is $_) at the index of default array is less than 0. If the caret is out of range of the array, it will default to undef which is treated as 0 in math operations)
        0 .. $^             # Add an array of range 0 to caret inclusive to the grep
    ;                       # End of the while loop statement modifier
    $^                      # Return caret variable
}                           # End of subroutine

```

# Answer
> 9 votes
# Python 3, ~~96~~ ~~92~~ 91 bytes

```
f=lambda l,n=1:n<=len(l)and-~f([v-(e<n)for e,v in enumerate(sorted(l)[::-1])if(e<n)-v],n+1)

```

Try it online!

Simply "eats" \\$1\\$ each of the \\$n\\$ cookies with the largest amount each day, starting with \\$n=1\\$, until we don't have \\$n\\$ different cookies left. Returns the number of days this was successful.

### Explanation

```
f=lambda l,n=1:                   # function taking the list of
                                  # cookies l and day n
  n<=len(l)                       # if don't we have enough cookies for
                                  # today return False (0)
           and                    # if we do have enough cookies
              -~                  # return 1 plus
                f([...],n+1)      # our function called reclusively for
                                  # day n+1 with updated list:
         sorted(l)[::-1]          # of cookies sorted from most to least
       for e,v in enumerate(..)   # over the position and number of the
                                  # cookies
v-(e<n)                           # subtract 1 from the n largest
                                  # amount of cookies
                        if(e<n)-v # discarding empty amounts

```

# Answer
> 6 votes
# Python 2, ~~82~~ ~~77~~ 76 bytes

-5 bytes inspired by x1Mike7x's answer. (Adding a `0` to the cookie list at every iteration)
-1 byte thanks to dingledooper!

```
l=input()
i=0
while l.sort()<l>[0]:i-=1;l[i:]=[x-1for x in[1]+l[i:]]
print~i

```

Try it online!

# Answer
> 5 votes
# Jelly, ~~15~~ 14 bytes

```
‘ɼ-€+NÞƲAƑ¿ṛ®’

```

Try it online!

All testcases

## Explanation

```
‘ɼ-€+NÞƲAƑ¿ṛ®’  Main monadic link
          ¿     While
         Ƒ        invariant under
        A           absolute value
                  (that is, no numbers are negative)
                do
       Ʋ        (
 ɼ                Apply this to the register:
‘                   Increment
   €              Map [over the range 1..register]:
  -                 -1
    +             Add
                    the list
      Þ             sorted by
     N              negation
       Ʋ        )
           ṛ    Replace with
            ®   the register
             ’  Decrement

```

# Answer
> 5 votes
# JavaScript (ES6), 70 bytes

```
f=(a,c=d=0)=>c?d-1:f(a.sort((a,b)=>b-a).map(x=>c*x?x-!!c--:x,c=++d),c)

```

Try it online!

### Commented

```
f = (                  // f is a recursive function taking:
  a,                   //   a[] = list of cookies
  c =                  //   c   = cookies that were not eaten the day before
  d = 0                //   d   = day counter
) =>                   //
  c ?                  // if we failed to eat all the cookies the day before:
    d - 1              //   stop and return d - 1
  :                    // else:
    f(                 //   do a recursive call:
      a.sort((a, b) => //     sort the list of cookies ...
        b - a          //       ... from highest to lowest
      )                //
      .map(x =>        //     for each value x in the sorted list:
        c * x ?        //       if both c and x are not equal to 0:
          x - !!c--    //         decrement x and c
        :              //       else:
          x,           //         leave x unchanged
        c = ++d        //       start by incrementing d and setting c to d
      ),               //     end of map()
      c                //     pass c
    )                  //   end of recursive call

```

# Answer
> 5 votes
# Python 3.8, ~~88~~ ~~82~~ ~~81~~ 80 bytes

```
f=lambda a,n=-1:-1in(a:=sorted([0]+a))and-n-2or f([x-1for x in a[n:]]+a[:n],n-1)

```

Try it online!

Unwrapped version:

```
def f(a, n=-1):
    a = sorted([0] + a)
    if -1 in a:
        return -n - 2
    p = [x - 1 for x in a[n:]]
    q = a[:n]
    return f(p + q, n - 1)

```

# Answer
> 4 votes
# 05AB1E, 14 bytes

```
v{āNÌ‹R-Wds}\O

```

Try it online! or Try all cases!

**Commented:**

```
v          }     # for N in range(len(input))
 {               # sort the current cookie list (initially the input)
  ā              # push the range [1..len(list)]
   NÌ            # push N+2
     ‹           # is each value in the range less than N+2?
                 # this yields a list with N+1 leading ones
      R          # reverse the list of 1's and 0's
       -         # subtract this from the current cookie list
        Wds      # push min(list) >= 0 under the current list

            \    # after the loop: discard the final cookie list
             O   # sum the stack: this counts the number of times
                 #                the cookie counts were non-negative

```

# Answer
> 3 votes
# K (ngn/k), 32 bytes

```
{#(|/'0>)_x{x[y#>x]-:1;x}\1+!#x}

```

Try it online!

* `x{...}\1+!#x` set up a scan, seeded with `x` (the number of cookies of each type), run over `1..(number of types of cookies + 1)` (variable `y`)
    + `y#>x` identify the `n` cookies to eat (i.e., the `y` indices containing the largest values)
    + `{x[...]-:1;x}` eat those cookies, feeding the result into the next iteration of the scan
* `(|/'0>)_...` remove scan iteration results where there was any negative value
* `#...` return the count of the filtered results

# Answer
> 2 votes
# Stax, 19 bytes

```
ⁿ┘ª1µiZ&Xû¢♣◙2╜8æ≥/

```

Run and debug it

A direct implementation. Takes in golfscript arrays, but normal ones are supported as well.

## Explanation

```
{{No{i|i^<-mcc:@i^>wL%v
{                  w    do-while top of stack is true:
 {No                    sort descending
    {      m            map each element to:
     i|i^<              iteration index <= outer loop iteration index?
          -             subtract that form the element
            cc          copy twice
              :@        count of truthy elements
                i^<     < index+1?
                    L   wrap all arrays in stack
                     %v length decremented

```

# Answer
> 2 votes
# , 38 bytes

```
_1+1#.0*/"1@:<:[(-~\:~)/\.@|.@,(#$1:)\

```

Try it online!

For `1 2 2`:

```
(#$1:)\
1 0 0
1 1 0
1 1 1

[ … |.@,
1 1 1
1 1 0
1 0 0
1 2 2

   f   /\.    for each suffix, fold from bottom to top with f
(  /:~)       sort the remaining cookies (highest first),
 -~           subtract the needed cookies for the day:
0 0 _1
1 0  1
1 2  1
1 2  2

0*/"1@:<: does the row only contain numbers >= 0?
0 1 1 1

   1#.    count the 1s
_1+       minus one (the initial cookie row)
-> 2

```

# Answer
> 2 votes
# Pip, 20 bytes

```
TvNgg:RSNg+:vRL UiDi

```

Takes inputs as command-line arguments. Try it here!

The equivalent program in Pip Classic is **22 bytes**:

```
TvNgg:RVSNg+:vRL++i--i

```

Verify all test cases: Try it online!

### Explanation

```
TvNgg:RSNg+:vRL UiDi
                      g is list of cmdline args; v is -1; i is 0 (implicit)
T                     Loop until
 vNg                  there is a -1 in the cookie counts list:
      R                The reverse of
       SNg             the cookie counts list, sorted ascending
                       (in other words: the cookie counts list, sorted descending)
                Ui     Increment i and
            vRL        create a list of that many -1's
          +:           Add those two lists itemwise
    g:                 Assign the result back to g
                  Di  Decrement i and autoprint it

```

---

Here are two different approaches, also 20 bytes each:

```
Wi<#R:SN:FI:gDg@<Uii   Filter 0's out of the list at each step instead of checking for -1
L#gI(g:RSNgi)Dg@<Uii   Loop len(input) times; increment i only if there are enough cookies

```

# Answer
> 2 votes
# JavaScript (Node.js), 62 bytes

```
f=(c,d=0)=>c.sort((x,y)=>y-x)[d]?f(c,++d,c.map(x=>--c[--d])):d

```

Try it online!

The TIO setup is based on Arnauld's answer.

Seems greedy eating cookies with most copies works, though I don't know how to prove it (but that doesn't matter).

```
f = (
        c, // cookies (array of integers)
        d = 0 // day (integer)
    ) =>
    c.sort((x, y) => y - x) // sort cookies (desc order)
[d] ? // Is there enough kinds of cookie for today?
f(c, ++d, // Next iteration (day + 1)
    c.map(x => --c[--d]) // Eat 1 per each
    // greedy eat kinds with most copies
): d

```

# Answer
> 2 votes
# Haskell, 71 bytes

```
(0?)
n?a=maximum$n:[(n+1)?b|b<-mapM(\x->x:[x-1|x>0])a,sum b+n+1==sum a]

```

Try it online!

The relevant function is `(0?)`, which takes the list `a` of cookie quantities and returns the number of days.

Due to Haskell requiring `import Data.List` for sorting, I think bruteforce is the way to go.

# Answer
> 1 votes
# JavaScript (Node.js), ~~97 91 88 84 69~~ 63 bytes

```
f=(n,d=0)=>n.sort((a,b)=>b-a)[d]?f(n.map((e,i)=>e-=d>=i),d+1):d

```

Try it online!

## How it works

### Arguments

* `n` \[init: none\] - the array of cookie types
* `d` \[init: 0\] - the day number

### Function body

First, we check if there are enough truthy entries to "pick" cookies. If not we simply return the day count.

If there are enough, then from each element of the sorted list (descending) we subtract 1 if the index is low enough and the element is strictly positive. If not, leave the element as it is. Call `f` with the obtained array and an incremented day number.

I also realized that since `0` is falsey, we do not need to filter. PLEASE don't make the 69 joke, it's getting boring.

*-2 bytes thanks to @A username*

*-6 bytes thanks to @tsh*

# Answer
> 1 votes
# Retina 0.8.2, ~~31~~ 29 bytes

```
.+
$*
m{O^`^1*
1_
_
}1`1$
_
_

```

Try it online! Takes a newline-separated list, but link is to test suite that converts from comma-separated list for convenience. Explanation: Performs a slightly different calculation with the same result: on day `m` he eats up to `m` cookies, then when all the cookies have run out the desired answer is the most cookies he ate in any given day.

```
.+
$*

```

Convert to unary.

```
m{`
}`

```

Repeat until all the cookies have been eaten, and also evaluate the script in multiline mode.

```
O^`^1*

```

Sort the cookies in descending order.

```
1_
_

```

Try to eat the same number of cookies that were eaten the previous day.

```
1`1$
1_

```

Try to eat a new different cookie each day.

```
_

```

Count the maximum number of cookies eaten on any given day.

# Answer
> 1 votes
# Charcoal, 42 bytes

```
≔⁰ζＷ›Ｌθζ«≦⊕ζ≔⟦⟧ηＷ⌈⁻θηＦ№θκ⊞ηκ≔ΦＥη⁻κ‹λζκθ»Ｉζ

```

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

```
≔⁰ζ

```

Start with `n=0`.

```
Ｗ›Ｌθζ«

```

While there are enough different cookies:

```
≦⊕ζ

```

Increment `n`.

```
≔⟦⟧ηＷ⌈⁻θηＦ№θκ⊞ηκ

```

Sort the cookies into descending order.

```
≔ΦＥη⁻κ‹λζκθ

```

Decrement the first `n` cookies, removing entries that become zero.

```
»Ｉζ

```

Print the final value of `n`.

# Answer
> 1 votes
# , 86 bytes

```
function(b){while({b=-sort(-b);b=c(b[1:T]-1,b[-1:-T],0);T<=sum(b|1)&b[T]+1})T=T+1
T-1}

```

Try it online!

```
days_peter_keeps_box=
function(b){
  while({                       # Loop for each day peter has the box:
    b=-sort(-b)                 # sort the cookies with most-abundant types first,
    b=c(b[1:T]-1,b[-1:-T],0)    # take out 1 cookie from each of the first T types (initially 1),
    T<=length(b)                # now check: if T is greater than the number of cookie types
      &b[T]>-1                  # or any of the types have less than zero cookies left
                                # then we've gone one day too many... stop the loop;
  })T=T+1                       # otherwise increment T.
T-1}                            # When the loop is finished, output T-1.

```

# Answer
> 0 votes
# Core Maude, 257 bytes

```
fmod P is pr SORTABLE-LIST{Nat<}*(sort List{Nat<}to L). var L : L . var X
N :[L]. op b : L -> Nat . op _,_ : L Nat -> Nat . eq b(L)= L,0 . eq L,N =
d(sort(L),s N),s N . eq X,s N = N[owise]. op d : L Nat ~> L . eq d(L,0)=
L . eq d(L s N,s X)= d(L,X)N . endfm

```

### Example Session

```
             \||||||||||||||||||/
           --- Welcome to Maude ---
             /||||||||||||||||||\
         Maude 3.1 built: Oct 12 2020 20:12:31
         Copyright 1997-2020 SRI International
           Tue May 18 23:37:06 2021
Maude> fmod P is pr SORTABLE-LIST{Nat<}*(sort List{Nat<}to L). var L : L . var X
> N :[L]. op b : L -> Nat . op _,_ : L Nat -> Nat . eq b(L)= L,0 . eq L,N =
> d(sort(L),s N),s N . eq X,s N = N[owise]. op d : L Nat ~> L . eq d(L,0)=
> L . eq d(L s N,s X)= d(L,X)N . endfm
Maude> red b(1 2) .
reduce in P : b(1 2) .
rewrites: 37 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 2
Maude> red b(1 2 3) .
reduce in P : b(1 2 3) .
rewrites: 99 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 3
Maude> red b(2 2 2) .
reduce in P : b(2 2 2) .
rewrites: 96 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 3
Maude> red b(11 22 33 44 55 66 77 88 99) .
reduce in P : b(11 22 33 44 55 66 77 88 99) .
rewrites: 1045 in 0ms cpu (0ms real) (~ rewrites/second)
result NzNat: 9
Maude> red b(1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 6 6 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10 10 10) .
reduce in P : b(1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 3 3 3 3 3 3 3 3 3 4 4 4 4 4 4 4 4 4 4 4 4 5 5 5 5 5 5 5 5 5 5 5 5 6 6
    6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 7 7 7 7 8 8 8 8 8 8 8 8 8 8 8 8 9 9 9 9 9 9 9 9 9 9 9 9 10 10 10 10 10 10 10 10 10 10 10 10) .
rewrites: 82081 in 27ms cpu (27ms real) (2952129 rewrites/second)
result NzNat: 35

```

### Ungolfed

```
fmod P is
    pr SORTABLE-LIST{Nat<} * (sort List{Nat<} to L) .

    var L : L .
    var X N : [L] .

    op b : L -> Nat .
    op _,_ : L Nat -> Nat .
    eq b(L) = L, 0 .
    eq L, N = d(sort(L), s N), s N .
    eq X, s N = N [owise] .

    op d : L Nat ~> L .
    eq d(L, 0) = L .
    eq d(L s N, s X) = d(L, X) N .
endfm

```

This program accepts input via a function `b` which takes a list of natural numbers. The function `d` will "eat" cookies for each step, and it the program runs until the list term is no longer a well-formed list of natural numbers, then returns the index of the previous step.

# Answer
> 0 votes
# Haskell, 114 bytes

```
import Data.List;p i k|i<length(filter(>0)k)=p(i+1).zipWith(-)(sort k)$replicate(length k-i-1)0++repeat 1|0<1=i---

```

Try it online!

---

Uses an algorithm of order \\$\mathcal O(m\cdot n\ln n)\\$ where \\$m\\$ is the maximum number of cookies of one kind and \\$n\\$ is the input list's size: On day \\$d\\$, sort all remaining cookies by their quantity and remove the \\$d\\$ cookies of whose kinds there are the most, if possible. Else, this day is the one sought after. If on the other hand the removal was successful, go on to day \\$d+1\\$.

---
Tags: code-golf
---