-1

Let's say we have an array, block[5]={0,1,0,3,0}. The array has three zeroes and I want to find a random position of one zero. And how can i make this with a bidimensional array?

kinsua
  • 13
  • 1

2 Answers2

0

You can does like this:

#include <iostream>
#include <ctime>



int main() {
    int block[5] = { 0,1,0,3,0 };
    int Random_Val = 0;

    srand(time(NULL));

    Random_Val = (rand()%5);

    while (block[Random_Val] != 0) {
        Random_Val = (rand() % 5);
    }
     return = 0;
  }

for 2D arrays:

#include <iostream>
#include <ctime>



int main() {
    int block[5][5] = { { 0,1,0,3,0 },{ 0,1,0,3,0 },{ 0,1,0,3,0 },{ 0,1,0,3,0 },{ 0,1,0,3,0 } };
    int Random_Val = 0;
    int Random_Val2 = 0;


    srand(time(NULL));

    Random_Val = (rand() % 5);
    Random_Val2 = (rand() % 5);

    while (block[Random_Val][Random_Val2] != 0) {
        Random_Val = (rand() % 5);
        Random_Val2 = (rand() % 5);
    }

    };
  • 1
    Please, do not use `rand`. It has a lot of problems and, for instance with MSVC, it generates only 32768 distinct random numbers. If the input array has larger dimensions, you wouldn't be able to hit all the elements (which may result even in an endless loop). Use C++11 `` mechanisms instead. – Daniel Langr Aug 28 '20 at 10:28
  • Can you expand a bit more? @DanielLangr – Ahmet Yusuf Yatkın Aug 28 '20 at 10:58
  • See, e.g., https://stackoverflow.com/questions/52869166/why-is-the-use-of-rand-considered-bad. In short: it uses a low-quality generator, it uses a global state, it does not come up with distribution mechanisms, it can have a very limited amount of generated values, etc. There are more posts related to this issue on StackOverflow, just use Google. – Daniel Langr Aug 28 '20 at 11:03
0

You can use std::vector

#include <vector>

std::vector block = {0,1,0,3,0};
std::vector index_vector;

auto it = block.end();
while(it =! block.begin())
{
   auto newit = std::find(block.begin(), it, 0);
   if (newit =! it)
   {
      it = newit;
      int index = std::distance(block.begin(), it);
      index_vector.push_back(index );
   }
   else
     break;
 }

then you can chose randomly in index_vector

 double r = ((double) rand() / (RAND_MAX));
 int i = (int) (r* index_vector.size());
 myrandomindex = index_vector[i];
 
gibs
  • 90
  • 6
  • 2
    Please, do not use `rand`. It has a lot of problems and, for instance with MSVC, it generates only 32768 distinct random numbers. If the input array has larger dimensions, you wouldn't be able to hit all the elements. Use C++11 `` mechanisms instead. – Daniel Langr Aug 28 '20 at 10:29