LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How can I modify this program to change it to a 2D array?? (https://www.linuxquestions.org/questions/linux-newbie-8/how-can-i-modify-this-program-to-change-it-to-a-2d-array-4175433410/)

carlosk711 10-21-2012 08:48 PM

How can I modify this program to change it to a 2D array??
 
I want it to be a 4x4 array the reads out 1-4 at random with repeating

EX)
4312
3124
1243
2431

My current program reads out a 1-10 at random without repeating
Can someone help me modify it?
Code:

#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main ()
{
    int A[10];
    srand (time(NULL) );
    int count = 0;
    while (count <10){
    int k = (rand() % 10) + 1;
    bool Placed = false;
    for (int i = 0; (i < count); i++){
    if (A[i] == k){
    Placed = true;
}
}
    if (!Placed){
    A[count] = k;
    count ++;
}
}


    for (int i=0; i<10; i++)
{
    cout << A[i] << " ";
}
    cout << endl;
    return 0;
}


Elv13 10-21-2012 10:49 PM

[Wrong forum]

As this is C++, using static array is not necessary, use Vectors or Lists so you have a the find() function.

As for the 2D static array, a neat trick is to keep your existing code intact (but use 14 as size instead of 10). Then make a new array of size 4 and type int*. Place the newArr[0] = A, newArr[1] = newArr[1] = A+4; and so on. With that, you can have both a continuous and a 2D view of the same dataset. Again, it is a little trick, not something that would work in a pure algorithm point of view. It work because of the way C does static array pointer.

carlosk711 10-22-2012 07:19 AM

My apologies, I have reposted in another forum


All times are GMT -5. The time now is 08:08 PM.