Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

var QUESTION_ID=77608,OVERRIDE_USER=20260;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/77608/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
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>

share|improve this question
2  
Would a list of singleton strings be an acceptable input format? – Dennis yesterday
    
Yes, singletons are fine. – xnor yesterday

22 Answers 22

Python 3, 38 34 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!

share|improve this answer
    
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 yesterday
    
Ah, I tried taking a list, but I didn't think of using backticks... I'll ask the OP. – Dennis yesterday
    
Am I missing something - why can't you just use s.find? – immibis yesterday
    
@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... – Dennis yesterday
    
@Dennis s.index then? Seems to work for me. – immibis yesterday

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.

share|improve this answer
    
Or, just use a regex XD. That works too. – Cᴏɴᴏʀ O'Bʀɪᴇɴ yesterday
    
ahem Retina ahem – Jan Dvorak yesterday

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.
share|improve this answer
    
Five bytes you say? What kind of encoding is that? – Jan Dvorak yesterday
1  
Jelly has its own code page, which encodes each of the 256 characters it understands as a single byte. – Dennis yesterday

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.
share|improve this answer
2  
SIxLQ seems to work. – FryAmTheEggman yesterday
    
This is genius. – Maltysen yesterday
1  
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. – FryAmTheEggman yesterday

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!

share|improve this answer

R, 66 48 46 43 bytes

function(s)identical(x<-rle(s)$v,unique(x))

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.

It certainly isn't 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 is identical to itself with duplicates removed, return TRUE, otherwise FALSE.

Verify all test cases online

Saved 20 bytes thanks to MickyT and 3 thanks to Albert Masclans!

share|improve this answer

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
share|improve this answer

Pyth, 7 bytes

{IeMrz8

Test Suite.

share|improve this answer

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.

share|improve this answer

Mathematica, 26 bytes

0<##&@@Sort[#&@@@Split@#]&
share|improve this answer

Python, 56 bytes

a=lambda s:1-(s[0]in s.lstrip(s[0]))&a(s[1:])if s else 1
share|improve this answer
    
No need to assign the lambda. – cat 12 hours ago
    
@cat Yeah, that was just from testing.. – orlp 10 hours ago
    
Fails in Python 3.4.1 (int not subscriptable) – CatsAreFluffy 6 hours ago
    
a(s[1:]) will error if the lambda is unnamed. – Dennis 6 hours ago
    
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 – CatsAreFluffy 6 hours ago

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"
share|improve this answer

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.

share|improve this answer

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
share|improve this answer
    
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 ] – Luis Mendo 23 hours ago
    
@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. – Suever 20 hours ago
    
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? – Luis Mendo 19 hours ago

Julia, 35 bytes

s->issorted(s,by=x->findfirst(s,x))

For whatever reason, sort does not take a string, but issorted does...

share|improve this answer
    
...Are strings not immutable arrays in Julia like Python? That would make me really sad. – cat 12 hours ago
    
Yes, strings are immutable. That's probably why issorted works, but sort doesn't. – Dennis 12 hours ago

Java, 161 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.Pattern;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.Pattern;

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());
    }
}
share|improve this answer

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>

share|improve this answer

Lua, 107 Bytes

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.

(...):gsub("(.)(.+)%1",function(...)a,b=...if b:find("[^"..a.."]")then print(1<0)os.exit()end end)print(1)

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

(...):gsub("(.)(.+)%1",  -- iterate over each group of the form x.*x and apply an anonymous
  function(...)          -- function that takes the captured group as parameters
  a,b=...                -- unpack the values in the locale ...
  if b:find("[^"..a.."]")-- if the captured group (.+) contain other character than
  then                   -- the one captured by (.)
    print(1<0)           -- ouput false
    os.exit()            -- and exit
  end
end)
print(1)                 -- output 1, reached only when the string is okay :)
share|improve this answer

R 33 bytes Not working

Trying to reduce the bytes of Alex A.,

all({x=rle(scan())$v}==unique(x))
share|improve this answer
    
You'll need cat to write to STDOUT to make this a full program. As it stands it's a snippet, which we don't allow by default; all submissions unless otherwise specified must be full programs or functions. Also this was an approach I tried initially but it fails with an error for the false cases since the vectors being compared by == don't have the same length. – Alex A. 17 hours ago

Perl 5, 20 bytes

A subroutine:

pop!~/(.)(?!\1).+\1/

See it in action as:

perl -e'print sub{pop!~/(.)(?!\1).+\1/}->(51)'
share|improve this answer
    
A subroutine Wat. I thought I sort of understood Perl for a sec... – cat 12 hours ago
    
@cat see perldoc.perl.org/perlsub.html – msh210 11 hours ago

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 ;.

share|improve this answer

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.
share|improve this answer
    
:] :i :-1 – CatsAreFluffy 5 hours ago
4  
Not sure if joke or golfing suggestion... – Dennis 5 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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