跳至主要内容

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...

LevelDB Source Reading (1): Structure

LevelDB Source Reading (1): Structure LevelDB “is an open source on-disk key-value store.” After I read some documents, I have some basic understanding of LevelDB. So I come up with some questions about structure of LevelDB to answer when reading the source code. Structure Log File: repair/recover db A log file (*.log) stores a sequence of recent updates. Each update is appended to the current log file. The log file contents are a sequence of 32KB blocks. The only exception is that the tail of the file may contain a partial block. Block format: Each block consists of a sequence of records: block := record* trailer? record := checksum: uint32 // crc32c of type and data[] ; little-endian length: uint16 // little-endian type: uint8 // One of FULL, FIRST, MIDDLE, LAST data: uint8[length] // data is LengthPrefixedSlice with type from batch data definition in Block : data: also named `writeBatch` in levelDB // WriteBatch header has an 8-byte ...

Install `nicstat`on Linux

Introduction nicstat is to network interfaces as “iostat” is to disks, or “prstat” is to processes. It is designed as a much better version of “netstat -i”. Its differences include: Reports bytes in & out as well as packets. Normalizes these values to per-second rates. Reports on all interfaces (while iterating) Reports Utilization (rough calculation as of now) Reports Saturation (also rough) Prefixes statistics with the current time With the help from nicstat , we can identify whether distributed Java application is saturating the network by view the utilization percentage of specific interface. Download Sourceforge Download Link Build Following the guide of README.txt, we build like following: $ mv Makefile.Linux Makefile $ make mv nicstat `./nicstat.sh --bin-name` Install $ make install gcc -O3 -m32 nicstat.c -o nicstat In file included from /usr/include/features.h: 392 : 0 , from /usr/include/stdio.h: 27 , from nicsta...