不使用linq比较数组

时间:2018-09-10 01:20:40

标签: c# arrays contains

我正在制作一个彩票游戏,要求用户输入10个数字,然后将其与我在数组中创建的随机数字进行比较。我需要将两者进行比较,但不允许使用contains方法。

我认为我需要使用一个foreach循环来比较数组,但实际上我无所适从。我一直在与我所知不多的人联系在一起,并想知道我是否走上了正确的道路。

foreach循环是比较两个数组的正确方法吗?

到目前为止,这是我的代码。

using System;

namespace lotto2
{
class Program
{
    static void Main(string[] args)
    {

        //an array named "input" to hold the users' 10 guesses
        int[] inputs = new int[10];

        //an array named "lotNum" to hold 10 random numbers
        int[] lotNums = new int[10];

        //a for loop to loop over the inputs array. each loop will ask the user for a number
        Console.WriteLine("Enter your 10 lottery numbers one at a time. The numbers must be between 1 and 25.");
        for (int i = 0; i < inputs.Length; i++)
        {
            inputs[i] = Convert.ToInt32(Console.ReadLine());
        }

        //a random number generator  
        Random ranNum = new Random();

        //loop to call the random generator 10 times and store 10 random numbers in the "lotNum" array
        for (int i = 0; i < 10; i++)
        {
            lotNums[i] = ranNum.Next(1, 26); //chooses random numbers between 1 and 25
        }

        //writes out the randomly generated lotto numbers
        Console.Write("\nThe lottery numbers are: ");
        for (int i = 0; i < 10; i++)
        {
            Console.Write("{0}  ", lotNums[i]);
        }

        //loop for checking users inputs against random generated numbers..
        //foreach loop maybe?
        foreach (var input in lotNums)
        {
        }

        //print out if there are any matches, which numbers matched

        //declared integer for the correct numbers the user guessed
        int correct;

        //end progam
        Console.WriteLine("\n\nPress any key to end the program:");
        Console.ReadKey();
    }
}

}

4 个答案:

答案 0 :(得分:1)

这是一个可以正确执行您想要的程序。它甚至可以确保您没有重复的乐透号码。

void Main()
{
    const int count = 10;
    const int max = 25;

    //an array named "input" to hold the users' 10 guesses
    int[] inputs = new int[count];

    //a for loop to loop over the inputs array. each loop will ask the user for a number
    Console.WriteLine("Enter your {0} lottery numbers one at a time. The numbers must be between 1 and {1}.", count, max);
    for (int i = 0; i < inputs.Length; i++)
    {
        inputs[i] = Convert.ToInt32(Console.ReadLine());
    }

    //a random number generator  
    Random ranNum = new Random();

    //an array named "allNums" to hold all the random numbers
    int[] allNums = new int[max];
    for (int i = 0; i < allNums.Length; i++)
    {
        allNums[i] = i + 1;
    }

    //shuffle
    for (int i = 0; i < allNums.Length; i++)
    {
        int j = ranNum.Next(0, allNums.Length);
        int temporary = allNums[j];
        allNums[j] = allNums[i];
        allNums[i] = temporary;
    }

    //an array named "lotNum" to hold 10 random numbers
    int[] lotNums = new int[count];

    Array.Copy(allNums, lotNums, lotNums.Length);

    //writes out the randomly generated lotto numbers
    Console.Write("\nThe lottery numbers are: ");
    for (int i = 0; i < lotNums.Length; i++)
    {
        Console.Write("{0}  ", lotNums[i]);
    }

    int correct = 0;
    Console.Write("\nThe correct numbers are: ");
    for (int i = 0; i < lotNums.Length; i++)
    {
        for (int j = 0; j < inputs.Length; j++)
        {
            if (lotNums[i] == inputs[j])
            {
                Console.Write("{0}  ", lotNums[i]);
                correct++;
            };
        }
    }

    Console.Write("\nYou got {0} correct. ", correct);

    Console.WriteLine("\n\nPress any key to end the program:");
    Console.ReadLine();
}

答案 1 :(得分:0)

您的方法正确。

我的实现是:

foreach (var input in inputs)
{
    for (int i = 0; i < lotNums.Length; i++){
        if(input == lotNums[i]){
            Console.WriteLine(lotNums[i]);
        }
    }
}

这会将输入数组的每个数字与彩票数组进行比较。 我正在打印每个匹配项,但是如果找到匹配项,则可以将其设置为True,或者在需要时将每个匹配项添加到数组中。

答案 2 :(得分:0)

这是我尝试过的方法。我希望这有意义吗?

/**
 * MadLib.java  
 *
 * @author: Jackie Hirsch
 * Assignment: Madlib
 * 
 * Brief Program Description: This program has will read a madlib with 
the inputs that the user gives the computer. 
 * 
 *
 */
import javax.swing.JOptionPane; //import of JOptionPane
public class MadLib
{
    public static void main (String[] args)
    {
        String cheeseType; //Cheese Character
        String interjection; //interjection
        String treeType; //tree type
        String wholeNumberFriends; // number for number of friends on 
        //line 27
        String numberMiles; //number of miles
        int wholeNumberFriendsConverted; // number for number of 
        //friends on line 27 converted
        double numberMilesConverted; //number of miles

        //ask user for variable string cheese type
        cheeseType = JOptionPane.showInputDialog ("Enter a type of 
        cheese");
        //ask user for varaible string interjection
        interjection = JOptionPane.showInputDialog ("Enter an 
        interjection");
        //ask user for variable string tree type
        treeType = JOptionPane.showInputDialog ("Enter a type of 
        tree");
        //ask user for variable integer number for number of friends
        wholeNumberFriends = JOptionPane.showInputDialog ("Enter a 
        whole number");
        //ask user for variable double number for number of miles
        numberMiles = JOptionPane.showInputDialog ("Enter a decimal or 
        whole number");

        //string converted
        wholeNumberFriends = Integer.parseInt 
        (wholeNumberFriendsConverted);
        numberMiles = Integer.parseInt (numberMilesConverted);




        //Madlib reading printed
        JOptionPane.showMessageDialog (null, "There once was a " + 
        cheeseType + "and this " + cheeseType  + "was super exciting. " 
        +
        "Because " + cheeseType + "was so exciting he would shout, " + 
        interjection + ". " +
        "His " + wholeNumberFriendsConverted + "friends, the " + 
        treeType + ", would sing home and the whole"  +
        "neighborhood hated them. One neighboor walked outside and 
        said, " +
        "''You annoying hooligans are crazy!!!''. They were so confused 
        that" +
        "they ran away to Neverland which was " + numberMilesConverted 
        + "miles so they never" +
        "had to grow up. Then they ran into captain hook and then Peter 
        Pan saved them.");
        System.exit (0); //ends the program

    }
}

答案 3 :(得分:0)

您必须计算两个序列的交集。您有三种选择:

  • 双foreach循环。这是需要避免的事情,因为它具有时间复杂度O(m * n)。十个项目不是问题,但我们应该制作可扩展的程序。
  • 使用哈希联接。您可以为此使用HashSet,这将是我的首选方法。但是,由于它固有地暗示要使用Contains,因此此处不是该选项。
  • 合并排序的序列。这就是去这里的方式。

该程序是不言自明的,它产生并与两个随机序列相交。

static Random rnd = new Random((int)DateTime.Now.Ticks);

static int[] GetRandomArray(int arrSize, int minNumber, int maxNumber)
{
    int[] tmpArr = new int[maxNumber - minNumber + 1];
    for (int i = 0; i < tmpArr.Length; ++i)
    {
        tmpArr[i] = i + minNumber; // fill with 1, 2, 3, 4,...
    }

    int[] ret = new int[arrSize];
    for (int i = 0; i < ret.Length; ++i)
    {
        int index = rnd.Next(tmpArr.Length - i); //choose random position
        ret[i] = tmpArr[index];
        tmpArr[index] = tmpArr[tmpArr.Length - 1 - i]; //fill last of the sequence into used position
    }

    return ret;
}

static IEnumerable<int> GetMatches(int[] a, int[] b)
{
    Array.Sort(a);
    Array.Sort(b);

    for (int i = 0, j = 0; i < a.Length && j < b.Length;)
    {
        if (a[i] == b[j])
        {
            yield return a[i];
            ++i;
            ++j;
        }
        else if (a[i] > b[j])
        {
            ++j;
        }
        else
        {
            ++i;
        }
    }
}

static void Main(string[] args)
{
    var a = GetRandomArray(5, 3, 7);
    var b = GetRandomArray(10, 1, 25);

    Console.WriteLine("A: " + string.Join(", ", a));
    Console.WriteLine("B: " + string.Join(", ", b));
    Console.WriteLine("Matches: " + string.Join(", ", GetMatches(a, b)));
    Console.ReadKey();
}

结果类似于:

A: 7, 4, 6, 3, 5
B: 17, 1, 8, 14, 11, 22, 3, 20, 4, 25
Matches: 3, 4

您可以考虑如果两个序列中的一个或两个都包含重复,将会发生什么情况。