Array exercise code not working as intended - c++

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

Related

Generating a sequence of different numbers

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);
}

Algorithm crashing

int function(int A[], int n)
{
int i = 0;
int sum = 0;
int amount = 0;
while(i<n) {
if(A[i] > 0) {
sum=sum+A[i];
amount++;
}
else {
i++;
}
}
while(!(i<n)) {
if(ile>0){
return sum/amount;
} else {
return 0;
}
}
}
I am generating random array of numbers between 0-10 , Im trying to use this with this algorithm, but all the time im getting result 6422260. Can someone tell me how should I approach this?
int n;
cin >> n;
int arr[n];
srand(time(NULL));
for (int i = 0; i < 10; i++)
{
arr[i] = rand() % 10;
}
function(arr, n);
Here is a solution to your problem:
#include <random>
#include <iostream>
void fill(int arr[]);
int random(int from, int to);
using namespace std;
int main(void)
{
int arr[10];
fill(arr);
for(int i = 0; i<10; i++)
printf("%d ", arr[i]);
return 0;
}
void fill(int arr[]){
for(int i=0;i<(*(&arr + 1) - arr);i++){
arr[i] = random(0, 10);//adjust accordngly
}
}
int random(int from, int to){
std::random_device dev;
std::mt19937 rng(dev());
std::uniform_int_distribution<std::mt19937::result_type> dist6(from, to); // distribution in range [from, to]
return dist6(rng);
}
Your problem is you are not generating random numbers your algorithm is generating the same set of numbers! You need a logic to generate random number. Usually they are generated from system time ...
Attribution : https://stackoverflow.com/a/13445752/14911094
#alkantra, your problem is not generating random numbers. Basically, you are asking your question wrong. If required, it should be separated:
What's this code doing?
How to generate a random sequence?
The algorithm you are trying to achieve is for calculating arithmetic mean (or simply average). If you remember the formula for calculating arithmetic mean you learnt in school, the formula is:
arithmetic mean = sum/n
where
sum - sum of all numbers (from the given array[] of course)
n - count of the numbers in the given array[]
The purpose of the sum variable is to sum all given numbers, if not equal to 0, and n(in your code amount) just increases for every number added to sum.
And in the end the function should return, as the formula says, sum/amount. I could write this code, i.e. the whole program (except for the random()), though it's quite easy, so I'll leave it up to you.
About the random library, I don't know much, but there are may resources on the net, so take your time.
https://www.tutorialspoint.com/cplusplus-program-to-generate-random-number
https://www.tutorialspoint.com/rand-and-srand-in-c-cplusplus

Finding the Lowest sum in a 2d array by picking 1 element from each row

I am writing a code where 2d matrix array is given and by choosing 1 element from each row you must output the smallest sums. Sums as in you must give n number of minimum sums
#include<iostream>
#include<math.h>
using namespace std;
int main() {
int n;
cin>>n;
int hist[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>hist[i][j];
}
}
int num=pow(n,n);
int sum[num];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
sum[i]=sum[i]+hist[i][j];
}
}
for(int i=0;i<n;i++){
cout<<sum[i]<<" ";
}
return 0;
}
example input would be:
3
1 8 5
9 2 5
10 7 6
The output will be
9 10 12
since 1+2+6=9; 1+2+7=10; 1+2+10
The main problem I am facing would be that I can't find the lowest sum or even the sums I tried to brute force it put it won't work.
Could you help me fix the code so that at least I could find the sums?
Many problems with your code (it's not even legal C++). But the problem that is causing your current question is that you must initialise sum to zero. at the moment you have garbage values in sum.
int sum[num] = {0};
Some other issues
int num=pow(n,n);
This calculates n to the power of n, but there are only n squared sums. So this would be better
int sum[n*n] = {0};
But the big issue, the issue that makes your code illegal C++, is that in C++ array dimensions must be compile time constants not variables. So this
int hist[n][n];
and this
int sum[num];
are not legal C++. They are legal in C, which is why your compiler is accepting them, but not every C++ compiler would. Since you are trying to write C++ code you should use a vector. Here's your code rewritten to use vectors.
#include <vector>
using std::vector;
...
vector<vector<int>> hist(n, vector<int>(n));
...
vector<int> sum(num, 0);
...
That's it nothing else needs to change.
Instead of brute forcing, why not realize that the smallest path is simply the smallest element of each row and the second smallest path is the smallest element of the first n-1 rows, and the second smallest element of n.
You can elegantly express this by sorting the rows of the matrix first and then keeping a counter of where you are at each row:
#include <algorithm>
#include <iostream>
#include <vector>
struct path {
path(int n) : n(n), indexes(n) {}
// Add one to last row index, then carry over to previous rows.
path& operator ++() {
indexes.back()++;
for (int i = n-1; i >= 0; i--) {
if (indexes[i] == n) {
indexes[i] = 0;
indexes[i-1]++;
} else {
break;
}
}
return this;
}
int n;
std::vector<int> indexes;
};
Now your problem is as simple as:
int main() {
int n;
cin>>n;
std::vector<std::vector<int>> hist(n, std::vector<int>(n));
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>hist[i][j];
}
// sort each row after reading
std::sort(hist[i].begin(), hist[i].end());
}
int num_minimum_sums = n;
path p(n);
while (num_minimum_sums-- > 0) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += hist[i][p.indexes[i]];
}
std::cout << sum << std::endl;
++p;
}
}

c++ random number generation not random

I'm trying to perform a random shuffle of a vector using Visual Studio 2013 C++. The following is the code that I have
static void shuffle(vector<int>& a){
int N = a.size();
unsigned long long seed = chrono::system_clock::now().time_since_epoch().count();
default_random_engine generator(seed);
for (int i = 0; i < N; i++){
uniform_int_distribution<int> distribution(0,(N-1)-i);
int r = i + distribution(generator);
swap(a[i], a[r]);
}
}
My problem is when I call this method multiple times in succession the shuffle is not random. What could be wrong with the code?
Any help would be much appreciated.
Uhm, I'm curious... why isn't the following sufficient for your needs:
static void shuffle(vector<int>& a)
{
// There are better options for a seed here, but this is what you used
// in your example and it's not horrible, so we'll stick with it.
auto seed (std::chrono::system_clock::now().time_since_epoch().count());
// Don't bother writing code to swap the elements. Just ask the standard
// library to shuffle the vector for us.
std::shuffle(std::begin(a), std::end(a), std::default_random_engine(seed));
}
std::shuffle dosent remove duplicates, it just swaps the positions of the random numbers generated.
How can I efficiently select several unique random numbers from 1 to 50, excluding x?
You can home cook your own shuffle code otherwise:
#include <ctime>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
void myShuffleWithNoRepeats( int random_once_buf[] , int size=100)
{
srand(time(0));
for (int i=0;i<size;i++)
{
// call made to rand( ) , stored in random_once_buf[ ]
random_once_buf[i]=rand() % 100;
//////////////////////////////////////////////////////////////////////////////////////
// The line below generates unique random number only once //
// //
// the variable i is the random_once_buffer[i] buffer array index count, //
// j is the check for duplicates, j goes through the random_once_buffer[i] buffer //
// from 0 to i at every iteration scanning for duplicates, reversing one step if one duplicate is found.. //
//////////////////////////////////////////////////////////////////////////////////////
for(int j=0;j<i;j++) if (random_once_buf[j] == random_once_buf[i]) i--;
}
cout<<" \n\n\n ";
}
int main(void)
{
const int size=100 ;
int random_once_buffer[100] ;
// Call made to function myShuffleWithNoRepeats( )
myShuffleWithNoRepeats( random_once_buffer , size );
// Loop to display the array random_once_buffer[ ]
for ( int i=0;i<size;i++) cout<<""<<random_once_buffer[i]<<"\t";
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}

simple prime finder freezing due to large integers C++

I took it upon myself to learn C++ a few days ago. I have just written a program to find prime numbers, up to a user inputted value, and write these values to a file. The program works fine with numbers up to the order of 100,000 - 500,000. But, if I try to go to 1,000,000 the program freezes. Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
long pp, z,counter,lim,indyCounter;
bool isPrime=false;
ofstream myfile;
myfile.open("E:\\Program Files (x86)\\C++ Programs\\PrimeFinder\\Primes.txt");
cout<<"up to what number would you like to calculate primes? ";
cin>>lim;
cout<<endl;
long ps[lim]; //real-time array of primes
pp=3; //prospective prime
ps[0]=2; //initializing prime array with first prime number
counter=1;
indyCounter=1;
for(int y=1; y<=lim;y++)
{
ps[y]=1;
}
for(int z=0; z<=lim; z++)
{
for(int x=0;x<counter;x++)
{
if(pp%ps[x]!=0)
{
isPrime = true;
}
if(pp%ps[x]==0 && ps[x]!=1)
{
isPrime=false;
break;
}
}
if(isPrime)
{
ps[indyCounter]=pp;
indyCounter++;
}
counter++;
pp++;
}
for(int y=0; y<=lim-1;y++)
{
if(ps[y]!=1)
{
myfile<<ps[y]<<endl;
}
}
myfile.close();
return 0;
}
please excuse my beginners code, and all advice is much appreciated!
Thanks,
Steve
The default stack size on Windows is only 8MB, and an array of 1000000 longs requires 8MB, so you're overflowing the stack. You need to allocate your array on the heap instead.