Simple Programming
1 minute to read
We are given a file called data.dat
and we are told to count every line that has a number of 0
that is multiple of 3
or that has a number of 1
that is a multiple of 2
.
We can take a look at the first lines of the file:
$ head data.dat
0001100000101010100
110101000001111
101100011001110111
0111111010100
1010111111100011
1110011110010110
11100101010110111
10101101011
1111011101001
0001110001
Alright. The idea is to iterate the file on each line and add 1
to a counter (initialized with 0
) if the condition is satisfied.
This Ruby code does the task:
#!/usr/bin/env ruby
counter = 0
File.readlines('data.dat').each do |line|
counter += 1 if line.count('0') % 3 == 0 or line.count('1') % 2 == 0
end
puts "CTFlearn{#{counter}}"
$ ruby solve.rb
CTFlearn{6662}
It is also possible to use filter
to remove all the unwanted lines, and some number methods, and then just print the length of the resulting array:
#!/usr/bin/env ruby
puts "CTFlearn{#{File.readlines('data.dat').filter do |line|
(line.count('0') % 3).zero? or line.count('1').even?
end.length}}"