Random Number Generator Without Any Repeating Numbers - c++

So basically I have to make an array that allows the user to randomly generate the amount of numbers of their choice, and none of the numbers can be the same. My code generates them normally but still gets repeated numbers and I'm not sure why as I think I prevented it. I'm still fairly new to arrays so this may look really dumb, any help would be appreciated! I've left a lot of side notes to try and break down each section, and at the bottom I'll include what it looks like when it runs.
#include <iostream>
#include <ctime>
#include <windows.h>
using namespace std;
int main()
{
int numberlist[20]; //the array
int count=0,amount=0,value=0;
bool found=false;
srand(time(NULL)); //makes randomizer not the same
cout << "How many numbers to generate?" << endl;
cin>>amount; //gets user input
for(int count=0; count<amount; count++){
value = rand() % 40 + 1; //generates random number from 1-40 until amount is reached
found=false;
if(value==numberlist[count])found=true; //if value is in the array, change found from false to true
if(value!=numberlist[count] && found==false){ //if number is unique and new
numberlist[count]=value; //add number to array
cout << value << endl; //show the value to the screen
}
else if (found==true) {count--;} //if value is in array erase 1 from count
}
return 0;
}
//What it looks like altogether
//How many numbers to generate?
// 9 (<the users input)
//37
//5
//30
//13
//7
//18
//1
//25
//25 (The 25 is the repeating number in this case)

you have mistake in your logic
if(value==numberlist[count])found=true; //if value is in the array, change found from false to true
That's only check if there is no duplicates on in position equals count, You have to iterate over all array position!
Full code below:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int numberlist[20]; //the array
int count=0,amount=0,value=0;
bool found=false;
srand(time(NULL)); //makes randomizer not the same
cout << "How many numbers to generate?" << endl;
cin>>amount; //gets user input
for(int count=0; count<amount; count++){
value = rand() % 40 + 1; //generates random number from 1-40 until amount is reached
found=false;
for(int i = 0 ; i < count; i++) // iterate over all position in array
if(value==numberlist[i])found=true; //if value is in the array, change found from false to true
if(found==false){ //if number is unique and new <--- I have also fix this condition
numberlist[count]=value; //add number to array
cout << value << endl; //show the value to the screen
}
else if (found==true) {count--;} //if value is in array erase 1 from count
}
return 0;
}

Related

This program takes user input and is supposed to sort it using bubbleSort but its outputting letters and numbers and I'm not sure why

The output I'm getting when I run this code after inputting any set of integers, and ending the loop with the sentinel number 999, is always 0x7ffd85bc43b0 and I can't figure out why. I think I'm missing some important code somewhere, but I'm not sure where? This program is also eventually supposed to be able to find the mean and median of the inputted numbers as well.
// HouseholdSize.cpp - This program uses a bubble sort to arrange up to 300 household sizes in
// descending order and then prints the mean and median household size.
// Input: Interactive.
// Output: Mean and median household size.
#include <iostream>
#include <string>
#include <algorithm>
#include <cmath>
#include <any>
#include <stdio.h>
using namespace std;
void swapping(int &a, int &b) { //swap the content of a and b
int temp;
temp = a;
a = b;
b = temp;
}
void display(int householdSizes, int size) {
for(int i = 0; i<size; i++){
}
}
void bubbleSort(int householdSizes[], int size) {
for(int i = 0; i<size; i++) {
int swaps = 0; //flag to detect any swap is there or not
for(int j = 0; j<size-i-1; j++) {
if(householdSizes[j] > householdSizes[j+1]) { //when the current item is bigger than next
swapping(householdSizes[j], householdSizes[j+1]);
swaps = true; //set swap flag
}
}
if(swaps== false)
break; // No swap in this pass, so array is sorted
}
}
int main()
{
// Declare variables.
const int SIZE = 300; // Number of household sizes
int householdSizes[SIZE]; // Array used to store 300 household sizes
int x;
int limit = SIZE;
int householdSize = 0;
int pairsToCompare;
bool switchOccurred;
int temp;
double sum = 0;
double mean = 0;
double median = 0;
// Input household size
cout << "Enter household size or 999 to quit: ";
cin >> householdSize;
// This is the work done in the fillArray() function
x = 0;
while(x < limit && householdSize != 999)
{
// Place value in array.
householdSizes[x] = householdSize;
// Calculate total of household sizes
x++; // Get ready for next input item.
cout << "Enter household size or 999 to quit: ";
cin >> householdSize;
} // End of input loop.
// Find the mean
// This is the work done in the sortArray() function
int n = sizeof(householdSizes)/sizeof(householdSizes[0]);
bubbleSort(householdSizes, n);
cout <<householdSizes;
// This is the work done in the displayArray() function
// Print the mean
// Find the median
// Print the median
return 0;
} // End of main function
An array can't be printed directly using cout << householdSizes; Since an array is convertible to a pointer, that is what is done implicitly behind the scenes. Change cout << householdSizes; to:
for(int i = 0; i < x; ++i){
std::cout << householdSizes[i] << " ";
}
P.S. Also do as #0x5453 says. He is right.

C++ modify array outside of main and print new numbers from main along with the number of results?

new to C++ and learning about arrays and functions.
I need to use 2 functions outside of function main. The first to read numbers inputted by the user and store them in an array. The user enters positive numbers followed by a negative number to signify the end of the list. The second to find any negative numbers and return them to main. Once in main, I need to print those negative numbers along with how many there are.
I have the first part down, I'm just trying to figure out how to accomplish the second part. The second part is a bit of a mess so I apologize in advance (I've tried a few different things). A side note: I realize that index isn't a great variable name, but just go with it.
Any help is super appreciated, thank you!
Here is some of the code I have down.
#include <iostream> //for cin and cout
using namespace std;
const int max_size = 20; //maximum size of array
//function prototypes
void read_list(int[], int&);
int find_negative(int[], int);
int main()
{
//array of positive integers with max size specified
int list[max_size];
//variable for number of positive integers in the array
int number_of_integers;
//variable for counter
int index;
//read inputted integers
read_list(list, number_of_integers);
//find any negative numbers via a function then display result in main.
find_negative(list, number_of_integers);
//print any negative numbers
for (index=0; index < number_of_integers; index++)
{
cout << list[index-1] << " ";
}
return 0;
}
void read_list(int list[], int& length)
{
//variables for loop and entered numbers
int number;
int index = 0;
//prompt the user to enter numbers
cout << "To get started, please enter a number of positive "
<< "integers, each separated by a blank space.\n"
<< "Mark the end of the list with a negative number: ";
//read the first number
cin >> number;
//check whether entered number is positive or negative
//and that the size of the array is not exceeded
while (number>=0 && index < max_size)
{
//store the entered integer in the array
list[index] = number;
//increment the index
index++;
//read the next integer
cin >> number;
}
//length is the number of positive integers in the array
length = index;
}
int find_negative(int list[], int length)
{
int index; //counter
for (index = 0; index < length; index++)
{
while (index < 0)
{
list[index] = index - 1;
}
}
return list[index];
}

The three biggest numbers in array

#include<iostream>
using namespace std;
int main()
{
int s;
cin>>s;
int t=3;
int maxValue,imax[t],maxIndex,arr[s];
for(int i=0; i<s; i++){
cin>>arr[i];
}
maxValue=arr[0];
for(int i=0;i<s;i++){
if(arr[i]>maxValue){
maxValue=arr[i];
imax[0] = i;
}
}
maxValue=arr[0];
for(int i=0;i<s;i++){
if (i == imax[0]) { continue; }
if(arr[i]>maxValue){
maxValue=arr[i];
imax[1] = i;
}
}
maxValue=arr[0];
for(int i=0;i<s;i++){
if (i == imax[0]) { continue; }
if (i == imax[1]) { continue; }
if(arr[i]>maxValue){
maxValue=arr[i];
imax[2] = i;
}
}
cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
cout<<"Third biggest number:"<<arr[imax[2]];
return 0;
}
This program must return tree numbers which is biggest in this arraybut , i do not know why when I introduce as example five numbers (121,34,56,67,545) and the compiler was return 545 and then crash.
Thank you in advance for the answer.
The problem is that before iterating the loop, you first set the maxValue to be the first element in the array. The imax only gets updated whenever there is at least one element greater than the current maxValue. However, if the first element is somehow the maxValue you are looking for, then the imax never gets set, which would be uninitialized causing segmentation fault at the end.
In your code, after finding the largest element 545, the second largest element was never found, since 121 is the first element in the array. Hence after printing out 545, imax[1] is uninitialized and the program crashes.
You use uninitialized array values in lines
cout<<"First biggest number:"<<arr[imax[0]]<<"\n";
cout<<"Second biggest number:"<<arr[imax[1]]<<"\n";
cout<<"Third biggest number:"<<arr[imax[2]];
If there are less than 3 different numbers in input, some imax array elements will not be initialized. Also if input array is empty, imax will not be initialized at all.
Therefore in expression arr[imax[1]] you read element of arr with index, which was not initialized and can be some very big number. It can be fixed if you declare iarr as
int imax[t] = {};
This will zero-initialize all elements of array and will prevent crashing.
Your program also doesn't check number of elements in input array, so if there are less than three input numbers arr[2] will also print uninitialized value.
Here's proper solution using STL algorithms and std::vector. It works with any number of t - you can easily change it to print largest 10 numbers. It is also memory efficient - it does not need to store whole input array so you can process large inputs with it.
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
int s;
std::cin >> s;
unsigned t = 3;
std::vector<int> max_numbers;
max_numbers.reserve(t + 1);
for (int i = 0; i < s; ++i) {
int number;
if (std::cin >> number) { //Check basic input errors
max_numbers.push_back(number); // Add number to top-3 list
// Sort elements in descending order
std::sort(max_numbers.begin(), max_numbers.end(), std::greater<int>());
// Remove duplicates
max_numbers.erase(std::unique(max_numbers.begin(), max_numbers.end()),
max_numbers.end());
// Remove excess elements
if (max_numbers.size() > t) {
max_numbers.resize(t);
}
}
}
std::cout << "Biggest " << t << " numbers are" << std::endl;
for (int i : max_numbers) {
std::cout << i << std::endl;
}
}

Having Trouble With A Simple C++ Program

I'm creating this very simple C++ program.
the program asks the user to enter a few integers and stores them in an array.but when a specific integer(for example 50)is entered,the input is ended and then,all of the integers are displayed on the screen except for 50.
for example:
input:
1
2
88
50
output:
1
2
88
the error i'm getting is when i use cout to print the array,all of numbers are shown,including 50 and numbers i did'nt even entered.
this is my code so far:
#include<iostream>
int main() {
int num[100];
for(int i=0;i<=100;i++) {
cin >> num[i];
if (num[i]!=50) break;
}
for(int j=0;j<=100;j++) {
cout << num[j] << endl;
}
return 0;
}
Change the program the following way
#include<iostream>
int main()
{
const size_t N = 100;
int num[N];
size_t n = 0;
int value;
while ( n < N && std::cin >> value && value != 50 ) num[n++] = value;
for ( size_t i = 0; i < n; i++ ) std::cout << num[i] << std::endl;
return 0;
}
Here in the first loop variable n is used to count the actual number of entered values. And then this variable is used as the upper bound for the second loop.
As for your program then the valid range of indices for the first loop is 0-99 and you have to output only whose elements of the array that were inputed.
A do while loop is more suitable for your problem. The stop condition will check if the number fit inside the array (if k is not bigger than 100) and if number entered is 50.
#include<iostream>
using namespace std;
int main() {
int num[100];
int k = 0;
// A do while loop will be more suitable
do{
cin >> num[k++];
}while(k<100&&num[k-1]!=50);
for (int j = 0; j < k-1; j++) {
cout << num[j] << endl;
}
return 0;
}
Also, a better solution to get rid of 100 limitation is to use std::vector data structure that automatically adjust it's size, like this:
vector<int> num;
int temp;
do {
cin >> temp;
num.push_back(temp);
} while (temp != 50);
Note, you can use temp.size() to get the number of items stored.
You read up to 101 numbers, but if you enter 50 you break the loop and go for printing it. In the printing loop you go through all 101 numbers, but you actually may have not set all of them.
In the first loop count in a count variable the numbers you read until you meet 50 and in the printing loop just iterate count-1 times.
You have allocated an array of 100 integers on the stack. The values are not initialized to zero by default, so you end up having whatever was on the stack previously appear in your array.
You have also off-by-one in both of your loops, you allocated array of 100 integers so that means index range of 0-99.
As the question is tagged as C++, I would suggest that you leave the C-style array and instead use a std::vector to store the values. This makes it more flexible as you don't have to specify a fixed size (or manage memory) and you don't end up with uninitialized values.
Little example code (requires C++11 compiler):
#include <iostream>
#include <vector>
int main()
{
std::vector<int> numbers; // Store the numbers here
for(int i = 0; i < 100; ++i) // Ask a number 100 times
{
int n;
std::cin >> n;
if( n == 50 ) // Stop if user enters 50
break;
numbers.push_back(n); // Add the number to the numbers vector
}
for (auto n : numbers) // Print all the values in the numbers vector
std::cout << n << std::endl;
return 0;
}
There are just 2 changes in your code check it out :
int main()
{
int num[100],i; //initialize i outside scope to count number of inputs
for(i=0;i<100;i++) {
cin >> num[i];
if (num[i]==50) break; //break if the entered number is 50
}
for(int j=0;j<=i-1;j++)
{
cout << num[j] << endl;
}
return 0;
}
Okay, others already pointed out the two mistakes. You should use i < 100 in the loop conditions instead of i <= 100 and you have to keep track of how many elements you entered.
Now let me add an answer how I think it would be better.
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector.
for (int temp; // a temp variable in the for loop.
numbers.size() < 100 && // check that we have less than 100 elements.
std::cin >> temp && // read in the temp variable,
// and check if the read was a success.
temp != 50) // lastly check that the value we read isn't 50.
{
numbers.push_back(temp); // Now we just add it to the vector.
}
for (int i = 0; i < numbers.size(); ++i)
std::cout << numbers[i]; // Now we just print all the elements of
// the vector. We only added correct items.
}
The above code doesn't even read anymore numbers after it found 50. And if you want to be able to enter any number of elements you just have to remove the check that we have less than 100 elements.
Now I commented the above code a bit much, if you compress it it'll reduce to just:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector.
for (int temp; numbers.size() < 100 && std::cin >> temp && temp != 50)
numbers.push_back(temp);
for (int i = 0; i < numbers.size(); ++i)
std::cout << numbers[i];
}
If you can use the C++11 standard it reduces to:
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers; // Create an empty vector.
for (int temp; numbers.size() < 100 && std::cin >> temp && temp != 50)
numbers.push_back(temp);
for (int element : numbers)
std::cout << element;
}
for (auto element : numbers) is new, it basically means for every int 'element' in 'numbers'.

display 25 randomnumbers from an array

I have in C++ an array of 100 elements, so v[1], ... ,v[100] contains numbers. How can i display, 25 random numbers from this array? So i wanna select 25 random positions from this array and display the values.. How can i do this in C++?
Thanks!
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
using namespace std;
int aleator(int n)
{
return (rand()%n)+1;
}
int main()
{
int r;
int indexes[100]={0};
// const int size=100;
//int a[size];
std::vector<int>v;
srand(time(0));
for (int i=0;i<25;i++)
{
int index = aleator(100);
if (indexes[index] != 0)
{
// try again
i--;
continue;
}
indexes[index] = 1;
cout << v[index] ;
}
cout<<" "<<endl;
system("pause");
return 0;
}
The idea is that i have this code, and i generate 100 random numbers. What i want is an array with random 25 elements from those 100 generated.. But i don't know how to do that
Regards
Short Answer
Use std::random_shuffle(v.begin(),v.end()) to shuffle the array, and then display the first 25 elements.
Long Answer
First of all, the elements would be v[0]...v[99] (C++ uses 0-based indexing), not v[1]...v[100]. To answer your question, though, it depends on whether it is acceptable to repeat elements of the array or not. If you aren't worried about repeats, then simply use the index rand()%v.size(), repeatedly until you have selected a sufficient number of indices (25 in your question). If repeats are not acceptable, then you need to shuffle the array (by swapping elements at random), and then display the first (or last, or any contiguous region of) N elements (in this case N=25). You can use std::random_shuffle to shuffle the array. That does the bulk of the work for you. Once you've done that, just show 25 elements.
If you want to print 25 numbers of an array V you can use this code do:
int V[100]={1,2,5,...} ;
srand ( time (0) ) ;
for (int i=0;i<25;i++)
{
cout << V[rand() % 100 + 1]<<" " ;
}
I modified the version of Mehdi a little in order to make it choose differnet indexes
NOTE: This makes the algorithm not deterministic - it relies on the RNG.
int indexes[100]={0};
srand ( time (0) );
for (int i=0;i<25;i++)
{
int index = rand() % 100;
if (indexes[index] != 0)
{
// try again
i--;
continue;
}
indexes[index] = 1;
cout << v[index] ; cout << endl;
}