-
Notifications
You must be signed in to change notification settings - Fork 258
Vegetable Harvest
Raymond Chen edited this page Aug 1, 2024
·
6 revisions
TIP102 Unit 1 Session 1 Advanced (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 10 mins
- 🛠️ Topics: 2D Arrays, Matrix traversal
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
- The function
print_catchphrase()
should take a single parameter, character, and print the corresponding catchphrase based on the given character. If the character does not match any in the table, it should print a default message.
HAPPY CASE
Example 1:
Input:
[
['x', 'c', 'x'],
['x', 'x', 'x'],
['x', 'c', 'c'],
['c', 'c', 'c']
]
Output: 6
Explanation: vegetable_patch[0][1], vegetable_patch[2][1], vegetable_patch[2][2], vegetable_patch[3][0], vegetable_patch[3][1], and vegetable_patch[3][2] all have value 'c'
Example 2:
Input:
[
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x'],
['x', 'x', 'x']
]
Output: 0
Explanation: There are no 'c' in the vegetable patch.
EDGE CASE
If the matrix is empty, the function should return 0.
Example: []
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Define a function that uses conditionals to match the input character to a predefined set of catchphrases, printing the appropriate message.
1. Initialize a counter for carrots.
2. Iterate over each row in the matrix.
3. Iterate over each element in the row.
4. Check if the element is 'c'.
5. Increment the counter if the element is 'c'.
6. Return the counter
- Incorrectly formatting the strings (ensure they match exactly).
- Forgetting to handle characters not listed in the table.
Implement the code to solve the algorithm.
def harvest(vegetable_patch):
# Initialize the carrot counter
carrot_count = 0
# Get the number of rows (n) and columns (m)
n = len(vegetable_patch)
m = len(vegetable_patch[0])
# Traverse the 2D matrix
for i in range(n):
for j in range(m):
# Check if the current element is 'c'
if vegetable_patch[i][j] == 'c':
# Increment the carrot counter
carrot_count += 1
# Return the total number of carrots
return carrot_count