Advertisement
Guest User

Untitled

a guest
Aug 24th, 2019
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. /*
  2. Flavius Josephus was a famous Jewish historian of the first century,
  3. at the time of the destruction of the Second Temple. According to legend,
  4. during the Jewish-Roman war he was trapped in a cave with a group of
  5. forty soldiers surrounded by Romans. Preferring death to capture,
  6. the Jews decided to form a circle and, proceeding around it, to kill
  7. every third person remaining until no one was left. Josephus found the
  8. safe spot in the circle and thus stayed alive.
  9.  
  10. Write a function josephus(n,m) that returns a list of n people,
  11. numbered from 0 to n-1, in the order in which they are executed,
  12. every mth person in turn, with the sole survivor as the last person
  13. in the list.
  14.  
  15. What is the value of josephus(41,3)?
  16. In what position did Josephus survive?
  17. */
  18.  
  19. struct Josephus {
  20. people: Vec<Option<usize>>,
  21. m: usize,
  22. current: usize,
  23. count: usize,
  24. }
  25.  
  26. impl Iterator for Josephus {
  27. type Item = usize;
  28. fn next(&mut self) -> Option<Self::Item> {
  29. if self.count == 0 {
  30. return None
  31. }
  32. for i in 0..self.m {
  33. self.current = (self.current + 1) % self.people.len();
  34. while self.people[self.current].is_none() {
  35. self.current = (self.current + 1) % self.people.len();
  36. }
  37. }
  38. self.count -= 1;
  39. self.people[self.current] = None;
  40. Some(self.current)
  41. }
  42. }
  43.  
  44. impl Josephus {
  45. fn new(size: usize, m: usize) -> Self {
  46. let mut j = Josephus{ count: size, m: m, current: size - 1, people: vec!() };
  47. for i in 0..size {
  48. j.people.push(Some(i));
  49. }
  50. j
  51. }
  52. }
  53.  
  54. fn main() {
  55. let mut x = Josephus::new(41, 3).peekable();
  56. while let Some(p) = x.next() {
  57. if x.peek().is_none() {
  58. println!("\nfinal position = {}", p)
  59. } else {
  60. print!("{} ", p);
  61. }
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement