I'm stuck with arrays and need some help.
I have two arrays and I'm comparing it using foreach loop. I want the program to write "you won" ONLY if there are two numbers in winningNumbers
that matches with someNumbers
. If there is only one match, the output should be "You lost"
(I have to use loops to solve this problem)
int[] someNumbers = { 1, 2, 3, 4, 5, 6 };
int[] winningNumbers = { 1, 2, 13, 14, 15, 16 };
bool winning = false;
foreach (var item1 in someNumbers)
{
foreach (var item2 in winningNumbers)
{
if (item1 == item2)
{
winning = true;
}
}
}
if (winning == true )
{
Console.WriteLine("You won");
}
else
{
Console.WriteLine("You lost");
}
Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.
Programmers who wish to compare the contents of two arrays must use the static two-argument Arrays. equals() method. This method considers two arrays equivalent if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equivalent, according to Object. equals() .
The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.
Java provides a direct method Arrays. equals() to compare two arrays. Actually, there is a list of equals() methods in the Arrays class for different primitive types (int, char, ..etc) and one for Object type (which is the base of all classes in Java).
Use a counter for each match. If it's >= 2 then it reports a win. If you require it to be exactly two matches, remove the > operator. Try it here: https://dotnetfiddle.net/sjYbYk
edit: stringbuilder added to report winning matches.
using System;
using System.Text;
public class Program
{
public static void Main()
{
int[] someNumbers = { 1, 2, 3, 4, 5, 6 };
int[] winningNumbers = { 1, 2, 13, 14, 15, 16 };
int matched = 0;
StringBuilder sb = new StringBuilder();
sb.Append("You Matched ");
foreach (var item1 in someNumbers)
{
foreach (var item2 in winningNumbers)
{
if (item1 == item2)
{
matched++;
sb.Append(item1 + ",");
}
}
}
if (matched >= 2 )
{
Console.WriteLine("You won");
Console.WriteLine(sb.ToString().TrimEnd(','));
}
else
{
Console.WriteLine("You lost");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With