Sign that word 2!

17

3

Sign that word 2!

Not that long ago, I posted a challenge called Sign that word!. In the challenge, you must find the signature of word, which is the letters put in order (e.g. The signature of this is hist). Now then, that challenge did quite well, but there was one key issue: it was WAY too easy (see the GolfScript answer). So, I've posted a similar challenge, but with more rules, most of which have been suggested by PPCG users in the comments on the previous puzzle. So, here we go!

Rules

  1. Your program must take an input, then output the signature to STDOUT or the equivalent in whatever language your using.
  2. You are not allowed to use built-in sorting functions, so stuff like $ in GolfScript is not allowed.
  3. Multicase must be supported - your program must group letters of both uppercase and lowercase together. So the signature of Hello is eHllo, not Hello as you are given by the GolfScript answer on the first version.
  4. There must be a free interpreter/compiler for your program, which you should link to.

Scoring

Your score is your byte count. Lowest byte count wins.

Leaderboard

Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

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

var QUESTION_ID=55090;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),e.has_more?getAnswers():process()}})}function shouldHaveHeading(e){var a=!1,r=e.body_markdown.split("\n");try{a|=/^#/.test(e.body_markdown),a|=["-","="].indexOf(r[1][0])>-1,a&=LANGUAGE_REG.test(e.body_markdown)}catch(n){}return a}function shouldHaveScore(e){var a=!1;try{a|=SIZE_REG.test(e.body_markdown.split("\n")[0])}catch(r){}return a}function getAuthorName(e){return e.owner.display_name}function process(){answers=answers.filter(shouldHaveScore).filter(shouldHaveHeading),answers.sort(function(e,a){var r=+(e.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0],n=+(a.body_markdown.split("\n")[0].match(SIZE_REG)||[1/0])[0];return r-n});var e={},a=1,r=null,n=1;answers.forEach(function(s){var t=s.body_markdown.split("\n")[0],o=jQuery("#answer-template").html(),l=(t.match(NUMBER_REG)[0],(t.match(SIZE_REG)||[0])[0]),c=t.match(LANGUAGE_REG)[1],i=getAuthorName(s);l!=r&&(n=a),r=l,++a,o=o.replace("{{PLACE}}",n+".").replace("{{NAME}}",i).replace("{{LANGUAGE}}",c).replace("{{SIZE}}",l).replace("{{LINK}}",s.share_link),o=jQuery(o),jQuery("#answers").append(o),e[c]=e[c]||{lang:c,user:i,size:l,link:s.share_link}});var s=[];for(var t in e)e.hasOwnProperty(t)&&s.push(e[t]);s.sort(function(e,a){return e.lang>a.lang?1:e.lang<a.lang?-1:0});for(var o=0;o<s.length;++o){var l=jQuery("#language-template").html(),t=s[o];l=l.replace("{{LANGUAGE}}",t.lang).replace("{{NAME}}",t.user).replace("{{SIZE}}",t.size).replace("{{LINK}}",t.link),l=jQuery(l),jQuery("#languages").append(l)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",answers=[],page=1;getAnswers();var SIZE_REG=/\d+(?=[^\d&]*(?:&lt;(?:s&gt;[^&]*&lt;\/s&gt;|[^&]+&gt;)[^\d&]*)*$)/,NUMBER_REG=/\d+/,LANGUAGE_REG=/^#*\s*([^,]+)/;
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>

user42003

Posted 2015-08-21T07:11:06.310

Reputation:

2Must lowercase and uppercase be ordered? For example, for ThHihs, can we output hHhist or do we have to output hhHist or Hhhist? – Fatalize – 2015-08-21T07:20:54.033

I cannot comprehend rule 3. – feersum – 2015-08-21T07:20:55.123

@Fatalize As long as they are grouped together, it doesn't matter. It can be any of those. – None – 2015-08-21T07:23:09.080

@feersum Try running the GolfScript answer on the first version of this challenge with the string "Hello" (without the quotes). Then you should see what I mean. – None – 2015-08-21T07:26:57.270

2@Kslkgh I do not wish to install a GolfScript interpreter in order to understand the question. The requirements should be clearly specified in the question itself. – feersum – 2015-08-21T07:29:56.307

1@feersum You don't need to. There is a link in the answer to an online interpreter. But I will make it clearer. – None – 2015-08-21T07:35:09.003

So what you really mean is that the sorting should be case-insensitive? Why not simply say so? – feersum – 2015-08-21T08:07:41.277

Let us continue this discussion in chat.

– None – 2015-08-21T08:44:41.387

8Correctly handling lower/upper case in Unicode is scary, so is this question voluntarily limited to ASCII letters: [a-zA-Z]? – Matthieu M. – 2015-08-21T09:03:16.637

3

You forgot to close the parenthesis after "see this GolfScript answer". https://xkcd.com/859/

– nyuszika7h – 2015-08-21T09:24:19.123

1"Your score is your byte count." So I rank better when I have more bytes? Maybe you should update that one :P – BlueWizard – 2015-08-21T17:51:21.917

1@JonasDralle: remember, this is golf, where scoring is always backwards! – Lynn – 2015-08-21T22:11:45.900

Answers

11

Pyth, 10 bytes

sm@+drd1zG

Try it online: Demonstration

Explanation:

             implicit: z = input string
 m       G   map each letter (variable d) of the alphabet to:
   +drd1        d + upper(d)
  @     z       filter z for these two letters
s            sum, join to a string

Jakube

Posted 2015-08-21T07:11:06.310

Reputation: 21 462

5

Python 3, 72 70 bytes

s=input()
print("".join(d*(ord(d)&31==c)for c in range(27)for d in s))

Assumes the input consists of only [a-zA-Z].

(-2 bytes thanks to @xnor)

Sp3000

Posted 2015-08-21T07:11:06.310

Reputation: 58 729

I think you can do "".join(c*b ...) for "".join(c ... if b) the same way sum(n ... if b) can be sum(n*b ...). – xnor – 2015-08-22T01:46:34.140

Collapsing the two loops into a single loop with a sentinel, and compressing the equality check: c=1 for d in(input()+'~')*26:print(d[ord(d)&32^c:],end='');c+=d>'z' (67) – xnor – 2015-08-22T02:20:11.483

@xnor I've added the first tip (thanks!) but I think you should post the second as a separate answer :) – Sp3000 – 2015-08-22T03:24:52.820

5

Haskell, 51

f s=[x|(a,b)<-zip['a'..'z']['A'..],x<-s,x==a||x==b]

The zip creates a list of pairs of characters [('a','A'), ...('z','Z')]. Because of truncation, the second endpoint doesn't need to be specified. For each pair in the list, we take the letters in the input string s that are either of the two characters in the pair.

xnor

Posted 2015-08-21T07:11:06.310

Reputation: 115 687

4

Pyth, 15 14 bytes

s*V/LzJ.irG1GJ

Thanks for isaacg for removing 1 byte.

I don't know much about Pyth yet, so this may not be golfed well.

Try it here.

jimmy23013

Posted 2015-08-21T07:11:06.310

Reputation: 34 042

One easy golf: s is the same as jk on a list of strings. – isaacg – 2015-08-21T08:08:07.923

4

GOTO++, 531 bytes

niveaugourou 0
s=ENTRETONTEXTE()
§2 a=LeCaracNumero()&s *(1)
n=*(1)
costaud i=*(2)/&i infeg NombreDeLettres(&s)/i=+*(1)
b=LeCaracNumero()&s &i
c=&b
d=&a
GOTONULPOURLESNULS %4 }&b sup *(96){
c=-*(32)
§4 GOTONULPOURLESNULS %5 }&a sup *(96){
d=-*(32)
§5 GOTONULPOURLESNULS %1 }&c inf &d{
a=&b
n=&i
§1 faiblard
GOTOPRINTDUTEXTE()&a
s=Marijuana()}BOITEAPINGOUINS()}PrendsUnMorceau()&s *(0) &n{ }PrendsUnMorceau()&s }&n+*(1){ *(0){{ «»
GOTONONNULPOURLESNULS %3 }NombreDeLettres(&s) eg *(1){
GOTOPASMALIN %2
§3 GOTOPRINTDUTEXTE()&s

GOTO++ Project page

Here's a slighlty more readable and commented version of the code(Note that GOTO starts a comment in GOTO++):

niveaugourou 0                                          GOTO Allow every keyword to be used
s=ENTRETONTEXTE()                                       GOTO Read from STDIN
§2 a=LeCaracNumero()&s *(1)                             GOTO Get first char in s
n=*(1)                                                  
costaud i=*(2)/&i infeg NombreDeLettres(&s)/i=+*(1)     GOTO Loop on every char of s
b=LeCaracNumero()&s &i                                  GOTO b = i-th char
c=&b                                            
d=&a
GOTONULPOURLESNULS %4 }&b sup *(96){                    GOTO If b is uppercase, goto §4 
c=-*(32)                                                GOTO Get the uppercase ASCII value of b
§4 GOTONULPOURLESNULS %5 }&a sup *(96){                 GOTO same as above but with a
d=-*(32)                                                
§5 GOTONULPOURLESNULS %1 }&c inf &d{                    GOTO If b is after a in alphabetical order, goto §1 (next loop iteration)
a=&b                                                    GOTO Else replace a by b
n=&i                                                                
§1 faiblard                                             GOTO End loop
GOTOPRINTDUTEXTE()&a                                    GOTO Print the value of a
t=PrendsUnMorceau()&s *(0) &n                           GOTO Get the part of s before a
u=PrendsUnMorceau()&s }&n+*(1){ *(0)                    GOTO Get the part of s after a
e=BOITEAPINGOUINS()&t &u                                GOTO Create an array of penguins containing the two substrings
s=Marijuana()&e «»                                      GOTO Concatenate the penguins in the array
GOTONONNULPOURLESNULS %3 }NombreDeLettres(&s) eg *(1){  GOTO If s is one char long, goto §3
GOTOPASMALIN %2                                         GOTO Else goto §2
§3 GOTOPRINTDUTEXTE()&s                                 GOTO Print the last char

Fatalize

Posted 2015-08-21T07:11:06.310

Reputation: 32 976

2Marks of a great programming language: all commands are in French and the official website says "Send your logo et look dumb." – Alex A. – 2015-08-22T19:06:09.183

@AlexA. Mark of a great programming language: function(arg) and function() arg are both valid. Also, priority brackets are } { and not the boring ( ) – Fatalize – 2015-08-22T19:19:54.823

4

Javascript, 112 194 bytes

r=[];t=[];a=s.split('').map(function(x){t[i=parseInt(x,36)]?t[i].push(x):t[i]=[x];return i;});while(l=a.length)r[l-1]=t[a.splice(a.indexOf(Math.max.apply({},a)),1)].pop();console.log(r.join(''))

This is far away from "golfed" but I'm a bit busy right now, just editted to remove sort.

frikinside

Posted 2015-08-21T07:11:06.310

Reputation: 181

1@frikinside While it might not help this solution since sorting was disallowed, Javascript ES6 arrow functions could help shorten this. (Not all browsers support ES6 yet, try Firefox). Maybe it'll help your future solutions though! :) An example of what it might look like: console.log(input.split('').sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase())).join('')) – jrich – 2015-08-21T14:36:43.750

@UndefinedFunction Actually I choose to use plain javascript on purpose, for the "challenge" but thx a lot for the nice suggestion! – frikinside – 2015-08-24T11:19:13.143

@edc65 actually I was aware of that in a previous comment (like u said) and I did not forget it, I wasn't have time until now. – frikinside – 2015-08-24T11:23:58.583

4

JavaScript (ES6), 71 74

Limited to A-Za-z (see comment by @Matthieu M)

Edit Too used to compose a single expression with commas, to avoid 'return'. Here an output is required, so I can use a simple for and forget about commas.

Using array comprehension the byte count is 73, but that is not valid EcmaScript 6 anymore

Usual note: test running the snippet on any EcmaScript 6 compliant browser (notably not Chrome not MSIE. I tested on Firefox, Safari 9 could go)

f=w=>{v=[];for(c of w)v[n=parseInt(c,36)]=(v[n]||'')+c;alert(v.join``)}
<input id=I value='Hellzapoppin'><button onclick=f(I.value)>-></button>

edc65

Posted 2015-08-21T07:11:06.310

Reputation: 31 086

4

Python 3, 64

A small improvement on Sp3000's answer, which uses the idea of iterating iterating the character indices, and for each one, iterating through the input to take characters that match up to case.

c=1
for d in(input__+'~')*26:print(end=d[ord(d)&31^c:]);c+=d>'z'

This uses a single loop, looping through the input 26 times. The separator ~ is used to know when to go to the next character index c. To whether character d matches value c up to case, the last five bits of the bit-value of d are xor-ed with c, with a 0 indicating a match.

Then, the character d is printed exactly when the result is 0, with an empty string otherwise.

xnor

Posted 2015-08-21T07:11:06.310

Reputation: 115 687

3

PHP, 275 270 bytes

<?php
for($i=65;$i<123;$i++){$v[$i]=chr($i);}foreach(str_split($argv[1])as$c){$a=array_search($c,$v);if($a<97){$p[]=($a+32);$z[]=$a;}else{$p[]=$a;}}foreach($p as$chr){$m=min($p);if($z[0]+32==$m){echo chr($m-32);unset($z[0]);}else{echo chr($m);}unset($p[array_search($m,$p)]);}


Explanation:
The code generates an array with every letter in the alphabet, which has its ASCII Value as Array Key. Afterwards the code generates a new array which contains the ASCII Values of the Input. Then the lowest Value gets printed out and gets removed.

Usage:
Call the script with an argument: php -d error_reporting=0 script.php Hello

Ungolfed Version:

<?php
$input = $argv[1];
$valueArray = [];
for($i=65;$i<123;$i++) {
    $valueArray[$i] = chr($i);
}
$new = str_split($input);
foreach($new as $char) {
    if(array_search($char, $valueArray)<97) {
        $newArray[] = (array_search($char, $valueArray)+32);
        $checkArray[] = array_search($char, $valueArray);
    } else {
        $newArray[] = array_search($char, $valueArray);
    }
}
foreach($newArray as $chr) {
    if($checkArray[0]+32 == min($newArray)) {
        $string .= chr(min($newArray)-32);
        unset($checkArray[0]);
    } else {
        $string .= chr(min($newArray));
    }
    $key = array_search(min($newArray), $newArray);
    unset($newArray[$key]);
}

echo $string;


Any advices are greatly appreciated.

jrenk

Posted 2015-08-21T07:11:06.310

Reputation: 451

Uppercase letters are not working ... need to fix this. – jrenk – 2015-08-21T08:16:54.793

Fixed that the code also works when the Input has Uppercase letters. – jrenk – 2015-08-21T14:31:34.840

3

Python 2.7, 114 106 bytes

l=[0]*123
for e in raw_input():l[ord(e)]+=1
print''.join(chr(j)*l[j]for i in range(26)for j in(i+65,i+97))

Logs the presence of a char in a 123 length array(for including both A-Z and a-z ranges) and then iterates through it to get the non-zero entries.
Inefficient, but more efficient than brute forcing it(but longer :().

Testing it-

<< HelloWorldhi
>> deHhillloorW

Kamehameha

Posted 2015-08-21T07:11:06.310

Reputation: 553

When I run it with HelloWorldhi, I get ['d', 'e', 'H', 'h', 'i', 'lll', 'oo', 'r', 'W'] – Blue – 2015-08-21T11:09:50.690

@muddyfish oops my bad. I pasted the wrong code while trying out a couple of things. Thanks for that :) – Kamehameha – 2015-08-21T11:27:17.843

You don't need the if l[j] either. – Blue – 2015-08-21T11:47:16.593

@muddyfish Nice, they become empty strings(and are removed when joined). -8 bytes. Thanks :) – Kamehameha – 2015-08-21T11:53:47.160

You could replace raw_input with just input if your input is 'HelloWorldhi' instead of HelloWorldhi. – SirParselot – 2015-08-21T12:38:59.613

1@SirParselot Yeah, but that seemed like modifying the input as given in the question, so didn't do that – Kamehameha – 2015-08-21T13:17:59.153

It doesn't say anything about it in the instructions, but it's your code so it's up to you – SirParselot – 2015-08-21T13:28:37.223

3

Haskell, 83 53 bytes

import Data.Char
f y=[c|x<-[' '..],c<-y,toLower c==x]

Usage: f "HelloWorldhi" -> "deHhillloorW".

How it works: let y be the input string

[ |x<-[' '..]                  ]  -- for every x from Space to the last Unicode character
             ,c<-y                -- loop through all character c from the input string
 c                ,toLower c==x   -- and keep those where the lowercase version equals x

Edit: 30 bytes saved, imagine that! Thanks @Mauris.

nimi

Posted 2015-08-21T07:11:06.310

Reputation: 34 639

2Why not just import Data.Char;f y=[c|x<-[' '..],c<-y,toLower c==x] (53 bytes)? (This will take some time to terminate, because length [' '..] == 1114080 -- but it's finite.) – Lynn – 2015-08-21T22:07:01.410

1@Mauris: Wow! Btw: 8.5sec on a 4 year old laptop is not too long. – nimi – 2015-08-21T22:48:31.650

3

Python 3, 61 bytes

A new answer for a different technique!

z=['']*42
for c in input():z[ord(c)&31]+=c
print(*z,sep='')

Noting that ord('a')&31==ord('A')&31 and that ord('z')&31==ord('Z')&31, we can simply create an array of empty strings and for each character add it to the array index of its ASCII value &31. When you print it, it will be sorted.

Limited to input a-zA-Z.

Tryth

Posted 2015-08-21T07:11:06.310

Reputation: 750

2

Python 3, 97 92 bytes

from itertools import*;print(*min(permutations(input()),key=lambda z:str(z).lower()),sep='')

The best way to sort is clearly to generate all permutations, and then pick the minimum, which just happens to be sorted :)

The strings are lowercased before comparison to abide by the 'case-aware' rules.

Warning: may be very slow with big strings.

An interpreter is located here.

Tryth

Posted 2015-08-21T07:11:06.310

Reputation: 750

2

Python 3, 118 bytes

i=input();i,x=map(list,(i,i.lower()))
while x:q=min(x);x.remove(q);q=[q.upper(),q][q in i];i.remove(q);print(q,end="")

Could be golfed much shorter, I know

Blue

Posted 2015-08-21T07:11:06.310

Reputation: 26 661

You can replace if q not in i: with if~-(q in i):. – PurkkaKoodari – 2015-08-21T10:41:38.027

I do because I'm calling the .remove() function on it. – Blue – 2015-08-21T10:57:54.737

2

Powershell, 164 Bytes

I'm sure there's a cleaner way to do this, but I couldn't come up with anything else. Just takes the input as a character array, does an insertion sort, and spits out the output. Loses horribly, even to other non-golfing languages.

Code:

$a=[char[]]($args[0]);For($u=1;$u-lt$a.Count;$u++){$n=$a[$u];$l=$u;while(($l-gt0)-and((""+$a[$l-1]).CompareTo(""+$n)-gt0)){$a[$l]=$a[$l-1];$l--}$a[$l]=$n};$a-join''

Usage:

PS C:\scripts> .\sign-word-2.ps1 tTHhis
hHistT

Expanded & Explained:

$a=[char[]]($args[0])               # Takes command-line argument, recasts as char array
For($u=1;$u-lt$a.Count;$u++){       # Performs a quick-n-dirty insertion sort
  $n=$a[$u]
  $l=$u
  while(($l-gt0)-and((""+$a[$l-1]).CompareTo(""+$n)-gt0)){
  # Ugly, ugly code here. String.CompareTo(String) is case-insensitive, but
  # because we cast as a char[], Char.CompareTo(Char) is case-sensitive ...
  # So, need to do an on-the-fly re-casting as a string with ""+
    $a[$l]=$a[$l-1]
    $l--
  }
  $a[$l]=$n
}
$a-join''             # Without the -join'', it would print out the chars with a space between

AdmBorkBork

Posted 2015-08-21T07:11:06.310

Reputation: 41 581

2

Julia, 61 bytes

f=s->s>""?(k=indmax([s...]%32);f(s[k+1:end]s[1:k-1])s[k:k]):s

Julia will display it as a string output if you call it in the REPL. If it has to print out to STDOUT, then it needs 78 bytes:

x->(f=s->s>""?(k=indmax([s...]%32);f(s[k+1:end]s[1:k-1])s[k:k]):s;print(f(x)))

An interpreter for Julia can be found here. Another one, which I've already put some code into, is here. Note that, with the second one, you will need to make the terminal (at the bottom) visible by dragging the boundary up. Clicking "execute" will make it run in the terminal at the normal command line (and thus won't show the output if called without println). Alternatively, you can just type julia into the terminal itself, then handle everything inside the REPL that will come up.

And for a bit of extra fun, here are some other implementations

Gnome Sort (83 bytes):

s->(for m=2:endof(s),n=m:-1:2 s[n]%32<s[n-1]%32&&(s=s[[1:n-2,n,n-1,n+1:end]])end;s)

My own sorting algorithm (84 bytes):

s->(k=1;while length(k)>0 k=find(diff([s...]%32).<0);s=s[setdiff(1:end,k)]s[k]end;s)

Glen O

Posted 2015-08-21T07:11:06.310

Reputation: 2 548

2

Java (JDK 10), 125 bytes

s->{for(int i=s.length,j;i-->1;)for(j=i;j-->0;)s[i]^=(s[i]&95)<(s[j]&95)?s[j]^(s[j]=s[i]):0;System.out.print(new String(s));}

Try it online!

Using a naive sort.

Olivier Grégoire

Posted 2015-08-21T07:11:06.310

Reputation: 10 647

2

Scala, 82 bytes

print((""/:args(0)){case(s,c)=>val(a,b)=s.span(h=>{if(h<97)32 else 0}+h<c);a+c+b})

from command line:

$ scala -e 'print((""/:args(0)){case(s,c)=>val(a,b)=s.span(h=>{if(h<97)32 else 0}+h<c);a+c+b})' Hello
eHllo

probably can be golfed a bit further... just implementing insertion sort using fold.

gilad hoch

Posted 2015-08-21T07:11:06.310

Reputation: 717

2

x86 machine code, 51 42 bytes

00000000  b3 82 89 da 8b 07 80 fc  0d 74 12 b9 20 20 09 c1  |.........t..  ..|
00000010  38 e9 7e 06 86 c4 89 07  31 d2 43 eb e7 85 d2 74  |8.~.....1.C....t|
00000020  df c6 47 01 24 b4 09 cd  21 c3                    |..G.$...!.|
0000002a

Bubble sort, with some register reuse tricks to shave bytes here and there; the .COM file runs in DosBox, receives the input from command line and prints the output to standard output.

sample session

Commented assembly:

    org 100h

section .text

start:
    ; bubble sort - external loop
ext:
    ; start from the first character (assume bh=0, true on every DOS)
    mov bl,82h
    ; "not-swapped" flag - 82h => no swaps in current iteration;
    ; 0 => a swap happened (the 82h will come in handy later)
    mov dx,bx
    ; bubble sort - internal loop
int:
    ; read 2 characters at time in the full ax
    mov ax,word[bx]   ; al     ah
                      ; ^[bx]  ^[bx+1]
    ; check if we are at the end (the command line is CR terminated)
    cmp ah,0dh
    je skip
    ; make uppercase in cx
    mov cx,2020h
    or cx,ax
    ; compare
    cmp cl,ch
    jle next
    ; wrong order - swap and rewrite
    xchg al,ah
    mov word[bx],ax
    ; mark that we did a swap
    xor dx,dx
next:
    ; next character
    inc bx
    jmp int
skip:
    ; loop as far as we swapped something
    test dx,dx
    jz ext
end:
    ; $-terminate the string
    mov byte[bx+1],'$'
    ; print
    ; dx already contains the location of the string, since that's the
    ; flag value we used for "no swaps"
    mov ah,9
    int 21h
    ret

Matteo Italia

Posted 2015-08-21T07:11:06.310

Reputation: 3 669

1

Perl, 88 bytes

@_=/./g;a:{for(0..@_-2){@_[$_,$_+1]=@_[$_+1,$_],redo a if uc$_[$_]gt uc$_[$_+1]}}print@_

Just a simple Bubble Sort. Call with -n option to pass the text.

e.g:

echo "tThHiIsS" | perl -n sort2.pl

Output:

hHiIsStT

samgak

Posted 2015-08-21T07:11:06.310

Reputation: 1 577

1

PHP, 106 bytes

The code:

$c=count_chars($argv[1]);$r=str_repeat;for($i=64;++$i<91;)echo$r(chr($i),$c[$i]),$r(chr($i+32),$c[$i+32]);

There is nothing special in the code; count_chars() produces an array indexed by ASCII codes that contains the number of occurrences for each ASCII character. The rest is a dull iteration over this array.

Example of execution:

$ php -d error_reporting=0 sign.php qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKasdfJHGFDSAZXCVBNM
AaaBbCcDddEeFffGgHhIiJjKkLlMmNnOoPpQqRrSssTtUuVvWwXxYyZz

An extra byte can be saved using PHP 7: replace $c[$i] with ($c=count_chars($argv[1]))[$i] and remove the assignment of $c from the beginning of the program.

axiac

Posted 2015-08-21T07:11:06.310

Reputation: 749

1

Haskell, 74 bytes

l=(`mod`32).fromEnum
f=foldr(#)""
e#[]=[e]
e#a@(h:t)|l e<l h=e:a|1<2=h:e#t

Completely different from my other answer. This time it's a simple Insertion sort.

nimi

Posted 2015-08-21T07:11:06.310

Reputation: 34 639

1

Pip, 18 14 bytes

GitHub repository for Pip

Seems there's no competing with Pyth, but this is pretty respectable.

FcAZ OcQUC_FIa

Works only on strings containing a-zA-Z. For each letter of the alphabet, uses a filter operation to grab the letters from the input string that equal that letter case-insensitively:

                    a <- cmdline arg, AZ <- string containing uppercase alphabet (implicit)
FcAZ                For each character c in AZ:
           FIa      Filter characters of a on the following lambda function:
      UC_           Uppercase of character...
         Qc         ... is equal to c
     O              Output the resulting list, joined on empty string by default

Two notes:

  • The space is necessary; otherwise, the sequence AZO would scan as A ZO instead of AZ O;
  • The program doesn't output a trailing newline. To add one, put an x at the end of the code (thereby printing an empty string after the loop is done).

Sample run (using the x variant):

dlosc@dlosc:~/pip$ pip -e "FcAZ OcQUC_FIax" "HelLo wOrld"
deHlLloOrw

DLosc

Posted 2015-08-21T07:11:06.310

Reputation: 21 213

0

Perl 5 -a, 31 bytes

for$i(a..z){print grep/$i/i,@F}

Try it online!

Xcali

Posted 2015-08-21T07:11:06.310

Reputation: 7 671