Generate unique multiple random numbers - c++

I want to generate unique random numbers and add item in function of these random numbers. Here is my code :
The problem is when i verify if the number generated exist in the array with the code results.contains(randomNb) :
int nbRandom = ui->randoomNumberSpinBox->value();
//nbRandom is the number of the random numbers we want
int i = 1;
int results[1000];
while ( i < nbRandom ){
int randomNb = qrand() % ((nbPepoles + 1) - 1) + 1;
if(!results.contains(randomNb)){
//if randomNb generated is not in the array...
ui->resultsListWidget->addItem(pepoles[randomNb]);
results[i] = randomNb;
//We add the new randomNb in the array
i++;
}
}

results is an array. That's a built-in C++ type. It's not a class type and doesn't have methods. So this can't work:
results.contains(randomNb)
You probably want to use a QList instead. Like:
QList<int> results;
Add elements to it with:
results << randomNb;
Also, you have an off-by-one error in the code. You start counting from 1 (i = 1) instead of 0. This will result in missing the last number. You should change the i initialization to:
int i = 0;
With the changes, your code would become:
int nbRandom = ui->randoomNumberSpinBox->value();
//nbRandom is the number of the random numbers we want
int i = 0;
QList<int> results;
while ( i < nbRandom ){
int randomNb = qrand() % ((nbPepoles + 1) - 1) + 1;
if(!results.contains(randomNb)){
//if randomNb generated is not in the array...
ui->resultsListWidget->addItem(pepoles[randomNb]);
results << randomNb;
//We add the new randomNb in the array
i++;
}
}

Related

Reversing positive sequences in array

So, I have a cycle that goes over an array and should reverse the sequence of consecutive positive numbers, but it seems to count excess negative number as a part of a sequence, thus changing its position. I can't figure the error myself, and will be happy to hear any tips!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
int Arr[100];
int Arr2[100];
int main()
{
srand(time(NULL));
int n, x;
bool seq = false;
int ib = 0;
printf("Starting array\n");
for (n = 0; n < 100; Arr[n++] = (rand() % 101) - 50);
for (n = 0; n < 100; printf("%3d ", Arr[n++]));
putchar('\n');
for (n = 0; n < 100; n++) //sorting
{
if (Arr[n] > 0) //check if the number is positive
{
if (seq == false) //if it isn't the part of a sequence
{
seq = true; ib = n; //declare it now is, and remember index of sequence's beginning
}
else
seq = true; //do nothing if it isn't first
}
else //if the number is negative
{
if (seq==true) //if sequence isn't null
for (x = n; ib <= n; ib++, x--) //new variable so that n will stay unchanged,
number of iterations = length of sequence
{
Arr2[x] = Arr[ib]; //assigning array's value to a new one,
reversing it in the process
}
seq = false; //declaring sequence's end
Arr2[n + 1] = Arr[n + 1]; //assigning negative numbers at the same place of a new array
}
}
printf("Modified array\n");
for (n = 0; n < 100; printf("%3d ", Arr2[n++]));
putchar('\n');
system('pause');
return 0;
}
following what we discussed in comments, i listed couple of rules here to shape my answer around it.
Rules :
the sequence of elements can be varied. so if there are 5 positive numbers in a row within an array, we would be reversing the 5 elements. for example
array[5] = {1,2,3,4,5} would become array[5]{5,4,3,2,1}
if single positive number neighboured by negatives, no reverse can happen
array[4] = {-1,0,-2,1} would result the same array
no processing happens when a negative number is discovered.
based on these rules.
here is what I think going wrong in your code.
Problems :
1- consider thisarray = {1,2,-1}. notice that the last value is negative. because of this. the following code would run when the 3rd index of the array is processed;
` Arr2[n + 1] = Arr[n + 1]; //assigning negative numbers at the same place of a new array`
this is a no-no. since you are already at the end of the Arr2 n+1 would indicate that there is a 4th element in the array. (in your case 101h element of the array) this would cause an undefined behaviour.
2 - consider the same array mentioned above. when that array is looped, the outcome would be array = {-1,2,1} . the -1 and 1 are swapped instead of 1 and 2.
3 - you are assigning ib = n whenever a negative number is found. because whenever a negative value is hit, seq=false is forced. But the ib, never been put into use until a next negative number is found. here is an example;
array = {...2, 6}
in such scenario, 2 and 6 would never get reversed because there is no negative value is following this positive sequence.
4 - consider this scenario arr = {-10,-1,....} this would result in arr = {0,-1,....}. This happens because of the same code causing the undefined behaviour problem mentioned above.
`Arr2[n + 1] = Arr[n + 1];`
Suggestion
Most of the problems mentioned above is happening because you are trying to figure out the sequence of the positive numbers when a negative number is found.
else //if the number is negative
{
if (seq==true) //if sequence isn't null
for (x = n; ib <= n; ib++, x--) //new variable so that n will stay unchanged,
number of iterations = length of sequence
{
Arr2[x] = Arr[ib]; //assigning array's value to a new one,
reversing it in the process
}
you should completely get rid of that and completely ignore the negative numbers unless you forgot to mention in your question some key details. instead just focus on the positive numbers. I'm not going to send you the entire code but here is how I approached the problem. feel free to let me know if you need help and I would be more then happy to go through in detail.
start your for loop as usual.
for (n = 0; n < 100; n++) //sorting
{
don't try to do anything when an element in an array is a negative value.
if (Arr[n] > 0) //check if the number is positive
if the number is positive. create recording the sequence indices. for one, we know the sequence will start at n once the `if (Arr[n] > 0) true. so we can do something like this;
int sequenceStart = n;
we also need to know when the positive number sequence ends.
int sequenceEnd = sequenceStart;
the reason for int sequenceEnd = sequenceStart; is because we going to start using the same n value to start with. we can now loop through the array and increment the sequenceEnd until we reach to a negative number or to the end of the array.
while (currentElement > 0)
{
n++;//increment n
if(n < arraySiz) //make sure we still in the range
{
currentElement = Arr[n]; // get the new elemnet
if (currentElement > 0)
{
sequenceEnd++;
}
}
else
break; // we hit to a negative value so stop the while loop.
}
notice the n++;//increment n this would increment the n++ until we reach to the negative number. which is great because at the end of the sequence the for loop will continue from the updated n
after the while loop, you can create an array that has the same size as the number of sequences you iterated through. you can then store the elements from starting arr[sequenceStart] and arr[sequenceEnd] this will make the reversing the sequence in the array easier.

I Need help Checking for Duplicate Integers in a 2-D Array

I am asked to create a unique (no two numbers are the same) set of random numbers
(the user inputs the row and column dimensions 'd1' and 'd2')
I am totally lost as to how to compare each element of both arrays to see if they're duplicates.
(Max is the largest value to be generated)
void RandomArray(IntArrayPtr* m, int d1, int d2, int max)
{
for (int i = 0; i < d1; i++)
{
for (int j = 0; j < d2; j++)
{
m[i][j] = (rand() % max + 1);
if (i > 0 && j > 0)
{
if (m[i][j] == m[i][j - 1] || m[i][j] == m[i-1][j])
{
m[i][j] = (rand() % max+ 1);
}
}
}
}
}
Store every value in C++ datastructure called unordered_set and check if the random value generated exists in this set or not.
Reference on how to use unordered_set: https://stackoverflow.com/a/24644253/3326925
PS: I'm not that good in C++ but can tell you to relate this with HashSet used in Java.
Another solution is generating a set of n random numbers, using something like numbers.add( n + random() ) where n is the last number added and random() is a random increment (different each time).
Once you have the set, you can use std::random_shuffle(...)on it. And add the elements 1 by 1 on the matrix.

Sudoku Blanks - c++

I have to write a program that takes in a Sudoku square(with all slots filled) and randomly assigns 25 blanks to be filled in. This is what I have so far but because this code has the chance to generate the same position in the array more than once I'm getting a varying number of blanks(17-21). I'm wondering if there is a simple way to get it to output 25 blanks no matter what. My print function inserts a blank if the value is zero at any spot in the array.
void insertBlanks(int square[9][9])
{
srand(time(NULL));
int i = 0;
while(i < 25)
{
int tempOne = rand() % 9;
int tempTwo = rand() % 9;
square[tempOne][tempTwo] = 0;
i = i + 1;
}
}
You should check if a 0 is already there.
if(square[tempOne][tempTwo] != 0)
{
square[tempOne][tempTwo] = 0;
i = i + 1;
}

Segmentation Fault while simulating top-down addition in C++

I'm trying to write a program in C++ that takes in two strings containing numbers and adds them together to return a "sum" (which is also a string).
I've written comparable programs in Java and Python, so I decided that while learning C++, I might as well write something comparable. I don't know why I'm receiving the errors, and I'm not receiving any errors while compiling with Visual Studio or g++.
Below is the reference to the function in question in the main program.
Number base(NULL);
Number r = base.addNums("1", "1");
cout << r.toString() << endl;
I have ensured that I have a constructor as follows for the reference to the addNums function:
Number(void){}
I wrote some comments to try and explain my thought process while writing the header file. The method in question is as follows:
Number addNums(string in1, string in2){
// Calling number 1: X, and number 2: Y
const char* x;
const char* y;
x = in1.c_str();
y = in2.c_str();
// Flag for one number having more digits
bool flag = false;
// Flag for X having more digits
bool xIsBigger = false;
// For storing the sum later
string summ = "";
// Check and see if the flags are needed
if (!(strlen(x) == strlen(y))){
flag = true;
if (strlen(x) > strlen(y)){
xIsBigger = true;
}
}
// Prepend the zeroes to the necessary variable
// to make it work as written addition does
if (flag){
if (xIsBigger){
string zeroes;
for (unsigned int i = 0; i < (strlen(x) - strlen(y)); ++i){
zeroes += "0";
}
string newYStr = zeroes + in2;
const char* newY = newYStr.c_str();
// Add zeroes to Y variable
y = newY;
} else{
string zeroes;
for (unsigned int i = 0; i < (strlen(y) - strlen(x)); ++i){
zeroes += "0";
}
string newXStr = zeroes + in1;
const char* newX = newXStr.c_str();
// Add variables to X value
x = newX;
}
}
// If we encounter x + y > 9, we need this
int carry = 0;
// Current digit being processed
char digitX, digitY;
// Digit to be carried
char toCarry;
// Iterate through the number right to left
// to simulate top-down addition
for (int i = strlen(x) - 1; i >= 0; --i){
digitX = x[i];
digitY = y[i];
// If we're carrying a 1, add it to the top number
if (carry > 0){
digitX += 1;
carry = 0;
}
// Add together the two numbers stored in characters
int currentSum = atoi(&digitX) + atoi(&digitY);
// If x + y > 9, we need to carry
if (currentSum > 9){
string sumString = "" + currentSum;
// Max possible is 9 + 9, so we only have to carry 1
carry = 1;
// Add the second digit in the number to the position in the sum
summ = sumString.at(1) + summ;
}
// Didn't need a carry
else{
string sumString = "" + currentSum;
summ = sumString + summ;
}
}
// Return the object containing the sum
return Number(summ);
}
I'm relatively new to the use of pointers, but in the process of learning some more of the language and writing this program, and through extensive googling of syntax and language-specifics, I've been forced into what I feel is the need to use them.
I'm very sorry I cannot provide more information and I appreciate any help or critique that can help me.
Thanks in advance!
'string newYStr' may be going out of scope? Try declaring it in the top and then check.

Recursive function that takes the sum of odd integers

The program runs but it also spews out some other stuff and I am not too sure why. The very first output is correct but from there I am not sure what happens. Here is my code:
#include <iostream>
using namespace std;
const int MAX = 10;
int sum(int arrayNum[], int n)
{
int total = 0;
if (n <= 0)
return 0;
else
for(int i = 0; i < MAX; i ++)
{
if(arrayNum[i] % 2 != 0)
total += arrayNum[i];
}
cout << "Sum of odd integers in the array: " << total << endl;
return arrayNum[0] + sum(arrayNum+1,n-1);
}
int main()
{
int x[MAX] = {13,14,8,7,45,89,22,18,6,10};
sum(x,MAX);
system("pause");
return 0;
}
The term recursion means (in the simplest variation) solving a problem by reducing it to a simpler version of the same problem until becomes trivial. In your example...
To compute the num of the odd values in an array of n elements we have these cases:
the array is empty: the result is trivially 0
the first element is even: the result will be the sum of odd elements of the rest of the array
the first element is odd: the result will be this element added to the sum of odd elements of the rest of the array
In this problem the trivial case is computing the result for an empty array and the simpler version of the problem is working on a smaller array. It is important to understand that the simpler version must be "closer" to a trivial case for recursion to work.
Once the algorithm is clear translation to code is simple:
// Returns the sums of all odd numbers in
// the sequence of n elements pointed by p
int oddSum(int *p, int n) {
if (n == 0) {
// case 1
return 0;
} else if (p[0] % 2 == 0) {
// case 2
return oddSum(p + 1, n - 1);
} else {
// case 3
return p[0] + oddSum(p + 1, n - 1);
}
}
Recursion is a powerful tool to know and you should try to understand this example until it's 100% clear how it works. Try starting rewriting it from scratch (I'm not saying you should memorize it, just try rewriting it once you read and you think you understood the solution) and then try to solve small variations of this problem.
No amount of reading can compensate for writing code.
You are passing updated n to recursive function as argument but not using it inside.
change MAX to n in this statement
for(int i = 0; i < n; i ++)
so this doesnt really answer your question but it should help.
So, your code is not really recursive. If we run through your function
int total = 0; //Start a tally, good.
if (n <= 0)
return 0; //Check that we are not violating the array, good.
else
for(int i = 0; i < MAX; i ++)
{
if(arrayNum[i] % 2 != 0) //THIS PART IS WIERD
total += arrayNum[i];
}
And the reason it is wierd is because you are solving the problem right there. That for loop will run through the list and add all the odd numbers up anyway.
What you are doing by recursing could be to do this:
What is the sum of odd numbers in:
13,14,8,7,45,89,22,18,6,10
+
14,8,7,45,89,22,18,6
+
8,7,45,89,22,18
+
7,45,89,22 ... etc
And if so then you only need to change:
for(int i = 0; i < MAX; i ++)
to
for(int i = 0; i < n; i ++)
But otherwise you really need to rethink your approach to this problem.
It's not recursion if you use a loop.
It's also generally a good idea to separate computation and output.
int sum(int arrayNum[], int n)
{
if (n <= 0) // Base case: the sum of an empty array is 0.
return 0;
// Recursive case: If the first number is odd, add it to the sum of the rest of the array.
// Otherwise just return the sum of the rest of the array.
if(arrayNum[0] % 2 != 0)
return arrayNum[0] + sum(arrayNum + 1, n - 1);
else
return sum(arrayNum + 1, n - 1);
}
int main()
{
int x[MAX] = {13,14,8,7,45,89,22,18,6,10};
cout << sum(x,MAX);
}