The question is to count the number of repeating elements in the given array:
Suppose the input is:
1
1 2 3 3 3
2
1 2 2 3 3 3 4 5
Then the output should be 3 for the first input and 5 for the second one.
I have written the code, according to logic its output should be 3 but I'm getting the output as 5 could anyone spot the error.
#include <bits/stdc++.h>
using namespace std;
int main() {
int a[5] = {
1,
4,
2,
4,
4
};
int b[101];
memset(b, 0, 101);
int cp = 0, i = 0;
b[a[i]] = 1;
for (int j = i + 1; j < 5; j++) {
if (b[a[j] > 0]) {
if (b[a[j]] == 1)
cp++;
cp++;
b[a[j]]++;
} else
b[a[j]] = 1;
}
cout << cp;
return 0;
}
There is a typo in your code - you wrote if(b[a[j]>0]) instead of if (b[a[j]] > 0), which produces completely different behavior.
To avoid such mistakes, you should format your code properly and give meaningful names to variables. For example, your main function could be rewritten as:
int main() {
const size_t SIZE = 5;
int a[SIZE] = {1, 4, 2, 4, 4};
const int MAX_VALUE = 100;
int count[1 + MAX_VALUE] = {};
int duplicates = 0;
for (int j = 0; j < SIZE; j++) {
if (count[a[j]] > 0)
duplicates++;
if (count[a[j]] == 1)
duplicates++;
count[a[j]]++;
}
cout << duplicates;
}
Note how I also removed a special case for the first array element - it is unnecessary and often prone to errors.
If I read something like
#include <bits/stdc++.h>
using namespace std;
and the variable names, then I assume that this question is related to some competetive programming site. So, my guess is that there are more constraints that we do not know. We see for example the magic number 101 here. Maybe there is a constraint that we have only integers in the range 0..100. Anyway, we do not know.
I would like to show a C++ solution. Basically this is using the standard approach for counting items, by using a std::map or std::unordered_map.
Please see the following code which basically consists of 2 lines. I will explain it afterwards:
#include <iostream>
#include <vector>
#include <unordered_map>
#include <numeric>
std::vector testData{ 1,4,2,4,4 };
int main() {
std::unordered_map<int, size_t> counter{};
// Count the occurence of each integer value
for (const int i : testData) counter[i]++;
// Accumulate repeating values and show result
std::cout << std::accumulate(counter.begin(), counter.end(), 0U, [](size_t c, const auto& p) { return c+(p.second > 1 ? p.second : 0U); });
return 0;
}
As said, we use the standard approach with maps. The important point here is to understand the index operator of a map. Please see here. And read:
Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.
The important point is: It will either return a reference to a value, if it is already in the map. If not, it will create the value in the map and again return a reference to the value. And because we get a reference to the value in any way, we can simply increment it.
After we have done this for all source values from our "testData"-vector in a very simple for loop, we have the count of all values. If the count for one value is greater then 1, then it is a duplicate or "repeated".
Therefore, we just need to accumulate all counters that are greater than 1. And for this we use the dedicated function std::accumulate.
If you should have any questions, then please ask.
Related
This question already has answers here:
Unique (non-repeating) random numbers in O(1)?
(22 answers)
Closed 1 year ago.
My goal is creating an array of 5 unique integers between 1 and 20. Is there a better algorithm than what I use below?
It works and I think it has a constant time complexity due to the loops not being dependent on variable inputs, but I want to find out if there is a more efficient, cleaner, or simpler way to write this.
int * getRandom( ) {
static int choices[5] = {};
srand((unsigned)time(NULL));
for (int i = 0; i < 5; i++) {
int generated = 1 + rand() % 20;
for (int j = 0; j < 5; j++){
if(choices[j] == generated){
i--;
}
}
choices[i] = generated;
cout << choices[i] << endl;
}
return choices;
}
Thank you so much for any feedback. I am new to algorithms.
The simplest I can think about is just create array of all 20 numbers, with choices[i] = i+1, shuffle them with std::random_shuffle and take 5 first elements. Might be slower, but hard to introduce bugs, and given small fixed size - might be fine.
BTW, your version has a bug. You execute line choices[i] = generated; even if you find the generated - which might create a copy of generated value. Say, i = 3, generated is equal to element at j = 0, now your decrement i and assign choices[2] - which becomes equal to choices[0].
C++17 code with explanation of why and what.
If you have any questions left don't hesitate to ask, I'm happy to help
#include <iostream>
#include <array>
#include <string>
#include <random>
#include <type_traits>
// container for random numbers.
// by putting the random numbers + generator inside a class
// we get better control over the lifecycle.
// e.g. what gets called when.
// Now we know the generation gets called at constructor time.
class integer_random_numbers
{
public:
// use std::size_t for things used in loops and must be >= 0
integer_random_numbers(std::size_t number, int minimum, int maximum)
{
// initialize the random generator to be trully random
// look at documentation for <random>, it is the C++ way for random numbers
std::mt19937 generator(std::random_device{}());
// make sure all numbers have an equal chance. range is inclusive
std::uniform_int_distribution<int> distribution(minimum, maximum);
// m_values is a std::vector, which is an array of which
// the length be resized at runtime.
for (auto n = 0; n < number; ++n)
{
int new_random_value{};
// generate unique number
do
{
new_random_value = distribution(generator);
} while (std::find(m_values.begin(), m_values.end(), new_random_value) != m_values.end());
m_values.push_back(new_random_value);
}
}
// give the class an array index operator
// so we can use it as an array later
int& operator[](const std::size_t index)
{
// use bounds checking from std::vector
return m_values.at(index);
}
// reutnr the number of numbers we generated
std::size_t size() const noexcept
{
return m_values.size();
}
private:
// use a vector, since we specify the size at runtime.
std::vector<int> m_values;
};
// Create a static instance of the class, this will
// run the constructor only once (at start of program)
static integer_random_numbers my_random_numbers{ 5, 1, 20 };
int main()
{
// And now we can use my_random_numbers as an array
for (auto n = 0; n < my_random_numbers.size(); ++n)
{
std::cout << my_random_numbers[n] << std::endl;
}
}
Generate 5 random numbers from 1 to 16, allowing duplicates
Sort them
Add 1 to the 2nd number, 2 to the 3rd, 3 to 4th, and 4 to the 5th.
The last step transforms the range from [1,16] to [1,20] by remapping the possible sequences with duplicates into sequences with unique integers. [1,2,10,10,16], for example, becomes [1,3,12,13,20]. The transformation is completely bijective, so you never need to discard and resample.
problem:
Given a matrix of integers, count the amount of times each number 0-9 appears. Print out your results on one line in the following form:
0:number of zeros;1:number of ones;2:number of twos;3:number of threes;4:number of fours;5:number of fives;6:number of sixes;7:number of sevens;8:number of eights;9:number of nines;
For example, if you are passed an identify matrix, it contains 12 zeros and 4 ones and no other numbers from 0 to 9, your output would be:
0:12;1:4;2:0;3:0;4:0;5:0;6:0;7:0;8:0;9:0;
So far I have been created some codes:
#include<bits/stdc++.h>
using namespace std;
void printfrequency(int array[][4])
{
int c=0;
for(int a=0; a<10; a++){
for (int i=0; i<4; i++)
for ( int j=0;j<4;j++)
if(array[i][j] == a){
c++;
}
cout << a << ":" << c <<";" ;
}
}
int main()
{
int array[4][4] = { {3,5,7,9}, {2,4,8,9},{1,1,1,1},{3,6,9,2} };
printfrequency(array);
return 0;
}
and here is the ouput:
0:0;1:4;2:6;3:8;4:9;5:10;6:11;7:12;8:13;9:16;
How can I achieve 0:12;1:4;2:0;3:0;4:0;5:0;6:0;7:0;8:0;9:0; ?
The code you show gives output based on the frequencies for the specific array init visible in the shown code.
That array init contains no zeros, so the output should start with "0:0" and it does. (Actually required for the shown array init would be "zeros:0", but I stick with your codes basic concept of output and only discuss frequency values).
The output mentioned as example in the assignemnt is for an "identity" matrix, though you have a typo there. Such an identity matrix has a diagonal of "1"s in other wise all "0"s. Counting them gives the output of 4 ones and 12 zeros for a 4 by 4 matrix as shown.
The code is not correct, it fails to reset the count and the frequencies hence increase over the output.
To fix that mistake (but still get the frequencies for the array init, not the example output) change
int c=0;
for(int a=0; a<10; a++)
{
to
for(int a=0; a<10; a++)
{
int c=0;
That will reset the count for each digit your are counting and get you the output:
0:0;1:4;2:2;3:2;4:1;5:1;6:1;7:1;8:1;9:3;
All answers are given, correct and accepted.
But additionally I would like to give some hints for a "better" C++ programming style.
We can see in your code that you maybe try to learn from some "Hacker" or "competition" site. That will never work. If you really want to learn C+, then start with books or serious sites.
What we can see in your code:
#include<bits/stdc++.h> is not compliant C++ code. The header file is an extension available for some compilers.But you should never use it.
using namespace std; should never be used. Please use fully qualified names and to not pull in the complete std::namespace
Prefer pre-increment overpost-increment, whereever possible
Do not use C-Style arrays in C++. Use C++ instead.
Variable names should be expressive
Add comments. The more, the better.
Then, without changing any algorithm or structure of your original program and just modifying the names and adding comments, your code could look like the below:
#include <iostream>
#include <array>
// We want to have a square matrix with 4 rows and 4 coulmns
constexpr unsigned int MatrixSize = 4;
// Save some typing work and make array definition more readable
using SquareMatrix = std::array<std::array<int, MatrixSize>, MatrixSize >;
// Function to print thr frequency of interges in a matrix in the range 0..9
void printFrequencyOfNumbersIn(SquareMatrix& squareMatrix) {
// Check all interger digits in the range 0..9
for (int digit = 0; digit < 10; ++digit) {
// The initial counter value for this digit will always start with 0
int digitCounterForThisDigit = 0;
// Now, iterate over all rows
for (int row = 0; row < MatrixSize; ++row)
// And then iterate over all columns of that row
for (int column = 0; column < MatrixSize; ++column)
// CHeck, if the value in the matrix is equal to the current evaluated digit
if (squareMatrix[row][column] == digit)
// If so, then increment counter
++digitCounterForThisDigit;
// And show the frequency count for the digit under evaluation
std::cout << digit << ':' << digitCounterForThisDigit << ';';
}
}
int main() {
// Define and initialize our squre matrix
SquareMatrix matrix = { {{3,5,7,9}, {2,4,8,9},{1,1,1,1},{3,6,9,2}} };
// Let the subfunction analyze and print the frequencies
printFrequencyOfNumbersIn(matrix);
return 0;
}
This is by far more better understandbale than the original version. Functionality wise it is the same.
And, if you want a "more modern" C++ approach, then you would use a std::map or std::unordered_map. That is the idiomatic correct approach for frequency calculation.
This would then look like that:
#include <iostream>
#include <map>
#include <array>
#include <algorithm>
using MyTpe = int;
// Save some typing work. This will define a square matrix with data of type T
// and rows/columns size equal to template parameter MatrixSize
template <typename T, size_t MatrixSize >
using SquareMatrix = std::array<std::array<T, MatrixSize>, MatrixSize>;
// Here we make an abbreviation for our square matrtx that should consist of 4 rows and 4 columns of ints
using MySquareMatrix = SquareMatrix<MyTpe, 4u>;
// Print frequency of any interger in the matrix
void printFrequencyOfNumbersin(MySquareMatrix& mySquareMatrix) {
// Standard idiomatic approach for counting elements
std::map<MyTpe, size_t> counter{ {0,0u}, {1,0u}, {2,0u}, {3,0u}, {4,0u}, {5,0u}, {6,0u}, {7,0u}, {8,0u}, {9,0u} };
// Go through all rows and columns of the matrix
for (const auto& row : mySquareMatrix) for (MyTpe columnValue : row)
// Count occurence of cell value
counter[columnValue]++;
// Show result to user
for (const auto [number, count] : counter) std::cout << number << ':' << count << ';';
}
int main() {
// Test Data
MySquareMatrix matrix = { {{3,5,7,9}, {2,4,8,9},{1,1,1,1},{3,6,9,2}} };
// Evaluate and print
printFrequencyOfNumbersin(matrix);
return 0;
}
Here is a solution.
#include<bits/stdc++.h>
using namespace std;
int main(){
map<int,int>mp;
int array[4][4] = { {3,5,7,9},{2,4,8,9},{1,1,1,1},{3,6,9,2} };
mp[0]=0,mp[1]=0, mp[2]=0,mp[3]=0, mp[4]=0,mp[5]=0,mp[6]=0,mp[7]=0,mp[8]=0,mp[9]=0;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
int x=array[j][i];
mp[x]++;
}
}
for(auto it=mp.begin();it!=mp.end();it++){
cout<<it->first<<":"<<it->second<<";";
}
}
My C++ skills are rusty but trying to help my son with his assignment so pardon me if its very simple.
I am trying to find all of the neighbors of an element in array and seeing if that particular element is larger than all of its neighbors.
#include <iostream>
using namespace std;
int row2(int arr[][3], int n){
cout << "row2";
if (arr[1][n] > arr[0][n] && arr[1][n] > arr[0][1] && arr[1][n] > arr[1][1] && arr[1][n] > arr[2][1] && arr[1][n] > arr[2][n]){
return true;
}
else
return false;
}
int row3(int arr[][3], int n){
cout << "row3==n";
cout << n;
if (n == 0 || n == 2){
if (arr[3][n] > arr[1][n] && arr[3][n] > arr[3][1] && arr[3][n] > arr[1][1]){
cout << "row3 if";
return true;
}
else
cout << "row3 else";
return false;
}
else{
if (arr[3][1] > arr[3][2] && arr[3][1] > arr[3][0] && arr[3][1] > arr[1][2] && arr[3][1] > arr[1][0] && arr[3][1] > arr[1][1]){
return true;
}
else
return false;
}
}
When compiling I get an error in this line val = arr[counterx] [counter]; expected body of lambda expression
val4 = arr[val2], [val3];
Any pointers?
Thanks in advance!
The shown code has several bugs, and errors. Both syntax errors and logical errors.
void findit(int arr[], int sizey, int sizex)
This declares the first parameter to be a plain, garden variety array. Just a one dimensional array. Typical values in this array, that you might found would be arr[0], or arr[1], or maybe arr[x] if x was some integer variable. But then, in the this function:
val = arr[counterx] [counter];
this tries to access arr as if it was a two-dimensional array, instead: arr[something][somethingelse]. That would be a two-dimensional array, while the arr is declared as a one-dimensional array.
In your main you declare a
int arr[3][3]
which is a two-dimensional array, but then pass it to findit:
findit(arr, m,n);
However, as we've just discovered, the first parameter to findit is not a two-dimensional array, but a one dimensional array. It's clear that findit's arr should be declared as a two-dimensional array.
However there is no way, in C++, to pass a two-dimensional array to a C++ function, with unspecified first and second dimension. C++ does not work this way. In an array parameter specification, in C++, only the first array dimnension can be left unspecified. The 2nd, and all following dimensions must be specified. You could, for example, declare:
void findit(int arr[][3], int sizey, int sizex)
That would allow you to pass any two-dimensional array of ints, as long as the 2nd dimension is 3. But then passing both size parameters is meaningless. It is only necessary to explicitly pass in the size of the first dimension, since the size of the second dimension is already known.
Finally:
val4 = arr[val2], [val3];
It is unclear what this is, but this is not a valid C++ syntax. If you meant to access an element in this two-dimensional array, using the given indices, the appropriate syntax would be:
val4 = arr[val2][val3];
This addresses the fundamental compilation errors in the shown code. Unfortunately there are many, many obvious logical problems in the shown code. For example, one of the logical problems:
val = arr[counterx] [counter];
If you inspect the preceding for loops, you will discover that:
for (int counterx = -1; counter <= sizex; counter++){
So, the counterx variable will start iterating from -1, so the above will appear to try to evaluate:
val = arr[-1][counter];
In C++, no array has a value at a negative index offset, so the above logic will result in undefined behavior, and nonsensical results. If you have any kind of an array, like x[], you might find something at x[0], and at x[1], but not at x[-1]. The same applies to multi-dimensional arrays too.
This is the first logical error that was obvious to the naked eye, and there are probably a few more, here. Overall, the approach in the shown code is somewhat unclear. You might benefit from taking a step back, and redesigning the overall approach for this task, since the shown logic does not appear to be going about it correctly, in several fundamental ways.
expected body of lambda expression val4 = arr[val2], [val3];
Seems like a syntax error on this line val4 = arr[val2], [val3]; and not the one you mentioned in the question.
I assume you meant to write val4 = arr[val2][val3]; without the comma.
That being said, the values of val2 and val3 are being assigned the same value and may cause an index out of bounds exception if unchecked. Moreover, starting counter and counterx at -1 will cause out of bounds exceptions.
Moreover, you cannot pass a multidimensional array to a function without passing it as a double pointer or hardcoding the size.
EDIT 1:
I put together a solution for finding the max number in each row. It's not the most optimized code but it's quick and works. I assumed the row,col sizes could change, so I'm using std::vector instead of std:array or primitive array. However, you could revert back if you know you can hardcode int[3][3] into your solution.
#include <iostream>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <array>
void findit(std::vector<std::vector<int>> arr){
for (size_t rowsIndex = 0; rowsIndex <= arr.size(); rowsIndex++){
std::vector<int> row = arr[rowsIndex];
int maxNum = *std::max_element(row.begin(), row.end());
std::cout<< "largest num in row " << rowsIndex << ": " << maxNum << std::endl;
}
}
int main(){
std::vector<std::vector<int>> arr;
arr.push_back({0, 1, 2 });
arr.push_back({4, 5, 6 });
arr.push_back({8, 9, 10});
findit(arr);
}
EDIT 2:
If you want to check a target index against adjacent indecies, there's no need to use a forloop. There are only 4 (or 8) possible indecies to check against, just easier (and efficient) to hardcode them:
#include <iostream>
#include <iterator>
#include <iostream>
#include <algorithm>
#include <array>
void checkIfIndexIsLargestInItsAdjacency(std::vector<std::vector<int>> arr, size_t targetRow, size_t targetColumn){
int targetNumber = arr[targetRow][targetColumn];
int numberToTheLeft = targetColumn > 0 ? arr[targetRow][targetColumn-1] : 0;
int numberToTheRight = targetColumn + 1 < arr[targetRow].size() ? arr[targetRow][targetColumn+1] : 0;
int numberToTheUp = targetRow > 0 ? arr[targetRow-1][targetColumn] : 0;
int numberToTheDown = targetRow + 1 < arr.size() ? arr[targetRow+1][targetColumn] : 0;
std::cout<< "targetNumber: " << targetNumber << std::endl;
std::cout<< "Number to the left: " << numberToTheLeft << std::endl;
std::cout<< "Number to the right: " << numberToTheRight << std::endl;
std::cout<< "Number to the up: " << numberToTheUp << std::endl;
std::cout<< "Number to the down: " << numberToTheDown << std::endl;
std::array<int, 4> adjacentNumbers = {numberToTheLeft, numberToTheRight, numberToTheUp, numberToTheDown};
int maxAdjacentNum = *std::max_element(adjacentNumbers.begin(), adjacentNumbers.end());
std::cout << "Target number is " << (maxAdjacentNum >= targetNumber? "smaller" : "bigger") << " than adjacent numbers" << std::endl;
}
int main(){
std::vector<std::vector<int>> arr;
arr.push_back({0, 1, 2 });
arr.push_back({4, 5, 6 });
arr.push_back({8, 9, 10});
checkIfIndexIsLargestInItsAdjacency(arr, 1, 1);
checkIfIndexIsLargestInItsAdjacency(arr, 2, 2);
}
Example output:
targetNumber: 5
Number to the left: 4
Number to the right: 6
Number to the up: 1
Number to the down: 9
Target number is smaller than adjacent numbers
targetNumber: 10
Number to the left: 9
Number to the right: 0
Number to the up: 6
Number to the down: 0
Target number is bigger than adjacent numbers
I wanted to ask how it is possible to sort an integers digit by size using bitshifting operations.
Here is an example:
Input : 12823745
Output : 87543221
Basically sorting the digits from the high digits to the small digits
I heared it is possible without using the Bubblesort/Quicksort algorithms, but by using some bitshifting operations.
Does someone know how that can be achieved?
Quick sort and bubble sort are general purpose algorithms. As such the do not make any assumption on the data to be sorted. However, whenever we have additional information on the data we can use this to get something different (I do not say better/faster or anything like this because it is really hard to be better than something as simple and powerful as quick/bubble sort and it really depends on the specific situation what you need).
If there is only a limited number of elements to be sorted (only 10 different digits) one could use something like this:
#include <iostream>
#include <vector>
using namespace std;
typedef std::vector<int> ivec;
void sort(std::vector<int>& vec){
ivec count(10,0);
for (int i=0;i<vec.size();++i){count[vec[i]]++;}
ivec out;
for (int i=9;i>-1;--i){
for (int j=0;j<count[i];j++){
out.push_back(i);
}
}
vec = out;
}
void print(const ivec& vec){
for (int i=0;i<vec.size();++i){std::cout << vec[i];}
std::cout << std::endl;
}
int main() {
ivec vec {1,2,8,2,3,7,4,5};
sort1(vec);
print(vec);
return 0;
}
Note that this has complexity O(N). Further, this always works when set of possible elements has a finite size (not only for digits but not for floats). Unfortunately it is only practical for really small sizes.
Sometimes it is not sufficient to just count the elements. They might have some identity beside the value that has to be sorted. However, the above can be modified easily to work also in this case (needs quite some copies but still O(n)).
Actually I have no idea how your problem could be solved by using bitshift operations. However, I just wanted to point out that there is always a way not to use a general purpose algorithm when your data has nice properties (and sometimes it can be even more efficient).
Here is a solution - Implement bubble sort with loops and bitwise operations.
std::string unsorted = "37980965";
for(int i = 1; i < unsorted.size(); ++i)
for(int j = 0; j < i; ++j) {
auto &a = unsorted[i];
auto &b = unsorted[j];
(((a) >= (b)) || (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b))));
}
std::cout << unsorted ;
Notice that the comparison and swap happens without any branching and arithmetic operations. There are only comparison and bitwise operations done.
How about this one?
#include <iostream>
int main()
{
int digit[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
unsigned int input = 12823745;
unsigned int output = 0;
while(input > 0) {
digit[input % 10]++;
input /= 10;
}
for(int i = 9; i >= 0; --i) {
while(digit[i] > 0) {
output = output * 10 + i;
digit[i]--;
}
}
std::cout << output;
}
I am new to C++, I have a problem of array manipulation. I have an array of X with length 100, I need to fill the value of X with integer value of 1 to 10 (1,2,3,4,5,6,7,8,9,10) randomly.
I know that there will be duplicate, maybe like 1 printed ten times, etc, but that's really what I want.
Here is what I have:
an array of X:
int X[100];
Here is my code snippet:
int* X = NULL;
int* val = NULL;
int length1= 100;
int length2= 10;
X = new int[length1];
val = new int[length2];
int i;
int j;
for (i = 0; i < isi; i++) {
val[i] = i;
for (j = 0; j < length1; j++) {
if (j > i) {
X[j] = val[i];
} else {
X[j] = val[0];
}
cout << "X[" << j << "] = " << X[j] << "\n";
Sleep(1);
}
}
Code above makes the array X from index 0 to 99 has value of 0, then index 0 to 99 has value of 1 and so the other index until the index 0 to 99 has value of 9.
This is not what I want, what I want is to make it (if it is not random) index 0 to 9 has value of 0, then 10 to 19 has value of 1 ... until index 90 to 99 has value of 9. Hope my explanation clear.
I have come to a question in stackoverflow: How would you make an array of 10000 with only values of 1-1000 inclusive?
But still can't resolve my problem my self.
Can someone please give me solution to this.
Thank you in advance
#include <stdlib.h>
int main(int argc, char **argv) {
int r[100];
for (int i = 0; i < 100; ++i) {
r[i] = rand() % 10 + 1;
}
}
For some output, you can #include <iostream> and then std::cout << "r[" << i << "] = " << r[i] << "\n" inside the loop after each assignment.
If you want to seed the random number generator for a different sequence each time, then #include <time.h> and then srand(time(NULL)) before your first call to rand.
You can also use generate function:
#include <iostream>
#include <algorithm>
#include <random>
using namespace std;
int main()
{
int arr[100];
random_device rd;
default_random_engine dre(rd());
uniform_int_distribution<int> uid(0,9);
generate(arr, arr + sizeof(arr) / sizeof(int), [&] () { return uid(dre); });
for (int a : arr)
cout << a << " ";
}
Here are two ways to solve this problem - since this is a learning experience, only pseudo code (and relevant links) are provided. Each "task" can be looked up and solved separately. Note that neither method uses a secondary array.
If the amount of each number in the final result does not need to be the same (eg. 2 might appear 17 times) then consider the following loop-and-assign-random approach. A standard C for-each loop is sufficient.
# for every index pick a random value in [0, 10) and assign it
for i in 0 to last array index:
array[i] = random in range 0, 10
If the amount of numbers need to be the same, then consider filling the array and then shuffling it. The modulus operator is very handy here. (This assumes the array length is a multiple of the group size.)
# fill up array as 0,1,2,3,4,5,6,7,8,9,0,1,2.. (will be 10 groups)
for i in 0 to last array index:
array[i] = i % 10
# and randomly rearrange order
shuffle array
For the shuffle see Fisher-Yates, which even shows a C implementation - there are "more C++" ways, but this is a good technique to learn and practice with loops. (One cool property about Fisher-Yates is that as soon an item is swapped into the current index it is at the final swap location - thus the shuffle loop can be modified to shuffle and immediately perform an action such as displaying the value.)
In both cases a random function should be used; else the numbers will not be .. random.
To loop over the items of a collection the most natural C++ loop is the range based for loop.
In order to assign something to each item, the formal item name should be a reference, thus:
for( auto& item : X )
{
// E.g. assign to item here.
}
This serves up each item of the array, in order, to the code marked by a comment.
There are two different random generators in C++, the old C library one, which is just a pair of functions, and the more general and modern but also not-so-easy-to-grok C++11 thingy. I suggest you google it and try out things. Ask new more specific question if/when stuck.
I think others have pointed it out but you have to first write the pre-compiler directive #include <ctime> and then use the srand function. Most would say don't use that but since you and I are at the basics our teachers, respectively, start us off with that. And it might work with your compiler as well.
Here is a link to learn more about it. I would have commented but I can't.
http://www.cplusplus.com/reference/cstdlib/srand/