How to resolve the algorithm Population count step by step in the Ruby programming language
How to resolve the algorithm Population count step by step in the Ruby programming language
Table of Contents
Problem Statement
The population count is the number of 1s (ones) in the binary representation of a non-negative integer. Population count is also known as:
For example, 5 (which is 101 in binary) has a population count of 2.
Evil numbers are non-negative integers that have an even population count. Odious numbers are positive integers that have an odd population count.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Population count step by step in the Ruby programming language
The provided Ruby code extends the Integer class with two instance methods: popcount and evil?. It also includes some sample usage of these methods. Here's a detailed explanation:
-
Integer#popcount: This method counts the number of 1 bits in the binary representation of an integer. In Ruby 2.4 and later, it uses thedigitsmethod to convert the integer to a base-2 array and then counts the occurrences of 1 in that array. In Ruby versions prior to 2.4, it converts the integer to a binary string usingto_s(2)and counts the occurrences of "1" in the string. -
Integer#evil?: This method returnstrueif the integer is non-negative and the number of 1 bits in its binary representation is even. Otherwise, it returnsfalse. An "evil" number is a non-negative integer with an even number of 1 bits in its binary representation. -
After defining the instance methods, the code includes some sample usage:
- It calculates and prints the popcount for powers of 3 from 0 to 29 using the
mapmethod andjoinmethod. - It prints the first 30 evil numbers using the
stepmethod,lazymethod, andselectmethod to filter out non-evil numbers. - It prints the first 30 non-evil numbers using the
stepmethod,lazymethod, andrejectmethod to filter out evil numbers.
- It calculates and prints the popcount for powers of 3 from 0 to 29 using the
Source code in the ruby programming language
class Integer
def popcount
digits(2).count(1) #pre Ruby 2.4: self.to_s(2).count("1")
end
def evil?
self >= 0 && popcount.even?
end
end
puts "Powers of 3:", (0...30).map{|n| (3**n).popcount}.join(' ')
puts "Evil:" , 0.step.lazy.select(&:evil?).first(30).join(' ')
puts "Odious:", 0.step.lazy.reject(&:evil?).first(30).join(' ')
You may also check:How to resolve the algorithm RIPEMD-160 step by step in the Ruby programming language
You may also check:How to resolve the algorithm Sorting algorithms/Comb sort step by step in the Ruby programming language
You may also check:How to resolve the algorithm IBAN step by step in the Ruby programming language
You may also check:How to resolve the algorithm Wieferich primes step by step in the Ruby programming language
You may also check:How to resolve the algorithm Non-continuous subsequences step by step in the Ruby programming language