All together now

Given a list of digits 1 through 9, output whether each digit is grouped together as a single contiguous block. In other words, no two of the same digit are separated by different digits. It's OK if a digit doesn't appear at all. Fewest bytes wins.

Input: A non-empty list of digits 1 through 9. This can be as a decimal number, string, list, or similar sequence.

Output: A consistent Truthy value if all the digits are grouped in contiguous blocks, and a consistent Falsey value if they are not.

True cases:

3
51
44999911
123456789
222222222222222222222

False cases:

818
8884443334
4545
554553
1234567891

• Would a list of singleton strings be an acceptable input format? Apr 12, 2016 at 0:22
• Yes, singletons are fine.
– xnor
Apr 12, 2016 at 1:31
• Can anyone tell me what the most efficient algorithm for this problem would be? Or is there a more general problem that this falls under that I can look up?
– user53017
Apr 14, 2016 at 12:36
• @amt528 You can do it in linear time by iterating over each digit and checking that there's no runs of it past the first.
– xnor
Apr 15, 2016 at 2:15
• Could you provide an example of how it's implemented?
– user53017
Apr 15, 2016 at 15:31

Python 3, 3834 33 bytes

lambda s:s==sorted(s,key=s.index)

This expects a list of digits or singleton strings as argument. Test it on Ideone.

Thanks to @xsot for golfing off 4 bytes!

Thanks to @immibis for golfing off 1 byte!

• If you are allowed to accept a list of strings instead, you can shorten this to lambda s:s==sorted(s,key=s.find)
– xsot
Apr 12, 2016 at 0:19
• Ah, I tried taking a list, but I didn't think of using backticks... I'll ask the OP. Apr 12, 2016 at 0:22
• Am I missing something - why can't you just use s.find? Apr 12, 2016 at 4:31
• @immibis s has to be a list of singleton strings (or I'd have to cast s to list for the comparison), and list.find is not defined... Apr 12, 2016 at 4:33
• @Dennis s.index then? Seems to work for me. Apr 12, 2016 at 4:37

JavaScript (ES6), 27 bytes

s=>!/(.)(?!\1).*\1/.test(s)

Uses negative lookahead to look for two non-contiguous digits. If at least two such digits exist, then they can be chosen so that the first digit precedes a different digit.

• Or, just use a regex XD. That works too. Apr 12, 2016 at 0:01
• ahem Retina ahem Apr 12, 2016 at 5:58

05AB1E, 4 bytes

Code:

Ô¹ÙQ

Explanation:

Ô     # Push connected uniquified input. E.g. 111223345565 would give 1234565.
¹    # Push input again.
Ù   # Uniquify the input. E.g. 111223345565 would give 123456.
Q  # Check if equal, which yields 1 or 0.

Uses CP-1252 encoding.

Try it online!

• You...just beat jelly...I never thought this was possible... Apr 15, 2016 at 8:17

Jelly, 5 bytes

ĠIFPỊ

Try it online!

How it works

ĠIFPỊ  Main link. Input: n (list of digits or integer)

Ġ      Group the indices of n by their corresponding values, in ascending order.
For 8884443334, this yields [[7, 8, 9], [4, 5, 6, 10], [1, 2, 3]].
I     Increments; compute the all differences of consecutive numbers.
For 8884443334, this yields [[1, 1], [1, 1, 4], [1, 1]].
F    Flatten the resulting 2D list of increments.
P   Product; multiply all increments.
Ị  Insignificant; check if the product's absolute value is 1 or smaller.
• Five bytes you say? What kind of encoding is that? Apr 12, 2016 at 5:56
• Jelly has its own code page, which encodes each of the 256 characters it understands as a single byte. Apr 12, 2016 at 5:57

Pyth, 6 5 bytes

1 bytes thanks to FryAmTheEggman

SIxLQ

Inspired by the Python solution here.

Test suite

Explanation:

SIxLQ
xLQ   Map each element in the input to its index in the input. Input is implicit.
SI      Check whether this list is sorted.
• SIxLQ seems to work. Apr 12, 2016 at 1:12
• This is genius. Apr 12, 2016 at 1:52
• The second Q doesn't seem to get parsed properly, it swaps argument order or something so you get all 0s and it always gives true. Here's a test suite. Apr 12, 2016 at 1:55

R, 66484643 38 bytes

function(s)!any(duplicated(rle(s)$v)) This is a function that accepts the input as a vector of digits and returns a boolean. To call it, assign it to a variable. Not the shortest but I thought it was a fun approach. We run length encode the input and extract the values. If the list of values contains duplicates then return FALSE, otherwise return TRUE. Verify all test cases online Saved 20 bytes thanks to MickyT, 3 thanks to Albert Masclans, and 5 thanks to mnel! MATL, 8 bytes t!=tXSP= The output is an array containing only ones for truthy, or an array containing at least one zero for falsey. Try it online! Explanation Consider the input 22331, which satisfies the condition. Testing if each character equals each other gives the 2D array 1 1 0 0 0 1 1 0 0 0 0 0 1 1 0 0 0 1 1 0 0 0 0 0 1 The final result should be truthy if the rows of that array (considered as atomic) are in (lexicographical) decreasing order. For comparison, input 22321 gives the array 1 1 0 1 0 1 1 0 1 0 0 0 1 0 0 1 1 0 1 0 0 0 0 0 1 in which the rows are not sorted. t! % Take string input. Duplicate and tranpose = % Test for equality, element-wise with broadcast: gives a 2D array that % contains 0 or 1, for all pairs of characters in the input t % Duplicate XS % Sort rows (as atomic) in increasing order P % Flip vertically to obtain decreasing order = % Test for equality, element-wise Retina, 17 bytes M(.)(?!\1).+\1 0 Try it online! (Slightly modified to run all test cases at once.) The first regex matches digits which are separated by other digits, so we get a 0 for valid inputs and anywhere between 1 and 9 for invalid inputs (due to the greediness of the the .+, we can't get more than n-1 matches for n different digits). To invert the truthiness of the result, we count the number of 0s, which is 1 for valid inputs and 0 for invalid ones. • I made a shorter one, but it's close enough to yours that it should be a comment instead. Use AntiGrep instead of Match, then remove the last line: A(.)(?!\1).+\1 for 15 bytes. Also works for multiple inputs. Truthy is the input, falsy is nothing. One does not simply out-golf Martin at his own language. :) Apr 22, 2016 at 19:11 • @mbomb007 I think I actually considered that, but unfortunately, the challenge asks for a consistent truthy (and falsy) value, so printing the input as truthy isn't allowed. Apr 22, 2016 at 19:43 Java, 161 156 bytes Because Java... Shamelessly stealing borrowing the regex from this answer because I started out trying to do this with arrays and math manipulation, but it got hideously complex, and regex is as good a tool as any for this problem. import java.util.regex.*;public class a{public static void main(String[] a){System.out.println(!Pattern.compile("(.)(?!\\1).*\\1").matcher(a[0]).find());}} Ungolfed: import java.util.regex.*; public class a { public static void main(String[] args) { System.out.println(!Pattern.compile("(.)(?!\\1).*\\1").matcher(args[0]).find()); } Laid out like a sensible Java person: import java.util.regex.Matcher; import java.util.regex.Pattern; public class { public static void main(String[] args) { Pattern p = Pattern.compile("(.)(?!\\1).*\\1"); Matcher m = p.matcher(args[0]); System.out.println(!m.find()); } } • like a sensible Java person That would be, not using Java ever. – cat Apr 13, 2016 at 20:07 • Other solutions are just providing a function, would make it a lot shorter. Something like s->s.match("(.)(?!\\1).*\\1") Apr 13, 2016 at 21:47 • But then we couldn't revel in the verboseness of the answer. Apr 14, 2016 at 0:54 Pyth, 7 bytes {IeMrz8 Ruby, 23 bytes Anonymous function. Accepts a string. Regex strat. ->n{/(.)(?!\1).*\1/!~n} Regex breakdown /(.)(?!\1).*\1/ (.) # Match a character and save it to group 1 (?!\1) # Negative lookahead, match if next character isn't # the same character from group 1 .* # Any number of matches \1 # The same sequence as group 1 !~ means if there are no matches of the regex within the string, return true, and otherwise return false. Mathematica, 26 bytes 0<##&@@Sort[#&@@@Split@#]& MATL, 13 11 bytes u"G@=fd2<vA Thanks to Luis Mendo for saving two bytes! Try it Online! Explanation % Grab the input implicitly u % Find the unique characters " % For each of the unique characters G % Grab the input again @= % Determine which chars equal the current char f % Find the locations of these characters d % Compute the difference between the locations 2< % Find all index differences < 2 (indicating consecutive chars) v % Vertically concatenate all stack contents A % Ensure that they are all true % Implicit end of the for loop • You can take the input with quotes (allowed by default) and remove j. Also, I think you can move vA within the loop and remove ] Apr 12, 2016 at 8:52 • @LuisMendo Thanks! I had messed around with putting Y& inside but that didn't work because fd2< can be empty. Moving vA inside works great though! Also I really wish we had a stable unique that didn't take up tons of bytes. Apr 12, 2016 at 11:24 • Now stable unique takes a little less, using a number instead of the predefined string. I may add a shorter version in the future, though. Or just make u stable by default (you could always include S afterwards, two bytes). What do you think? Apr 12, 2016 at 12:13 Haskell, 44 bytes import Data.List ((==)<*>nub).map head.group Usage example: ((==)<*>nub).map head.group$ "44999911" -> True.

A non-pointfree version:

f x = q == nub q                -- True if q equals q with duplicates removed
where
q = map head $group x -- group identical digits and take the first -- e.g. "44999911" -> ["44","9999","11"] -> "491" -- e.g "3443311" -> ["3","44","33","11"] -> "3431" J, 8 bytes -:]/:i.~ Test it with J.js. How it works -:]/:i.~ Monadic verb. Argument: y (list of digits) i.~ Find the index in y of each d in y. ]/: Sort y by the indices. -: Match; compare the reordering with the original y. • :] :i :-1 Apr 13, 2016 at 2:02 • Not sure if joke or golfing suggestion... Apr 13, 2016 at 2:19 Python, 56 55 bytes a=lambda s:~(s[0]in s.lstrip(s[0]))&a(s[1:])if s else 1 • Fails in Python 3.4.1 (int not subscriptable) Apr 13, 2016 at 1:38 • Saved an extra byte with ~(which literally is equivalent to1-): a=lambda s:~(s[0]in s.lstrip(s[0]))&a(s[1:])if s else 1 Apr 13, 2016 at 1:53 C#, 119 bytes bool m(String s){for(int i=0;i<9;i++){if(new Regex(i.ToString()+"+").Matches(s).Count>1){return false;}}return true;} Ungolfed bool m(String s) { for(int i=0;i<9;i++) { if(new Regex(i.ToString() + "+").Matches(s).Count > 1) { return false; } } return true; } • Welcome to PPCG! Instead of deleting a post and making a new post with the fixed version, you could also edit your old post and then undelete it. (No need to do that now that there's two posts already anyway, but just so you know in the future.) Apr 14, 2016 at 13:06 • My bad. When I first intended to participate in this Code Golf I misread the objective and didn't had much time to do another solution ( and knowing myself, I wouldn't try to correct the previous posted solution ). But then I was told I had some more time free and attempted to post the "correct solution". Didn't even thought in doing what you said. Next time I'll have that in mind! Apr 14, 2016 at 14:11 • No problem at all, I hope you'll have a good time in the community. :) Apr 14, 2016 at 14:13 Julia, 35 bytes s->issorted(s,by=x->findfirst(s,x)) For whatever reason, sort does not take a string, but issorted does... • ...Are strings not immutable arrays in Julia like Python? That would make me really sad. – cat Apr 12, 2016 at 19:21 • Yes, strings are immutable. That's probably why issorted works, but sort doesn't. Apr 12, 2016 at 19:24 • There isn't a sorting method defined for strings, but it wouldn't work if they were processed in the same way as one-dimensional arrays because those are sorted by performing an in-place sort of a copy, and as you said, strings are immutable. It's not a problem for checking for sorted order though because it's implemented as a simple loop over an iterable, which is fine for strings. Just some trivia. ¯\_(ツ)_/¯ Apr 13, 2016 at 16:48 • @AlexA. So very much like Python in fact; the difference is that Python's builtin sorted turns its iterable argument into a mutable list first -- that's why sorted(string) returns a list of strings – cat Apr 13, 2016 at 20:09 Factor, 22 bytes [ dup natural-sort = ] Does what it says on the tin. As an anonymouse function, you should call this, or make it a : word ;. • it scares me when a cat brings a mouse into the game Apr 13, 2016 at 14:35 • @downrep_nation :P – cat Apr 13, 2016 at 15:10 Lua, 10794 85 Bytes 13 bytes saved thanks to @LeakyNun At least, it beats Java :D. Lua sucks at manipulating strings, but I think it is good enough :). It takes its input as a command-line argument, and outputs 1 for truthy cases and false for falsy ones. Now outputs using its exit code. Exit code 0 for truthy, and 1 for falsy o=os.exit;(...):gsub("(.)(.+)%1",function(a,b)if 0<#b:gsub(a,"")then o(1)end end)o(0) Ungolfed Be care, there's two magic-variables called ..., the first one contains the argument of the program, the second one is local to the anonymous function and contains its parameters o=os.exit; -- ; mandatory, else it would exit instantly (...):gsub("(.)(.+)%1", -- iterate over each group of the form x.*x and apply an anonymous function(a,b) -- function that takes the captured group as parameters if 0<#b:gsub(a,"") -- if the captured group (.+) contain other character than then -- the one captured by (.) o(1) -- exit with falsy end end) o(0) -- exit with truthy, reached only when the string is okay • If it is permitted, you can replace os.exit() with i=#0... Jun 10, 2016 at 9:38 Wolfram Language (Mathematica), 18 bytes Gather@#==Split@#& Try it online! Gather gathers a list into sublists of identical elements, and Split splits a list into sublists of consecutive identical elements. They give the same result if and only if each value appears in only one contiguous block. JavaScript ES6, 71 69 bytes h=y=>y.match(/(.)\1*/g);x=>h((u=h(x)).sort().join).length==u.length Or, equivalently: x=>((u=x.match(r=/(.)\1*/g)).sort().join).match(r).length==u.length x=>(h=y=>y.match(/(.)\1*/g))((u=h(x)).sort().join).length==u.length Golfing in progress. Verify test cases var truthy = 3 51 44999911 123456789 222222222222222222222.split  ; var falsey = 818 8884443334 4545 554553 1234567891.split  ; var Q = x => ((u = x.match(r = /(.)\1*/g)).sort().join ).match(r).length == u.length; truthy.concat(falsey).forEach(e => { t = document.createTextNode(${e} => ${Q(e)}); o.appendChild(t); o.appendChild(document.createElement("br")); }); * { font-family: Consolas, monospace; } <div id=o></div> C# 111 bytes bool f(string s){for(int i=0;i<s.Length-1;i++)if(s[i]!=s[i+1]&&s.LastIndexOf(s[i])!=i)return 1==2;return true;} old strategy 131 bytes bool s(string i){var f=Regex.Matches(i,@"([0-9])\1{0,}").Cast<Match>().Select(m=>m.Value[0]);return f.Distinct().SequenceEqual(f);} first golf i think i did ok in C, 7473 71 bytes Shaved one three byte thanks to @xsot! a[99],c,m;main(d){for(;~c;m|=c^d&&a[d=c]++)c=getchar();putchar(48+!m);} • a[99] I love Perl's autovivification! Oh, wait... – cat Apr 13, 2016 at 20:05 • I think this works: a[99],c,m;main(d){for(;~c;m|=a[d=c]+=c!=d)c=getchar();putchar(48+1/m);} – xsot Apr 14, 2016 at 13:34 • @xsot - Thank you for shaving one byte by replacing !--m with 1/m. About a[d=c]+=c!=d, I tried it with gcc and it didn't work on my computer because of order of evaluation. We must find a compiler that will play along. Apr 14, 2016 at 15:13 • Oh, I just tested it on ideone and it worked fine. How about this: a[99],c,m;main(d){for(;~c;m|=c^d&&a[d=c]++)c=getchar();putchar(48+!m);} – xsot Apr 14, 2016 at 22:48 Haskell, 37 bytes f l=(==)=<<scanl1 min$(<$>l).(==)<$>l

Uses the same approach as Luis Mendo's MATL answer: creates a vector for each entry which indices equal it, and checks that the result is sorted in decreasing order.

(<$>l).(==)<$>l is shorter version of [map(==a)l|a<-l]. The function (<$>l).(==) that takes a to map(==a)l is mapped onto l. scanl1 min takes the cumulative smallest elements of l, which equals the original only if l is reverse-sorted. (==)=<< checks if the list is indeed invariant under this operation. A different recursive strategy gave 40 bytes: f(a:b:t)=f(b:t)>(elem a t&&a/=b) f _=1>0 This checks each suffix to see if its first element doesn't appear in the remainder, excusing cases where the first two elements are equal as part of a contiguous block. Racket, 53 bytes The dumb, simple version. (λ(s)(let([s(string->list s)])(eq?(sort s char<?)s))) Ungolfed: (define (lame-all-together s) (let ([s (string->list s)]) (eq? (sort s char<?) s))) Racket, 86 bytes Here's the version implementing @xnor's comment about more efficient ways to do this. (λ(s)(let([s(string->list(regexp-replace#px"(.)\\1+"s"\\1"))])(eq?(sort s char<?)s))) Ungolfed: (define (all-together s) (let ([s (string->list (regexp-replace #px"(.)\\1+" s "\\1"))]) (eq? (sort s char<?) s ))) Okay, this may actually just shift the weight of computation from the sort function to regexp-replace, but it was an interesting solution. Basically, it removes runs of duplicate characters first (see here), then tests if the remaining length-1 runs are in sorted fashion. Perl 5, 20 bytes 19, plus 1 for -pe instead of -e.$_=!/(.)(?!\1).+\1/

Convex, 17 bytes

9´\f{\s'++\ð½¬}ª!

Try it online!

Japt, 9 bytes

ò¦ mÌ
eUâ

Try it

Explanation

:Implicit input of string U             :e.g., "8884443334"
ò¦        :Split on inequality                    :["888","444","333","4"]
mÌ     :Map and return the last digit of each  :["8","4","3","4"]
\n        :Assign to U
Uâ      :Remove duplicates                      :["8","4","3"]
e         :Test for equality with U               :false
:Implicit output of result

APL (Dyalog), 17 bytes

(⍋≡⍳∘≢)∘⌽∘∊2⊥∘.=⍨

Try it online!