Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a new element different from 1000 elements of an array

I was asked this questions in an interview. Consider the scenario of punched cards, where each punched card has 64 bit pattern. I was suggested each card as an int since each int is a collection of bits.

Also, to be considered that I have an array which already contains 1000 such cards. I have to generate a new element everytime which is different from the previous 1000 cards. The integers(aka cards) in the array are not necessarily sorted.

Even more, how would that be possible the question was for C++, where does the 64 bit int comes from and how can I generate this new card from the array where the element to be generated is different from all the elements already present in the array?

like image 548
Cipher Avatar asked Sep 14 '11 08:09

Cipher


People also ask

How can we create an array of 10 integers?

Array Initialization in Java To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.

What are the different ways to initialize an array with all elements?

There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.

How can we get the first 10 elements of an array?

Use the Array. slice() method to get the first N elements of an array, e.g. const first3 = arr. slice(0, 3) . The slice() method will return a new array containing the first N elements of the original array.

What are the different ways to initialize an array with all elements as zero?

3. What are the different ways to initialize an array with all elements as zero? Explanation: None.


1 Answers

There are 264 64 bit integers, a number that is so much larger than 1000 that the simplest solution would be to just generate a random 64 bit number, and then verify that it isn't in the table of already generated numbers. (The probability that it is is infinitesimal, but you might as well be sure.)

Since most random number generators do not generate 64 bit values, you are left with either writing your own, or (much simpler), combining the values, say by generating 8 random bytes, and memcpying them into a uint64_t.

As for verifying that the number isn't already present, std::find is just fine for one or two new numbers; if you have to do a lot of lookups, sorting the table and using a binary search would be worthwhile. Or some sort of a hash table.

like image 150
James Kanze Avatar answered Oct 05 '22 23:10

James Kanze