[Go to site: main page, start]

0% found this document useful (0 votes)
12 views5 pages

Java Programming Assignment Solutions

Java Fast learner Worksheet

Uploaded by

ritikrk008
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)
12 views5 pages

Java Programming Assignment Solutions

Java Fast learner Worksheet

Uploaded by

ritikrk008
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

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Fast Learner
Assignment: 3.2

Student Name: Ritik Kumar UID:21BCS1054


Branch: BE - CSE Section/Group: 614 - B
Semester: 6th
Subject Name: Java Project Lab Subject Code: 21CSH-319

QUESTION 1. 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".

import [Link]; public


class FindAddedLetter {
public static char findAddedLetter(String s, String t) {int[]
count = new int[26];
for (char c : [Link]()) {
count[c - 'a']++;
}
for (char c : [Link]()) {
count[c - 'a']--;
}
for (int i = 0; i < 26; i++) {if
(count[i] < 0) {
return (char) ('a' + i);
}
}
return ' ';
}
public static void main(String[] args) { Scanner
scanner = new Scanner([Link]);
[Link]("Enter string s:");
String s = [Link]();
[Link]("Enter string t:");
String t = [Link]();
char addedLetter = findAddedLetter(s, t);
[Link]("Added letter: " + addedLetter);
[Link]();
}
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
QUESTION 2. 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.

import [Link];
import [Link];
public class BalancedParentheses {
public static boolean isBalanced(String str) {
Stack<Character> stack = new Stack<>();
for (char c : [Link]()) {
if (c == '(' || c == '{' || c == '[') {
[Link](c);
} else {
if ([Link]()) {
return false;
}
char top = [Link]();
if ((c == ')' && top != '(') || (c == '}' && top != '{') || (c == ']' && top != '[')) {
return false;
}
}
}
return [Link]();
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string containing only parentheses:");
String input = [Link]();
boolean balanced = isBalanced(input);
if (balanced) {
[Link]("The string is balanced.");
} else {
[Link]("The string is not balanced.");
}
[Link]();
}
}

QUESTION 3. 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 [Link](T o1, T o2) method.
import [Link].*;
class Player {
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
String name;
int score;
Player(String name, int score) {
[Link] = name;
[Link] = score;
}
}
class Checker implements Comparator<Player> {
public int compare(Player a, Player b) {
if ([Link] != [Link]) {
return [Link]([Link], [Link]);
} else {
return [Link]([Link]);
}
}
}
public class PlayerComparator {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the number of players:");
int n = [Link]();
[Link]();
List<Player> players = new ArrayList<>();
for (int i = 0; i < n; i++) {
[Link]("Enter player name and score separated by space:");
String[] input = [Link]().split(" ");
String name = input[0];
int score = [Link](input[1]);
[Link](new Player(name, score));
}
[Link](players, new Checker());
for (Player player : players) {
[Link]([Link] + " " + [Link]);
}
[Link]();
}
}
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
QUESTION 4. Given an input string (s) and a pattern (p), implement wildcard pattern matching with
support for '?' and '*' where: • '?' Matches any single character. • '*' Matches any sequence of characters
(including the empty sequence). The matching should cover the entire input string (not partial).

import [Link];
public class WildcardMatching {
public static boolean isMatch(String s, String p) {
int m = [Link]();
int n = [Link]();
boolean[][] dp = new boolean[m + 1][n + 1];
dp[0][0] = true;
for (int j = 1; j <= n; j++) {
if ([Link](j - 1) == '*') {
dp[0][j] = dp[0][j - 1];
}
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if ([Link](j - 1) == '?' || [Link](i - 1) == [Link](j - 1)) {
dp[i][j] = dp[i - 1][j - 1];
} else if ([Link](j - 1) == '*') {
dp[i][j] = dp[i][j - 1] || dp[i - 1][j];
}
}
}
return dp[m][n];
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the input string (s):");
String s = [Link]();
[Link]("Enter the pattern string (p):");
String p = [Link]();
boolean result = isMatch(s, p);
[Link]("Output: " + result);
[Link]();
}
}

QUESTION 5. Given an array of integers nums sorted in non-decreasing order, find the starting and
endingposition 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.

import [Link].*;
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
public class FindTargetRange {
public static int[] searchRange(int[] nums, int target) {
int[] result = {-1, -1};
int left = 0, right = [Link] - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] >= target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
if (left < [Link] && nums[left] == target) {
result[0] = left;
} else {
return result;
}
right = [Link] - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] <= target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
result[1] = right
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the elements of the array :");
String[] input = [Link]().split(" ");
int[] nums = new int[[Link]];
for (int i = 0; i < [Link]; i++) {
nums[i] = [Link](input[i]);
}
[Link]("Enter the target value:");
int target = [Link]();
int[] result = searchRange(nums, target);
[Link]("Output: [" + result[0] + ", " + result[1] + "]");
[Link]();
}
}

Common questions

Powered by AI

The dynamic programming structure is recursive, where each state `dp[i][j]` represents whether the first `i` characters of the string match the first `j` characters of the pattern. It considers two main cases: direct character matching or '?' and handling '*' as a decision to either ignore the character in the pattern or consider it as matching one character in the text. This recursive model gradually builds up from simple base cases, illustrating how complex scenarios can be solved incrementally through simpler ones .

The algorithm used is a modified binary search which efficiently finds the starting and ending positions of a target value in a sorted array. This method is efficient because it leverages the properties of binary search to achieve O(log n) complexity, meaning it significantly reduces the number of comparisons compared to a linear scan, especially beneficial for large datasets .

For a string of parentheses to be considered balanced, it must meet three conditions: it can be an empty string, any concatenation of two balanced strings remains balanced, and any balanced string can be enclosed in matching pairs of parentheses (round, curly, or square). The code uses a stack to verify these conditions by pushing opening brackets and ensuring every closing bracket matches the last pushed opening bracket .

The implementation uses two separate binary searches: the first search narrows down to find the starting index of the target by adjusting the `right` boundary, and once located, a second search runs from this start index, adjusting the `left` boundary to determine the ending index. Each search separately ensures accuracy by only altering the specific boundary being pursued, thus preserving binary search efficiency while ensuring completeness .

Upon finding the target, the algorithm doesn't return immediately but adjusts boundaries to locate the full range of the target occurrences. After the initial find, it refines the search to identify the leftmost and rightmost indexes by conducting additional targeted binary search runs, adjusting `left` and `right` boundaries respectively until the full range is captured .

The implementation distinguishes using dynamic programming. The '?' matches any single character by checking if the current characters in the strings `s` and `p` match or if '?' is encountered, then referencing the previous state `dp[i-1][j-1]`. For '*', which matches any sequence of characters, the algorithm checks previous states `dp[i][j-1]` or `dp[i-1][j]`, allowing '*' to either skip a character or absorb one, respectively .

The solution identifies the added letter by using an integer array to count occurrences of each character in the original string `s` and the modified string `t`. Characters in `s` increment the count, while characters in `t` decrement it. The index where the count becomes negative indicates the added letter, thus identifying it .

The algorithm first checks if the input string is empty, which is a trivial balanced case, returning true immediately. This early return prevents unnecessary computation for this simplest form of input, showcasing a base case handling strategy often used in recursive and iterative algorithms .

A Comparator defines a method for sorting objects beyond their natural ordering. In the Player comparison task, a custom Comparator is implemented in the `Checker` class to sort `Player` objects. It first sorts players by decreasing score using `Integer.compare()`, and if scores are equal, it sorts by name alphabetically with `String.compareTo()` .

The code handles '?' and '*' using conditional checks: '?' directly matches any single character through `dp[i-1][j-1]`. '*' uses `dp[i][j-1]` to match no character and `dp[i-1][j]` to match one or more characters, thus adapting to any number of occurrences of the preceding element in the text .

You might also like