I have a 2d array of size 4X4 that is

int arr[4][4];

i want to initialize this from 1-15 but in random manner not sequential
example


7 8 9 5
1 2 12 14
3 6 10 13
11 4 15 0

I try

random()

function but iam not getting the desired out put...
thanks

Recommended Answers

All 4 Replies

You want a random shuffle. Simply filling the array with random values will very likely produce duplicates. Shuffling multi-dimensional arrays is harder, so the usual advice is to shuffle a one-dimensional array and then copy the results into your final two-dimensional array:

#include <stdio.h>
#include <stdlib.h>

void swap(int *a, int *b)
{
    int save = *a;

    *a = *b;
    *b = save;
}

void random_shuffle(int *a, size_t n)
{
    size_t i;

    for (i = 0; i < n - 1; i++)
        swap(&a[i], &a[i + (rand() % (n - i))]);
}

#define M 4
#define N 4

int main(void)
{
    int a[M][N] = {
        {0,  1,  2,  3},
        {4,  5,  6,  7},
        {8,  9,  10, 11},
        {12, 13, 14, 15}
    };
    int i, j;

    random_shuffle(&a[0][0], M * N);

    for (i = 0; i < M; i++) {
        for (j = 0; j < N; j++)
            printf("%3d", a[i][j]);
        putchar('\n');
    }

    return 0;
}

For fun: The above code has a very subtle problem! See if you can find it.

Narue beat me to the punch...Here's my simple solution

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define ARR_SIZE 16
#define LOW 0
#define HIGH 15

int mya[ARR_SIZE] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};

int main(int argc, char**argv)
{
	int i = 0;
	int j = 0;
	int count = 0;
	int index = 0;
	time_t seconds;
	time(&seconds);
	srand((unsigned int) seconds);

	for (; i < ARR_SIZE; ++i, ++count)
	{
		index = rand() % (HIGH - LOW + 1 - count) + LOW;
		fprintf(stdout, "ans->%d\n", mya[index]);
			
		for (j = index; j < (ARR_SIZE - 1); ++j)
		{
			mya[j] = mya[j + 1];
		}
	}

	exit(EXIT_SUCCESS);
}

@Narue Thanks for great help but when I try to run code provided you i get the compiler error that
can't load <filename>.exe

iam using turbo c++ can you explain why?

thanks @gerard4143

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.