Avatar of theIDinside

theIDinside's solution

to Rectangles in the Rust Track

Published at May 18 2020 · 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 ignored 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))
}
#[derive(Clone, Copy)]
struct Pos {
    x: usize,
    y: usize,
}

impl PartialEq for Pos {
    fn eq(&self, other: &Pos) -> bool {
        self.x == other.x && self.y == other.y
    }

    fn ne(&self, other: &Pos) -> bool {
        !(self == other)
    }
}

impl Pos {
    pub fn new(x: usize, y: usize) -> Pos { Pos { x, y } }
}

struct Line {
    left: Pos,
    right: Pos
}

impl Line {
    pub fn new(left: Pos, right: Pos) -> Line { Line { left, right } }
}

impl PartialEq for Line {
    fn eq(&self, rhs: &Line) -> bool {
        (self.left == rhs.left && self.right == rhs.right) || (self.left == rhs.right && self.right == rhs.left)
    }
}

fn pos_are_vertically_aligned(pos_a: &Pos, pos_b: &Pos) -> bool {
    pos_a.x == pos_b.x
}

fn lines_are_vertically_aligned(line_a: &Line, line_b: &Line) -> bool {
    pos_are_vertically_aligned(&line_a.left, &line_b.left) && pos_are_vertically_aligned(&line_a.right, &line_b.right)
}
/// Checks to see if corners all are connected with lines, thus is a well formed rectangle
fn is_well_formed_rectagle(top: &Line, bottom: &Line, string_source_map: &[&str]) -> bool {
    for y in top.left.y .. bottom.left.y {
        if &string_source_map[y][top.left.x .. bottom.left.x + 1] != "|" &&  &string_source_map[y][top.left.x .. bottom.left.x + 1] != "+" {
            return false;
        }
    }
    for y in top.right.y .. bottom.right.y {
        if &string_source_map[y][top.right.x .. bottom.right.x + 1] != "|" && &string_source_map[y][top.right.x .. bottom.right.x + 1] != "+" {
            return false;
        }
    }
    true
}

pub fn count(lines: &[&str]) -> u32 {
    let mut corners: Vec<Pos> = Vec::new();
    let mut validated_horizontal_lines: Vec<Line> = Vec::new();

    for (y, line) in lines.iter().enumerate() {
        for (x, ch) in line.chars().enumerate() {
            if ch == '+' {
                corners.push(Pos::new(x, y));
            }
        }
    }
    // Corners in each input string-line are ordered by their x-value, due to the input. Therefore we don't need error-checking of what corner is left-most.
    // Valid horizontal lines are ++, two corners next to each other and +----+, two corners with an X amount of '-' between them.
    // Lines can stretch across multiple corners, so +--+ is one line and +--+------+ is actually 3 lines, the +--+, +------+ and both combined
    for (idx, corner) in corners.iter().enumerate() {
        'inner: for n_corner in corners.iter().skip(idx + 1) {
            if corner.y == n_corner.y && corner != n_corner {
                let mut valid = false;
                'validate: for x in corner.x .. (n_corner.x) {
                    if &lines[corner.y][x..x+1] != "+" && &lines[corner.y][x..x+1] != "-" {
                        // isn't valid data. Has to be either '+' or '-' 
                        println!("{} is not valid map element", &lines[corner.y][x..x]);
                        valid = false;
                        break 'validate;
                    } else {
                        valid = true;
                    }
                }
                if valid {
                    validated_horizontal_lines.push(Line::new(*corner, *n_corner));
                }
            } else {
                break 'inner;
            }
        }
    }

    let mut count = 0;
    println!("Horizontal line count: {}", validated_horizontal_lines.len());
    for (idx, line) in validated_horizontal_lines.iter().enumerate() {
        for n_line in validated_horizontal_lines.iter().skip(idx+1) {
            if lines_are_vertically_aligned(&line, &n_line) && is_well_formed_rectagle(&line, &n_line, lines) {
                count += 1;
            }
        }
    }
    count
}

Community comments

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

theIDinside's Reflection

This solution is purely solved for what is asked. I figure some cool data structures can be used here, or some recursive searching through the string array data, but that seems as doing too much for this particular exercise. I also haven't tried optimizing it in any particular way either.