37
\$\begingroup\$

In the game Yahtzee, players roll five six-sided dice, and attempt to create certain hands to score points. One such hand is a small straight: four consecutive numbers, not necessarily in order. The three possible small straights are 1, 2, 3, 4, 2, 3, 4, 5, and 3, 4, 5, 6.

For example, [3, 5, 6, 1, 4] contains the small straight [3, 4, 5, 6].

Input

An unsorted list of five integers, each between 1 and 6 inclusive, representing a Yahtzee hand.

Output

A truthy value if the hand contains a small straight and a falsy value otherwise.

Test cases

Truthy:

[[1, 2, 3, 3, 4], [1, 2, 3, 4, 5], [3, 5, 6, 1, 4], [1, 5, 3, 4, 6], [4, 5, 2, 3, 5], [1, 4, 3, 2, 2], [5, 4, 3, 6, 3], [5, 3, 5, 4, 6], [2, 4, 5, 1, 3], [3, 6, 4, 5, 3], [5, 6, 4, 3, 5], [4, 5, 3, 6, 3], [4, 5, 5, 3, 2], [4, 5, 2, 3, 5], [4, 6, 5, 3, 6], [4, 2, 3, 1, 5], [3, 6, 4, 6, 5], [5, 2, 1, 3, 4], [4, 4, 1, 2, 3], [4, 1, 4, 2, 3], [5, 1, 4, 3, 6], [5, 2, 2, 3, 4], [4, 4, 6, 5, 3], [2, 4, 3, 5, 1], [5, 4, 2, 5, 3], [2, 3, 5, 5, 4], [1, 6, 3, 4, 5], [4, 5, 3, 3, 6], [6, 4, 3, 6, 5], [4, 6, 6, 5, 3], [4, 3, 5, 2, 2], [2, 3, 2, 1, 4], [4, 2, 6, 1, 3], [4, 4, 5, 3, 6], [4, 5, 6, 3, 6]]

Falsy:

[[1, 2, 3, 5, 6], [5, 1, 1, 6, 6], [4, 6, 4, 1, 1], [6, 4, 1, 6, 4], [4, 6, 3, 6, 6], [2, 1, 4, 6, 4], [2, 6, 1, 5, 6], [2, 6, 1, 5, 6], [3, 6, 5, 3, 2], [3, 2, 3, 5, 3], [5, 5, 6, 2, 3], [3, 4, 6, 4, 3], [1, 4, 5, 5, 1], [1, 4, 4, 4, 1], [1, 6, 5, 1, 4], [6, 6, 4, 5, 4], [5, 3, 3, 3, 2], [5, 2, 1, 5, 3], [3, 5, 1, 6, 2], [6, 4, 2, 1, 2], [1, 3, 1, 3, 2], [3, 1, 3, 4, 3], [4, 3, 1, 6, 3], [4, 6, 3, 3, 6], [3, 6, 3, 6, 4], [1, 1, 3, 1, 3], [5, 5, 1, 3, 2], [3, 4, 2, 6, 6], [5, 4, 2, 6, 1], [2, 4, 4, 5, 4], [3, 6, 2, 5, 5], [2, 5, 3, 5, 1], [3, 2, 2, 3, 4], [5, 2, 2, 6, 2], [5, 6, 2, 5, 6]]

Inspired by this

Catalogue

var QUESTION_ID=74997;var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";var COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk";var OVERRIDE_USER=30525;var answers=[],answers_hash,answer_ids,answer_page=1,more_answers=true,comment_page;function answersUrl(index){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(index,answers){return"http://api.stackexchange.com/2.2/answers/"+answers.join(';')+"/comments?page="+index+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){answers.push.apply(answers,data.items);answers_hash=[];answer_ids=[];data.items.forEach(function(a){a.comments=[];var id=+a.share_link.match(/\d+/);answer_ids.push(id);answers_hash[id]=a});if(!data.has_more)more_answers=false;comment_page=1;getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:true,success:function(data){data.items.forEach(function(c){if(c.owner.user_id===OVERRIDE_USER)answers_hash[c.post_id].comments.push(c)});if(data.has_more)getComments();else if(more_answers)getAnswers();else process()}})}getAnswers();var SCORE_REG=/<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;var OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(a){return a.owner.display_name}function process(){var valid=[];answers.forEach(function(a){var body=a.body;a.comments.forEach(function(c){if(OVERRIDE_REG.test(c.body))body='<h1>'+c.body.replace(OVERRIDE_REG,'')+'</h1>'});var match=body.match(SCORE_REG);if(match)valid.push({user:getAuthorName(a),size:+match[2],language:match[1],link:a.share_link,});else console.log(body)});valid.sort(function(a,b){var aB=a.size,bB=b.size;return aB-bB});var languages={};var place=1;var lastSize=null;var lastPlace=1;valid.forEach(function(a){if(a.size!=lastSize)lastPlace=place;lastSize=a.size;++place;var answer=jQuery("#answer-template").html();answer=answer.replace("{{PLACE}}",lastPlace+".").replace("{{NAME}}",a.user).replace("{{LANGUAGE}}",a.language).replace("{{SIZE}}",a.size).replace("{{LINK}}",a.link);answer=jQuery(answer);jQuery("#answers").append(answer);var lang=a.language;lang=jQuery('<a>'+lang+'</a>').text();languages[lang]=languages[lang]||{lang:a.language,lang_raw:lang.toLowerCase(),user:a.user,size:a.size,link:a.link}});var langs=[];for(var lang in languages)if(languages.hasOwnProperty(lang))langs.push(languages[lang]);langs.sort(function(a,b){if(a.lang_raw>b.lang_raw)return 1;if(a.lang_raw<b.lang_raw)return-1;return 0});for(var i=0;i<langs.length;++i){var language=jQuery("#language-template").html();var lang=langs[i];language=language.replace("{{LANGUAGE}}",lang.lang).replace("{{NAME}}",lang.user).replace("{{SIZE}}",lang.size).replace("{{LINK}}",lang.link);language=jQuery(language);jQuery("#languages").append(language)}}
body{text-align:left!important}#answer-list{padding:10px;width:290px;float:left}#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="language-list"> <h2>Shortest Solution 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> <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> <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>

\$\endgroup\$
8
  • \$\begingroup\$ Does the truthy value have to be consistent? Could I output some (non-constant) positive integer for truthy results and 0 for falsy results? \$\endgroup\$ Mar 7, 2016 at 18:13
  • \$\begingroup\$ @MartinBüttner It needn't be consistent. \$\endgroup\$
    – lirtosiast
    Mar 7, 2016 at 18:13
  • 10
    \$\begingroup\$ Make sure to check if it works on [1,2,3,3,4]. Many answers die because of this. \$\endgroup\$ Mar 7, 2016 at 18:30
  • \$\begingroup\$ Can I assume the array is padded by zeros? \$\endgroup\$ Mar 7, 2016 at 18:58
  • 6
    \$\begingroup\$ @CatsAreFluffy "die" \$\endgroup\$ Mar 7, 2016 at 20:19

46 Answers 46

29
\$\begingroup\$

MATL, 7 12 11 9 8 6 bytes

Thanks a lot to @lirtosiast for removing 2 bytes

ud7BXf

Truthy is an array of nonzero values. Falsy is empty array (no output displayed).

As of release 16.2.0, u is stable by default. So the code needs an extra S to sort the output: uSd7BXf (7 bytes). The link includes this modification.

Try it online!

u     % input array implicitly. Transform into array of unique elements sorted
d     % array of differences between consecutive elements
7B    % push arrray [1 1 1] (number 7 converted to binary)
Xf    % indices of occurrences of the second array within the first
\$\endgroup\$
11
  • 4
    \$\begingroup\$ 6 bytes?! This is unbelievable! \$\endgroup\$
    – Adnan
    Mar 7, 2016 at 21:26
  • 3
    \$\begingroup\$ @AandN \o/ \o/ \o/ \$\endgroup\$
    – Luis Mendo
    Mar 7, 2016 at 21:28
  • 8
    \$\begingroup\$ I'd like it if you would keep the byte count history like other users do. It shows the progression. \$\endgroup\$
    – mbomb007
    Mar 7, 2016 at 22:19
  • 1
    \$\begingroup\$ At least the progression from 8 to 6 was correct... \$\endgroup\$ Mar 7, 2016 at 22:54
  • 5
    \$\begingroup\$ @DonMuesli FWIW I agree with you and disagree with mbomb007. Versions that weren't working are meaningless and shouldn't be included in the history. I usually include only byte counts of working versions, so it's definitely a strictly decreasing sequence. \$\endgroup\$ Mar 8, 2016 at 10:23
13
\$\begingroup\$

Python, 44 bytes

lambda l:any({i+1,i+2,i+3}<set(l)for i in l)

Back after 9 months with an improvement. We don't need to check if i is in the set with Zgarb's idea of checking only start values in the set. We can now also use < for strict subsets because i must also be included.


47 bytes:

lambda l:any({i,i+1,i+2,i+3}<=set(l)for i in l)

Checks if any die rolls is the start of a small straight set. Thanks to Zgarb for the idea of only checking start values in the list, saving 5 bytes.

Python 3.5 has shorter set conversion, for 45 bytes

lambda l:any({i,i+1,i+2,i+3}<={*l}for i in l)

It's the same length to do {*range(i,i+4)} as {i,i+1,i+2,i+3}.

\$\endgroup\$
0
10
\$\begingroup\$

Labyrinth, 41 bytes

=|?30
0 _ }:/2
3 1  { "!
({(  &{/
} )
+:"

A collab answer with @MartinBüttner. I think we've squeezed this one far beyond my initial expectations.

Output is 1 for truthy, empty for falsy. Try it online!

Quick explanation

Convert each number n to a binary integer 1 followed by n+1 zeroes, i.e. 2^(n+1). Bitwise OR the results and check for 1111 (in binary). Exponentiation needs to be implemented manually in Labyrinth.

Detailed explanation

The usual primer:

  • Labyrinth is a stack-based 2D programming language. For memory there is a main stack and an auxiliary stack, and popping from an empty stack produces 0 rather than an error.
  • At each junction, where the instruction pointer could move down two or more possible paths, the top of the stack is checked to decide where to go next. Negative is left, zero is forward, positive is right.
  • Digits in Labyrinth do not push the corresponding digit to the stack – rather, they pop n and push n*10 + <digit>. To start a new number, _ pushes zero.

Setup

Execution begins at the top-left, with the instruction pointer facing rightwards. We execute:

=        Swap tops of main and auxiliary stacks
|        Bitwise OR

Aside from effectively pushing zeroes, these instructions don't change the stack.

Left loop: exponentiate and bitwise OR

Labyrinth doesn't have exponentiation, so we need to implement it manually. First we read an integer with ?, and since this is guaranteed to be positive we turn right. _1 pushes 1 and we enter the inner loop.

The inner loop does the following:

(       Decrement. For the first iteration this turns 1 into 0 so we move straight ahead
        downwards; for other iterations when we're coming from the left this turns 2^k into
        2^k-1 > 0, making us turn right (also downwards)
)       Increment again
"       No-op
:+      Duplicate and add, i.e. double
}       Move result to aux
(       Decrement input n. Since this is at a junction, we turn right and continue the
        loop if n is still positive, else we exit the loop by going forwards if n is 0
{       Move result from aux to main

Since this is a do-while loop, for input n this calculates 2^(n+1). We end with the zeroed input on the stack, and 30 turns this zero into 30. We then perform the same instructions from the setup, but this time they're actually useful.

=       Swap tops of main and aux, moving 30 to aux and 2^(n+1) to main
|       Bitwise OR (for the first input, this is bitwise OR with an implicit zero at
        the bottom of the stack)

This loop continues for each number in the input until EOF, when ? returns 0. This makes us move forwards instead of turning, leading into...

Bridge: some extra setup

The 30 after the ? turns the 0 from EOF into 30, which is pushed to the auxiliary stack via }. Of importance is the fact that we pushed a 30 to the auxiliary stack for every input number, so now the auxiliary stack contains 5 + 1 = 6 copies of the number 30.

Meanwhile, the main stack contains the bitwise OR of 2^(n+1) for each input n. Let's call this bitwise OR b, since it gets modified in the right loop.

Right loop: check result and output

Here's what happens in the right-hand side loop:

:     Duplicate top of stack. This makes us turn right for the first iteration, since
      b is positive. For later iterations, when we're coming in from the
      right, we usually take the same turn (but see below)
{&    Bitwise AND with a 30 pulled from aux
{/    Integer division by a 30 pulled from aux. This returns 1 or 0 depending on whether
      we have found a small straight.
"     No-op at a junction. Turn right if small straight, else go forward.

[If small straight found]
!     Output the previous 1. This is at a dead end, so we turn around.
"     No-op at junction. Turn right since top of stack is positive.
      (stuff happens - see below)

[If small straight not found]
2     Turn 0 into 2
/     Divide b by said 2
      (continue loop)

Now, termination is a little tricky with this program. Here are the possible ways the program can terminate:

  • After 3 iterations of the right loop, and b is still positive: Remember how we put six 30s into the auxiliary stack? Since we use two of them each iteration, on the fourth iteration we start pulling zeroes from the bottom of the auxiliary stack. This causes a division by zero when we do {/, and the program terminates.

  • After outputting a 1 for a small straight: So we've executed ! then turned right at the no-op " junction. Then we're in for a rollercoaster as we start crawling all over the left half again:

2     Pops b, pushes 10*b + 2
/}    Divide bottom zero by b, giving zero, pushing to aux
03    Zero at bottom of stack becomes 3
?     Push 0 due to EOF, main stack [3 0]. Go straight.
|=    Bitwise OR then swap tops of main and aux
03    Zero at bottom of stack becomes 3, stacks [3 | 3]
({(   Dec, shift dec. Stacks [2 2 | ], and we're in the exponentiator again.

After a few trips in the exponentiator, the stack looks something like [12 | 30 30], which errors out by division by zero after another two iterations in the right loop.

  • After b becomes zero at some point: The key here is that the : in the right loop is at a junction. If the input was, say, 1 1 1 1 1, then b would be 4, then 2, then 1, then 0 after the third iteration. Instead of turning at the :, the IP now moves straight ahead, and something like the previous case happens to cause an eventual termination.

All in all it's a mess how the program terminates, but hey anything to save those few bytes!

\$\endgroup\$
7
\$\begingroup\$

Mathematica, 39 43 44 31 39 44 bytes

Differences@Union@#~MatchQ~{___,1,1,1,___} &
\$\endgroup\$
1
  • 15
    \$\begingroup\$ Well, not crossed out 44 is still 44... \$\endgroup\$
    – Riker
    Mar 7, 2016 at 20:45
7
\$\begingroup\$

Haskell, 39 34 bytes

f x=any(\y->all(`elem`x)[y..y+3])x

Usage example: f [1,2,3,3,4] -> True.

Similar to @xnor's answer, i.e. check if any of the small straights are in the input list. Actually I'm testing all "small straights" (i.e. 4 consecutive numbers) starting with any of the numbers from the input list, some of them being invalid and therefore always fail the all test and don't distort the any test, e.g. [5,6,7,8].

Edit: @Zgarb saved 5 bytes. Thanks!

\$\endgroup\$
0
5
\$\begingroup\$

MATL, 11 bytes

udY'w1=)2>a

Try it online

u           unique (implicit sort)
d           diff
Y'          run-length-encode
w1=)        exract the length of all runs of ones
2>          check whether they are longer than two
a           any (any non-zero element)
\$\endgroup\$
0
5
\$\begingroup\$

JavaScript (ES6), 55 53 bytes

a=>(z=[0,1,2,3]).some(b=>z.every(c=>a.includes(c+b)))

returns true for truthy and false for falsy.

How it works

Return if some value in [0, 1, 2, 3] fulfills the condition that for every value in [0, 1, 2, 3] the sum of these two values is in the input array.

So, return if the array has every value in [0, 1, 2, 3] (impossible), [1, 2, 3, 4], [2, 3, 4, 5], or [3, 4, 5, 6].

\$\endgroup\$
5
\$\begingroup\$

Perl, 47 43 42 39 37 29 bytes

Includes +1 for -p

Run with the sequence on STDIN, e.g.

perl -p smallstraight.pl <<< "1 2 3 3 4"

smallstraight.pl:

s//$_|=1x$'.w/reg;$_=/.w{4}/

Explanation

s//          / eg             Each possible postfix string (including the
                              empty string) is assigned to $' in turn
                              So each input digit will be the start of $'
                              at least once
       1x$'.w                 Put a w at position $'.
                              e.g. digit 4 becomes 1111w
   $_|=                       Or into existing $_.
                                w        is binary 0111 0111
                                space    is binary 0010 0000
                                digit<=7 is binary 0011 0xxx
                              So an "or" with "w" is always w again:
                                                   0111 0111
                              And no other way can you get a w since w is the
                              only thing that can set the high bits. So the
                              already existing string in $_ has no effect on
                              the number of w's in the result
              r               The $_ that has been "or"ed several times is
                              exfiltrated out of the substitution. It will
                              have a w in every position that the original
                              string had a digit with an extra w at position
                              0 since the s///g will also have matched the
                              empty string at the end
                              So e.g. "1 2 3 5 6" will become "wwww3ww 6"
                  $_=/.w{4}/  We have a small straight if there were 4
                              consecutive numbers, now 4 consecutive w's. But
                              the w we always get at the start of the string
                              doesn't count. Notice that the string cannot 
                              have a newline since bit "0010 0000" is always
                              set. So "." to skip one character is safe
\$\endgroup\$
5
\$\begingroup\$

Ruby, 31

Instead of trying to be smart like the first Ruby answer, this just goes through the array of integers, and for each integer, sees if there's a small straight in the input starting with that integer. Doesn't worry about the possible values or uniqueness.

This seems to be using the same algorithm as Sherlock's answer.

->x{x.any?{|d|[*d..d+3]-x==[]}}
\$\endgroup\$
5
\$\begingroup\$

Ruby, 58 55 50 47 43 33 bytes

I just now saw that I have been beaten to the punch by Paul's Ruby answer. I am not deterred however as I think this could still be a decent answer with some more golfing. Based, in part, on xnor's Python answer.

Edit: Some golfing and correcting a mix-up in the ternary conditional.

Edit: I now use .any? like Not that Charles does in their Ruby answer but only because I needed a simple way to remove a and to return only a truthy and a falsey with !([*i..i+3]-l)[0] since .map would return an array of true and false.

->l{l.any?{|i|!([*i..i+3]-l)[0]}}

Returns either true or false.

Ungolfed:

def f(l)
  a = p
  l.any? do |i|
    if ( (i..i+3).to_a - l )[0]     # if (i..i+3) in l
      a = false                     # a[0] is equivalent to !a.empty?
    else
      a = true
    end
  end
  puts a
end

Important note: For those who want to use the (a2 - a1).empty? code to determine if all elements of a2 are in a1, note that if you want to make sure that, for example, [2,1,2] is in [1,2,3,3] to multiplicity of elements, you need other code. Relevant discussion of this problem here.

\$\endgroup\$
6
  • \$\begingroup\$ Could you link to the answer instead of the user? \$\endgroup\$ Mar 9, 2016 at 1:47
  • \$\begingroup\$ @CᴏɴᴏʀO'Bʀɪᴇɴ Fixed. \$\endgroup\$
    – Sherlock9
    Mar 9, 2016 at 1:49
  • \$\begingroup\$ I think I accidentally used the same algorithm you did. Sorry! codegolf.stackexchange.com/a/75273 I wouldn't have posted if I noticed that before I posted it. \$\endgroup\$ Mar 10, 2016 at 16:12
  • \$\begingroup\$ @NotthatCharles Well, your answer was better than mine, so I have given you an upvote. \$\endgroup\$
    – Sherlock9
    Mar 10, 2016 at 17:35
  • \$\begingroup\$ Also, just as a note, since 0 is truthy in Ruby, I think your answer is invalid. p is a one-character falsy value. \$\endgroup\$ Mar 10, 2016 at 17:43
4
\$\begingroup\$

Japt, 13 12 bytes

Uá4 d@7o ¬fX

Test it online! or Verify all test cases.

How it works

       // Implicit: U = input array
Uá4    // Take all permutations of U of length 4.
d@     // Return whether any item X returns truthily to this function:
7o ¬   //  Take the range [0..7) and join. Produces "0123456".
fX     //  Match X in this string.
       //  This returns null if X is not a subset of [0..7), and a (truthy) array otherwise.
       // Implicit output
       
\$\endgroup\$
1
  • 3
    \$\begingroup\$ Nice approach!! \$\endgroup\$
    – Luis Mendo
    Mar 7, 2016 at 21:27
4
\$\begingroup\$

Pyth, 13 11

@.PQ4.:S6 4

2 bytes thanks to Jakube!

Returns a non-empty list for truthy, empty list for falsy.

Try it online or run the Test Suite (split by a syntax error for Readability™).

\$\endgroup\$
1
  • \$\begingroup\$ .PQ4 instead of .:{SQ4 \$\endgroup\$
    – Jakube
    Mar 10, 2016 at 18:16
3
\$\begingroup\$

CJam, 16 15 12 bytes

7,4ewl~f&3f>

Yields a non-empty string for truthy test cases and an empty string for falsy ones.

Test suite.

Explanation

7,      e# Push [0 1 2 3 4 5 6].
4ew     e# Get all length-4 sublists. This gives:
        e#   [[0 1 2 3]
        e#    [1 2 3 4]
        e#    [2 3 4 5]
        e#    [3 4 5 6]]
        e# i.e. all possible small straights (and an impossible one).
l~      e# Read and evaluate input.
f&      e# Set intersection of each small straight with the full list.
        e# If any small straight is contained in the list, all 4 of its
        e# elements will be retained.
3f>     e# Discard the first three elements of each intersection. If a 
        e# small straight was not in the list, this will give an empty 
        e# list. Otherwise, one element will remain.

At the end of the program, this list is flattened into a single string and printed to STDOUT. If any of the small straights were found, their remaining elements will be in the string. Otherwise all the lists were empty, and so the string is also empty.

\$\endgroup\$
2
  • \$\begingroup\$ @mbomb007 "i.e. all possible small straights (and an impossible one)." The input will never contain zero, so that small straight will never be found and therefore doesn't affect the result. \$\endgroup\$ Mar 7, 2016 at 20:54
  • \$\begingroup\$ @mbomb007 Yeah, getting rid of [0 1 2 3] would cost 2 bytes. \$\endgroup\$ Mar 7, 2016 at 21:00
3
\$\begingroup\$

05AB1E, 9 8 10 bytes

Truthy is containing an array in the output, falsy is when no output is produced. Code:

œvy¦¥1QPiy

Explanation outdated:

œ          # Compute all permutations
 vy        # Map over each permutation
   ¦       # Head, leaves [1:]
    ¥      # Delta, computes the differences between the elements
     P     # Product, which computes the product of the array
      iy   # If equal to 1, push the array again
           # Implicit, if there is a match, an array will be displayed.
       

Try it online!

Uses CP-1252 encoding.

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

Javascript ES6 47 bytes

q=>/12+3+4|23+4+5|34+5+6/.test(q.sort().join``)

Javascript ES6 52 bytes

q=>/1,+1,+1/.test(q.sort().map((a,i)=>a-q[i-1]||``))

//sort the array
//map each element to the difference from the last element
//Look for three 'increment by ones' (ignore increment by 0s)


Old answer

Javascript ES6 64 bytes

thanks to ETHproductions for helping save several bytes

q=>q.sort().map(o=>(o-s?o-s<2?t++:t=t>3?t:1:0,s=o),t=1,s=-1)|t>3

q=>              //take an input
q.sort()         //sort it
.map(            //for each number
  o=>
    s=           //set current value = 
      !(o-s) ?   //if it's a duplicate
        o :      //just keep the current state (set s to s again)
        (  
         o-s < 2 ?  //if the current values is one more than the next one
           t++ :    //increment the total
           t=t>4?t:1 //otherwise, set the total back to 1, unless we've hit 4 total already
         )&&o  //set the current value to the current token
   ,t=1,s=-1)  //init the total, and the current value (set it to -1 since we won't hit that anyways

|t>3 //return total > 3 (so 1 if we get a run of 4 or 5)

Testing

//true and false test cases from OP
tr = [[1, 2, 3, 3, 4], [1, 2, 3, 4, 5], [3, 5, 6, 1, 4], [1, 5, 3, 4, 6], [4, 5, 2, 3, 5], [1, 4, 3, 2, 2], [5, 4, 3, 6, 3], [5, 3, 5, 4, 6], [2, 4, 5, 1, 3], [3, 6, 4, 5, 3], [5, 6, 4, 3, 5], [4, 5, 3, 6, 3], [4, 5, 5, 3, 2], [4, 5, 2, 3, 5], [4, 6, 5, 3, 6], [4, 2, 3, 1, 5], [3, 6, 4, 6, 5], [5, 2, 1, 3, 4], [4, 4, 1, 2, 3], [4, 1, 4, 2, 3], [5, 1, 4, 3, 6], [5, 2, 2, 3, 4], [4, 4, 6, 5, 3], [2, 4, 3, 5, 1], [5, 4, 2, 5, 3], [2, 3, 5, 5, 4], [1, 6, 3, 4, 5], [4, 5, 3, 3, 6], [6, 4, 3, 6, 5], [4, 6, 6, 5, 3], [4, 3, 5, 2, 2], [2, 3, 2, 1, 4], [4, 2, 6, 1, 3], [4, 4, 5, 3, 6], [4, 5, 6, 3, 6]]

fa = [[1, 2, 3, 5, 6], [5, 1, 1, 6, 6], [4, 6, 4, 1, 1], [6, 4, 1, 6, 4], [4, 6, 3, 6, 6], [2, 1, 4, 6, 4], [2, 6, 1, 5, 6], [2, 6, 1, 5, 6], [3, 6, 5, 3, 2], [3, 2, 3, 5, 3], [5, 5, 6, 2, 3], [3, 4, 6, 4, 3], [1, 4, 5, 5, 1], [1, 4, 4, 4, 1], [1, 6, 5, 1, 4], [6, 6, 4, 5, 4], [5, 3, 3, 3, 2], [5, 2, 1, 5, 3], [3, 5, 1, 6, 2], [6, 4, 2, 1, 2], [1, 3, 1, 3, 2], [3, 1, 3, 4, 3], [4, 3, 1, 6, 3], [4, 6, 3, 3, 6], [3, 6, 3, 6, 4], [1, 1, 3, 1, 3], [5, 5, 1, 3, 2], [3, 4, 2, 6, 6], [5, 4, 2, 6, 1], [2, 4, 4, 5, 4], [3, 6, 2, 5, 5], [2, 5, 3, 5, 1], [3, 2, 2, 3, 4], [5, 2, 2, 6, 2], [5, 6, 2, 5, 6]]

f=q=>q.sort().map(o=>(o-s?o-s<2?t++:t=t>3?t:1:0,s=o),t=1,s=-1)|t>3


tr.map(f)   //just look to make sure every value is true
fa.map(f)  //just look to make sure every value is false
\$\endgroup\$
2
  • 1
    \$\begingroup\$ I believe the parentheses can be removed from t=(t>4)?t:1. \$\endgroup\$ Mar 7, 2016 at 20:30
  • \$\begingroup\$ Here's a couple more minor improvements: q=>q.sort().map(o=>(o-s?o-s<2?t++:t=t>4?t:1:0,s=o),t=1,s=9)|t>3 This version returns 1 for truthy and 0 for falsy. \$\endgroup\$ Mar 7, 2016 at 20:38
3
\$\begingroup\$

C#, 156 151 150 131 121 93 92 90 bytes

int l;bool f(int[]a){foreach(var v in a)l|=1<<v-1;return(l&15)>14||(l&30)>29||(l&60)>59;}

or: (same number of bytes)

int l;bool f(int[]a){foreach(var v in a)l|=1<<v;return(l&30)>29||(l&60)>59||(l&120)>119;}

Ungolfed:

int l;
bool f(int[] a)
{
    foreach (var v in a)
        l |= 1 << v - 1;
    return (l & 15) > 14 ||   //Bits 1-4 are set OR
           (l & 30) > 29 ||   //Bits 2-5 are set OR
           (l & 60) > 59;     //Bits 3-6 are set
}

Big Edit: Just realized I only need to post a function, not a whole program. That saves a whole lot. No boilerplate, no need to convert string input into numbers, etc. Now we're actually approaching a respectable number of bytes (for a non-golfing language anyhow).

\$\endgroup\$
2
  • \$\begingroup\$ return bool to save 3 bytes. \$\endgroup\$ Mar 7, 2016 at 23:33
  • \$\begingroup\$ @Timbo - Yeah, I thought about that after I went home yesterday, fixed it. That was leftover from it being a full program (main in C# must return either void or int.) Unfortunately, I also gained 2 bytes because I was expecting 0-5 instead of 1-6. So net loss of 1 byte anyhow. \$\endgroup\$ Mar 8, 2016 at 14:27
3
\$\begingroup\$

TI-BASIC, 25 bytes

not(min(fPart(prod(Ans+36)/(65{703,779,287

An equivalent (ungolfed) Python expression which you can test:

def has_small_straight(l):
    product = reduce(lambda x,y: x*y, [x + 36 for x in l], 1)
    numbers = [37*19*13*5, 19*13*5*41, 13*5*41*7]
    return not(all([product%x for x in numbers]))

The idea behind this is divisibility. To check whether a 1, 2, 3, 4, 2, 3, 4, 5, or 3, 4, 5, 6 occurs, we can map the numbers 1-6 to 37-42, and then multiply the correct numbers together.

Each of the numbers in [37,42] have a prime factor that the other numbers lack.

n             |  1 |  2 |  3 |  4 |  5 |  6 |
n + 36        | 37 | 38 | 39 | 40 | 41 | 42 |
Factor        | 37 | 19 | 13 |  5 | 41 |  7 |

Therefore, if the product of the five numbers is divisible by 37, the original list contained a 1. If by 19, it contained a 2; etc. If it is divisible by 37*19*13*5 = 65*703, it contains 1, 2, 3, and 4 and similarly for the other two numbers.

This solution is an improvement on one that @Weregoose posted in 2009.

\$\endgroup\$
1
  • \$\begingroup\$ This is brilliant! \$\endgroup\$ Mar 10, 2016 at 17:58
3
\$\begingroup\$

Ruby - 80 -> 79 -> 76 -> 54 -> 48 -> 40 bytes

Fifth Try (40 bytes):

->x{/1234|2345|3456/===x.uniq.sort.join}

Uses lambda syntax to define the function. (Thanks to competing Ruby golfer @Sherlock9 for this idea.)

To test using lambda call:

s = ->x{/1234|2345|3456/===x.uniq.sort.join}
s.call([1,3,5,4,4])
s.call([1,3,5,4,2])

Fourth Try:

def s?(x)/1234|2345|3456/===x.uniq.sort.join end

Replaced nil? and negation with === operator.

Third Try:

def s?(x)!(/1234|2345|3456/=~x.uniq.sort.join).nil?end

Uses regular expression.

Second Try:

def s?(x)[1234,2345,3456].select{|a|x.uniq.sort.join.include?a.to_s}.any?end

New approach uses dedup (uniq), sort and join, plus include? to search for a match of any solutions in the input rendered as a string.

First Try: 79 bytes

def s?(x)[[1,2,3,4],[2,3,4,5],[3,4,5,6]].select{|a|(a&x.uniq).length>3}.any?end

Tester:

x = [1,4,3,3,6]
s?(x)

x = [2,4,5,1,3]
s?(x)

Uses deduping (uniq function) plus set intersection (& operator) to test if any of the good sequences matches the given sequence. No sorting needed.

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

Dyalog APL, 15 bytes

{∨/∧/⍵∊⍨⍵∘.+⍳4}

uses ⎕IO=0

⍳4 is 0 1 2 3

⍵∘.+⍳4 is 5×4 a matrix of each die incremented by each of ⍳4

⍵∊⍨ checks if the elements of the matrix are in the hand, result is a boolean (0-or-1) matrix, we need to find a row of all 1s

∧/ is the and-reduction by rows, result is a boolean vector

∨/ is the or-reduction of that vector

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

PHP, 95 bytes

function s($d){$a=array_diff;$r=range;return!($a($r(1,4),$d)&&$a($r(2,5),$d)&&$a($r(3,6),$d));}
Exploded view
function s($d){
  $a = array_diff;
  $r = range;
  return !($a($r(1,4),$d)
        && $a($r(2,5),$d)
        && $a($r(3,6),$d));
}
Input / function call
s(Array[int, int, int, int, int]);
Output
bool
\$\endgroup\$
2
\$\begingroup\$

Seriously, 21 bytes

3R`;4+@x`M4,╨╗`╜íu`MΣ

Try it online!

Outputs a positive value for true, and a 0 for false.

Explanation:

3R`;4+@x`M4,╨╗`╜íu`MΣ
3R`;4+@x`M             push [[1,2,3,4], [2,3,4,5], [3,4,5,6]
          4,╨╗         push all 4-length permutations of input to register 0
              `   `M   map:
               ╜íu       push 1-based index of list in permutations, 0 if not found
                    Σ  sum
\$\endgroup\$
0
2
\$\begingroup\$

PARI/GP, 71 bytes

This can probably be golfed further, but as a start:

s=setminus;v->t=s([1..6],Set(v));!#s(t,[1,2])+!#s(t,[5,6])+!#s(t,[1,6])

I don't see a way of reducing duplication without using more space; this version is 75 bytes:

s=setminus;v->t=s([1..6],Set(v));z=(u->!#s(t,u));z([1,2])+z([5,6])+z([1,6])
\$\endgroup\$
2
\$\begingroup\$

Retina, 70 54 bytes

Input is a single string of the integers like 13342. Output is a 1 if found, or a 0 if not.

.                       # Replace integer digits with unary
$*x,
+`(x+(x+,))\2           # Sorts the list by repeated swapping
$2$1
(x+,)\1                 # Removes adjacent duplicates
$1
(x+,)x\1xx\1xxx\1       # Matches a small straight

Note that the removal of duplicates only needs to occur once, since there are only five numbers. Needing to remove more than one number would mean there isn't a small straight anyway.

Try it online

Thanks to Martin for the idea to move the commas inside the capture groups, saving a whopping 16 bytes.

\$\endgroup\$
3
  • \$\begingroup\$ How does it work? \$\endgroup\$ Mar 7, 2016 at 21:37
  • \$\begingroup\$ . $*x Replace numbers with n x's, where n is the number. +` Repeat the following until the string stabilizes (x+(x+,))\2 $2$1 Replace n*xm*x,m*x, with m*x,n*xm*x (x+,)\1 $1 Replace x*n,x*n, with x*n, (x+,)x\1xx\1xxx\1 Match n*x,xn*x,xxn*x,xxxn*x Updated \$\endgroup\$ Mar 7, 2016 at 22:25
  • \$\begingroup\$ @CatsAreFluffy I'm not using that as a description. Just an FYI. Anyone who's ever read the Retina github page once over should get that. Comments about what is being accomplished (like sorting, removing duplicates) are more important than describing that each is a replacement. \$\endgroup\$
    – mbomb007
    Mar 7, 2016 at 22:28
2
\$\begingroup\$

Pyth, 11 bytes

f!-TQ.:S6 4

Test suite

Generate the length 4 substrings of [1..6], then filter them on no elements remaining when the elements of the input are removed.

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

Jelly, 9 bytes

There has to be an 8-byte solution, will continue searching... Code:

Œ!Ḋ€Iµ7Be

This is the same as my 05AB1E solution.

Explanation:

Œ!         # Compute all permutations
  Ḋ€       # Dequeue each, leaving [1:]
    I      # Delta function
     µ     # Start a new monadic chain
      7B   # 7 in binary, which is [1, 1, 1]
        e  # Return 1 if this array exists

Try it online!

\$\endgroup\$
2
  • \$\begingroup\$ Another, alternative 9: Œ!I=1ZS3e... \$\endgroup\$ Mar 7, 2016 at 19:50
  • \$\begingroup\$ Doesn't work for [1, 2, 1, 2, 1], and neither does your other answer unfortunately. My alternative seems to work (but I've been wrong before... test it too :) ), feel free to use that. \$\endgroup\$ Mar 7, 2016 at 21:46
2
\$\begingroup\$

Jelly, 8 bytes

6Rṡ4ḟ€ċ“

Try it online! or verify the truthy test cases and the falsy test cases.

How it works

6Rṡ4ḟ€ċ“  Main link. Argument: A (list)

6R        Yield [1, 2, 3, 4, 5, 6].
  ṡ4      Split it into overlapping slices of length 4, yielding
          [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]].
    ḟ€    Remove all occurrences of A's elements from each slice.
      ċ“  Count the resulting number of empty list.
          This returns the number of distinct small straights in A (0, 1 or 2).
\$\endgroup\$
2
\$\begingroup\$

Scala, 76 70 61 60 bytes

(s:Seq[Int])=>(1 to 6)sliding(4)exists(t=>(s diff t).size<2)

Tester:

val f = <code here>
val truthy = Seq(Seq(1, 2, 3, 3, 4), Seq(1, 2, 3, 4, 5), Seq(3, 5, 6, 1, 4), Seq(1, 5, 3, 4, 6), Seq(4, 5, 2, 3, 5), Seq(1, 4, 3, 2, 2), Seq(5, 4, 3, 6, 3), Seq(5, 3, 5, 4, 6), Seq(2, 4, 5, 1, 3), Seq(3, 6, 4, 5, 3), Seq(5, 6, 4, 3, 5), Seq(4, 5, 3, 6, 3), Seq(4, 5, 5, 3, 2), Seq(4, 5, 2, 3, 5), Seq(4, 6, 5, 3, 6), Seq(4, 2, 3, 1, 5), Seq(3, 6, 4, 6, 5), Seq(5, 2, 1, 3, 4), Seq(4, 4, 1, 2, 3), Seq(4, 1, 4, 2, 3), Seq(5, 1, 4, 3, 6), Seq(5, 2, 2, 3, 4), Seq(4, 4, 6, 5, 3), Seq(2, 4, 3, 5, 1), Seq(5, 4, 2, 5, 3), Seq(2, 3, 5, 5, 4), Seq(1, 6, 3, 4, 5), Seq(4, 5, 3, 3, 6), Seq(6, 4, 3, 6, 5), Seq(4, 6, 6, 5, 3), Seq(4, 3, 5, 2, 2), Seq(2, 3, 2, 1, 4), Seq(4, 2, 6, 1, 3), Seq(4, 4, 5, 3, 6), Seq(4, 5, 6, 3, 6))
val falsy = Seq(Seq(1, 2, 3, 5, 6), Seq(5, 1, 1, 6, 6), Seq(4, 6, 4, 1, 1), Seq(6, 4, 1, 6, 4), Seq(4, 6, 3, 6, 6), Seq(2, 1, 4, 6, 4), Seq(2, 6, 1, 5, 6), Seq(2, 6, 1, 5, 6), Seq(3, 6, 5, 3, 2), Seq(3, 2, 3, 5, 3), Seq(5, 5, 6, 2, 3), Seq(3, 4, 6, 4, 3), Seq(1, 4, 5, 5, 1), Seq(1, 4, 4, 4, 1), Seq(1, 6, 5, 1, 4), Seq(6, 6, 4, 5, 4), Seq(5, 3, 3, 3, 2), Seq(5, 2, 1, 5, 3), Seq(3, 5, 1, 6, 2), Seq(6, 4, 2, 1, 2), Seq(1, 3, 1, 3, 2), Seq(3, 1, 3, 4, 3), Seq(4, 3, 1, 6, 3), Seq(4, 6, 3, 3, 6), Seq(3, 6, 3, 6, 4), Seq(1, 1, 3, 1, 3), Seq(5, 5, 1, 3, 2), Seq(3, 4, 2, 6, 6), Seq(5, 4, 2, 6, 1), Seq(2, 4, 4, 5, 4), Seq(3, 6, 2, 5, 5), Seq(2, 5, 3, 5, 1), Seq(3, 2, 2, 3, 4), Seq(5, 2, 2, 6, 2), Seq(5, 6, 2, 5, 6))
println("Failed truthy: " + truthy.filterNot(f))
println("Failed falsy: " + falsy.filter(f))
\$\endgroup\$
2
\$\begingroup\$

Javascript ES6 43 bytes

q=>/1,1,1,1/.test(q.map(a=>l[a]=1,l=[])&&l)


//couldn't quite get this to work :/

q=>q.map(a=>l&=~(1<<a),l=62)&&l<7||l==32

This takes the number 62 (111110 in binary) For each number in the input array it removes that bit

The resulting number should either be

100000 or
000000 or
000010 or
000110 or
000100

so I check if the result is less than 7 (0000111) or if it's equal to 32 (100000)

\$\endgroup\$
2
  • \$\begingroup\$ Couldn't it be 34, with a list like 2,3,4,5,2? \$\endgroup\$
    – lirtosiast
    Mar 8, 2016 at 16:39
  • \$\begingroup\$ That still doesn't change the fact this doesn't work for [3, 4, 5, 4, 3]. I think you need to use 126 instead of 62... \$\endgroup\$
    – Sp3000
    Mar 8, 2016 at 16:46
2
\$\begingroup\$

Mumps, 113 78 Bytes

The version of Mumps I'm using is InterSystems Cache.

I can't think of a way of golfing this technique any shorter; with a different technique it might be possible, but for now this'll do and at least it's shorter than C++... but not by much. Anyway...

OK, here's a shorter way. Instead of having 3 separate variables for the short runs, use a single variable for all 6 'dice' and extract the portions later:

R R S Y=111111 F F=1:1:5{S $E(Y,$E(R,F))=0} W '$E(Y,1,4)!'$E(Y,2,5)!'$E(Y,3,6)

so much for me not finding a better way with the same technique... I should look before I leap, eh? ;-)

I'll leave my original answer below for historical purposes...



R R S (G,H,I)=1111 F F=1:1:5{S Q=$E(R,F) S:1234[Q $E(G,Q)=0 S:2345[Q $E(H,Q-1)=0 S:3456[Q $E(I,Q-2)=0} W 'G!'H!'I

and here's the explanation of what's going on with the code:

R R                   ; read from STDIN to variable R
S (G,H,I)=1111        ; set our 3 possible short straights
F F=1:1:5{            ; For loop from 1 to 5
S Q=$E(R,F)           ; get each digit from the input and save in Q
S:1234[Q $E(G,Q)=0    ; If Q is either 1,2,3 or 4, zero out that position in G.
S:2345[Q $E(H,Q-1)=0  ; if Q is either 2,3,4 or 5, zero out that position (-1) in H.
S:3456[Q $E(I,Q-2)=0  ; if Q is either 3,4,5 or 6, zero out that position (-2) in I.
}                     ; and end the loop.
W 'G!'H!'I            ; If G,H, or I are all zeroes (indicating a full straight),
                      ; taking the not of each will make (at least one) of the
                      ; values true. OR-ing all three values will let us know if
                      ; at least one short straight was complete.
                      ; Output is 1 for truthy, 0 for falsy.

I didn't test every single truthy & falsy input as that involved manually typing them all in; but I did test approximately the first half of each, verified the long straights still show truthy and several of the runs noted to not necessarily work correctly ([4,2,5,3,4], [1,2,3,3,4] etc.) and seems to be working correctly.

\$\endgroup\$
1
\$\begingroup\$

Jelly, 11

QṢṡ4ðfø6Rṡ4

Try it online!

This is pretty much a copy of my Pyth answer, just trying to figure out how to chain stuff. Feels like it should be golfable.

Expansion:

QṢṡ4ðfø6Rṡ4  ##  1, 2, 0 chain, 1 argument from command line
QṢṡ4         ##  first chain, uniQue and Sort the input, then
             ##  get overlapping lists of length 4 (ṡ)
    ð        ##  separator
     f       ##  filter left argument on being a member of right argument
      ø      ##  separator
       6Rṡ4  ##  all overlapping lists of length 4, from 1-indexed range of 6
             ##  generates [1,2,3,4],[2,3,4,5],[3,4,5,6]

If you want to ask any hard questions, like why the separators are different, then my answer to you is: "I'll answer in 6-8 weeks" :P (More seriously, I think it's the pattern matching, monad-dyad vs nilad-dyad, but I don't know and don't want to spread misinformation.)

\$\endgroup\$
3
  • \$\begingroup\$ Explanation:Q Unique elements Ṣ sort the list ṡ4 all slices of length 4 ðf filter by { 6R range form 1 to 6 ṡ4 all slices of length 4 from that \$\endgroup\$ Mar 7, 2016 at 19:21
  • \$\begingroup\$ For some reason Q is with the uppercase overdot operators in the documentation. Maybe it was an overdot once? \$\endgroup\$ Mar 7, 2016 at 19:23
  • \$\begingroup\$ @CatsAreFluffy I have no idea, I used the one from the code page in the atoms page. \$\endgroup\$ Mar 7, 2016 at 19:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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