I am trying to generate a sequence of 6 random numbers with all the numbers being different from each other(no repetition of the numbers). But when I try to test whether I have successfully generated those numbers or not by trying to print them out, the code compiles successfully but nothing appears on the screen. Something seems to be wrong with my use of the function erase() because once I remove it the code produce some output although not what I am looking for.
#include<bits/stdc++.h>
#include<time.h>
using namespace std;
int main(void)
{
srand(time(NULL));
vector<int>v;
vector<int>V;
int arr[6];
int i,j;
for(i=1;i<=6;i++)
{
V.push_back(i);
}
for(int i=0;i<6;i++)
{
cout<<V[i]<<" ";
}
for(int i=0;i<6;i++)
{
int n=rand()%6;
v.push_back(V[n]);
V.erase(V.begin()+n);
}
cout<<endl;
for(int i=0;i<6;i++)
{
cout<<V[i]<<" ";
}
return 0;
}
You are using a wrong algorithm:
Generate six random numbers
If there are some which are equal, do something.
This is better:
Make a full list of all possible numbers.
Take random a number out of that list and remove it from the list. Do this six times.
You should use std::shuffle to re-order your numbers
#include <vector>
#include <iostream>
#include <random>
#include <algorithm>
#include <numeric>
void print_numbers(const std::vector<int> & numbers) {
for (int number : numbers) {
std::cout << number << " ";
}
std::cout << std::endl;
}
int main() {
std::vector numbers(6);
std::iota(numbers.begin(), numbers.end(), 1);
print_numbers(numbers);
std::random_device rd; // ok for small quantities like this, generally prefer a std::default_random_engine with some seed
std::shuffle(numbers.begin(), numbers.end(), rd);
print_numbers(numbers);
}
Related
I'm new to c++ but long story short , i want to write a c++ program that will accept input from user through an array and it will sum each array element input
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int main() {
int array[100];
int sum;
for(int i=0; i<100; i++){
cout<<"Insert element "<<i<<": ";
cin>>array[i];
sum = array[i]+ //summ with the next array input;
cout<<sum;
}
return 0;
}
means that if i enter any integer the program should be able to give the summation of the inputs in sequence from the first input to the last input
C++ standard library already has a function to do this which is std::accumulate:
#include <iostream>
#include <numeric>
int main() {
int array[5] = {1,2,3,4,5};
int total = std::accumulate(std::begin(array), std::end(array), 0);
return 0;
}
If you plan to use not a full array you should use std::begin(array), std::begin(array) + amount as ranges.
initialize your sum var to 0 initially and write sum+=array[i] instead of what you have written, there is also a limitation in this program as value of sum after all user input should be <=10^9 as int datatype store no. approximately upto 10^9 so take note of this fact also. Write cout<<sum<<endl; instead to be able to distinguish till previous input sum to the new input sum.
Hope this will help.
You can use a do while loop:
#include<iostream>
#include<string>
#include<math.h>
int main()
{
int array[100];
int sum=0;
int i=0;
std::cout<<"Insert element"<<" "<<i<<": ";
std::cin>>array[i];
do
{
sum=sum+array[i];
std::cout<<sum<<std::endl;
i++;
std::cout<<"Insert element"<<" "<<i<<": ";
}while(std::cin>>array[i]);
return 0;
}
If all you want is the sum then just compute the sum. No need to store anything:
#include <iostream>
#include <string>
#include <math.h>
int main() {
int sum = 0;
for(int i=0; i<100; i++){
std::cout << "Insert element " << i << ": ";
int t;
std::cin >> t;
sum += t
std::cout << sum;
}
}
So here's my problem i'm writing a c++ code to basically randomly generate X amount of numbers between [0-100] and then create a 2D array with all the numbers found sorted by smallest->biggest
and print out each number found and how many times they are found.
this is the code i've written but there is a problem with it
whenever i print the array with the numbers and how many times each one is found no matter how many times one number is found it's the same for all of them
how can i fix that
#include <random>
#include <functional>
#include <iostream>
using namespace std;
std::default_random_engine generator;
std::uniform_int_distribution<int> data_element_distribution(0, 100);
auto random_element = std::bind(data_element_distribution, generator);
int main()
{
int size, i;
int different_numbers;
cout<<"Enter the size of the Linear List:";
cin>>size;
int LinearList[size], TempList[size];
for (i=0; i < size; i++)
{
int data_element = random_element(); //Filling the Linear List with random numbers
LinearList[i]=data_element;
TempList[i]=LinearList[i];
}
int j, temp;
for(j=size;j>1;j--)
{
for ( i=1; i<j; i++)
{
if(TempList[i]<TempList[i-1])
{
temp=TempList[i]; //Sorting numbers
TempList[i]=TempList[i-1];
TempList[i-1]=temp;
}
}
}
different_numbers=1;
int numbers[size];
int *Histogram;
Histogram=new int[different_numbers,1];
for (i=0;i<size-1;i++)
{
if(TempList[i]!=TempList[i+1])
{ //Finding the Size of the Histogram
numbers[different_numbers]=TempList[i]; //Counting how many Times each Number is found
Histogram[different_numbers,1]=1;
different_numbers++;
}
else
{
Histogram[different_numbers,1]++;
}
}
for(i=1;i<different_numbers;i++)
{
Histogram[i,0]=numbers[i]; //Printing numbers and Times found
cout<<Histogram[i,0];
cout<<" Is found "<<Histogram[i,1]<<" times."<<endl;
}
return 0;
}
edit: thank you guys for your comments and help i'll give it a try you're all life savers Xd
I need my program to make a random sequence from 1-3 each time, but I don't understand how I'd use rand() to make the sequence of numbers 1 to 3 in a different order each program. It can't be the same number again, so I don't know what I'd do to prevent that. An example run would be
123 the first, 231 the second, 321 and so fourth
What would you use to make a sequence that doesn't repeat numbers
The simplest way to generate your sequence would be to use std::shuffle to re-order a vector containing your desired values:
#include <vector>
#include <algorithm>
#include <random>
#include <iostream>
int main()
{
std::random_device rd;
std::mt19937 g(rd());
std::vector<int> elements = { 1, 2, 3 };
std::shuffle(elements.begin(), elements.end(), g);
for (int i : elements)
{
std::cout << i << "\n";
}
}
If you really must use rand() (its not generally a very good random number generator) you can just about squeeze it into shuffle too:
#include <vector>
#include <algorithm>
#include <ctime>
#include <iostream>
struct RandDevice
{
using result_type = uint32_t;
static result_type max() { return static_cast<result_type>(RAND_MAX); };
static result_type min() { return 0; };
result_type operator()() {
return static_cast<result_type>(rand());
}
};
int main()
{
std::vector<int> elements = { 1, 2, 3 };
srand(time(0));
std::shuffle(elements.begin(), elements.end(), RandDevice());
for (int i : elements)
{
std::cout << i << "\n";
}
}
You can use std::next_permutation
Example here : https://en.cppreference.com/w/cpp/algorithm/next_permutation
it's pretty easy to do.. just compare the number you with every occupied element in the array. if it is not in the array, add to array. else, try again.
I have done similar code check this out
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
void displayArray(int randNum[], int elements);
void randomNum(int randNums[], int elements);
int main ()
{
//declare array
int numbers[999] = {0};
//random number generator
srand(static_cast<int>(time(0)));
randomNum(numbers, 999);
displayArray(numbers, 999);
system("pause");
return 0;
}
void randomNum(int randNums[], int elements)
{
for (int i = 0; i < elements; i++)
{
bool same;
do
{
same = false;
randNums[i] = rand() % 999 + 100;
// Check if the newly generated number is a duplicate:
for (int check = 0; check < i; check++)
{
if (randNums[i] == randNums[check])
{
same = true;
break;
}
}
} while (same);
}
}
void displayArray(int randNum[], int elements)
{
for (int sub = 0; sub < elements; sub ++)
{
cout << "Unique Numbers: " << randNum[sub] << endl;
}
}
Hello I am currently stuck on a homework problem as I have no idea how exactly to approach the problem.
Write a program that reads in a list of integers into an array with base type
int. Provide the facility to either read this array from the keyboard or
from a file, at the user’s option. If the user chooses file input, the program
should request a file name. You may assume that there are fewer than 50
entries in the array. Your program determines how many entries there are.
The output is to be a two-column list. The first column is a list of the distinct
array elements; the second column is the count of the number of
occurrences of each element. The list should be sorted on entries in the
first column, largest to smallest.
So I were to enter: 1, 2, 1, 10, 15, 12, 2, 10, 10
The program should output something like:
List Frequency
1-----2
2-----2
10----3
15----1
I am able to sort the numbers but don't know how I would go about comparing the numbers in the array.
#include <iostream>//Input/Output Library
#include <cstdlib>
#include <iomanip>
using namespace std;//Namespace of the System Libraries
//Global Constants
const int MAX = 10;
//Function Prototypes
void input(int array[], int size);
void sort(int array[],int size);
int main(int argc, char** argv){
//Declare Variable
int array[MAX];
int size = MAX;
//Input Data
input(array, size);
sort(array, size);
cout<<"\nSort Frequency\n";
for(int i = 0; i<size; i++){
cout<<array[i]<<endl;
}
return 0;
}
void input(int a[], int size){
cout<<"Enter "<<size<<" numbers for the array: \n";
for(int i=0; i<size; i++){
cin>>a[i];
}
}
void sort(int a[],int n){
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(a[i]>a[j]){
a[i]=a[i]^a[j];
a[j]=a[i]^a[j];
a[i]=a[i]^a[j];
}
}
}
}
In addition to #stryku's answer since you only want to print frequencies, you don't even need to create the v vector:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <map>
int main() {
std::map<int, size_t> counts;
std::for_each(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(), [&counts](int k) {
++counts[k];
});
for(const auto &pair : counts)
std::cout<<pair.first <<" "<< pair.second<<"\n";
return 0;
}
Here you go (:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <map>
int main() {
std::vector<int> v;
std::map<int, size_t> counts;
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(v));
for(const auto &number : v)
++counts[number];
for(const auto &pair : counts)
std::cout<<pair.first <<" "<< pair.second<<"\n";
return 0;
}
I think your teacher will be surprised if you would explain it to him
So far, I have made a program that creates a random number using srand and rand.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
for(int x = 1; x<25;x++) {
cout << 1+ (rand()%6);
}
}
How do I store the random number using int?
How do I store the random number using int?
As mentioned in my comment, that's simply done assigning an int variable instead of outputting it:
int myRandValue = 1+ (rand()%6);
But it sounds like you want to have the whole set of generated values available for use after generating them.
You can simply store your random numbers in a std::vector<int> like this:
std::vector<int> myRandValues;
for(int x = 1; x<25;x++) {
myRandValues.push_back(1+ (rand()%6));
}
and later access them from another loop like
for(auto randval : myRandValues) {
cout << randval << endl;
}