Avatar of mrios22

mrios22's solution

to Rectangles in the Rust Track

Published at Jun 23 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))
}
/* IMPORTANT COMMENT

The coordinate system in this program is all screwed up. Imagine that 'x' means 'row' and 'y' means 'column' and the matrices
are zero-indexed and you're halfway to understanding what's happening here. 

I used macros because I was sick and tired of the borrow checker's nonsense.

*/ 


type Point = (usize,usize); 
type Matrix = Vec<Vec<char>>;

macro_rules! get_xy {
    ($x:expr, $y:expr, $matrix:expr) => (
        if  $y < $matrix[$x].len()  && $matrix[$x].len() > 0 {
            Some($matrix[$x][$y])
        } else {
            None
        }
    )
}

macro_rules! get_x {
    ($pt:expr) => ($pt.0);
}

macro_rules! get_y {
    ($pt:expr) => ($pt.1);
}

macro_rules! is_on_vertical_segment {
    ($x:expr, $y:expr, $matrix:expr) => (
        if let Some(val) = get_xy!($x,$y,$matrix) {
            !['|','+'].contains(&val)
        } else {
            false
        }
    )
}

macro_rules! is_on_horizontal_segment {
    ($x:expr, $y:expr, $matrix:expr) => (
        if let Some(val) = get_xy!($x,$y,$matrix) {
            !['-','+'].contains(&val)
        } else {
            false
        }
    )
}

fn lines_to_matrix(lines: &[&str]) -> Matrix {
    lines.iter().map(|line| line.chars().collect::<Vec<char>>()).collect::<Matrix>()
}

fn contains_rect_with_points(upper_left: Point, lower_right: Point, matrix: &Matrix) -> bool {

    let x_min: usize = get_x!(upper_left); 
    let x_max: usize = get_x!(lower_right); 
    let y_min: usize = get_y!(upper_left);
    let y_max: usize = get_y!(lower_right); 

    // Time to scan for some dealbreakers. 

    if x_min >= x_max {                         // Supplied points must not be identical and must be upper left and lower right.
        return false                            //
    } else if y_min >= y_max {                  // 
        return false
    } 

    if get_xy!(x_min,y_min,matrix) != Some('+') {
        return false
    } else if get_xy!(x_max,y_max,matrix) != Some('+') {
        return false
    } else if get_xy!(x_min,y_max,matrix) != Some('+') {
        return false
    } else if get_xy!(x_max,y_min,matrix) != Some('+') {
        return false 
    }

    for x in x_min..x_max {
        if is_on_vertical_segment!(x,y_min, matrix) {
            return false
        } else if is_on_vertical_segment!(x,y_max, matrix)  {
            return false 
        } 
    }

    for y in y_min..y_max {
        if is_on_horizontal_segment!(x_min, y, matrix){
            return false 
        } else if is_on_horizontal_segment!(x_max, y, matrix){
            return false
        }
    }

    return true
}

pub fn count(lines: &[&str]) -> u32 {

    let mut possible_corners: Vec<Point> = vec![];
    let matrix = lines_to_matrix(lines);
    let mut rectangle_count = 0;

    for x in 0.. {
        if x < matrix.len() {
            for y in 0.. {
                if let Some(val) = get_xy!(x,y,matrix) {
                    if val == '+' {
                        possible_corners.push((x,y));
                    }
                } else {
                    break;
                }

            }
        } else {
            break;
        }
    }

    for possible_upper_left_corner in possible_corners.iter() {
        for possible_lower_right_corner in possible_corners.iter() {

            if contains_rect_with_points(*possible_upper_left_corner, *possible_lower_right_corner, &matrix){
                rectangle_count += 1;
            }
        }
    } 

    rectangle_count
}

Community comments

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

mrios22's Reflection

This needs some refactoring -- use impl's instead of macros, fix the coordinate system, etc. but it passes the tests.