-6
\$\begingroup\$

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!

\$\endgroup\$
  • 3
    \$\begingroup\$ Any particular reason for the input being restricted to the console? Why not allow a function taking an argument? \$\endgroup\$ – Adám Jan 8 at 10:15
  • \$\begingroup\$ What if my function is executable without boilerplate? \$\endgroup\$ – Adám Jan 8 at 10:16
  • 2
    \$\begingroup\$ @RileyJones Why is "" invalid? It has no characters outside the set. \$\endgroup\$ – Adám Jan 8 at 10:46
  • 11
    \$\begingroup\$ Hi! I've downvoted this post as it goes against several site conventions (allowable I/O methods, allowed to be programs or functions, and input parsing) without really providing justification for those decisions (e.g., input parsing as a core component of the challenge). \$\endgroup\$ – AdmBorkBork Jan 8 at 13:32
  • 2
    \$\begingroup\$ Hi Riley, thank you for your challenge. Please do stick around, and answer a few challenges to get to know the site better. It would be a good idea to post your next challenge to the sandbox (see link at top right of screen) for review before it goes live. @AdmBorkBork I applaud you for explaining the reason for your downvote, and I don't disagree with your reasons. On the other hand I think all of us need to be a bit more welcoming and lenient with new contributors lest they are put off using the site in future. \$\endgroup\$ – Level River St Jan 9 at 20:16

13 Answers 13

5
\$\begingroup\$

05AB1E, 16 15 bytes

-1 byte thanks to Kevin Cruijssen

žKlsSåßi{ë”ͼî®

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Your Input is titlecased as well now. \$\endgroup\$ – Kevin Cruijssen Jan 8 at 12:26
  • \$\begingroup\$ @KevinCruijssen Yeah, several other answers titlecase Input, so I assumed it wasn't an issue \$\endgroup\$ – Grimmy Jan 8 at 12:29
  • 1
    \$\begingroup\$ Ah ok. Btw, you can also save a byte by changing {ОKlм‚õ¢≠i to žKlsSåßi{ë: verify all test cases. \$\endgroup\$ – Kevin Cruijssen Jan 8 at 13:28
  • \$\begingroup\$ @a'_' I had already stated that in my first comment. :) And I've asked OP about it, but no response yet. It's easy to fix in 2 bytes though, by changing the ”Í¼î® to „ͼî®.ª: try it online. \$\endgroup\$ – Kevin Cruijssen Jan 8 at 14:52
4
\$\begingroup\$

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

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

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
\$\endgroup\$
  • \$\begingroup\$ The first Burlesque answer after 2 years! \$\endgroup\$ – a'_' Jan 8 at 14:21
  • 2
    \$\begingroup\$ I've recently been trying to learn it for a bit of fun. I looked at it several years ago and decided I'd go for befunge instead. Finally decided to give it a go for this year's advent of code. \$\endgroup\$ – DeathIncarnate Jan 8 at 14:41
4
\$\begingroup\$

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

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

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!

\$\endgroup\$
  • \$\begingroup\$ Fails on input that contains only numbers. Input 123 outputs Invalid input. \$\endgroup\$ – mypetlion Jan 8 at 18:07
  • \$\begingroup\$ Also fails on lowercase characters outside of the given alphabet. For example ú does not output Invalid input. \$\endgroup\$ – mypetlion Jan 8 at 18:11
  • \$\begingroup\$ @mypetlion Fixed \$\endgroup\$ – TFeld Jan 9 at 8:18
  • \$\begingroup\$ @a'_' Fixed now \$\endgroup\$ – TFeld Jan 9 at 8:18
3
\$\begingroup\$

Red, 86 bytes

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

Try it online!

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

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:

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

Perl 5 -pF//, 45 bytes

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

Try it online!

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

Keg, 35 bytes

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

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

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

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.
```
\$\endgroup\$
  • \$\begingroup\$ But now it doesn't \$\endgroup\$ – Lyxal Jan 9 at 0:37
2
\$\begingroup\$

PHP, 92 bytes

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

Try it online!

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

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.

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

C++ (clang), 223 \$\cdots\$ 190 182 bytes

#import<regex>
#import<iostream>
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;s=s[0]?s:i;std::cout<<s;}

Try it online!

Saved 8 bytes thanks to ceilingcat!!!

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

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.