Check whether letters of word are in alphabetical order

37

3

Write a function/program that accepts a string of lower/uppercase letters [A-Za-z] as input, that checks whether the occuring letters are unique and in alphabetical order (ignoring lower and uppercase) or not. The output must be truthy if they are unique and in alphabetical order and falsy if not.

Here some testcases

a                           true
abcdefGHIjklmnopqrSTUVWXyz  true     
aa                          false
puz                         true
puzz                        false
puzZ                        false
puZ                         true
PuZ                         true
pzu                         false
pzU                         false
abcdABCD                    false
dcba                        false

If you want, run your program on all words of a wordlist like this one and and post some interesting ones =).

Score

Lowest number of bytes wins.

flawr

Posted 2015-03-01T11:42:37.923

Reputation: 40 560

3

Weak test cases. (See my comment on Richard A's PHP answer.)

– manatwork – 2015-03-11T17:20:30.303

Does the alphabet loop? Should za be a truthy value? – MayorMonty – 2015-09-24T01:06:53.850

No, the alphabet begins with a and ends with z. – flawr – 2015-09-24T12:17:20.650

You should have some test cases that aren't in alphabetical order – Jo King – 2019-03-03T21:43:41.830

1@JoKing I added some. – flawr – 2019-03-05T09:02:22.710

@manatwork I don't really know PHP, can you suggest some explicit examples? – flawr – 2019-03-05T09:02:56.233

Your freshly added test cases are Ok, they make it obvious that the PHP solution lacks the order check part of the task. – manatwork – 2019-03-05T09:33:40.727

@manatwork Great, thanks for the rapid answer after you had to wait four years for mine:) – flawr – 2019-03-05T09:55:17.330

Answers

28

CJam, 8 bytes

lel_$_&=

Here is a test harness for all examples in the challenge. This returns 0 or 1 (which are falsy and truthy, respectively, in CJam).

And here is a script to filter the word list in the question (takes a few seconds to run). You'll have to copy the word list into the input field manually, because it's too long for a permalink.

Explanation

l        "Read input.";
 el      "Convert to lower case.";
   _$    "Get a copy and sort it.";
     _&  "Remove duplicates (by computing the set intersection with itself).";
       = "Check for equality with original (lower case) word.";

Martin Ender

Posted 2015-03-01T11:42:37.923

Reputation: 184 808

21

Regex (any flavor), 55 bytes

Some people don't consider regex to be a programming language, but it's been used before, and it's not close to being the shortest.

^a?b?c?d?e?f?g?h?i?j?k?l?m?n?o?p?q?r?s?t?u?v?w?x?y?z?$

I've added one byte for the i (case-insensitive) flag. This is very straightforward and might be shorter to generate on the fly.

If regex alone are not allowed, you can use this 56-byte Retina program suggested by Martin Büttner:

i`^a?b?c?d?e?f?g?h?i?j?k?l?m?n?o?p?q?r?s?t?u?v?w?x?y?z?$

Running this on the wordlist linked above yielded 10 6-letter words in alphabetical order.

["abhors", "almost", "begins", "begirt", "bijoux", "biopsy", "chimps", "chinos", "chintz", "ghosty"]

NinjaBearMonkey

Posted 2015-03-01T11:42:37.923

Reputation: 9 925

2

You can use Retina instead of ES6 if someone complains that regex is not a language: i`^a?b?c?d?e?f?g?h?i?j?k?l?m?n?o?p?q?r?s?t?u?v?w?x?y?z?$

– Martin Ender – 2015-03-01T17:12:46.450

@MartinBüttner I'd forgotten about Retina. Thanks! – NinjaBearMonkey – 2015-03-01T17:17:24.637

@MartinBüttner According to the META (http://meta.codegolf.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073) Regexes can be 'seen' somewhat as a programming language.

– Ismael Miguel – 2015-03-02T09:24:35.220

@IsmaelMiguel I know. And in fact that definition was specifically chosen to make sure it doesn't rule out regex. But some people still regularly complain, because you can't use regex like any other language. – Martin Ender – 2015-03-02T12:45:28.197

@MartinBüttner Those who complain can go to a place called META and look for it. Why no one visits such a beautiful place full of questions that solve most issues? – Ismael Miguel – 2015-03-02T12:54:08.897

If you want a dynamically generated version, there's a decently short and readable Haskell version with '^':concatMap(:"?")['a'..'z']++"$" (34 bytes) or a somewhat golfed Ruby version with ?^+(?a..?z).to_a.join(??)+?$ (28 bytes). – wchargin – 2015-03-02T22:44:28.257

(Correction to my last comment: Ruby code should end with +"?$". Use /#{?^+(?a..?z).to_a.join(??)+"?$"}/ to put it in a Regexp if needed.) – wchargin – 2015-03-02T22:51:14.460

Looks like 54 bytes to me. (26*2+2) – Eric – 2015-03-04T02:38:47.087

@Eric I added a byte for the i flag. – NinjaBearMonkey – 2015-03-04T02:39:42.933

@hsl Oh, duh, you even wrote that. I feel smrt. – Eric – 2015-03-04T02:40:09.610

19

Python 3, 44 bytes

*s,=input().lower()
print(sorted(set(s))==s)

A simple approach - check uniqueness, check sortedness.

Sp3000

Posted 2015-03-01T11:42:37.923

Reputation: 58 729

Can you explain what *s,=... does? – flawr – 2015-03-01T13:22:02.783

@flawr This is called 'starred assignment'. In this code, it simply converts the right side into a list. It's the same as s=list(input().lower()). – Jakube – 2015-03-01T13:40:00.560

1@flawr As Jakube says, here it's just converting input into a list of chars. In general it's a special assignment syntax which lets you do things like x,*y = [1, 2, 3, 4], which assigns 1 to x and [2, 3, 4] to y. – Sp3000 – 2015-03-01T13:42:52.840

@mbomb007 *s,= is list(s)... link

– Sp3000 – 2015-03-02T22:43:39.390

You can do {*s} instead of set(s) to save 2 bytes. – mbomb007 – 2017-01-17T19:53:51.597

@mbomb007 Python 3.5.0 came after this answer – Sp3000 – 2017-01-18T11:43:00.060

Ah, right. Nevermind. – mbomb007 – 2017-01-18T14:54:08.963

12

><>, 52 42 39 bytes

0>i:1+?v1n;
? )'`':/'@'v
0v?){:-<'`'/;n

This type of question is one of the few types that ><> is pretty comfortable with, since we only need to deal with one char at a time.

Explanation

Don't get lost! There's a lot of wrapping here.

0            Push 0. We'll be mapping a-z to 1-26, so 0 will be smaller than everything

(loop)
i            Read a char of input
:1+? 1n;     If there's no more input, print 1
:'`')?       If the char is bigger than backtick...
  '`'          Push backtick  (which is one before 'a'), else...
  '@'          Push an @ sign (which is one before 'A')
-            Subtract, mapping a-z to 1-26
:{)?         If the new char is bigger than the previous char...
               Repeat from the beginning of the loop, else...
  0n;          Print 0

Previous solution, 42 bytes

0i:1+?v1n;n0/\!
?)'`':/'@'v
? ){:-<'`'/ vv

The interesting thing is that, despite appearing to have the same functionality, the alternative

0i:1+?v1n;n0\/!
?)'`':/'@'v
? ){:-<'`'/ ^^

(The change is in the arrows and mirrors on the far right)

actually gives incorrect results, due to ><>'s interpreter using a Python defaultdict. What happens is that, by traversing through the empty space at the end of the second row, 0s are implicitly placed into the blank spaces when ><> tries to access the cell. This then messes with the ? conditional trampoline at the beginning of the same row, as the newly placed 0s are skipped rather than the v at the end.

Sp3000

Posted 2015-03-01T11:42:37.923

Reputation: 58 729

I feel like you could save some bytes by only substracting 32 from lowercase letters rather than getting alphabetic index for all letters – Aaron – 2015-09-23T15:30:10.337

9

Haskell, 52 Bytes

import Data.Char
and.(zipWith(>)=<<tail).map toLower

Usage: (and.(zipWith(>)=<<tail).map toLower) "abcd" which outputs True.

nimi

Posted 2015-03-01T11:42:37.923

Reputation: 34 639

9

C, 67 65 57 54 (52) characters

f(char*s){int c,d=0;for(;(c=*s++)&&(c&~32)>(d&~32);d=c);return!c;}

a little shorter:

f(char*s){int c,d=0;for(;(c=*s++)&&(c&~32)>d;d=c&~32);return!c;}

and even shorter:

f(char*s){int d=32;for(;(*s|32)>d;d=*s++|32);return!*s;}

Here's a little test: http://ideone.com/ZHd0xl

After the latest suggestions here are still two shorter versions:

// 54 bytes
f(char*s){int d=1;for(;(*s&=95)>d;d=*s++);return!*s;}

// 52, though not sure if valid because of global variable
d;f(char*s){d=1;for(;(*s&=95)>d;d=*s++);return!*s;}

Also this code relies on the fact, that in ASCII lowercase and uppercase only differ by the 5th bit (32) which I filter out. So this might not work with other encodings obviously.

EDIT: The latest version always sets the 5th bit as |32 is shorter than &~32.

Felix Bytow

Posted 2015-03-01T11:42:37.923

Reputation: 311

Good use of domain knowledge to handle the case sensitivity issue. – RomSteady – 2015-03-02T22:55:22.273

Save 2 by replacing the for loop with for(;(*s&=95)>d;d=*s++);. And you can initialize d to 1 without changing the result, saving 1 more. See.

– AShelly – 2015-03-03T02:53:16.700

1I'm not sure if this is considered legal in code golf, but d;f(char*s){d=32;for...} works, declaring d implicitly as a global int (which, in GCC, is a warning—"data definition has no type or storage class"—but not an error). This saves two bytes. – wchargin – 2015-03-03T03:13:43.307

AShelly hm, didn't consider that. Your suggestion changes the original string though. But whatever, it's code golf :D Also I'm not sure about WChargin's hint as d as a global variable would not really be part of the function. – Felix Bytow – 2015-03-03T06:22:30.773

I think the problem with the global is that it won't work the 2nd time the function is called. – AShelly – 2015-03-03T15:48:52.040

1Why not initialize d in the for loop rather than its own statement? That way you save a ;. – Josh – 2015-03-03T16:38:45.687

6

Ruby, 33

->s{c=s.upcase.chars
c==c.sort|c}

Checks to see if the sorted unique characters are the same as all the characters.

britishtea

Posted 2015-03-01T11:42:37.923

Reputation: 1 189

1Think you can get it a little shorter with c==c.sort|c – histocrat – 2015-03-02T20:59:14.550

Ooh, I like that, that's clever. Thanks. – britishtea – 2015-03-02T21:10:43.300

5

Javascript (ES5), 101

function i(s){b=0;l=''.a
s.toUpperCase().split('').forEach(function(c){if(c<=l)b=1
l=c})
return!b}

Improved to 87 by edc95:

upvote his comment :)

function i(s){return!s.toUpperCase().split(l='').some(function(c){return(u=l,l=c)<=u})}

Btw, the test cases currently in OP are fulfilled if a program is only checking uniqueness, disregarding order.


I cant write comments yet, so I'll answer some remarks here:

@edc65: Thanks! I tried rewriting it using some(), but I couldn't get a shorter solution, because even though it looks like it would enable me to get rid of the superflous b variable, you need to type "return" twice (same with reduce()), and you can't just return the comparison's result directly, because the last character needs to be saved after the comparison with it.

@edc65: That's a nice use of the comma operator for 87! I edited it into my answer for more visibility.

Tamas

Posted 2015-03-01T11:42:37.923

Reputation: 61

That's a better idea than mine. Using .some could be even better (52 with ES6) – edc65 – 2015-03-01T17:25:43.767

You can remove the space between return and !b to save a char. – ProgramFOX – 2015-03-01T19:20:28.157

As is, just caring white space,96:function i(s){b=0;l='';s.toUpperCase().split('').forEach(function(c){if(c<=l)b=1;l=c});return!b} – edc65 – 2015-03-01T20:02:44.633

The same, golfed more,92:function i(s){s.toUpperCase(b=0).split(l='').forEach(function(c){if(c<=l)b=1;l=c});return!b} – edc65 – 2015-03-01T20:03:25.987

1Using some(or every, same score),87:function i(s){return!s.toUpperCase().split(l='').some(function(c){return(u=l,l=c)<=u})} – edc65 – 2015-03-01T20:04:09.420

4

Brachylog, 3 bytes

ḷ⊆Ạ

Try it online!

The predicate succeeds if the input meets the requirements outlined and fails if it does not, printing true. or false. if run as a program.

       The input,
ḷ      lowercased,
 ⊆     is a not-necessarily-contiguous sub-list of
  Ạ    "abcdefghijklmnopqrstuvwxyz".

The first version I came up with, not explicitly referencing the alphabet:

Brachylog, 4 bytes

ḷ≠.o

Try it online!

        The input,
ḷ       lowercased,
 ≠      in which every character is distinct,
  .     is the output variable,
   o    which sorted,
        is still the output variable.

Unrelated String

Posted 2015-03-01T11:42:37.923

Reputation: 5 300

4

Haskell, 90 bytes

Supplies the function f :: String -> Bool

import Data.List
import Distribution.Simple.Utils
f l=g$lowercase l
g l=sort l==l&&l==nub l

Usage (assuming it is saved as golf.hs). ... is used to replace ghci's verbose loading messages.

$ ghci golf.hs
...
*Main> f "as"
...
True
*Main> f "aa"
False

If someone has a lowercase method shorter than import Distribution.Simple.Utils then please comment.

HEGX64

Posted 2015-03-01T11:42:37.923

Reputation: 313

1Use map toLower from Data.Char instead of lowercase – nimi – 2015-03-01T17:11:33.950

1Also: you can remove the parameter l at f, i.e. f=g.lowercase (or f=g.map toLower if you switch to toLower). Within g one comparison is enough: g l=nub(sort l)==l. – nimi – 2015-03-01T18:45:56.403

4

Wolfram Mathematica, 49 37 bytes

f[x_]:=(l=Characters[ToLowerCase[x]];Union[l]==l)

P.S. Shorter solution by Martin Büttner:

Union[l=Characters@ToLowerCase@#]==l&

Savenkov Alexey

Posted 2015-03-01T11:42:37.923

Reputation: 161

2#⋃#==#&@*Characters@*ToLowerCase – alephalpha – 2015-03-02T03:16:08.097

1@alephalpha That is beautiful! – Martin Ender – 2015-03-02T17:56:50.510

4

J, 17 bytes

Checks if the lowercase sorted /:~ string equals -: the lowercase nub ~. string.

   (/:~-:~.)@tolower

   NB. testing with the example inputs
   ((/:~-:~.)@tolower) every (1$'a');'abcdefGHIjklmnopqrSTUVWXyz';'aa';'puz';'puzz';'puzZ';'puZ';'PuZ'
1 1 0 1 0 0 1 1

As in J a 1-charater long "string" represented as a regular string (with quotes) is just a character atom not a real string I formatted the input appropriately so all input would be real strings. (In the example above I used 1$'a'.)

randomra

Posted 2015-03-01T11:42:37.923

Reputation: 19 909

4

MATLAB, 29 27 bytes

Now for a one-liner which even makes sense outside of code-golf.

As an anonymous function (use as o('yourstring'))

o=@(s)all(diff(lower(s))>0)

I guess this function is pretty self-explanatory since it reads like a newspaper ad.

Previous version (29 bytes):

all(diff(lower(input('')))>0)

Input must be presented between ' marks, e.g. 'Potato'.

Sanchises

Posted 2015-03-01T11:42:37.923

Reputation: 8 530

3

R, 37 bytes

all(diff(utf8ToInt(scan(,''))%%32)>0)

Try it online!

Posting since this is substantially different and shorter than Michal's R answer.

Converts the letters to ASCII codepoints with utf8ToInt, then takes modulo 32 so that lower and upper letters are converted to the same numbers 1...26. Computes the pairwise differences, and checks that they are all positive.

Robin Ryder

Posted 2015-03-01T11:42:37.923

Reputation: 6 625

3

Pure Bash 4.x, 37

[[ ${1,,} =~ ^`printf %s? {a..z}`$ ]]

Input taken as a command-line parameter. As per standard shell semantics, exit code 0 means true (alphabetic) and exit code != 0 means false (not alphabetic).

The printf creates the regex as in @hsl's solution. The input string is expanded to lowercase and compared against the regex.


Previous answer:

Bash + coreutils, 52

Straightforward solution:

a=`fold -1<<<${1,,}`
cmp -s <(sort -u<<<"$a")<<<"$a"

Digital Trauma

Posted 2015-03-01T11:42:37.923

Reputation: 64 644

Note that this requires bash 4.x. – Mark Reed – 2015-03-02T20:09:10.067

@MarkReed Yes. Noted. – Digital Trauma – 2015-03-02T20:38:24.467

3

JavaScript (ES6) 54

Convert to uppercase, then to array and sort. If during sort two element are in the wrong order or equal, return 0 (falsy) else 1 (truthy)

Edit Shortened thx to @Optimizer (but still 2 more than the @Tamas solution implemented in ES6: F=s=>[...s.toUpperCase()].every(c=>(u=l,l=c)>u,l=''))

F=s=>[...s.toUpperCase(x=1)].sort((a,b)=>a<b?1:x=0)&&x

Test in Firefox / FireBug console

;['a','abcdefGHIjklmnopqrSTUVWXyz','aa','puz','puzz','puzZ','puZ','PuZ']
.map(w=>w+' '+F(w))

["a 1", "abcdefGHIjklmnopqrSTUVWXyz 1", "aa 0", "puz 1", "puzz 0", "puzZ 0", "puZ 1", "PuZ 1"]

edc65

Posted 2015-03-01T11:42:37.923

Reputation: 31 086

1s= does not seem to be required... – Optimizer – 2015-03-03T17:26:43.067

@Optimizer right, it was a first try when at last i compared the original (uppercased) and the sorted – edc65 – 2015-03-03T18:26:55.643

3

C# 6, 18 + 82 76 = 94 bytes

Requires (18 bytes):

using System.Linq;

Code (76 bytes):

bool a(string s)=>(s=s.ToLower()).Distinct().OrderBy(x=>x).SequenceEqual(s);

C# 6 supports lambdas to define a function, which is useful for golfing.

Non-C# 6 version:

bool a(string s){return (s=s.ToLower()).Distinct().OrderBy(x=>x).SequenceEqual(s);}

Ungolfed code:

bool IsInAlphabeticalOrder(string s)
{
    s = s.ToLower();
    return s.Distinct()
            .OrderBy(x => x)
            .SequenceEqual(s);
}

ProgramFOX

Posted 2015-03-01T11:42:37.923

Reputation: 8 017

3

J, 21 characters

This is too long. The argument must have rank 1, i.e. it must be a string or vector.

*/@(<=~.;/:~)@tolower
  • tolower yy in lower case.
  • /:~ yy in lexical order.
  • ~. y – the nub of y, that is, y with duplicates removed.
  • x ; yx and y put into boxes and then concatenated.
  • < yy put into a box.
  • x = yx compared element-wise with y.
  • (< y) = (~. y) ; (/:~ y) – a vector indicating if y is equal to its nub and itself sorted.
  • */ y – the product of the items of y, or its logical and if the items are booleans.
  • */ (< y) = (~. y) ; (/:~ y) – a boolean indicating the desired property for lowercase y.

FUZxxl

Posted 2015-03-01T11:42:37.923

Reputation: 9 656

3

Julia, 44 bytes

s->(l=lowercase(s);l==join(sort(unique(l))))

This creates an anonymous function that takes a single argument s, converts it to lower case, and compares it to the unique sorted version of the string. It returns a boolean, i.e. true or false. If you want to test it out, assign it like f=s->... and then call f("PuZ"), etc.

Alex A.

Posted 2015-03-01T11:42:37.923

Reputation: 23 761

Amen to that, @flawr. Thanks for the support. – Alex A. – 2015-03-02T16:28:12.457

3

Perl 6, 35 bytes

{my@c=.uc.comb;@c eq@c.sort.unique}

This produces a callable block; if I could just assume that $_ is already set to the desired word, I could delete the surrounding curly braces and lose two more bytes, but probably the only reasonable way to make that assumption would be to run it with -n and feed the word as standard input, which would add the two bytes right back.

Mark Reed

Posted 2015-03-01T11:42:37.923

Reputation: 667

Sure it does. .uc.comb doesn't rearrange anything, so if the uppercased and combed array is equal to the sorted uppercased and combed array, that means it started out in sorted order. – Mark Reed – 2019-03-03T22:26:30.290

right, it's checking the size of the intersection, which ignores order. Ok, updated. – Mark Reed – 2019-03-03T22:33:17.557

3

Golang (65 bytes)

Go is not a golf friendly language, also, i suck at golf...

func a(s[]byte)(bool){return len(s)<2||s[0]|32<s[1]|32&&a(s[1:])}

Run it here: http://play.golang.org/p/xXJX8GjDvr

edit 106->102

edit 102->96

edit 96->91

edit 91->87

edit 87->65

I beat the java version, I can stop for today

Kristoffer Sall-Storgaard

Posted 2015-03-01T11:42:37.923

Reputation: 489

3

C (44 bytes)

f(char*s){return(*s&=95)?f(s+1)>*s?*s:0:96;}

Test it here: http://ideone.com/q1LL3E

Posting this because I can't comment yet, otherwise it would be a suggestion to improve the existing C answer because I completely stole the case-insensitive idea from the existing C answer.

Returns 0 if the string is not ordered, and a non-zero value if ordered.

erai

Posted 2015-03-01T11:42:37.923

Reputation: 31

3

Java 8 - 90 89 87 85 chars

The idea here is to use a 'reduce' function that tracks the last char and "gives up" when it detects the sequence is not strictly ascending.

golfed:

int f(String s){return s.toLowerCase().chars().reduce(0,(v,c)->(v<0)?v:(c>v)?c:-1);}

ungolfed:

int f(String s){
    return s.toLowerCase()
            .chars()
            .reduce(0, (v,c) -> (v<0)? v : (c>v)?c:-1);
}

example:

System.out.println(new Quick().f("abc"));
System.out.println(new Quick().f("aa"));
System.out.println(new Quick().f("abcdefGHIjklmnopqrSTUVWXyz"));
System.out.println(new Quick().f("puZ"));
System.out.println(new Quick().f("Puz"));
System.out.println(new Quick().f("cba"));

output:

99
-1
122
122
122
-1

Michael Easter

Posted 2015-03-01T11:42:37.923

Reputation: 585

2

Python 2, 43 bytes

lambda s:eval('"%s"'%'"<"'.join(s.lower()))

Try it online!

Puts < symbols between all the letters (converted to lowercase), and then evals it. Python's chained comparison operators are perfectly happy to evaluate the whole thing as one big boolean expression.

ArBo

Posted 2015-03-01T11:42:37.923

Reputation: 1 416

2

Perl, 27

@hsl's regexp dynamically build.

#!perl -p
$"="?";@x=a..z;$_=/^@x?$/i

Also we can do a reverse match: convert the input into a regexp: PuZ => .*p.*u.*z.* and then match this to a string of letters in alphabetical order. Result - also 27 characters.

#!perl -lp
$_=join(s//.*/g,a..z)=~lc

nutki

Posted 2015-03-01T11:42:37.923

Reputation: 3 634

2

k (6 bytes)

&/>':_

& returns true if both args are true

/ modifies & to apply "over" a list, like a fold in functional languages

> greater than

': modifies > to apply "each-prior", so returns a vector of booleans stating which elements are greater than their predecessor

_ makes it argument lower case

  _"puzZ"
"puzz"
  >':_"puzZ"
1110b
  &/>':_"puzZ"
0b

(0b means boolean false)

q (13 bytes)

all(>':)lower

q is just syntactic sugar on k. all is defined as &/, and lower is _

mollmerx

Posted 2015-03-01T11:42:37.923

Reputation: 229

4Can you explain how this works? – flawr – 2015-03-02T16:11:50.143

This almost feels like cheating on other languages... Who needs function names, parentheses and semicolons? :) – Sanchises – 2015-03-02T22:59:48.353

@sanchises k has all of those things and they work pretty much the same way as in C style languages. It's just that this problem happens to be expressible as a single statement. – mollmerx – 2015-03-04T16:50:40.333

2

Python, 50 bytes

f=lambda x:sorted(set(x.lower()))==list(x.lower())

Try online here: http://repl.it/c5Y/2

mbomb007

Posted 2015-03-01T11:42:37.923

Reputation: 21 944

2

VBA (161 bytes)

Function t(s As String)
t = 0
For i = 2 To Len(s)
a = Left(LCase(s), i)
    If Asc(Right(a, 1)) <= Asc(Right(a, 2)) Then Exit Function
Next
t = 1
End Function  

Compares ascii value with previous letter in lowercase, return 0 (false) when its value is smaller / equal and exit function

Alex

Posted 2015-03-01T11:42:37.923

Reputation: 369

1

Python 2, 62 bytes (thank to Shaggy)

def a(w):
    v=w.lower()
    print v==''.join(sorted(set(v)))

I know I can not beat anyone but here is my solution.

PoC: https://repl.it/repls/UnderstatedDecimalSales

chau giang

Posted 2015-03-01T11:42:37.923

Reputation: 725

Thank you so much for pointing the missing part for me, I just updated my answer! – chau giang – 2019-03-03T18:13:13.870

1

Japt, 6 bytes

v ä< e

Try it online!

Explanation:

v         #Convert to all lowercase
  ä  e    #For every pair of consecutive letters:
   <      # Check that the second letter is later in the alphabet than the first

Kamil Drakari

Posted 2015-03-01T11:42:37.923

Reputation: 3 461

1

APL (Dyalog Extended), 6 bytesSBCS

Anonymous tacit prefix function.

(∧≡∪)⌊

Try it online!

()⌊ on the lowercase:

∧≡∪ does the ascending sort match the unique?

Adám

Posted 2015-03-01T11:42:37.923

Reputation: 37 779

1

><>, 29 20 bytes

Saved 9 bytes thanks to Jo King

0\0=n;
!\i1+48*%:r)?

Try it online!

Emigna

Posted 2015-03-01T11:42:37.923

Reputation: 50 798

20 bytes – Jo King – 2019-03-05T01:54:34.930

@JoKing: I was sure it could still be golfed, but 9 bytes is more than I'd thought was possible. I really like the 0=. Need to remember that one for future golfs :) – Emigna – 2019-03-05T06:56:39.083

1

Ruby, 29 bytes

->s{s=~/^#{[*?a..?z]*??}?$/i}

Try it online!

Returns 0 if in order, or false if not in order.

G B

Posted 2015-03-01T11:42:37.923

Reputation: 11 099

1

Erlang, 51

f(S)->G=string:to_lower(S),ordsets:from_list(G)==G.

Uses an ordered set (analogous to java.util.TreeSet) to sort the characters and discard any duplicates. The new list is then compared with the input string.

Test Function:

test() ->
    [io:format("~p ~p~n", [S, f(S)]) || S <- ["a","abcdefGHIjklmnopqrSTUVWXyz","aa","puz","puzz","puzZ","puZ","PuZ"]].

c.P.u1

Posted 2015-03-01T11:42:37.923

Reputation: 1 049

1

Java, 96

boolean a(char[]a){int i=-1,l=0;for(;++i<a.length;l+=i>0&&a[i]<=a[i-1]?1:0)a[i]|=32;return l<1;}

Pretty straightforward here. Just convert all to lower and compare each to the previous character.

Geobits

Posted 2015-03-01T11:42:37.923

Reputation: 19 061

1

PowerShell, 37

-join(($x="$input")[0..26]|sort)-eq$x

Can be shortened by another byte by using command-line arguments instead of stdin ($args instead of $input).

Tricks used:

  • PowerShell is case-insensitive by default, simplifying the check.
  • Getting a char[] from the input is a bit shorter if we know an upper bound for the length [0..x] instead of [char[]]

Joey

Posted 2015-03-01T11:42:37.923

Reputation: 12 260

1

Rebol - 26 25

(s: input)= sort unique s

NB. Above works fine in Rebol 2. However in Rebol 3 sort isn't case insensitive (yet) so for now it would need to be written has (s: input)= sort lowercase unique s

draegtun

Posted 2015-03-01T11:42:37.923

Reputation: 1 592

1

R, 62 Bytes

s=strsplit(tolower(word),"")[[1]]
all(s[order(unique(s))]==s)

This will throw a warning if there is a repeating character.

To avoid this, I inserted zeros to make both strings the same length. I assumed this is OK since we are only using letters and not numbers.

s <- strsplit(tolower(word), "")[[1]]
all(c(s[order(unique(s))],rep('0',length(s)-length(unique(s)) )) == s) 

Michal

Posted 2015-03-01T11:42:37.923

Reputation: 209

1

Clojure, 69

(let[s(seq(.toLowerCase (read-line)))](= s(seq(apply sorted-set s))))

Run in the REPL, enter a string and press return. Prints true or false. E.g.

user=> (let[s(seq(.toLowerCase (read-line)))](= s(seq(apply sorted-set s))))
puZ
true
user=> (let[s(seq(.toLowerCase (read-line)))](= s(seq(apply sorted-set s))))
puzz
false

cfrick

Posted 2015-03-01T11:42:37.923

Reputation: 313

1

PHP (89 76 72 63 bytes)

I'm pretty horrible at golfing, but I thought I'd give it a shot.

<?=(join(array_unique(str_split($a=strtolower($argv[1]))))==$a)+0;

I had to cast the output to an integer, since booleans aren't printed in php.

I was able to remove the echo by using <?=, I also removed the $b.

[edit]

Removed the space after <?= and followed manatwork's suggestion to cut 4 bytes.

Also, replacing the implode with join and omitting the glue parameter saved another 9 bytes. Thanks manatwork.

MisterBla

Posted 2015-03-01T11:42:37.923

Reputation: 181

You can also force a boolean into integer by adding 0 to it. +0 is shorter than (int). – manatwork – 2015-03-11T17:09:32.497

Though this passes successfully the test cases provided in the question, it definitely not checks for alphabetical order. For example it outputs 1 for “xa”. – manatwork – 2015-03-11T17:16:49.180

There is an alias for implode(), with shorter name: join(). And the first parameter is optional, defaulting to empty string. – manatwork – 2015-03-11T17:25:21.573

@manatwork There is too, completely missed it. Thank you. – MisterBla – 2015-03-11T17:28:00.323

@manatwork I see it doesn't do alphabetical order... which I find weird, array_unique should sort the array. – MisterBla – 2015-03-11T17:31:05.077

I count 63 bytes. Forgot to count the tag? – Titus – 2019-03-04T15:38:11.107

1

Javascript, 147 145 bytes

function(a){b=[];a=a.toLowerCase().split('');while(a.length)b.push(a.pop().charCodeAt(0));while(c=b.pop()){if(c>=b[b.length-1])return 0}return 1}

An anonymous function that converts to lowercase, creates an array of char codes, then checks them from right to left.

SuperJedi224

Posted 2015-03-01T11:42:37.923

Reputation: 11 342

0

Retina, 33 bytes (non-competing)

Uses features newer than the challenge. Byte count assumes ISO 8859-1 encoding.

T`L`l
^
$_¶
O`\G.
D`\G.
^(.*)¶\1$

Try it online

Translate uppercase to lowercase, duplicate input, sort the first line, deduplicate first line, then check if the lines are equal.

mbomb007

Posted 2015-03-01T11:42:37.923

Reputation: 21 944

0

C++14, 59 58 bytes

-1 byte for int instead of auto in range-based for-loop.

As unnamed lambda returning via reference parameter. 64 (>0) for true, 0 for false. Input s may be std::string or char[].

[](auto&s,int&r){int b=r=64;for(int c:s)r*=b<(c&=95),b=c;}

The &=95 is from this answer.

Ungolfed and usage:

#include<string>
#include<iostream>

auto f=
[](auto&s,int&r){
  int b=r=64;
  for(int c:s)
    r*=b<(c&=95),
    b=c;
}
;

int main(){
  std::string s;
  int r;
  s="ABC";
  f(s,r); std::cout << s << ", " << r << std::endl;
  s="AbC";
  f(s,r); std::cout << s << ", " << r << std::endl;
  s="ACB";
  f(s,r); std::cout << s << ", " << r << std::endl;
  s="AcB";
  f(s,r); std::cout << s << ", " << r << std::endl;
}

Karl Napf

Posted 2015-03-01T11:42:37.923

Reputation: 4 131

0

MathGolf, 6 bytes

mδ_s▀=

Try it online!

Explanation

m        explicit map (per character)
 δ       capitalize string
         these two commands transforms the input string to uppercase
  _      duplicate the uppercase string
   s     sort(array)
    ▀    unique elements of string
     =   check if equal to the uppercased input

maxb

Posted 2015-03-01T11:42:37.923

Reputation: 5 754

0

C# (Visual C# Interactive Compiler), 44 bytes

n=>n.Aggregate((a,b)=>a>1&a%32<b%32?b:'')>1

Can be 42 bytes if I return a SOH char for non-alphabetic and anything else for alphabetic.

Try it online!

Embodiment of Ignorance

Posted 2015-03-01T11:42:37.923

Reputation: 7 014

0

JavaScript (Node.js), 93 bytes

w=>new Set(w).size==w.length&&[...w.toLowerCase()].sort().join``==[...w.toLowerCase()].join``

Try it online!

Kamil Naja

Posted 2015-03-01T11:42:37.923

Reputation: 121

0

Perl 6, 30 14 bytes

{[<] .uc.ords}

Try it online!

Gets the ordinal values of the uppercased string and checks if they are in strictly increasing order.

Jo King

Posted 2015-03-01T11:42:37.923

Reputation: 38 234

0

PHP, 42 bytes

for(;$c=_&$argn[$i++];$p=$c)$c<$p&&die(1);

exits with 1 (error) for falsy, exit code 0 for truthy.
Run as pipe with -nR or try it online.

If you absolutely need visible output, take these 51 bytes:

for(;$c=_&$argn[$i++];$p=$c)$c<$p&&die("0");echo 1;

Titus

Posted 2015-03-01T11:42:37.923

Reputation: 13 814

0

Bash+coreutils, 27 bytes

grep -Ei ^1`echo ?{a..z}?`$

Try it online!

There was an earlier answer with pure Bash, but this one is cool because it saves space by making a much "worse" regular expression. The command substitution expands to the regular expression

^1?a? ?b? ?c? ?d? ?e? ?f? ?g? ?h? ?i? ?j? ?k? ?l? ?m? ?n? ?o? ?p? ?q? ?r? ?s? ?t? ?u? ?v? ?w? ?x? ?y? ?z?$

which accepts many things that we don't care about (1's at the beginning and spaces almost anywhere) but that's okay because it selects correctly when limited to things in the input specification. This lets us avoid a printf %s and just accept the spaces that Bash gives when it expands ?{a..z}?

Sophia Lechner

Posted 2015-03-01T11:42:37.923

Reputation: 1 200

0

APL(NARS), 32 char, 64 bytes

{(k≡∪k)∧k≡k[⍋k←26∣¯1+(⎕A,⎕a)⍳⍵]}

how to use and test (note that "'a'" is a char type and ",'a'" is one type array chars):

  h←{(k≡∪k)∧k≡k[⍋k←26∣¯1+(⎕A,⎕a)⍳⍵]}
  h ,'a'
1
  h 'abcdefGHIjklmnopqrSTUVWXyz'
1
  h 'aa'
0
  h 'puz'
1
  h 'puzz'
0
  h 'puzZ'
0

Possible there is something more short.

RosLuP

Posted 2015-03-01T11:42:37.923

Reputation: 3 036

0

05AB1E, 4 bytes

lDêQ

Try it online or verify all test cases.

Explanation:

      #  i.e. input: "Test"
l     # Convert the (implicit) input-string to lowercase
      #  STACK: ["test"]
 D    # Duplicate it
      #  STACK: ["test", "test"]
  ê   # Uniquify and sort the characters in the duplicated string
      #  STACK: ["test", "est"]
   Q  # Check if both strings are equal
      #  STACK: [0]
      # (after which the top of the stack is output implicitly as result)

Kevin Cruijssen

Posted 2015-03-01T11:42:37.923

Reputation: 67 575

0

PHP (52 bytes)

This is an answer based on @HSL's regex (sorry dude).

The idea is to grab the regex and generate it instead of having it hard-coded.

Here is the code:

echo preg_match("@^".join('?',range(a,z))."?$@",$s);

Since this answer isn't entirely of my authority, I have marked it as "Community Wiki".

To use this, simply add a line before with $s='String!';.

Ismael Miguel

Posted 2015-03-01T11:42:37.923

Reputation: 6 797

If the string to parse should be provided in variable $s, then that should be preg_match()'s 2nd parameter. Which is 2 characters shorter. – manatwork – 2015-03-02T11:21:19.283

@manatwork Oh god! Sorry the stupidity! I was distracted and wrote it without thinking. I've fixed it now. – Ismael Miguel – 2015-03-02T12:11:50.437