17
\$\begingroup\$

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>

\$\endgroup\$
  • 2
    \$\begingroup\$ Must lowercase and uppercase be ordered? For example, for ThHihs, can we output hHhist or do we have to output hhHist or Hhhist? \$\endgroup\$ – Fatalize Aug 21 '15 at 7:20
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ – feersum Aug 21 '15 at 7:29
  • 1
    \$\begingroup\$ @feersum You don't need to. There is a link in the answer to an online interpreter. But I will make it clearer. \$\endgroup\$ – user42003 Aug 21 '15 at 7:35
  • 8
    \$\begingroup\$ Correctly handling lower/upper case in Unicode is scary, so is this question voluntarily limited to ASCII letters: [a-zA-Z]? \$\endgroup\$ – Matthieu M. Aug 21 '15 at 9:03
  • 3
    \$\begingroup\$ You forgot to close the parenthesis after "see this GolfScript answer". xkcd.com/859 \$\endgroup\$ – nyuszika7h Aug 21 '15 at 9:24

24 Answers 24

11
\$\begingroup\$

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
\$\endgroup\$
5
\$\begingroup\$

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.

\$\endgroup\$
5
\$\begingroup\$

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)

\$\endgroup\$
  • \$\begingroup\$ 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 ...). \$\endgroup\$ – xnor Aug 22 '15 at 1:46
  • \$\begingroup\$ 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) \$\endgroup\$ – xnor Aug 22 '15 at 2:20
  • \$\begingroup\$ @xnor I've added the first tip (thanks!) but I think you should post the second as a separate answer :) \$\endgroup\$ – Sp3000 Aug 22 '15 at 3:24
4
\$\begingroup\$

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
\$\endgroup\$
  • 2
    \$\begingroup\$ Marks of a great programming language: all commands are in French and the official website says "Send your logo et look dumb." \$\endgroup\$ – Alex A. Aug 22 '15 at 19:06
  • \$\begingroup\$ @AlexA. Mark of a great programming language: function(arg) and function() arg are both valid. Also, priority brackets are } { and not the boring ( ) \$\endgroup\$ – Fatalize Aug 22 '15 at 19:19
4
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ One easy golf: s is the same as jk on a list of strings. \$\endgroup\$ – isaacg Aug 21 '15 at 8:08
4
\$\begingroup\$

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>

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

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ @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('')) \$\endgroup\$ – jrich Aug 21 '15 at 14:36
  • \$\begingroup\$ @UndefinedFunction Actually I choose to use plain javascript on purpose, for the "challenge" but thx a lot for the nice suggestion! \$\endgroup\$ – frikinside Aug 24 '15 at 11:19
  • \$\begingroup\$ @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. \$\endgroup\$ – frikinside Aug 24 '15 at 11:23
4
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ When I run it with HelloWorldhi, I get ['d', 'e', 'H', 'h', 'i', 'lll', 'oo', 'r', 'W'] \$\endgroup\$ – Blue Aug 21 '15 at 11:09
  • \$\begingroup\$ @muddyfish oops my bad. I pasted the wrong code while trying out a couple of things. Thanks for that :) \$\endgroup\$ – Kamehameha Aug 21 '15 at 11:27
  • \$\begingroup\$ You don't need the if l[j] either. \$\endgroup\$ – Blue Aug 21 '15 at 11:47
  • \$\begingroup\$ @muddyfish Nice, they become empty strings(and are removed when joined). -8 bytes. Thanks :) \$\endgroup\$ – Kamehameha Aug 21 '15 at 11:53
  • 1
    \$\begingroup\$ @SirParselot Yeah, but that seemed like modifying the input as given in the question, so didn't do that \$\endgroup\$ – Kamehameha Aug 21 '15 at 13:17
3
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ Uppercase letters are not working ... need to fix this. \$\endgroup\$ – jrenk Aug 21 '15 at 8:16
  • \$\begingroup\$ Fixed that the code also works when the Input has Uppercase letters. \$\endgroup\$ – jrenk Aug 21 '15 at 14:31
3
\$\begingroup\$

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.

\$\endgroup\$
  • 2
    \$\begingroup\$ Why 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.) \$\endgroup\$ – Lynn Aug 21 '15 at 22:07
  • 1
    \$\begingroup\$ @Mauris: Wow! Btw: 8.5sec on a 4 year old laptop is not too long. \$\endgroup\$ – nimi Aug 21 '15 at 22:48
3
\$\begingroup\$

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.

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

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.

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

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

\$\endgroup\$
  • \$\begingroup\$ You can replace if q not in i: with if~-(q in i):. \$\endgroup\$ – PurkkaKoodari Aug 21 '15 at 10:41
  • \$\begingroup\$ I do because I'm calling the .remove() function on it. \$\endgroup\$ – Blue Aug 21 '15 at 10:57
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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)
\$\endgroup\$
2
\$\begingroup\$

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.

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

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
\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

Perl 5 -a, 31 bytes

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

Try it online!

\$\endgroup\$

Your Answer

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