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>
-
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– Downgoat2015年11月23日 23:26:49 +00:00Commented 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– Ypnypn2015年11月23日 23:27:29 +00:00Commented Nov 23, 2015 at 23:27
-
9\$\begingroup\$ Welcome to PPCG! Great first challenge! \$\endgroup\$Conor O'Brien– Conor O'Brien2015年11月23日 23:56:19 +00:00Commented Nov 23, 2015 at 23:56
-
3\$\begingroup\$ Can we write functions? \$\endgroup\$Downgoat– Downgoat2015年11月23日 23:57:18 +00:00Commented 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– user459412015年11月24日 00:15:51 +00:00Commented Nov 24, 2015 at 0:15
42 Answers 42
Pyth, 15 bytes
Cs.O@R/lz2_BCMz
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.
-
\$\begingroup\$
Bifurcate shows its utility again. \$\endgroup\$lirtosiast– lirtosiast2015年11月24日 03:37:14 +00:00Commented Nov 24, 2015 at 3:37 -
\$\begingroup\$ whoa bifurcate is awesome. \$\endgroup\$Maltysen– Maltysen2015年11月25日 00:58:25 +00:00Commented Nov 25, 2015 at 0:58
-
\$\begingroup\$ @KenanRhoton In response to your proposed edit, check out the commit that added the
Cflooring functionality: github.com/isaacg1/pyth/commit/0baf23ec Notice the day it was added, the same day this question was asked. That's because this question inspired me to add that functionality, making it ineligible for use on this question. \$\endgroup\$izzyg– izzyg2016年09月27日 15:28:03 +00:00Commented Sep 27, 2016 at 15:28
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.
蜐蕈帑聿纂胯箩悚衅鹊颂鹛拮拮氰人
-
5\$\begingroup\$
Given each instruction could be compressed to 3 bits and encoded in UTF64, the whole program could technically be expressed in 3 characters.You win. The internet. And everything else. \$\endgroup\$cat– cat2015年11月24日 04:12:00 +00:00Commented Nov 24, 2015 at 4:12 -
2\$\begingroup\$ I don't think this is valid. Brainfuck source code is the characters
+-<>,.[], in whatever encoding, not their binary representations. We have a consensus that an encoding that can't be used by an existing interpreter is invalid. \$\endgroup\$lirtosiast– lirtosiast2015年11月24日 05:34:03 +00:00Commented Nov 24, 2015 at 5:34 -
2\$\begingroup\$ @ThomasKwa, hence I gave my score primarily in un-encoded bytes. The character encoding was just joining in the idea that scoring by characters can be abused. \$\endgroup\$Hand-E-Food– Hand-E-Food2015年11月24日 05:42:51 +00:00Commented Nov 24, 2015 at 5:42
-
4\$\begingroup\$ @ThomasKwa : it's time for some of us to make such an interpreter, to be used in future challenges. Imagine BF beating the best golfscript solution! :) \$\endgroup\$vsz– vsz2015年11月24日 07:25:39 +00:00Commented Nov 24, 2015 at 7:25
-
2\$\begingroup\$ @vsz esolangs.org/wiki/Chinese \$\endgroup\$John Dvorak– John Dvorak2015年11月25日 11:35:08 +00:00Commented Nov 25, 2015 at 11:35
CJam, 16 bytes
q:i_W%.+_,2/=2/c
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.
-
9\$\begingroup\$ Why almost any CJam/Pyth golf is 10-30 chars no matter the difficulty? O.o \$\endgroup\$Zereges– Zereges2015年11月23日 23:37:12 +00:00Commented Nov 23, 2015 at 23:37
-
1\$\begingroup\$ Difficulty? This is a simple median calculation, minus the sorting... \$\endgroup\$Dennis– Dennis2015年11月24日 00:37:50 +00:00Commented Nov 24, 2015 at 0:37
-
4\$\begingroup\$ @Dennis I think that's what he means. It can be about the same length for both easier and harder questions. \$\endgroup\$geokavel– geokavel2015年11月24日 01:12:23 +00:00Commented Nov 24, 2015 at 1:12
-
\$\begingroup\$ @Zereges Not really. 10-30 is typical for easy problems. See this if you want an example of how it looks for something more complex: codegolf.stackexchange.com/a/64086/32852. \$\endgroup\$Reto Koradi– Reto Koradi2015年11月24日 04:32:26 +00:00Commented Nov 24, 2015 at 4:32
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.
-
\$\begingroup\$ Ah, you beat me to what my next task was going to be (had I not found 10 bytes to shave off) \$\endgroup\$cat– cat2015年11月24日 02:00:59 +00:00Commented Nov 24, 2015 at 2:00
-
\$\begingroup\$ No, no, 10 bytes to shave off my 166 byte Go solution. Yours is far more elegant, however. \$\endgroup\$cat– cat2015年11月24日 02:05:08 +00:00Commented Nov 24, 2015 at 2:05
-
\$\begingroup\$
-1-len(x)//2is equivalent to~len(x)//2because of how floor division works on negative integers. \$\endgroup\$xsot– xsot2015年11月24日 04:43:11 +00:00Commented Nov 24, 2015 at 4:43 -
\$\begingroup\$ @xsot Thanks—it makes the code a little more evil though :) \$\endgroup\$lirtosiast– lirtosiast2015年11月24日 05:28:40 +00:00Commented Nov 24, 2015 at 5:28
TeaScript, 23 bytes (削除) 25 30 31 33 (削除ここまで)
2(x[t=xn/2]c+xv[t]c)/2)
Uses @isaacg's idea of reversing the string.
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
-
5\$\begingroup\$ That kerning... \$\endgroup\$lirtosiast– lirtosiast2015年11月24日 00:30:55 +00:00Commented Nov 24, 2015 at 0:30
-
10\$\begingroup\$ That header is rad. I want that header for every goddamn language. \$\endgroup\$cat– cat2015年11月24日 00:31:15 +00:00Commented Nov 24, 2015 at 0:31
-
\$\begingroup\$ Yeah, except the kerning. \$\endgroup\$cat– cat2015年11月24日 00:31:36 +00:00Commented Nov 24, 2015 at 0:31
-
\$\begingroup\$ @sysreq lol, it had to do with the fact I'm using a different font, fixed. \$\endgroup\$Downgoat– Downgoat2015年11月24日 00:39:36 +00:00Commented Nov 24, 2015 at 0:39
-
12\$\begingroup\$ Please tell me will work. \$\endgroup\$jado– jado2015年11月24日 02:13:12 +00:00Commented Nov 24, 2015 at 2:13
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.
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]))))
Husk, 11 bytes
c1⁄2S¤+öc→←1⁄2↔
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→←1⁄2 [TChar]->TInt ASCII code of middle (floored) char in string
¤+öc→←1⁄2 [TC]->[TC]->TI Sum of ASCII codes of middle of two strings
S¤+öc→←1⁄2↔ [TC]->TI Sum of ASCII codes of the middle of a string and its reverse
c1⁄2S¤+öc→←1⁄2↔ [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: Ṡ&ö;c1⁄2S¤+öc→←1⁄2↔, 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.
-
\$\begingroup\$ Huh, I tried this: Try it online! \$\endgroup\$Razetime– Razetime2020年10月23日 14:19:29 +00:00Commented Oct 23, 2020 at 14:19
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
R, 73 bytes
function(x,y=utf8ToInt(x),n=sum(1|y))if(n)intToUtf8(mean(y[n/2+c(1,.5)]))
Many thanks to @ngm for coming up with this non-recursive idea - allowed to golf 20 bytes.
Old solution:
R, (削除) 101 (削除ここまで) 95 bytes
"!"=function(x,n=sum(1|x))"if"(n<3,mean(x),!x[-c(1,n)])
try(intToUtf8(!utf8ToInt(scan(,""))),T)
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 !
-
\$\begingroup\$ doesn't
intToUtf8truncate non-integers? \$\endgroup\$Giuseppe– Giuseppe2018年08月09日 14:57:19 +00:00Commented Aug 9, 2018 at 14:57 -
\$\begingroup\$ @Giuseppe you are right as always :) \$\endgroup\$JayCe– JayCe2018年08月09日 15:04:29 +00:00Commented Aug 9, 2018 at 15:04
-
-
-
\$\begingroup\$ Well, I wouldn't have come up with it unless you had put the original effort in. And my answer was a port of the top vote-getting Pyth answer. With a bunch of tricks we R people have come up. And then you made it shorter. So go ahead and make the edit with a clear conscience! \$\endgroup\$ngm– ngm2018年08月09日 16:47:18 +00:00Commented Aug 9, 2018 at 16:47
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
}
-
\$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ done. \$\endgroup\$Zereges– Zereges2015年11月24日 00:15:23 +00:00Commented Nov 24, 2015 at 0:15
-
\$\begingroup\$ I don't think you can output with the character code, and I don't think you can output
0for "" either. \$\endgroup\$lirtosiast– lirtosiast2015年11月24日 17:46:29 +00:00Commented Nov 24, 2015 at 17:46 -
\$\begingroup\$ It would be nice to have apparent rules. \$\endgroup\$Zereges– Zereges2015年11月24日 19:17:58 +00:00Commented Nov 24, 2015 at 19:17
-
\$\begingroup\$ 54 bytes \$\endgroup\$ceilingcat– ceilingcat2019年06月19日 03:38:00 +00:00Commented Jun 19, 2019 at 3:38
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.
-
\$\begingroup\$ You beat me to it. Oh well, least I can do is help you ;)
s=>String.fromCharCode((s[~~(t=s.length/2-.5)][r="charCodeAt"]()+s[Math.ceil(t)][r])/2)is 5 bytes shorter. \$\endgroup\$Conor O'Brien– Conor O'Brien2015年11月24日 00:10:39 +00:00Commented Nov 24, 2015 at 0:10 -
\$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ Sweet. I need the
()aroundcharCodeAtso it's really 3 chars,but thanks anyway! \$\endgroup\$Downgoat– Downgoat2015年11月24日 00:14:32 +00:00Commented Nov 24, 2015 at 0:14 -
\$\begingroup\$ @ןnɟuɐɯɹɐןoɯ if
tis an integer that won't work \$\endgroup\$Downgoat– Downgoat2015年11月24日 00:36:29 +00:00Commented Nov 24, 2015 at 0:36 -
\$\begingroup\$
Math.ceil(t)can be changed to0|t+.9\$\endgroup\$ETHproductions– ETHproductions2015年11月24日 01:37:08 +00:00Commented Nov 24, 2015 at 1:37 -
\$\begingroup\$ I get
TypeError: s[~(~((intermediate value)))] is undefinedfor an empty string \$\endgroup\$rink.attendant.6– rink.attendant.62015年11月25日 09:14:58 +00:00Commented Nov 25, 2015 at 9:14
O, (削除) 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)
-
7\$\begingroup\$ I'm sure you posted an ungolfed version to say that ;) \$\endgroup\$Conor O'Brien– Conor O'Brien2015年11月24日 00:12:22 +00:00Commented Nov 24, 2015 at 0:12
-
4\$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ I just got lucky :D \$\endgroup\$jado– jado2015年11月24日 00:13:30 +00:00Commented Nov 24, 2015 at 0:13
Vyxal K, 8 bytes
‡ḢṪ↔Ṫtṁ⌊
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
Minkolang 0.13, (削除) 23 (削除ここまで) 20 bytes
$oI2$%d$z,-Xz3&+2:O.
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.
-
1\$\begingroup\$
hiyareturnsiinstead ofq\$\endgroup\$Downgoat– Downgoat2015年11月24日 00:02:49 +00:00Commented Nov 24, 2015 at 0:02 -
\$\begingroup\$ @Vɪʜᴀɴ: OH. I misread it. I thought the question was asking for the character in the middle, going to the floored average position if the length was even. \$\endgroup\$El'endia Starman– El'endia Starman2015年11月24日 00:27:26 +00:00Commented Nov 24, 2015 at 0:27
-
\$\begingroup\$ @ThomasKwa: Fixed. \$\endgroup\$El'endia Starman– El'endia Starman2015年11月24日 00:51:19 +00:00Commented Nov 24, 2015 at 0:51
-
\$\begingroup\$ @Vɪʜᴀɴ: ^ Fixed. \$\endgroup\$El'endia Starman– El'endia Starman2015年11月24日 00:52:09 +00:00Commented Nov 24, 2015 at 0:52
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!
-
\$\begingroup\$ The reverse thing is brilliant +1 \$\endgroup\$Downgoat– Downgoat2015年11月24日 01:33:25 +00:00Commented Nov 24, 2015 at 1:33
-
\$\begingroup\$ Couldn't you just do
V=Ul /2;((UcV +Uw cV )/2 d? \$\endgroup\$Mama Fun Roll– Mama Fun Roll2015年11月24日 01:53:57 +00:00Commented Nov 24, 2015 at 1:53 -
\$\begingroup\$ @ןnɟuɐɯɹɐןoɯ Well, duh :P I've used
cso many times without an argument that I forgot it accepted one. Thanks! \$\endgroup\$ETHproductions– ETHproductions2015年11月24日 02:19:53 +00:00Commented Nov 24, 2015 at 2:19
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]))
}
}
}
ESMin, 23 chars
a=ïꝈ/2,ϚĎ((ïüa+ᴙïüa)/2)
Thanks to @ETHProductions for the idea!
-
2\$\begingroup\$ Lucky, a challenge measured in chars instead of bytes ;) \$\endgroup\$ETHproductions– ETHproductions2015年11月24日 02:51:13 +00:00Commented Nov 24, 2015 at 2:51
-
\$\begingroup\$ Oh yay! We're all tied. \$\endgroup\$Mama Fun Roll– Mama Fun Roll2015年11月24日 03:34:18 +00:00Commented Nov 24, 2015 at 3:34
-
\$\begingroup\$ Whoever downvoted this, could I please get an explanation? \$\endgroup\$Mama Fun Roll– Mama Fun Roll2015年11月24日 14:21:12 +00:00Commented Nov 24, 2015 at 14:21
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.
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...
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.
-
\$\begingroup\$ Drop
Average(...,...)and use(...+...)/2for -5 bytes.=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)),"")\$\endgroup\$Taylor Raine– Taylor Raine2018年08月08日 11:01:08 +00:00Commented Aug 8, 2018 at 11:01 -
\$\begingroup\$ Excel will accept (and floor) a non-integer second argument to MID, so you don't have to split it into cases -
=IFERROR(CHAR(CODE(MID(A1,LEN(A1)/2+1,1))/2+CODE(MID(A1,LEN(A1)/2+.5,1))/2),"")for 79 bytes \$\endgroup\$Sophia Lechner– Sophia Lechner2018年08月09日 21:12:50 +00:00Commented Aug 9, 2018 at 21:12
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
-
\$\begingroup\$
chrandordare not in Prelude, so according to our golfing rules you need to include theimport Data.Charin your byte count. In better news, you can dropf[]=[];f[c]=[c]and addf e=eas last line to save some bytes. \$\endgroup\$Laikoni– Laikoni2018年08月11日 13:45:54 +00:00Commented Aug 11, 2018 at 13:45 -
\$\begingroup\$ Wait, you can only shorten
f[]=[]tof e=e, otherwiseinitthrows an error. \$\endgroup\$Laikoni– Laikoni2018年08月11日 13:53:04 +00:00Commented Aug 11, 2018 at 13:53
Jelly, 7 bytes
JÆṁị1Æm
Takes input as a list of codepoints. Outputs a single codepoint.
How it works
JÆṁị1Æm - Main link. Takes a string S on the left
J - Indices of S
Æṁ - Median
1 - 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.
Mathematica, (削除) 118 (削除ここまで) 99 chars
Floor
If[#=="","",FromCharacterCode[%@Mean@#[[Ceiling[l=Length@#/2];;%[l+1]]]&@ToCharacterCode@#]]&
Mma character code manipulation is pricey...
-
\$\begingroup\$ This function only works once, unless you repeat the entire code each time you want to call it. The point of function submissions is for them to be reusable. Calling your function breaks the value of the global
%which it relies on. \$\endgroup\$Martin Ender– Martin Ender2015年11月30日 12:26:15 +00:00Commented Nov 30, 2015 at 12:26 -
1\$\begingroup\$ Why not use the shortened forms of Floor and Ceiling? \$\endgroup\$DavidC– DavidC2016年09月27日 14:42:46 +00:00Commented Sep 27, 2016 at 14:42
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 ASCIIasc()values of the 2 Characters divided by 2 and return the ASCII Characterchr()based on that value.
I think I can golf away one of the asc() calls, but couldn't get it to work shorter.
K, 40 bytes
{(*|r;`c$_(+/r:2#l_x)%2)@l=_l:-1+(#x)%2}
><>, 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.
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
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)||''
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