Skip to content

Instantly share code, notes, and snippets.

@dharshan
Created December 15, 2017 12:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dharshan/824ad5f8b9e40bd9332f89dcda2dbc31 to your computer and use it in GitHub Desktop.
Save dharshan/824ad5f8b9e40bd9332f89dcda2dbc31 to your computer and use it in GitHub Desktop.
A smart-set is a set of distinct numbers in which all the elements have the same number of 1s in their binary form. The set of all smallest elements from each smart-set that can be formed from a given array of distinct positive numbers is known as the smartest-set.
### smart sets, nestaway challenge skilenza
# Pseudo code
# Take number of test case
# Take array size
# Take array elements
# Test all are within give range
# Convert array elements into binary format
# Group binary elements based on number of 1's present
# Sort grouped elements in ascending order
# take first element from each set and display
test_cases_range = 1..1000 # ranges for input validation
arr_size_range = 1..10_000
arr_num_size_range = 1..100_000
test_cases = gets.chomp.to_i
if test_cases_range.cover? test_cases
while test_cases > 0
arr_size = gets.chomp.to_i
if arr_size_range.cover? arr_size
nums = gets.chomp
nums = nums.split(' ').map(&:to_i) # input to integer arary
if !nums.any? { |num| arr_num_size_range.cover? num }
puts 'Array elements are out of range'
else
bin_hash = {}
nums.each do |num|
bin_hash[num.to_s] = num.to_s(2).scan(/1/).count # convert anc scan for 1's and store it in hash
end
bin_array = bin_hash.group_by { |_k, v| v }.sort.map(&:flatten) # group hash by comman values and sort. convert them to array groups
bin_array = bin_array.map { |arr| arr.select { |n_arr| n_arr.class == String } } # extract input number from array group
bin_array.each { |arr| arr.map!(&:to_i) } # convert array group to integers (easy for sorting)
bin_array.each(&:sort!) # sort internal array elements
res = bin_array.collect(&:first) # collect all first elements from array group
res.each { |num| print num; print ' ' } # use print inorde tp print output in a line
test_cases -= 1
print "\n" # to print next set in next line
end
else
puts 'array size number is out of range'
end
end
else
puts 'test case numbers are out of range'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment