计算最长的头部连胜

时间:2017-03-21 15:02:37

标签: java

我已经坚持了几个星期,我不知道该怎么做。我只想要最长的连胜。我已经尝试了无数次,我只是不知道我做错了什么。

public class LongestStreak extends ConsoleProgram
{
public static final int FLIPS = 100;
int currentRun;
int runStart;
int maxRun;

public void run()
{
double heads = 0;
double tails = 0;
    for(int i = 0; i < FLIPS; i++)
        {
        if(Randomizer.nextBoolean())
        {
            System.out.println("Heads");
            heads++;
            currentRun++; // use ++ in preference to +=1, and this should be before maxRun test
            if (maxRun < currentRun) {
                maxRun = currentRun;
                runStart = currentRun - i; // this will produce a 1-based position
            } else {
            currentRun = 0;
            }
        }
        else
        {
            System.out.println("Tails");
            tails++;
        }
    }
    System.out.println(FLIPS);
}

}

2 个答案:

答案 0 :(得分:0)

我不确定我是否理解你的问题,但在这里我有一个解决方案,它将为你打印100 FLIPS中最长的连胜

public static void run() {
    Random r = new Random();
    double heads = 0;
    double tails = 0;
    for (int i = 0; i < FLIPS; i++) {
        if (r.nextBoolean()) {
            System.out.println("Heads");
            heads++;
            currentRun++;
            if (maxRun < currentRun) {
                maxRun = currentRun;
                runStart = currentRun - i;
            }
        } else {
            System.out.println("Tails");
            tails++;
            currentRun = 0;
        }
    }
    System.out.println(FLIPS);
    System.out.println(maxRun);
}

答案 1 :(得分:0)

public class LongestStreak extends ConsoleProgram
{
    public static final int FLIPS = 100;


    public void run()
    {

        int consecutiveHeads = 0;
        int maxRun = 0;

        for(int i = 0; i < FLIPS; i++)
        {
            if(Randomizer.nextBoolean())
            {
                System.out.println("Heads");
                consecutiveHeads++;
                    if(maxRun <  consecutiveHeads)
                    {
                         maxRun = consecutiveHeads;
                    }


            }
            else
            {
                System.out.println("Tails");
                consecutiveHeads = 0;
            }
        }

                        System.out.println("Longest streak of heads: " + maxRun);
    }
}