Skip to content

Instantly share code, notes, and snippets.

@Riveascore
Created August 5, 2020 03:31
Show Gist options
  • Save Riveascore/7718eef77d281b770d3553e46976be31 to your computer and use it in GitHub Desktop.
Save Riveascore/7718eef77d281b770d3553e46976be31 to your computer and use it in GitHub Desktop.
Count the number of derrangements of an array
class CountDerangements
def initialize(set_size)
@set_size = set_size
@solution_n = solution_n_minus_1 = solution_n_minus_2 = 0
for n in 1..@set_size
if n == 1
@solution_n = 0
elsif n == 2
@solution_n = 1
else
@solution_n = (n - 1) * (solution_n_minus_1 + solution_n_minus_2)
end
solution_n_minus_2 = solution_n_minus_1
solution_n_minus_1 = @solution_n
end
end
def count_derangements
@solution_n
end
end
# for i in 1..64
for i in 1..10
n = CountDerangements.new(i).count_derangements
puts("Derangments in set size %d -> %d" % [i, n])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment