I’ve spent some time solving Leetcode problems. More technically I’ve had a few issues with 54. Spiral Matrix and 59. Spiral Matrix II and now I find that solutions would have been much easier had I used Stride.
- None, a basic knowledge of programming in Swift would be helpful
Sequentially: A logical order or sequence
Stride: A function to stride over values of any type
Imagine you want to move through an array.
The traditional way is to use a for loop. An alternative is to use stride, and that produces the same result.
The syntax is rather different, but at first glance you can pick one or the other and be relatively pleased with either choice.
This article is about choosing Stride in Swift. Why?
The advantages of Stride over a for loop
- You can move through an array or set of numbers sequentially, in units that may be larger than one
- Negative values are possible!
- Stride works with non-Integer values
Let us look at these step-by-step:
Moving in units larger than one (although, of course one is also acceptable)
this can be
by: 1 of course.
Negative values in Stride
This works kind of “in reverse” from the normal stride. Start high, and move negatively.
Stride with non-Integer values
We can use Stride with non-Integer values.
Wait! There are two Strides?
We can actually see from the compiler’s autocomplete that there are two Strides; StrideThrough and StrideTo,
It might not be a surprise, but one of these goes to the last value and one includes it.
Which one? take a look at the code below:
Want to take a look at a video
Ok, no problem.
The Leetcode problem
Leetcode 34 ramps things up a little bit further.
It asks us to output a spiral from a 2-dimensional matrix.
You probably know the solution from here. A judicious use of Stride will help us out. Here is a solution: