# Week8

{% file src="https://1730460162-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fwc27wmKfnoDuqA5F9f2t%2Fuploads%2Fg9b3HE7uOBRN6n7HSiJQ%2FTB_FRQQuiz330_6424fc4bd27a11.6424fc4cbd9808.82203026.pdf?alt=media&token=c6d5ed30-eeb6-4475-b747-ed2fddc1cd4a" %}

### 1.a: numberOfLeapYears

```java
public static int numberOfLeapYears(int year1, int year2)
{
    int leapYears = 0;
    for(int y = year1; y <= year2; y++)
        if(isLeapYear(y))
            leapYears++;
    return leapYears;
}
```

### 1.b: dayOfWeek

```java
public static int dayOfWeek(int month, int day, int year)
{
    int additionalDays = dayOfYear(month, day, year) - 1;
    return (firstDayOfYear(year) + additionalDays) % 7;
}
```

### 2.a: scoreGuess

```java
//第一种解法
public int scoreGuess(String guess)
{
    int count = 0;
    for(int i = 0; i < secret.length(); i++)
    {
        int j = i + guess.length();
        if(j <= secret.length() && secret.substring(i, j).equals(guess))
            count++;
    }
    return count * (guess.length() * guess.length());
}
```

<pre class="language-java"><code class="lang-java"><strong>//第二种解法
</strong><strong>public int scoreGuess(String guess)
</strong>{
    int count = 0;
    for(int i = 0; i &#x3C;= secret.length()-guess.length(); i++)
    {
        int j = i + guess.length();
        if(secret.substring(i, j).equals(guess))
            count++;
    }
    return count * (guess.length() * guess.length());
}
</code></pre>

<pre class="language-java"><code class="lang-java"><strong>//第三种解法：按照默写的思路(countSpaces)
</strong>public int scoreGuess(String guess)
{
    String x = secret;
    int count = 0;
    while(x.indexOf(guess)!=-1)){
        x = x.substring(x.indexOf(guess)+1);
        count++;
    }
    return count * (guess.length() * guess.length());
}
</code></pre>

### 2.b: findBetterGuess

```java
public String findBetterGuess(String guess1, String guess2)
{
    int score1 = scoreGuess(guess1);
    int score2 = scoreGuess(guess2);

    if(score1 > score2)
        return guess1;
    else if(score2 > score1)
        return guess2;
    else
    {
        if(guess1.compareTo(guess2) > 0)
            return guess1;
        else
            return guess2;
    }
}
```

