0% found this document useful (0 votes)
27 views7 pages

Codes

The document contains various code snippets in Python and Java, showcasing different algorithms and functions. These include sorting, counting unique marbles, calculating scores, and manipulating strings. Each section provides example usage and outlines the logic behind the functions implemented.

Uploaded by

Sadiq Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views7 pages

Codes

The document contains various code snippets in Python and Java, showcasing different algorithms and functions. These include sorting, counting unique marbles, calculating scores, and manipulating strings. Each section provides example usage and outlines the logic behind the functions implemented.

Uploaded by

Sadiq Ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

➢ def index_sort_count(A): >def max_reachable_squares(H, W): >public class MaxBishopSquares {

count = 0 return min(H, W) public static int


for K in range(1, len(A) + 1): # Example usage: maxBishopSquares(int H, int W) {
if A[K - 1] != K: rows = 5 return Math.min(H, W); }
count += 1 columns = 6 public static void main(String[] args) {
return count result = max_reachable_squares(rows, int H = 5;
# Example usage: columns) int W = 7;
array = [3, 1, 2] print(result) int result = maxBishopSquares(H
result = index_sort_count(array) W);
print(result) System.out.println(result); }}
Birthday party : >def min_steps_to_magic_string(S): >def unique_marbles(N, A, B):
>import java.util.Scanner; # Count occurrences of each character unique_set = set()
public class BirthdayParty { char_count = {} def explore(marbles):
public static void main(String[] args) { for char in S: if marbles > 0 and marbles not in
Scanner scanner = new if char in char_count: unique_set:
Scanner(System.in); char_count[char] += 1 unique_set.add(marbles)
System.out.print("Enter the number of else: explore(marbles - A)
pieces of the first cake (N): "); char_count[char] = 1 explore(marbles - B)
int N = scanner.nextInt(); # Find the maximum occurrence of a
System.out.print("Enter the number of character explore(N)
pieces of the second cake (M): "); max_occurrence = return len(unique_set)
int M = scanner.nextInt(); max(char_count.values()) if char_count
int result = else 0 # Example usage:
maxPeopleWithEqualPieces(N, M); # Calculate the minimum steps initial_marbles = 10
System.out.println("Maximum number required operation_A = 3
of people at the party: " + result); return len(S) - max_occurrence if operation_B = 5
} max_occurrence > 0 else 0
private static int # Example usage: result = unique_marbles(initial_marble
maxPeopleWithEqualPieces(int N, int M) { input_string = "al.com" operation_A, operation_B)
int gcd = findGCD(N, M); result = print(result)____________________
return gcd; min_steps_to_magic_string(input_string)
} print(result)
private static int findGCD(int a, int b) { ➢ def special_series(N): (i-2)) % 47
while (b != 0) { if N == 1 or N == 2: prev_2 = prev_1
int temp = b; return 1 prev_1 = current
b = a % b; prev_1 = 1 return current
a = temp; prev_2 = 1 # Example usage:
} current = 0 N_value = 10
return a; } } for i in range(3, N+1): result = special_series(N_value)
current = (prev_1 * (i-1) + prev_2 * print(result)

>def maximize_grade(N, P, K): >import java.util.Scanner; >def ant_original_position(N, A):


# Convert the string to a list for easy public class MinASCIIDistance { net_displacement = 0
swapping public static int for move in A:
grades = list(N) minASCIIDistance(String s, String a) { if move == 1:
# Find the lexicographically smallest int distance = 0; net_displacement += 1
character for (int i = 0; i < s.length(); i++) { else:
smallest_char = min(grades) char charS = s.charAt(i); net_displacement -= 1
# Swap the smallest character with the char charA = a.charAt(i); # If the net displacement is zero, the
character at position P ant returns to the original position
grades[P - 1] = smallest_char int asciiS = (int) charS; return abs(net_displacement // N)
# Perform additional swaps if allowed int asciiA = (int) charA; # Example usage:
swaps_left = K - 1 moves = 7
idx = 0 int diff = Math.abs(asciiS - ant_moves = [1, 1, -1, -1, 1, -1, -1]
while swaps_left > 0 and idx < asciiA); result = ant_original_position(moves,
len(grades): distance += diff; ant_moves)
if grades[idx] != smallest_char: } print(result)
grades[idx] = smallest_char return distance; >public class FellisFunction {
swaps_left -= 1 } public static void main(String[] args) {
idx += 1 public static void main(String[] args) int N = 2;
# Convert the list back to a string and { int result = fellisFunction(N);
return Scanner n=new Scanner(System.in); System.out.println(result); }
return ''.join(grades) String stringS =n.next(); public static int fellisFunction(int N) {
# Example usage: String stringA = n.next(); if (N == 0) {
grades = "Jeepk" int result = return 1;
position = 3 minASCIIDistance(stringS, stringA); } else if (N == 1) {
max_swaps = 2 System.out.println("Minimum total return 1;
result = maximize_grade(grades, position, ASCII distance: " + result); } else {
max_swaps) } return (fellisFunction(N - 1) + 7
print(result) } * fellisFunction(N - 2) + (N / 4)) %
1000000007; } } }
➢ def string_swap(S, operations): ➢ def special_series(N): ➢ def string_swap(S, A):
for op in operations: if N == 1 or N == 2: for op in A:
if op == 1: return 1 if op == 1:
# Swap the first and last characters prev_1 = 1 # Swap the first and last
S = S[-1] + S[1:-1] + S[0] prev_2 = 1 characters
elif op == 2: current = 0 S = S[-1] + S[1:-1] + S[0]
# Swap the first and last N/2 for i in range(3, N+1): elif op == 2:
characters current = (prev_1 * (i-1) + prev_2 * # Swap the first N/2 and last N
mid = len(S) // 2 (i-2)) % 47 characters
S = S[mid:] + S[:mid] prev_2 = prev_1 mid = len(S) // 2
return S prev_1 = current S = S[mid:] + S[:mid]
# Example usage: return current return S
initial_string = "abcdefgh" # Example usage: # Example usage:
sequence_of_operations = [1, 2, 1] N_value = 10 initial_string = "abcdefgh"
result = string_swap(initial_string, result = special_series(N_value) operations_sequence = [1, 2, 1]
sequence_of_operations) print(result) result = string_swap(initial_string,
print(result) operations_sequence)
print(result)
➢ public class AntOnRail { ➢ public class TossAndScore { ➢ import java.util.Scanner;
public static void main(String[] args) { public static int public class SpecialFibonacci {
int[] moves = {1, -1, 1, -1, 1}; calculateFinalScore(String s) { public static void main(String[] args
int numberOfMoves = moves.length; int score = 0; {
int result = int consecutiveHeads = 0; Scanner scanner = new
countBackToStartPosition(numberOfMoves, for (char result : s.toCharArray()) { Scanner(System.in);
moves); if (result == 'H') { System.out.print("Enter the value of N
System.out.println("Number of times consecutiveHeads++; ");
the ant reaches back to its original position: score += 2; int N = scanner.nextInt();
" + result); } else { int result =
} consecutiveHeads = 0; calculateSpecialFibonacci(N);
public static int score -= 1; System.out.println("Result: " +
countBackToStartPosition(int N, int[] A) { } result);
int currentPosition = 0; // Initialize the if (consecutiveHeads == 3) { scanner.close();
current position break; // Game ends when 3 }
int count = 0; // Initialize the count of consecutive heads are obtained private static int
reaching back to the original position } calculateSpecialFibonacci(int N) {
for (int i = 0; i < N; i++) { } if (N == 0 || N == 1) {
currentPosition += A[i]; return score; return N;
if (currentPosition == 0) { } }
count++; public static void main(String[] args)
} { int[] fib = new int[N + 1];
} String tossResults = "HTHHTT"; // fib[0] = 1;
Replace with your actual toss results fib[1] = 1;
return count; int finalScore =
} calculateFinalScore(tossResults); for (int i = 2; i <= N; i++) {
} System.out.println("Final Score: " + fib[i] = (fib[i - 1] * fib[i - 1] +
finalScore); fib[i - 2]*fib[i-2]);
} }
}
return fib[N];
}
}
import java.util.Arrays; public class FellisFunction { import java.util.Arrays;
public class MaxProductPair { public class PSBalance {
public static int[] public static void main(String[] args) public static void main(String[] args
maxProductPairWithSum18(int[] arr) { { {
int maxProduct = int N = 2; int[] a={1,2,3,4,5};
Integer.MIN_VALUE; int result = fellisFunction(N); int[] res=Balance(a);
int[] resultPair = new int[2]; System.out.println(result); System.out.println(Arrays.toString(res
for (int i = 0; i < arr.length; i++) { } }
for (int j = i + 1; j < arr.length; j++) { public static int[] Balance(int[] a){
if (arr[i] + arr[j] == 18 && arr[i] > public static int fellisFunction(int N) { int n=a.length;
arr[j]) { if (N == 0) { int[] r=new int[n];
int product = arr[i] * arr[j]; return 1; int sum=0;
if (product > maxProduct) { } else if (N == 1) { for(int i=0;i<n;i++){
maxProduct = product; return 1; sum+=a[i];
resultPair[0] = arr[i]; } else { r[i]=Math.abs(sum-
resultPair[1] = arr[j]; return (fellisFunction(N - 1) + 7 sumR(i+1,a));
}}} } * fellisFunction(N - 2) + (N / 4)) % }
return resultPair; } 1000000007; return r; }
public static void main(String[] args) { } public static int sumR(int j,int[] a){
int[] integerArray = {4, 8, 2, 10, 6}; } int n=a.length;
int[] result = } int val=0;
maxProductPairWithSum18(integerArray); for(int i=j;i<n;i++){
System.out.println("Pair with val+=a[i];
maximum product and sum 18: " + }
Arrays.toString(result)); if(j==n){
} return 0; }
} return val; } }
Generated numbers : Pyramid sum : ➢ import java.util.Scanner;
import java.util.HashSet; import java.util.Scanner; public class MarbleJarOperations
import java.util.Scanner; public class PyramidSum { {
import java.util.Set; public static void main(String[] args) public static int
public class UniqueMarbles { { performOperations(int N, int A, int B)
public static void main(String[] args) { Scanner scanner = new {
Scanner scanner = new Scanner(System.in); while (N > 0)
Scanner(System.in); System.out.print("Enter the height {
System.out.print("Enter the initial of the pyramid (N): "); if (N - A >= 0)
number of marbles (N): "); int N = scanner.nextInt(); {
int N = scanner.nextInt(); int result = pyramidSum(N); N -= A;
System.out.print("Enter the value of A: System.out.println("Sum of the }
"); pyramid: " + result); else if (N - B >= 0)
int A = scanner.nextInt(); } {
System.out.print("Enter the value of B: private static int pyramidSum(int N) { N -= B;
"); int sum = 0; }
int B = scanner.nextInt(); for (int i = 1; i <= N; i++) { else
int result = countUniqueMarbles(N, A, sum += rowSum(i); {
B); } break;
System.out.println("Total number of return sum; }}
unique marbles that can be left behind: " + } return N; }
result); private static int rowSum(int row) { public static void main(String[] args)
} int sum = 0; {
private static int countUniqueMarbles(int for (int i = 1; i <= row; i++) { Scanner scanner = new
N, int A, int B) { sum += i; Scanner(System.in);
Set<Integer> uniqueMarbles = new } System.out.print("Enter the initial
HashSet<>(); return sum; number of marbles (N): ");
uniqueMarbles.add(N); } int initialMarbles =
for (int i = 0; i <= N; i += A) { } scanner.nextInt();
for (int j = 0; j <= N; j += B) { System.out.print("Enter the numb
uniqueMarbles.add(N - i - j); of marbles to take out (A): ");
} int takeOutA = scanner.nextInt();
} System.out.print("Enter the numb
return uniqueMarbles.size(); of marbles to take out (B): ");
} int takeOutB = scanner.nextInt();
} int remainingMarbles =
performOperations(initialMarbles,
takeOutA, takeOutB);
System.out.println("Remaining
marbles in the jar: " +
remainingMarbles);
scanner.close(); } }
def find_original_number(z1, z2, z3): public class ParallelUniverseChessBoard public class StringSwap {
""" {
Finds the original integer X given its public static int public static String
transformed values z1, z2, and z3. maxSquaresBishopCanReach(int rows, performOperations(String s, int[]
int columns) { operations) {
Args: int[][] chessboard = new for (int op : operations) {
z1: Integer resulting from the first bit flip. int[rows][columns];. if (op == 1) {
z2: Integer resulting from the second bit flip. for (int i = 0; i < rows; i++) { s = swapFirstAndLast(s);
z3: Integer resulting from the third bit flip. for (int j = 0; j < columns; j++) { } else if (op == 2) {
chessboard[i][j] = 0; s = swapFirstAndLastHalf(s)
Returns: }} }
The original integer X. chessboard[0][0] = 1; }
# Find the differences between the for (int i = 0; i < rows; i++) { return s;
transformed values. for (int j = 0; j < columns; j++) { }
diff12 = z2 ^ z1 if (chessboard[i][j] == 1) {
diff23 = z3 ^ z2 int k = i - 1; private static String
int l = j - 1; swapFirstAndLast(String s) {
# Identify the bit positions of the while (k >= 0 && l >= 0) { char[] chars = s.toCharArray();
differences. chessboard[k][l] = 1; char temp = chars[0];
bit12 = diff12.bit_length() - 1 k--; chars[0] = chars[chars.length - 1];
bit23 = diff23.bit_length() - 1 l--; chars[chars.length - 1] = temp;
} return new String(chars);
# Determine the original bit values based on k = i - 1; }
the differences. l = j + 1;
bit1 = (z1 >> bit12) & 1 while (k >= 0 && l < private static String
bit2 = (z2 >> bit23) & 1 columns) { swapFirstAndLastHalf(String s) {
chessboard[k][l] = 1; int length = s.length();
# Calculate the original value of X. k--; int half = length / 2;
x = z1 ^ (1 << bit12) ^ (1 << bit23) l++; char[] chars = s.toCharArray();
}
# Check if x is valid and satisfies the k = i + 1; for (int i = 0; i < half; i++) {
conditions. l = j - 1; char temp = chars[i];
if x.bit_length() > 32 or (2 * (x ^ (1 << while (k < rows && l >= 0) chars[i] = chars[i + half];
bit12)) + 5) != z2 or (2 * (x ^ (1 << bit23)) + { chars[i + half] = temp;
5) != z3: chessboard[k][l] = 1; }
raise ValueError("Invalid value for X") k++;
l--; return new String(chars);
return x } }
k = i + 1;
# Example usage l = j + 1; public static void main(String[] args
z1 = 42 while (k < rows && l < {
z2 = 38 columns) { String inputString = "String"; //
z3 = 36 chessboard[k][l] = 1; Replace with your input string
original_number = k++; int[] operations = {1, 2, 1}; //
find_original_number(z1, z2, z3) l++; Replace with your array of operations
}} }}
print(f"Original number: int count = 0; String result =
{original_number}") for (int i = 0; i < rows; i++) { performOperations(inputString,
for (int j = 0; j < columns; j++) { operations);
if (chessboard[i][j] == 1) { System.out.println("Final String:
count++; + result);
}} } }
return count; } }
public static void main(String[] args)
{
int rows = Integer.parseInt(args[0]);
int columns =
Integer.parseInt(args[1]);
int maxSquares =
maxSquaresBishopCanReach(rows,
columns);
System.out.println("The maximum
number of squares the bishop can reach
is: " + maxSquares);
}
}
public class AntOnRailing >import java.util.Scanner; >def remove_unique_characters(S):
{ public class MagicStringTransformation frequency = {}
public static int finalPosition(int[] moves) { non_unique_chars = set()
{ public static String # Count the frequency of each
int position = 0; makeMagicString(String S) character
for (int move : moves) { for char in S:
{ if (S.isEmpty()) frequency[char] =
position += move; { frequency.get(char, 0) + 1
} return S; # Identify non-unique characters
return position; } for char, count in frequency.items():
} char firstChar = S.charAt(0); if count > 1:
public static void main(String[] args) String magicString = non_unique_chars.add(char)
{ S.replaceAll("[a-zA-Z]", result = []
int[] antMoves = {1, -1, 1, 1, -1}; String.valueOf(firstChar)); # Traverse the string and keep non-
return magicString; unique characters
int finalPosition = } for char in S:
finalPosition(antMoves); public static void main(String[] args) if char in non_unique_chars:
System.out.println("Final position of { result.append(char)
the ant: " + finalPosition); Scanner scanner = new return ''.join(result)
} Scanner(System.in); # Example usage:
} System.out.print("Enter the string S = input("Enter the string: ")
S: "); result = remove_unique_characters(S)
String inputString = print(f"Modified string: {result}")
scanner.nextLine();
String magicString =
makeMagicString(inputString);
System.out.println("Magic string: "
+ magicString);
scanner.close(); } }
import java.util.Arrays; >def calculate_qualifying_score(S1, S2, >def gcd(a, b):
P): while b:
public class DivideArray qualifying_score = 35 a, b = b, a % b
{ # Step 1: Subtract marks obtained in return a
semester 1 from semester 2
public static void divideArray(int[] arr) score_diff = [S2[i] - S1[i] for i in def lcm(a, b):
{ range(len(S1))] return a * b // gcd(a, b)
int N = arr.length; # Step 2: Add marks of up to P
subjects with high scores def find_meeting_time(N, M):
for (int i = 1; i <= N; i++) qualifying_score += return lcm(N, M)
{ sum(sorted(score_diff,
int[] firstPart = reverse=True)[:P]) # Example usage:
Arrays.copyOfRange(arr, 0, i); # Determine qualification status N = 5 # Time taken by Robotop to
int[] secondPart = result = "qualified" if qualifying_score complete one lap
Arrays.copyOfRange(arr, i, N); >= 35 else "disqualified" M = 7 # Time taken by Robocop to
return result complete one lap
System.out.println("First part (i = " + # Example usage:
i + "): " + Arrays.toString(firstPart)); subjects_count = int(input("Enter the meeting_time = find_meeting_time(N,
System.out.println("Second part (N - number of subjects: ")) M)
i = " + (N - i) + "): " + S1 = [float(input(f"Enter marks for print("The least time at which they me
Arrays.toString(secondPart)); subject {i + 1} in semester 1: ")) for i in again is:", meeting_time, "seconds")
System.out.println(); range(subjects_count)]
} S2 = [float(input(f"Enter marks for
} subject {i + 1} in semester 2: ")) for i in
range(subjects_count)]
public static void main(String[] args) P = int(input("Enter the number of
{ subjects to consider for high scores: "))
int[] A = {1, 2, 3, 4, 5};
System.out.println("Dividing the array qualification_result =
A into two parts:"); calculate_qualifying_score(S1, S2, P)
divideArray(A); print(f"The student is
} {qualification_result} to appear in the
} competition.")
➢ def solve(input1, input2, input3): String swap : >public class keyboardPress {
N = input1 import java.util.Scanner; Run | Debug
A = input2 public class StringSwap { public static void main(String[] args) {
B = input3 public static void main(String[] args) String s = "60004";
uniq = set() { int result = minKeyPress(s);
uniq.add(N) Scanner scanner = new System.out.println(result);
for Scanner(System.in); public static int minKeyPress(String s)
in range(N): System.out.print("Enter the initial int currentNo = 1;
cur = list(uniq) string: "); int keyPress = -1;
for value in cur: String inputString = for (charc: s.toCharArray()) {
if value Α > Θ: uniq.add(value - A) scanner.nextLine(); int digit = c '0';
if value B> 0: uniq.add(value - B) System.out.print("Enter the length } currentNo = currentNo + 10 + digit;
return len(uniq) of array M: "); }}}
int m = scanner.nextInt();
int[] operations = new int[m];
System.out.print("Enter the array A
of length M: ");
for (int i = 0; i < m; i++) {
operations[i] = scanner.nextInt();
}
String result =
performOperations(inputString,
operations);
System.out.println("Final string
after performing all operations: " +
result);
}
private static String
performOperations(String str, int[]
operations) {
int n = str.length();
for (int operation : operations) {
if (operation == 1) {
str = swapFirstAndLast(str);
} else if (operation == 2) {
str = swapFirstAndLastHalf(str);
}
}
return str;
}
private static String
swapFirstAndLast(String str) {
char[] charArray =
str.toCharArray();
char temp = charArray[0];
charArray[0] =
charArray[charArray.length - 1];
charArray[charArray.length - 1] =
temp;
return new String(charArray);
}
private static String
swapFirstAndLastHalf(String str) {
int n = str.length();
int half = n / 2;
char[] charArray =
str.toCharArray();
for (int i = 0; i < half; i++) {
char temp = charArray[i];
charArray[i] = charArray[i +
half];
charArray[i + half] = temp;
}
return new String(charArray);
}
}

You might also like