TransWikia.com

Dissect a word and arrange all its letters in alphabetical order

Code Golf Asked by Riley Jones on December 22, 2020

Question

Write a program to accept one string on the console only and print back its letters arranged in alphabetical order. The string must only have the following characters:

0123456789abcdefghijklmnopqrstuvwxyz

Rules

The ascending alphabetical order is defined in the given string.

All repeated characters must be printed.

If the string contains characters other than the ones mentioned above, it must display “Invalid input”.

This is code-golf, so shortest answer in bytes wins.

Standard loopholes are forbidden.

A null string “” will output “Invalid input”.

Your program must be executable and not a function or snippet.

Boilerplate is not required.

Examples

"dragon"--> adgnor
"skoda3ferrari"--> 3aadefikorrrs
"ferret"--> eefrrt
"werewolf92"--> 29eeflorww
"@hog"--> Invalid input
"gTa5"--> Invalid input
"  l "--> Invalid input
""--> Invalid input

Edit: The double quotes are given for clarification.

May the force be with you. Good luck!

13 Answers

05AB1E, 16 15 bytes

-1 byte thanks to Kevin Cruijssen

žKlsSåßi{ë”ͼî®

Try it online!

Correct answer by Grimmy on December 22, 2020

Charcoal, 37 bytes

≔⁺⭆χιβη¿∨¬θ⊙θ¬№ηιInvalid inputFηF№θιι

Try it online! Link is to verbose version of code. Explanation:

≔⁺⭆χιβη

Concatenate the digits with the lowercase letters.

¿∨¬θ⊙θ¬№ηι

If the input is empty or contains a character not in the digit letter string, ...

Invalid input

... then output the required error message, ...

Fη

... else for each digit and lowercase letter...

F№θιι

... output each time it appears in the input.

Answered by Neil on December 22, 2020

x86-16 machine code, IBM PC-DOS, 81 80 bytes

Binary:

00000000: b40a ba4f 01cd 218b f2ad 8bd6 8acc 8be9  ...O..!.........
00000010: 938b f28b fe51 ad3c 307c 0c3c 397e 0e3c  .....Q.<0|.<9~.<
00000020: 617c 043c 7a7e 06ba 4201 59eb 103a c47c  a|.<z~..B.Y..:.|
00000030: 0286 c4ab 4e4f e2de 59e2 d688 1bb4 09cd  ....NO..Y.......
00000040: 21c3 496e 7661 6c69 6420 696e 7075 7424  !.Invalid input$

Build and test DISSECT.COM using xxd -r

Unassembled listing:

B4 0A           MOV  AH, 0AH            ; DOS read buffered input from STDIN 
BA 014F R       MOV  DX, OFFSET BUF     ; load buffer pointer    
CD 21           INT  21H                ; get STDIN input 
8B F2           MOV  SI, DX             ; buffer pointer into SI 
AD              LODSW                   ; load char count into AH 
8B D6           MOV  DX, SI             ; save start of string 
8A CC           MOV  CL, AH             ; string length into CX 
8B E9           MOV  BP, CX             ; save string length for later display 
            OUTER_LOOP: 
8B F2           MOV  SI, DX             ; reset SI to beginning of buffer 
8B FE           MOV  DI, SI             ; reset DI to beginning of buffer 
51              PUSH CX                 ; save outer loop counter 
            INNER_LOOP: 
AD              LODSW                   ; load next two chars into AH/AL
3C 30           CMP  AL, '0'            ; is char < '0' ? 
7C 0C           JL   INVALID            ; if so, not valid 
3C 39           CMP  AL, '9'            ; is char <= '9'? 
7E 0E           JLE  VALID              ; if so, valid 
3C 61           CMP  AL, 'a'            ; is char < 'a'? 
7C 04           JL   INVALID            ; if so, not valid 
3C 7A           CMP  AL, 'z'            ; is char <= 'z'? 
7E 06           JLE  VALID              ; if so, valid 
            INVALID: 
BA 0142 R       MOV  DX, OFFSET INV     ; load address of "invalid" string 
59              POP  CX                 ; discard saved counter 
EB 11           JMP  OUTPUT             ; display "invalid" string
            VALID: 
3A C4           CMP  AL, AH             ; compare chars 
7C 02           JL   NO_SWAP            ; if AL < AH, do not swap 
86 C4           XCHG AL, AH             ; otherwise, swap chars 
            NO_SWAP:
AB              STOSW                   ; store chars back to buffer 
4E              DEC  SI                 ; adjust SI to previous char 
4F              DEC  DI                 ; adjust DI to previous char 
E2 DE           LOOP INNER_LOOP         ; loop inner iterations
59              POP  CX                 ; restore outer loop counter 
E2 D6           LOOP OUTER_LOOP         ; loop outer
C6 03 24        MOV  BYTE PTR[BP+DI],'$'; add string terminator
            OUTPUT:
B4 09           MOV  AH, 09H            ; DOS display string function 
CD 21           INT  21H                ; write output to console 
C3              RET                     ; exit to DOS

INV DB "Invalid input"                  ; "invalid" message string
BUF DB '$'                               ; buffer size is 36 bytes, also string terminator

Standalone PC DOS executable. Implements a simple bubble sort algorithm.

Input via console/STDIN, output to console/STDOUT.

enter image description here

Answered by 640KB on December 22, 2020

Perl 5 -pF//, 45 bytes

$_=/^[a-zd]+$/?join"",sort@F:"Invalid Input"

Try it online!

Answered by Nahuel Fouilleul on December 22, 2020

PHP, 92 bytes

$a=str_split($s=$argn);sort($a);echo preg_match('/^[a-zd]+$/',$s)?join($a):'Invalid input';

Try it online!

Answered by 640KB on December 22, 2020

Burlesque, 37 bytes

><JJann!/^zz!=||{vv"Invalid Input"}if

Try it online!

><                    # Sort input string
JJ                    # Duplicate twice
ann!                  # Not alphanumeric
/^                    # Swap and duplicate (sorted string)
zz!=                  # Lowercased not equal to original (i.e. contains uppercase)
||                    # Or
{vv"Invalid Input"}if # If not alphanumeric or lowercase drop sorted list 
                        and output invalid input

Answered by DeathIncarnate on December 22, 2020

Jelly, 18 bytes

ɠfƑØBŒl¤ȧṢȯ“4{ẉṄi»

Try it online!

A full program that reads its input from STDIN and outputs to STDOUT.

If the input validation and requirement to use STDIN were removed, this would be a single byte:

Answered by Nick Kennedy on December 22, 2020

C++ (clang), 223 $cdots$ 182 170 bytes

Saved 8 a whopping 20 bytes thanks to ceilingcat!!!

#import<bits/stdc++.h>
int main(){std::string s,i="Invalid input";getline(std::cin,s);sort(begin(s),end(s));for(int c:s)s=c<48|c>122|c>57&c<97?i:s;std::cout<<(s[0]?s:i);}

Try it online!

A program that reads a single string from stdin (handling all invalid cases) and outputs to stdout.

Answered by Noodle9 on December 22, 2020

Red, 86 bytes

func[s][a: charset[#"0"-#"9"#"a"-#"z"]either parse sort s[some a][s]["Invalid input"]]

Try it online!

Answered by Galen Ivanov on December 22, 2020

APL (Dyalog Extended), 37 bytesSBCS

{0∊(≢⍵),⍵∊⎕D,⌊⎕A:'Invalid input'⋄∧⍵}⍞

Try it online!

 prompt for text input from the console

{} apply the following anonymous lambda to that:

⎕A the uppercase Alphabet

Lowercase that

⎕D, prepend the digits

⍵∊ for each character of the argument, indicate if it is a member thereof

(), prepend the following:

  ≢⍵ the tally of characters in the argument

0∊: if zero is a member thereof:

  'Invalid input' return (and implicitly print) this message

 else:

  ∧⍵ sort the argument ascending

Answered by Adám on December 22, 2020

Keg, 35 bytes

₳0a&᠀:(⑴|⑻-)⒃᠀⒃¬+[Invalid input|¿÷⑭

Nice to see Keg still "up to par" with Golfscript! No regrets about the bad pun

Answered by Lyxal on December 22, 2020

GolfScript, 37 bytes

.$58,48>123,97>+-!*"Invalid input"or

Try it online!

Explanation

Whoa. Maybe I shouldn't have done this..

.                                     # Make 2 copies of the input,
 $                                    # One is the sorted copy of the input,
  58,48>123,97>+-!                   # Another is whether all of input is in the
                                      # lowercase alphanumeric range
                   *                  # Multiply them:
                                      #     If the input contains invalid characters,
                                      #     e.g. @hog, this multiplies the sorted copy by 0.
                                      # ----If the input is a null string,
                                      #     The input multiplies 0 by the null string, 
                                      #     which is still the null string.
                                      # ----If the input is a valid string,
                                      #     e.g. dragon, the input multiplies the
                                      #     sorted copy by 1 (because everything is
                                      #     inside the range)
                    "Invalid input"or # Do a "logical magic":
                                      #     If the input is 0 or the null string, 
                                      #         returns "Invalid input"
                                      #     Otherwise, this returns the
                                      #         sorted copy of the input.

# Further explanation of the code snippet
#                  # Swap the stack so that an unused copy of the input emerges
#  58,              # Generate a range and drop the last: 0 to ASCII ':'
                    # (The previous character is '9')
#     48>           # Select everything that is larger than 48 (ASCII '0')
#        123,97>    # Same thing with generating 'a' to 'z'
#               +   # Join the inputs together
#                -  # Set subtraction: subtract this string from the fresh unused input
#                   # This results in everything that isn't alphanumeric
#                 ! # Negate the string. If the string has something, 
#                   # it turns to 0. Otherwise it turns to 1.
```

Answered by user85052 on December 22, 2020

Python 3.8 (pre-release), 77 75 74 88 bytes

import re
print(*re.match('[0-9a-z]+$',i:=input())and sorted(i)or'Invalid input',sep='')

Try it online!

Answered by TFeld on December 22, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP