Avatar of HarrisonMc555

HarrisonMc555's solution

to Rectangles in the Rust Track

Published at Feb 28 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

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(Debug, Copy, Clone, Eq, PartialEq)]
enum Tile {
    Corner,
    Horizontal,
    Vertical,
    Empty,
}

type Grid = Vec<Vec<Tile>>;
type GridRef<'a> = &'a [Vec<Tile>];
type Location = (usize, usize);

pub fn count(lines: &[&str]) -> u32 {
    let tiles = match to_tiles(lines) {
        Some(tiles) => tiles,
        None => return 0,
    };
    count_rectangles(&tiles)
}

fn count_rectangles(tiles: GridRef) -> u32 {
    if tiles.is_empty() {
        return 0;
    }
    let row_indices = 0..tiles.len();
    let num_rectangles_from_rows =
        row_indices.map(|i| count_rectangles_from_row(tiles, i));
    num_rectangles_from_rows.sum()
}

fn count_rectangles_from_row(tiles: GridRef, row_index: usize) -> u32 {
    let col_indices_and_tiles = tiles[row_index].iter().enumerate();
    let top_left_corners =
        col_indices_and_tiles.filter(|(_, tile)| tile.is_corner());
    let num_rectangles_from_corners = top_left_corners
        .map(|(j, _)| count_rectangles_from_top_left(tiles, (row_index, j)));
    num_rectangles_from_corners.sum()
}

fn count_rectangles_from_top_left(tiles: GridRef, location: Location) -> u32 {
    let (row_index, col_index) = location;
    let col_indices = col_index + 1..tiles[0].len();
    let col_indices_and_tiles = col_indices.map(|j| (j, tiles[row_index][j]));
    let connected_horizontally = col_indices_and_tiles
        .take_while(|(_, tile)| tile.connects_horizontally());
    let connected_corners =
        connected_horizontally.filter(|(_, tile)| tile.is_corner());
    let num_rectangles_from_corners = connected_corners
        .map(|(j, _)| count_rectangles_from_top_right(tiles, j, location));
    num_rectangles_from_corners.sum()
}

fn count_rectangles_from_top_right(
    tiles: GridRef,
    col_index: usize,
    original_corner: Location,
) -> u32 {
    let (row_index, _) = original_corner;
    let row_indices = row_index + 1..tiles.len();
    let row_indices_and_tiles = row_indices.map(|i| (i, tiles[i][col_index]));
    let connected_vertically = row_indices_and_tiles
        .take_while(|(_, tile)| tile.connects_vertically());
    let corners_of_rectangles = connected_vertically.filter(|&(i, tile)| {
        let location = (i, col_index);
        tile.is_corner()
            && does_connect_from_bottom_right(tiles, location, original_corner)
    });
    let num_rectangles = corners_of_rectangles.count();
    num_rectangles as u32
}

fn does_connect_from_bottom_right(
    tiles: GridRef,
    location: Location,
    original_corner: Location,
) -> bool {
    let (row_index, col_index) = location;
    let (_, original_col) = original_corner;
    let horizontal_until_corner = (original_col + 1..col_index)
        .map(|j| tiles[row_index][j])
        .all(|tile| tile.connects_horizontally());
    if !horizontal_until_corner {
        return false;
    }
    let bottom_left_is_corner = tiles[row_index][original_col].is_corner();
    if !bottom_left_is_corner {
        return false;
    }
    if !does_connect_from_bottom_left(tiles, row_index, original_corner) {
        return false;
    }
    true
}

fn does_connect_from_bottom_left(
    tiles: GridRef,
    row_index: usize,
    original_corner: Location,
) -> bool {
    let (original_row, col_index) = original_corner;
    let col_indices = original_row..row_index;
    // We assume we originally started from a corner just like we assume each
    // call to does_connect_from_bottom_left starts from a corner
    col_indices
        .map(|i| tiles[i][col_index])
        .all(|tile| tile.connects_vertically())
}

fn to_tiles(lines: &[&str]) -> Option<Grid> {
    lines
        .iter()
        .map(|line| line.chars().map(Tile::try_from_char).collect())
        .collect()
}

impl Tile {
    pub fn try_from_char(c: char) -> Option<Self> {
        Some(match c {
            '+' => Tile::Corner,
            '-' => Tile::Horizontal,
            '|' => Tile::Vertical,
            ' ' => Tile::Empty,
            _ => return None,
        })
    }

    pub fn is_corner(self) -> bool {
        match self {
            Tile::Corner => true,
            _ => false,
        }
    }

    pub fn connects_horizontally(self) -> bool {
        match self {
            Tile::Corner => true,
            Tile::Horizontal => true,
            _ => false,
        }
    }

    pub fn connects_vertically(self) -> bool {
        match self {
            Tile::Corner => true,
            Tile::Vertical => true,
            _ => false,
        }
    }
}

Community comments

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

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?