面試題:
如果有一個文件很大,內(nèi)存很大,不知道有多少行。你的任務是隨機輸出一行。文件只能遍歷一次。
解析:算法就是需要保證輸出一行的概率是相等的。
相關(guān)問題:
給你一個長度為N的鏈表。N很大,但你不知道N有多大。你的任務是從這N個元素中隨機取出k個元素。你只能遍歷這個鏈表一次。你的算法必須保證取出的元素恰好有k個,且它們是完全隨機的(出現(xiàn)概率均等)。
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Random;
public class RandomOutput {
public static String randomOutput(String path) {
String res = null;
String temp = null;
FileReader reader = null;
BufferedReader br = null;
int i = 0;
int ranValue = 0;
// Random rand = new Random();
try {
reader = new FileReader(path);
br = new BufferedReader(reader);
res = br.readLine();
i++;
while((temp = br.readLine()) != null) {
i++;
System.out.println(i);
// ranValue = rand.nextInt(i);
ranValue = new Random().nextInt(i);
System.out.println(ranValue);
if (ranValue < 1) {
res = temp;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
br.close();
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
public static void main(String[] argv) {
String res = randomOutput("test.txt");
System.out.println(res);
}
}
解法:
該算法是針對從一個序列中隨機抽取不重復的k個數(shù),保證每個數(shù)被抽取到的概率為k/n這個問題而構(gòu)建的。做法是:
首先構(gòu)建一個可放k個元素的蓄水池,將序列的前k個元素放入蓄水池中。
然后從第k+1個元素開始,以k/n的概率來決定該元素是否被替換到池子中。 當遍歷完所有元素之后,就可以得到隨機挑選出的k個元素。復雜度為O(n).
其偽代碼如下:
Init : a reservoir with the size: k
for i= k+1 to N
M=random(1, i);
if( M <= k)
SWAP the Mth value and ith value
end for
證明每個數(shù)被取到的概率為k/n:
對于第i個數(shù)(i<k),在前k步被選中的概率是1, 從第k+1步開始,i不被選中的概率為k/k+1,那么讀到第n個數(shù)時, 第i個數(shù)(i<k)被選中的概率 = 被選中的概率 * 以后每一步都不被換走的概率,即:
1 * k/k+1 * k+1/k+2*...*n-1/n = k/n
對于第j個數(shù)(j>=k)被選中的概率為: 在他出現(xiàn)時被選中的概率 * 在他出現(xiàn)以后不被換走的概率,即:
k/j * j /j+1*...*n-1/n = k/n
綜上得證。