SHARE
TWEET

Untitled

a guest Apr 19th, 2019 79 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Iterate over a 2D array in a spiral pattern.
  2.  
  3.    The first spiral looks like this:
  4.        1
  5.      ┍━──┐   (starting segment highlighted)
  6.    4 │   │ 2
  7.      └───┘
  8.        3
  9.  
  10.    All remaining spirals look like this:
  11.        1
  12.     ━┭───┐
  13.    4 │   │ 2
  14.      └───┘
  15.        3
  16. */
  17. fn main() {
  18.   let m = [[1,  2,  3,  4,  5],
  19.            [6,  7,  8,  9,  10],
  20.            [11, 12, 13, 14, 15],
  21.            [16, 17, 18, 19, 20]];
  22.  
  23.   let mut steps = [m[0].len()-1, m.len()-1];
  24.   let mut xy = 0;
  25.  
  26.   let mut i = [0, 0];
  27.   let mut increment = true;
  28.   let mut first = true;
  29.  
  30.   println!("{:?}", m[i[1]][i[0]]);
  31.   while steps[xy] > 0 {
  32.     let mut s = steps[xy];
  33.     while s > 0 {
  34.       if increment {
  35.         i[xy] += 1;
  36.       } else {
  37.         i[xy] -= 1;
  38.       }
  39.       println!("{:?}", m[i[1]][i[0]]);
  40.       s -= 1;
  41.     }
  42.  
  43.     if !first {
  44.       steps[xy] -= 1;
  45.     } else {
  46.       first = false;
  47.     }
  48.     if xy == 1 {
  49.       increment = !increment;
  50.     }
  51.     xy = if xy == 0 { 1 } else { 0 };
  52.   }
  53. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top