CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    Join Date
    Nov 2011
    Posts
    2

    Filling an array with unique numbers

    Hi there
    This is my homework , I solved it but Im stuck where it says fill the array with only unique numbers , meaning A number cannot be repeated inside the array ..

    here is the question :

    Write a program that uses a random number generator to fill an array with 30 unique numbers between 0 and 100. The program prints out the array and then prints out all even numbers larger than the largest odd number in the array.

    and here is my code :

    Code:
    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    
    using namespace std;
    int i;
    int array[30];
    int odd;
    int Max;
    int counter = 0;
    
    
    int main()
    
    {	
    	cout << "The array consist of 30 elemnts is: ";
    	cout << endl;
    
    	srand ( time(0) );
    
    	for (int j = 0;j<30;j++)
    	{
    
    		i = rand() % 101;
    		 
    
    		 if (i != i-1)
    			array[j]=i;
    
    		 else
    		 {
    			i = rand() % 101;
    		 array[j]=i;
    		 }
    	}
    	
    	for (int k = 0; k < 30 ; k++)
    	{
    		cout << array[k] << " ";
    
    	}
    	cout << endl;
    	
    	cout << "All the even numbers larger than the largest odd number are: ";
    	for (int l = 0; l < 30 ; l++)
    	{
    		odd = -1;
    		Max = -1;
    		for (int n = 0; n < 30 ; n++)
    		{
    			if (array[n] % 2 != 0 && array[n] > Max)
    				{
    					odd = array[n];
    					Max = array[n];
    				}
    		}
    
    		
    		
    	}
    	
    	for(int u = Max+1;u<=100;u++)
    
    		{
    			if (u % 2 == 0)
    				cout << u << " ";
    			if (u == 100)
    				break;
    		}
    	cout << endl;
    	cout << "The largest odd number is : " << Max;
    	cout << endl;
    	return 0;
    }

  2. #2
    Join Date
    Aug 2009
    Posts
    440

    Re: Filling an array with unique numbers

    You'll need to check the newly generated number against the numbers in the array. The easy way to do this is to have a function that does it for you. You can then check this inside of the for loop. Basically, if you find the number in the array, then you need to generate a new random number.

  3. #3
    Join Date
    May 2009
    Posts
    2,413

    Re: Filling an array with unique numbers

    As an alternative approach you could declare an array with 101 boolean elements. Initially you set all elements to false. Then you start generating random numbers and if the corresponding index position in the array is false you change it to true and increment a counter (which initially is set to zero). If an array element already is true you just continue with the next random number because you know this random number has already been counted. When the counter reaches 30 you have 30 random numbers (it's the index positions with true elements).

    Yet another approach is to use an array with 101 integer elements this time. Initially you fill the array with the integer sequence from 0, 1, 2, ... up to 100. You introduce a counter representing the number of remaining array elements. Initially it's N=101. Then you generate a random index position within the N range. The integer at that position is the first random number. You store it in some other array. Since one random number now is taken you decrement N. Then you overwrite the taken random number with the last random number of the array (it's at index position N). Now you generate another random index position within the N range, etcetera. This goes on until you have extracted 30 random numbers.

    The first is a variation of the set approach to unique random number generation and the second is a variation of the random shuffle approach.
    Last edited by nuzzle; November 23rd, 2011 at 04:29 AM.

  4. #4
    Join Date
    Nov 2011
    Posts
    2

    Re: Filling an array with unique numbers

    I think I solved it thanks to you guys

    I actually used a recursive function

    here is the new code

    Code:
    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    
    using namespace std;
    int i;
    int array[30];
    int odd;
    int Max;
    int counter = 0;
    
    
    
    int unique(int array[] , int l)
    {
    	int s;
    
    	if (array[l] == 0)
    	{
    		array[l]=i;
    
    	return array[l];
    	}
    	else
    	{
    		s=l-1;
    		if (i == array[s])
    		unique(array,s);
    		return 0;
    	}
    }
    
    int main()
    
    {	
    	cout << "The array consist of 30 elemnts is: ";
    	cout << endl;
    
    	srand ( time(0) );
    
    	for (int j = 0;j<30;j++)
    	{
    
    		i = rand() &#37; 101;
    		 
    unique(array , j);
    	}
    	
    	for (int k = 0; k < 30 ; k++)
    	{
    		cout << array[k] << " ";
    
    	}
    	cout << endl;
    	
    	cout << "All the even numbers larger than the largest odd number are: ";
    	for (int l = 0; l < 30 ; l++)
    	{
    		odd = -1;
    		Max = -1;
    		for (int n = 0; n < 30 ; n++)
    		{
    			if (array[n] % 2 != 0 && array[n] > Max)
    				{
    					odd = array[n];
    					Max = array[n];
    				}
    		}
    
    		
    		
    	}
    	
    	for(int u = Max+1;u<=100;u++)
    
    		{
    			if (u % 2 == 0)
    				cout << u << " ";
    			if (u == 100)
    				break;
    		}
    	cout << endl;
    	cout << "The largest odd number is : " << Max;
    	cout << endl;
    	return 0;
    }

  5. #5
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Filling an array with unique numbers

    Quote Originally Posted by EnGxSoLiD View Post
    I think I solved it thanks to you guys

    I actually used a recursive function
    You don't need recursion. Use a container that only holds unique values to help you. In the example, items from the array are inserted into a set. At the same time, a check is made to see if the item is already in the set.

    Since a set does a search in logarithmic time, it is much faster than going through an array in a linear fashion searching for duplicates.
    Code:
    #include <set>
    #include <algorithm>
    #include <iostream>
    #include <ctime>
    
    template <typename T>
    bool isUnique(T *ptr, unsigned int numItems)
    {
            std::set<T> ourSet;  
            for(unsigned int i = 0; i < numItems; ++i )
            {
                if (ourSet.find( *ptr ) != ourSet.end() )  
                       return false;  
                ourSet.insert( *ptr );  
            }
            return true;
    }
    
    int main()
    {	
            int array[30];
    	srand ( time(0) );
            std::fill(array, array + 30, rand() &#37; 101);
    
            if ( isUnique(array, 30) )
                std::cout << "Array has unique values";
            else
                std::cout << "Array does not have unique values";
    }
    I won't explain further, since this looks like a homework problem.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; November 23rd, 2011 at 07:54 AM.

  6. #6
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Filling an array with unique numbers

    Yet another approach would be to create a 101 bye array and fill it with the values 0 - 100. Call the random_shuffle function, then copy the first 30 elements to your new array. I would assume that qualifies as a random number generator.

  7. #7
    Join Date
    Jun 2010
    Location
    Germany
    Posts
    2,675

    Re: Filling an array with unique numbers

    And while we're talking of alternative STL-based implementations of the approaches proposed by nuzzle, here's another one:

    Keep inserting random interegers in the range 0 to 100 into an std::set<int> until its size() reaches 30.
    Last edited by Eri523; November 23rd, 2011 at 09:00 AM.
    I was thrown out of college for cheating on the metaphysics exam; I looked into the soul of the boy sitting next to me.

    This is a snakeskin jacket! And for me it's a symbol of my individuality, and my belief... in personal freedom.

  8. #8
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Filling an array with unique numbers

    Quote Originally Posted by Paul McKenzie View Post
    You don't need recursion. Use a container that only holds unique values to help you. In the example, items from the array are inserted into a set. At the same time, a check is made to see if the item is already in the set.

    Since a set does a search in logarithmic time, it is much faster than going through an array in a linear fashion searching for duplicates.
    Code:
    #include <set>
    #include <algorithm>
    #include <iostream>
    #include <ctime>
    
    template <typename T>
    bool isUnique(T *ptr, unsigned int numItems)
    {
            std::set<T> ourSet;  
            for(unsigned int i = 0; i < numItems; ++i )
            {
                if (ourSet.find( *ptr ) != ourSet.end() )  
                       return false;  
                ourSet.insert( *ptr );  
            }
            return true;
    }
    
    int main()
    {	
            int array[30];
    	srand ( time(0) );
            std::fill(array, array + 30, rand() &#37; 101);
    
            if ( isUnique(array, 30) )
                std::cout << "Array has unique values";
            else
                std::cout << "Array does not have unique values";
    }
    I won't explain further, since this looks like a homework problem.

    Regards,

    Paul McKenzie
    Overkill. As Eri says, this is sufficient:

    Code:
    int main()
    {
        std::set<int> vals;
    
        while (vals.size() < 30)
            vals.insert(rand() % 101);
    
        int array[30];
        std::copy(vals.begin(),vals.end(),array);
    }

  9. #9
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    Re: Filling an array with unique numbers

    Quote Originally Posted by Lindley View Post
    Overkill. As Eri says, this is sufficient:

    Code:
    int main()
    {
        std::set<int> vals;
    
        while (vals.size() < 30)
            vals.insert(rand() % 101);
    
        int array[30];
        std::copy(vals.begin(),vals.end(),array);
    }
    And you can always add a random_shuffle to hide from the professor that you used an stl set. Teachers tend to not like it when you do things the smart way...
    Is your question related to IO?
    Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
    It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.

  10. #10
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Filling an array with unique numbers

    Quote Originally Posted by Lindley View Post
    Overkill. As Eri says, this is sufficient:

    Code:
    int main()
    {
        std::set<int> vals;
    
        while (vals.size() < 30)
            vals.insert(rand() &#37; 101);
    
        int array[30];
        std::copy(vals.begin(),vals.end(),array);
    }
    I'm assuming that the OP wants to know if the array has unique values, but this of course is the better way to do things.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; November 23rd, 2011 at 10:55 AM.

  11. #11
    Join Date
    May 2009
    Posts
    2,413

    Re: Filling an array with unique numbers

    Quote Originally Posted by Paul McKenzie View Post
    but this of course is the better way to do things.
    But there's an even better way and that's to simply replace the std::set with an std::unordered_set. It gives a lower complexity because set accesses then becomes O(1) rather than O(logN). This is possible when there's no requirement the numbers must be sorted.

    Still it's worth mentioning that the set approach performs very bad if the number of wanted numbers (here 30) is close or even equal to the number of available numbers (101). Then the performance slows down to a crawl because eventually almost every trial random number will be a duplicate and rejected. In that case the random shuffle approach is superior.

  12. #12
    Join Date
    Nov 2011
    Posts
    6

    Re: Filling an array with unique numbers

    Quote Originally Posted by EnGxSoLiD View Post
    I think I solved it thanks to you guys

    I actually used a recursive function

    here is the new code

    Code:
    #include <iostream>
    #include <cstdlib>
    #include <ctime>
    
    using namespace std;
    int i;
    int array[30];
    int odd;
    int Max;
    int counter = 0;
    
    
    
    int unique(int array[] , int l)
    {
    	int s;
    
    	if (array[l] == 0)
    	{
    		array[l]=i;
    
    	return array[l];
    	}
    	else
    	{
    		s=l-1;
    		if (i == array[s])
    		unique(array,s);
    		return 0;
    	}
    }
    
    int main()
    
    {	
    	cout << "The array consist of 30 elemnts is: ";
    	cout << endl;
    
    	srand ( time(0) );
    
    	for (int j = 0;j<30;j++)
    	{
    
    		i = rand() % 101;
    		 
    unique(array , j);
    	}
    	
    	for (int k = 0; k < 30 ; k++)
    	{
    		cout << array[k] << " ";
    
    	}
    	cout << endl;
    	
    	cout << "All the even numbers larger than the largest odd number are: ";
    	for (int l = 0; l < 30 ; l++)
    	{
    		odd = -1;
    		Max = -1;
    		for (int n = 0; n < 30 ; n++)
    		{
    			if (array[n] % 2 != 0 && array[n] > Max)
    				{
    					odd = array[n];
    					Max = array[n];
    				}
    		}
    
    		
    		
    	}
    	
    	for(int u = Max+1;u<=100;u++)
    
    		{
    			if (u % 2 == 0)
    				cout << u << " ";
    			if (u == 100)
    				break;
    		}
    	cout << endl;
    	cout << "The largest odd number is : " << Max;
    	cout << endl;
    	return 0;
    }
    This is good function unique

  13. #13
    Join Date
    Nov 2011
    Posts
    6

    Re: Filling an array with unique numbers

    This is good function unique ...thanks

  14. #14
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: Filling an array with unique numbers

    To the OP : I think you need to do additional testing on your code in post # 4

    (to make it easier, sort the numbers before printing them out).

  15. #15
    Join Date
    Nov 2011
    Posts
    6

    Re: Filling an array with unique numbers

    why such complicated code...


    for (int j = 0;j<30;j++)
    {
    i = rand() % 101;
    if (i != i-1)
    array[j]=i;
    else
    {
    i = rand() % 101;
    array[j]=i;
    }
    }

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured