跳至主要内容

Programming Pearls: How to Random?

Programming Pearls: How to Random?

Notes for Programming Pearls: second edition , chapter 12, trying to remember the process to solve a problem.


They want to automating the task of drawing a random sample from a printed list of precincts.

The input consists of a list of precinct names and an integer m. The output is a list of m of the precincts choosen at random. There are usually a few hundred precinct names( each a string of at most a dozen characters), and m is typically between 20 and 40.

Problem definition

In order to make problem easier to understand and solve, we can make description more abstract.

The input consists of two integers m and n, with m < n. The output is a sorted list of m random integers in the range [0, n-1} in which no integer occurs more than once. For probability buffs, we desire a sorted selection without replacement in which each selection occurs with equal probability.

One solution

Author give us an algorithm from Knuth

select = m
remaining = n
for i = [0, n)
    if (bigrand() % remaining) < select
        print i
        select--
    remaining--

Design space

In order to prepare to solve the tomorrow’s problem, author want us to solve this problem differently.

Set based

One solution we can easily come up with is to produce random number and remove duplicate until we find m different numbers. And set is the common solution for remove duplicates.

while(set.size() < m) {
    random = getRandom()
    if(!set.contain(random)) {
        set.add(random)
    }
}
Faster – less random number

Using the set-based solution has an obvious defect that when m is coming close to n, we will discard many random number which will waste some time.
The following is the algorithm composed by Bob Floyd which will not discard any random number:

for(int j = n - m; j < n; j++) {
    t = ranint();
    if !set.contain(t)
        set.insert(t)
    else 
        set.insert(j)
Another approach – shuffle

Let’s think in another dimension: we don’t generate random number, we shuffle the input and choose first m numbers. So I come up with the following solution with O(m)O(m) space.

a = [0..m-1]
select = 0
while select < m
    i = ranint()
    if i < m
        swap(a, select, i)
    else
        a[select] = i
    select++
More to think

The function we have seen so far offer several different solutions to the problem, but they by no means cover the design space. Suppose, for instance, that n is a million and m is n - 10. We might generate a sorted random sample of 10 elements, and then report the integers that aren’t there. Next, suppose that m is ten million and n is 2**31. We could generate eleven million integers, sort them, scan through to remove duplicates, and then generate a ten-million-element sorted sample of that.

Upper words inspire me much:

  • to keep mind open – not be limited by old solution, think again about new way to solve it;
  • to solve problem according to its condition – not be limited by old problem, this problem is always different;

Written with StackEdit.

评论

此博客中的热门博文

Spring Boot: Customize Environment

Spring Boot: Customize Environment Environment variable is a very commonly used feature in daily programming: used in init script used in startup configuration used by logging etc In Spring Boot, all environment variables are a part of properties in Spring context and managed by Environment abstraction. Because Spring Boot can handle the parse of configuration files, when we want to implement a project which uses yml file as a separate config file, we choose the Spring Boot. The following is the problems we met when we implementing the parse of yml file and it is recorded for future reader. Bind to Class Property values can be injected directly into your beans using the @Value annotation, accessed via Spring’s Environment abstraction or bound to structured objects via @ConfigurationProperties. As the document says, there exists three ways to access properties in *.properties or *.yml : @Value : access single value Environment : can access multi

Elasticsearch: Join and SubQuery

Elasticsearch: Join and SubQuery Tony was bothered by the recent change of search engine requirement: they want the functionality of SQL-like join in Elasticsearch! “They are crazy! How can they think like that. Didn’t they understand that Elasticsearch is kind-of NoSQL 1 in which every index should be independent and self-contained? In this way, every index can work independently and scale as they like without considering other indexes, so the performance can boost. Following this design principle, Elasticsearch has little related supports.” Tony thought, after listening their requirements. Leader notice tony’s unwillingness and said, “Maybe it is hard to do, but the requirement is reasonable. We need to search person by his friends, didn’t we? What’s more, the harder to implement, the more you can learn from it, right?” Tony thought leader’s word does make sense so he set out to do the related implementations Application-Side Join “The first implementation

Implement isdigit

It is seems very easy to implement c library function isdigit , but for a library code, performance is very important. So we will try to implement it and make it faster. Function So, first we make it right. int isdigit ( char c) { return c >= '0' && c <= '9' ; } Improvements One – Macro When it comes to performance for c code, macro can always be tried. #define isdigit (c) c >= '0' && c <= '9' Two – Table Upper version use two comparison and one logical operation, but we can do better with more space: # define isdigit(c) table[c] This works and faster, but somewhat wasteful. We need only one bit to represent true or false, but we use a int. So what to do? There are many similar functions like isalpha(), isupper ... in c header file, so we can combine them into one int and get result by table[c]&SOME_BIT , which is what source do. Source code of ctype.h : # define _ISbit(bit) (1 << (