0% found this document useful (0 votes)
14 views

Problem Solving Assignment

Uploaded by

yash agrawal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Problem Solving Assignment

Uploaded by

yash agrawal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Question 1:

Solution:

We wish to build a mansion beside a long road. The far side of the road is filled with n
houses, each containing a given number of people. Our mansion is as long as w houses
combined. The goal is to position the mansion so that the number of people across from it is
maximized.

Input

The input is provided in a file named manin.txt:

• The first line contains two integers, n (the number of houses) and w (the width of the
mansion).
• The next n lines contain the number of people living in each house.

Output

The output is written to a file named manout.txt, which must contain a single integer
representing the largest possible number of people living across from the mansion.

Approach

To solve this problem, we use the sliding window technique, which allows us to find the
maximum sum of w consecutive elements in the array of people counts efficiently.

Steps

1. Read the input from manin.txt:


o Read the integers n and w from the first line.
o Read the number of people in each house from the subsequent n lines.
2. Calculate the maximum sum of people for a window of size w:
o Calculate the initial sum for the first w houses.
o Use the sliding window technique to update the sum by subtracting the first
element of the previous window and adding the next element.
o Track the maximum sum during the iteration.
3. Write the output to manout.txt:
o Write the maximum sum found to the output file.
Python Implementation

Explanation

• Initial Sum: Calculate the sum of the first w houses.


• Sliding Window: Slide the window one house at a time, updating the sum by
removing the first element of the previous window and adding the next element.
Update max_sum if the new sum is greater.

Complexity Analysis

• Time Complexity: O(n)O(n)O(n), as we traverse the array only once.


• Space Complexity: O(1)O(1)O(1), aside from storing the input.

Example

Input (manin.txt):

74

Output :

12
Conclusion

This approach efficiently finds the maximum number of people living across from a mansion
of width w by leveraging the sliding window technique, ensuring a linear runtime suitable for
large values of n up to 100,000.

Question 2:
We are tasked with organizing a dinner for an international conference. Multiple countries are
represented, each with a certain number of delegates, and there are several restaurants in the
area, each with a different number of available seats. The goal is to seat as many delegates as
possible while ensuring no two delegates from the same country are seated at the same
restaurant.

Input

The input is provided in a file named restin.txt:

• The first line contains an integer representing the number of countries.


• The second line contains the number of delegates from each country.
• The third line contains an integer representing the number of restaurants.
• The fourth line contains the number of seats available in each restaurant.

Output

The output should be written to a file named restout.txt, which must contain a single
integer representing the smallest number of delegates who cannot be seated.

Approach

To solve this problem, we need to:

1. Sort the delegates and restaurant capacities in descending order to maximize the
number of seated delegates.
2. Iteratively seat the delegates while ensuring no two delegates from the same country
sit in the same restaurant.

Steps

1. Read input from restin.txt:


o Read the number of countries and the number of delegates for each country.
o Read the number of restaurants and the number of seats in each restaurant.
2. Sort the data:
o Sort the number of delegates for each country in descending order.
o Sort the number of available seats for each restaurant in descending order.
3. Seat the delegates:
o Use a priority queue (or greedy approach) to seat delegates, ensuring that no
two delegates from the same country are seated at the same restaurant.
4. Calculate the number of unseated delegates:
o After attempting to seat all delegates, count how many delegates remain
unseated.
5. Write the output to restout.txt:
o Output the number of unseated delegates.
Python Implementation

Explanation

• Sorting: Sorting delegates and restaurant seats in descending order ensures that the
largest groups are seated in the restaurants with the most capacity.
• Seating Logic: A priority queue (max-heap) is used to seat delegates while ensuring
no two delegates from the same country sit together in one restaurant.
• Complexity:
o Time Complexity: O((C+R)log⁡(C+R))O((C + R) \log (C +
R))O((C+R)log(C+R)), where CCC is the number of countries and RRR is the
number of restaurants.
o Space Complexity: O(C+R)O(C + R)O(C+R), for storing the number of
delegates and seats.

Example

Input (restin.txt):

34333523
Output : 2

Conclusion

This approach efficiently arranges delegates to maximize seating while complying with the
rule that no two delegates from the same country are seated at the same restaurant. The
method is suitable for up to 5000 countries and restaurants.

Question : 3
You are navigating through a desert using a map represented as an (x, y) coordinate plane.
Starting at the origin (0, 0) and facing north, you follow a sequence of directional instructions
composed of:

• F: Move forward one kilometer in the current direction.


• L: Turn 90° to the left.
• R: Turn 90° to the right.

However, one R (right turn) is missing in the sequence. Given the coordinates of the
destination (an oasis), you must determine where to insert the missing R to correctly reach the
oasis.

Input and Output

Input:

• A sequence of directional instructions.


• The coordinates (x, y) of the oasis.

Output:

• The number of letters after which the missing R should be inserted.

Approach

To solve this problem, we simulate the movement described by the sequence of directions:

1. Start at the initial position (0, 0) facing north.


2. Execute the movement according to the sequence, keeping track of the current
position and direction.
3. Insert an R at different positions in the sequence, one at a time, and simulate the
movement to check if it results in reaching the oasis.
4. Output the position after which the missing R must be inserted to reach the
destination.

Directions and Movements

• Initial facing direction: North (0, 1).


• Turn left (L):
o North (0, 1) → West (-1, 0)
o West (-1, 0) → South (0, -1)
o South (0, -1) → East (1, 0)
o East (1, 0) → North (0, 1)
• Turn right (R):
o North (0, 1) → East (1, 0)
o East (1, 0) → South (0, -1)
o South (0, -1) → West (-1, 0)
o West (-1, 0) → North (0, 1)
Implementation Strategy

1. Simulate the Original Path:


o Traverse the given direction sequence, keeping track of the current position
and direction.
2. Try Inserting R:
o For each position in the sequence, insert an R and simulate the new path.
o Check if the new path reaches the given coordinates of the oasis.
3. Output the Result:
o Return the index after which the R should be inserted.

Python Implementation

Explanation

• The simulate_path function simulates the movement according to the direction


sequence.
• By iterating through the positions where R can be inserted, we check if adding R at
any point results in reaching the target coordinates.
• The solution stops when the correct position is found and outputs the index after
which R should be inserted.

Complexity Analysis

• Time Complexity: O(n2)O(n^2)O(n2), where nnn is the length of the original


direction sequence (due to simulating the path for each possible insertion).
• Space Complexity: O(1)O(1)O(1), aside from storing the input.

Example
Given:

• Directions: RFFLFLFFRFFL
• Oasis coordinates: (3, 3)

Output:

• Insert R after position X to reach the target coordinates.

Conclusion

This approach effectively determines the correct position to insert a missing R in the direction
sequence to reach the specified destination on a coordinate plane

Question 4:
We have a maze where a token, represented by 'X,' is positioned on a white square within a
grid of shaded (gray) and unshaded (white) squares. The token can move either horizontally
or vertically for any number of white squares but is restricted by shaded squares, as it cannot
pass over or stop on them.

The objective is to find the minimum number of moves needed to ensure the token can
reach any other white square.

Steps to Solve:

1. Understanding Movement Constraints:


o The token can move horizontally or vertically, stopping only on white squares.
o The token must avoid shaded squares during its movement.
2. Analyzing the Grid:
o We identify the starting position of the token ('X') and note the distribution of
white and shaded squares in each row and column.
o This helps us map out possible paths the token can take without crossing
shaded areas.
3. Possible Moves from Start Position:
o From the starting position, we examine the immediate options for movement:
▪ Right: The token can move right until it encounters a shaded square.
▪ Down: Similarly, it can move down until it reaches a shaded square.
o Since we are looking for the minimum moves, we focus on the shortest paths
to reach a position that enables further white square access.
4. Evaluating the Reachability of White Squares:
o Using Breadth-First Search (BFS) or a similar algorithm could help here as it
would allow us to explore all reachable white squares systematically, counting
moves until all are accessible.
o Based on the grid's layout, we determine how many moves are required to
cover all possible white squares.
5. Calculation and Result:
o After examining potential paths and counting minimum moves required to
reach each unvisited white square, the correct answer is identified.

Solution Outcome:

After going through possible paths and move calculations, the minimum number of moves
required for the token to be able to reach any white square is 10 moves.

Answer:

The correct answer is: (C) 10


Question 5:

We have a sequence of digits: 294563011. We are allowed to change or remove digits


according to two rules:

1. Rule (i): If three consecutive digits are palindromic (first digit = third digit), we can
remove these three digits.
2. Rule (ii): Any digit, except 9, can be increased by 1. This operation can help us form
palindromic triplets for removal according to Rule (i).

The goal is to determine the least number of times Rule (ii) must be applied to remove all
digits from the sequence.

Step-by-Step Solution

1. Identify Palindromic Triplets in the Sequence:


o Start with the sequence: 294563011
o Look for any consecutive triplets that are palindromic.
o There are no immediate palindromic triplets in this sequence, so we need to
use Rule (ii) to create them.
2. Applying Rule (ii) to Create Palindromic Triplets:
o We will increment some digits to form palindromic patterns that can then be
removed using Rule (i).
o Step-by-Step Transformation:
1. Change the '4' to '5' in 294563011, resulting in 295563011.
▪ This change creates the palindromic triplet 555 in the middle.
▪ Using Rule (i), remove 555 to get 2963011.
▪ Rule (ii) used once.
2. Change the '3' to '4' in 2963011, resulting in 2964011.
▪ This change creates the palindromic triplet 464.
▪ Using Rule (i), remove 464 to get 29011.
▪ Rule (ii) used twice.
3. Change the '2' to '3' in 29011, resulting in 39011.
▪ This change creates the palindromic triplet 909.
▪ Using Rule (i), remove 909 to get 11.
▪ Rule (ii) used three times.
4. The remaining sequence is '11', which is already a palindromic pair.
▪ Using Rule (i), remove 11 to get an empty sequence.
3. Conclusion:
o The minimum number of times Rule (ii) must be used is 3 to completely
remove all digits.

Answer:

The correct answer is: (C) 3

Question 6:

• We have five cities (P, Q, R, S, T) arranged along a circular highway.


• The table provides the shortest distances between each pair of cities.
• Since it’s a circular path, each pair of cities can be reached by traveling either
clockwise or counterclockwise around the lake, but the table only lists the shorter
distance.

Step-by-Step Solution

1. Examine Distances and Possible City Connections:


o Based on the shortest distances in the table, we can deduce which cities are
likely neighbors on the circular path:
▪ City P to City R: 2 km (suggesting they are adjacent).
▪ City P to City Q: 6 km.
▪ City P to City S: 3 km.
▪ City Q to City R: 4 km.
▪ City Q to City T: 2 km.
▪ City R to City S: 5 km.
▪ City S to City T: 1 km (suggesting they are adjacent).
2. Determine the Circular Sequence:
o Start by connecting cities with the shortest distances to determine a plausible
circular sequence:
▪ Since City S and City T are 1 km apart, they are likely neighbors in
the circle.
▪ City Q and City T are 2 km apart, suggesting City Q is next to City T.
▪ City P and City R are 2 km apart, suggesting City R is next to City P.
o By examining these connections, one possible sequence of cities around the
lake that follows a constant direction is:
▪ P→R→S→T→Q
3. Verify the Sequence with Given Options:
o Comparing this sequence with the provided answer choices, we find that the
sequence P, R, S, T, Q matches one of the options.

Conclusion

The correct answer is: (B) P, R, S, T, Q

Question 7:
The puzzle involves a game where two players eat squares from a block of chocolate in
alternate turns. To take a bite, a player must choose a square and eat every square above it
and/or to the right (including the chosen square). The goal is to eventually force the opponent
to eat a square that both players dislike (in this case, square 1).

Problem Breakdown

In the given 3×3 chocolate block scenario, the players take turns. The goal is to make
strategic moves to ensure the friend ends up eating square 1. You are provided five options to
start with:

• (A) Square 5
• (B) Square 6
• (C) Square 9
• (D) Square 10
• (E) Square 11

The task is to select the square that allows you to ultimately force the opponent to eat square
1.

Strategy Explanation

To solve this, let's analyze each option based on how it impacts the possible moves for both
players, focusing on the goal of forcing the friend to eat square 1.

1. Square 5:
If you choose square 5, all squares to the right of it (squares 6, 9, and 10) will be
consumed. This leaves squares 7, 8, and 11 for subsequent moves, which gives your
friend significant freedom in choosing subsequent moves. This option does not
guarantee you can force your friend to end up eating square 1.
2. Square 6:
Choosing square 6 means consuming square 6 and all squares above and to the right
of it (squares 9 and 10). Your friend is left with squares 5, 7, 8, and 11. This move
similarly leaves options open for your friend, making it challenging to force them to
eat square 1.
3. Square 9:
Selecting square 9 will eat up square 9 and squares to the right of it (including square
10). This leaves your friend with the possibility to choose among squares 5, 6, 7, and
8, which can still lead to different outcomes and does not guarantee forcing the friend
to eat square 1.
4. Square 10:
By choosing square 10, you consume square 10 and all the squares to its right (square
11). This move leaves the 2x2 grid comprising squares 5, 6, 7, and 8. Depending on
your friend's move, this configuration allows you to steer the game towards a win
since you can potentially guide their moves to end at square 1.
5. Square 11:
Choosing square 11 results in eating square 11 and squares to the right of it (none in
this case). This option leaves a larger portion of the grid for your friend to work with,
offering minimal control over the game's outcome.
Optimal Move

The correct choice is (D) Square 10. This move effectively reduces the chocolate block to a
manageable size, giving you control over your friend's subsequent moves and allowing you to
force your friend to eat square 1 eventually.

Conclusion

The optimal strategy to ensure that your friend ends up eating square 1 is to choose square
10. This move strategically reduces the available options and provides you with the ability to
control the game's progression.

Question 8:

A pizza delivery boy is tasked with delivering pizzas to 11 houses lined up in a row, one
pizza per house. He follows a series of instructions to navigate between the houses:

• "Go to Mel's house, then go F3, B1, F6, B3, F1, B5, F1, F5, F1, B3,"
o F denotes moving forward a specified number of houses.
o B denotes moving backward a specified number of houses.

One of these instructions has been written incorrectly. The task is to identify where the
mistake lies.

Analyzing the Instructions

1. Initial Position: The delivery starts at Mel's house (position 0).


2. Instruction Breakdown:
o F3: Move forward 3 houses → Current position = 3.
o B1: Move back 1 house → Current position = 2.
o F6: Move forward 6 houses → Current position = 8.
o B3: Move back 3 houses → Current position = 5.
o F1: Move forward 1 house → Current position = 6.
o B5: Move back 5 houses → Current position = 1.
o F1: Move forward 1 house → Current position = 2.
o F5: Move forward 5 houses → Current position = 7.
o F1: Move forward 1 house → Current position = 8.
o B3: Move back 3 houses → Current position = 5.

Checking for Errors

• The goal is to deliver pizzas to all 11 houses, but by following these instructions, we
can see that:
o The instructions cause repeated visits to certain positions (e.g., positions 5 and
8).
o Not all positions from 1 to 11 are visited.

Identifying the Mistake

• The issue appears to arise around the middle of the instructions, where movements
cause revisiting previously visited houses rather than covering new ones.
• Critical Instructions to Check:
o 5th and 6th instructions: The move sequence F1 (moving to position 6)
followed by B5 (moving back to position 1) seems suspect. This backward
move covers a large distance, and subsequent instructions do not adequately
cover all the houses.

Conclusion

The mistake is likely in (C) the 5th or 6th instruction. This part of the sequence creates an
inefficiency and leads to repeated house visits instead of ensuring a systematic coverage of all
11 houses.
Question 9:

The problem involves classifying spiders as boys or girls based on their sizes. The objective
is to find a threshold value xxx (an odd number) such that all spiders with sizes larger than
xxx are considered girls, and all spiders smaller than xxx are considered boys. The aim is to
minimize the total number of misclassified spiders (i.e., girl spiders below or equal to xxx
and boy spiders above xxx).

Analysis and Solutions

Scenario 1

• Sizes of boy spiders: 12, 12, 14, 18, 22, 24


• Sizes of girl spiders: 16, 20, 26, 28, 30, 30, 30, 32

To find the optimal value of xxx:

1. Possible values for xxx (odd numbers): 15, 17, 19, 21, 23, 25, 27, 29, 31
2. Evaluation:
o x=15x = 15x=15: Boy spiders misclassified = 0; Girl spiders misclassified = 1
(16). Total errors = 1.
o x=17x = 17x=17: Boy spiders misclassified = 1 (18); Girl spiders
misclassified = 1 (16). Total errors = 2.
o x=19x = 19x=19: Boy spiders misclassified = 2 (18, 22); Girl spiders
misclassified = 2 (16, 20). Total errors = 4.
o x=21x = 21x=21 and above: Misclassification count increases further.

Best choice: x=15x = 15x=15 with 1 misclassification.


Scenario 2

• Sizes of boy spiders: 14, 14, 14, 18, 18, 22, 26


• Sizes of girl spiders: 16, 20, 20, 24, 24, 28, 28

1. Possible values for xxx (odd numbers): 15, 17, 19, 21, 23, 25, 27
2. Evaluation:
o x=15x = 15x=15: Boy spiders misclassified = 0; Girl spiders misclassified = 1
(16). Total errors = 1.
o x=17x = 17x=17: Boy spiders misclassified = 1 (18); Girl spiders
misclassified = 1 (16). Total errors = 2.
o x=19x = 19x=19: Boy spiders misclassified = 2 (18, 22); Girl spiders
misclassified = 3 (16, 20, 20). Total errors = 5.

Best choice: x=15x = 15x=15 with 1 misclassification.

Scenario 3

• Sizes of boy spiders: 16, 18, 20, 22, 26, 28, 30, 32, 34, 40, 42
• Sizes of girl spiders: 24, 26, 30, 36, 38, 42, 44, 46, 48, 50

1. Possible values for xxx (odd numbers): 23, 25, 27, 29, 31, 33, 35, 37, 39, 41
2. Evaluation:
o x=23x = 23x=23: Boy spiders misclassified = 0; Girl spiders misclassified = 1
(24). Total errors = 1.
o x=25x = 25x=25: Boy spiders misclassified = 1 (26); Girl spiders
misclassified = 1 (24). Total errors = 2.
o x=27x = 27x=27: Boy spiders misclassified = 2 (26, 28); Girl spiders
misclassified = 2 (24, 26). Total errors = 4.

Best choice: x=23x = 23x=23 with 1 misclassification.

Conclusion

The optimal values for xxx for each scenario are:

1. Scenario 1: x=15x = 15x=15


2. Scenario 2: x=15x = 15x=15
3. Scenario 3: x=23x = 23x=23
Question 10:

1. Initial sequence: 2945630113

• Check for palindromic triples (Rule (i)):


o There is no group of three consecutive digits where the first and third are the
same in the initial sequence.

2. Applying Rule (ii) (incrementing a digit except for 9)

To form a palindromic triple:

• Consider changing 222 in the sequence to 333, making the sequence


394563011339456301133945630113.
• Now, we have 394394394 as a palindromic triple, which can be removed:
o New sequence: 563011356301135630113.

3. Continuing with the new sequence 563011356301135630113

• Check for palindromic triples:


o We have 313313313 as a palindromic triple, which can be removed:
▪ New sequence: 560560560.

4. Sequence 560560560

• Check for palindromic triples:


o There are no palindromic triples in this sequence.
• Consider incrementing 555 to 666, making the sequence 660660660.
o 660660660 can be removed using Rule (i).

Conclusion

• Number of times Rule (ii) was applied: 2 times (incrementing 222 to 333 and
incrementing 555 to 666).
Final Answer

(B) 2

You might also like