[Beginner] Let's solve AtCoder problem with Ruby while looking at the article!

Introduction

I started AtCoder in Ruby. This was fun and addictive, and it was the moment when I realized the fun of programming from the bottom of my heart.

Well, I'm not a programmer, Here are some tips you should know to get started with AtCoder. I think that you can manage to fight by challenging AtCoder with reference to the following.

Through studying AtCoder algorithms I hope it conveys the fun of Ruby and the fun of programming.

I can solve A and B normally, and sometimes C can be solved, If you look at the following and apply it, it will probably be at the same level. ..

Except for mysterious algorithms and formulas The basics are all the following applications.

Split the entered character string (failure example)

gets.split('')
aaa
=> ["a", "a", "a", "\n"]

/ n is included.

Split the entered character string (success example)

gets.chomp.split('')
aaa
=> ["a", "a", "a"]

I was able to divide it into a nice feeling by inserting chomp.

How to enter numbers (failure example)

gets.chomp
1
=> "1"

The input is a character string, isn't it?

How to enter numbers (success example)

gets.to_i
1
=> 1

gets is entered as a string.

How to enter a numbered array a

gets.split.map(&:to_i)
1 2 3
=> [1, 2, 3]

Please enter a space for each number.

How to make multiple nested arrays

3.times.map{gets.split.map(&:to_i)}
1 2 3
1 2 3
1 2 3
=> [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

You now have a nested array of numbers.

One input method + how to repeat it N times to create an array of input values

N = gets.to_i
3
=> 3
b = N.times.map{gets.to_i}
1
2
3
=> [1, 2, 3]

How to tell if it's even or odd

a = 2
=> 2

a.even?
=> true

a.odd?
=> false

Determine if even? Is an even number odd? Determines if it is odd.

Check the length of the variable

a = "aaaa"
=> "aaaa"

a.size
=> 4

a.length
=> 4

a = [1,2]
=> [1, 2]

a.size
=> 2

a.length
=> 2

size and length are the same. You can also arrange strings.

Get the absolute value of a number

a = -10
=> -10

a
=> -10

a.abs
=> 10

Write the ternary operator

if true 
  puts "Yes"
else 
  puts "No"
end

#The above can be written in one line
puts true ? "Yes": "No"

This is often seen in Question A, so remember it!

Output the maximum and minimum values in the array

a = [0, 1 ,2, 3]
=> [0, 1, 2, 3]

 a.min
=> 0

a.max
=> 3

Eliminate duplicates in arrays

 a = [1, 1, 2, 2, 3]
=> [1, 1, 2, 2, 3]

a.uniq
=> [1, 2, 3]

Output the total value in the array

a = [1, 1, 2, 2, 3]
=> [1, 1, 2, 2, 3]

 a.sum
=> 9

a.inject(:+)
=> 9

#Remarks: Multiplication is as follows
a.inject(:*)
=> 12

Either sum or inject is fine. If it is Ruby2.3.3 series, sum may not be usable!

Add to the end of the array

 a = []
=> []

 a << 1
=> [1]

 a << 2
=> [1, 2]

a << 3
=> [1, 2, 3]

Delete the end of the array

a = [1,2,3]
=> [1, 2, 3]

a.delete_at(-1)
=> 3

a
=> [1, 2]

Convenient because you can specify the position of any array

Delete the specified number in the array

 a = [1,2,3]
=> [1, 2, 3]

a.delete(1)
=> 1

a
=> [2, 3]

a = [1,1,2,3]
=> [1, 1, 2, 3]

 a.delete(1)
=> 1

a
=> [2, 3]

I wrote it differently from delete_at, It may be rare to delete the specified number I often see duplicate removal using uniq

Specify the end of the array

 a = [1, 1, 2, 2, 3]
=> [1, 1, 2, 2, 3]

 a[-1]
=> 3

Extracts an array of specified numbers


#Take out the 5th
n = 5
=> 5

a = [1, 1, 2, 2, 3]
=> [1, 1, 2, 2, 3]

a[n]
=> nil

a[n - 1]
=> 3

The array starts at 0, so you have to -1.

Exit the loop when the array reaches a certain value

a = [1, 2, 3, 4]

a.each do |i|
  if i == 2
    puts i
    break
  end
end

By the way, the difference between Break and Return is whether to break out of the loop or the method. Return can only be used inside a method.

How to return true when all the elements of the array are true

a = [2,2,2,2]
=> [2, 2, 2, 2]

a.all?{|n| n.even?}
=> true

 a
=> [2, 2, 2, 2]

a.all?{|n| n == 2}
=> true

a = [2,2,2,3]
=> [2, 2, 2, 3]

a.all?{|n| n == 2}
=> false

Returns true because all the elements of the array are even.

Sort array + change from ascending to descending order

a = [3,1,2]
=> [3, 1, 2]

a.sort
=> [1, 2, 3]

a.sort.reverse
=> [3, 2, 1]

#By the way, the character strings in the array. ..

a = [ "aaa", "ccc","bbb"]
=> ["aaa", "ccc", "bbb"]

a.sort
=> ["aaa", "bbb", "ccc"]

a.sort.reverse
=> ["ccc", "bbb", "aaa"]

See quite a lot

Delete the first element of the array

a = [5,6,7]
=> [5, 6, 7]

 a.drop(1)
=> [6, 7]

#It doesn't seem to be destructive.
 a
=> [5, 6, 7]

 a.drop(1)
=> [6, 7]

a.drop(2)
=> [7]

a.drop(3)
=> []

drop does not seem to be destructive

Extract the first element of the array

a[0]
=> 5

a.shift
=> 5

#↑ Same?

a = [5,6,7]
=> [5, 6, 7]

a.shift
=> 5

a.shift
=> 6

a.shift
=> 7

a = [5,6,7]
=> [5, 6, 7]

 a[0]
=> 5

a[0]
=> 5

Shift seems destructive. I thought it was the same.

How to count at a certain value

a = [1, 2, 3, 4]

count = 0

a.each do |i|
  if i == 1
    count += 1
  end
end

puts count

=>1

Conditional branch when divisible by a certain value

k = 2
a, b = [1, 3]

(a..b).each do |c|
  if c % k == 0
    puts  'OK'
    break
  end

  if c == b
    puts 'NG'
  end
end

How to keep looping until true

x = 2
yen = 100
count = 0

while yen > x do
  yen += yen / 100
  count = count + 1
end

puts count

While loops as long as it remains true. You don't need a conditional expression, just break yourself If you want to exit and exit, use loop do ... end! Of course, while true do ... end is fine.

Attach arrays into strings

a = ["a", "b", "c", "d"]
=> ["a", "b", "c", "d"]

 a.join
=> "abcd"

Find out how many specified characters there are after joining the arrays into a string

 a = ["a","b","a","b","a"]
=> ["a", "b", "a", "b", "a"]

a.join
=> "ababa"

a.join.scan("ab")
=> ["ab", "ab"]

#further"ab"Take out the number of.
a.join.scan("ab").length
=> 2

It seems that scan can be used quite well. ..

Specify the contents and index of the array block (value that repeats each time)

c = gets.chomp

alf = []
("a".."z").each do |i|
  alf << i
end

#Specify the contents and index of the array as blocks
alf.each_with_index do |k, i|
  if k == c
    puts alf[i+1]
    break
  end
end

If only k is used, the contents of the array "a", "b" ... "z" will be extracted. You can't specify an index, right? each.with.Using index|k, i|Then You can specify the index of the array in i. It's 0 in alf [0]. The content of the actual array is k.

How to make a one-dimensional or two-dimensional array

a = Array.new(3)
=> [nil, nil, nil]

a = Array.new(3).map{Array.new(3, 0)}
=> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

a[0][1] = 1
=> 1

 a
=> [[0, 1, 0], [0, 0, 0], [0, 0, 0]]

 a[2][1] = 1
=> 1

 a
=> [[0, 1, 0], [0, 0, 0], [0, 1, 0]]

a[2][0] = 1
=> 1

a
=> [[0, 1, 0], [0, 0, 0], [1, 1, 0]]

It's complicated when it comes to 2D

Repeat a string several times.

a = 2
=> 2

b = 3
=> 3

a.to_s * b
=> "222"

The input of a entered as a number is converted into a character string, and b is repeated 3 times.

Truncate, round up, round off numbers

a = 1.4
=> 1.4

a.floor
=> 1

 a.ceil
=> 2

a.round
=> 1

a =1.5
=> 1.5

a.floor
=> 1

a.ceil
=> 2

a.round
=> 2

Greatest common divisor and minimum common divisor of numbers

#Greatest common divisor
4.gcd(2)
=> 2

4.gcd(4)
=> 4

4.gcd(6)
=> 2


#Least common multiple
 4.lcm(2)
=> 4

4.lcm(4)
=> 4


4.lcm(6)
=> 12

Whether to output with puts, p, or print

To conclude first, puts are good. The answer does not match because p has "".

a = "aaa"
=> "aaa"

p a
"aaa"
=> "aaa"


 puts a
aaa
=> nil


 print a
aaa=> nil

Get the index of the value that is the index method

#String
a = ["3","4"]
=> ["3", "4"]

 a
=> ["3", "4"]

a.index("3")
=> 0

a.index("4")
=> 1

application

Array multiplication

n = gets.to_i
a = gets.split.map(&:to_i)
sum = 1

#Basically turn with each, but note that there is 0 in the multiplication
a.each do |i|
  if i == 0
    sum = 0
    break
  end

#Sum for large numbers<=Let's do 〇〇!
  sum *= i if sum <= 〇〇
end

Use to_d because an error will occur if to_f is used as the decimal point.

require 'bigdecimal'
require 'bigdecimal/util'

l = gets.chomp.split(" ")
a = l[0].to_i
#to_It seems that an error will occur if it is set to f
#The answer may not match.
b = l[1].to_d

puts (b * a).floor

Prime factorization

require 'prime'

a = 100
=> 100

 n = a.prime_division
=> [[2, 2], [5, 2]]

#[[2, 2], [5, 2]]Is"(2**2) * (5**2) = 100"That means

#Since it is a two-dimensional array, specify two elements
n.each do |i, k|
  puts i
  puts k
end

2
2
5
2
=> [[2, 2], [5, 2]]

Get all patterns in an array (permutation)

 n = 3
=> 3

a = [1,2,3]
=> [1, 2, 3]

a.permutation(n).to_a
=> [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

Very convenient!

Delete the specified character in the character string multiple times

n = "testrestdest"
=> "testrestdest"

a
=> ["test", "rest", "pest", "dest"]

a.each do |i|
  n.gsub!(/#{i}/, '')
end

n
=> ""

All disappeared It is destructive with gsub !.

Solve without searching the array

#Atcoder149B
#https://atcoder.jp/contests/abc149/tasks/abc149_b

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

k.times do
  if a >= 1
    a = a - 1
   elsif b >= 1
    b = b- 1
   elsif a = 0 && b = 0
  end
end
puts "#{a} #{b}"
#Time over

a, b, k = gets.split().map(&:to_i)
if a >= k
  puts "#{a-k} #{b}"
elsif a+b <= k
  puts "#{0} #{0}"
else
  puts "#{0} #{b-(k-a)}"
end
#OK

Be aware of absolute numbers when you are on the number line!

a and b are the first coordinates

a = 1
=> 1

a = -2
=> -2

 a - b
=> -5

(a - b).abs
=> 5

A value that returns to the original position from the input value [angle] in a linear function

x = gets.to_i

puts 360.lcm(x) / x

If the number is divisible by 360 degrees, you can divide it normally, If the value is not divisible by 360 degrees, find the least common multiple of 360 degrees It seems that you need to break it.

Recommended Posts

[Beginner] Let's solve AtCoder problem with Ruby while looking at the article!
[At Coder] Solve the ABC183 D problem with Ruby
[At Coder] Solve the ABC182 D problem with Ruby
[Competition Pro] Solve the knapsack problem with Ruby
Solve the N + 1 problem with Ruby on Rails: acts-as-taggable-on
Let's solve the FizzBuzz problem!
I tried to solve the problem of "multi-stage selection" with Ruby
Solve with Ruby AtCoder ABC177 D UnionFind
I tried to solve the tribonacci sequence problem in Ruby, with recursion.
AtCoder Beginner Contest 169 A, B, C with ruby
AtCoder ABC127 D hash to solve with Ruby 2.7.1
[Beginner's point of view] I tried to solve the FizzBuzz problem "easily" with Ruby!
Solve the Discrete Logarithm Problem with an arbitrary mod
AtCoder Beginner Contest 182 Participation Article
Solve Google problems with Ruby
Let's solve the roman numerals
AtCoder Beginner Contest 132 D Problem
[Ruby] problem with if statement
Solving with Ruby AtCoder ACL Beginner Contest C Union Find (DSU)