Check if number is in array

I want to check if the random generated number is present in the array, and if it is create a new random number instead. The problem is I have an array of objects, and not sure how to make this 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
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <stdlib.h>
#include <time.h>

const int MAX =10;

class Baz
{
    public:
        int number;
        std::string name;
};

class Foobar
{
    public:
        Baz bar[MAX];

        void newBaz()
        {
            srand(time(0));
            int random;

            random = rand()%1000-9999;

            //CHECK IF VALUE OF 'random' IS PRESENT IN 'bar[].number'
            for(int i=0; i < sizeof bar[].number; i++)
            {
                //IF VALUE IS PRESENT
                if(bar[i].number == random)
                {
                    //GIVE 'random' NEW VALUE
                    random = rand()%1000-9999;

                    //CHECK AGAIN
                    i = 0;
                }//END if
            }//END for

            //GIVE VALUE OF 'random' TO 'bar[].number'
            bar[0].number = random;

            std::cin >> bar[0].name;
        }//END newBaz()
};

int main()
{
    Foobar qux;

    qux.newBaz();
}


The problem is the for and if statement in newBaz function (Foobar class). I can tell it wont work, but I cant tell why. Sorry for any careless mistakes, made this topic in a haste.
Bump... nothing?
I'm not sure what you think sizeof does... but it doesn't do what you're thinking.

i < sizeof bar[].number; <- I cannot imagine how this could possibly compile. This should be giving you errors.

You'll need to loop for each element in the array. You have 'MAX' elements, so just loop 'MAX' times:

for(int i=0; i < MAX; i++)


Furthermore, you are not resetting your loop properly. Remember that the increment portion of the for loop will occur after every time the loop completes. Which means when you reset i to 0 on line 36, the loop will finish an iteration then i will be incremented to 1 -- meaning element 0 will not be checked again.

You can "side-step" this by resetting i to -1 instead of to 0, but that's hackish. A better way would be to just nest the loop. You have 2 loop conditions here (one loop to ensure the number is unique, and one to iterate over all values to make sure it's unique).. so 2 loops makes things more clear:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
bool alreadyinarray = false;
do
{
    random = rand() % whatever;

    for(int i = 0; i < max; ++i)
    {
        if(bar[i].number == random)
        {
            alreadyinarray = true;
            break;
        }
    }
} while (alreadyinarray);



Also... don't put the srand() call there. srand should typically be called exactly once throughout the entire life of the program. It should not be called every time newBaz is called.


EDIT:

Bump... nothing?


Please give us more than an hour to respond. There aren't necessarily people on here 24/7.
Last edited on
1. Have a look at your loop termination condition (line 27). It's sematically and syntactically wrong.
2.
and if it is create a new random number instead
Do you mean: Replace it by a new one? Then your code is wrong. It ever replaces only the first number of your array.
3. The numbers of your array aren't initialized, which will give them random values on object creation. Maybe no problem in your task. But think about that the array may contain any number multiple times.
4. What's your intention with line 36?
- I suggest you replace "sizeof()" with 10.

- Also, use a for loop or some other loop to initialize the values in your array of objects.
- Personally, i would do something along these lines.

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <stdlib.h>
#include <time.h>

const int MAX =10;

class Baz
{
    public:
        int number;
        std::string name;
};

class Foobar
{
    public:
        Baz bar[MAX];

        Foobar()
        {
            srand(time(0));
            int r;
            for (int f=0;f<10;f++)
            {
                 r = rand()%1000-9999;
                 bar[f].number= r;
                 std::cout<<"Enter the name for baz "<<f<<std::endl;
                 std::cin>>bar[f].name;
            }


        }

        void newBaz()
        {
            srand(time(0));
            int random;

            random = rand()%1000-9999;

            //CHECK IF VALUE OF 'random' IS PRESENT IN 'bar[].number'
            for(int i=0; i < 10; i++)
            {
                //IF VALUE IS PRESENT
                if(bar[i].number == random)
                {
                    //GIVE 'random' NEW VALUE
                    random = rand()%1000-9999;

                    //CHECK AGAIN
                    i = 0;
                }//END if
            }//END for

            //GIVE VALUE OF 'random' TO 'bar[].number'
            bar[0].number = random;

          //  std::cin >> bar[0].name;
        }//END newBaz()
};

int main()
{
    Foobar qux;

    qux.newBaz();
}
I think I have corrected most of the errors, but still have some questions.

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <stdlib.h>
#include <time.h>

const int MAX =10;

class Baz
{
    public:
        int number;
        std::string name;
};

class Foobar
{
    public:
        Baz bar[MAX];

        Foobar()
        {
            int random;
            for (int j=0; j < MAX; j++)
            {
                 //GIVE VALUE OF 'random' TO 'bar[].number'
                 random = rand()%1000-9999;
                 bar[j].number = random;
            }
        }//END constructor Foobar()


        void newBaz()
        {
            int random;
            bool isPresent = false;

            do
            {
             // random = rand()%1000-9999;

                //CHECK IF VALUE OF 'random' IS PRESENT IN 'bar[].number'
                for(int i=0; i < MAX; i++)
                {
                    //IF VALUE IS PRESENT
                    if(bar[i].number == random)
                    {
                        //GIVE 'random' NEW VALUE
                        random = rand()%1000-9999;

                        //CHECK AGAIN
                        isPresent = true;
                    }//END if
                }//END for

            }while(isPresent)

//          bar[0].number = random;

            std::cin >> bar[0].name;
        }//END newBaz()
};

int main()
{
    srand(time(0));
    Foobar qux;

    qux.newBaz();
}


Do you mean: Replace it by a new one? Then your code is wrong. It ever replaces only the first number of your array

I want the value of 'random' to be replaced if the number given to it allready exists within the array, thus every number in the array must be unique.

I'm not sure what you mean? This is what I want it to do
-Iterate through the array
-If a number in the array is equal to the random number
-Change the random number(not the number in the array)
-Iterate again to make sure the new random number isnt present
-If the random number is unique
-Give the random number to the array object number-spot and continue program.

Please give us more than an hour to respond. There aren't necessarily people on here 24/7.

Sorry for the bump, wont happen again

I suggest you replace "sizeof()" with 10

I did put the const int MAX; variable there instead. This should work just as fine? The reason is if the value is changed, the easy way is to just having to change it once at one location.

Also, use a for loop or some other loop to initialize the values in your array of objects

As soon as I run the program, the objects are created from main(dont know why, but they are) and if I'm not wrong there should be pregenerated numbers inside the arrays?


EDIT
Added thejman250's constructor(or parts of it)
The reason I dont want to use std::cin in the constructor is because when the program starts, it creates the objects, and the user should not have to enter the names at the beginning of the program. Correct me if I'm wrong.

But the idea of generating the random numbers in the constructor is a great.
Last edited on
- Then i guess you don't need each object in the array to have a separate name?

- Moreover, i suggest you put a prompt before std::cin in line 58 if you want the use to enter the name there.

- If you initialize the values in the array of random objects with the constructor, then they will be created in main, as your instance of the Foobar class was created in main.
I'm really confused right now. Done some changes to the code to try and find why its messing with me
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <stdlib.h>
#include <time.h>

const int MAX =10;

class Baz
{
    public:
        int number;
        std::string name;
};

class Foobar
{
    public:
        Baz bar[MAX];

        Foobar()
        {
            int random;
            std::cout << "\nInteger random created at adress " << &random;

            for (int j=0; j < MAX; j++)
            {
                 //GIVE VALUE OF 'random' TO 'bar[].number'
                 random = rand()%1000;
                 bar[j].number = random;

                 std::cout << "\nFoobar constructor generated random number " << random << " at adress " << &bar[j].number;
            }
        }//END constructor Foobar()


        void newBaz()
        {
            int random;
            std::cout << "\nInteger random created at adress " << &random;
            bool isPresent = false;
            std::cout << "\nBool created at adress " << &isPresent;

            do
            {
             // random = rand()%1000-9999;

                //CHECK IF VALUE OF 'random' IS PRESENT IN 'bar[].number'
                std::cout << "\nCheck if random generated number is unique";
                for(int i=0; i < MAX; i++)
                {
                    //IF VALUE IS PRESENT
                    if(bar[i].number == random)
                    {
                        std::cout << "\nGenerated number for " << bar[i].number << " is NOT unique";
                        //GIVE 'random' NEW VALUE
                        random = rand()%1000;
                        std::cout << "\nGenerated new number";

                        //CHECK AGAIN
                        isPresent = true;
                    }//END if
                }//END for

            }while(isPresent);
            std::cout << "\nAll numbers are unique";

//          bar[0].number = random;

            std::cout << "Enter name: ";
            std::cin >> bar[0].name;
        }//END newBaz()
};

int main()
{
    srand(time(0));
    Foobar qux;
    std::cout << "Foobar object created at adress " << &qux;

    qux.newBaz();
}


EDIT!
sorry wasnt planing on pressing submit. Here comes the rest of the post

It gives me a infinite loop at line 47, dont know why?
The random variable created on line 21 and 36 has the same adress. Is it using the same variable, or is it creating a new one on the same adress?
Last edited on
Then i guess you don't need each object in the array to have a separate name?

Each Foobar object should have 'MAX' number of names given by the user.

Moreover, i suggest you put a prompt before std::cin in line 58 if you want the use to enter the name there.

I did the post in a haste and didnt think of making it user-friendly. Sorry

If you initialize the values in the array of random objects with the constructor, then they will be created in main, as your instance of the Foobar class was created in main.

Not sure what you mean. Why?


- put this inside of your do while loop but before the for loop:

1
2
3

isPresent = false;
put this inside of your do while loop but before the for loop:


Then the variable is destroyed when the scope ends, and I can not use while(isPresent) to end the loop?

Error message on line 63 if I do:
error: 'isPresent' was not declared in this scope
Not sure what you mean. Why?


- Main creates an instance of your object.

- The class has a constructor.

- The constructor runs when the class is instantiated.

- Moreover, in your program an instance of your class is instantiated in main. Thus, your constructor will run when said instance of your class is instantiated in main.

- Hence, the variables being initialized (which happens in the constructor) will be happening in main as well.

Then the variable is destroyed when the scope ends, and I can not use while(isPresent) to end the loop?



- The variable shouldn't be destroyed when the scope of the do while loop ends

- ex:
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

bool isPresent;

do
{
isPresent= false;

for(int i=0; i < MAX; i++)
{
if(bar[i].number == random)
{


 std::cout << "\nGenerated number for " << bar[i].number << " is NOT unique";
//GIVE 'random' NEW VALUE
random = rand()%1000;
 std::cout << "\nGenerated new number";
isPresent = true;
}
else
{
}
}




}
while(isPresent);

Last edited on
random isn't initialized @line 37

I bet if you made the find function separate from the generation of random numbers, it would be easier.

You need to take "i" out of the loop:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
bool isPresent = false;
do
{
  int random = rand()% whatever;
  std::cout << "\nCheck if random generated number is unique";
  int i;
  for(i=0; i < MAX; i++)
  {
    if(bar[i].number == random)
    {
    std::cout << "\nGenerated number for " << bar[i].number << " is NOT unique";
    isPresent = true;
    break;
    }
  }
  if (i == MAX)  // The number wasn't found
    isPresent = false;
}while(isPresent);
Last edited on
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
#include <stdlib.h>
#include <time.h>

const int MAX =10;

class Baz
{
    public:
        int number;
        std::string name;
};

class Foobar
{
    public:
        Baz bar[MAX];

        Foobar()
        {
            int random;
            std::cout << "\nInteger random created at adress " << &random;

            for (int j=0; j < MAX; j++)
            {
                 //GIVE VALUE OF 'random' TO 'bar[].number'
                 random = rand()%1000;
                 bar[j].number = random;

                 std::cout << "\nFoobar constructor generated random number " << random << " at adress " << &bar[j].number;
            }
        }//END constructor Foobar()


        void newBaz()
        {
            int random;
            int i;
            bool isPresent;
            std::cout << "\nInteger random created at adress " << &random;

            do
            {
             // random = rand()%1000-9999;

                isPresent = false;
                std::cout << "\nBool created at adress " << &isPresent;

                //CHECK IF VALUE OF 'random' IS PRESENT IN 'bar[].number'
                std::cout << "\nCheck if random generated number is unique";
                for(i=0; i < MAX; i++)
                {
                    //IF VALUE IS PRESENT
                    if(bar[i].number == random)
                    {
                        std::cout << "\nGenerated number for " << bar[i].number << " is NOT unique";
                        //GIVE 'random' NEW VALUE
                        random = rand()%1000;
                        std::cout << "\nGenerated new number";

                        isPresent = true;
                        break;
                    }//END if

                }//END for

            //CHECK AGAIN?
            if(i==MAX)
                isPresent = false;

            }while(isPresent);
            std::cout << "\nAll numbers are unique";

//          bar[0].number = random;

            std::cin >> bar[0].name;
        }//END newBaz()
};

int main()
{
    srand(time(0));
    Foobar qux;
    std::cout << "\nFoobar object created at adress " << &qux;

    qux.newBaz();
}
OUTPUT

Integer random created at adress 0x22ff18
Foobar constructor generated random number 379 at adress 0x22fec8
Foobar constructor generated random number 151 at adress 0x22fed0
Foobar constructor generated random number 388 at adress 0x22fed8
Foobar constructor generated random number 363 at adress 0x22fee0
Foobar constructor generated random number 197 at adress 0x22fee8
Foobar constructor generated random number 493 at adress 0x22fef0
Foobar constructor generated random number 978 at adress 0x22fef8
Foobar constructor generated random number 98 at adress 0x22ff00
Foobar constructor generated random number 705 at adress 0x22ff08
Foobar constructor generated random number 437 at adress 0x22ff10
Foobar object created at adress 0x22fec8
Integer random created at adress 0x22ff18
Bool created at adress 0x22ff1f
Check if random generated number is unique
Generated number for 437 is NOT unique
Generated new number
Bool created at adress 0x22ff1f
Check if random generated number is unique
All numbers are unique
Process returned 0


But the number 437 IS unique. It generates a new number for the last constructed object each time I run the program, telling its not unique...

Why?
Topic archived. No new replies allowed.