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

Java Complex Som

Uploaded by

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

Java Complex Som

Uploaded by

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

Complex Problem

Project Based Learning in java with Lab

Student Name: Somya Kukreti UID: 21BCS3656


Branch: BE-CSE Section/Group:CC-610/B

Ques 1 : Consider a function public String matchFound(String input 1, String input 2),
where • input1 will contain only a single word with only 1 character replaces by an
underscore ‘_’ • input2 will contain a series of words separated by colons and no space
character in between • input2 will not contain any other special character other than
underscore and alphabetic characters.
Code : public static String matchFound(String input1, String input2) {
String[] words = input2.toUpperCase().split(":");
StringBuilder matchedWords = new StringBuilder();
for (String word: words) {
if (word.length() == input1.length()) {
boolean matched = true;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) != input1.charAt(i) && input1.charAt(i) != '_')
{ matched = false;
break;
}
}
if (matched) {
if (matchedWords.length() > 0) {
matchedWords.append(":");
}
matchedWords.append(word);
}
}
}

Ques 2 : Encoding Three Strings: Anand was assigned the task of coming up with an
encoding mechanism for any given three strings.He has come up with the following
plan…….Final Result – The three output strings after applying the above three steps i.e.
for the above example . Output1 =”Jnhan” Output2=”ohnyJan’ Output3 = “NJOARD”
Help Anand to write a program that would do the above.
Code : public class StringEncoder {
public static String[] splitString(String input) {
String[] parts = new String[3];
int len = input.length();

Devesh Kumar Singh 21BCS8725


int partLength = len / 3;
int remainder = len % 3;
parts[0] = input.substring(0, partLength + (remainder >= 1 ? 1 : 0));
parts[1] = input.substring(partLength + (remainder >= 1 ? 1 : 0),
partLength * 2 + (remainder >= 2 ? 1 : 0));
parts[2] = input.substring(partLength * 2 + (remainder >= 2 ? 1 : 0));
return parts;
}
public static String concatenateParts(String[] parts1, String[] parts2, String[]
parts3) {
String output1 = parts1[0] + parts2[1] + parts3[2];
String output2 = parts1[1] + parts2[2] + parts3[0];
String output3 = parts1[2] + parts2[0] + parts3[1];
return output1 + "\n" + output2 + "\n" + output3;
}
public static String toggleCase(String input) {
StringBuilder toggled = new StringBuilder();
for (char c: input.toCharArray()) {
if (Character.isLowerCase(c)) {
toggled.append(Character.toUpperCase(c));
} else if (Character.isUpperCase(c)) {
toggled.append(Character.toLowerCase(c));
} else {
toggled.append(c);
}
}
return toggled.toString();
}
public static void main(String[] args) {
String input1 = "John";
String input2 = "Johny";
String input3 = "Janardhan";
String[] parts1 = splitString(input1);
String[] parts2 = splitString(input2);
String[] parts3 = splitString(input3);
String concatenatedOutput = concatenateParts(parts1, parts2, parts3);
String output3 = toggleCase(concatenatedOutput.split("\n")[2]);
System.out.println("Output1: " + concatenatedOutput.split("\n")[0]);
System.out.println("Output2: " + concatenatedOutput.split("\n")[1]);
System.out.println("Output3: " + output3);
}
}

Devesh Kumar Singh 21BCS8725


Ques : 3 Givena String (In Uppercase alphabets or Lowercase alphabets), new alphabets
isto be appended with following rule: (i) If alphabet is present in input string, use
numeric value of that alphabet. E.g. a or A numeric value is 1 and so on. New alphabet
to be appendedbetween 2 alphabets :… Constraint: Whether string alphabets are In
Uppercase or Lowercase, appended alphabets must be in lower case. Output string must
also be in lowercase.
Code: public class AlphabetAppender {
public static String appendAlphabets(String input) {
StringBuilder output = new StringBuilder();
char[] chars = input.toLowerCase().toCharArray();
for (int i = 0; i < chars.length; i++) {
char currentChar = chars[i];
if (Character.isLetter(currentChar)) {
int numericValue = currentChar - 'a' + 1;
if (i + 1 < chars.length && Character.isLetter(chars[i + 1])) {
int nextNumericValue = chars[i + 1] - 'a' + 1;
int sum = (numericValue + nextNumericValue) % 26;
char newChar;
if (sum == 0)
{ newChar = '0';
} else {
newChar = (char)((sum - 1) + 'a');
}
output.append(currentChar).append(newChar);
} else {
output.append(currentChar);
}
} else {
output.append(currentChar);
}
}
return output.toString();
}
public static void main(String[] args) {
String input = "ac 12a";
String output = appendAlphabets(input);
System.out.println("Output: " + output);
}
}

Ques 4: String
t is generated by random shuffling string s and then add one more letter at a
random position. Return the letter that was added to t. Hint: Input: s = "abcd", t =
"abcde" Output: "e"
Devesh Kumar Singh 21BCS8725
Code : import java.util.*;
public class RandomShuffleWithOneMoreLetter {
public static char addLetter(String s) {
char[] sChars = s.toCharArray();
List<Character> charList = new ArrayList<>();
for (char c : sChars) {
charList.add(c);
}
Collections.shuffle(charList);
Random random = new Random();
char additionalLetter = (char) (random.nextInt(26) + 'a');
int randomIndex = random.nextInt(s.length() + 1);
charList.add(randomIndex, additionalLetter);
StringBuilder sb = new StringBuilder();
for (char c : charList) {
sb.append(c);
}
return additionalLetter;
}
public static void main(String[] args) {
String s = "abcd";
char addedLetter = addLetter(s);
System.out.println("Input: s = \"" + s + "\", t = \"" + addLetter(s) + "\"");
System.out.println("Output: \"" + addedLetter + "\"");
}
}

Ques : 5 The next greater element of some element x in an array is the first greater
element that is to the right of x in the same array. You are given two distinct 0-indexed
integer arrays nums1 and nums2, where nums1 is a subset of nums2. For each 0 <= i <
nums1.length, find the index j such that nums1[i] == nums2[j] and determine the next
greater element of nums2[j] in nums2. If there is no next greater element, then the
answer for this query is -1. Return an array ans of length nums1.length such that ans[i] is
the next greater element as described above.
Code : import java.util.*;
public class NextGreaterElement {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Map < Integer, Integer > map = new HashMap < > ();
Stack < Integer > stack = new Stack < > ();
for (int num: nums2) {
while (!stack.isEmpty() && stack.peek() < num) {
map.put(stack.pop(), num);
}

Devesh Kumar Singh 21BCS8725


stack.push(num);
}
int[] result = new int[nums1.length];
for (int i = 0; i < nums1.length; i++) {
result[i] = map.getOrDefault(nums1[i], -1);
}
return result;
}
public static void main(String[] args) {
NextGreaterElement solution = new NextGreaterElement();
int[] nums1 = {4, 1, 2 };
int[] nums2 = { 1, 3, 4, 2 };
int[] result = solution.nextGreaterElement(nums1, nums2);
System.out.println("Output: " + Arrays.toString(result));
}
}

Ques 6 : A string containing only parentheses is balanced if the following is true: 1. if it is


an empty string 2. if A and B are correct, AB is correct, 3. if A is correct, (A) and {A}
and [A] are also correct. Examples of some correctly balanced strings are: "{}()",
"[{()}]", "({()})" Examples of some unbalanced strings are: "{}(", "({)}", "[[", "}{" etc.
Given a string, determine if it is balanced or not….
Code : import java.util.*;
public class BalancedParentheses {
public static boolean isBalanced(String str) {
Stack < Character > stack = new Stack < > ();
for (char c: str.toCharArray()) {
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else {
if (stack.isEmpty()) {
return false;
}
char top = stack.pop();
if ((c == ')' && top != '(') || (c == ']' && top != '[') || (c == '}'
&& top != '{')) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {

Devesh Kumar Singh 21BCS8725


Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String str = scanner.nextLine();
System.out.println(isBalanced(str));
}
scanner.close();
}
}

Ques 7 : Comparators are used to compare two objects. In this challenge, you'll create a
comparator and use it to sort an array. The Player class has fields: a String and a integer.
Given an array of Player objects, write a comparator that sorts them in order of
decreasing score; if or more players have the same score, sort those players
alphabetically by name. To do this, you must create a Checker class that implements the
Comparator interface, then write an int compare(Player a, Player b) method
implementing the Comparator.compare(T o1, T o2) method.
Code : import java.util.*;
class Player {
String name;
int score;
Player(String name, int score) {
this.name = name;
this.score = score;
}
}
class Checker implements Comparator<Player> {
@Override
public int compare(Player a, Player b) {
if (a.score != b.score) {
return Integer.compare(b.score, a.score);
} else {
return a.name.compareTo(b.name);
}
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
Player[] players = new Player[n];
for (int i = 0; i < n; i++) {
String name = scanner.next();
int score = scanner.nextInt();

Devesh Kumar Singh 21BCS8725


players[i] = new Player(name, score);
}
Arrays.sort(players, new Checker());
for (Player player : players) {
System.out.println(player.name + " " + player.score);
}
scanner.close();
}
}

Ques 8 : Java's BigDecimal class can handle arbitrary-precision signed decimal numbers.
Let's test your knowledge of them! Given an array, , of real number strings, sort them in
descending order — but wait, there's more! Each number must be printed in the exact
same format as it was read from stdin, meaning that is printed as , and is printed as . If
two numbers represent numerically equivalent values (e.g., ), then they must be listed in
the same order as they were received as input). You must rearrange array 's elements
according to the instructions above…
Code : import java.util.*;
public class BigDecimalSort {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
String[] numbers = new String[n];
for (int i = 0; i < n; i++) {
numbers[i] = scanner.next();
}
Arrays.sort(numbers, (a, b) - > {
if (a.length() != b.length()) {
return b.length() - a.length();
} else {
return b.compareTo(a);
}
});
for (String number: numbers) {
System.out.println(number);
}
scanner.close();
}
}

Ques 9 : Given an input string (s) and a pattern (p), implement wildcard pattern matching
with support for '?' and '*' where: • '?' Matches any single character. • '*' Matches any
Devesh Kumar Singh 21BCS8725
sequence of characters (including the empty sequence). The matching should cover the
entire input string (not partial).
Code: public class WildcardMatching {
public boolean isMatch(String s, String p) {
int m = s.length();
int n = p.length();
boolean[][] dp = new boolean[m + 1][n + 1];
dp[0][0] = true;
for (int j = 1; j <= n; j++) {
if (p.charAt(j - 1) == '*') {
dp[0][j] = dp[0][j - 1];
} }
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (p.charAt(j - 1) == '?' || s.charAt(i - 1) == p.charAt(j - 1))
{ dp[i][j] = dp[i - 1][j - 1];
} else if (p.charAt(j - 1) == '*') { dp[i]
[j] = dp[i][j - 1] || dp[i - 1][j];
}
}
return dp[m][n];
}
public static void main(String[] args) {
WildcardMatching solution = new WildcardMatching();
String s1 = "aa";
String p1 = "a";
System.out.println("Output for Example 1: " + solution.isMatch(s1, p1));
}
r strings
for (int i = 0; i < n; i++)
{ numbers[i] = scanner.next();
}
Arrays.sort(numbers, (a, b) - > {
if (a.length() != b.length()) {
return b.length() - a.length();
} else {
return b.compareTo(a);
});
for (String number: numbers) {
System.out.println(number);
}
scanner.close();
} }

Devesh Kumar Singh 21BCS8725


Ques 10 : Given an array of integers nums sorted in non-decreasing order, find the
starting and ending position of a given target value. If target is not found in the array,
return [-1, -1]. You must write an algorithm with O(log n) runtime complexity...
Code: import java.util.*;
public class FindTargetRange {
public int[] searchRange(int[] nums, int target) {
int[] result = {-1, -1 };
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] >= target) {
right = mid - 1;
} else {
left = mid + 1;
}} if (left < nums.length && nums[left] == target)
{ result[0] = left;
}
left = 0;
right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] <= target) {
left = mid + 1;
} else {
right = mid - 1;
}
}if (right >= 0 && nums[right] == target)
{ result[1] = right;
}return result;
}
public static void main(String[] args) {
FindTargetRange solution = new FindTargetRange();
int[] nums1 = { 5, 7, 7, 8, 8, 10 };
int target1 = 8;
int[] result1 = solution.searchRange(nums1, target1);
System.out.println("Output for Example 1: " + Arrays.toString(result1));
}
}

Devesh Kumar Singh 21BCS8725

You might also like