Avatar of emengd

emengd's solution

to Rectangles in the OCaml Track

Published at Feb 21 2019 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

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).

Getting Started

For installation and learning resources, refer to the exercism help page.

Installation

To work on the exercises, you will need Opam and Base. Consult opam website for instructions on how to install opam for your OS. Once opam is installed open a terminal window and run the following command to install base:

opam install base

To run the tests you will need OUnit. Install it using opam:

opam install ounit

Running Tests

A Makefile is provided with a default target to compile your solution and run the tests. At the command line, type:

make

Interactive Shell

utop is a command line program which allows you to run Ocaml code interactively. The easiest way to install it is via opam:

opam install utop

Consult utop for more detail.

Feedback, Issues, Pull Requests

The exercism/ocaml repository on GitHub is the home for all of the Ocaml exercises.

If you have feedback about an exercise, or want to help implementing a new one, head over there and create an issue. We'll do our best to help you!

Submitting Incomplete Solutions

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

test.ml

open OUnit2
open Rectangles

let ae exp got _test_ctxt = assert_equal exp got ~printer:string_of_int

let tests = [
   "no rows" >::
      ae 0 (count_rectangles [||]);
   "no columns" >::
      ae 0 (count_rectangles [|""|]);
   "no rectangles" >::
      ae 0 (count_rectangles [|" "|]);
   "one rectangle" >::
      ae 1 (count_rectangles [|"+-+"; 
                               "| |"; 
                               "+-+"|]);
   "two rectangles without shared parts" >::
      ae 2 (count_rectangles [|"  +-+"; 
                               "  | |"; 
                               "+-+-+"; 
                               "| |  "; 
                               "+-+  "|]);
   "five rectangles with shared parts" >::
      ae 5 (count_rectangles [|"  +-+"; 
                               "  | |"; 
                               "+-+-+"; 
                               "| | |"; 
                               "+-+-+"|]);
   "rectangle of height 1 is counted" >::
      ae 1 (count_rectangles [|"+--+"; 
                               "+--+"|]);
   "rectangle of width 1 is counted" >::
      ae 1 (count_rectangles [|"++"; 
                               "||"; 
                               "++"|]);
   "1x1 square is counted" >::
      ae 1 (count_rectangles [|"++";
                               "++"|]);
   "only complete rectangles are counted" >::
      ae 1 (count_rectangles [|"  +-+"; 
                               "    |"; 
                               "+-+-+"; 
                               "| | -"; 
                               "+-+-+"|]);
   "rectangles can be of different sizes" >::
      ae 3 (count_rectangles [|"+------+----+"; 
                               "|      |    |"; 
                               "+---+--+    |"; 
                               "|   |       |"; 
                               "+---+-------+"|]);
   "corner is required for a rectangle to be complete" >::
      ae 2 (count_rectangles [|"+------+----+"; 
                               "|      |    |"; 
                               "+------+    |"; 
                               "|   |       |"; 
                               "+---+-------+"|]);
   "large input with many rectangles" >::
      ae 60 (count_rectangles [|"+---+--+----+"; 
                                "|   +--+----+"; 
                                "+---+--+    |"; 
                                "|   +--+----+"; 
                                "+---+--+--+-+"; 
                                "+---+--+--+-+"; 
                                "+------+  | |"; 
                                "          +-+"|]);
]

let () =
  run_test_tt_main ("rectangles tests" >::: tests)
open Base

let count_duplicates l1 l2 =
  let rec loop n l1 l2 =
    match l1, l2 with
    | [], _ | _, [] -> n
    | x :: xs, y :: ys ->
      if x < y then
        loop n l1 ys
      else if x = y then
        loop (n +  1) xs ys
      else
        loop n xs l2
  in
  loop 0 l1 l2

let merge l1 l2 =
  let rec loop l l1 l2 =
    match l1, l2 with
    | [], l0 | l0, [] ->
      List.rev_append l0 l
    | x :: xs, y :: ys ->
      if x < y then
        loop (y :: l) l1 ys
      else if x = y then (* shouldn't occur *)
        loop (x :: l) xs ys
      else
        loop (x :: l) xs l2
  in
  List.rev (loop [] l1 l2)

let count_rectangles lines =
  let h = Array.length lines in
  if h = 0 then
    0
  else
    let w = String.length lines.(0) in
    if w = 0 then
      0
    else
      let column_memo_1 = Array.create ~len:w [] in
      let column_memo_2 = Array.create ~len:w [] in
      let rec loop i j id total line_memo_1 line_memo_2 =
        if j >= w then
          loop (i + 1) 0 id total [] []
        else if i >= h then
          total
        else
          match lines.(i).[j] with
          | ' ' -> begin
              column_memo_1.(j) <- [];
              column_memo_2.(j) <- [];
              loop i (j + 1) id total [] []
            end
          | '|' ->
            loop i (j + 1) id total [] []
          | '-' -> begin
              column_memo_1.(j) <- [];
              column_memo_2.(j) <- [];
              loop i (j + 1) id total line_memo_1 line_memo_2
            end
          | '+' -> begin
              let n = count_duplicates column_memo_2.(j) line_memo_2 in
              let new_line_memo_2 = merge line_memo_2 column_memo_1.(j) in
              column_memo_1.(j) <- id :: column_memo_1.(j);
              column_memo_2.(j) <- merge column_memo_2.(j) line_memo_1;
              loop i (j + 1) (id + 1) (total + n) (id :: line_memo_1) new_line_memo_2
            end
          | _ ->
            raise (Invalid_argument "invalid input")
      in
      loop 0 0 0 0 [] []

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?