23
\$\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\$
  • 15
    \$\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 Nov 23 '15 at 23:26
  • 1
    \$\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 Nov 23 '15 at 23:27
  • 9
    \$\begingroup\$ Welcome to PPCG! Great first challenge! \$\endgroup\$ – Conor O'Brien Nov 23 '15 at 23:56
  • 2
    \$\begingroup\$ Can we write functions? \$\endgroup\$ – Downgoat Nov 23 '15 at 23:57
  • 10
    \$\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\$ – Mego Nov 24 '15 at 0:15

35 Answers 35

1
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ chr and ord are not in Prelude, so according to our golfing rules you need to include the import Data.Char in your byte count. In better news, you can drop f[]=[];f[c]=[c] and add f e=e as last line to save some bytes. \$\endgroup\$ – Laikoni Aug 11 '18 at 13:45
  • \$\begingroup\$ Wait, you can only shorten f[]=[] to f e=e, otherwise init throws an error. \$\endgroup\$ – Laikoni Aug 11 '18 at 13:53
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\$
  • \$\begingroup\$ l%2-!!l instead of -!(!l+l%2) for 51 bytes \$\endgroup\$ – vazt Aug 8 '18 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 Dec 21 '18 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\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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