From the course: Code Clinic: Ruby
Unlock the full course today
Join today to access over 22,400 courses taught by industry experts or purchase this course individually.
Using loops
- Now that we have all the tools that we need, let's begin our first attempt at solving this challenge. Let's do that by using loops. If you have any prior programming experience, then you'll be familiar with loops. They're useful and they're used often. In Ruby, one of the simplest kinds of loops is times. In this example, the code will loop through eight times. It will repeat itself eight different times. And each time through the loop, the value of n will be to assign a number, starting with zero and incrementing until it gets to seven. When you think of our chess board, we can use a loop like this to loop over each of the eight columns in order to place each of our eight queens. Then, to place a queen in each column, we can loop over each of the eight rows in that column and test each location. If the location is safe, we'll place a queen there and move to the next column. If the location is not safe, then we'll keep going to the next row. Let me show you what that code looks…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
-
Eight Queens problem1m 46s
-
Hints, tips, and tricks3m 54s
-
Overview of my solution5m 55s
-
Queen and board classes6m 10s
-
Displaying the board7m 1s
-
Determining safe positions6m 48s
-
Using loops7m 8s
-
Loops with backtracking5m 12s
-
Loops with smarter backtracking6m 2s
-
Recursion primer3m 45s
-
Using recursion6m 52s
-
Finding all possible solutions5m 46s
-
Further exercises3m 56s
-
-
-
-