Avatar of waltersamson

waltersamson's solution

to Rectangles in the Rust Track

Published at May 28 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))
}
const VERTEX: u8 = b'+';
const HORIZ_EDGE: u8 = b'-';
const VERT_EDGE: u8 = b'|';

#[derive(Clone, Copy, Debug)]
struct Point {
    y: usize,
    x: usize,
}

#[derive(Clone, Copy, Debug)]
struct Edge {
    left: Point,
    right: Point,
}

#[derive(Clone, Copy, Debug)]
struct Square {
    top: Edge,
    bot: Edge,
}

pub fn count(lines: &[&str]) -> u32 {
    let mut count = 0;
    for (y, row) in lines.iter().enumerate() {
        for (x, token) in row.bytes().enumerate() {
            if token == VERTEX {
                count += count_from_topleft(y, x, lines);
            }
        }
    }
    count
}

fn count_from_topleft(y: usize, x: usize, lines: &[&str]) -> u32 {
    let mut topedges = Vec::<Edge>::new();
    for (i, token) in lines[y].bytes().enumerate() {
        if i > x && token == VERTEX {
            topedges.push(
                Edge{left: Point{y: y, x: x}, right: Point{y: y, x: i}}
            );
        }
    }
    count_from_topedges(topedges, lines)
}

fn count_from_topedges(topedges: Vec<Edge>, lines: &[&str]) -> u32 {
    let mut count = 0;
    for edge in topedges {
        for y in edge.left.y+1..lines.len() {
            if lines[y].as_bytes()[edge.left.x] == VERTEX &&
                lines[y].as_bytes()[edge.right.x] == VERTEX
            {
                let bot_edge = Edge{
                    left: Point{y: y, x: edge.left.x},
                    right: Point{y: y, x: edge.right.x}
                };
                let square_candidate = Square{top: edge, bot: bot_edge};
                if is_valid_square(square_candidate, lines) {
                    count += 1;
                }
            }
        }
    }
    count
}

fn is_valid_square(square: Square, lines: &[&str]) -> bool {
    if lines[square.top.left.y]
        .as_bytes()[square.top.left.x+1..square.top.right.x]
        .iter()
        .any(|c| *c != HORIZ_EDGE && *c != VERTEX) {return false;}
    if lines[square.bot.left.y]
        .as_bytes()[square.bot.left.x+1..square.bot.right.x]
        .iter()
        .any(|c| *c != HORIZ_EDGE && *c != VERTEX) {return false;}
    for row in &lines[square.top.left.y+1..square.bot.left.y] {
        if (row.as_bytes()[square.top.left.x] != VERT_EDGE &&
            row.as_bytes()[square.top.left.x] != VERTEX) ||
            (row.as_bytes()[square.top.right.x] != VERT_EDGE &&
            row.as_bytes()[square.top.right.x] != VERTEX) {return false;}
    }
    true
}

Community comments

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

waltersamson's Reflection

Just a translation of the Go submission I did earlier this year.