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

CAT1 STSCoding

The document discusses various algorithms like finding the maximum equilibrium sum, leaders in an array, majority element, quicksort, selection sort, sorted unique permutations, number of paths, combinations, Josephus trap, maze solving, N queens, Warnsdorff's algorithm for knight's tour, and Hamiltonian cycle. Code implementations are provided for these algorithms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

CAT1 STSCoding

The document discusses various algorithms like finding the maximum equilibrium sum, leaders in an array, majority element, quicksort, selection sort, sorted unique permutations, number of paths, combinations, Josephus trap, maze solving, N queens, Warnsdorff's algorithm for knight's tour, and Hamiltonian cycle. Code implementations are provided for these algorithms.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

=>Max Equilibrium Sum:-

def find_max_equilibrium_sum(arr):
max_sum = float('-inf')
for i in range(len(arr)):
prefix_sum = sum(arr[:i])
suffix_sum = sum(arr[i + 1:])

if prefix_sum == suffix_sum:
max_sum = max(max_sum, prefix_sum)
return max_sum
arr=list(map(int,input("Enter the elements").spilt())
print(find_max_equilibrium_sum(arr))
------------------------------------------------------------------------------------------------------------------------------------------------------------
=>Leaders In Array
def printLeaders(arr,size):
for i in range(0, size):
for j in range(i+1, size):
if arr[i]<=arr[j]:
break
if j == size-1: # If loop didn't break
print arr[i],
# Driver function
arr=list(map(int,input("Enter the elements").spilt())
printLeaders(arr, len(arr))
------------------------------------------------------------------------------------------------------------------------------------------------------------
=>Majority Element
def find_majority_element(arr):
size = len(arr)
for element in set(arr):
if arr.count(element) > (size / 2):
print(element)
return
print('None')
# Driver program
arr =list(map(int,input("Enter the elements").spilt())
find_majority_element(arr)
------------------------------------------------------------------------------------------------------------------------------------------------------------
=>Quick Sort
def quicksort(arr, low, high):
if low < high:
pivot_index = partition(arr, low, high)
quicksort(arr, low, pivot_index)
quicksort(arr, pivot_index + 1, high)
def partition(arr, low, high):
pivot_element = arr[low]
left = low + 1
right = high
done = False
while not done:
while left <= right and arr[left] <= pivot_element:
left = left + 1
while arr[right] >= pivot_element and right >= left:
right = right - 1
if right < left:
done = True
else:
arr[left], arr[right] = arr[right], arr[left]

arr[low], arr[right] = arr[right], arr[low]


return right
# Example usage:
arr = list(map(int,input("Enter the elements").spilt())
quicksort(arr, 0, len(arr) - 1)
print("Sorted Array:", arr)
------------------------------------------------------------------------------------------------------------------------------------------------------------
=>Selection Sort:-
def selection_sort(arr):
n = len(arr)
for i in range(n - 1):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
def print_array(arr):
for num in arr:
print(num, end=" ")
print()
# Example usage:
arr = list(map(int,input("Enter the elements").spilt())
selection_sort(arr)
print("Sorted array:")
print_array(arr)
------------------------------------------------------------------------------------------------------------------------------------------------------------
=>Sorted Unique Permutation
def selection_sort(arr):
n = len(arr)
for i in range(n - 1):
min_idx = i
for j in range(i + 1, n):
if arr[j] < arr[min_idx]:
min_idx = j
# Swap arr[i] and arr[min_idx]
arr[i], arr[min_idx] = arr[min_idx], arr[i]
def print_array(arr):
for num in arr:
print(num, end=" ")
print()
# Example usage:
size = int(input("Enter the size of the array: "))
arr = [int(input("Enter element " + str(i + 1) + ": ")) for i in range(size)]
selection_sort(arr)
print("Sorted array:")
print_array(arr)
------------------------------------------------------------------------------------------------------------------------------------------------------------
=>Maneuvering
def number_of_paths(m, n):
if m == 1 or n == 1:
return 1
return number_of_paths(m - 1, n) + number_of_paths(m, n - 1)
# Example usage:
print(number_of_paths(3, 3))
------------------------------------------------------------------------------------------------------------------------------------------------------------
=>Combination
def combination_util(arr, n, r, index, data, i):
if index == r:
for j in range(r):
print(data[j], end=" ")
print()
return
if i >= n:
return
data[index] = arr[i]
combination_util(arr, n, r, index+1, data, i+1)
combination_util(arr, n, r, index, data, i+1)
# Example usage:
arr = [1, 2, 3]
r=2
n = len(arr)
data = [0] * r
combination_util(arr, n, r, 0, data, 0)
------------------------------------------------------------------------------------------------------------------------------------------------------------
=>Josephus trap
def josephus(n, k):
if n == 1:
return 1
else:
return (josephus(n - 1, k) + k - 1) % n + 1
# Example usage:
n=5
k=2
print("The chosen place is", josephus(n, k))
------------------------------------------------------------------------------------------------------------------------------------------------------------
=>Maze Solving
def maze_solve(maze, x, y, sol):
global cont
if x == len(maze) - 1 and y == len(maze[0]) - 1:
sol[x][y] = 1
return True
if is_passable(maze, x, y):
sol[x][y] = 1
if maze_solve(maze, x, y + 1, sol):
return True
if maze_solve(maze, x + 1, y, sol):
return True
sol[x][y] = 0
return False
def is_passable(maze, x, y):
global cont
cont += 1
return 0 <= x < len(maze) and 0 <= y < len(maze[0]) and maze[x][y] == 1
def main():
maze = [
[1, 1, 1, 1, 0],
[0, 0, 0, 1, 1],
[1, 1, 1, 1, 1],
[1, 0, 0, 0, 1],
[1, 1, 1, 1, 1]
]
sol = [[0] * len(maze[0]) for _ in range(len(maze))]
if maze_solve(maze, 0, 0, sol):
for row in sol:
print(" ".join(map(str, row)))
else:
print("Solution is not possible")
if __name__ == "__main__":
global cont
cont = 0
main()
print("Number of recursive calls:", cont)
------------------------------------------------------------------------------------------------------------------------------------------------------------
=>N Queens
N=4
def is_safe(board, row, col):
for j in range(col, -1, -1):
if board[row][j] == 1:
return False
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
for i, j in zip(range(row, N), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solve_n_queens_util(board, col):
if col >= N:
return True
for i in range(N):
if is_safe(board, i, col):
board[i][col] = 1
if solve_n_queens_util(board, col + 1):
return True
board[i][col] = 0
return False
def main():
board = [[0] * N for _ in range(N)]
if solve_n_queens_util(board, 0):
for i in range(N):
for j in range(N):
print(f" {board[i][j]}", end=" ")
print()
else:
print("Solution does not exist")
if __name__ == "__main__":
main()
------------------------------------------------------------------------------------------------------------------------------------------------------------
=>Warnsdorff’s Algorithm
def initialize_board(size):
return [[float('-inf') for _ in range(size)] for _ in range(size)]
def print_solution(board):
for row in board:
for cell in row:
print(cell, end="\t")
print()
def solve_knight_tour_problem(board_size):
board = initialize_board(board_size)
visited = initialize_board(board_size)
x_moves = [2, 1, -1, -2, -2, -1, 1, 2]
y_moves = [1, 2, 2, 1, -1, -2, -2, -1]
def is_valid_move(x, y):
return 0 <= x < board_size and 0 <= y < board_size
def solve_problem(move_count, x, y):
# Base Case: We were able to move to each square exactly once
if move_count == board_size * board_size:
return True
for i in range(len(x_moves)):
next_x = x + x_moves[i]
next_y = y + y_moves[i]
# Check if the new position is valid and not visited yet
if is_valid_move(next_x, next_y) and visited[next_x][next_y] == float('-inf'):
visited[next_x][next_y] = move_count
if solve_problem(move_count + 1, next_x, next_y):
return True
# Backtrack!!!
visited[next_x][next_y] = float('-inf')
return False
visited[0][0] = 0
# Start knight tour from top-left corner square (0, 0)
if solve_problem(1, 0, 0):
print_solution(visited)
else:
print("No feasible solution found...")
if __name__ == "__main__":
chess_board_size = 8
solve_knight_tour_problem(chess_board_size)
------------------------------------------------------------------------------------------------------------------------------------------------------------
=>Hamiltonian Cycle
V=5
def is_safe(v, graph, path, pos):
if graph[path[pos - 1]][v] == 0:
return False
for i in range(pos):
if path[i] == v:
return False
return True
def ham_cycle_util(graph, path, pos):
if pos == V:
if graph[path[pos - 1]][path[0]] == 1:
return True
else:
return False
for v in range(1, V):
if is_safe(v, graph, path, pos):
path[pos] = v
if ham_cycle_util(graph, path, pos + 1):
return True
path[pos] = -1
return False
def ham_cycle(graph):
path = [-1] * V
path[0] = 0
if not ham_cycle_util(graph, path, 1):
print("\nSolution does not exist")
return 0
print_solution(path)
return 1
def print_solution(path):
print("Solution Exists: Following is one Hamiltonian Cycle")
for i in range(V):
print(f" {path[i]}", end=" ")
print(f" {path[0]} ")
# driver program to test above function
if __name__ == "__main__":
graph1 = [
[0, 1, 0, 1, 0],
[1, 0, 1, 1, 1],
[0, 1, 0, 0, 1],
[1, 1, 0, 0, 1],
[0, 1, 1, 1, 0],
]
ham_cycle(graph1)
graph2 = [
[0, 1, 0, 1, 0],
[1, 0, 1, 1, 1],
[0, 1, 0, 0, 1],
[1, 1, 0, 0, 0],
[0, 1, 1, 0, 0],
]
ham_cycle(graph2)
------------------------------------------------------------------------------------------------------------------------------------------------------------

You might also like