So I am fairly new to programming with c++ and I was wondering if there was a way to set up a code with an array of variable dimensions that removed random points on that array i.e.
1111
1111
1111
then randomly remove a point:
1101
1111
1111
and then be able to repeat this process until all points are removed.
Any ideas?
My strategy is first count the remaining elements in the array, if there are/is remaining element(s), then generate a random index of the remainders and remove it.
#include <iostream>
#include <stdlib.h>
#include <time.h>
usingnamespace std;
constint ROWS = 3;
constint COLS = 4;
bool removePoint(int arr[ROWS][COLS]);
void print2dArray(int arr[ROWS][COLS]);
int main()
{
srand(time(0));
int arr[ROWS][COLS];
for (int i=0; i<ROWS; ++i)
for (int j=0; j<COLS; ++j)
arr[i][j] = 1;
while (removePoint(arr))
{
print2dArray(arr);
cout << endl;
}
}
//----------------------------------------------
bool removePoint(int arr[ROWS][COLS])
{
// Count remaining elements
int rem = 0;
for (int i=0; i<ROWS; ++i)
for (int j=0; j<COLS; ++j)
if (arr[i][j]) ++rem;
// If there is no remaining, return false, means
//the function does nothing to the array
if (!rem) returnfalse;
// Generate a random remove index, range [1,rem] inclusive
//This is not row or col index. If we have 7 remaining elements,
//and removeIndex is 4, then the 4th element in the 7 remaining
//elements will be removed.
int rmi = rand() % rem + 1;
// Remove it
for (int i=0; i<ROWS && rmi; ++i)
for (int j=0; j<COLS && rmi; ++j)
if (arr[i][j] && !--rmi) arr[i][j] = 0; //if arr[i][j] is not empty and (rmi after decremented) is 0,
//we found the element to remove
// Return true means the function successfully removes a point
returntrue;
}
//----------------------------------------------
void print2dArray(int arr[ROWS][COLS])
{
for (int i=0; i<ROWS; ++i)
{
for (int j=0; j<COLS; ++j)
cout << arr[i][j] << " ";
cout << endl;
}
}