Guest User

Untitled

a guest
Apr 20th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.02 KB | None | 0 0
  1. mod minesweeper {
  2. use std;
  3.  
  4. pub fn is_mine(string: &str, x_pos: usize) -> bool {
  5. string.chars().nth(x_pos).unwrap() == '*'
  6. }
  7.  
  8. pub fn fill(empty: Vec<&str>) -> Vec<std::string::String> {
  9. let mut result = vec![];
  10.  
  11. for (y_pos, row) in empty.iter().enumerate() {
  12. let mut new_row = String::from(empty[y_pos]);
  13.  
  14. for (x_pos, c) in row.chars().enumerate() {
  15. let b_up: bool = y_pos > 0;
  16. let b_down: bool = empty.len() > y_pos + 1;
  17. let b_left: bool = x_pos > 0;
  18. let b_right: bool = row.len() > x_pos + 1;
  19.  
  20. let mine_count = [
  21. // looking up
  22. b_up && is_mine(empty[y_pos - 1], x_pos),
  23. // looking down
  24. b_down && is_mine(empty[y_pos + 1], x_pos),
  25. // looking left
  26. b_left && is_mine(empty[y_pos], x_pos - 1),
  27. // looking right
  28. b_right && is_mine(empty[y_pos], x_pos + 1),
  29. // looking up left
  30. b_up && b_left && is_mine(empty[y_pos - 1], x_pos - 1),
  31. // looking up right
  32. b_up && b_right && is_mine(empty[y_pos - 1], x_pos + 1),
  33. // looking down left
  34. b_down && b_left && is_mine(empty[y_pos + 1], x_pos - 1),
  35. // looking down right
  36. b_down && b_right && is_mine(empty[y_pos + 1], x_pos + 1)
  37. ].iter().filter(|x| **x ).count();
  38.  
  39. if c == ' ' && mine_count > 0 {
  40. new_row.remove(x_pos);
  41. new_row.insert(x_pos, mine_count.to_string()
  42. .chars()
  43. .next()
  44. .unwrap());
  45. }
  46. }
  47. result.push(new_row);
  48. };
  49.  
  50. result
  51. }
  52. }
  53.  
  54. #[test]
  55. fn add_numbers_to_empty_sweeper_board() {
  56. assert_eq!(
  57. minesweeper::fill(vec![
  58. " ",
  59. " ",
  60. " "
  61. ]),
  62. vec![
  63. " ",
  64. " ",
  65. " "
  66. ]
  67. )
  68. }
  69.  
  70. #[test]
  71. fn add_numbers_to_filled_sweeper_board() {
  72. assert_eq!(
  73. minesweeper::fill(vec![
  74. "** ",
  75. " ",
  76. " "
  77. ]),
  78. vec![
  79. "**1",
  80. "221",
  81. " "
  82. ]
  83. )
  84. }
  85.  
  86. #[test]
  87. fn add_numbers_to_all_mines() {
  88. assert_eq!(
  89. minesweeper::fill(vec![
  90. "***",
  91. "* *",
  92. "***"
  93. ]),
  94. vec![
  95. "***",
  96. "*8*",
  97. "***"
  98. ]
  99. )
  100. }
  101.  
  102. #[test]
  103. fn add_numbers_to_bigger_filled_sweeper_board() {
  104. assert_eq!(
  105. minesweeper::fill(vec![
  106. "** ",
  107. " ",
  108. " * ",
  109. " "
  110. ]),
  111. vec![
  112. "**1 ",
  113. "2321",
  114. " 1*1",
  115. " 111"
  116. ]
  117. )
  118. }
Add Comment
Please, Sign In to add comment