I did it with only one For Loop

I’m not sure why there was need to use two For loops when you can iterate through each character in both words with one For Loop as I did here. If you only use one For Loop and one Index iterator, obviously you’ll be in the same place always. The only bug left to fix is if the user enters a string longer than the hidden word but I’m sure that logic will be implemented later in the course anyway.

You need to do a nested for loop because you need to compare each letter with every other letter. With only one loop you’re comparing letters in the same position so you’re only ever going to be counting for bulls. For instance say the hidden word is “ten” and the guess is “net” (for simplicity I’ll use i and j for the loop variables)

With your one loop:
i = 0
t e n == n e t
i = 1
t e n == n e t
i = 2
t e n == n e t

Result = 1 Bull 0 Cows

Now with a nested for loop:
i = 0, j = 0
t e n == n e t
i = 0, j = 1
t e n == n e t
i = 0, j = 2
t e n == n e t - Same letter different positions +1 Cow

i = 1, j = 0
t e n == n e t
i = 1, j = 1
t e n == n e t - Same letter and position +1 Bull

Result = 1 Bull, 2 Cows

1 Like

First note: My loop would actually give 2 cows and 1 bull as well. I set it to give cows any time the characters do not match.

With that said, did I misunderstand the game rules? I thought you received cows on any wrong character. But what you’re saying is, you get cows when you guess the correct character but in the wrong place.

Yes, cows are for right character wrong position.


Privacy & Terms