49
\$\begingroup\$

The challenge is simple:

Write a function or program that takes an input x, and outputs the lower case alphabet if x is part of the lower case alphabet, outputs the upper case alphabet if x is part of the upper case alphabet and outputs just x if it's not part of either.

Rules:

  • The input can be function argument or from STDIN
  • The input will be any of the printable ASCII characters from 32 to 126 (space to tilde).
  • The input may be inside quotation marks,'x' or "x", but remember that ' and " are valid input and should be supported.
  • The input can be any of the letters in the alphabet, i.e. you can't assume it will be a or A.
  • The output should be only one of the alphabets or the single symbol, but trailing newlines are OK.
  • The letters in the alphabet should not be separated by spaces, commas or anything else.

Some examples:

F
ABCDEFGHIJKLMNOPQRSTUVWXYZ

z
abcdefghijklmnopqrstuvwxyz

"
"

    <- Input:  Space
    <- Output: Space

Shortest code in bytes win.


Optional but appreciated: If your language has an online interpreter, please also post a link so that it can be easily tested by others.


Leaderboard

The Stack Snippet at the bottom of this post generates the catalog 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 bytes

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 bytes

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 bytes

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

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

var QUESTION_ID=67357,OVERRIDE_USER=44713;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<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="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><div id="language-list"> <h2>Winners 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><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>

\$\endgroup\$
  • \$\begingroup\$ Are we allowed to import packages like, in Python for example: import Random and then use Random.randint (obviously not for this challenge but still)? \$\endgroup\$ – Daniel Dec 22 '15 at 15:28
  • \$\begingroup\$ Yes, you may import packages. but the bytes for writing for instance import string are counted, thus it's often better to do workarounds. Note that the package must exist before the challenge is posted. Many challenges have something like: "Using packages that does this is not allowed", but that is not the case in this challenge. \$\endgroup\$ – Stewie Griffin Dec 22 '15 at 15:36
  • \$\begingroup\$ I'm assuming that by "quotes are valid input and must be supported" you mean that if your input method requires quotes then quotes as input would be escaped \$\endgroup\$ – Cyoce Dec 23 '15 at 5:10
  • \$\begingroup\$ May we assume a REPL environment? \$\endgroup\$ – cat Dec 23 '15 at 17:38

65 Answers 65

22
\$\begingroup\$

TeaScript, 5 bytes

xN(0)

TeaScript has a (almost) built-in for this :D

Try it online (note: the online interpreter has been updated to TeaScript v3 so in which this is N0)

Try all the test cases


TeaScript 3, 2 bytes [non-competing]

Using TeaScript 3, this can become 2-bytes. This is non-competing because TeaScript 3 was made after this challenge

N0

1 byte alternative

If we could output 0123456789 for digits, then this could be:

°
\$\endgroup\$
  • \$\begingroup\$ TeaScript 3 is valid. So, you may use it! \$\endgroup\$ – user75200 Nov 2 '17 at 13:06
27
\$\begingroup\$

Pyth, 10 bytes

h/#z[GrG1z

Test suite

We start by constructing a list with 3 elements: the lowercase alphabet, the uppercase alphabet, and the input. ([GrG1z) Then, we filter this list on the number of appearances of the input in the elements being nonzero. (/#z) Finally, we take the first element of the filtered list.

\$\endgroup\$
  • 6
    \$\begingroup\$ Seriously, is there anything you couldn't solve with a few bytes of Pyth? I really need to learn this language.. \$\endgroup\$ – Hexaholic Dec 22 '15 at 17:49
  • 26
    \$\begingroup\$ Learn which language?...you mentioned two by name. :P \$\endgroup\$ – quintopia Dec 22 '15 at 18:21
  • 2
    \$\begingroup\$ @quintopia Well, why not both? :) \$\endgroup\$ – Hexaholic Dec 22 '15 at 21:16
  • \$\begingroup\$ Holy cow, this is clever! I just went with the obvious solution of ternary statements, which ended up being 14 bytes ?}zGG?}zKrG1Kz \$\endgroup\$ – Tornado547 Dec 2 at 21:28
15
\$\begingroup\$

LabVIEW, 23 LabVIEW Primitives

The selector (the ? on the cse structure) is connected to a vi that is called Lexical Class. It ouputs numbers from 1-6 depending on input, 5 is lower case 4 is upper case.

The for loop goes 26 times to create an alphabet or once to pass the symbol through.

\$\endgroup\$
  • 4
    \$\begingroup\$ As someone who had the (privilege? misfortune? you decide) of working in LabVIEW many years ago, your answers bring a smile to my day. =) \$\endgroup\$ – corsiKa Dec 22 '15 at 16:26
12
\$\begingroup\$

Haskell, 48 bytes

f c=filter(elem c)[['a'..'z'],['A'..'Z'],[c]]!!0

Usage example:

*Main> f 'g'
"abcdefghijklmnopqrstuvwxyz"
*Main> f 'H'
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
*Main> f '\''
"'"

Take all lists of ['a'..'z'], ['A'..'Z'] and the singleton list with the input char c where c is element of. For letters we have always two matches, so we pick the first one.

\$\endgroup\$
11
\$\begingroup\$

JavaScript (ES6), 79 bytes

x=>(a="abcdefghijklmnopqrstuvwxyz",x>"`"&x<"{"?a:x>"@"&x<"["?a.toUpperCase():x)

Explanation

JavaScript compares the code of each character alphabetically when comparing strings, so the codes of the characters used in the comparisons are 1 below and above the required range of characters.

x=>(
  a="abcdefghijklmnopqrstuvwxyz", // a = lower-case alphabet
  x>"`"&x<"{"?a:                  // if x is a lower-case letter, output alphabet
  x>"@"&x<"["?a.toUpperCase():    // if x is an upper-case letter, output upper-case
  x                               // else just output x
)

Test

var solution = x=>(a="abcdefghijklmnopqrstuvwxyz",x>"`"&x<"{"?a:x>"@"&x<"["?a.toUpperCase():x)
X = <input type="text" oninput="result.textContent=solution(this.value)" />
<pre id="result"></pre>

\$\endgroup\$
  • \$\begingroup\$ Is that actually the shortest way to produce a string with the entire alphabet in Javascript? If you wanted the entire printable ASCII-range, would you have to type every single character? \$\endgroup\$ – Stewie Griffin Dec 22 '15 at 8:54
  • 1
    \$\begingroup\$ @StewieGriffin Sadly it is. The only other way would be something like: for(a="",i=64;++i<91;)a+=String.fromCharCode(i). String.fromCharCode is very unsuitable for golfing, but sometimes it's the only way! \$\endgroup\$ – user81655 Dec 22 '15 at 8:56
  • 4
    \$\begingroup\$ In this case the balance is between String.fromCharCode and .toUpperCase (Dumb and Dumber) but toUpperCase is the winner \$\endgroup\$ – edc65 Dec 22 '15 at 9:27
  • \$\begingroup\$ Nice! I've tried a few different ways of golfing this further, but haven't found one that works. x=>x.replace(/[A-Z]/i,c=>c>"`"?a:a.toUpperCase(),a="abcdefghijklmnopqrstuvwxyz") does, but is one byte longer. Changing [A-Z] to \w works for everything except _. Your solution seems to be the shortest possible. \$\endgroup\$ – ETHproductions Dec 22 '15 at 18:51
  • \$\begingroup\$ Here's one of the shortests way to generate ABC...abc...? without a real for loop: (some padding) [for(_ of[...Array(i=64)])if(i++%32<26)String.fromCharCode(i)].join``+x \$\endgroup\$ – ETHproductions Dec 22 '15 at 19:34
8
\$\begingroup\$

R, 90 75 bytes

a=scan(,'');l=letters;L=LETTERS;cat("if"(a%in%l,l,"if"(a%in%L,L,a)),sep="")

Thanks to Giuseppe.

Old version (90 bytes):

a=scan(,'');l=letters;L=LETTERS;if(a%in%l)cat(l,sep="")else if(a%in%L)cat(L,sep="")else a

Looks ugly, but those cats cannot be outsourced to functions, IMHO.

\$\endgroup\$
  • \$\begingroup\$ 75 bytes \$\endgroup\$ – Giuseppe Nov 9 '17 at 22:04
  • \$\begingroup\$ 73 bytes: the 2nd parameter of scan can be any object of type character, so you can letters instead of ''. \$\endgroup\$ – Robin Ryder Sep 7 at 17:34
7
\$\begingroup\$

Python 3, 92 84 82 74 bytes

Current version: 74, thanks to isaacg and wnnmaw!

lambda c:(c,''.join(chr(x+(67,97)[c>'Z'])for x in range(25)))[c.isalpha()]

Ungolfed: (for some definition of ungolfed

lambda c:
    (
        c,
        ''.join([chr(x + (67,97)[c > 'Z']) for x in range(25)])
    )
    [c.isalpha()]

First version: 92

def f(c):print(''.join([chr(x+(97if c>'Z'else 65)) for x in range(25)])if c.isalpha()else c)

Second version: 82, thanks to isaacg! :)

lambda c:''.join(chr(x+(97if c>'Z'else 65))for x in range(25))if c.isalpha()else c
\$\endgroup\$
  • \$\begingroup\$ Hi, and welcome to PPCG! Nice answer. Here's a golfing suggestion: You can use a lambda expression (lambda c:) instead of an explicit definition (def f(c):print(), and save some bytes. Also, you don't need the space before the for. \$\endgroup\$ – isaacg Dec 22 '15 at 11:09
  • \$\begingroup\$ Ah, I assumed "output" to mean print, and not just return :) Neat, if that's the case it's down to 84, lambda c:''.join([chr(x+(97if c>'Z'else 65))for x in range(25)])if c.isalpha()else c. Thanks! \$\endgroup\$ – Koneke Dec 22 '15 at 11:20
  • \$\begingroup\$ Yeah, the standard definition of output on the site allow returning from functions, so you can edit the new version into your answer. Another golf is that the brackets aren't necessary - the function works exactly the same without them, as a generator comprehension instead of a list comprehension. \$\endgroup\$ – isaacg Dec 22 '15 at 11:23
  • \$\begingroup\$ Ah, haven't actually used generator comprehensions before, learning new things! Thanks again :) \$\endgroup\$ – Koneke Dec 22 '15 at 11:27
  • \$\begingroup\$ Note that when inputing " to the function, you need \" instead. \$\endgroup\$ – Daniel Dec 22 '15 at 16:50
6
\$\begingroup\$

Python 3, 118 105 98 97 83 bytes

Simple solution. EDIT: Golfed with thanks to Erik the Golfer's suggestion.

lambda s,a='ABCDEFGHIJKLMNOPQRSTUVWXYZ':(s,(a,a.lower())[s.islower()])[s.isalpha()]

Ungolfed:

def f(s):
 a='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
 if s.isalpha():
  if s.islower():return a.lower()
  else:return a
 return s
\$\endgroup\$
  • 1
    \$\begingroup\$ Could you use a ternary operator to save a few bytes? Something like return a.lower() if s.islower() else a. \$\endgroup\$ – David Robertson Dec 22 '15 at 13:00
  • \$\begingroup\$ @DavidRobertson I'm not sure if you're reading my solution, which is the top line of code, correctly, but that is exactly what I'm doing. \$\endgroup\$ – Sherlock9 Dec 22 '15 at 13:57
  • \$\begingroup\$ Ah! I was reading the ungolfed version. Sorry about that! \$\endgroup\$ – David Robertson Dec 22 '15 at 14:40
  • \$\begingroup\$ @DavidRobertson Not a problem \$\endgroup\$ – Sherlock9 Dec 22 '15 at 15:21
  • \$\begingroup\$ Golfed: lambda s,a='abcdefghijklmnopqrstuvwxyz':(s,(a,a.upper())[s.isupper()])[s.isalpha()] \$\endgroup\$ – Erik the Outgolfer Jul 22 '16 at 10:04
5
\$\begingroup\$

PHP, 62 76 82 bytes

PHP is doing OK now:

<?=ctype_alpha($x=$argv[1])?join(range(Z<$x?a:A,Z<$x?z:Z)):$x;

Takes an input from command line, like:

$ php alphabet.php A
$ php alphabet.php "a"
$ php alphabet.php " "
$ php alphabet.php _

Edits

  • Saved 6 bytes by replacing 91>ord($x) with Z<$x. Thought way to complicated. Thanks to manatwork.
  • Saved 14 bytes by removing strtoupper and building the demanded range directly.
\$\endgroup\$
  • \$\begingroup\$ That ord() looks bad there. Try Z<$x?$a:strtoupper($a). \$\endgroup\$ – manatwork Dec 22 '15 at 12:23
  • \$\begingroup\$ @manatwork Haha, I've thought way to complicated in that second part. Thanks to point it out. \$\endgroup\$ – insertusernamehere Dec 22 '15 at 19:13
  • \$\begingroup\$ Try ' '&$x^A to make uppercase and lowercase a and z. That is, your code becomes <?=ctype_alpha($x=$argv[1])?join(range(' '&$x^A,' '&$x^Z)):$x; \$\endgroup\$ – Ismael Miguel Dec 23 '15 at 23:33
  • \$\begingroup\$ @IsmaelMiguel This will have the exact same byte count. \$\endgroup\$ – insertusernamehere Dec 23 '15 at 23:50
  • 1
    \$\begingroup\$ Don't worry - and it's still a nice way to obfuscate. ;) \$\endgroup\$ – insertusernamehere Dec 24 '15 at 0:01
5
\$\begingroup\$

Perl, 46 34 33 bytes

includes +2 for -nE

say/[a-z]/?a..z:/[A-Z]/?A..Z:$_

Run as

perl -nE 'say/[a-z]/?a..z:/[A-Z]/?A..Z:$_'

  • update 34 save 12 bytes by omitting for and using barewords, thanks to @Dom Hastings.
  • update 33 save 1 byte using -E and say instead of print.
\$\endgroup\$
  • \$\begingroup\$ @DomHastings Thanks! Should have known barewords were allowed there - and I should've seen that for :-/. Tried a bunch of approaches, (-p with $"='';$_="@_", even $a='/[a-z]/?a..z:';print eval$a.uc$a.'$_' but everything is longer... \$\endgroup\$ – Kenney Dec 22 '15 at 21:51
  • \$\begingroup\$ Had a think on this, if you set $_= instead of printing and use the -p flag instead of -n you can save another two... I still can't think of any other ways to save more so far... \$\endgroup\$ – Dom Hastings Dec 23 '15 at 11:04
  • \$\begingroup\$ @DomHastings I tried that, but I can't set $_ to a list (that I know of). It would have to be interpolated ($_="@_") but that uses space as a separator so I'd have to do $"='' as well, (or use a join'',) which makes it longer. Not much wiggle room on this one! \$\endgroup\$ – Kenney Dec 23 '15 at 15:07
  • \$\begingroup\$ Hah, of course! You even said that (when I re-read the comment after not being at the pub...) I'll keep thinking on it, but you might be the shortest you'll get without using say instead of print! \$\endgroup\$ – Dom Hastings Dec 23 '15 at 15:28
5
\$\begingroup\$

Ruby, 41 + 1 = 42

With switch -p, run

([*?A..?z]*'').scan(/\w+/){$&[$_]&&$_=$&}

This generates the string

ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz

and checks each contiguous block of "word characters", which happen to be just the lowercase and uppercase alphabets and the underscore character. If there were multiple consecutive word characters between Z and a, this trick wouldn't work.

Edited to add explanation, by request:

The -p flag does essentially

while( $_ = STDIN.gets )
  #execute code
  print $_
end

[*?A..?z] is the array of characters between uppercase A and lowercase Z, in ASCII order. That's the uppercase alphabet, some non-letter characters, and the lowercase alphabet. *'' joins the array into a string, so we can call .scan on it. scan will find each match of the regular expression /\w+/, populate the magic variable $& with it, and call the block. Each time the block is iterated, it checks whether the matched string contains $_ and sets the output to that string if so. So if $_ is contained in either the uppercase or lowercase alphabet, it gets modified accordingly, otherwise it's unchanged.

The ungolfed version would look something like

while ($_ = STDIN.gets )
 %w[ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz].each do |alphabet|
  $_ = alphabet if alphabet.include?($_)
 end
 print $_
end
\$\endgroup\$
  • \$\begingroup\$ Can you post an un-golfed version? I'm still not understanding fully how this works. \$\endgroup\$ – Shelvacu Dec 24 '15 at 21:58
  • \$\begingroup\$ Sure, posted one. \$\endgroup\$ – histocrat Dec 26 '15 at 2:15
4
\$\begingroup\$

CJam, 18 bytes

'[,65>_elr:R]{R&}=

'[,65> pushes the uppercase alphabet, _el the lowercase alphabet, and r:R a single-char string that is read from STDIN and assigned to variable R. These are wrapped in an array (]) and the first one that has any chars in common with R is selected using {R&}=.

\$\endgroup\$
  • \$\begingroup\$ I'm trying to understand how to CJam, but I'm lost between the official doc and what I'm reading here. Can someone give me for example a page where I can understand why is _el the lowercase alphabet? \$\endgroup\$ – Erdal G. Dec 23 '15 at 18:30
  • \$\begingroup\$ Ah, el means "convert to lowercase". I've just pushed the uppercase alphabet, so now I duplicate it with _, then call el on the resulting copy. \$\endgroup\$ – Lynn Dec 23 '15 at 18:31
  • 1
    \$\begingroup\$ I made a nice pdf containing (almost) all CJam commands. \$\endgroup\$ – Lynn Dec 23 '15 at 18:31
4
\$\begingroup\$

Retina, 62 bytes

[a-z]
abcdefghijklmnopqrstuvwxyz
[A-Z]
ABCDEFGHIJKLMNOPQRSTUVWXYZ

The two short lines are the regex to match. If the input is lowercase (in the range [a-z]), it replaces that character (in this case, that is the entire input) with the lowercase alphabet. The process is similar for uppercase. If it's not a letter, no replacements are made, and it is outputted untouched.

Try it online.

\$\endgroup\$
4
\$\begingroup\$

Python 2.7.10, 95 93 79 bytes

This is my first time even attempting to golf, so please, any help or advice is extremely appreciated!

from string import* 
lambda i:(i,(uppercase,lowercase)[i.islower()])[i.isalpha()]

Thanks to Morgan Thrapp for the help!

\$\endgroup\$
  • 1
    \$\begingroup\$ @MorganThrapp, that doesn't seem to work. Are you sure that it works in Python 2.7.10? \$\endgroup\$ – Daniel Dec 22 '15 at 21:23
  • \$\begingroup\$ It works in 2.7.8. What doesn't work? \$\endgroup\$ – Morgan Thrapp Dec 22 '15 at 21:24
  • \$\begingroup\$ @MorganThrapp, actually, could you please explain first exactly how that works? Maybe it's just that I don't understand so I'm doing something wrong. \$\endgroup\$ – Daniel Dec 22 '15 at 21:27
  • \$\begingroup\$ Sure, it uses the fact that False == 0 and True == 1 to index into tuples. So, it first checks if it's a letter with isalpha, if it is, it returns 1 and then checks if it's lowercase and does the same. \$\endgroup\$ – Morgan Thrapp Dec 22 '15 at 21:28
  • 1
    \$\begingroup\$ No problem! I love golfing, so I'm always happy to help out someone new! \$\endgroup\$ – Morgan Thrapp Dec 22 '15 at 21:31
4
\$\begingroup\$

Ruby, 46 43 characters

(42 characters code + 1 character command line option)

[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}

Thanks to:

  • Jordan for the === magic (-3 characters)

Sample run:

bash-4.3$ echo -n 'm' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}'
abcdefghijklmnopqrstuvwxyz

bash-4.3$ echo -n 'W' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}'
ABCDEFGHIJKLMNOPQRSTUVWXYZ

bash-4.3$ echo -n '@' | ruby -pe '[?a..?z,?A..?Z].map{|r|r===$_&&$_=[*r]*""}'
@
\$\endgroup\$
4
\$\begingroup\$

MATL, 22 bytes

jtt1Y2XIm~Iw?km?Ik]]1$

This uses the current version (3.1.0) of the language.

EDIT (Sep 15, 2017): Try it at MATL Online! (with a newer version of the language).

Examples

>> matl jtt1Y2XIm~Iw?km?Ik]]1$
> e
abcdefghijklmnopqrstuvwxyz

>> matl jtt1Y2XIm~Iw?km?Ik]]1$
> T
ABCDEFGHIJKLMNOPQRSTUVWXYZ

>> matl jtt1Y2XIm~Iw?km?Ik]]1$
> "
"

Explanation

j              % input string (assumed to be a single character)        
tt             % duplicate twice
1Y2            % predefined literal: uppercase letters
XI             % copy to clipboard I         
m~             % check if not member    
I              % paste from clipboard I      
w              % swap elements in stack      
?              % if
    k          % convert string to lowercase 
    m          % check if member         
    ?          % if                          
        I      % paste from clipboard I      
        k      % convert string to lowercase 
    ]          % end                         
]              % end                         
1$             % input specification for implicit printing
\$\endgroup\$
3
\$\begingroup\$

Java, 165 characters

class A {public static void main(String[]p){int c=p[0].charAt(0),d=c|32,b=(d-96)*(d-123),e=b<0?65|(c&32):c,f=e+(b<0?26:1);for(;e<f;e++){System.out.print((char)e);}}}

Generates the required output to stdout (rather than returning it). Input is via the runtime arguments.

How it works.

1) Setup some integer variables
c = the ASCII value of the first character of the first parameter of the runtime arguments.
d = c converted to lowercase ASCII value (by ORing it with 32)
b = calculation to see if d is a letter. Will be <0 if a letter.
e = The start character for output. If ASCII value in d is a letter (see b) then it is set to 'A' (or 'a' by adding c AND 32 to 'A' ASCII value) else it is set to the original value of c.
f = the number of characters to output. If it not a letter (see b) then this is set to 1 else it is set to 26
2) Loop from e to e+f outputing each character to stdout.

\$\endgroup\$
  • 2
    \$\begingroup\$ You know that for most challenges the solution can be provided either as complete program or a function? Given the enormous amount of boilerplate code in Java, a function may be shorter. \$\endgroup\$ – manatwork Dec 23 '15 at 13:35
  • 1
    \$\begingroup\$ Applying a couple of small tricks, without changing the logic, I got this: void f(char c){for(int d=c|32,b=(d-96)*(d-123),e=b<0?65|(c&32):c,f=e+(b<0?26:1);e<f;)System.out.print((char)e++);}. \$\endgroup\$ – manatwork Dec 23 '15 at 15:29
3
\$\begingroup\$

Perl, 23 bytes

Includes +2 for -nE (instead of the normal +1) to be fair to the other perl solution

Run with the input on STDIN without trailing newline:

echo -n g | perl -lnE 'say/\pL/?a&$_|A..Z:$_'

Just the code:

say/\pL/?a&$_|A..Z:$_
\$\endgroup\$
  • \$\begingroup\$ Nice use of the fact that input is limited to 7-bit characters. \$\endgroup\$ – msh210 Sep 28 '16 at 18:21
3
\$\begingroup\$

Lua, 98 97 bytes

Sadly, I didn't find a solution shorter than 26 bytes to set a with the alphabet. In fact, I didn't find shorter than 32.

Edit : save 1 Byte thanks to @ATaco, was doing this error a lot when started with Lua :p

c=io.read()a="abcdefghijklmnopqrstuvwyz"print(not c:find"%a"and c or c:find"%u"and a:upper()or a)

You can test it online on the official site or on ideone. If you use the former, the input won't work (disabled), so use the following source, where it is wrapped into a function.

function f(c)
  a="abcdefghijklmnopqrstuvwyz"
  print(not c:find"%a"and c or c:find"%u"and a:upper()or a)
end

print(f("\""))
print(f("a"))
print(f("Q"))
\$\endgroup\$
  • \$\begingroup\$ You are not the only who not found shorter way to generate the alphabet in Lua. :( \$\endgroup\$ – manatwork Dec 22 '15 at 11:29
  • \$\begingroup\$ @manatwork haha, exactly the same thing, except I didn't have to print it, but to concatenate it ^^. At least, that mean there isn't a hidden trick I didn't know to do it ^^'. \$\endgroup\$ – Katenkyo Dec 22 '15 at 13:44
  • \$\begingroup\$ You can save a byte with c=io.read()a="abcdefghijklmnopqrstuvwyz" instead of a,c=... \$\endgroup\$ – ATaco Sep 29 '16 at 0:13
2
\$\begingroup\$

Mathematica, 75 bytes

#/.Thread[Join[a=Alphabet[],b=ToUpperCase@a]->Array[""<>If[#>26,b,a]&,52]]&

Pretty good score for a non-golfing language... Any solutions using character code processing would take more bytes, due to the costs of ToCharacterCode and FromCharacterCode.

\$\endgroup\$
2
\$\begingroup\$

C (function), 71 bytes

f(s,n,c){n=1;if(isalpha(s))s-=s%32-1,n=26;for(c=s;c<s+n;)putchar(c++);}
\$\endgroup\$
  • \$\begingroup\$ f(s,n,c){for(c=s-=(n=isalpha(s)?26:1)>1?s%32-1:0;c<s+n;)putchar(c++);} saves a byte. \$\endgroup\$ – Kenney Dec 23 '15 at 17:41
  • 1
    \$\begingroup\$ f(s,n){for(n=isalpha(s)?s-=s%32-1,s+26:s+1;s<n;)putchar(s++);} for 62 bytes \$\endgroup\$ – gastropner Nov 11 '17 at 9:41
2
\$\begingroup\$

Python, 81 bytes

f=lambda z,a="abcdefghijklmnopqrstuvwxyz":[k for k in[a,a.upper(),z]if z in k][0]

This is basically a translation of the Pyth answer. It defines a function f that takes as argument the character and returns the result.

\$\endgroup\$
  • 1
    \$\begingroup\$ You mean if z in k, right? Also, f= is optional by default. \$\endgroup\$ – xnor Dec 22 '15 at 21:00
  • \$\begingroup\$ @xnor Yes. Apparently I missed a Ctrl-C. \$\endgroup\$ – PurkkaKoodari Dec 22 '15 at 21:01
  • 2
    \$\begingroup\$ Remove f=, make the function anonymous. -2 \$\endgroup\$ – Erik the Outgolfer Jul 22 '16 at 10:13
2
\$\begingroup\$

Jolf, 17 bytes

Try it here.

? hpLipl? hpUipui
?                  if
  hpL               the lowercase alphabet (array) contains
     i               the input
      pl            return the lowercase alphabet (string)
        ?          else if
          hpU       the uppercase alphabet (array) contains
             i       the input
              pu    return the uppercase alphabet (string)
                i  otherwise, return the input
                   implicit: print the result
\$\endgroup\$
2
\$\begingroup\$

MATLAB: 71 68 bytes

i=input('');b=i<65|i>122|(i>90&i<97);[i*b,~b*((65:90)+32*(i>96)),'']

(thanks to OP for saving 3 bytes)

Test:

i='a'
ans=
abcdefghijklmnopqrstuvwxyz

i='A'
ans=
ABCDEFGHIJKLMNOPQRSTUVWXYZ

i='~'
ans=
~

Explanation: Uppercase alphabet occupies 65:90 ASCII characters. Lowercase alphabet is at 97:122 ASCII. So, b=i<65|i>122|(i>90&i<97) checks whether the input character i is NOT alphabetic. If so, input is returned. The uppercase alphabet is returned if b==1 and i<97 (uppercase character). If b==1 and i>96, 32 is added to 65:90 that corresponds to 97:122 - the lowercase alphabet.

\$\endgroup\$
  • \$\begingroup\$ Nice submission. Two comments: It's common to either use i=input('') if the submission is a script, or as a function argument if it's a function @(i)i^2. i='a' is in general not accepted. Also, you can save 3 bytes by doing [1,2,3,''] instead of char([1,2,3]). \$\endgroup\$ – Stewie Griffin Dec 22 '15 at 14:45
  • \$\begingroup\$ Ok, edited. Thanks for suggestion! \$\endgroup\$ – brainkz Dec 23 '15 at 12:40
2
\$\begingroup\$

SpecBAS, 111 bytes

I've been through several versions of this, 111 seems to be the best I can manage.

1 INPUT l$: a$="abcdefghijklmnopqrstuvwxyz"
2  ?IIF$(l$ IN ["a" TO "z","A" TO "Z"],IIF$(l$=UP$ l$,UP$ a$,a$),l$)

Line 2 uses the ? shortcut for PRINT and nested inline IF statements

Pseudo code explanation

IF character IN "a".."z","A".."Z"
THEN
 IF character = UPPERCASE character
 THEN
  print UPPERCASE alphabet
 ELSE
  print alphabet
 ENDIF
ELSE
 print the character
ENDIF
\$\endgroup\$
  • \$\begingroup\$ It's hard to make ["a" TO "z","A" TO "Z"] look more like a pseudo code than it already does. "a".."z","A".."Z" looks more like a "real code", at least in my eyes... Both are very easy to understand though =) \$\endgroup\$ – Stewie Griffin Dec 22 '15 at 11:15
  • 2
    \$\begingroup\$ Spec what???? \$\endgroup\$ – Bassdrop Cumberwubwubwub Dec 22 '15 at 13:47
2
\$\begingroup\$

Swift 2, 142 Bytes

func d(s:String)->String{let a="abcdefghijklmnopqrstuvwxyz";for v in s.utf8{return v>64&&v<91 ?a.uppercaseString:(v>96&&v<123 ?a:s)};return s}

Ungolfed

func d(s: String) -> String{
    let a="abcdefghijklmnopqrstuvwxyz"
    for v in s.utf8{
        return (
            v > 64 && v < 91 ?
            a.uppercaseString :
            (
                v > 96 && v < 123 ?
                a :
                s
            )
        )
     }
    return s
}
\$\endgroup\$
2
\$\begingroup\$

05AB1E, 19 16 bytes

-3 bytes thanks to else

DAsåiAëDAusåiAuë

How it works

                   # implicit input
D                  # duplicate
 A                 # push lowercase alphabet
  s                # swap last two elements
   å               # push a in b
    i              # if
     A             # lowercase alphabet
      ë            # else
         D         # duplicate
          Au       # uppercase alphabet
            s      # swap last two elements
             å     # push a in b
              I    # if
               Au  # uppercase alphabet
                 ë # else leave input
                   # implicit print

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Not sure if ¹ (first input) already existed when you posted your answer, but you can golf 2 bytes with it: A¹åiAëAu¹åiAuë (Try it online or test suite). \$\endgroup\$ – Kevin Cruijssen Aug 9 '18 at 13:57
2
\$\begingroup\$

Java SE 8, 71 69 bytes

Golfed:

(a,s)->{char b=97;if(a<91)b-=32;a=b;b+=26;while(a<b)s+=a++;return s;}

Ungolfed:

(a,s)->{          // String as a parameter. If declaration is necessary it adds 8 bytes
char b = 97;      // Uppercase A char, this is important
if (a < 91)       // If it is not past 'z', where a is a char param
    b -= 32;      // Then go back to the lowercase alphabet
a = b;            // Done to prevent a cast
b += 26;          // End of alphabet
while (a < b)     // Go to end of alphabet
    s += a++;     // Append character
return s;}        // Then return

I had originally implemented the following

String s="";char b=96;if(a-91<0)b-=32;for(char c=b;++c<b+27;)s+=c;return s;

It's more elegant but sadly it's one byte larger. This is assuming that behavior for non alpha characters is undefined and string s is initialized to "" prior to execution. Be gentle it's my first post.

edit: 2 bytes saved by Stewie Griffin by changing

a - 91 < 0 to a < 91
\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to the site! :) \$\endgroup\$ – DJMcMayhem Nov 9 '17 at 19:59
  • 1
    \$\begingroup\$ Thanks! Been lurking for a few years now and really interested to see if I can make competing Java/C++ answers :) \$\endgroup\$ – jfh Nov 9 '17 at 20:03
  • 1
    \$\begingroup\$ a<91 should work, or...? \$\endgroup\$ – Stewie Griffin Nov 9 '17 at 20:33
2
\$\begingroup\$

Scala, 91 characters

(c:Char)=>{var a='a'.to('z').mkString;if(c.isUpper)a=a.toUpperCase;if(!c.isLetter)a=""+c;a}

Un-golfed

def f(c: Char): String = {
    var a='a'.to('z').mkString //set up lower case default response
    if (c.isUpper) {
        a = a.toUpperCase     //mutate the result if upper case
    }        
    if (!c.isLetter) { 
      a = ""+c                 //mutate the result if not a letter
    }
    a                         //return result
}

Having a initial mutable result rather than returning an immutable value from 3 distinct if else blocks saved me 2 chars, even though I hate it.

Scala-thonic method

A better method for scala would be something like this:

def convertToAlphabet(c: Char): String = {
    c match {
      case x if !x.isLetter => x.toString
      case x if x.isUpper => ('A' to 'Z').mkString
      case _ => ('a' to 'z').mkString
    }
}
\$\endgroup\$
2
\$\begingroup\$

Japt, 9 bytes

;[CBU]æøU

Run it online

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