27
\$\begingroup\$

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>

\$\endgroup\$
11
  • 17
    \$\begingroup\$ Usually we score in bytes so people can't compress their entire code, as this results in boring solutions. Are you sure you want this? \$\endgroup\$
    – Downgoat
    Commented Nov 23, 2015 at 23:26
  • 2
    \$\begingroup\$ @Vɪʜᴀɴ I don't think that will be a problem here, since solutions will be very short anyway, so compressing won't be worth it. \$\endgroup\$
    – Ypnypn
    Commented Nov 23, 2015 at 23:27
  • 9
    \$\begingroup\$ Welcome to PPCG! Great first challenge! \$\endgroup\$ Commented Nov 23, 2015 at 23:56
  • 3
    \$\begingroup\$ Can we write functions? \$\endgroup\$
    – Downgoat
    Commented Nov 23, 2015 at 23:57
  • 11
    \$\begingroup\$ Pro-tip: encode your answers in UTF-32. 4 bytes per character. Or maybe the OP should just get rid of the character scoring. \$\endgroup\$
    – user45941
    Commented Nov 24, 2015 at 0:15

40 Answers 40

1
2
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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...

\$\endgroup\$
3
  • \$\begingroup\$ <?=($l=strlen($s=$argv[1]))%2?$s[($l-1)/2]:chr(floor((ord($s[$l/2])+ord($s[$l/2-1]))/2)); is my proposal \$\endgroup\$ Commented Sep 27, 2016 at 23:10
  • \$\begingroup\$ @JörgHülsermann Brilliant golfing! You should post it as your own answer. If I have time I will golf my answer more with your nice solutions. Thanks. \$\endgroup\$
    – Mario
    Commented Sep 28, 2016 at 14:17
  • \$\begingroup\$ Feel free to take it as your answer \$\endgroup\$ Commented Sep 28, 2016 at 14:23
0
\$\begingroup\$

Seriously, 22 20 bytes

,O3 >WXXaXa3 >WXkæ≈c

Thanks @Mego for being great at your language

Try it online or whatever

\$\endgroup\$
8
  • 1
    \$\begingroup\$ This fails for empty input. I have a deleted 20-byte solution which I'm also trying to fix for empty input. \$\endgroup\$
    – lirtosiast
    Commented Nov 24, 2015 at 5:25
  • \$\begingroup\$ ,;``@(lIƒ will leave you with the input value on the stack if its len is > 0, or terminate the program otherwise. Note that there's an unprintable in the backticks - character 127. \$\endgroup\$
    – user45941
    Commented Nov 24, 2015 at 15:46
  • \$\begingroup\$ @Mego This doesn't seem to be working. \$\endgroup\$
    – jado
    Commented Nov 24, 2015 at 19:36
  • \$\begingroup\$ @phase You gotta quote strings for input. This works. \$\endgroup\$
    – user45941
    Commented Nov 24, 2015 at 19:42
  • \$\begingroup\$ @Mego What is the ƒ supposed to do? \$\endgroup\$
    – jado
    Commented Nov 24, 2015 at 19:56
0
\$\begingroup\$

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?
\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$
2
  • \$\begingroup\$ l%2-!!l instead of -!(!l+l%2) for 51 bytes \$\endgroup\$
    – vazt
    Commented Aug 8, 2018 at 15:29
  • \$\begingroup\$ Suggest s=s[l/2]+s[~-l/2+!l]>>1 instead of s+=l/2;s=*s+s[l%2-!!l]>>1 \$\endgroup\$
    – ceilingcat
    Commented Dec 21, 2018 at 2:58
0
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

Japt, 15 bytes

cUÊz)dUÔcUÊz¹cz

Try it

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
3
  • 1
    \$\begingroup\$ This fails for Hiya. The correct output should be q (113 as ord) \$\endgroup\$ Commented May 13, 2021 at 20:10
  • \$\begingroup\$ @cairdcoinheringaahing Hmm, good point. I wonder why... I'm looking into it. \$\endgroup\$
    – Makonede
    Commented May 13, 2021 at 20:12
  • 1
    \$\begingroup\$ It fails because this isn't the median, it's the middle. Median sorts its input \$\endgroup\$ Commented May 13, 2021 at 20:13
0
\$\begingroup\$

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?

\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.