diff --git a/.idea/workspace.xml b/.idea/workspace.xml new file mode 100644 index 0000000..696e6e6 --- /dev/null +++ b/.idea/workspace.xml @@ -0,0 +1,74 @@ + + + + + + + + + + + + + + + { + "associatedIndex": 1 +} + + + + { + "keyToString": { + "Application.Main.executor": "Run", + "ModuleVcsDetector.initialDetectionPerformed": "true", + "RunOnceActivity.ShowReadmeOnStart": "true", + "RunOnceActivity.git.unshallow": "true", + "git-widget-placeholder": "my-branch", + "ignore.virus.scanning.warn.message": "true", + "kotlin-language-version-configured": "true", + "last_opened_file_path": "C:/Users/Disha Toshniwal/OneDrive/Desktop/Java-Code", + "node.js.detected.package.eslint": "true", + "node.js.detected.package.tslint": "true", + "node.js.selected.package.eslint": "(autodetect)", + "node.js.selected.package.tslint": "(autodetect)", + "nodejs_package_manager_path": "npm", + "vue.rearranger.settings.migration": "true" + } +} + + + + + + + + + + 1759909425714 + + + + + + \ No newline at end of file diff --git a/2048.cpp b/2048.cpp new file mode 100644 index 0000000..533adca --- /dev/null +++ b/2048.cpp @@ -0,0 +1,156 @@ +#include +#include +#include +#include +#include // for getch() on Windows + +using namespace std; + +const int SIZE = 4; +int grid[SIZE][SIZE]; + +// Initialize grid +void initGrid() { + for (int i = 0; i < SIZE; i++) + for (int j = 0; j < SIZE; j++) + grid[i][j] = 0; +} + +// Add random tile (2 or 4) +void addRandomTile() { + int empty[SIZE * SIZE][2]; + int count = 0; + for (int i = 0; i < SIZE; i++) + for (int j = 0; j < SIZE; j++) + if (grid[i][j] == 0) { + empty[count][0] = i; + empty[count][1] = j; + count++; + } + if (count > 0) { + int r = rand() % count; + grid[empty[r][0]][empty[r][1]] = (rand() % 2 + 1) * 2; + } +} + +// Print grid +void printGrid() { + cout << "\n"; + for (int i = 0; i < SIZE; i++) { + for (int j = 0; j < SIZE; j++) { + if (grid[i][j] == 0) + cout << setw(5) << "."; + else + cout << setw(5) << grid[i][j]; + } + cout << "\n\n"; + } +} + +// Slide left +bool slideLeft() { + bool moved = false; + for (int i = 0; i < SIZE; i++) { + int temp[SIZE] = {0}; + int idx = 0; + for (int j = 0; j < SIZE; j++) { + if (grid[i][j] != 0) { + if (temp[idx] == 0) { + temp[idx] = grid[i][j]; + } else if (temp[idx] == grid[i][j]) { + temp[idx++] *= 2; + moved = true; + } else { + temp[++idx] = grid[i][j]; + } + if (j != idx) moved = true; + } + } + for (int j = 0; j < SIZE; j++) + grid[i][j] = temp[j]; + } + return moved; +} + +// Rotate grid 90° clockwise +void rotateGrid() { + int temp[SIZE][SIZE]; + for (int i = 0; i < SIZE; i++) + for (int j = 0; j < SIZE; j++) + temp[j][SIZE - 1 - i] = grid[i][j]; + for (int i = 0; i < SIZE; i++) + for (int j = 0; j < SIZE; j++) + grid[i][j] = temp[i][j]; +} + +// Move tiles based on arrow key +bool move(int key) { + bool moved = false; + switch(key) { + case 72: // up arrow + rotateGrid(); rotateGrid(); rotateGrid(); + moved = slideLeft(); + rotateGrid(); + break; + case 80: // down arrow + rotateGrid(); + moved = slideLeft(); + rotateGrid(); rotateGrid(); rotateGrid(); + break; + case 75: // left arrow + moved = slideLeft(); + break; + case 77: // right arrow + rotateGrid(); rotateGrid(); + moved = slideLeft(); + rotateGrid(); rotateGrid(); + break; + } + return moved; +} + +// Check if game is over +bool gameOver() { + for (int i = 0; i < SIZE; i++) + for (int j = 0; j < SIZE; j++) + if (grid[i][j] == 0) return false; + + for (int i = 0; i < SIZE; i++) + for (int j = 0; j < SIZE-1; j++) + if (grid[i][j] == grid[i][j+1]) return false; + + for (int j = 0; j < SIZE; j++) + for (int i = 0; i < SIZE-1; i++) + if (grid[i][j] == grid[i+1][j]) return false; + + return true; +} + +int main() { + srand(time(0)); + initGrid(); + addRandomTile(); + addRandomTile(); + printGrid(); + + while (true) { + cout << "Use arrow keys to move tiles.\n"; + int ch = _getch(); // first input + if (ch == 224) { // arrow keys are detected in 2 steps + int arrow = _getch(); // second input gives actual key code + if (move(arrow)) { + addRandomTile(); + printGrid(); + } else { + cout << "Invalid move or no tiles moved.\n"; + } + } + + if (gameOver()) { + cout << "Game Over!\n"; + break; + } + } + + return 0; +} diff --git a/Main.class b/Main.class new file mode 100644 index 0000000..98bc247 Binary files /dev/null and b/Main.class differ diff --git a/Main.java b/Main.java new file mode 100644 index 0000000..3fb27b9 --- /dev/null +++ b/Main.java @@ -0,0 +1,103 @@ +/** + +* @Filename- Main.java +* @Description- For taking user input and calling string functions +* @Author- Disha Toshniwal + */ + import java.util.*; + +public class Main { +public static void main(String[] args) { +Scanner scanner = new Scanner(System.in); +Mystring myStringFunctions = new Mystring(); + +System.out.println("Enter a string : "); +String mainString = scanner.nextLine(); +System.out.println("Choose an operation : "); +System.out.println("1. Append "); +System.out.println("2. Count Words "); +System.out.println("3. Replace "); +System.out.println("4. isPalindrome "); +System.out.println("5. Splice "); +System.out.println("6. Split "); +System.out.println("7. Max Repeat "); +System.out.println("8. Sort "); +System.out.println("9. Shift "); +System.out.println("10. Reverse "); +System.out.println("11. Exit "); + +System.out.print("Enter your choice (1 – 11) : "); +int userChoice = scanner.nextInt(); +scanner.nextLine(); // clear buffer + +switch (userChoice) { + case 1: + System.out.println("Enter a string to append : "); + String appendString = scanner.nextLine(); + myStringFunctions.append(mainString, appendString); + break; + + case 2: + System.out.println("Enter string to count total number of words : "); + String wordCountString = scanner.nextLine(); + myStringFunctions.countWords(wordCountString); + break; + + case 3: + System.out.println("Enter character you want to replace : "); + char oldCharacter = scanner.next().charAt(0); + System.out.println("Enter new character : "); + char newCharacter = scanner.next().charAt(0); + myStringFunctions.replace(mainString, oldCharacter, newCharacter); + break; + + case 4: + myStringFunctions.isPalindrome(mainString); + break; + + case 5: + System.out.println("Enter starting index : "); + int startIndex = scanner.nextInt(); + System.out.println("Enter length to remove : "); + int removeLength = scanner.nextInt(); + myStringFunctions.splice(mainString, startIndex, removeLength); + break; + + case 6: + scanner.nextLine(); // clear buffer + System.out.println("Enter pattern to split by : "); + String splitPattern = scanner.nextLine(); + myStringFunctions.split(mainString, splitPattern); + break; + + case 7: + myStringFunctions.maxrepeat(mainString); + break; + + case 8: + myStringFunctions.sort(mainString); + break; + + case 9: + System.out.println("Enter shift count : "); + int shiftCount = scanner.nextInt(); + myStringFunctions.shift(mainString, shiftCount); + break; + + case 10: + myStringFunctions.reverse(mainString); + break; + + case 11: + System.out.println("Exiting... "); + break; + + default: + System.out.println("Invalid choice! Please enter a number between 1 and 11. "); +} + +scanner.close(); +} + + +} diff --git a/MainOperation.java b/MainOperation.java new file mode 100644 index 0000000..2f68b35 --- /dev/null +++ b/MainOperation.java @@ -0,0 +1,88 @@ +/** + * @Filename - Main.java + * @Description - For taking user input and calling string functions + * @Author - Disha Toshniwal + */ +import java.util.*; +public class MainOperation{ +public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + MyOperation operation = new MyOperation(); + while (true) { + System.out.println("\n========= MENU =========\n1. Count Unique Palindromes\n2. Nth Fibonacci\n3. Snake to Camel Case\n4. Count Consonants\n5. Binary to Decimal\n6. Display Characters\n7. Character Frequency Compression\n8. Check Prime Number\n9. Number to Words\n10. Longest Substring Without Repeating Characters\n0. Exit"); + System.out.print("Enter your choice: "); + int choice = -1; + try { + choice = Integer.parseInt(scanner.nextLine()); + } catch (Exception e) { + System.out.println("Invalid input! Please enter a number between 0 and 10."); + continue; + } + + if (choice == 0) { + System.out.println("Exiting program. Goodbye!"); + break; + } + + switch (choice) { + case 1: + System.out.print("Enter a string: "); + System.out.println("Unique Palindromes Count: " + operation.countUniquePalindromes(scanner.nextLine())); + break; + case 2: + System.out.print("Enter n: "); + try { + System.out.println("Fibonacci Number: " + operation.nthFibonacci(Integer.parseInt(scanner.nextLine()))); + } catch (Exception e) { + System.out.println("Invalid input! Please enter an integer."); + } + break; + case 3: + System.out.print("Enter snake_case string: "); + System.out.println("CamelCase: " + operation.snakeToCamel(scanner.nextLine())); + break; + case 4: + System.out.print("Enter a string: "); + System.out.println("Consonant Count: " + operation.countConsonants(scanner.nextLine())); + break; + case 5: + System.out.print("Enter binary string: "); + System.out.println("Decimal Value: " + operation.binaryToDecimal(scanner.nextLine())); + break; + case 6: + System.out.print("Enter pattern (like a1b2): "); + operation.displayCharacters(scanner.nextLine()); + break; + case 7: + System.out.print("Enter a string: "); + System.out.println("Compressed String: " + operation.charFrequencyCompressed(scanner.nextLine())); + break; + case 8: + System.out.print("Enter number: "); + try { + int num = Integer.parseInt(scanner.nextLine()); + System.out.println(num + (operation.isPrime(num) ? " is Prime" : " is Not Prime")); + } catch (Exception e) { + System.out.println("Invalid input! Please enter a valid integer."); + } + break; + case 9: + System.out.print("Enter a number (0-9999): "); + try { + System.out.println("In Words: " + operation.numberToWords(Integer.parseInt(scanner.nextLine()))); + } catch (Exception e) { + System.out.println("Invalid input! Please enter a valid integer between 0 and 9999."); + } + break; + case 10: + System.out.print("Enter a string: "); + System.out.println("Longest Unique Substring Length: " + operation.longestSubstringWithoutRepeat(scanner.nextLine())); + break; + default: + System.out.println("Invalid choice! Please enter between 0–10."); + } + } + + scanner.close(); + } +} \ No newline at end of file diff --git a/MyOperation.java b/MyOperation.java new file mode 100644 index 0000000..3e4ada5 --- /dev/null +++ b/MyOperation.java @@ -0,0 +1,247 @@ +/** + * @Filename - Main.java + * @Description - Definition of functions + * @Author - Disha Toshniwal + */ +public class MyOperation { + + // 1. Count Unique Palindromes (Length >= 3) + public int countUniquePalindromes(String inputString) { + if (inputString == null || !inputString.matches("[a-zA-Z]+")) { + System.out.println("Invalid input! Please enter a valid alphabetic string."); + return 0; + } + + int palindromeCount = 0; + for (int startIndex = 0; startIndex < inputString.length(); startIndex++) { + for (int endIndex = startIndex + 1; endIndex < inputString.length(); endIndex++){ + if (isPalindrome(inputString, startIndex, endIndex)) { + palindromeCount++; + } + } + } + return palindromeCount; + } + + private boolean isPalindrome(String text, int startIndex, int endIndex) { + while (startIndex < endIndex) { + if (text.charAt(startIndex) != text.charAt(endIndex)) return false; + startIndex++; + endIndex--; + } + return true; + } + + // 2. Nth Fibonacci (Recursive) + public int nthFibonacci(int number) { + if (number < 0) { + System.out.println("Invalid input! Please enter a non-negative integer."); + return -1; + } + if (number <= 1) return number; + return nthFibonacci(number - 1) + nthFibonacci(number - 2); + } + + // 3. Snake to Camel Case + public String snakeToCamel(String snakeString) { + if (snakeString == null || !snakeString.matches("[a-z_]+")) { + System.out.println("Invalid input! Please enter a valid lowercase snake_case string."); + return ""; + } + + StringBuilder camelCaseResult = new StringBuilder(); + boolean convertNext = false; + + for (int index = 0; index < snakeString.length(); index++) { + char currentChar = snakeString.charAt(index); + if (currentChar == '_') { + convertNext = true; + } else { + if (convertNext && Character.isLowerCase(currentChar)) { + camelCaseResult.append(Character.toUpperCase(currentChar)); + } else { + camelCaseResult.append(currentChar); + } + convertNext = false; + } + } + return camelCaseResult.toString(); + } + + // 4. Count Consonants + public int countConsonants(String inputText) { + if (inputText == null || !inputText.matches("[a-zA-Z]+")) { + System.out.println("Invalid input! Please enter a valid alphabetic string."); + return 0; + } + + int consonantCount = 0; + for (int index = 0; index < inputText.length(); index++) { + char ch = Character.toLowerCase(inputText.charAt(index)); + if (ch >= 'a' && ch <= 'z' && "aeiou".indexOf(ch) == -1) { + consonantCount++; + } + } + return consonantCount; + } + + // 5. Binary to Decimal + public int binaryToDecimal(String binaryString) { + if (binaryString == null || !binaryString.matches("[01]+")) { + System.out.println("Invalid input! Please enter a valid binary string (only 0s and 1s)."); + return -1; + } + + int decimalValue = 0; + int base = 1; + for (int index = binaryString.length() - 1; index >= 0; index--) { + if (binaryString.charAt(index) == '1') { + decimalValue += base; + } + base *= 2; + } + return decimalValue; + } + + // 6. Display Characters (e.g., "a1b3" → "abbb") + public void displayCharacters(String inputString) { + if (inputString == null || !inputString.matches("([a-zA-Z][0-9]+)+")) { + System.out.println("Invalid input! Please enter a valid pattern like 'a1b2c3'."); + return; + } + + StringBuilder expandedString = new StringBuilder(); + int index = 0; + + while (index < inputString.length()) { + char currentChar = inputString.charAt(index); + + // Ensure currentChar is a letter + if (Character.isLetter(currentChar)) { + index++; + StringBuilder numStr = new StringBuilder(); + + // Collect all following digits (for multi-digit numbers) + while (index < inputString.length() && Character.isDigit(inputString.charAt(index))) { + numStr.append(inputString.charAt(index)); + index++; + } + + // Convert collected number string to integer + int repeatCount = Integer.parseInt(numStr.toString()); + + // Repeat the character + expandedString.append(String.valueOf(currentChar).repeat(repeatCount)); + } else { + index++; // skip any invalid character just in case + } + } + + System.out.println("Expanded String: " + expandedString); +} + + + // 7. Character Frequency Compression (e.g., "aaabb" → "a3b2") + public String charFrequencyCompressed(String inputString) { + if (inputString == null || !inputString.matches("[a-zA-Z]+")) { + System.out.println("Invalid input! Please enter a valid alphabetic string."); + return ""; + } + + StringBuilder compressedString = new StringBuilder(); + int index = 0; + + while (index < inputString.length()) { + char currentChar = inputString.charAt(index); + int count = 1; + int nextIndex = index + 1; + while (nextIndex < inputString.length() && inputString.charAt(nextIndex) == currentChar) { + count++; + nextIndex++; + } + compressedString.append(currentChar).append(count); + index = nextIndex; + } + + return compressedString.toString(); + } + + // 8. Check Prime Number + public boolean isPrime(int number) { + if (number <= 1) { + System.out.println("Invalid input! Please enter a number greater than 1."); + return false; + } + for (int divisor = 2; divisor * divisor <= number; divisor++) { + if (number % divisor == 0) return false; + } + return true; + } + + // 9. Number to Words (0–9999) + public String numberToWords(int number) { + if (number < 0 || number > 9999) { + System.out.println("Invalid input! Please enter a number between 0 and 9999."); + return ""; + } + + if (number == 0) return "zero"; + + String[] ones = { + "", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", + "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", + "sixteen", "seventeen", "eighteen", "nineteen" + }; + String[] tens = { + "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" + }; + + StringBuilder words = new StringBuilder(); + + if (number / 1000 > 0) { + words.append(ones[number / 1000]).append(" thousand "); + number %= 1000; + } + if (number / 100 > 0) { + words.append(ones[number / 100]).append(" hundred "); + number %= 100; + } + if (number > 0) { + if (number < 20) { + words.append(ones[number]); + } else { + words.append(tens[number / 10]); + if (number % 10 > 0) { + words.append(" ").append(ones[number % 10]); + } + } + } + return words.toString().trim(); + } + + // 10. Longest Substring Without Repeating Characters + public int longestSubstringWithoutRepeat(String inputString) { + if (inputString == null || !inputString.matches("[a-zA-Z]+")) { + System.out.println("Invalid input! Please enter a valid alphabetic string."); + return 0; + } + + int maxLength = 0; + for (int start = 0; start < inputString.length(); start++) { + boolean[] seenCharacters = new boolean[256]; + int currentLength = 0; + + for (int end = start; end < inputString.length(); end++) { + char currentChar = inputString.charAt(end); + if (seenCharacters[currentChar]) break; + seenCharacters[currentChar] = true; + currentLength++; + } + + if (currentLength > maxLength) { + maxLength = currentLength; + } + } + return maxLength; + } +} diff --git a/Mystring.class b/Mystring.class index 6cef430..944a2b0 100644 Binary files a/Mystring.class and b/Mystring.class differ diff --git a/Mystring.java b/Mystring.java index 4b25c1d..618fb0e 100644 --- a/Mystring.java +++ b/Mystring.java @@ -1,208 +1,139 @@ +/** + +* @Filename-Mystring.java +* @Description-Definition of all string functions +* @Author-Disha Toshniwal + */ import java.util.*; -class Mystring{ - public static void append(String str1,String str2){ - System.out.println("After append :\n "+str1+str2); - } - public static void countWords(String str2){ - int cnt=0; - for(char c:str2.toCharArray()){ - if(c==' '){ - cnt++; - } + +public class Mystring { + +//ADD TWO STRING +public void append(String firstString, String secondString) { + System.out.println("After append :\n " + firstString + secondString); +} +// Count Total Number Of Words +public void countWords(String inputString) { + int wordCount = 0; + for (int i=0;i splitParts = new ArrayList<>(); + String currentSegment = ""; + + for (int index = 0; index < inputString.length();) { + if (index + delimiter.length() <= inputString.length() && + inputString.substring(index, index + delimiter.length()).equals(delimiter)) { + splitParts.add(currentSegment); + currentSegment = ""; + index += delimiter.length(); } else { - words[index++] = word; - word = ""; + currentSegment += inputString.charAt(index); + index++; } } - words[index] = word; // last word - System.out.println(Arrays.toString(words)); -} - public static void maxrepeat(String str) { - int[] freq = new int[256]; // for ASCII characters + if (!currentSegment.isEmpty()) { + splitParts.add(currentSegment); + } - // count frequency of each character - for (int i = 0; i < str.length(); i++) { - char c = str.charAt(i); - freq[c]++; + System.out.println("Result after splitting:"); + for (String segment : splitParts) { + System.out.print(segment + "\t"); + } +} +// print the maximum repeating character in a string +public void maxrepeat(String inputString) { + int[] frequency = new int[256]; + for (int index = 0; index < inputString.length(); index++) { + char currentChar = inputString.charAt(index); + frequency[currentChar]++; } - int max = -1; - char result = ' '; + int maxFrequency = -1; + char mostFrequentChar = ' '; - // find the character with maximum frequency - for (int i = 0; i < str.length(); i++) { - if (max < freq[str.charAt(i)]) { - max = freq[str.charAt(i)]; - result = str.charAt(i); + for (int index = 0; index < inputString.length(); index++) { + char currentChar = inputString.charAt(index); + if (maxFrequency < frequency[currentChar]) { + maxFrequency = frequency[currentChar]; + mostFrequentChar = currentChar; } } - System.out.println("Character with maximum frequency: " + result); - System.out.println("Frequency: " + max); + System.out.println("Character with maximum frequency: " + mostFrequentChar); + System.out.println("Frequency: " + maxFrequency); } -public static void Sort(String str){ - - char[] arr = str.toCharArray(); // convert string to char array - - // Bubble Sort on characters - for (int i = 0; i < arr.length - 1; i++) { - for (int j = 0; j < arr.length - i - 1; j++) { - if (arr[j] > arr[j + 1]) { - char temp = arr[j]; - arr[j] = arr[j + 1]; - arr[j + 1] = temp; +// sort the input string +public void sort(String inputString) { + char[] charArray = inputString.toCharArray(); + for (int i = 0; i < charArray.length - 1; i++) { + for (int j = 0; j < charArray.length - i - 1; j++) { + if (charArray[j] > charArray[j + 1]) { + char tempChar = charArray[j]; + charArray[j] = charArray[j + 1]; + charArray[j + 1] = tempChar; } } } - - String sortedStr = new String(arr); - System.out.println("Sorted string: " + sortedStr); + String sortedString = new String(charArray); + System.out.println("Sorted string: " + sortedString); } -public static void Shift(String str,int n){ - n = n % str.length(); // handle if n > length - - // move first n chars to end - String shifted = str.substring(str.length() - n) + str.substring(0, str.length() - n); - - System.out.println("Shifted string: " + shifted); +// rotate the string +public void shift(String inputString, int shiftCount) { + shiftCount = shiftCount % inputString.length(); + String shiftedString = inputString.substring(inputString.length() - shiftCount) + + inputString.substring(0, inputString.length() - shiftCount); + System.out.println("Shifted string: " + shiftedString); } -public static void Reverse(String str){ - String word=""; - for(int i=str.length()-1;i>=0;i--){ - word+=str.charAt(i); +//reverse the string +public void reverse(String inputString) { + String reversedString = ""; + for (int index = inputString.length() - 1; index >= 0; index--) { + reversedString += inputString.charAt(index); } - System.out.println("Reversed String is :"+word); + System.out.println("Reversed String is: " + reversedString); } - public static void main(String[] args){ - Scanner sc=new Scanner(System.in); - System.out.println("Enter a string :"); - String str=sc.nextLine(); - System.out.println("Choose a operation :"); - System.out.println("1. Append "); - System.out.println("2. Count Words "); - System.out.println("3. Replace "); - System.out.println("4. isPalindrome "); - System.out.println("5. Splice "); - System.out.println("6. Split "); - System.out.println("7. maxrepeat "); - System.out.println("8. Sort "); - System.out.println("9. Shift "); - System.out.println("10. Reverse "); - System.out.println("11. Exit "); - System.out.println("Enter the operation you want to choose from 1 to 11:"); - int choice=sc.nextInt(); - sc.nextLine(); - switch(choice){ - case 1: - System.out.println("Enter a string to append:"); - String str1=sc.nextLine(); - append(str,str1); - break; - - case 2: - System.out.println("Enter String to count total number of words:"); - String str2=sc.nextLine(); - countWords(str2); - break; - - case 3: - System.out.println("Enter character you want to replace:"); - char a = sc.next().charAt(0); - System.out.println("Enter new character:"); - char b = sc.next().charAt(0); - replace(str,a,b); - break; - - case 4: - isPalindrome(str); - break; - - case 5: - splice(str,0,2); - break; - - case 6: - System.out.println("Enter string you want to split "); - String s=sc.nextLine(); - split(s); - break; - - case 7: - maxrepeat(str); - break; - - case 8: - Sort(str); - break; - - case 9: - System.out.println("Enter shift count:"); - int n = sc.nextInt(); - Shift(str,n); - break; - - case 10: - Reverse(str); - break; - - case 11: - break; - - } - } -}; \ No newline at end of file +}