-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfollowinginteger.rb
53 lines (51 loc) · 1.68 KB
/
followinginteger.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
=begin
FOLLOWING INTEGER
CHALLENGE DESCRIPTION:
Credits: This challenge has appeared in a past google competition
You are writing out a list of numbers.Your list contains all numbers with
exactly Di digits in its decimal representation which are equal to i, for each
i between 1 and 9, inclusive. You are writing them out in ascending order. For
example, you might be writing every number with two '1's and one '5'. Your
list would begin 115, 151, 511, 1015, 1051. Given N, the last number you
wrote, compute what the next number in the list will be. The number of 1s, 2s,
..., 9s is fixed but the number of 0s is arbitrary.
INPUT SAMPLE:
Your program should accept as its first argument a path to a filename. Each
line in this file is one test case. Each test case will contain an integer n <
10^6. E.g.
115
842
8000
OUTPUT SAMPLE:
For each line of input, generate a line of output which is the next integer in
the list. E.g.
151
2048
80000
=end
lines = File.readlines(ARGV[0])
lines.each do |line|
digit_count = Array.new(10, 0)
this_number = line.chomp.to_i
line.chomp.chars { |char| digit_count[char.to_i] += 1 }
n_digit_numbers = line.chomp.chars.permutation.map { |perm| perm.join.to_i }
n_digit_numbers.sort!
if this_number == n_digit_numbers.last
digits = this_number.to_s.chars + ["0"]
n_digit_numbers = digits.permutation.map { |perm| perm.join.to_i }
n_digit_numbers.sort!
n_digit_numbers.each do |number|
if number > this_number
puts number
break
end
end
else
n_digit_numbers.each do |number|
if number > this_number
puts number
break
end
end
end
end