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

java_assignmnet

The document contains multiple Java programs that demonstrate various algorithms and functionalities, including string compression, matrix norm calculation, Twitter handle formatting, spiral order printing, zero shifting in arrays, finding non-repeating characters, a Hangman game simulation, experience calculation, and anagram checking. Each program includes a main method for execution and showcases different programming concepts. The examples are designed for experiential learning and problem-solving in Java.

Uploaded by

bca15016.20
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

java_assignmnet

The document contains multiple Java programs that demonstrate various algorithms and functionalities, including string compression, matrix norm calculation, Twitter handle formatting, spiral order printing, zero shifting in arrays, finding non-repeating characters, a Hangman game simulation, experience calculation, and anagram checking. Each program includes a main method for execution and showcases different programming concepts. The examples are designed for experiential learning and problem-solving in Java.

Uploaded by

bca15016.20
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

NAME – ISHA GUPTA

SRN – PES1PG23CA059

1. Implement a method to perform basic string compression using the counts of repeated characters. For
example, the string “aabcccccaaa” would become a2b1c5a3.

public class StringCompression {

public static String compressString(String str) {


if (str == null || str.length() == 0) {
return str;
}

StringBuilder compressed = new StringBuilder();


int count = 1;

for (int i = 1; i < str.length(); i++) {


if (str.charAt(i) == str.charAt(i - 1)) {
count++;
} else {
compressed.append(str.charAt(i - 1)).append(count);
count = 1;
}
}

compressed.append(str.charAt(str.length() - 1)).append(count);

return compressed.length() < str.length() ? compressed.toString() : str;


}

public static void main(String[] args) {


String input = "aabcccccaaa";
String compressedString = compressString(input);
System.out.println("Compressed String: " + compressedString);
}
}

2. Find the NORM of a matrix (Square-root of sum of squares of all elements of a matrix)

public class MatrixNorm {

public static double calculateNorm(int[][] matrix) {


double sumOfSquares = 0;

for (int i = 0; i < matrix.length; i++) {


for (int j = 0; j < matrix[i].length; j++) {
sumOfSquares += Math.pow(matrix[i][j], 2);
}
}

return Math.sqrt(sumOfSquares);
}

public static void main(String[] args) {


int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

double norm = calculateNorm(matrix);


System.out.println("Norm of the matrix: " + norm);
}
}

3. Accept first and last name of the user and convert it to twitter handle format.
import java.util.Scanner;

public class TwitterHandle {

public static String convertToTwitterHandle(String firstName, String lastName) {


return "@" + firstName.toLowerCase() + "_" + lastName.toLowerCase();
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter your first name: ");


String firstName = scanner.nextLine();

System.out.print("Enter your last name: ");


String lastName = scanner.nextLine();

String twitterHandle = convertToTwitterHandle(firstName, lastName);

System.out.println("Your Twitter handle is: " + twitterHandle);

scanner.close();
}
}

Experiential learning – Orange problems


1. Program to display elements in spiral order (int/String).

Output: 33, 75, 18, 16, 42, 12


public class SpiralOrder {

public static void printSpiralOrder(int[][] matrix) {


if (matrix == null || matrix.length == 0) return;

int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;

while (top <= bottom && left <= right) {


for (int i = left; i <= right; i++) {
System.out.print(matrix[top][i] + " ");
}
top++;

for (int i = top; i <= bottom; i++) {


System.out.print(matrix[i][right] + " ");
}
right--;

if (top <= bottom) {


for (int i = right; i >= left; i--) {
System.out.print(matrix[bottom][i] + " ");
}
bottom--;
}

if (left <= right) {


for (int i = bottom; i >= top; i--) {
System.out.print(matrix[i][left] + " ");
}
left++;
}
}
}

public static void main(String[] args) {


int[][] matrix = {
{33, 75},
{18, 16},
{42, 12}
};

System.out.println("Spiral order of the matrix:");


printSpiralOrder(matrix);
}

2. Shift all zeros to the end of the array (+ve, -ve, 0’s)

import java.util.Arrays;

public class ShiftZerosToEnd {


public static void main(String[] args) {
int[] arr = {0, 3, -2, 0, 9, 0, -4, 8};

shiftZerosToEnd(arr);

System.out.println(Arrays.toString(arr));
}

public static void shiftZerosToEnd(int[] arr) {


int nonZeroIndex = 0;

for (int i = 0; i < arr.length; i++) {


if (arr[i] != 0) {
arr[nonZeroIndex] = arr[i];
nonZeroIndex++;
}
}

while (nonZeroIndex < arr.length) {


arr[nonZeroIndex] = 0;
nonZeroIndex++;
}
}
}

3. Given a string, find the first character that does not repeat anywhere in the string.

import java.util.LinkedHashMap;
import java.util.Map;

public class FirstNonRepeating {


public static char findFirstNonRepeating(String str) {
Map<Character, Integer> countMap = new LinkedHashMap<>();
for (char ch : str.toCharArray()) {
countMap.put(ch, countMap.getOrDefault(ch, 0) + 1);
}
for (Map.Entry<Character, Integer> entry : countMap.entrySet()) {
if (entry.getValue() == 1) {
return entry.getKey();
}
}
return '\0';
}

public static void main(String[] args) {


String input = "twisting";
char result = findFirstNonRepeating(input);
System.out.println("First Non-Repeating Character: " + result);
}

Experiential learning – Jackfruit problems

1. Accept a word through command line to simulate the game HANGMAN(10 chances)

import java.util.Scanner;

public class HangmanGame {


public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java HangmanGame <word>");
return;
}

String word = args[0].toLowerCase();


StringBuilder hiddenWord = new StringBuilder("_".repeat(word.length()));
int chances = 10;
boolean[] guessed = new boolean[word.length()];

Scanner scanner = new Scanner(System.in);

System.out.println("Welcome to Hangman! You have " + chances + " chances.");


while (chances > 0) {
System.out.println("Word: " + hiddenWord);
System.out.print("Enter a letter: ");
char guess = scanner.next().toLowerCase().charAt(0);

boolean correctGuess = false;


for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == guess && !guessed[i]) {
hiddenWord.setCharAt(i, guess);
guessed[i] = true;
correctGuess = true;
}
}

if (!correctGuess) {
chances--;
System.out.println("Incorrect guess! Remaining chances: " + chances);
} else {
System.out.println("Good guess!");
}

if (hiddenWord.toString().equals(word)) {
System.out.println("Congratulations! You guessed the word: " + word);
return;
}
}

System.out.println("Game over! The word was: " + word);


}
}

2. Accept date of joining a job and calculate total years if exp.

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;

public class ExperienceCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the date of joining (yyyy-MM-dd): ");


String joiningDateInput = scanner.nextLine();

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");


LocalDate joiningDate = LocalDate.parse(joiningDateInput, formatter);
LocalDate currentDate = LocalDate.now();

Period experience = Period.between(joiningDate, currentDate);

System.out.println("Total years of experience: " + experience.getYears());


}
}
3. Write a function that takes two strings and returns true if they are anagrams of each other (i.e., if
they contain the same characters in a different order).

import java.util.Arrays;

public class AnagramChecker {


public static void main(String[] args) {
String str1 = "triangle";
String str2 = "integral";

boolean result = areAnagrams(str1, str2);


System.out.println("Are the two strings anagrams? " + result);
}

public static boolean areAnagrams(String str1, String str2) {


if (str1.length() != str2.length()) {
return false;
}

char[] charArray1 = str1.toCharArray();


char[] charArray2 = str2.toCharArray();

Arrays.sort(charArray1);
Arrays.sort(charArray2);

return Arrays.equals(charArray1, charArray2);


}
}

You might also like