C++ Question!!!! Write a function that fills a dynamic, n x n array with integer
ID: 3576734 • Letter: C
Question
C++ Question!!!!
Write a function that fills a dynamic, n x n array with integers from 1 to n x n exactly. The array contains no duplicates. Use the array you created in problem 1 to create the array. The function's prototype is void randomFillUnique(int** a, int n); Write a program to test your function.
I am struggling with making an random number dynamic array with no repeating number..
Please help me!!
This is the code what I did
#include <iostream>
#include <ctime>
#include<random>
using namespace std;
int ** gen2Array(int n);
void randomnumberFillUnique(int**p, int n,int lbound, int ubound);
int main()
{ int** p = gen2Array(3);
const int lbound = 1;
const int ubound = 9;
cout << "The dynamic array is : " << endl;
for
(int i = 0;i<3;i++)
{
for (int j = 0;j < 3;j++)
{ cout << p[2][2] << "/t"; }
cout << " "; }
system("pause");
return 0; }
int ** gen2Array(int n) {
int **p; p = new int*[n]; // dynamic `array (size) of pointers to int`
for (int i = 0; i < n; i++) {
p[i] = new int[n]; // each i-th pointer is now pointing to dynamic array (size*2) of actual int values
}
return p;
}
void randomnumberFillUnique(int**p, int n, int lbound, int ubound) {
static default_random_engine e(time(NULL));
uniform_int_distribution u(lbound, ubound);
p = u(e);
for (int i = 0; i < n;i++) {
p = p % (i + 1);
}
}
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
size_t rmdup(int *arr, size_t len)
{
size_t prev = 0;
size_t curr = 1;
size_t last = len - 1;
while (curr <= last) {
for (prev = 0; prev < curr && arr[curr] != arr[prev]; ++prev);
if (prev == curr) {
++curr;
} else {
arr[curr] = arr[last];
--last;
}
}
return curr;
}
void print_array(int *arr, size_t len)
{
printf("{");
size_t curr = 0;
for (curr = 0; curr < len; ++curr) {
if (curr > 0) printf(", ");
printf("%d", arr[curr]);
}
printf("}");
}
int main()
{
int arr[] = {4, 8, 4, 1, 1, 2, 9};
printf("Before: ");
size_t len = sizeof (arr) / sizeof (arr[0]);
print_array(arr, len);
len = rmdup(arr, len);
printf(" After: ");
print_array(arr, len);
printf(" ");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.