简体   繁体   English

使用用户输入搜索数组

[英]Searching an array with user-input

There's a problem I have trouble solving.有一个问题我无法解决。 Shortly written, here's how it goes:写得很短,这是它的过程:

There are N professors at a school, born in a certain year and you need to find the amount of years the professors share (if two professors share a year, it's one year which is repeated).一所学校有N位教授,出生于某一年,你需要找到教授共享的年数(如果两个教授共享一年,则为一年,重复)。

Example: Input: (first line) 3 (second line) 1975 1960 1975 Output: (third line) 1示例:输入:(第一行)3(第二行)1975 1960 1975 输出:(第三行)1

I've started somehow, and I have only managed to create the input:我以某种方式开始了,我只设法创建了输入:

int N;
cin >> N;
int array[N];

for (int i = 0; i < N; i++) {
     cin >> array[i];
}

Now, I don't know how to continue, or use the information (years) the user has entered.现在,我不知道如何继续,或使用用户输入的信息(年)。

Edit: Although there might be better ways of solving this, I am just looking for a simple solution , or a code explaining how I can continue this program.编辑:虽然可能有更好的方法来解决这个问题,但我只是在寻找一个简单的解决方案,或者一个解释我如何继续这个程序的代码。

Edit: It should display the amount of years which repeat.编辑:它应该显示重复的年数。

In your program above, you were able to have the user input how many years they are entering as well as the years you are comparing.在上面的程序中,您可以让用户输入他们输入的年份以及您比较的年份。 Now to get the output, you should use for loops to iterate through the array and compare the years.现在要获得输出,您应该使用 for 循环遍历数组并比较年份。

For example: User entered: 1975 1960 1975 In your code this will be stored as: array[0] = 1975, array[1] = 1960, array[2] = 1975.例如:用户输入:1975 1960 1975 在您的代码中,这将存储为:array[0] = 1975, array[1] = 1960, array[2] = 1975。

One option I would suggest would be: Iterate through the array and count the number of duplicates.我建议的一种选择是:遍历数组并计算重复的数量。 If we find a higher count, then set that as the highest number of duplicates.如果我们找到更高的计数,则将其设置为最高的重复数。 Example: Read in 1975 and compare with each element if there are duplicates.示例:阅读 1975 年,如果有重复,则与每个元素进行比较。 If we find a duplicate, then increase the counter.如果我们发现重复,则增加计数器。 If the counter is greater than the highest count, then that becomes the highest count.如果计数器大于最高计数,则它成为最高计数。 Repeat this process for the entire array.对整个阵列重复此过程。

Program:程序:

int N;
cin >> N;
int A[N];
int highest_count = 0;
for (int i = 0; i < N; i++) {
    cin >> A[i];
}
for (int i = 0; i < N; i++) {
    int counter = 0;
    for (int j = i; j < N; j++) {
        if (A[i] == A[j] {
            counter++;
        }
        if (counter > highest_count) {
            highest_count = counter;
        }
    }
}
cout << highest_count;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM