Блог пользователя adito

Автор adito, 13 лет назад, По-английски

Iterate over t Number of Test Case

example:

Input:
5
abab
abcd
aabc
daba
saka

Common code for this case:

t = gets.to_i

t.times do
  string = gets.chomp
  # do something with string in each test case, t is needed in here.
end

But, if in the loop you don't need t, you can skip the first line.

gets.to_i.times do
  string = gets.chomp
  # do something with string in each test case.
end

Prime and Prime Factorization

You could use prime library for the type of problem that related to this case. For example:

require "prime"

# testing for primality
Prime.prime?(2) #=> true
Prime.prime?(109873464) #=> false
Prime.prime?(150001633) #=> true

# iterates over a list of prime number starting from 2
Prime.each(100) do |p|
  puts p
  # puts 2, 3, 5, 7, ...
end

# prime division
Prime.prime_division(34)   #=> [[2, 1], [17, 1]]

Constructing Array with Fixed Number of Element from STDIN

Here the sample problem:

Input:
10
1 2
2 2
1 3
2 1
0 0
0 4
5 5
4 5
3 4

The code:

n = gets.to_i
cards = Array.new(n) { gets.split.map(&:to_i) }

# or if you think you wont need n, you can do this instead
cards = Array.new(gets.to_i) { gets.split.map(&:to_i) }

Memoization Function Using Hash Default Value

You can use hash default value for constructing a recursive function. This is the example of factorial function using hash.

factorial = Hash.new {|h, k| h[k] = k * h[k-1] }
factorial[1] = 1

factorial[10] #=> 3628800
factorial[100] #=> 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000

Ok, that's all for now... comments and suggestion are welcomed.

  • Проголосовать: нравится
  • +30
  • Проголосовать: не нравится

»
13 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Great start! Please keep on extending it.

One addition: Assigning values to multiple values at once is useful when the input parameters are given on a single line, e.g. for three variables:

a,b,c = gets.split.map(&:to_i)