扑克牌的顺子

从扑克牌中随机抽5张牌,判断是不是一个顺子,即这五张牌是不是连续的,2~10为数字本身,A为1,J为11,Q为12,K为13,而大小王可以看成任意数字。

把5张牌看成一个数组,就看排序后的数组是不是连续的,大小王看成特殊的数字,例如定义为0,与其他数字区分开,0的作用就是补充其他数字间不连续的空缺。

步骤:1、将数组排序;2、统计0的个数;3、统计排序后的数组中相邻数字之间的空缺总数,如果空缺总数小于0的个数,那么该数组不连续,如果空缺总数小于或等于0的个数,那么该数组连续。

注意:如果非0数组重复出现,那么该数组也不是连续的,即扑克牌中出现了对子,不可能是顺子。

#include <iostream>
#include <stdlib.h>
using namespace std;

int compare(const void *arg1,const void *arg2)
{
    return *(int*)arg1-*(int*)arg2;
}
bool iscontinous(int *numbers,int length)
{
    if(numbers==NULL||length<1)
        return false;
    qsort(numbers,length,sizeof(int),compare);
    int zero=0,gap=0;
    for(int i=0;i<length;i++)
        if(numbers[i]==0)
            zero++;
    int low=zero,high=low+1;//不需要从头开始
    while(high<length)
    {
        if(numbers[low]==numbers[high])
            return false;
        gap+=numbers[high]-numbers[low]-1;
        low++;high++;
    }
    return gap<=zero?true:false;
}


int main()
{
    int data[]={4,3,0,5,0};
    cout<<iscontinous(data,5);
}
原文地址:https://www.cnblogs.com/home123/p/7240455.html