Algorithm to find the optimal number of style sets in the style of a glass?

I am developing a card game that uses three sets of blush style cards. From a random selection of cards, I need an algorithm to choose which cards will get me the most sets.

By “Rummy Style Sets of Three,” I mean:

  • All three cards have the same value, for example three jacks. OR
  • All three cards are of the same suit and consecutive in order, like 7, 8, 9 of all diamonds.

For example, given the cards: 6D, 7D, 7C, 7H, 8D, 8C, 9C, 10H
I could form a set: {7D, 7C, 7H}, but this would be the only set that I would choose from it, and this It would not be optimal.
The optimal sets in this case are: {{6D, 7D, 8D}, {7C, 8C, 9C}}

I tried brute force (rearranging through all the map data, see what is in order in this rearrangement), but it turned out to be too slow. The problem is that it has similarities with other problems being solved, and why I ask here.

+3
source share
3 answers

if you have N cards (N = 8), you can list all even triples at a given time N * (N - 1) * (N - 2) (with N = 8 you get 336). This is pretty fast. Check which of these tees are “rummy style” type sets and save them in the table as whole triples (an integer denotes the serial numbers of the cards).

. - . - . ('i') . "i- ", + 1 ; , "i- , + 1 . , .

:

: 6D, 7D, 7C, 7H, 8D, 8C, 9C, 10H

:

Cards        Index triple
6D 7D 8D     <0, 1, 4>
7D 7C 7H     <1, 2, 3>
7C 8C 9C     <2, 5, 6>

:

Decide on <0, 1, 4>:
  <0, 1, 4> INCLUDED:
     <1, 2, 3> CLASHES with <0, 1, 4>
     Decide on <2, 5, 6>:
       <2, 5, 6> INCLUDED:
          Solution with 2 sets (* BEST SOLUTION)
       <2, 5, 6> EXCLUDED:
          Solution with 1 sets
  <0, 1, 4> EXCLUDED:
     Decide on <1, 2, 3>:
        <1, 2, 3> INCLUDED:
           <2, 5, 6> CLASHES with <1, 2, 3>
           Solution with 1 sets
        <1, 2, 3> EXCLUDED:
           Decide on <2, 5, 6>:
             <2, 5, 6> INCLUDED:
                Solution with 1 set
             <2, 5, 6> EXCLUDED:
                Solution with 0 sets

( ).

. !

+5

, , , (.. ). , , , , ( ). ( , , , , ) , .

+1

, 2 :

1. sort cards first ascending by number, then by suit, as you did
   in your example and look what triples you can get
2. now sort a second time, but first by suit and then by number 
   and look what triples you can get

In step 1) you can just look sequencially for 3 same numbers => O(n)
In step 2) the same, but now looking for 3 sequential numbers of the same suit. => O(n)

Merging the two results gives you all the possible triples. If I am not mistaken, at the moment you have reached the NP-hard problem of the maximum installed packaging , since you want to get the maximum subset of non-overlapping triples. Since the number of cards is limited and not so high, you can use, for example, the backtracking algorithm mentioned by antti.huima to solve this problem.

+1
source

Source: https://habr.com/ru/post/1703122/