IT Log

Record various IT issues and difficulties.

How to generate non-consecutive integers randomly


To generate non-consecutive random integers, follow these steps:

  1. Initialize an empty list to store the generated numbers.
  2. Loop until you have generated the desired number of integers:
  3. Generate a random integer within your specified range.
  4. Check if this integer is consecutive (differs by 1) from any already in the list.
  5. If it’s not consecutive, add it to the list.
  6. Return or store the sorted list of generated integers.

Here’s a Python implementation:

This code generates n non-consecutive random integers between start and end. Each new number is checked against all previously generated numbers to ensure no two are consecutive. The result is returned as a sorted list.

Explanation:

This method ensures that no two generated integers are consecutive, providing an efficient solution for small to moderately sized datasets. For very large datasets or ranges, consider optimizing with combinatorial methods.


, , , ,

4 responses to “How to generate non-consecutive integers randomly”

  1. hiasdhihi

Leave a Reply