iPhone Password generator

So the code I've attached works well and fine, however my lines 25-33 is bulky and I have a feeling there's an easier way to pull this comparison off with a for-loop. I've tried every way my beginner know-how will allow me and this is the only way I was able to make the code work.

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
41
42
43
#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main()
{
	int times;
	int array[4];
	char repeat;
	srand(time(NULL));
	
	do{
		cout << "How many passwords to generate? ";
		cin >> times;
		
		for(int i=0;i<times;i++){
			for(int i=0;i<4;i++){
				int random = rand()%9 + 0;
				array[i] = random;
				cout << array[i];
			}
			
			if((array[0]!=array[1])&&(array[0]!=array[2])&&(array[0]!=array[3])){
				if((array[1]!=array[0])&&(array[1]!=array[2])&&(array[1]!=array[3])){
					if((array[2]!=array[0])&&(array[2]!=array[1])&&(array[2]!=array[3])){
						if((array[3]!=array[0])&&(array[3]!=array[1])&&(array[3]!=array[2])){
							cout << "**";
						}
					}
				}
			}
			
			cout << endl;
		}
		cout << "Repeat (y/n)? ";
		cin >> repeat;
	}while(repeat != 'n');

	return 0;
}
You have many redundant conditions there:

1
2
3
4
            if (array[0] != array[1] && array[0] != array[2] && array[0] != array[3])
                if (array[1] != array[2] && array[1] != array[3])
                    if (array[2] != array[3])
                        cout << "**";


or with a nested for loop:
1
2
3
4
5
6
7
8
9
            bool unique = true;
            for (std::size_t i=0; i < 3; ++i)
                for (std::size_t j=i+1; j < 4; ++j)
                   if (array[i] == arraj[j])
                       unique = false;
            
            if (unique)
                cout << "**";
 
Last edited on
Topic archived. No new replies allowed.