Created
January 14, 2019 20:29
-
-
Save theterminalguy/a08de1b8dc0b3b8c6442ec8783d3ea02 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def permutations(day_hours, missing_days, target) | |
results = [] | |
values = (0..day_hours).to_a | |
size = missing_days | |
puts target | |
permuts = values.repeated_permutation(size).to_a | |
permuts.each do |permut| | |
if permut.inject(:+) == target.to_i | |
results.push(permut.join(',')) | |
end | |
end | |
results | |
end | |
def find_schedules(work_hours, day_hours, pattern) | |
result = [] | |
days = pattern.split("") | |
missing_days = days.find_all { |i| i.eql? '?' }.count | |
missing_days_indexes = (days.map.with_index do |day, i| | |
(day == '?') ? i : nil | |
end).compact | |
hours_worked = days.select{ |i| i != '?'}.map(&:to_i).inject(:+) || 0 | |
pending_work_hours = work_hours.to_i - hours_worked.to_i | |
periods = permutations(day_hours, missing_days, pending_work_hours) | |
periods.each.with_index do |period, index| | |
new_periods = period.split(',') | |
new_pattern = Hash[missing_days_indexes.zip(new_periods)] | |
new_pattern.keys.each do |key| | |
days[key] = new_pattern[key] | |
end | |
result.push(days.join('')) | |
end | |
result | |
end | |
#find_schedules(56, 8, '???8???'); | |
find_schedules(24, 4, '08??840'); | |
#https://robots.thoughtbot.com/better-date-manipulation-in-postgres-queries | |
#https://www.mathplanet.com/education/algebra-2/discrete-mathematics-and-probability/permutations-and-combinations | |
https://codepen.io/jopico/pen/EGpim?editors=1000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment