Trouble returning an array value - c++

I keep getting an error code saying jeb has redefined itself and changing int to float or double doesn't work. This is meant to be a random number generator and my array is messing up.
#include "stdafx.h"
#include <iostream>
#include <random>
using std::cout;
using std::endl;
using std::cin;
int generate();
int numb();
int main()
{
int num = numb();
cout << num << endl;
cout << endl;
int gen = generate();
cout << gen << endl;
cout << endl;
system("Pause");
return 0;
}
int generate(float *jeb[])
{
int jeb [20] = {};
for (int i = 0; i < 20; i++) {
int rng = rand() % numb() + 1;
jeb[i] = rng;
return jeb;
}
}
int numb()
{
int choice;
cout << "Enter maximum number: ";
cin >> choice;
return choice;
}

There are several problems here:
int generate(int *jeb[])
{
int jeb [20] = {};
//...
}
Now you have two things called jeb.
Let's assume you just want one.
You could send in a pointer and fill it up
int generate(int *jeb)
{
//.. fill it up in a for loop
}
BUT this says it returns an int...
Instead of pointers, try using an array - you seem to know in advance you have 20 elements:
#include <array>
std::array<int, 20> generate()
{
std::array<int, 20> jeb;
for (int i = 0; i < 20; i++) {
int rng = rand() % numb() + 1;
jeb[i] = rng;
return jeb; //Really, wait - we haven't done the whole loop yet
}
}
Another issue might now be obvious: you are returning in the middle of the for loop. Wait until you've finished generating what you need.
std::array<int, 20> generate()
{
std::array<int, 20> jeb;
for (int i = 0; i < 20; i++) {
int rng = rand() % numb() + 1;
jeb[i] = rng;
}
return jeb; // loop now done
}

Related

Generate random number but required to have a certain number

I am trying to create a sequence of 4 different numbers and randomly generated from 0 to 100 but it must have number 86, here is what I did:
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
srand((unsigned) time(NULL));
// Loop to get 3 random numbers
for(int i = 0; i < 3; i++)
{
int random = rand() % 101;
// Print the random number
cout << random << endl;
}
cout << 86 << endl;
}
But I don't want to put 86 at the end, are there any ways to place it at any random position in the sequence ? Thank you
My approach using modern C++
#include <algorithm>
#include <iostream>
#include <array>
#include <random>
namespace {
std::default_random_engine generator(std::random_device{}());
int random(int min, int max) {
return std::uniform_int_distribution<int>{min, max}(generator);
}
}
int main() {
std::array<int, 4> elements = {86};
for (int i = 1; i < elements.size(); ++i) {
elements[i] = random(0, 100);
}
std::shuffle(elements.begin(), elements.end(), generator);
for (int nbr : elements) {
std::cout << nbr << "\n";
}
return 0;
}
You can do exactly as you said - place it in a random position. First, you store the four numbers to be generated in an array; then, you decide which position is 86; then, you fill the rest and print it.
int main()
{
srand((unsigned) time(NULL));
int nums[4];
int loc86 = rand() % 4;
for(int i = 0; i < 4; i++)
{
nums[i] = i != loc86 ? rand() % 101 : 86;
}
for(int i = 0; i < 4; i++)
{
// Print the random number
cout << num[i] << endl;
}
}
A bit offtopic, but if you really care about precision of the random number generation (and that it approaches uniform random distribution well enough), you might use pragmatic c++ random number generators as described here.
Two approaches
#include<iostream>
#include<cstdlib>
using namespace std;
int main()
{
srand((unsigned) time(NULL));
// Take a random position
const int j = rand() % 4;
// Loop to get 3 random numbers
for(int i = 0; i < 4; i++)
{
if (i == j)
cout << 86 << endl;
else
cout << rand() % 101 << end;
}
}
#include<iostream>
#include<algorithm>
#include<cstdlib>
using namespace std;
int main()
{
srand((unsigned) time(NULL));
// Fill and shuffle the array
int r[4] = {86, rand() % 101, rand() % 101, rand() % 101};
std::shuffle(std::begin(r), std::end(r));
for(int i = 0; i < 4; i++)
cout << r[i] << end;
}

C++ Array of random numbers

I have a bit of a problem with this. I've tried to create a function to return a random number and pass it to the array, but for some reason, all the numbers generated are "0".
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
int generLosNum(int);
int main()
{
srand(time(NULL));
int LosNum;
const int rozmiar = 10;
int tablica[rozmiar];
for(int i=0; i<rozmiar; i++)
{
tablica[i] = generLosNum(LosNum);
cout << tablica[i] <<" ";
}
return 0;
}
int generLosNum(int LosNum)
{
int LosowyNum;
LosowyNum = (rand() % 10);
return (LosNum);
}
So the return for your int generLosNum(int LosNum) was printing 0 because you had it returning LosNum which was initialized equaling to zero. I changed your code so it works and will print out the 10 random numbers.
#include <iostream>
#include <ctime>
#include <iomanip>
using namespace std;
int generLosNum();
int main()
{
srand(time(NULL));
int LosNum = 0;
const int rozmiar = 10;
int tablica[rozmiar];
for (int i = 0; i < rozmiar; i++)
{
tablica[i] = generLosNum();
cout << tablica[i] << " ";
}
return 0;
}
int generLosNum()
{
int LosowyNum;
LosowyNum = (rand() % 10);
return LosowyNum;
}
Change your method generLosNum to the following and the method signature to int generLosNum() and it should work.
int generLosNum()
{
return (rand() % 10);
}
Reason: As others also mentioned in the comments, you were just returning the number that you passed in as parameter and also the logic for this method doesn't even need a parameter.

Filling an 1D array in C++

I have an integer array:
int listint[10] = {1,2,2,2,4,4,5,5,7,7,};
What I want to do is to create another array in terms of the multiplicity. So I define another array by:
int multi[7]={0};
the first index of the multi array multi[0] will tell us the number of multiplicity of the array listint that has zero. We can easily see that, there is no zero in the array listint, therefore the first member would be 0. Second would be 1 spice there are only 1 member in the array. Similarly multi[2] position is the multiplicity of 2 in the listint, which would be 3, since there are three 2 in the listint.
I want to use an for loop to do this thing.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int j;
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[7] = { 0 };
for (int i = 0; i < 9; i++)
{
if (i == listint[i])
count++;
j = count;
multi[j] = 1;
}
cout << "multi hit \n" << multi[1] << endl;
return 0;
}
After running this code, I thought that I would want the multiplicity of the each element of the array of listint. So i tried to work with 2D array.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int i, j;
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[7][10] = { 0 };
for (int i = 0; i < 9; i++)
{
if (i == listint[i])
count++;
j = count;
for (j = 0; j < count; j++) {
multi[j][i] = 1;
}
}
cout << "multi hit \n" << multi[4][i] << endl;
return 0;
}
The first code block is something that I wanted to print out the multiplicity. But later I found that, I want in a array that multiplicity of each elements. SO isn't the 2D array would be good idea?
I was not successful running the code using 2D array.
Another question. When I assign j = count, I mean that that's the multiplicity. so if the value of count is 2; I would think that is a multiplicity of two of any element in the array listint.
A 2d array is unnecessary if you're just trying to get the count of each element in a list.
#include <iostream>
int main() {
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[8] = { 0 };
for (int i : listint)
++multi[i];
for (int i = 0; i < 8; ++i)
std::cout << i << ": " << multi[i] << '\n';
return 0;
}
There's also a simpler and better way of doing so using the standard collection std::map. Notably, this doesn't require you to know what the largest element in the array is beforehand:
#include <map>
#include <iostream>
int main() {
int listint[10] = {1,2,2,2,4,4,5,5,7,7,};
std::map<int, int> multi;
for (int i : listint)
multi[i]++;
for (auto [k,v] : multi)
std::cout << k << ": " << v << '\n';
}
Try this incase maps won't work for you since you're a beginner, simple:
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int j;
int listint[10] = {1,2,2,2,4,4,5,5,7,7};
int multi[8]={0};
for(int i=0; i<10; i++)
{
multi[listint[i]]++; // using listint arrays elements as index of multi to increase count.
}
for( int i=1; i<8; i++)
{
cout << "multi hit of "<<i<<" : "<< multi[i]<<endl;
}
return 0;
}
OR if numbers could get large and are unknown but sorted
#include <iostream>:
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count = 0;
int index = 0; // used to fill elements in below arrays
int Numbers[10] = {0}; // storing unique numbers like 1,2,4,5,7...
int Count[10] = {0}; // storing their counts like 1,3,2,2,2...
int listint[10] = {1, 2, 2, 2, 4, 4, 5, 5, 7, 7};
for(int i = 0; i < sizeof(listint) / sizeof(listint[0]); i++)
{
count++;
if (listint[i] != listint[i+1]) {
Numbers[index] = listint[i];
Count[index] = count;
count=0;
index++;
}
}
for(int i=0; i<index; i++)
{
cout << "multi hit of "<<Numbers[i]<<" is " << Count[i]<<endl;
}
return 0;
}

Generating a random value array without repeating

I want to make a method that generates an array with random values between 0 and 6 in it without repeating those values.
This is what I've got:
void randomArray(){
randNum = rand() % 6;
code[0] = randNum
for (int i = 1; i < 4; i++){
randNum = rand() % 6;
code[i] = randNum;
while (code[i] == code[i - 1]){
randNum = rand() % 6;
code[i] = randNum;
}
}
}
But I'm getting repeated values on the random-generated array.
PD: I also need to use a similar method to make an array of enum's.
You could do something like this:
int randomFromSet(std::vector<int>&_set)
{
int randIndex = rand() % _set.size();
int num = _set[randIndex];
_set.erase(_set.begin() + randIndex);
return num;
}
This chooses a random int from a provided set of numbers, and removes that choice from the set so that it can't be picked again.
Used like so:
std::vector<int> mySet {0,1,2,3,4,5,6};
std::cout<<randomFromSet(mySet)<<'\n;
#include <random>
#include <vector>
#include <numeric>
#include <iostream>
using std::cout;
using std::endl;
int main() {
const int sz = 7;
std::vector<int> nums(sz);
std::iota(std::begin(nums), std::end(nums), 0);
std::default_random_engine re;
int i = 8;
while(--i > 0) {
auto my_set{ nums };
std::shuffle(my_set.begin(), my_set.end(), re);
for (auto x : my_set) {
cout << x << " ";
}
cout << endl;
}
}
Im new to c++ , can I add my answer too?
its c-style c++ sorry for that.but its easy to code and to understand at the same time.
#include <iostream> //std::cout
#include <ctime> //time() function
#include <cstdlib> //rand() and srand() functions
void rand_gen(unsigned int arr[],unsigned int sizeofarray)
{
srand((unsigned int)time(0);
for (unsigned int c = sizeofarray ; c > 0 ; c--)
{
unsigned int r = rand()%sizeofarray;
if (arr[r] != 404)
{
std::cout<<"Try No."<<(sizeofarray+1)-c<<" : "<<arr[r]<<"\n";
arr[r] = 404;
} else { c++; }
}
}
int main()
{
unsigned int n[7]={0,1,2,3,4,5,6};
rand_gen(n,7);
std::cin.get();
return 0;
}

Function to find Armstrong numbers in a given range fails at some point

The assignment was to build a function to check if numbers in a range are armstrong numbers, and to add them in a vector. There are some problems when I call main, it won't execute the for loop part. I kinda think that the function is alright, because when I just call the function, there are no errors. The code is below, and I hope that you can help me.
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
std::vector<int> ArmstrongoviBrojevi (int , int );
std::vector<int> ArmstrongoviBrojevi (int p, int q) {
//function start
int z=0;
if (p<0){
std::vector<int> dodajVrijednost;
for (int i=1;i<=q;i++){
std :: string a = std:: to_string(i);
//check for length
int duzina = a.length();
int sum=0;
//check if number if armstrong
while (i>0){
int cifra=i%10;
i/=10;
sum+=pow(cifra,duzina);
}
//add to the vector
if (sum==i){
dodajVrijednost[z];
z++;
}
return dodajVrijednost;
}
}
}
//main
int main() {
std::cout << "Zadaća 1, Zadatak 1";
int a,b;
std::cout << "Molim vas unesite 2 broja" << std::endl;
std::cin >> a>>b;
std::vector<int>kopija ;
for (int g=0;g<ArmstrongoviBrojevi(a,b).size();g++){
if (g!=int(ArmstrongoviBrojevi(a,b).size())-1){
std::cout << ArmstrongoviBrojevi(a,b)[g] <<","<< std::endl;
}
else
std::cout << ArmstrongoviBrojevi(a,b)[g] << std::endl;
}
return 0;
}
There are at least two error in the ArmstrongoviBrojevi function. I guess the main one is that when condition p < 0 return false you don't return any value, but in main still trying to access it. To fix it you could declare dodajVrijednost outside of the if block and return value after it
std::vector<int> dodajVrijednost;
if (p < 0) {
...
}
return dodajVrijednost;
Another one is that dodajVrijednost[z]; should be dodajVrijednost.push_back(z);. Because you don't allocate memory for the vector somewhere before there is no element on index z. And statement dodajVrijednost[z]; alone does not make any sense.
I would also modify the main function, because now you recalculate your vector each time, it would be better to calculate result once.
std::vector<int> armstrongoviBrojevi = ArmstrongoviBrojevi(a,b);
for (int g=0;g<armstrongoviBrojevi.size();g++){
if (g!=armstrongoviBrojevi.size()-1){
std::cout << armstrongoviBrojevi[g] <<","<< std::endl;
}
else
std::cout << armstrongoviBrojevi[g] << std::endl;
}
/* Java program to find Armstrong numbers in a range */
class A{
public static void main(String[] args) {
int starting_number = 1;
int ending_number = 99999;
int c = 0;
for (int i = starting_number; i <= ending_number; i++) {
if (isArmstrong(i)) {
c++;
if(c==1)
{
System.out.print(i);
}
else{
System.out.print(", "+i);
}
} else {
}
}
}
public static boolean isArmstrong(int n) {
int no_of_digits = String.valueOf(n).length();
int sum = 0,s=0;
int value = n;
for (int i = 1; i <= no_of_digits; i++) {
int digit = value % 10;
value = value / 10;
sum = sum + (int) Math.pow(digit, no_of_digits);
}
if (sum == n) {
s=s+sum;
return true;
} else {
return false;
}
}
}
I want sum of it