common elements about two array c++

Pages: 12
Excuse me whay if I use srand te reults is not good, for example I have 4 4 1 , so the number 4 is repeated two times not only one...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>

using namespace std;
int main(){

	int num1[5];
	int num2[5];
	srand(time(NULL));
	cout<<"array 1"<<endl;
	for (int i = 0; i <5; i++){
		num1[i] = rand() % 10;

		cout<<num1[i]<<endl;
	}
	cout<<"array 2"<<endl;
	for (int j = 0; j < 5; j++){
		num2[j] = rand() % 10;

		cout<<num2[j]<<endl;
	}

	cout<<"elementi comuni"<<endl;

	for (int i = 0; i <5; i++){
	for (int j = 0; j <5; j++){

				if (num1[i] == num2[j])
                    {
				cout<<" "<<num1[i];
				}

		}
	}
}
If you ask:
I take five random numbers, each with value in [0-9].
Why do I get same value more than once?

Then, Why not?

Each value has same* probability. What you pick for the first number has no effect* on what the next number can get.

If you want no value to appear more than once, then you have a different problem. For that, I would put numbers 0-9 into array, shuffle the array, and then pick five first elements.


* Technically, with rand(), there is no true randomness, but that is not the issue here.
In my upper code I whish two array with rand numbers if they are
in array 1 = 0 0 3 2 7
in array 2 = 2 4 1 9 0
the result is 0 0 2 (and not only 0 2) why?

How must modify this under code with srand to have a right result?
In the last code (without srand) even if in the array2 there are two equal numbers (8) the result is right 5 8 (and not 5 8 8..)
I wish to have the same with use of srand without repeated numbers...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <iostream>



using namespace std;


int main()
{
	int const dim{ 5 };  

	int v1[dim]{ 1, 5, 7, 10, 8 };
	int v2[dim]{ 5, 8, 22, 8, 4 };
	int v3[dim]{};

	
	for (int i = 0; i < dim; i++)
	{
		for (int j = 0; j< dim;  j++)
			if (v1[i] == v2[j])
			{
				
				v3[i] = v1[i];
			}
	}
cout << endl;

	for (int c = 0; c < dim; c++)
	{
		if (v3[c])
	 cout << ' ' << v3[c] << " Elemento in comune nei 2 array" << endl;
	}

	return 0;
}
Last edited on
Topic archived. No new replies allowed.
Pages: 12