From 402d641f645c0268aa94d8786e5cb9748991fa7d Mon Sep 17 00:00:00 2001 From: Abhinav Sarkar Date: Thu, 31 May 2012 21:14:34 +0530 Subject: [PATCH] Faster random number list generation --- column1/problem4.py | 19 +++++++++++++------ column1/test.sh | 8 ++++---- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/column1/problem4.py b/column1/problem4.py index 8f34042..bcc2f56 100644 --- a/column1/problem4.py +++ b/column1/problem4.py @@ -1,14 +1,21 @@ import random def k_uniq_rand_nums_of_n(n, k): - nums = [0] - for i in xrange(1, n): - nums.append(i) + nums = [0] * n + for i in xrange(n - 1, n - 1 - k, -1): j = random.randint(0, i) - nums[i] = nums[j] - nums[j] = i - return nums[:k] + num_j = nums[j] + if num_j == 0: + num_j = j + 1 + + num_i = nums[i] + if num_i == 0: + num_i = i + 1 + + nums[i], nums[j] = num_j, num_i + + return nums[-k:] if __name__ == '__main__': import sys diff --git a/column1/test.sh b/column1/test.sh index f42ced1..4864601 100644 --- a/column1/test.sh +++ b/column1/test.sh @@ -1,9 +1,9 @@ -echo "Generating input" +echo `date +%T` "Generating input" python problem4.py $1 $2 > input -echo "Generating output" +echo `date +%T` "Generating output" cat input | python problem3.py $1 > output -echo "Sorting input" +echo `date +%T` "Sorting input" sort -g input > input_sorted -echo "Diffing sorted input and output" +echo `date +%T` "Diffing sorted input and output" diff -s input_sorted output rm input input_sorted output \ No newline at end of file