Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8590571
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T23:19:26+00:00 2026-06-11T23:19:26+00:00

I am trying to find k random numbers in the range 1..n such that

  • 0

I am trying to find k random numbers in the range 1..n such that none of the k numbers are contiguous. The code I came up with is

def noncontiguoussample(n,k):
    import random
    numbers = range(n)
    samples = []
    for _ in range(k):
        v = random.choice(numbers)
        samples.append(v)
        for v in range(v-1, v+2):
            try:
                numbers.remove(v)
            except ValueError:
                pass

    return samples

Update: I know this function won’t return the samples with uniform probability. Based on my limited testing, Amber’s solution below satisfies both the condition (a) individual elements of the sample are non-contiguous, and (b) all possible k samples (from 1…n) are generated with uniform probability.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T23:19:27+00:00Added an answer on June 11, 2026 at 11:19 pm

    The code is simpler if you use a set.

    import random
    
    def noncontiguoussample(n,k):
        numbers = set(range(1,n+1))
        samples = []
        for _ in range(k):
            v = random.choice(list(numbers))
            samples.append(v)
            numbers -= set([v-1, v, v+1])
        return samples
    

    However, as Michael Anderson points out in the comments, this algorithm can fail sometimes in cases where n < 3*k.


    A better algorithm that can’t fail (and is also faster!) might look like this:

    import random
    
    def noncontiguoussample(n,k):
        # How many numbers we're not picking
        total_skips = n - k
    
        # Distribute the additional skips across the range
        skip_cutoffs = random.sample(range(total_skips+1), k)
        skip_cutoffs.sort()
    
        # Construct the final set of numbers based on our skip distribution
        samples = []
        for index, skip_spot in enumerate(skip_cutoffs):
            # This is just some math-fu that translates indices within the
            # skips to values in the overall result.
            samples.append(1 + index + skip_spot)
    
        return samples
    

    The math-fu at the end there is this:

    • 1, the minimum value we can pick
    • plus 1 per number we’ve picked (index), to account for that picked number
    • plus our position within the skips (which will always increase by at least one)

    Thus the result will always increase by at least 2 for each iteration through the loop.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

All, I have implemented a code that generates 2 random prime numbers and the
I have the following code that returns 50 random color-coded numbers: Sub RandomNumberColor() Dim
I am trying to find a c function that generates a 32bit random/pseudo random
Trying to find an example that has css rollover using sprites & sliding door
While trying to find an answer to Android Jasper Reporting I found out that
here is my code trying to do reduction to find maximum of a 50
I am trying to find a given set of numbers for the equation x^3
I am trying to make a program generating random numbers until it finds a
I'm trying to find the best algorithm for finding a random number between 1-100
I am trying to find a way to pull 10 random records and then

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.