开发者

sorting cards with wildcards

开发者 https://www.devze.com 2023-03-07 21:29 出处:网络
i am programming a card game and i need to sort a stack of cards by their rank. so that they form a gapless sequence.

i am programming a card game and i need to sort a stack of cards by their rank. so that they form a gapless sequence. in this special game the card with value 2 could be used as a wild card, so for example the cards

 2 3 5 

should be sorted like this

 3 2 5

because the 2 replaces the 4, otherwise it would not be a valid sequence.

however the cards

2 3 4

should stay like they are.

restriction: there an be only one '2' used as a wildcard.

2 2 3 4

would also stay like it is, because the first 2 would replace the ACE (or 1, whatever you call it).

the following would not be a开发者_运维问答 valid input sequence, since one of the 2s must be use as a wildcard and one not. it is not possible to make up a gapless sequence then.

2 4 2 6

now i have a difficulty to figure out if a 2 is used as a wildcard or not. once i got that, i think i can do the rest of the sorting

thanks for any algorithmic help on this problem!


EDIT in response to your clarification to your new requirement:
You're implying that you'll never get data for which a gapless sequence cannot be formed. (If only I could have such guarantees in the real world.) So:

  • Do you have a 2?
    • No: your sequence must already be gapless.
    • Yes: You need to figure out where to put it.
  • Sort your input. Do you see a gap? Since you can only use one 2 as a wildcard, there can be at most one gap.
    • No: treat the 2 as a legitimate number two.
    • Yes: move the 2 to the gap to fill it in.

EDIT in response to your new requirement:
In this case, just look for the highest single gap, and plug it with a 2 if you have a 2 available.

Original answer:
Since your sequence must be gapless, you could count the number of 2s you have and the sizes of all the gaps that are present. Then just fill in the highest gap for which you have a sufficient number of 2s.

0

精彩评论

暂无评论...
验证码 换一张
取 消