Validate Random Die Tippers

32

1

Almost six years ago, fellow PPCG member steenslag posted the following challenge:

In a standard dice (die) the numbers are arranged so that opposite faces add to seven. Write the shortest possible program in your preferred language which outputs a random throw followed by 9 random tippings. A tipping is a quarter turn of the dice, e.g. if the dice is facing 5, all possible tippings are 1,3,4 and 6.

Example of desired output:

1532131356

So, now that everybody has completely forgotten about it and the winning answer has long since been accepted, we'll be writing a program to validate the die tipping sequences generated by the submitted solutions. (This makes sense. Just pretend it does.)

Challenge

Your program or function is given a sequence such as 1532131356. Validate that each consecutive digit is:

  • Not equal to the previous digit
  • Not equal to 7 minus the previous digit

(You don't have to validate the first digit.)

Rules

  • Your program must return a truthy value if the input is valid and a falsey value otherwise.
  • You can assume that the input consists of only the digits 1-6 and is at least 1 character long. Sequences won't have a fixed length like in steenslag's challenge.
  • You can take the input as a string ("324324"), an array or array-like datastructure ([1,3,5]) or as multiple arguments (yourFunction(1,2,4)).

Standard I/O and loophole rules apply.

Test cases

Truthy

1353531414
3132124215
4142124136
46
4264626313135414154
6
2642156451212623232354621262412315654626212421451351563264123656353126413154124151545145146535351323
5414142

Falsey

  • Repeated digit

    11
    3132124225
    6423126354214136312144245354241324231415135454535141512135141323542451231236354513265426114231536245
    553141454631
    14265411
    
  • Opposing side of die

    16
    42123523545426464236231321
    61362462636351
    62362462636361
    

user2428118

Posted 2016-12-21T13:47:13.620

Reputation: 2 000

Answers

13

Python 2, 43 45 bytes

lambda s:reduce(lambda p,n:n*(7-p!=n!=p>0),s)

43 bytes (inspired heavily by @Zgarb)

lambda s:reduce(lambda p,n:n*(p>0<n^p<7),s)

This function combines my reduce statement with the bit-flicking logic from @Zgarb's answer, for a combination that is shorter than both.

Both answers output the following:

  • 0 if the input is not a valid sequence
  • The last digit of the sequence if it is valid

notjagan

Posted 2016-12-21T13:47:13.620

Reputation: 4 011

4Welcome to PPCG, This is a really nice first answer. – Post Rock Garf Hunter – 2016-12-21T14:53:11.867

1This doesn't work for about half of the false cases. E.g. 3132124225 returns 5. – Jake Cobb – 2016-12-21T15:37:24.357

You can fix it using n and p*(7-p!=n!=p). – Jake Cobb – 2016-12-21T15:45:35.387

@JakeCobb It should work with all the test cases now. Unfortunately it's now 2 bytes longer :( – notjagan – 2016-12-21T17:46:30.873

What a clever use of reduce, passing each value to the next step. – xnor – 2016-12-22T04:38:21.360

9

Python, 44 bytes

lambda x:all(0<a^b<7for a,b in zip(x,x[1:]))

Bitwise magic! This is an anonymous function that takes a list of integers, and checks that the XOR of every two consecutive elements is between 1 and 6 inclusive.

Why it works

First, the XOR is always between 0 and 7 inclusive, since 7 is 111 in base 2, and our numbers have at most 3 binary digits. For the equality, a^b == 0 if and only if a == b. Also, we have 7-a == 7^a when 0 ≤ a ≤ 7, and thus a^b == 7 if and only if a == 7^b == 7-b.

Zgarb

Posted 2016-12-21T13:47:13.620

Reputation: 39 083

7

05AB1E, 11 9 bytes

-2 bytes for Osable's smart idea of using a product.

¥¹D7-Á+«P

Try it online!

¥           # Push deltas.
 ¹D7-Á      # Push original array, and 7 - [Array] shifted right once.
      +     # Add original to the 7 - [Array] shifted right.
       «    # Concat both.
        P   # Product, if either contain a zero, results in 0, meaning false.

Third approach using 05AB1E, that doesn't use the pairwise command:

  • 0 if it violates the tipsy properties.
  • Not 0 if there was nothing preventing it from being tipsy.

Magic Octopus Urn

Posted 2016-12-21T13:47:13.620

Reputation: 19 422

1@Emigna didn't think it mattered but fixed! – Magic Octopus Urn – 2016-12-21T16:40:24.207

1I wanted to post an answer with deltas, but I did not think about Á. Nice! – Osable – 2016-12-21T18:05:42.130

1You can save 2 bytes using the definition of truthy/falsy values with ¥¹D7-Á+«P . It yields 0 when there is a 0 in the array or any other value otherwise. – Osable – 2016-12-21T18:31:15.280

1@Osable SMAART! Mega smart man, good job. – Magic Octopus Urn – 2016-12-21T20:03:59.213

6

R, 39 37 32 31 bytes

all(q<-diff(x<-scan()),2*x+q-7)

Try it online!

Takes input from stdin. Uses diff to see if any two consecutive digits are the same; then compares each digit to 7 minus the previous digit. Returns TRUE or FALSE.

Saved 5 bytes thanks to Jarko Dubbeldam, and another thanks to JayCe.

rturnbull

Posted 2016-12-21T13:47:13.620

Reputation: 3 689

Saving the differences in some variable q and then testing 2*x+q-7 instead of c(0,x)!=c(7-x,0) saves a few bytes. If x1 + x2 = 7 then 2*x1 + diff(x1,x2) = 7. Checking 2*x+q - 7 then explicitly tests !=0. – JAD – 2016-12-22T11:25:59.240

@JarkoDubbeldam Great observation, thanks! I've updated the solution. – rturnbull – 2016-12-22T14:10:14.920

save 1 byte – JayCe – 2018-08-08T12:53:16.023

@JayCe Thanks, I've updated the answer now. – rturnbull – 2018-08-09T06:20:36.037

5

05AB1E, 10 bytes

$ü+7ʹüÊ*P

Uses the CP-1252 encoding. Try it online!

Adnan

Posted 2016-12-21T13:47:13.620

Reputation: 41 965

1Argh!, why didn't I think of Ê :P Nice! – Emigna – 2016-12-21T14:35:55.737

Hmm, so 1*[] = [] but product(1, []) = 1. That's good to know. – Emigna – 2016-12-21T14:38:36.653

@Emigna Actually, that is a bug. The product of [] should be 1. – Adnan – 2016-12-21T14:42:59.477

Yeah, I've wished that it worked like that several times before. Order of operations also matter here. )1*, )1s* and )1P are all [] while )1sP is 1. – Emigna – 2016-12-21T14:47:50.000

1@Emigna Ahh, that's because the product of [] gives an error and is discarded. That's why it gives 1. I'll try to fix it when I get home. – Adnan – 2016-12-21T14:50:22.427

5

R, 49 44 bytes

!any(rle(x<-scan())$l-1,ts(x)==7-lag(ts(x)))

Reads input from stdin (separated by space) and outputs TRUE/FALSE. Will give a warning if input is of length one but still works.

Edit: saved a couple of bytes thanks to @rturnbull

Billywob

Posted 2016-12-21T13:47:13.620

Reputation: 3 363

You can combine all(x)&all(y) into all(x,y) to save some bytes. You can also switch rle(x)$l==1 to rle(x)$l-1, which will then return a set of all FALSE if x is valid; then switch the later != to an == and the all to !any. This yields !any(rle(x<-scan())$l-1,ts(x)==7-lag(ts(x))), saving 5 bytes in total. (PS, I've written an alternative solution you may be interested in.)

– rturnbull – 2016-12-22T16:42:57.233

4

Ruby, 34 bytes

->s{!s[/[16]{2}|[25]{2}|[34]{2}/]}

G B

Posted 2016-12-21T13:47:13.620

Reputation: 11 099

2you could shave off two bytes by using the string #[] method instead: ->s{!s[/[16]{2}|[25]{2}|[34]{2}/]} – Alexis Andersen – 2016-12-22T20:38:37.493

I didn't know you can use it with regex, thanks. – G B – 2016-12-22T21:26:14.703

4

05AB1E, 15 bytes

ü+7å¹ü-0å¹g_~~_

Try it online! or as a Test suite

Emigna

Posted 2016-12-21T13:47:13.620

Reputation: 50 798

4

JavaScript (ES6), 43 40 bytes

Returns 0 / true.

f=([k,...a],n=0)=>!k||k-n&&7-k-n&&f(a,k)

Test cases

f=([k,...a],n=0)=>!k||k-n&&7-k-n&&f(a,k)

console.log('Testing truthy cases ...');
console.log(f('1353531414'));
console.log(f('3132124215'));
console.log(f('4142124136'));
console.log(f('46'));
console.log(f('4264626313135414154'));
console.log(f('6'));
console.log(f('2642156451212623232354621262412315654626212421451351563264123656353126413154124151545145146535351323'));
console.log(f('5414142'));

console.log('Testing falsy cases ...');
console.log(f('11'));
console.log(f('3132124225'));
console.log(f('6423126354214136312144245354241324231415135454535141512135141323542451231236354513265426114231536245'));
console.log(f('553141454631'));
console.log(f('14265411'));
console.log(f('16'));
console.log(f('42123523545426464236231321'));
console.log(f('61362462636351'));
console.log(f('62362462636361'));

Arnauld

Posted 2016-12-21T13:47:13.620

Reputation: 111 334

Sadly the simple port of the Retina answer is only 38 bytes. – Neil – 2016-12-21T20:23:34.797

@Neil I think it's actually 37 with test() – Arnauld – 2016-12-21T20:38:58.220

Sorry, I accidentally pasted a newline into the byte counter. – Neil – 2016-12-21T20:57:18.280

4

Perl 6, 22 bytes

Using a regex:

{!/(.)<{"$0|"~7-$0}>/}

Takes the input as a string. Inspired by G B's Ruby answer.
How it works:

  • / /: A regex.
  • (.): Match any character, and capture it as $0.
  • <{ }>: Dynamically generate a sub-regex to be matched at that position.
  • "$0|" ~ (7 - $0): The sub-regex we generate is one that matches only the previous digit, or 7 minus the previous digit (e.g. 5|2).
    Thus the overall regex will match iff it finds an invalid consecutive pair of digits anywhere.
  • {! }: Coerce to a boolean (causing the regex to be matched against $_), negate it, and turn the whole thing into a lambda (with implicit parameter $_).

Perl 6, 38 bytes

Using list processing:

{all ([!=] 7-.[1],|$_ for .[1..*]Z$_)}

Takes the input as an array of integers.
How it works:

  • .[1..*] Z $_: Zip the input list with an offset-by-one version of itself, to generate a list of 2-tuples of consecutive digits.
  • [!=] 7 - .[1], |$_: For each of those, check if (7 - b) != a != b.
  • all ( ): Return a truthy or falsy value depending on whether all loop iterations returned True.

smls

Posted 2016-12-21T13:47:13.620

Reputation: 4 352

4

JavaScript 61 43 bytes

Comments have mentioned I can't use C# linq functions without including the using statement, so here's the exact same in less bytes using standard JS...

f=a=>a.reduce((i,j)=>i>6|i==j|i+j==7?9:j)<7

C#, 99 67 65 bytes

Takes input as an int array a

// new solution using linq
bool A(int[]a){return a.Aggregate((i,j)=>i>6|i==j|i+j==7?9:j)<7;}
// old solution using for loop
bool A(int[]a){for(int i=1;i<a.Length;)if(a[i]==a[i-1]|a[i-1]+a[i++]==7)return false;return true;}

Explanation:

// method that returns a boolean taking an integer array as a parameter
bool A(int[] a) 
{
    // aggregate loops over a collection, 
    // returning the output of the lambda 
    // as the first argument of the next iteration
    return a.Aggregate((i, j) => i > 6 // if the first arg (i) > than 6
    | i == j      // or i and j match
    | i + j == 7  // or i + j = 7
    ? 9   // return 9 as the output (and therefore the next i value)
    : j   // otherwise return j as the output (and therefore the next i value)
    ) 
    // if the output is ever set to 9 then it will be carried through to the end
    < 7; // return the output is less than 7 (not 9)
}

Erresen

Posted 2016-12-21T13:47:13.620

Reputation: 449

I think this needs to be wrapped in a function, or maybe a lambda (does C# have those?) Also, you could save a few bytes by returning 0 or 1 instead of false or true – James – 2016-12-21T18:21:32.937

oh, ok - first post on code golf. I'll edit... – Erresen – 2016-12-21T18:22:44.693

No problem. BTW, welcome to the site! :) – James – 2016-12-21T18:23:34.673

@DJMcMayhem Correct me if I'm wrong but since the output requirement is truthy/falsey then the output options are language dependent tl;dr 1/0 are not truthy/falsey in c# – None – 2016-12-21T18:41:01.717

@Phaeze You're correct that they're not truthy/falsey, but the standard IO rules http://meta.codegolf.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods reckon you can output using exit codes and that functions can output in the same way as programs. I'll change back to booleans if required, but it'll cost me a few bites

– Erresen – 2016-12-21T18:51:43.550

Fair enough, i just wan't sure how that rule applied to c# since it's kind of the black sheep for that :), either way though very nice answer – None – 2016-12-21T18:53:25.773

@Phaeze Cheers - I'm working on a lambda solution now, but if it comes to nought i'll switch to booleans. If i'm gonna play, i might as well play by the rules :) – Erresen – 2016-12-21T18:55:30.657

Nice good luck. I'm working on a linq solution, trying really hard to get sub 90 ;) – None – 2016-12-21T18:59:53.200

When using linq functions your submission has to also include the using statement – None – 2016-12-21T20:32:36.707

You can save two bytes by replacing "==9" and "!=9" with ">6" and "<9", which serve the same purpose: bool A(int[]a){return a.Aggregate((i,j)=>i>6|i==j|i+j==7?9:j)<9;} – Bence Joful – 2016-12-21T20:45:22.143

@BenceJoful thanks! edited – Erresen – 2016-12-21T20:58:10.327

@Phaeze really? that sucks. where's that written? – Erresen – 2016-12-21T21:02:04.227

I'll try to find a post on it, I picked it up just from reading through challenges over the years. but to give an example as to why, in c# 6 you can import a static so you could assume that import and only call Sqrt() instead of Math.Sqrt() – None – 2016-12-21T21:09:18.727

Here is a general answer http://meta.codegolf.stackexchange.com/questions/383/should-imports-includes-count-in-golf it mentions that the std import can be exlcuded which holds true for c# the compiler will automatically add that one.

– None – 2016-12-21T21:17:02.983

And heres a better one that links to the different scenarios that have been asked. http://meta.codegolf.stackexchange.com/a/10848/19547

– None – 2016-12-21T21:21:57.780

@Phaeze fair enough. I've switch the implementation to javascript's reduce function, and saved a few bites. – Erresen – 2016-12-21T21:24:34.220

4

Python, 38 bytes

f=lambda h,*t:t==()or 7>h^t[0]>0<f(*t)

A recursive function that takes arguments like f(1,2,3).

This makes use of argument unpacking to extract the first number into h and the rest into the tuple t. If t is empty, output True. Otherwise, use Zgarb's bit trick to check that the first two die rolls are not incompatible. Then, check that the result also holds on the recursive call on the tail.

xnor

Posted 2016-12-21T13:47:13.620

Reputation: 115 687

3

Processing, 93 92 90 bytes

Changed || to | : 1 byte saved thanks to @ClaytonRamsey

Started counting backwards: 2 bytes saved thanks to @IsmaelMiguel

int b(int[]s){for(int i=s.length;--i>0;)if(s[i-1]==s[i]|s[i-1]==7-s[i])return 0;return 1;}

Takes input as an array of ints, output 1 for true or 0 for false.

Ungolfed

int Q104044(int[]s){
  for(int i=s.length;--i>0;)
    if(s[i-1]==s[i]|s[i-1]==7-s[i])
      return 0;
  return 1;
}

user41805

Posted 2016-12-21T13:47:13.620

Reputation: 16 320

Usually Java allows | instead of || if you want to save a byte. – Clayton Ramsey – 2016-12-21T16:59:10.227

@ClaytonRamsey I don't know why I didn't think of it, thanks! – user41805 – 2016-12-21T17:01:59.540

I found another one. You could cut down on the use of returns with the tertiary operator – Clayton Ramsey – 2016-12-21T18:47:51.303

@ClaytonRamsey The return 0 is inside the if-statement while return 1 is not. I don't see how that is possible unless you have some other idea – user41805 – 2016-12-21T18:56:51.270

never mind, I misread your code – Clayton Ramsey – 2016-12-21T18:57:23.090

But I'm glad that someone is trying to help me golf this verbosity :) – user41805 – 2016-12-21T18:58:48.977

Why don't you loop the array backwards? That should save 1-2 bytes. Something like for(int i=s.length-1;--i;). I'm not sure if this works. – Ismael Miguel – 2016-12-22T15:44:24.640

@IsmaelMiguel Thank you, this saves me 2 bytes! – user41805 – 2016-12-22T15:51:51.080

Wow, I really wasn't expecting it to work! I know barely anything about Java and Processing. – Ismael Miguel – 2016-12-22T15:53:26.963

2Golfed it! Yipee! (nobody's going to read these summaries so why not have fun :) <-- I read it, while comparing what you have with what you had. – Ismael Miguel – 2016-12-22T15:59:18.357

3

><> (Fish) 47 bytes

0:i:1+?!v\!
   0n;n1< >
!?-{:-"0"/^
!? -{-$7:/^

Pretty simple;

Line 1: check to see if inputted a number, if no number (EOF) then we have a truthy to print else checks.

Line 2: print outcome.

Line 3: turn input into number (ASCII 0 - from input), then check if it's equal to previous input.

Line 4: check if input is opposite side of die.

Teal pelican

Posted 2016-12-21T13:47:13.620

Reputation: 1 338

3

PowerShell, 57 44 41 bytes

(Crossed out 44 is still regular 44)

0-notin($args|%{7-$_-$l-and$l-ne($l=$_)})

Try it online!

(OP has clarified that taking input as separate arguments is OK - saved 13 bytes ... saved another 3 bytes by eliminating $b)

We're looping through the input $args a digit at a time. Each digit, we verify that the $last digit is -notequal to the current digit $_, and that 7-$_-$l is some number other than zero (which is truthy). Those Boolean results are encapsulated in parens and fed into the right-hand operand of the -notin operator, checking against 0. In other words, if there is any False value anywhere in the loop, the -notin will also be False. That Boolean is left on the pipeline, and output is implicit.

Lengthy because of the $ requirement for variable names, and that Boolean commands -ne -and are verbose in PowerShell. Oh well.

AdmBorkBork

Posted 2016-12-21T13:47:13.620

Reputation: 41 581

3

Brain-Flak 128 Bytes

(()){{}(({}<>)<>[({})])}{}([]){{{}}<>}{}([]){{}({}({})<>)<>([][()])}{}(<{}>)<>(([])){{}{}({}[(()()()){}()]){<>}<>([][()])}({}{})

Outputs 0 for falsey, or -7 for truthy.

Try it Online! (Truthy)
Try it Online! (Flasey)

Explanation (t stands for top and s stands for second from the top):

(())                # push a 1 to get this loop started
{{}                 # loop through all pairs, or until 2 are equal
(({}<>)<>[({})])    # pop t, push t on the other stack, and t - s on this one
}{}                 # end loop and pop one more time
([])                # push the height of the stack
{                   # if the height isn't 0 (there were equal numbers)...
{{}}<>              # pop everything from this stack and switch
}                   # end if
{{}                 # for every pair on the stack: pop the height and...
({}({})<>)<>        # push t + s on the other stack leaving s on this one
([][()])            # push the height - 1
}                   # end loop when there is only 1 number left
{}(<{}>)<>          # pop t, pop s, push 0 and switch stacks
(([]))              # push the height twice
{                   # loop through every pair
{}{}                # pop the height and what was t - 7
({}[(()()()){}()])  # push t - 7
{<>}<>              # if t is not 0 switch stacks and come come back
                    # if t is 0 (ie, there was a pair that added to 7) just switch once
([][()])            # push height - 1
}                   # end loop
({}{})              # push t + s (either 0 + 0 or 0 + -7)

Riley

Posted 2016-12-21T13:47:13.620

Reputation: 11 345

3

MATLAB, 30 bytes

@(a)all(diff(a)&movsum(a,2)-7)

rahnema1

Posted 2016-12-21T13:47:13.620

Reputation: 5 435

3

PHP, 63 bytes

for($d=$argv[$i=1];$c=$argv[++$i];$d=$c)$d-$c&&$d+$c-7?:die(1);

takes input as list of command arguments; exits with 1 (error) if input is invalid, 0 (ok) if valid.

Run with -nr.

input as string argument, 65 bytes

for($d=($s=$argv[1])[0];$c=$s[++$i];$d=$c)$d-$c&&$d+$c-7?:die(1);

Titus

Posted 2016-12-21T13:47:13.620

Reputation: 13 814

3

C 47 44 bytes

F(char*s){return!s[1]||(*s^s[1])%7&&F(s+1);}

takes a string of digits (or a zero terminated array of bytes)

Explanation

F(char*s){

according to the standard int return type is implied. (saving 4 bytes)

return unconditional return because this is a recursive function

using shortcut evaluation:

!s[1]|| if the second character is nul return true

((*s^s[1])%7&& if the first two charcters aren't legal false

F(s+1)) check the rest of the string in the same way

that confusing expression

*s is the first character s[1] is the second

*s^s[1] exclusive-ors them together if they are the same the result is 0 if they add to 7 the result is 7 , (if they differ and don't add to 7 the result is between 1 and 6 inclusive)

so (*s^s[1])%7 is zero for bad input and non-zero otherwise, thus false if these 2 characters are bad, and true otherwise

comment: as this function call uses only end-recursion (only the last statement is a recursive call) an optimiser could translate the recursion into a loop, this is a happy conicidence and is obviously not worth any golf score, but in the real word makes it possible to process strings of any length without running out of stack.

Jasen

Posted 2016-12-21T13:47:13.620

Reputation: 413

1About your !((*s^s[1])%7) I think you don't want the !. Zero values for bad input would be falsy, so you want to return the falsy when it's bad. – nmjcman101 – 2016-12-22T14:36:09.870

2

Python, 71 bytes

f=lambda s:len(s)<2or(s[0]!=s[1]and int(s[0])!=7-int(s[1]))and f(s[1:])

Uses a recursive approach.

Explanation:

f=lambda s:                                                              # Define a function which takes an argument, s
           len(s)<2 or                                                   # Return True if s is just one character
                      (s[0]!=s[1]                                        # If the first two characters matches or...
                                 and int(s[0])!=7-int(s[1])              # the first character is 7 - the next character, then return False
                                                           )and f(s[1:]) # Else, recurse with s without the first character

Loovjo

Posted 2016-12-21T13:47:13.620

Reputation: 7 357

say that the input is a list of ints, and then you don't need the casts. – Jasen – 2016-12-25T02:24:19.500

2

Retina, 28 bytes

M`(.)\1|16|25|34|43|52|61
^0

Try it online!

Alternatively:

M`[16]{2}|[25]{2}|[34]{2}
^0

Try it online!

Martin Ender

Posted 2016-12-21T13:47:13.620

Reputation: 184 808

2

MATL, 9 bytes

dG2YCs7-h

The input is an array of numbers representing the digits.

The output is a non-empty array, which is truthy if all its entries are non-zero, and falsy otherwise (read more about MATL's criterion for truthy and falsy here).

Try it online! Or verify all test cases.

Explanation

d     % Take input implicitly. Consecutive differences
G     % Push input again
2YC   % Overlapping blocks of length 2, arranged as columns of a matrix
s     % Sum of each column
7-    % Subtract 7, element-wise
h     % Concatenate horizontally. Implicitly display

Luis Mendo

Posted 2016-12-21T13:47:13.620

Reputation: 87 464

Is it possible/intended to add some new MATLAB functions to MATL? – rahnema1 – 2016-12-21T16:11:34.960

@rahnema1 Yes, there are some function names currently unused. However, I tend to be selective and add only those that I think will be used often. If you have any proposals we can discuss them in the MATL chatroom :-)

– Luis Mendo – 2016-12-21T17:34:43.967

@rahnema1 If you are thinking of movsum, there's already conv2 (which includes conv); see Y+ and Z+ – Luis Mendo – 2016-12-21T17:36:50.090

2

C# (with Linq) 90 81 73 71 69 68 Bytes

using System.Linq;n=>n.Aggregate((p,c)=>p<9|c==p|c==103-p?'\b':c)>9;

Explanation:

using System.Linq;           //Obligatory import
n=>n.Aggregate((p,c)=>       //p serves as both previous character in chain and error flag
    p<9                      //8 is the error flag, if true input is already invalid            
        |c==p            
            |c==103-p        //103 comes from 55(7) + 48(0)
                ?'\b'       //'\b' because it has a single digit code (8)
                    :c)      //valid so set previous character, this catches the first digit case as well
                        >8;  //as long as the output char is not a backspace input is valid

user19547

Posted 2016-12-21T13:47:13.620

Reputation:

2

C, 81 bytes, was 85 bytes

int F(int *A,int L){int s=1;while(--L)s&=A[L]!=A[L-1]&A[L]!=(7-A[L-1]);return s;}

Input is an array of integers A with length L. Returns 1 for true and 0 for false. The input is checked from the end to the start using the input length L as the array index.

user230118

Posted 2016-12-21T13:47:13.620

Reputation: 239

int is optional at the start, you can save 4 bytes. – Jasen – 2016-12-22T10:05:18.770

int s=1; can be declared outside the function as s=1; for another 4. – nmjcman101 – 2016-12-22T14:18:38.350

68 bytes – ceilingcat – 2020-01-23T00:16:21.203

2

Haskell, 37 bytes

f(a:b:c)=a+b/=7&&a/=b&&f(b:c)
f _=1<2

Usage example: f [1,5,2] -> False.

Simple recursion. Base case: single element list, which returns True. Recursive case: let a and b be the first two elements of the input list and c the rest. All of the following conditions must hold: a+b/=7, a/=b and the recursive call with a dropped.

nimi

Posted 2016-12-21T13:47:13.620

Reputation: 34 639

2

JavaScript, 40 bytes

f=i=>i.reduce((a,b)=>a&&a-b&&a+b-7&&b,9)

Takes advantage of the JavaScript feature that && will return the last value that is parsed (either the falsy term or the last term). 0 is passed along if it doesn't meet the conditions, and the previous term is passed along otherwise. The 9 makes sure that it starts with a truthy value.

JackW

Posted 2016-12-21T13:47:13.620

Reputation: 121

1

Groovy, 61 bytes

{i=0;!(true in it.tail().collect{x->x in [7-it[i],it[i++]]})}

Magic Octopus Urn

Posted 2016-12-21T13:47:13.620

Reputation: 19 422

1

Python 2, 58 Bytes

lambda x:all(x[i]!=x[i+1]!=7-x[i]for i in range(len(x)-1))

Noodle9

Posted 2016-12-21T13:47:13.620

Reputation: 2 776

1

><>, 39 bytes

0>i'0'-::&0)?v1n;>&!
?=0+=7+@=}:{:<;n0^

Try it online!

Emigna

Posted 2016-12-21T13:47:13.620

Reputation: 50 798

1

Batch, 102 bytes

@set s=%1
@set/an=0%s:~0,2%,r=n%%9*(n%%7)
@if %r%==0 exit/b
@if %n% gtr 6 %0 %s:~1%
@echo 1

Ungolfed:

@echo off
rem grab the input string
set s=%1
:loop
rem convert the first two digits as octal
set /a n = 0%s:~0,2%
rem check for divisibility by 9 (011...066)
set /a r = n %% 9
rem exit with no (falsy) output if no remainder
if %r% == 0 exit/b
rem check for divisibility by 7 (016...061)
set /a r = n %% 7
rem exit with no (falsy) output if no remainder
if %r% == 0 exit/b
rem remove first digit
set s=%s:~1%
rem loop back if there were at least two digits
if %n% gtr 6 goto loop
rem truthy output
echo 1

Neil

Posted 2016-12-21T13:47:13.620

Reputation: 95 035

1

Clojure, 55 49 46 bytes

edit 1: using (mapcat ...) instead of (flatten(map ...))

edit 2: using (juxt - +) instead of (juxt = +), checking for values 0 or 7

#(not(some #{0 7}(mapcat(juxt - +)(rest %)%)))

Consecutive values are not allowed to be equal (difference = 0) or sum up to 7. Got to use juxt again :)

NikoNyrh

Posted 2016-12-21T13:47:13.620

Reputation: 2 361

1

JavaScript (ES6), 46 Bytes

a=>r=1&&a.reduce((c,p)=>r=c==p||c==7-p?0:1)&&r

f=a=>r=1&&a.reduce((c,p)=>r=c==p||c==7-p?0:1)&&r;

console.log(f([4,6]));
console.log(f([1,6]));

Arjun

Posted 2016-12-21T13:47:13.620

Reputation: 4 544

1

Bash, 60 bytes

f(){ 
while [ $2 ]
do
(( ($1^$2)%7 ))||return 1
shift
done
}

Takes separate arguments as input.

Explanation

while-do-shift-done loops though the arguments giving each pair a turn as ($1,$2) if the loop completes truth is returned.

The complicated expression (( ($1^$2)%7 )) exclusive-ors the the arguments being tested together and mod(7)s them.

Valid pairs will result in non-zero, invalid ones in zero.

((...)) yields true when the arithmetic returns non-zero.

|| runs the next command if the previous was false (in this context that means if the arithmetic above returned 0).

Unix shell treats zero as true (except as above) so return 1 yields a false result from this function when an invalid pair is found.

Jasen

Posted 2016-12-21T13:47:13.620

Reputation: 413

1

Prolog (SWI), 45 bytes

p([A,B|T]):-A+B=\=7,A\=B,p([B|T]).
p([_|[]]).

Online interpreter

Emigna

Posted 2016-12-21T13:47:13.620

Reputation: 50 798

1

Math++, 111 bytes

?>b
0>n
n+1>n
b%10>{n}
_(b/1)>b
3+4*!b>$
0>n
n+1>n
10+4*!({n}-{n+1})>$
11+3*!(7-{n}-{n+1})>$
8+4*!{n}>$
1
0>$
0

SuperJedi224

Posted 2016-12-21T13:47:13.620

Reputation: 11 342

1

Mathematica, 32 bytes

FreeQ[Most@#~BitXor~Rest@#,0|7]&

Unnamed function taking a list of integers as input and outputting True or False. Like many existing answers, it computes the bitwise XOR of consecutive elements of the input, and checks that the answer is never 0 nor 7.

Greg Martin

Posted 2016-12-21T13:47:13.620

Reputation: 13 940

1

PHP, 41 bytes

<?=!similar_text(aa^af,$s^s.$s=$argv[1]);

Takes input as a string. Prints 1 if the input is valid, an empty string otherwise.

Calculates XOR by pairs of adjacent characters, using shifted version of the input. Then searches for 0x00 or 0x07 characters in it.

user63956

Posted 2016-12-21T13:47:13.620

Reputation: 1 571

1

SmileBASIC, 65 bytes

DEF T A
WHILE LEN(A)V=POP(A)IF!(O-V&&7-O-V)THEN?0A
O=V
WEND?1
END

This can definitely be made a little smaller

12Me21

Posted 2016-12-21T13:47:13.620

Reputation: 6 110