Ludium
Sign In
Introduction to Computational Thinking and Data Science
Optimization
01Optimization Models and the Knapsack Problem02Brute-Force Knapsack and the Exponential Power Set03Greedy Algorithms: One Function, Any Definition of Best04Lambda Keys and Why Greedy Can Miss the OptimumProblem setMIT problem set
01The Knapsack Search Tree: Every Combination, 2ⁿ Nodes02Recursive maxVal: An Exhaustive Search That Beats Greedy03Memoization: Turning Slow Fibonacci into fastFib04Overlapping Subproblems and the Memoized KnapsackProblem setMIT problem set
Graph Models
01Graphs as Models: Nodes, Edges and Euler's Seven Bridges02Coding a Graph in Python: Node, Edge, Digraph and Graph03Depth-First Search for the Shortest Path in a Graph04Breadth-First Search: A Queue of Paths, Fewest Hops FirstProblem setMIT problem set
Stochastic Thinking
01Predictive Nondeterminism and the Stochastic Die Roll02Probability as Counting, and When Multiplying Fails03Simulating Rare Events: Random Seeds and Many Trials04The Birthday Problem: Formula Versus SimulationProblem setMIT problem set

Coding challenges on stochastic thinking — MIT problem set

Problem 1Predictive Nondeterminism and the Stochastic Die Roll

Robot Simulation: The RectangularRoom Class

MIT 6.0002 Introduction to Computational Thinking and Data Science, Fall 2016 · Problem set 3, Problem 1: Implementing the RectangularRoom and Robot classes — RectangularRoom · Prof. Eric Grimson, Prof. John Guttag and Dr. Ana Bell · CC BY-NC-SA 4.0 · MIT publishes no solution for this set; the worked solution is ours

Complete the abstract class RectangularRoom, which represents the space to be cleaned and keeps track of which tiles have been cleaned. You write __init__, clean_tile_at_position, is_tile_cleaned, get_num_cleaned_tiles, is_position_in_room and get_dirt_amount; the class Position is given.

This problem set simulates Roomba-like robots cleaning the floor of a room. A room is a rectangle divided into square tiles. At the start of the simulation, each tile is covered in some amount of dirt, which is the same across tiles.

  • Representation. You will need to keep track of which parts of the floor have been cleaned by the robot(s). When a robot's location is anywhere inside a particular tile, we will consider the dirt on that entire tile to be reduced by some amount determined by the robot. We consider the tile to be "clean" when the amount of dirt on the tile is 0. We will refer to the tiles using ordered pairs of integers: (0, 0), (0, 1), …, (0, h-1), (1, 0), (1, 1), …, (w-1, h-1). Tiles can never have a negative amount of dirt.
  • Starting conditions. Initially, the entire floor is uniformly dirty. Each tile should start with an integer amount of dirt, specified by dirt_amount.
  • A Position represents a location in x- and y-coordinates, floats satisfying 0 ≤ x < w and 0 ≤ y < h, measured from the lower left corner of the room, (0.0, 0.0). Note that room tiles are ordered pairs of integers but a Position is specified as floats — be careful converting between the two.

An abstract class will never be instantiated in the simulation; it is a template for its subclasses (EmptyRoom and FurnishedRoom, the next challenges). The methods whose comment says "do not change" — get_num_tiles, is_position_valid and get_random_position — stay unimplemented here and must keep raising NotImplementedError. Store the room's dimensions as self.width and self.height: the given FurnishedRoom code reads them.

room = RectangularRoom(3, 4, 2)
print(room.get_dirt_amount(1, 2))  # 2
room.clean_tile_at_position(Position(1.5, 2.5), 1)
print(room.get_dirt_amount(1, 2))  # 1
print(room.is_tile_cleaned(1, 2))  # False
room.clean_tile_at_position(Position(1.9, 2.1), 5)
print(room.get_dirt_amount(1, 2))  # 0
print(room.get_num_cleaned_tiles())  # 1
print(room.is_position_in_room(Position(3.0, 1.0)))  # False

Adapted for the browser: MIT's tester cleans each tile at a random point inside it; the tests here use fixed points inside each tile, and the room's dimensions are named width and height because the given furniture code relies on them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import math
import random

# --- given: class Position from ps3.py (do not edit) ---
class Position(object):
    """
    A Position represents a location in a two-dimensional room, where
    coordinates are given by floats (x, y).
    """
    def __init__(self, x, y):
        """
        Initializes a position with coordinates (x, y).
        """
        self.x = x
        self.y = y

    def get_x(self):
        return self.x

    def get_y(self):
        return self.y

    def get_new_position(self, angle, speed):
        """
        Computes and returns the new Position after a single clock-tick has
        passed, with this object as the current position, and with the
        specified angle and speed.

        Does NOT test whether the returned position fits inside the room.

        angle: float representing angle in degrees, 0 <= angle < 360
        speed: positive float representing speed

        Returns: a Position object representing the new position.
        """
        old_x, old_y = self.get_x(), self.get_y()

        # Compute the change in position
        delta_y = speed * math.cos(math.radians(angle))
        delta_x = speed * math.sin(math.radians(angle))

        # Add that to the existing position
        new_x = old_x + delta_x
        new_y = old_y + delta_y

        return Position(new_x, new_y)

    def __str__(self):
        return "Position: " + str(math.floor(self.x)) + ", " + str(math.floor(self.y))


# === Problem 1
class RectangularRoom(object):
    """
    A RectangularRoom represents a rectangular region containing clean or dirty
    tiles.

    A room has a width and a height and contains (width * height) tiles. Each tile
    has some fixed amount of dirt. The tile is considered clean only when the amount
    of dirt on this tile is 0.
    """
    def __init__(self, width, height, dirt_amount):
        """
        Initializes a rectangular room with the specified width, height, and
        dirt_amount on each tile.

        width: an integer > 0
        height: an integer > 0
        dirt_amount: an integer >= 0
        """
        pass

    def clean_tile_at_position(self, pos, capacity):
        """
        Mark the tile under the position pos as cleaned by capacity amount of dirt.

        Assumes that pos represents a valid position inside this room.

        pos: a Position object
        capacity: the amount of dirt to be cleaned in a single time-step
                  can be negative which would mean adding dirt to the tile

        Note: The amount of dirt on each tile should be NON-NEGATIVE.
              If the capacity exceeds the amount of dirt on the tile, mark it as 0.
        """
        pass

    def is_tile_cleaned(self, m, n):
        """
        Return True if the tile (m, n) has been cleaned.

        Assumes that (m, n) represents a valid tile inside the room.

        m: an integer
        n: an integer

        Returns: True if the tile (m, n) is cleaned, False otherwise

        Note: The tile is considered clean only when the amount of dirt on this
              tile is 0.
        """
        pass

    def get_num_cleaned_tiles(self):
        """
        Returns: an integer; the total number of clean tiles in the room
        """
        pass

    def is_position_in_room(self, pos):
        """
        Determines if pos is inside the room.

        pos: a Position object.
        Returns: True if pos is in the room, False otherwise.
        """
        pass

    def get_dirt_amount(self, m, n):
        """
        Return the amount of dirt on the tile (m, n)

        Assumes that (m, n) represents a valid tile inside the room.

        m: an integer
        n: an integer

        Returns: an integer
        """
        pass

    def get_num_tiles(self):
        """
        Returns: an integer; the total number of tiles in the room
        """
        # do not change -- implement in subclasses.
        raise NotImplementedError

    def is_position_valid(self, pos):
        """
        pos: a Position object.

        returns: True if pos is in the room and (in the case of FurnishedRoom)
                 if position is unfurnished, False otherwise.
        """
        # do not change -- implement in subclasses
        raise NotImplementedError

    def get_random_position(self):
        """
        Returns: a Position object; a random position inside the room
        """
        # do not change -- implement in subclasses
        raise NotImplementedError

Scratchpad— run any Python to test ideas
1
2
3
4
5
# Scratchpad — run any Python here to test ideas.
# Anything you write below stays separate from the problem's tests.

print("hello, world")

Python runtime ready in a moment
Python runtime ready in a moment
Visible tests · 3Examples — click to expand
?
a new room has dirt_amount on every tile
?
cleaning by the full amount makes every tile clean
?
get_num_cleaned_tiles counts tiles cleaned one at a time
Hidden tests · 7Bodies hidden — pass/fail only
?
Hidden test 1
?
Hidden test 2
?
Hidden test 3
?
Hidden test 4
?
Hidden test 5
?
Hidden test 6
?
Hidden test 7