Write a function that fills a dynamic, n x n array with integers from 1 to n x n
ID: 3576234 • Letter: W
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. here is the arrray used for problem 1:
#include <iostream>
#include <ctime>
#include <random>
using namespace std;
/*
Write a function that generates a dynamic n x n array of integers.
The functions prototype is
int ** gen2Array(int n);
*/
int ** gen2Array(int n);
int main()
{
int** result = gen2Array(3);
/* initialize random seed: */
srand (time(NULL));
for(int i = 0; i < 3; i++)
for(int x = 0; x < 3; x++)
{
result[i][x] = 3;
}
for(int i = 0; i < 4; i++)
{
for(int x = 0; x <3; x++)
cout << result[2][2] << " ";
cout << endl;
}
system("pause");
return 0;
}
int ** gen2Array(int n)
{
int **p;
p = new int*[n];
for (int i = 0; i < n; ++i) {
p[i] = new int[n];
}
return p;
}
The function's prototype is
void randomFillUnique(int** a, int n);
Write a program to test your function.
Explanation / Answer
#include <iostream>
#include <ctime>
#include<cstdlib>
#include <random>
using namespace std;
/*
Write a function that generates a dynamic n x n array of integers.
The functions prototype is
int ** gen2Array(int n);
*/
int ** gen2Array(int n);
void randomFillUnique(int** a, int n);
int main()
{
int** result = gen2Array(3);
/* initialize random seed: */
srand (time(NULL));
for(int i = 0; i < 3; i++)
for(int x = 0; x < 3; x++)
{
result[i][x] = 3;
}
randomFillUnique(result,3);
for(int i = 0; i < 3; i++)
{
for(int x = 0; x <3; x++)
cout << result[i][x] << " ";
cout << endl;
}
system("pause");
return 0;
}
int ** gen2Array(int n)
{
int **p;
p = new int*[n];
for (int i = 0; i < n; ++i) {
p[i] = new int[n];
}
return p;
}
void randomFillUnique(int** a, int n)
{
for(int i = 0; i < n; i++)
{
for(int j = 0; i < n; i++)
{
a[i][j] = rand() % (n*n);
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.