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 8192625
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T04:13:19+00:00 2026-06-07T04:13:19+00:00

Python’s module ‘random’ has a function random.choice random.choice(seq) Return a random element from the

  • 0

Python’s module ‘random’ has a function random.choice

random.choice(seq)
Return a random element from the non-empty sequence seq. If seq is empty, raises IndexError.

How can I emulate this in .NET ?

public T RandomChoice<T> (IEnumerable<T> source)

Edit: I heard this as an interview question some years ago, but today the problem occurred naturally in my work. The interview question was stated with constraints

  • ‘the sequence is too long to save to memory’
  • ‘you can only loop over the sequence once’
  • ‘the sequence doesn’t have a length/count method’ (à la .NET IEnumerable)
  • 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-07T04:13:20+00:00Added an answer on June 7, 2026 at 4:13 am

    To make a method that iterates the source only once, and doesn’t have to allocate memory to store it temporarily, you count how many items you have iterated, and determine the probability that the current item should be the result:

    public T RandomChoice<T> (IEnumerable<T> source) {
      Random rnd = new Random();
      T result = default(T);
      int cnt = 0;
      foreach (T item in source) {
        cnt++;
        if (rnd.Next(cnt) == 0) {
          result = item;
        }
      }
      return result;
    }
    

    When you are at the first item, the probability is 1/1 that it should be used (as that is the only item that you have seen this far). When you are at the second item, the probability is 1/2 that it should replace the first item, and so on.


    This will naturally use a bit more CPU, as it creates one random number per item, not just a single random number to select an item, as dasblinkenlight pointed out. You can check if the source implements IList<T>, as Dan Tao suggested, and use an implementation that uses the capabilities to get the length of the collection and access items by index:

    public T RandomChoice<T> (IEnumerable<T> source) {
      IList<T> list = source as IList<T>;
      if (list != null) {
        // use list.Count and list[] to pick an item by random
      } else {
        // use implementation above
      }
    }
    

    Note: You should consider sending the Random instance into the method. Otherwise you will get the same random seed if you call the method two times too close in time, as the seed is created from the current time.


    The result of a test run, picking one number from an array containing 0 – 9, 1000000 times, to show that the distribution of the chosen numbers is not skewed:

    0: 100278
    1: 99519
    2: 99994
    3: 100327
    4: 99571
    5: 99731
    6: 100031
    7: 100429
    8: 99482
    9: 100638
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Python's IDLE has 'Check Module' (Alt-X) to check the syntax which can be called
Python has great module for working with iterators called itertools Is there any analog
Python 3.2 documentation refers to Collin Winter's functional module which contains function compose :
Python 3.2 introduces a new function recursive_repr in reprlib module. When I looked into
Python does not print traceback messages from exceptions raised in daemon threads. For example,
Python has a lot of convenient data structures (lists, tuples, dicts, sets, etc) which
python newbie here. I'm writing the code to control an experiment that has multiple
Python has the idea of metaclasses that, if I understand correctly, allow you to
python manage.py dumpdata modelName > file.json . created an empty database for a user
Python's file.read() function won't read anything. It always returns '' no matter what's inside

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.