linear search for number vector in c++ - c++

I am trying to output 9 random non repeating numbers. This is what I've been trying to do:
#include <iostream>
#include <cmath>
#include <vector>
#include <ctime>
using namespace std;
int main() {
srand(time(0));
vector<int> v;
for (int i = 0; i<4; i++) {
v.push_back(rand() % 10);
}
for (int j = 0; j<4; j++) {
for (int m = j+1; m<4; m++) {
while (v[j] == v[m]) {
v[m] = rand() % 10;
}
}
cout << v[j];
}
}
However, i get repeating numbers often. Any help would be appreciated. Thank you.

With a true random number generator, the probability of drawing a particular number is not conditional on any previous numbers drawn. I'm sure you've attained the same number twice when rolling dice, for example.
rand(), which roughly approximates a true generator, will therefore give you back the same number; perhaps even consecutively: your use of % 10 further exacerbates this.
If you don't want repeats, then instantiate a vector containing all the numbers you want potentially, then shuffle them. std::shuffle can help you do that.
See http://en.cppreference.com/w/cpp/algorithm/random_shuffle

When j=0, you'll be checking it with m={1, 2, 3}
But when j=1, you'll be checking it with just m={2, 3}.
You are not checking it with the 0th index again. There, you might be getting repetitions.
Also, note to reduce the chances of getting repeated numbers, why not increase the size of random values, let's say maybe 100.
Please look at the following code to get distinct random values by constantly checking the used values in a std::set:
#include <iostream>
#include <vector>
#include <set>
int main() {
int n = 4;
std::vector <int> values(n);
std::set <int> used_values;
for (int i = 0; i < n; i++) {
int temp = rand() % 10;
while (used_values.find(temp) != used_values.end())
temp = rand() % 10;
values[i] = temp;
}
for(int i = 0; i < n; i++)
std::cout << values[i] << std::endl;
return 0;
}

Related

find the all possible sum in a matrix

I am trying to write a code that find the sum of all the possible numbers in a 2d matrix.
But the catch is that you must choose one element from one row.
#include <algorithm>
#include <iostream>
#include <vector>
#include <climits>
#include <math.h>
using namespace std;
int main() {
int n;
cin>>n;
int array[n][n]={0};
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
cin>>array[i][j];
}
}
int power=pow(n,n);
int sum[power]={0};
for(int i=0;i<power;i++){
for(int j=0;j<n;j++){
for(int l=0;l<n;l++){
sum[i]=sum[i]+array[j][l];
}
}
}
for(int i=0;i<power;i++){
cout<<sum[i]<<" ";
}
return 0;
}
this code only brings out the sum of all the elements in the 2d array. So i need help trying to find all the possible sum given one element from each row is chosen for each sum.
2
1 1
1 2
2, 3, 2, 3
this should be the output but it only gives out 5
Your core loop is all wrong. If you want sum[i] to contain the values for a given path, you need to treat i as if it were a path through the matrix.
In general, treat i as a number in base n (=2 for your example).
That means
i = idx_1 * n^(n-1) + idx_2 * n^(n-2) + ... + idx_n
You can recover the various indexes by repeatedly dividing by n and taking the remainder:
for(uint64_t i=0;i<power;i++){
sum[i] = 0;
uint64_t encoded_index = i;
for (size_t j = 0; j < n; j++) {
uint64_t index_j = encoded_index % n;
encoded_index /= n;
sum[i] += hist[j][index_j];
}
}
And of course this trick only works if n*n < 2**64 (as uint64_t is 64 bits).
For a more general approach see my answer to your other question.

Why does the compiler skip the for-loop?

I have tried to do some practice with vector, and I made a simple for loop to calculate the sum of the elements within the vector. The program did not behave in the way I expect, so I try to run a debugger, and to my surprise, somehow, the compiler skips the for loop altogether, and I have not come up with a reasonable explanation.
//all code is written in cpp
#include <vector>
#include <iostream>
using namespace std;
int simplefunction(vector<int>vect)
{
int size = vect.size();
int sum = 0;
for (int count = 0; count == 4; count++) //<<--this for loop is being skipped when I count==4
{
sum = sum + vect[count];
}
return sum; //<<---the return sum is 0
}
int main()
{
vector<int>myvector(10);
for (int i = 0; i == 10; i++)
{
myvector.push_back(i);
}
int sum = simplefunction(myvector);
cout << "the result of the sum is " << sum;
return 0;
}
I have done some research, and usually the ill-defined for loop shows up when the final condition cannot be met (Ex: when setting count-- instead of count++)
Your loop's conditions are wrong, as they are always false!
Look at to the loops there
for (int i = 0; i == 10; i++)
// ^^^^^^^-----> condition : is it `true` when i is 0 (NO!!)
and
for (int count=0; count==4; count++)
// ^^^^^^^^^-----> condition : is it `true` when i is 0 (NO!!)
you are checking i is equal to 10 and 4 respectively, before incrementing it. That is always false. Hence it has not executed further. They should be
for (int i = 0; i < 10; i++) and for (int count=0; count<4; count++)
Secondly, vector<int> myvector(10); allocates a vector of integers and initialized with 0 s. Meaning, the loop afterwards this line (i.e. in the main())
for (int i = 0; i == 10; i++) {
myvector.push_back(i);
}
will insert 10 more elements (i.e. i s) to it, and you will end up with myvector with 20 elements. You probably meant to do
std::vector<int> myvector;
myvector.reserve(10) // reserve memory to avoid unwanted reallocations
for (int i = 0; i < 10; i++)
{
myvector.push_back(i);
}
or simpler using std::iota from <numeric> header.
#include <numeric> // std::iota
std::vector<int> myvector(10);
std::iota(myvector.begin(), myvector.end(), 0);
As a side note, avoid practising with using namespace std;

How to find the minimun of an array?

I was trying to solve this question
but codechef.com says the answer is wrong.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int t, n, diff, mindiff;
cin >> t;
cin >> n;
int val[n];
while(t--)
{
mindiff = 1000000000;
for(int i = 0; i<n; i++)
{
cin >> val[i];
}
int a = 0;
for(a = 0; a<n ; a++)
{
for(int b=a+1; b<n ; b++)
{
diff = abs(val[a] - val[b]);
if(diff <= mindiff)
{
mindiff = diff;
}
}
}
cout << mindiff << endl;
}
return 0;
}
The results are as expected (for at least the tests I did) buts the website says its wrong.
There are a few things in your code that you should change:
Use std::vector<int> and not variable-length arrays (VLA's):
Reasons:
Variable length arrays are not standard C++. A std::vector is standard C++.
Variable length arrays may exhaust stack memory if the number of entries is large. A std::vector gets its memory from the heap, not the stack.
Variable length arrays suffer from the same problem as regular arrays -- going beyond the bounds of the array leads to undefined
behavior. A std::array has an at() function that can check boundary access when desired.
Use the maximum int to get the maximum integer value.
Instead of
mindif = 1000000000;
it should be:
#include <climits>
//...
int mindiff = std::numeric_limits<int>::max();
As to the solution you chose, the comments in the main section about the nested loop should be addressed.
Instead of a nested for loop, you should sort the data first. Thus finding the minimum value between two values is much easier and with less time complexity.
The program can look something like this (using the data provided at the link):
#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
int main()
{
int n = 5;
std::vector<int> val = {4, 9, 1, 32, 13};
int mindiff = std::numeric_limits<int>::max();
std::sort(val.begin(), val.end());
for(int a = 0; a < n-1 ; a++)
mindiff = std::min(val[a+1] - val[a], mindiff);
std::cout << mindiff;
}
Output:
3
To do this you can use a simple for():
// you already have an array called "arr" which contains some numbers.
int biggestNumber = 0;
for (int i = 0; i < arr.size(); i++) {
if (arr[i] > biggestNumber) {
biggestNumber = arr[i];
}
}
arr.size will get the array's length so that you can check every value from the position 0 to the last one which is arr.size() - 1 (because arrays are 0 based in c++).
Hope this helps.

Copying elements from one array to another c++

I have looked and looked and am still lost on how to copy or get elements from an array and put them into new arrays ( divide and conquer is the goal).
I have an array that generates 100 random numbers. I need to split the random numbers into 4 smaller arrays obviously containing 25 elements and not have any duplicates. I have read about using pointers, but honestly I don't understand why even use a pointer. Why do I care about another variables address?
I don't know how to do this. Here is my code so far:
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
// Seed the random number generator
srand(time(NULL));
//create an array to store our random numbers in
int Orignumbers[100] = {};
// Arrays for the divide and conquer method
int NumbersA [25] = {};
int NumbersB [25] = {};
int NumbersC [25] = {};
int NumbersD [25] = {};
//Generate the random numbers
for(int i =0; i < 100; i++)
{
int SomeRandomNumber = rand() % 100 + 1;
// Throw random number into the array
Orignumbers[i] = SomeRandomNumber;
}
// for(int i = 0; i < ) started the for loop for the other arrays, this is where I am stuck!!
// Print out the random numbers
for(int i = 0; i < 100; i++)
{
cout << Orignumbers[i] << " , ";
}
}
"divide and conquer" is rather easy; when copying into NumbersA and so forth, you just have to access your Originnumbers with a proper offset, i.e. 0, 25, 50, and 75:
for(int i = 0; i < 25; i++) {
NumbersA[i] = Orignumbers[i];
NumbersB[i] = Orignumbers[i+25];
NumbersC[i] = Orignumbers[i+50];
NumbersD[i] = Orignumbers[i+75];
}
The thing about "no duplicates" is a little bit more tricky. Generating a random sequence of unique numbers is usually solved through "shuffling". Standard library provides functions for that:
#include <random>
#include <algorithm>
#include <iterator>
#include <vector>
int main()
{
std::random_device rd;
std::mt19937 g(rd());
int Orignumbers[100];
//Generate the random numbers without duplicates
for(int i =0; i < 100; i++) {
Orignumbers[i] = i+1;
}
std::shuffle(Orignumbers, Orignumbers+100, g);
// Arrays for the divide and conquer method
int NumbersA [25] = {};
int NumbersB [25] = {};
int NumbersC [25] = {};
int NumbersD [25] = {};
for(int i = 0; i < 25; i++) {
NumbersA[i] = Orignumbers[i];
NumbersB[i] = Orignumbers[i+25];
NumbersC[i] = Orignumbers[i+50];
NumbersD[i] = Orignumbers[i+75];
}
// Print out the random numbers
for(int i = 0; i < 100; i++)
{
cout << Orignumbers[i] << " , ";
}
}
Problem:
The program can't be guaranteed to have no duplicate value as the rand() function can generate any random sequence and that may include the decimal value of 99 for 99 times though probability is very low but chances are.
Example:
for(loop=0; loop<9; loop++)
printf("%d", Rand()%10);
If looped for 10 times, it may result some values like:
Output: 6,1,1,1,2,9,1,3,6,9
Compiled Successfully:
Hence, no certainity that values won't repeat
Possibly Solution:
There could be a solution where you can place the values in OriginalArray and compare the rand() generate values against the OriginalArray values.
For first iteration of loop, you can directly assign value to OriginalArray then from 2nd iteration of loop you've to compare rand() value against OriginalArray but insertion time consumption may be higher than O(NN) as rand() function may repeat values.
Possibly Solution:
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
int Orignumbers[100] ;
int NumbersA [25] ,
NumbersB [25] ,
NumbersC [25] ,
NumbersD [25] ;
srand(time(NULL));
for(int i =0; i < 100; i++){
Orignumbers[i] = rand() % 100+1;
for(int loop=0; loop<i; loop++) {
if(Orignumber[loop] == Orignumber[i] ) {
i--;
break;
}
}
}
//Placing in four different arrays thats maybe needed.
for(int i = 0; i <25; i++ ) {
NumbersA[i] = Orignumbers[i];
NumbersB[i] = Orignumbers[i+25];
NumbersC[i] = Orignumbers[i+50];
NumbersD[i] = Orignumbers[i+75];
}
for(int i = 0; i < 99; i++)
cout << Orignumbers[i] << " , ";
}
As you tagged your question with C++ then forget about old-fashion arrays, let's do it C++ style.
You want to split your array into 4 arrays and they should not have duplicate numbers, so you can't have a number 5 times in your original array, because then surely one of your 4 arrays will have a duplicate one, So here is the way I propose to do it :
#include <set>
#include <ctime>
#include <vector>
int main() {
std::multiset<int> allNums;
std::srand(unsigned(std::time(0)));
for (int i = 0; i < 100; ++i) {
int SomeRandomNumber = std::rand() % 100 + 1;
if (allNums.count(SomeRandomNumber) < 4) {
allNums.insert(SomeRandomNumber);
}
else {
--i;
}
}
std::vector<int> vOne, vTwo, vThree, vFour;
for (auto iter = allNums.begin(); iter != allNums.end(); ++iter) {
vOne.push_back(*iter);
++iter;
vTwo.push_back(*iter);
++iter;
vThree.push_back(*iter);
++iter;
vFour.push_back(*iter);
}
system("pause");
return 0;
}
EDIT : As you mentioned in the comments, you just want to find a number in an array, so how about this :
for (int i = 0; i < 100; ++i) {
if (origArray[i] == magicNumber) {
cout << "magicNumber founded in index " << i << "of origArray";
}
}
On some situations, even on C++, the use of arrays might be preferable than vectors, for example, when dealing with multidimensional arrays (2D, 3D, etc) that needs to be continuous and ordered on the memory. (e.g. later access by other applications or faster exporting to file using formats such as HDF5.)
Like Jesper pointed out, you may use Copy and I would add MemCopy to copy the content of an array or memory block into another.
Don't underestimate the importance of pointers, they may solve your problem without the need doing any copy. A bit like Stephan solution but without the need of the index variable "i", just having the pointers initialized at different places on the array. For a very large number of elements, such strategy will save some relevant processing time.

how to generate evenly distributed n-permutation from range 0 to m (m<n)

repeating of a number is allowed but the probability is limited
for example:
giving a number sequence 0-8,i want to generate a 25 number random sequence,the max repeate time of a digit is 3.
One relatively foolproof method is rejection sampling. Generate 25 numbers independently. If any number appears more than 3 times, throw them all away and try again. This method has poor worst-case performance, but it's so simple that you won't have to worry that you've accidentally introduced unwanted correlations.
As far as I understand you need something like this (Reworked according to comment below):
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <iostream>
using std::vector;
using std::cout;
vector<int> Generate(const vector<int> & numbers, int generateN, int maxRepeatN)
{
vector<int> longList(numbers.size() * maxRepeatN);
for(int i = 0; i < numbers.size(); i++)
for(int j = 0; j < maxRepeatN; j++)
longList[i * maxRepeatN + j] = numbers[i];
vector<int> result(generateN);
for(int i = 0; i < generateN; i++)
{
int id = rand() % longList.size();
result[i] = longList[id];
longList.erase(longList.begin() + id);
}
return result;
}
int main()
{
srand((unsigned)time(0));
vector<int> numbers = {0, 1, 2, 3, 4, 5, 6, 7, 8}
vector<int> result = Generate(numbers, 25, 3);
for(int i = 0; i < result.size(); i++)
cout << result[i] << " ";
return 0;
}
Idea of algorithm is that you create long list of all possible digits to get (it guarantees that you won't get more than a max digits of one type). Then you get digits one by one from it (removing digits after getting from long list guarantees distribution).
*This code is for example only and such use of std::vector is not optimal at all.