Avatar of Ragusaen

Ragusaen's solution

to Rectangles in the Rust Track

Published at Aug 18 2019 · 0 comments
Instructions
Test suite
Solution

Count the rectangles in an ASCII diagram like the one below.

   +--+
  ++  |
+-++--+
|  |  |
+--+--+

The above diagram contains 6 rectangles:



+-----+
|     |
+-----+
   +--+
   |  |
   |  |
   |  |
   +--+
   +--+
   |  |
   +--+




   +--+
   |  |
   +--+


+--+
|  |
+--+

  ++
  ++


You may assume that the input is always a proper rectangle (i.e. the length of every line equals the length of the first line).

Rust Installation

Refer to the exercism help page for Rust installation and learning resources.

Writing the Code

Execute the tests with:

$ cargo test

All but the first test have been ignored. After you get the first test to pass, open the tests source file which is located in the tests directory and remove the #[ignore] flag from the next test and get the tests to pass again. Each separate test is a function with #[test] flag above it. Continue, until you pass every test.

If you wish to run all tests without editing the tests source file, use:

$ cargo test -- --ignored

To run a specific test, for example some_test, you can use:

$ cargo test some_test

If the specific test is ignored use:

$ cargo test some_test -- --ignored

To learn more about Rust tests refer to the online test documentation

Make sure to read the Modules chapter if you haven't already, it will help you with organizing your files.

Further improvements

After you have solved the exercise, please consider using the additional utilities, described in the installation guide, to further refine your final solution.

To format your solution, inside the solution directory use

cargo fmt

To see, if your solution contains some common ineffective use cases, inside the solution directory use

cargo clippy --all-targets

Submitting the solution

Generally you should submit all files in which you implemented your solution (src/lib.rs in most cases). If you are using any external crates, please consider submitting the Cargo.toml file. This will make the review process faster and clearer.

Feedback, Issues, Pull Requests

The exercism/rust repository on GitHub is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help!

If you want to know more about Exercism, take a look at the contribution guide.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

rectangles.rs

use rectangles::count;

#[test]
fn test_zero_area_1() {
    let lines = &[];
    assert_eq!(0, count(lines))
}

#[test]
#[ignore]
fn test_zero_area_2() {
    let lines = &[""];
    assert_eq!(0, count(lines))
}

#[test]
#[ignore]
fn test_empty_area() {
    let lines = &[" "];
    assert_eq!(0, count(lines))
}

#[test]
#[ignore]
fn test_one_rectangle() {
    let lines = &[
        "+-+",
        "| |",
        "+-+",
        ];
    assert_eq!(1, count(lines))
}

#[test]
#[ignore]
fn test_two_rectangles_no_shared_parts() {
    let lines = &[
        "  +-+",
        "  | |",
        "+-+-+",
        "| |  ",
        "+-+  "
        ];
    assert_eq!(2, count(lines))
}

#[test]
#[ignore]
fn test_five_rectangles_three_regions() {
    let lines = &[
        "  +-+",
        "  | |",
        "+-+-+",
        "| | |",
        "+-+-+"
        ];
    assert_eq!(5, count(lines))
}

#[test]
#[ignore]
fn rectangle_of_height_1() {
    let lines = &[
        "+--+",
        "+--+"
        ];
    assert_eq!(1, count(lines))
}

#[test]
#[ignore]
fn rectangle_of_width_1() {
    let lines = &[
        "++",
        "||",
        "++"
        ];
    assert_eq!(1, count(lines))
}

#[test]
#[ignore]
fn unit_square() {
    let lines = &[
        "++",
        "++"
        ];
    assert_eq!(1, count(lines))
}

#[test]
#[ignore]
fn test_incomplete_rectangles() {
    let lines = &[
        "  +-+",
        "    |",
        "+-+-+",
        "| | -",
        "+-+-+"
        ];
    assert_eq!(1, count(lines))
}

#[test]
#[ignore]
fn test_complicated() {
    let lines = &[
        "+------+----+",
        "|      |    |",
        "+---+--+    |",
        "|   |       |",
        "+---+-------+"
        ];
    assert_eq!(3, count(lines))
}

#[test]
#[ignore]
fn test_not_so_complicated() {
    let lines = &[
        "+------+----+",
        "|      |    |",
        "+------+    |",
        "|   |       |",
        "+---+-------+"
        ];
    assert_eq!(2, count(lines))
}

#[test]
#[ignore]
fn test_large_input_with_many_rectangles() {
    let lines = &[
        "+---+--+----+",
        "|   +--+----+",
        "+---+--+    |",
        "|   +--+----+",
        "+---+--+--+-+",
        "+---+--+--+-+",
        "+------+  | |",
        "          +-+"
        ];
    assert_eq!(60, count(lines))
}
pub const starting_direction: (i32, i32) = (1,0);

pub fn count(lines: &[&str]) -> u32 {
    let mut rectangles: i32 = 0;

    for y in 0..lines.len() {
        for x in 0..lines[y].len() {
            if lines[y].as_bytes()[x] == '+' as u8 {
                rectangles += walk_through_rectangles(lines, (x as i32, y as i32));
            }
        }
    }

    rectangles as u32
}

// Returns the number of rectangles that was found from the corner
pub fn walk_through_rectangles(lines: &[&str], pos: (i32, i32)) -> i32 {
    walk_along_sides(lines, pos, (pos.0 + 1, pos.1), starting_direction)
}


// Returns amount of rectangular trips that ended in the starting position
pub fn walk_along_sides(lines: &[&str], start_pos: (i32, i32), current_pos: (i32, i32), direction: (i32, i32)) -> i32 {
    println!("Now walking ({0}, {1}) with direction ({2}, {3})", current_pos.0, current_pos.1, direction.0, direction.1);

    if start_pos == current_pos {
        return 1;
    }

    if current_pos.1 >= lines.len() as i32 || current_pos.1 < 0 || current_pos.0 >= lines[0].as_bytes().len() as i32 || current_pos.0 < 0 {
        return 0;
    }
    let c: char = lines[current_pos.1 as usize].as_bytes()[current_pos.0 as usize] as char;

    if c == ' ' {
        return 0;
    } else if c == '+' {
        let mut r = 0;

        println!("Split directions");

        let new_pos = (current_pos.0 + direction.0, current_pos.1 + direction.1);
        r += walk_along_sides(lines, start_pos, new_pos, direction);

        println!("Branch collapsed");

        // If turning causes a complete turn, then kill don't create the branch
        let new_direction = rotate_direction(direction);
        if new_direction != starting_direction {
            let new_pos = (current_pos.0 + new_direction.0, current_pos.1 + new_direction.1);
            r += walk_along_sides(lines, start_pos, new_pos, new_direction);            
        }
        println!("Other branch collapsed");
        return r;
    } else if (c == '-' && direction.0 != 0) || (c == '|' && direction.1 != 0) {
        let new_pos = (current_pos.0 + direction.0, current_pos.1 + direction.1);
        return walk_along_sides(lines, start_pos, new_pos, direction);
    }
    
    0
}


pub fn rotate_direction(direction: (i32, i32)) -> (i32, i32) {
    (-direction.1, direction.0)
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

Ragusaen's Reflection

The principle of my solution is that each rectangle must have a top-left corner, so I treat all vertices as top-left corners, and check if there are rectangles from this. This is done by walking anti-clockwise around the rectangle and splitting up into branches whenever another vertex is met. I have done this recursively, and the recursion stop at either: reaching back to the starting point, which means there is a rectangle; having completed a full turn, which means we did not find a rectangle in this branch; or having stepped outside of the lines or on a perpendicular line.