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

Problem Solving Tech

Uploaded by

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

Problem Solving Tech

Uploaded by

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

UNIT -1

What is program?
A program is a set of instructions that tell a computer what to do. It's like a
recipe for baking a cake: it tells you the ingredients you need and the steps to
follow to make the cake. Similarly, a computer program tells the computer what
tasks to perform, like opening a file, doing calculations, or displaying a message
on the screen.
Define algorithm?
An algorithm is a set of step-by-step instructions designed to solve a specific
problem or perform a specific task. It's like a recipe that outlines the exact steps
to follow to achieve a desired outcome. Algorithms are used in computer
science and programming to help computers solve problems efficiently and
effectively.
what is array?
An array is a data structure that stores a collection of elements, typically of the
same type, in a contiguous block of memory. Each element in the array is
accessed by its index, which is an integer value indicating its position in the
array.

What is the requirement solving problem by computer?


Clearly Defined Problem: Understand the problem you want to solve and define
it clearly. Break down the problem into smaller, manageable parts if needed.

Algorithm: Develop an algorithm to solve the problem. This algorithm should


outline the steps necessary to achieve the desired outcome.

Programming Language: Choose a programming language that is suitable for


the problem you are trying to solve. Different languages have different strengths
and weaknesses.

Development Environment: Set up a development environment with the


necessary tools and resources to write, test, and debug your code.
Input Data: Identify the input data required by your program to solve the
problem. This could be user input, data from files, or data from other sources.

Output Requirements: Determine what output your program should produce


once it has solved the problem. This could be displaying information to the user,
saving data to a file, or performing some other action.

Testing and Debugging: Test your program thoroughly to ensure it works as


expected. Debug any errors or issues that arise during testing.

Optimization: If necessary, optimize your program to improve its efficiency or


performance.

Documentation: Document your code to make it easier for others (or yourself in
the future) to understand and maintain.

Deployment: Once your program is working correctly, deploy it to the intended


environment where it will be used to solve the problem.
Discuss some of the problem-solving aspects?
1. Identifying the Problem: Clearly understanding the problem is the first
step. This involves defining the problem, understanding its context, and
identifying any constraints or limitations.
2. Analysing the Problem: Once the problem is identified, it's important to
analyse it thoroughly. This may involve breaking down the problem into
smaller, more manageable parts, and identifying the underlying causes.
3. Generating Solutions: After analysing the problem, brainstorming
potential solutions is crucial. This step involves thinking creatively and
considering all possible options.
4. Evaluating Solutions: Once a list of potential solutions is generated,
each solution should be evaluated based on criteria such as feasibility,
effectiveness, and cost. This helps in selecting the best solution.
5. Implementing the Solution: After selecting the best solution, it needs to
be implemented. This may involve creating a plan, allocating resources,
and taking action.
6. Monitoring and Evaluating: After implementing the solution, it's
important to monitor its effectiveness. This involves evaluating the results
and making any necessary adjustments.
7. Iterating: Problem-solving is often an iterative process. If the solution
does not fully solve the problem, it may be necessary to go back to earlier
steps and try a different approach.
8. Learning from the Process: Finally, it's important to reflect on the
problem-solving process and learn from it. This helps in improving
problem-solving skills for future challenges.
Write a short note on working backwards from the solution?
Working backwards from the solution is a problem-solving technique where
you start with the desired outcome and then work your way back to the initial
problem. This approach is particularly useful when the final goal is clear, but
the steps to achieve it are not immediately obvious.

Here's how it typically works:

1. Define the Goal: Begin by clearly defining the end goal or solution you
want to achieve. This could be a specific outcome, result, or state.
2. Identify the Final Step: Once you have a clear goal, identify the last step
or action that needs to be taken to achieve that goal. This step should
directly lead to the desired outcome.
3. Work Backwards: From the final step, identify the previous step that
would lead to the final step. Continue this process, working backwards
step by step, until you reach the starting point or initial problem.
4. Verify Steps: As you work backwards, ensure that each step logically
leads to the next and ultimately to the desired outcome. If a step does not
seem to connect, reassess and adjust as needed.
5. Implement the Plan: Once you have identified the steps working
backwards from the solution, you can create an action plan to implement
them in the correct sequence.
What are the problem-solving strategies?
Problem-solving strategies are approaches or methods used to find solutions to
problems. They help individuals or teams navigate through challenges and come
up with effective solutions. Some common problem-solving strategies include:

1. Trial and Error: This strategy involves trying different solutions until
the problem is solved. While simple, it can be time-consuming and may
not always be practical for complex problems.
2. Algorithmic Thinking: This strategy involves following a step-by-step
procedure or algorithm to solve a problem. Algorithms are particularly
useful for problems that can be broken down into smaller, more
manageable steps.
3. Heuristic Methods: Heuristics are rules of thumb or general strategies
that may not guarantee a solution but can help narrow down the search
space. Examples include working backwards from the solution or using
analogies from similar problems.
4. Divide and Conquer: This strategy involves breaking a problem down
into smaller, more manageable parts, solving each part independently,
and then combining the solutions to solve the overall problem.
5. Root Cause Analysis: This strategy involves identifying the underlying
cause of a problem rather than just addressing its symptoms. By
addressing the root cause, you can prevent the problem from recurring.
6. Decision Making: Problem-solving often involves making decisions.
Decision-making strategies such as weighing pros and cons, using
decision trees, or conducting cost-benefit analyses can help in choosing
the best course of action.
7. Creativity Techniques: Sometimes, thinking outside the box is
necessary to find innovative solutions. Creativity techniques such as
brainstorming, mind mapping, or lateral thinking can help generate new
ideas.
8. Collaboration: Problem-solving is often more effective when done
collaboratively. Working with others can provide different perspectives
and expertise that can lead to better solutions.

What is mean by top-down design?


Top-down design, also known as top-down programming or stepwise
refinement, is a problem-solving and design approach in software development.
It involves breaking down a system into smaller, more manageable modules or
functions, starting from the top-level module and gradually refining the details.

In top-down design, you begin by identifying the main function or goal of the
system. Then, you break down this main function into smaller sub-functions or
modules. Each sub-function is further broken down into smaller sub-functions,
and so on, until you reach a level where the functions are simple enough to be
easily implemented.

The key steps in top-down design are as follows:

1. Identify the Main Function: Define the overall purpose or goal of the
system.
2. Break Down the Main Function: Divide the main function into smaller,
more manageable sub-functions or modules.
3. Repeat the Process: For each sub-function, repeat the process of
breaking it down into smaller sub-functions until you reach a level where
the functions are simple enough to be implemented.
4. Implement the Functions: Implement each function, starting from the
lowest-level functions and working your way up to the top-level function.
5. Test and Debug: Test each function individually to ensure that it works
correctly, and then test the system as a whole to ensure that all functions
work together as expected.

Top-down design helps in managing complexity by breaking down a problem


into smaller, more manageable parts. It also allows for easier collaboration
among team members, as different team members can work on different parts of
the system independently.

Define implementation of algorithm.


Implementation of an algorithm refers to the process of translating a theoretical
algorithm into a concrete, executable form that can be run on a computer. It
involves writing code in a specific programming language that follows the steps
outlined in the algorithm to solve a particular problem.

The implementation of an algorithm typically involves the following steps:

1. Selecting a Programming Language: Choose a programming language


that is suitable for the problem at hand and that you are comfortable with.
2. Translating the Algorithm: Write code that translates the steps of the
algorithm into a sequence of instructions that can be executed by a
computer. This involves using the syntax and features of the chosen
programming language.
3. Testing and Debugging: Test the implementation of the algorithm using
different inputs to ensure that it produces the correct outputs. Debug any
errors or issues that arise during testing.
4. Optimization: Depending on the complexity of the algorithm and the
requirements of the problem, you may need to optimize the
implementation to improve its efficiency or reduce its resource usage.
5. Documentation: Document the implementation of the algorithm,
including explanations of the code and any assumptions or constraints
that apply.
6. Integration: If the algorithm is part of a larger system, integrate the
implementation into the overall system architecture.

The implementation of an algorithm is a crucial step in the development of


software and is key to solving real-world problems efficiently and effectively.
UNIT-2
Exchanging the values of two variables?
Exchanging the values of two variables temporarily in Python involves using a
temporary variable to hold one of the values while swapping the values between
the two variables. Here's a step-by-step explanation followed by Python code:

1. Initialize Variables: Start by initializing two variables, a and b, with the


values you want to swap.
2. Create a Temporary Variable: Create a third variable, temp, to
temporarily hold one of the values.
3. Swap Values: Assign the value of a to temp, then assign the value of b
to a, and finally assign the value of temp to b. This effectively swaps the
values of a and b.
4. Print the Result: Print the values of a and b to verify that the swap was
successful.
# Step 1: Initialize variables
a=5
b = 10

# Step 2: Create a temporary variable


temp = None

# Step 3: Swap values


temp = a
a=b
b = temp

# Step 4: Print the result


print("After swapping:")
print("a =", a)
print("b =", b)
counting summation of a set of number
Counting the summation of a set of numbers involves adding up all the numbers
in the set to find their total sum. Here's a step-by-step explanation of how this
can be done without using Python:

1. Understand the Set of Numbers: Start by understanding the set of


numbers you want to find the sum of. Let's say you have a set of
numbers: {2, 4, 6, 8, 10}.
2. Initialize a Variable: Initialize a variable, let's call it sum, to 0. This
variable will be used to keep track of the running sum.
3. Loop Through the Numbers: Iterate through each number in the set.
For each number, add it to the sum variable.
4. Calculate the Sum: After looping through all the numbers, the value of
the sum variable will be the total sum of the set of numbers.
5. Print the Result: Print the value of the sum variable to display the total
sum of the set of numbers.

Using the example set {2, 4, 6, 8, 10}, the steps would look like this:

1. Initialize sum to 0: sum = 0.


2. Start the loop:
• For the first number (2), add it to sum: sum = sum + 2.
• For the second number (4), add it to sum: sum = sum + 4.
• Continue this process for each number in the set.
3. After the loop, sum will contain the total sum of the set: sum = 2 + 4 + 6
+ 8 + 10 = 30.
4. Print the result: The sum of the set {2, 4, 6, 8, 10} is 30.

This process can be applied to any set of numbers to find their total sum.

Factorial computation
Calculating the factorial of a number involves multiplying the number by all
the positive integers less than it. For example, the factorial of 5 (written as 5!) is
5 x 4 x 3 x 2 x 1 = 120. Here's a step-by-step explanation of how to compute the
factorial of a number in Python:

1. Input a Number: Start by inputting the number for which you want to
calculate the factorial. Let's say you want to calculate the factorial of 5.
2. Initialize a Variable: Initialize a variable, let's call it factorial, to 1. This
variable will be used to store the running product.
3. Loop Through Numbers: Create a loop that iterates from 1 to the input
number (inclusive). For each iteration, multiply the factorial variable by
the current number in the loop.
4. Calculate the Factorial: After the loop completes, the factorial variable
will contain the factorial of the input number.
5. Print the Result: Print the value of the factorial variable to display the
factorial of the input number.
# Step 1: Input a number
number = 5

# Step 2: Initialize a variable


factorial = 1

# Step 3: Loop through numbers


for i in range(1, number + 1):
factorial *= i

# Step 4: Calculate the factorial


# After the loop, factorial = 1 * 2 * 3 * 4 * 5 = 120

# Step 5: Print the result


print(f"The factorial of {number} is: {factorial}")

Fibonacci series generation


he Fibonacci series is a sequence of numbers where each number is the sum of
the two preceding ones, usually starting with 0 and 1. So, the Fibonacci series
looks like this: 0, 1, 1, 2, 3, 5, 8, 13, ...

Here's a step-by-step explanation of how to generate the Fibonacci series in


Python:
1. Input the Number of Terms: Start by inputting the number of terms you
want in the Fibonacci series. Let's say you want to generate the series
with 10 terms.
2. Initialize Variables: Initialize three variables: a and b to 0 and 1 (the
first two numbers in the series), and count to 0 (to keep track of the
number of terms generated).
3. Generate the Series: Use a while loop to generate the series. Inside the
loop, calculate the next term (next_term) by adding a and b, then update
a to b and b to next_term. Increment count by 1 in each iteration.
4. Print the Series: Print each term as it is generated.
# Step 1: Input the number of terms
num_terms = 10

# Step 2: Initialize variables


a, b = 0, 1
count = 0

# Step 3: Generate the series


while count < num_terms:
print(a, end=" ")
next_term = a + b
a=b
b = next_term
count += 1

# Output will be: 0 1 1 2 3 5 8 13 21 34

Reversing the digit of an integer.


Reversing the digits of an integer involves rearranging the digits of the number
in the opposite order. For example, if the input is 123, the output should be 321.
Here's a step-by-step explanation of how to reverse the digits of an integer:
1. Input the Integer: Start by inputting the integer you want to reverse.
Let's say the input is 123.
2. Initialize Variables: Initialize a variable reversed_num to 0. This
variable will store the reversed number.
3. Extract Digits: Use a loop to extract each digit from the input number.
You can do this by using the modulo operator (%) to extract the last digit
and integer division (//) to remove the last digit from the number.
4. Reverse the Digits: Multiply the reversed_num variable by 10 and add
the extracted digit to it. This will shift the existing digits of
reversed_num to the left and add the extracted digit at the rightmost
position.
5. Repeat Until All Digits Are Processed: Continue the loop until all digits
of the input number are processed.
6. Print the Reversed Number: Print the value of the reversed_num
variable, which will be the reversed integer.
Using the example input 123, the pseudo-code would reverse the digits as
follows:
Iteration 1:
num = 123, digit = 3, reversed_num = 0 * 10 + 3 = 3

Iteration 2:
num = 12, digit = 2, reversed_num = 3 * 10 + 2 = 32

Iteration 3:
num = 1, digit = 1, reversed_num = 32 * 10 + 1 = 321

Output: 321
Base conversion.
Base conversion involves converting a number from one base to another. The
base of a number system determines the number of digits used to represent
numbers and the value of each digit based on its position. For example, the
decimal (base-10) number system uses digits 0-9, while the binary (base-2)
number system uses digits 0 and 1.

Here's a step-by-step explanation of how to convert a number from one base to


another, using pseudo-code:
1. Input the Number and Bases: Start by inputting the number you want to
convert (num), the base of the input number (from_base), and the base
to which you want to convert the number (to_base).
2. Convert the Number to Base-10 (Decimal): If from_base is not 10
(decimal), convert num to decimal. Iterate over the digits of num from
right to left (least significant digit to most significant digit). For each digit
at position i, multiply it by from_base^i and add the result to a running
sum (decimal_num).
3. Convert the Decimal Number to the Target Base: If to_base is not 10
(decimal), convert decimal_num to the target base. Initialize an empty
list (result_digits) to store the digits of the result. While decimal_num is
greater than 0, divide decimal_num by to_base and append the
remainder to result_digits. Finally, reverse result_digits to get the digits
in the correct order.
4. Output the Result: Convert the list of digits in result_digits to a string
and return the result.
Input: num (integer), from_base (integer), to_base (integer)

// Step 1: Convert the number to decimal if the input base is not 10


Set decimal_num to 0
Set i to 0
Repeat while num is greater than 0:
Set digit to num % 10
Set decimal_num to decimal_num + digit * (from_base raised to the power of
i)
Divide num by 10, discarding any remainder
Increment i by 1

// Step 2: Convert the decimal number to the target base


Create an empty list called result_digits
Repeat while decimal_num is greater than 0:
Set remainder to decimal_num % to_base
Append remainder to result_digits
Divide decimal_num by to_base, discarding any remainder

Reverse the order of elements in result_digits

// Step 3: Output the result


Set result to an empty string
For each digit in result_digits, from left to right:
Convert digit to a string and append it to result

Output: result

Unit -3
Finding the square root of number
Finding the square root of a number involves finding a value that, when
multiplied by itself, gives the original number. For example, the square root of
25 is 5 because 5 * 5 = 25. Here's a step-by-step explanation of how to find the
square root of a number using the Babylonian method, also known as the
Heron's method:

1. Input the Number: Start by inputting the number for which you want to
find the square root. Let's say the number is 25.
2. Initialize Variables: Initialize two variables, guess and prev_guess, to
any value. These variables will be used to approximate the square root.
3. Iterative Calculation: Use the following iterative formula to
approximate the square root:
guess = (guess + number / guess) / 2
1. Repeat this calculation until the difference between guess and
prev_guess is within a desired tolerance level, or until a maximum
number of iterations is reached.
2. Print the Result: Print the value of guess, which will be an
approximation of the square root of the input number.

Here's the pseudo-code implementing these steps:

Input: number (integer)


tolerance = 0.00001
max_iterations = 100
guess = number / 2
prev_guess = 0

while abs(guess - prev_guess) > tolerance and max_iterations > 0:


prev_guess = guess
guess = (guess + number / guess) / 2
max_iterations = max_iterations - 1

Output: guess
Using the example input 25, the pseudo-code would find the square root as
follows:
Iteration 1:
prev_guess = 0
guess = (0 + 25 / 0) / 2 = 12.5

Iteration 2:
prev_guess = 12.5
guess = (12.5 + 25 / 12.5) / 2 = 7.25

Iteration 3:
prev_guess = 7.25
guess = (7.25 + 25 / 7.25) / 2 = 5.349

Iteration 4:
prev_guess = 5.349
guess = (5.349 + 25 / 5.349) / 2 = 5.015
Iteration 5:
prev_guess = 5.015
guess = (5.015 + 25 / 5.015) / 2 = 5.000023

Output: 5.000023 (approximation of square root of 25)


The smallest division of the integer.

he smallest division of an integer refers to the smallest unit or factor by which


the integer can be divided without leaving a remainder. For example, the
smallest division of 12 is 1, because 12 can be divided by 1 without leaving a
remainder. Here's a step-by-step explanation of how to find the smallest division
of an integer:

1. Input the Integer: Start by inputting the integer for which you want to
find the smallest division. Let's say the integer is 12.
2. Initialize Variables: Initialize a variable divisor to 1. This variable will
be used to find the smallest division.
3. Check Division: Use a loop to iterate through all numbers from 1 to the
input integer. For each number, check if the input integer is divisible by
that number without leaving a remainder.
4. Update Smallest Division: If the input integer is divisible by the current
number (i), update the value of divisor to i.
5. Print the Result: Print the value of divisor, which will be the smallest
division of the input integer.

Here's the pseudo-code implementing these steps:

Input: number (integer)


divisor = 1

for i from 1 to number:


if number % i == 0:
divisor = i
break
Output: divisor

Greatest common divisor of two integer


The greatest common divisor (GCD) of two integers is the largest positive
integer that divides both numbers without leaving a remainder. For example, the
GCD of 12 and 18 is 6, because 6 is the largest number that divides both 12 and
18 evenly. Here's a step-by-step explanation of how to find the GCD of two
integers using the Euclidean algorithm:

1. Input the Integers: Start by inputting the two integers for which you
want to find the GCD. Let's say the integers are 12 and 18.
2. Initialize Variables: Initialize two variables, a and b, to the two input
integers.
3. Calculate Remainder: Use the Euclidean algorithm to repeatedly
calculate the remainder of a divided by b until the remainder is 0. This is
done by repeatedly setting a to b and b to the remainder of a divided by
b.
4. GCD is the Last Non-Zero Remainder: The GCD of the two input
integers is the last non-zero remainder calculated in the Euclidean
algorithm.
5. Print the Result: Print the value of b, which is the GCD of the two input
integers.
Here's the pseudo-code implementing these steps:
Input: a (integer), b (integer)
Set temp to 0

while b is not 0:
Set temp to b
Set b to a mod b
Set a to temp

Output: a (GCD of the two input integers)


Using the example input 12 and 18, the pseudo-code would find the GCD as
follows:
Iteration 1:
a = 12, b = 18, temp = 0
b = 12 % 18 = 12, a = 18

Iteration 2:
a = 18, b = 12, temp = 12
b = 18 % 12 = 6, a = 12

Iteration 3:
a = 12, b = 6, temp = 6
b = 12 % 6 = 0, a = 6

Output: 6 (GCD of 12 and 18)


Generating prime number
Generating prime numbers involves finding numbers that are only divisible by 1
and themselves. Here's a step-by-step explanation of how to generate prime
numbers:

1. Input the Range: Start by inputting the range of numbers within which
you want to find prime numbers. Let's say you want to find prime
numbers up to 50.
2. Initialize Variables: Initialize a list (primes) to store the prime numbers
found. Also, initialize a variable (is_prime) to True.
3. Iterate Through the Range: For each number num in the range from 2
to the maximum number in the range:
a. Set is_prime to True.
b. For each number i in the range from 2 to the square root of num
(rounded up to the nearest integer), check if num is divisible by i. If it is,
set is_prime to False and break out of the loop.
c. If is_prime is still True after checking all possible divisors, add num
to the primes list.
4. Print the Result: Print the list of prime numbers (primes) found within
the specified range.

Here's the pseudo-code implementing these steps:

Input: max_num (integer)


primes = []

for num from 2 to max_num:


is_prime = True
for i from 2 to floor(sqrt(num)) + 1:
if num % i == 0:
is_prime = False
break
if is_prime:
primes.append(num)

Output: primes

Computing the nth Fibonacci number


The Fibonacci sequence is a series of numbers where each number is the sum of
the two preceding ones, usually starting with 0 and 1. The sequence goes like
this: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. Here's how you can compute the nth
Fibonacci number using a recursive approach:

1. Input the Value of n: Start by inputting the value of n, which represents


the position of the Fibonacci number you want to find. For example, if n
is 5, you want to find the 5th Fibonacci number.
2. Define the Recursive Function: Define a recursive function
fibonacci(n) that takes an integer n as input and returns the nth Fibonacci
number.
3. Base Cases: The base cases for the Fibonacci sequence are when n is 0 or
1. If n is 0, return 0. If n is 1, return 1.
4. Recursive Step: For n greater than 1, recursively call the fibonacci
function with n-1 and n-2 as arguments and add the results together to get
the nth Fibonacci number.
5. Return the Result: Return the result of the recursive call.

Here's the pseudo-code for computing the nth Fibonacci number:

Function Fibonacci(n):
If n is 0:
Return 0
Else If n is 1:
Return 1
Else:
Return Fibonacci(n-1) + Fibonacci(n-2)

Input: n (integer)
Output: Fibonacci(n)

Unit -4
Array order reversal
Reversing the order of an array involves changing the sequence of its elements
from the last element to the first. For example, if you have an array [1, 2, 3, 4,
5], after reversing, it becomes [5, 4, 3, 2, 1]. Here's a step-by-step explanation of
how to reverse the order of an array:

1. Input the Array: Start by inputting the array you want to reverse. Let's
say the array is [1, 2, 3, 4, 5].
2. Initialize Variables: Initialize two variables, start and end, to the first
and last indices of the array, respectively.
3. Swap Elements: Use a loop to swap the element at index start with the
element at index end, and then increment start and decrement end.
Repeat this process until start is greater than or equal to end.
4. Print the Reversed Array: Print the reversed array.
Here's the pseudo-code implementing these steps:
Function reverse_array(arr):
start = 0
end = length(arr) - 1

while start < end:


temp = arr[start]
arr[start] = arr[end]
arr[end] = temp
start = start + 1
end = end - 1

Return arr

Input: arr (array)


Output: reversed_arr (array)
Finding the maximum number in a set?
To find the maximum number in a set (or array), you can iterate through the set
and keep track of the maximum number found so far. Here's a step-by-step
explanation of how to do this:

1. Input the Set: Start by inputting the set (or array) for which you want to
find the maximum number. Let's say the set is {3, 7, 1, 9, 5}.
2. Initialize Variables: Initialize a variable max_num to negative infinity.
This variable will store the maximum number found so far.
3. Iterate Through the Set: For each element num in the set, compare it
with max_num. If num is greater than max_num, update max_num to
num.
4. Print the Result: Print the value of max_num, which will be the
maximum number in the set.

Here's the pseudo-code implementing these steps:

Function find_max(set):
max_num = -infinity
for num in set:
if num > max_num:
max_num = num

Return max_num

Input: set (array)


Output: max_num (integer)
Remove the duplicates from an ordered array
Removing duplicates from an ordered array involves creating a new array that
contains only the unique elements from the original array, while maintaining the
order of appearance. Here's a step-by-step explanation of how to do this:

1. Input the Ordered Array: Start by inputting the ordered array from
which you want to remove duplicates. Let's say the array is [1, 2, 2, 3, 3,
3, 4, 5, 5, 6].
2. Initialize Variables: Initialize an empty array unique_array to store the
unique elements.
3. Iterate Through the Array: For each element num in the ordered array,
check if num is different from the last element added to unique_array.
If it is, append num to unique_array.
4. Print the Result: Print the unique_array, which will contain only the
unique elements from the original ordered array.

Here's the pseudo-code implementing these steps:

Function remove_duplicates(ordered_array):
unique_array = []
last_added = None

for num in ordered_array:


if num != last_added:
unique_array.append(num)
last_added = num

Return unique_array

Input: ordered_array (array)


Output: unique_array (array)

Partitioning an array

Partitioning an array involves rearranging the elements in such a way that all
elements less than a certain value (the pivot) are placed before the pivot, and all
elements greater than or equal to the pivot are placed after it. This process is
commonly used in sorting algorithms like Quicksort. Here's a step-by-step
explanation of how to partition an array:

1. Input the Array and Pivot: Start by inputting the array you want to
partition and choosing a pivot value. Let's say the array is [4, 7, 2, 9, 5]
and the pivot is 5.
2. Initialize Variables: Initialize two pointers, low and high, to the first
and last indices of the array, respectively.
3. Partitioning Step: Repeat the following steps until low is greater than or
equal to high:
• Increment low until you find an element greater than or equal to
the pivot.
• Decrement high until you find an element less than the pivot.
• Swap the elements at indices low and high.
4. Swap Pivot with Element at High: Swap the pivot with the element at
index high. This places the pivot in its correct sorted position in the
array.
5. Print the Result: Print the partitioned array.

Here's the pseudo-code implementing these steps:

Function partition(array, pivot):


low = 0
high = length(array) - 1
while low <= high:
while array[low] < pivot:
low = low + 1
while array[high] > pivot:
high = high - 1
if low <= high:
swap array[low] with array[high]
low = low + 1
high = high - 1

swap array[high] with array[low]

Return high

Input: array (array), pivot (integer)


Output: partitioned_array (array)

Unit -5
Text line length adjustment
Text line length adjustment, also known as text justification or text wrapping,
involves adjusting the length of lines of text so that they fit within a specified
width. This is commonly done in typesetting and word processing to improve
the readability and appearance of text. Here's a step-by-step explanation of how
text line length adjustment can be done:

1. Input the Text and Maximum Line Width: Start by inputting the text
you want to adjust and the maximum width of each line. For example,
let's say the text is "Lorem ipsum dolor sit amet, consectetur adipiscing
elit." and the maximum line width is 20 characters.
2. Split the Text into Words: Split the input text into individual words. For
the example text, this would result in the array ["Lorem", "ipsum",
"dolor", "sit", "amet,", "consectetur", "adipiscing", "elit."].
3. Initialize Variables: Initialize a variable current_line to an empty
string, which will be used to store the current line being built. Also,
initialize a list justified_lines to store the final adjusted lines of text.
4. Iterate Through the Words: For each word in the array of words:
• If adding the word to the current line would exceed the maximum
line width, add the current line to the justified_lines list and start a
new line with the current word.
• Otherwise, add the word and a space to the current line.
5. Adjust the Last Line: After iterating through all the words, add the
remaining contents of the current line to the justified_lines list.
6. Print the Result: Print each line in the justified_lines list, which will be
the adjusted lines of text.

Here's the pseudo-code implementing these steps:

Function adjust_text(text, max_width):


words = split text into words
current_line = ""
justified_lines = []

for word in words:


if length(current_line) + length(word) <= max_width:
current_line = current_line + word + " "
else:
justified_lines.append(current_line.strip())
current_line = word + " "

justified_lines.append(current_line.strip())

Return justified_lines
Input: text (string), max_width (integer)
Output: justified_lines (array of strings)

Keyword searching in text


Keyword searching in text involves finding occurrences of specific words or
phrases within a larger body of text. Here's a step-by-step explanation of how
keyword searching can be done:

1. Input the Text and Keywords: Start by inputting the text in which you
want to search for keywords, as well as the keywords you want to search
for. For example, let's say the text is "Lorem ipsum dolor sit amet,
consectetur adipiscing elit." and the keywords are "ipsum" and
"adipiscing".
2. Split the Text into Words: Split the input text into individual words. For
the example text, this would result in the array ["Lorem", "ipsum",
"dolor", "sit", "amet,", "consectetur", "adipiscing", "elit."].
3. Initialize Variables: Initialize a list found_keywords to store the
keywords found in the text.
4. Search for Keywords: For each word in the array of words:
• Check if the word matches any of the keywords. If it does, add the
keyword to the found_keywords list.
5. Print the Result: Print the found_keywords list, which will contain all
the keywords found in the text.

Here's the pseudo-code implementing these steps:

Function keyword_search(text, keywords):


words = split text into words
found_keywords = []

for word in words:


if word in keywords:
found_keywords.append(word)

Return found_keywords
Input: text (string), keywords (array of strings)
Output: found_keywords (array of strings)

Text line editing


Text line editing involves modifying the content of a text line, such as inserting,
deleting, or replacing characters. Here's a step-by-step explanation of how text
line editing can be done:

1. Input the Text Line: Start by inputting the text line you want to edit. For
example, let's say the text line is "Hello, world!".
2. Choose an Editing Operation: Decide on the editing operation you want
to perform. For example, you may want to insert a character, delete a
character, or replace a character.
3. Perform the Editing Operation: Perform the chosen editing operation
on the text line. For example:
• Insertion: Insert a character at a specific position in the text line.
• Deletion: Delete a character at a specific position in the text line.
• Replacement: Replace a character at a specific position in the text
line with another character.
4. Print the Result: Print the edited text line.

Here's the pseudo-code implementing these steps for each type of editing
operation:

Insertion:

Function insert_character(text, position, character):


return text[:position] + character + text[position:]

Input: text (string), position (integer), character (string)


Output: edited_text (string)
Deletion:
Function delete_character(text, position):
return text[:position] + text[position+1:]
Input: text (string), position (integer)
Output: edited_text (string)
Replacement:
Function replace_character(text, position, new_character):
return text[:position] + new_character + text[position+1:]

Input: text (string), position (integer), new_character (string)


Output: edited_text (string)

Keyword searching in a text


Keyword searching in a text involves finding occurrences of specific words or
phrases within a larger body of text. Here's a step-by-step explanation of how
keyword searching can be done:

1. Input the Text and Keywords: Start by inputting the text in which you
want to search for keywords, as well as the keywords you want to search
for. For example, let's say the text is "Lorem ipsum dolor sit amet,
consectetur adipiscing elit." and the keywords are "ipsum" and
"adipiscing".
2. Split the Text into Words: Split the input text into individual words. For
the example text, this would result in the array ["Lorem", "ipsum",
"dolor", "sit", "amet,", "consectetur", "adipiscing", "elit."].
3. Initialize Variables: Initialize a list found_keywords to store the
keywords found in the text.
4. Search for Keywords: For each word in the array of words:
• Check if the word matches any of the keywords. If it does, add the
keyword to the found_keywords list.
5. Print the Result: Print the found_keywords list, which will contain all
the keywords found in the text.

Here's the pseudo-code implementing these steps:

Function keyword_search(text, keywords):


words = split text into words
found_keywords = []

for word in words:


if word in keywords:
found_keywords.append(word)

Return found_keywords

Input: text (string), keywords (array of strings)


Output: found_keywords (array of strings)

You might also like