Output the alphabet, the ALPHABET, or just a character

49

4

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>

Stewie Griffin

Posted 2015-12-22T08:17:56.173

Reputation: 43 471

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)? – Daniel – 2015-12-22T15:28:55.420

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. – Stewie Griffin – 2015-12-22T15:36:10.300

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 – Cyoce – 2015-12-23T05:10:34.567

May we assume a REPL environment? – cat – 2015-12-23T17:38:37.517

Answers

22

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:

°

Downgoat

Posted 2015-12-22T08:17:56.173

Reputation: 27 116

TeaScript 3 *is* valid. So, you may use it! – user75200 – 2017-11-02T13:06:20.523

27

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.

isaacg

Posted 2015-12-22T08:17:56.173

Reputation: 39 268

6Seriously, is there anything you couldn't solve with a few bytes of Pyth? I really need to learn this language.. – Hexaholic – 2015-12-22T17:49:12.823

26Learn which language?...you mentioned two by name. :P – quintopia – 2015-12-22T18:21:22.727

2@quintopia Well, why not both? :) – Hexaholic – 2015-12-22T21:16:24.967

Holy cow, this is clever! I just went with the obvious solution of ternary statements, which ended up being 14 bytes

?}zGG?}zKrG1Kz – Tornado547 – 2019-12-02T21:28:02.067

15

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.

Eumel

Posted 2015-12-22T08:17:56.173

Reputation: 2 487

4As someone who had the (privilege? misfortune? you decide) of working in LabVIEW many years ago, your answers bring a smile to my day. =) – corsiKa – 2015-12-22T16:26:40.947

12

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.

nimi

Posted 2015-12-22T08:17:56.173

Reputation: 34 639

11

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>

user81655

Posted 2015-12-22T08:17:56.173

Reputation: 10 181

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? – Stewie Griffin – 2015-12-22T08:54:23.497

1@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! – user81655 – 2015-12-22T08:56:00.490

4In this case the balance is between String.fromCharCode and .toUpperCase (Dumb and Dumber) but toUpperCase is the winner – edc65 – 2015-12-22T09:27:08.530

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. – ETHproductions – 2015-12-22T18:51:00.987

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 – ETHproductions – 2015-12-22T19:34:59.740

@ETHproductions I was wondering about that; the best I had managed was String.fromCharCode(...Array(91).keys()).slice(65) which takes 50 bytes just to produce the uppercase alphabet, or String.fromCharCode(...Array(123).keys()).replace(/[^a-z]/gi,'') which concatenates both in "only" 64 bytes. – Neil – 2015-12-23T11:32:54.063

Bah, /[^\W_]/ is no shorter than /[A-Z]/i. – Neil – 2015-12-23T11:40:32.267

8

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.

Andreï Kostyrka

Posted 2015-12-22T08:17:56.173

Reputation: 1 389

75 bytes – Giuseppe – 2017-11-09T22:04:24.247

73 bytes: the 2nd parameter of scan can be any object of type character, so you can letters instead of ''. – Robin Ryder – 2019-09-07T17:34:06.313

7

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

Koneke

Posted 2015-12-22T08:17:56.173

Reputation: 121

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. – isaacg – 2015-12-22T11:09:27.327

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! – Koneke – 2015-12-22T11:20:21.490

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. – isaacg – 2015-12-22T11:23:50.257

Ah, haven't actually used generator comprehensions before, learning new things! Thanks again :) – Koneke – 2015-12-22T11:27:19.733

Note that when inputing " to the function, you need \" instead. – Daniel – 2015-12-22T16:50:36.883

You can save 5 bytes by replacing (97if c>'Z'else 65) with (67,97)[c>'Z'] – wnnmaw – 2015-12-23T16:03:22.400

True! We can actually use the same trick to replace the if else. Down to 76, neat! :) – Koneke – 2015-12-24T14:28:17.317

6

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

Sherlock9

Posted 2015-12-22T08:17:56.173

Reputation: 11 664

1Could you use a ternary operator to save a few bytes? Something like return a.lower() if s.islower() else a. – David Robertson – 2015-12-22T13:00:49.587

@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. – Sherlock9 – 2015-12-22T13:57:32.247

Ah! I was reading the ungolfed version. Sorry about that! – David Robertson – 2015-12-22T14:40:49.843

@DavidRobertson Not a problem – Sherlock9 – 2015-12-22T15:21:46.460

Golfed: lambda s,a='abcdefghijklmnopqrstuvwxyz':(s,(a,a.upper())[s.isupper()])[s.isalpha()] – Erik the Outgolfer – 2016-07-22T10:04:08.407

Can you do something like map(chr,range(65,91))? – Cyoce – 2016-12-15T00:39:14.567

@Cyoce I don't think I can. I can't .lower() a map and ''.join would add too many bytes. – Sherlock9 – 2016-12-17T12:04:46.830

5

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.

insertusernamehere

Posted 2015-12-22T08:17:56.173

Reputation: 4 551

That ord() looks bad there. Try Z<$x?$a:strtoupper($a). – manatwork – 2015-12-22T12:23:02.113

@manatwork Haha, I've thought way to complicated in that second part. Thanks to point it out. – insertusernamehere – 2015-12-22T19:13:14.147

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; – Ismael Miguel – 2015-12-23T23:33:12.383

@IsmaelMiguel This will have the exact same byte count. – insertusernamehere – 2015-12-23T23:50:08.657

@insertusernamehere -.- you're right... I counted those bytes incorrectly. sorry :/ – Ismael Miguel – 2015-12-23T23:59:55.430

1Don't worry - and it's still a nice way to obfuscate. ;) – insertusernamehere – 2015-12-24T00:01:14.483

Wow, I just php-golfed this challenge myself as an exercise and came up with exactly this code, byte for byte. – Tortoise – 2016-10-22T16:30:50.130

Save 4 bytes with range($x&a|A,$x&z|Z) and one byte with $argn and -R. – Titus – 2017-06-06T20:32:57.550

5

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.

Kenney

Posted 2015-12-22T08:17:56.173

Reputation: 946

@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... – Kenney – 2015-12-22T21:51:42.410

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... – Dom Hastings – 2015-12-23T11:04:51.250

@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! – Kenney – 2015-12-23T15:07:26.650

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! – Dom Hastings – 2015-12-23T15:28:51.970

5

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

histocrat

Posted 2015-12-22T08:17:56.173

Reputation: 20 600

Can you post an un-golfed version? I'm still not understanding fully how this works. – Shelvacu – 2015-12-24T21:58:56.643

Sure, posted one. – histocrat – 2015-12-26T02:15:02.507

4

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]*""}'
@

manatwork

Posted 2015-12-22T08:17:56.173

Reputation: 17 865

4

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&}=.

Lynn

Posted 2015-12-22T08:17:56.173

Reputation: 55 648

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? – Erdal G. – 2015-12-23T18:30:17.707

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. – Lynn – 2015-12-23T18:31:28.480

1

I made a nice pdf containing (almost) all CJam commands.

– Lynn – 2015-12-23T18:31:48.820

4

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.

NinjaBearMonkey

Posted 2015-12-22T08:17:56.173

Reputation: 9 925

4

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

Luis Mendo

Posted 2015-12-22T08:17:56.173

Reputation: 87 464

4

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!

Daniel

Posted 2015-12-22T08:17:56.173

Reputation: 6 425

1@MorganThrapp, that doesn't seem to work. Are you sure that it works in Python 2.7.10? – Daniel – 2015-12-22T21:23:30.023

It works in 2.7.8. What doesn't work? – Morgan Thrapp – 2015-12-22T21:24:42.827

@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. – Daniel – 2015-12-22T21:27:24.920

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. – Morgan Thrapp – 2015-12-22T21:28:45.587

@MorganThrapp, oh wow. That's pretty cool. Thanks! – Daniel – 2015-12-22T21:31:10.517

1No problem! I love golfing, so I'm always happy to help out someone new! – Morgan Thrapp – 2015-12-22T21:31:32.903

Let us continue this discussion in chat.

– Morgan Thrapp – 2015-12-22T21:35:14.577

3

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"))

Katenkyo

Posted 2015-12-22T08:17:56.173

Reputation: 2 857

You are not the only who not found shorter way to generate the alphabet in Lua. :(

– manatwork – 2015-12-22T11:29:16.260

@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 ^^'. – Katenkyo – 2015-12-22T13:44:41.287

You can save a byte with c=io.read()a="abcdefghijklmnopqrstuvwyz" instead of a,c=... – ATaco – 2016-09-29T00:13:35.907

3

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.

Minimal

Posted 2015-12-22T08:17:56.173

Reputation: 131

2You 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. – manatwork – 2015-12-23T13:35:08.327

1Applying 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++);}. – manatwork – 2015-12-23T15:29:57.560

3

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:$_

Ton Hospel

Posted 2015-12-22T08:17:56.173

Reputation: 14 114

Nice use of the fact that input is limited to 7-bit characters. – msh210 – 2016-09-28T18:21:05.237

2

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!

Neil A.

Posted 2015-12-22T08:17:56.173

Reputation: 2 038

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

– Kevin Cruijssen – 2018-08-09T13:57:40.713

2

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

jfh

Posted 2015-12-22T08:17:56.173

Reputation: 61

2Welcome to the site! :) – James – 2017-11-09T19:59:03.807

1Thanks! Been lurking for a few years now and really interested to see if I can make competing Java/C++ answers :) – jfh – 2017-11-09T20:03:00.140

1a<91 should work, or...? – Stewie Griffin – 2017-11-09T20:33:27.927

2

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

sprague44

Posted 2015-12-22T08:17:56.173

Reputation: 81

2

Japt, 9 bytes

;[CBU]æøU

Run it online

Oliver

Posted 2015-12-22T08:17:56.173

Reputation: 7 160

2

Brachylog, 8 bytes

∈Ạ|ḷ∈Ạụ|

Try it online!

∈Ạ          The input is a member of the lowercase alphabet,
  |         which is output, or
   ḷ∈Ạ      the input lowercased is a member of the lowercase alphabet,
      ụ|    which is output uppercased, or the input is output.

It'd be two bytes shorter if we had a constant for the uppercase alphabet but we don't :(

Unrelated String

Posted 2015-12-22T08:17:56.173

Reputation: 5 300

2

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

Brian

Posted 2015-12-22T08:17:56.173

Reputation: 1 209

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 =) – Stewie Griffin – 2015-12-22T11:15:33.810

2Spec what???? – Bassdrop Cumberwubwubwub – 2015-12-22T13:47:27.980

2

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.

LegionMammal978

Posted 2015-12-22T08:17:56.173

Reputation: 15 731

2

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.

PurkkaKoodari

Posted 2015-12-22T08:17:56.173

Reputation: 16 699

1You mean if z in k, right? Also, f= is optional by default. – xnor – 2015-12-22T21:00:14.747

@xnor Yes. Apparently I missed a Ctrl-C. – PurkkaKoodari – 2015-12-22T21:01:57.047

2Remove f=, make the function anonymous. -2 – Erik the Outgolfer – 2016-07-22T10:13:00.110

2

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.

brainkz

Posted 2015-12-22T08:17:56.173

Reputation: 349

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]). – Stewie Griffin – 2015-12-22T14:45:44.483

Ok, edited. Thanks for suggestion! – brainkz – 2015-12-23T12:40:02.760

2

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
}

Jojodmo

Posted 2015-12-22T08:17:56.173

Reputation: 1 569

2

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++);}

Digital Trauma

Posted 2015-12-22T08:17:56.173

Reputation: 64 644

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. – Kenney – 2015-12-23T17:41:31.233

1f(s,n){for(n=isalpha(s)?s-=s%32-1,s+26:s+1;s<n;)putchar(s++);} for 62 bytes – gastropner – 2017-11-11T09:41:42.533

2

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

Conor O'Brien

Posted 2015-12-22T08:17:56.173

Reputation: 36 228

1

Perl 6, 50

{join "",/<:Lu>/??"A".."Z"!!/<:Ll>/??"a".."z"!!$_}

bb94

Posted 2015-12-22T08:17:56.173

Reputation: 1 831

1

PHP, 60 bytes

for(ctype_alpha($c=$argn)?$c=$c&a|A:$z=25;$z++<26;)echo$c++;

Run as pipe with -R.

Titus

Posted 2015-12-22T08:17:56.173

Reputation: 13 814

1

Recursiva, 13 bytes

||&N(a(&N)a)a

Try it online!

Explanation:

This roughly translates to 'N(a and (' or 'N)a and )' or a. N(a checks if a is in (. ( and ) are upper and lower-case alphabet yield.

officialaimm

Posted 2015-12-22T08:17:56.173

Reputation: 2 739

1

Ly, 32 bytes

"AZ"Ris~[p&o;]&p"az"Rl~[p&o;]lo;

Try it online!

Explanation:

"AZ"Ris~[p&o;]&p"az"Rl~[p&o;]lo;

     is                          # take input and save it
"AZ"R  ~[    ]                   # is it in the uppercase alphabet?
         p&o;                    # output the stack, terminate
              &p                 # clear stack
                     l           # load input
                "az"R ~[    ]    # is it in the lowercase alphabet?
                        p&o;     # output the stack, terminate
                             lo; # output the input, terminate

LyricLy

Posted 2015-12-22T08:17:56.173

Reputation: 3 313

1

Python 2, 73 bytes

c=ord(input())
print[chr(c),bytearray(range(c&96|1,c&96|27))][64<c&95<91]

Try it online!

Lynn

Posted 2015-12-22T08:17:56.173

Reputation: 55 648

1

APL (Dyalog Unicode), 26 24 bytes

t←{⍵∊g←819⌶f←⎕A:g⋄⍵∊f:f⋄⍵}

Try it online!

The byte count does not include t← because it's not necessary, it just assigns the function to t (so you can call it by using t input).

If input is not a number, it needs to be enclosed in single quotes. For the input ', you need to escape it by typing it twice (so the call is t '''')

Thanks to @Adám for 2 bytes.

How it works:

{⍵∊g←819⌶f←⎕A:g⋄⍵∊f:f⋄⍵} ⍝ Main function
             :            ⍝ if
         f←⎕A             ⍝ Assigns the uppercase alphabet to f
   g←819⌶                 ⍝ Assigns the I-Beam command 819 (case convert) over the uppercase alphabet (f) to g
 ⍵∊                       ⍝ The right argument 'is in' the lowercase alphabet
              g           ⍝ then print g (the lowercase alphabet)
               ⋄   :      ⍝ else if
                ⍵∊f       ⍝ the right argument 'is in' f (the uppercase alphabet)           
                    f     ⍝ print f
                     ⋄⍵   ⍝ else, print the right argument.

J. Sallé

Posted 2015-12-22T08:17:56.173

Reputation: 3 233

1

APL (Dyalog), 22 bytes

Unnamed prefix lambda.

{⊃a/⍨⍵∊¨a←⎕A(819⌶⎕A)⍵}

Try it online!

{} anonymous function where represents the argument:

⎕A(819⌶⎕A)⍵ uppercase Alphabet, lowercased Alphabet, argument

a← store in a (for all)

⍵∊¨ three Booleans for argument's membership of each those

a/⍨ filter a by that

 pick the first

Adám

Posted 2015-12-22T08:17:56.173

Reputation: 37 779

1

C (gcc), 94 bytes

#define f(c)isupper(c)?"ABCDEFGHIJKLMNOPQRSTUVWXYZ":islower(c)?"abcdefghijklmnopqrstuvwxyz":&c

#define f(c) is like declaring a function f that takes a variable c.

isupper(c) checks if c is an uppercase letter, returns the uppercase alphabet if so. Otherwise, it checks if it's lowercase. If so, it returns the lowercase alphabet. Otherwise, it returns a pointer to c, which can be printed as a string (since you must pass a char or int to f).

Try it online!

MD XF

Posted 2015-12-22T08:17:56.173

Reputation: 11 605

Is it possible to store the alphabet in a variable and use toupper in here (I don't know C) – Stewie Griffin – 2017-11-17T08:04:35.187

@StewieGriffin toupper only works on chars, and strtoupper/strupper is not standard C (nor implemented on many systems). – MD XF – 2017-11-17T16:53:34.267

1

R, 80 bytes

s=(r=65:90)+32
a=utf8ToInt(scan(,''));intToUtf8("if"(a%in%r,r,"if"(a%in%s,s,a)))

Try it online!

-1 byte thanks to Giuseppe. Still not the golfiest way (see here). Similar ideas include:

R, 87 bytes

f=function(x,y)"if"(a%in%x,x,y)
a=utf8ToInt(scan(,''));intToUtf8(f(r<-65:90,f(r+32,a)))

Try it online!

a=utf8ToInt(scan(,''));intToUtf8("if"(a%in%c(32:64,91:96,123:126),a,65:90+32*(a>90)))

and my favorite:

a=utf8ToInt(scan(,''));intToUtf8(c(a,65:90+32*(a>90))[2*a%in%c(32:64,91:96,123:126)-1])

and inspired by the other R solution (same bytecount):

"+"=function(x,y)"if"(a%in%x,x,y)
a=scan(,'');cat(letters+LETTERS+a,sep="")

Try it online!

JayCe

Posted 2015-12-22T08:17:56.173

Reputation: 2 655

80 bytes – Giuseppe – 2018-08-09T13:44:12.363

@Giuseppe thanks! – JayCe – 2018-08-09T13:55:49.193

1

Noether, 40 bytes

{0A~bI~a/~c}{bP}b{Ua/~d}{bUP}1{cd|-}{aP}

Try it online!

Uses Noether's built-in constant function A to return the string abcdefghijklmnopqrstuvwxyx.

Beta Decay

Posted 2015-12-22T08:17:56.173

Reputation: 21 478

1

C# .NET, 193 bytes

class P{static void Main(string[]a){var z="ABCDEFGHIJKLMNOPQRSTUVWXYZ";var b=a[0];System.Console.Write(b.Length>1?b:z.IndexOf((b[0]))>-1?z:z.ToLower().IndexOf((b[0]))>-1?z.ToLower():b[0]+"");}}

Try Online EDIT: Variable assignment with if statements is stupid

canttalkjustcode

Posted 2015-12-22T08:17:56.173

Reputation: 131

1

Keg, -ir 45 37 21 bytes

:AZ"•[_AZɧ|:az"•[_azɧ

Try it online!

-16 bytes due to using ranges

Answer History

37 bytes

::`>$\~<*[_z(|:;)^|:A1->[_Z(|:;)^|,

-8 bytes thanks to A__

Try it online!

Lyxal

Posted 2015-12-22T08:17:56.173

Reputation: 5 253

37B by using control characters. – None – 2019-08-21T22:55:29.540

1

Zsh, 75 bytes

l=${(j::):-{a..z}} u=$l:u
<<<${${${l:#*$1*}:+${${${u:#*$1*}:+$1}:-$u}}:-$l}

l=${(j::):-{a..z}}                                  # set l to the (j::)oined lowercase
                   u=$l:u                           # set u to :uppercase'd l
<<<${${${l:#*$1*}:+${${${u:#*$1*}:+$1}:-$u}}:-$l}
       ${l:#*$1*}                                   # remove *$1* from $l (is empty if $1 is lower)
     ${          :+                        }        # If non-empty, then...
                       ${u:#*$1*}                   # remove *$1* from $u (is empty if $1 is upper)
                     ${          :+$1}              # If non-empty, substitute $1
                   ${                 :-$u}         # If empty, substitute $u
    ${                                       :-$l}  # If empty, substitute $l

Try it online!

GammaFunction

Posted 2015-12-22T08:17:56.173

Reputation: 2 838

1

Python 3, 84 bytes

lambda x,a='abcdefghijklmnopqrstuvwxyz':[x,a,a.upper()][(x in a)+2*(x in a.upper())]

Try it online!

Dat

Posted 2015-12-22T08:17:56.173

Reputation: 879

1

Wolfram Language (Mathematica), 62 bytes

""<>(#/.Join[a=Alphabet[];A=ToUpperCase@a;#->a&/@a,#->A&/@A])&

Try it online!

attinat

Posted 2015-12-22T08:17:56.173

Reputation: 3 495

1

Python 3, 93 bytes

i=input();a="abcdefghijklmnopqrstuvwxyz";A=a.upper();print(i in a and a or i in A and A or i)

Under 100 bytes!

Sagittarius

Posted 2015-12-22T08:17:56.173

Reputation: 169

1

Gema, 60 characters

\A=@set{a;abcdefghijklmnopqrstuvwxyz}
<J>=$a
<K>=@upcase{$a}

Sample run:

bash-4.3$ gema '\A=@set{a;abcdefghijklmnopqrstuvwxyz};<J>=$a;<K>=@upcase{$a}' <<< 'm'
abcdefghijklmnopqrstuvwxyz

bash-4.3$ gema '\A=@set{a;abcdefghijklmnopqrstuvwxyz};<J>=$a;<K>=@upcase{$a}' <<< 'W'
ABCDEFGHIJKLMNOPQRSTUVWXYZ

bash-4.3$ gema '\A=@set{a;abcdefghijklmnopqrstuvwxyz};<J>=$a;<K>=@upcase{$a}' <<< '@'
@

manatwork

Posted 2015-12-22T08:17:56.173

Reputation: 17 865

1

Seriously, 17 bytes

    ;;ú(úíuIúû;(@íuI

Hex Dump:

093b3ba328a3a17549a3963b2840a17549

Try It Online

Given that it pretty much just reads in an unformatted byte, checks if it's in the lowercase alphabet, then checks if it's in the uppercase alphabet, the automatic documentation given in the link is sufficient. (Note, however, that the documentation for í has the argument order reversed; it pops the sequence first.)

quintopia

Posted 2015-12-22T08:17:56.173

Reputation: 3 899

1

Python 2, 67 bytes

f=lambda c,i=26:c[c.isalpha():]or c*i and f(c,i-1)+chr(i^ord(c)&96)

For letter inputs, generates the string of letters recursively. Doing ord(c)&96 removes the 5 high bits, and the xor'ing the values i from 1 to 26 gives the letter char codes. For control flow, we count i down, adding new letters to the end, stopping when i=0. When the input c is not a letter, immediately outputs it and stops.

Thanks to Mauris for 2 bytes.

Previous solution (68):

lambda c:[c,str(bytearray(range(ord(c)&96,255)[1:27]))][c.isalpha()]

xnor

Posted 2015-12-22T08:17:56.173

Reputation: 115 687

The input will be any of the printable ASCII characters from 32 to 126 (space to tilde). Wouldn't ord(c)&96 suffice, then? – Lynn – 2015-12-22T21:42:10.363

@Mauris Yes, good call. – xnor – 2015-12-22T21:47:30.710

I think '_' --> c works and saves a byte in your recursive solution. – Lynn – 2015-12-22T22:02:25.393

1

Sed, 61 characters

(60 characters code + 1 character command line option)

s/[a-z]/&abcdefghijklmnopqrstuvwxyz/i
s/[A-Z].*/\U&/
T
s/.//

Sample run:

bash-4.3$ sed -r 's/[a-z]/&abcdefghijklmnopqrstuvwxyz/i;s/[A-Z].*/\U&/;T;s/.//' <<< 'm'
abcdefghijklmnopqrstuvwxyz

bash-4.3$ sed -r 's/[a-z]/&abcdefghijklmnopqrstuvwxyz/i;s/[A-Z].*/\U&/;T;s/.//' <<< 'W'
ABCDEFGHIJKLMNOPQRSTUVWXYZ

bash-4.3$ sed -r 's/[a-z]/&abcdefghijklmnopqrstuvwxyz/i;s/[A-Z].*/\U&/;T;s/.//' <<< '@'
@

manatwork

Posted 2015-12-22T08:17:56.173

Reputation: 17 865

1

Python 2.7, 88 bytes (incl. print)

from string import*
def f(c):print[c,uppercase,c,lowercase,c][sorted('@Z`z'+c).index(c)]

Patrick Fournier

Posted 2015-12-22T08:17:56.173

Reputation: 111

1

JavaScript (ES6), 99 87 79 78 bytes

x=>(y='abcdefghijklmnopqrstuvwxyz',parseInt(x,36)>9?x>'`'?y:y.toUpperCase():x)

Uses the short array fill trick to allocate space, then just math and String.fromCharCode to get the alphabet. Thought it would be shorter until I realized the rule about non-alphabet characters. parseInt turned out to be helpful in determining if the character was in the alphabet.

Test

var F=x=>(y='abcdefghijklmnopqrstuvwxyz',parseInt(x,36)>9?x>'`'?y:y.toUpperCase():x)
x = <input type="text" oninput="result.textContent=this.value?F(this.value):''" />
<pre id="result"></pre>

Mwr247

Posted 2015-12-22T08:17:56.173

Reputation: 3 494

1

Mouse-2002, 125 bytes

... or 126 bytes if I can't assume a REPL envrironment (which assumes a $ at the end of the program; the non-REPL interpreter crashes without one)

An attempt at code deduplication... probably a failed one.

Golfed:

?'a:123b:a.65<a.31>*1=a.90>a.97<*1=+a.122>+1=[a.!']a.63>a.91<*1=[65i:(i.91<^i.!'i.1+i:)]a.96>a.b.<*1=[97i:(i.b.<^i.!'i.1+i:)]

Ungolfed:

?' a:                    ~ a = getchar();
123 b:                   ~ b = 123
a. 65 <                  ~ return whether a < 65
a. 31 >                  ~ same for 31
  * 1 =                    ~ AND
a. 90 >                  ~ a > 90 ?
a. 97 <                  ~ a < 97 ?
  * 1 =                    ~ AND
+                          ~ OR
a.122 >                  ~ a > 122 ?
  + 1 =                    ~ OR
[                          ~ if 1
  a.!'                       ~ print ascii codepoint
]                          ~ fi
a. 63 >                  ~ a > 63 ?
a. 91 <                  ~ a < 91 ?
  * 1 =                    ~ AND
[                          ~ if 1
  65 i:                      ~ for i = 65;
  (                          ~ do;
    i. 91 < ^                  ~ i < 91;
    i.!'                       ~ print(charAt(i));
    i. 1+ i:                   ~ i++;
  )                         ~ done;
]                          ~ fi
a. 96 >                  ~ a > 96 ?
a. b. <                  ~ a < b ?
  * 1 =                    ~ AND
[                          ~ if 1
  97 i:                      ~ for i = 97;
  (                          ~ do;
    i. b. < ^                  ~ i < 91; 
    i.!'                       ~ print(charAt(i));
    i. 1+ i:                   ~ i++;
  )                          ~ done;
]                          ~ fi
$                        ~ \bye

cat

Posted 2015-12-22T08:17:56.173

Reputation: 4 989

1

Ruby, 56+2 = 58 bytes

2 bytes for -p flag

c=$_[0]
[?a..?z,?A..?Z].map{|r|r===c&&c=r.to_a.join}
p c

Ungolfed version (no -p flag)

while true
  char = gets.chars.first
  [("a".."z"),("A".."Z")].each do |range|
    char = range.to_a.join("") if range.include? char
  end
  p char
end

Shelvacu

Posted 2015-12-22T08:17:56.173

Reputation: 610

1

s-lang, 40 bytes (non-competing)

Replaces any letter with the alphabet, matching the case.

t@[[a-z]][abcdefghijklmnopqrstuvwxyz]
  • t Replace with regex function
  • @ Match case for entire match parameter for t function
  • [[a-z]] first argument ([a-z]) regex for matching any letter (@ parameter makes it so this function ignores the case when matching, so we don't need A-Z too)
  • abcdefghijklmnopqrstuvwxyz what to replace it with

Try it here

MCMastery

Posted 2015-12-22T08:17:56.173

Reputation: 783

1

Java 7, 99 bytes

void f(char c){for(int a=c|32,i=97;i<123;i++)System.out.print(a<123&a>96?(char)(i-a+c):i<98?c:"");}

Slightly more readable, with no scrollbars:

void f(char c){
    for(int a=c|32,i=97;i<123;i++)  // a is lowercased input, i loops alphabet 
        System.out.print(           
            a<123&a>96?             // if a is a letter
                (char)(i-a+c):      //   subtract diff between lower and input
                    i<98?c:"");     // else print input if first iteration
}

The logic here is pretty straightforward, but a different method than the other Java answer.

Geobits

Posted 2015-12-22T08:17:56.173

Reputation: 19 061

0

AWK 104 bytes

/[a-z]/{print"abcdefghijklmnopqrstuvwxyz"}
/[A-Z]/{print"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}
/[^A-z]/{print$0}

Arc676

Posted 2015-12-22T08:17:56.173

Reputation: 301

0

Powershell, 116 bytes

$b='j';$a='ABCDEFGHIJKLMNOPQRSTUVWXYZ';switch($b){{$b-cmatch'[a-z]'}{$a.ToLower()}{$b-cmatch'[A-Z]'}{$a}default{$_}}

Change $b='j' to modify result.

I couldn't figure out a way to get the alphabet that was shorter than just writing the alphabet unfortunately.

e.g. (65..90|%{[char][byte]$_})-join''

Ally Wilson

Posted 2015-12-22T08:17:56.173

Reputation: 9

This appears to be whats called a snippet program, where input is taken from a variable, in this case b. Snippets are not allowed so you should restructure to either a function or a full program. – Post Rock Garf Hunter – 2017-09-15T13:25:43.003

Hi and welcome to PPCG! Take a look at New users' guide to PowerShell and Tips for golfing in Windows PowerShell to get some basics. Secondly, to get the alphabet shorter, try -join[char[]](65..90) for 21 bytes.

– AdmBorkBork – 2017-09-20T18:21:51.227

0

Excel VBA, 114 Bytes

Anonymous VBE immediate window function that takes input and outputs to the VBE immediate window.

a=Asc([A1]):i=IIf(a>64And a<91,64,(a>96And a<123)*-96):?IIf(i=0,[A1],"");:If i>0 Then For j=1To 26:?Chr(i+j);:Next

Taylor Scott

Posted 2015-12-22T08:17:56.173

Reputation: 6 709

0

REXX, 75 bytes

b=arg(1)
a=xrange(a,z)
if b>z then a=lower(a)
if verify(b,a) then a=b
say a

idrougge

Posted 2015-12-22T08:17:56.173

Reputation: 641

0

Jelly, 11 bytes

XØA,Øa¤ċÐfȯ

Try it online!

Erik the Outgolfer

Posted 2015-12-22T08:17:56.173

Reputation: 38 134

0

Ink, 103 bytes

VAR u="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
VAR l="abcdefghijklmnopqrstuvwxyz"
=o(c)
{u?c:{u}|{l?c:{l}|{c}}}->->

Try it online!

Sara J

Posted 2015-12-22T08:17:56.173

Reputation: 2 576

0

k4, 24 bytes

{*b@&x in/:b:(.Q`A`a),x}

Another port of the Pyth answer—constructs a list of upper, lower, and the arg, and returns the first one that contains the arg.

Aaron Davies

Posted 2015-12-22T08:17:56.173

Reputation: 881

0

Sprects, 207 bytes

|<CHAR>|ZA|YA|XA|WA|VA|UA|TA|SA|RA|QA|PA|OA|NA|MA|LA|KA|JA|IA|HA|GA|FA|EA|DA|CA|BA|AABCDEFGHIJKLMNOPQRSTUVWXYZ|za|ya|xa|wa|va|ua|ta|sa|ra|qa|pa|oa|na|ma|la|ka|ja|ia|ha|ga|fa|ea|da|ca|ba|aabcdefghijklmnopqrstuvwxyz

Enter character on <CHAR>.

Erik the Outgolfer

Posted 2015-12-22T08:17:56.173

Reputation: 38 134