[go: up one dir, main page]

0% found this document useful (0 votes)
18 views9 pages

TBU Questions

Uploaded by

4113 PAVITHRA K
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)
18 views9 pages

TBU Questions

Uploaded by

4113 PAVITHRA K
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/ 9

1.

Rearrange Alphabets in Ascending Order

Question: Write a program to rearrange the alphabets in a given string.

Solution:

import java.util.Arrays;

public class RearrangeAlphabets {


public static void main(String[] args) {
String input = "ACCOMODATION";
char[] charArray = input.toCharArray();
Arrays.sort(charArray);
String output = new String(charArray);
System.out.println(output); // Output: AACCDIMOOTN
}
}

2. Find Occurrence of Each Character

Question: Write a program to count the occurrences of each character in a given string.

Solution:

import java.util.HashMap;

public class CharacterOccurrence {


public static void main(String[] args) {
String input = "ACCOMODATION";
HashMap<Character, Integer> charCount = new HashMap<>();
for (char c : input.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1);
}
System.out.println(charCount); // Output: {A=2, C=2, O=2, M=1, D=1,
T=1, I=1, N=1}
}
}

3. Rotate Alphabets by 13 Places (ROT13)

Question: Write a program to encode a string by rotating its characters by 13 places.

Solution:

public class ROT13Encoder {


public static void main(String[] args) {
String input = "HeLlO";
StringBuilder output = new StringBuilder();

for (char c : input.toUpperCase().toCharArray()) {


if (c >= 'A' && c <= 'Z') {
c = (char) (((c - 'A' + 13) % 26) + 'A');
}
output.append(c);
}

System.out.println(output); // Output: URYYB


}
}

4. Encoding Based on First Occurrence Count

Question: Encode a string based on the occurrence of its characters in the order of their first appearance.

Solution:

import java.util.LinkedHashMap;

public class EncodeFirstOccurrence {


public static void main(String[] args) {
String input = "HELLOWORLD";
LinkedHashMap<Character, Integer> countMap = new LinkedHashMap<>();
StringBuilder result = new StringBuilder();

for (char c : input.toCharArray()) {


countMap.put(c, countMap.getOrDefault(c, 0) + 1);
result.append(countMap.get(c));
}

System.out.println(result); // Output: 1132111


}
}

5. Word Count

Question: Write a program to find the word with the maximum count in a given sentence.

Solution:

import java.util.HashMap;

public class MaxWordCount {


public static void main(String[] args) {
String input = "Run and run, they said, but to run and run is
tiring";
String[] words = input.toLowerCase().replaceAll("[^a-z ]",
"").split("\\s+");

HashMap<String, Integer> wordCount = new HashMap<>();


for (String word : words) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}

String maxWord = "";


int maxCount = 0;
for (String word : wordCount.keySet()) {
if (wordCount.get(word) > maxCount) {
maxWord = word;
maxCount = wordCount.get(word);
}
}

System.out.println(maxWord); // Output: run


}
}

6. Left Diagonal Sum in a Matrix

Question: Calculate the sum of non-repeated left diagonal elements in a square matrix.

Solution:

import java.util.HashSet;
import java.util.Scanner;

public class LeftDiagonalSum {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
int[][] matrix = new int[m][n];

// Fill matrix
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (sc.hasNextInt()) {
matrix[i][j] = sc.nextInt();
} else {
matrix[i][j] = 1; // Fill missing elements with 1
}
}
}

// Ensure square matrix


int size = Math.max(m, n);
int[][] squareMatrix = new int[size][size];
for (int i = 0; i < m; i++) {
System.arraycopy(matrix[i], 0, squareMatrix[i], 0, n);
}

HashSet<Integer> allElements = new HashSet<>();


HashSet<Integer> repeatedElements = new HashSet<>();
int sum = 0;

for (int i = 0; i < size; i++) {


int element = squareMatrix[i][i];
if (!allElements.add(element)) {
repeatedElements.add(element);
}
}

for (int i = 0; i < size; i++) {


int element = squareMatrix[i][i];
if (!repeatedElements.contains(element)) {
sum += element;
}
}

System.out.println(sum); // Output: 15 (for sample input)


}
}

7. Highest Occurring First Character

Question: Find the highest occurring first character of words in a given sentence.

Solution:

import java.util.HashMap;

public class HighestFirstChar {


public static void main(String[] args) {
String input = "grass is greener on the other side";
String[] words = input.split("\\s+");
HashMap<Character, Integer> charCount = new HashMap<>();

for (String word : words) {


char firstChar = word.toLowerCase().charAt(0);
charCount.put(firstChar, charCount.getOrDefault(firstChar, 0) +
1);
}

char maxChar = '\0';


int maxCount = 0;

for (char c : charCount.keySet()) {


if (charCount.get(c) > maxCount || (charCount.get(c) ==
maxCount && maxChar == '\0')) {
maxChar = c;
maxCount = charCount.get(c);
}
}

System.out.println(maxChar); // Output: g
}}
1. Find the Sum, Average, Mean, and Median of an Array

import java.util.Arrays;

public class ArrayStats {


public static void main(String[] args) {
int[] arr = {3, 5, 2, 8, 7};

// Sum
int sum = Arrays.stream(arr).sum();
System.out.println("Sum: " + sum);

// Average
double avg = sum / (double) arr.length;
System.out.println("Average: " + avg);

// Mean
System.out.println("Mean: " + avg);

// Median
Arrays.sort(arr);
double median;
int n = arr.length;
if (n % 2 == 0) {
median = (arr[n / 2 - 1] + arr[n / 2]) / 2.0;
} else {
median = arr[n / 2];
}
System.out.println("Median: " + median);
}
}

2. Find the Mean and Median of an Array by Sorting

public class MeanMedian {


public static void main(String[] args) {
int[] arr = {3, 5, 1, 9, 4};
Arrays.sort(arr);

// Mean
double mean = Arrays.stream(arr).average().orElse(0);
System.out.println("Mean: " + mean);

// Median
int n = arr.length;
double median = (n % 2 == 0) ? (arr[n / 2 - 1] + arr[n / 2]) / 2.0 :
arr[n / 2];
System.out.println("Median: " + median);
}
}
3. Find the Sum of Two Complex Numbers

public class ComplexNumbers {


public static void main(String[] args) {
int a = 3, b = 4; // First complex number: 3 + 4i
int x = 5, y = 6; // Second complex number: 5 + 6i

int realSum = a + x;
int imaginarySum = b + y;

System.out.println("Sum of Complex Numbers: " + realSum + " + " +


imaginarySum + "i");
}
}

4. Matrix Addition, Subtraction, and Multiplication

public class MatrixOperations {


public static void main(String[] args) {
int[][] mat1 = {{1, 2}, {3, 4}};
int[][] mat2 = {{5, 6}, {7, 8}};

// Matrix Addition
int[][] sum = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
sum[i][j] = mat1[i][j] + mat2[i][j];
}
}
System.out.println("Matrix Sum: " + Arrays.deepToString(sum));

// Matrix Subtraction
int[][] diff = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
diff[i][j] = mat1[i][j] - mat2[i][j];
}
}
System.out.println("Matrix Difference: " +
Arrays.deepToString(diff));

// Matrix Multiplication
int[][] prod = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
prod[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
System.out.println("Matrix Product: " + Arrays.deepToString(prod));
}
}
5. Longest Substring with No Repetition in String

import java.util.*;

public class LongestUniqueSubstring {


public static int longestSubstringWithoutRepetition(String s) {
Set<Character> set = new HashSet<>();
int left = 0, maxLength = 0;

for (int right = 0; right < s.length(); right++) {


while (set.contains(s.charAt(right))) {
set.remove(s.charAt(left++));
}
set.add(s.charAt(right));
maxLength = Math.max(maxLength, right - left + 1);
}
return maxLength;
}

public static void main(String[] args) {


System.out.println(longestSubstringWithoutRepetition("abcabcbb"));
// Output: 3
}
}

6. Count of Special Characters

public class SpecialCharacterCount {


public static int countSpecialCharacters(String str) {
int count = 0;
for (char ch : str.toCharArray()) {
if (!Character.isLetterOrDigit(ch)) {
count++;
}
}
return count;
}

public static void main(String[] args) {


System.out.println(countSpecialCharacters("Hello@123!")); // Output:
2
}
}
7. Number of Words in a Sentence

public class WordCount {


public static int countWords(String sentence) {
return sentence.trim().split("\\s+").length;
}

public static void main(String[] args) {


System.out.println(countWords("Hello World! I love coding.")); //
Output: 5
}}

8. Count of Consonants in a Sentence

public class ConsonantCount {


public static int countConsonants(String str) {
int count = 0;
for (char ch : str.toLowerCase().toCharArray()) {
if (ch >= 'a' && ch <= 'z' && !"aeiou".contains(ch + "")) {
count++;
}
}
return count;
}

public static void main(String[] args) {


System.out.println(countConsonants("Hello World")); // Output: 7
}
}

9. Count of Vowels in a Sentence

public class VowelCount {


public static int countVowels(String str) {
int count = 0;
for (char ch : str.toLowerCase().toCharArray()) {
if ("aeiou".contains(ch + "")) {
count++;
}
}
return count;
}

public static void main(String[] args) {


System.out.println(countVowels("Hello World")); // Output: 3
}
}
10. Merge Two Arrays and Calculate Mean and Median

import java.util.*;

public class MergeAndCalculate {


public static void main(String[] args) {
int[] arr1 = {1, 3, 5};
int[] arr2 = {2, 4, 6};

// Merge Arrays
int[] merged = new int[arr1.length + arr2.length];
System.arraycopy(arr1, 0, merged, 0, arr1.length);
System.arraycopy(arr2, 0, merged, arr1.length, arr2.length);

Arrays.sort(merged);

// Mean
double mean = Arrays.stream(merged).average().orElse(0);
System.out.println("Mean: " + Math.round(mean));

// Median
double median = (merged.length % 2 == 0) ?
(merged[merged.length / 2 - 1] +
merged[merged.length / 2]) / 2.0 :
merged[merged.length / 2];
System.out.println("Median: " + Math.round(median));
}
}

11. Find If a Number has Exactly Three Factors

public class ThreeFactors {


public static boolean hasThreeFactors(int num) {
if (num < 2) return false;
int root = (int) Math.sqrt(num);
if (root * root != num) return false;

for (int i = 2; i <= Math.sqrt(root); i++) {


if (root % i == 0) return false;
}
return true; // Perfect square of a prime
}

public static void main(String[] args) {


System.out.println(hasThreeFactors(9)); // Output: true (3 factors:
1, 3, 9)
System.out.println(hasThreeFactors(10)); // Output: false
}
}

You might also like