Skip to content

Instantly share code, notes, and snippets.

@AnAverageBeing
Last active October 29, 2023 06:05
Show Gist options
  • Save AnAverageBeing/1f60b129a19f845e85e5ff3de047c9a7 to your computer and use it in GitHub Desktop.
Save AnAverageBeing/1f60b129a19f845e85e5ff3de047c9a7 to your computer and use it in GitHub Desktop.
Project

1. Rearrange

Define a class in java to modify a word by bringing all the vowels in the word at the beginning followed by the consonants.

Answer :=

public class Rearrange {
    private String word;

    public Rearrange(String word) {
        this.word = word;
    }

    public String rearrangeWord() {
        String vowels = "";
        String consonants = "";

        for (char ch : word.toCharArray()) {
            if ("AEIOUaeiou".contains(String.valueOf(ch))) {
                vowels += ch;
            } else {
                consonants += ch;
            }
        }

        return vowels + consonants;
    }

    public static void main(String[] args) {
        String inputWord = "example";
        Rearrange rearranger = new Rearrange(inputWord);
        String rearrangedWord = rearranger.rearrangeWord();

        System.out.println("Original word: " + inputWord);
        System.out.println("Rearranged word: " + rearrangedWord);
    }
}

Output :=

output


2. Transpose Matrix

Write a Java program to find the transpose of a given square matrix (N x N). The transpose of a matrix is obtained by swapping its rows with columns.

Answer :=

public class TransposeMatrix {
    // Method to find the transpose of the matrix
    public static int[][] transpose(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        int[][] result = new int[cols][rows];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                result[j][i] = matrix[i][j];
            }
        }

        return result;
    }

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

        int[][] transposedMatrix = transpose(inputMatrix);

        System.out.println("Original Matrix:");
        printMatrix(inputMatrix);

        System.out.println("Transposed Matrix:");
        printMatrix(transposedMatrix);
    }

    public static void printMatrix(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output :=

output


3. Matrix Multiplication

Write a Java program to perform matrix multiplication for two given matrices (A and B) and display the result matrix (C). Matrix multiplication is a binary operation that takes two matrices as inputs and produces another matrix as output. It involves multiplying the elements of rows of the first matrix with the corresponding elements of columns of the second matrix.

Answer :=

public class MatrixMultiplication {
    // Method to perform matrix multiplication
    public static int[][] multiplyMatrices(int[][] matrixA, int[][] matrixB) {
        int rowsA = matrixA.length;
        int colsA = matrixA[0].length;
        int colsB = matrixB[0].length;
        int[][] result = new int[rowsA][colsB];

        for (int i = 0; i < rowsA; i++) {
            for (int j = 0; j < colsB; j++) {
                int sum = 0;
                for (int k = 0; k < colsA; k++) {
                    sum += matrixA[i][k] * matrixB[k][j];
                }
                result[i][j] = sum;
            }
        }

        return result;
    }

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

        int[][] matrixB = {
            {5, 6},
            {7, 8}
        };

        int[][] resultMatrix = multiplyMatrices(matrixA, matrixB);

        System.out.println("Matrix A:");
        printMatrix(matrixA);

        System.out.println("Matrix B:");
        printMatrix(matrixB);

        System.out.println("Result Matrix:");
        printMatrix(resultMatrix);
    }

    public static void printMatrix(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output :=

output


4. Matrix Element Reversal

Write a Java program to reverse the digits of all elements in a matrix.

Answer :=

```public class MatrixReverse {
    public static void main(String[] args) {
        int[][] originalArray = {
            {123, 456, 789},
            {987, 654, 321},
            {111, 222, 333}
        };

        System.out.println("Original Array:");
        printArray(originalArray);

        int[][] reversedArray = reverseMatrixElements(originalArray);

        System.out.println("\nReversed Array:");
        printArray(reversedArray);
    }

    public static int[][] reverseMatrixElements(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        int[][] reversedMatrix = new int[rows][cols];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                reversedMatrix[i][j] = reverseNumber(matrix[i][j]);
            }
        }

        return reversedMatrix;
    }

    public static int reverseNumber(int num) {
        int reversed = 0;

        while (num != 0) {
            int digit = num % 10;
            reversed = reversed * 10 + digit;
            num /= 10;
        }

        return reversed;
    }

    public static void printArray(int[][] matrix) {
        for (int[] row : matrix) {
            for (int element : row) {
                System.out.print(element + " ");
            }
            System.out.println();
        }
    }
}

Output :=

output


5. Palindrome Check

Write a Java program to check if a given string is a palindrome or not using recursion. A palindrome is a word, phrase, number, or other sequences of characters that reads the same forward and backward (ignoring spaces, punctuation, and capitalization).

Answer :=

public class PalindromeCheck {
    // Method to check if the given string is a palindrome
    public static boolean isPalindrome(String str) {
        // Convert the string to lowercase and remove spaces
        str = str.toLowerCase().replaceAll("[^a-zA-Z0-9]", "");
        
        // Base case: if the string is empty or has only one character
        if (str.length() <= 1) {
            return true;
        }
        
        // Compare the first and last characters
        if (str.charAt(0) != str.charAt(str.length() - 1)) {
            return false;
        }
        
        // Recursively check the substring without the first and last characters
        return isPalindrome(str.substring(1, str.length() - 1));
    }

    public static void main(String[] args) {
        // Sample input and output
        String input = "A man, a plan, a canal, Panama";
        boolean result = isPalindrome(input);
        
        if (result) {
            System.out.println("The string is a palindrome.");
        } else {
            System.out.println("The string is not a palindrome.");
        }
    }
}

Output :=

output


6. String Anagrams

Write a Java program to check if two given strings are anagrams or not. Anagrams are two words or phrases that have the same characters but may be in a different order.

Answer :=

import java.util.Arrays;

public class StringAnagrams {
    // Method to check if two strings are anagrams
    public static boolean areAnagrams(String str1, String str2) {
        // Remove spaces and convert to lowercase
        str1 = str1.replaceAll("\\s", "").toLowerCase();
        str2 = str2.replaceAll("\\s", "").toLowerCase();

        // If lengths are different, they can't be anagrams
        if (str1.length() != str2.length()) {
            return false;
        }

        // Convert strings to char arrays and sort them
        char[] charArray1 = str1.toCharArray();
        char[] charArray2 = str2.toCharArray();
        Arrays.sort(charArray1);
        Arrays.sort(charArray2);

        // Compare sorted char arrays
        return Arrays.equals(charArray1, charArray2);
    }

    public static void main(String[] args) {
        // Sample input and output
        String str1 = "listen";
        String str2 = "silent";

        if (areAnagrams(str1, str2)) {
            System.out.println(str1 + " and " + str2 + " are anagrams.");
        } else {
            System.out.println(str1 + " and " + str2 + " are not anagrams.");
        }
    }
}

Output :=

output


7. String Permutations

Write a Java program to print all permutations of a given string using recursion. Permutations are all possible arrangements of characters in a string.

Answer :=

public class StringPermutations {
    // Method to swap characters at positions i and j in a string
    private static String swap(String str, int i, int j) {
        char[] charArray = str.toCharArray();
        char temp = charArray[i];
        charArray[i] = charArray[j];
        charArray[j] = temp;
        return new String(charArray);
    }

    // Recursive method to generate permutations
    private static void generatePermutations(String str, int start, int end) {
        if (start == end) {
            System.out.println(str);
        } else {
            for (int i = start; i <= end; i++) {
                str = swap(str, start, i);
                generatePermutations(str, start + 1, end);
                str = swap(str, start, i); // Backtrack
            }
        }
    }

    // Method to print all permutations of a given string
    public static void printPermutations(String str) {
        generatePermutations(str, 0, str.length() - 1);
    }

    public static void main(String[] args) {
        String input = "abc"; // Change this to your desired input string
        System.out.println("Permutations of " + input + ":");
        printPermutations(input);
    }
}

Output :=

output


8. Fibonacci Series

Write a Java program to generate the Fibonacci series up to a given number using recursion. The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding ones.

Answer :=

public class FibonacciSeries {
    // Method to generate the Fibonacci series up to a given number
    public static void generateFibonacci(int n) {
        for (int i = 0; i < n; i++) {
            System.out.print(fibonacci(i) + " ");
        }
    }

    // Recursive method to calculate the nth Fibonacci number
    public static int fibonacci(int n) {
        if (n <= 1) {
            return n;
        }
        return fibonacci(n - 1) + fibonacci(n - 2);
    }

    public static void main(String[] args) {
        int n = 10; // Change this value to the desired number of terms
        System.out.println("Fibonacci series up to " + n + " terms:");
        generateFibonacci(n);
    }
}

Output :=

output


9. Factorial Calculation

Write a Java program to calculate the factorial of a given number using recursion. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n.

Answer :=

public class FactorialCalculation {
    // Method to calculate the factorial of a given number
    public static int calculateFactorial(int n) {
        if (n == 0 || n == 1) {
            return 1; // Base case: factorial of 0 and 1 is 1
        } else {
            return n * calculateFactorial(n - 1); // Recursive case
        }
    }

    public static void main(String[] args) {
        int number = 5; // Replace this with the desired number for which you want to calculate the factorial
        int factorial = calculateFactorial(number);
        
        System.out.println("Factorial of " + number + " is: " + factorial);
    }
}

Output :=

output


10. Power Calculation

Write a Java program to calculate the power of a given number (base and exponent) using recursion. The power of a number is obtained by multiplying the base with itself exponent times.

Answer :=

public class PowerCalculation {
    // Method to calculate the power of a number
    public static int calculatePower(int base, int exponent) {
        // Base case: Any number raised to the power of 0 is 1
        if (exponent == 0) {
            return 1;
        }
        
        // Recursive case: Multiply base with calculatePower(base, exponent - 1)
        return base * calculatePower(base, exponent - 1);
    }

    public static void main(String[] args) {
        int base = 2;
        int exponent = 5;
        int result = calculatePower(base, exponent);
        
        System.out.println(base + " raised to the power of " + exponent + " is: " + result);
    }
}

Output :=

output


11. Greatest Common Divisor (GCD)

Write a Java program to find the GCD of two numbers using recursion. The GCD is the largest positive integer that divides each of the numbers without leaving a remainder.

Answer :=

public class GCD {
    // Method to find the GCD of two numbers using recursion
    public static int findGCD(int num1, int num2) {
        if (num2 == 0) {
            return num1;
        }
        return findGCD(num2, num1 % num2);
    }

    public static void main(String[] args) {
        int num1 = 48;
        int num2 = 18;
        
        int gcd = findGCD(num1, num2);
        System.out.println("GCD of " + num1 + " and " + num2 + " is: " + gcd);
    }
}

Output :=

output


12. Check if Array is Sorted

Write a Java program to check if a given array of integers is sorted in non-decreasing order using recursion. A non-decreasing order means that the elements in the array are arranged in ascending order or may have equal consecutive elements.

Answer :=

public class ArraySortingCheck {
    // Method to check if the given array is sorted
    public static boolean isSorted(int[] arr) {
        return isSortedHelper(arr, 0);
    }

    // Recursive helper function to check array sorting
    private static boolean isSortedHelper(int[] arr, int index) {
        if (index >= arr.length - 1) {
            return true; // Base case: reached the end of the array
        }

        if (arr[index] > arr[index + 1]) {
            return false; // Array is not sorted
        }

        // Recursively check the rest of the array
        return isSortedHelper(arr, index + 1);
    }

    public static void main(String[] args) {
        int[] sortedArray = { 1, 2, 3, 4, 5 };
        int[] unsortedArray = { 5, 2, 8, 1, 3 };

        boolean isSortedSorted = isSorted(sortedArray);
        boolean isSortedUnsorted = isSorted(unsortedArray);

        System.out.println("Is sortedArray sorted? " + isSortedSorted);
        System.out.println("Is unsortedArray sorted? " + isSortedUnsorted);
    }
}

Output :=

output


13. Sum of Digits

Write a Java program to calculate the sum of digits of a positive integer using recursion. The sum of digits is obtained by adding up all the digits in the given number.

Answer :=

public class SumOfDigits {
    // Method to calculate the sum of digits of a positive integer
    public static int calculateSumOfDigits(int number) {
        if (number < 10) {
            return number; // Base case: single-digit number
        } else {
            return number % 10 + calculateSumOfDigits(number / 10);
        }
    }

    public static void main(String[] args) {
        // Sample input and output
        int num = 12345;
        int sum = calculateSumOfDigits(num);
        System.out.println("Sum of digits of " + num + " is " + sum);
    }
}

Output :=

output


14. Shift

A class Shift contains a two-dimensional integer array of order (mxn) where the maximum values of both m and n are 5. Design the class Shift to shuffle the matrix (i.e. the first row becomes the last, the second row becomes the first and so on). The details of the members of the class are given below

Answer :=

public class Shift {
    private int[][] matrix;
    private int m;
    private int n;

    public Shift(int[][] matrix) {
        this.matrix = matrix;
        m = matrix.length;
        n = matrix[0].length;
    }

    public void shuffleMatrix() {
        int[][] newMatrix = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                newMatrix[i][j] = matrix[(i + 1) % m][j];
            }
        }
        matrix = newMatrix;
    }

    public void printMatrix() {
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }

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

        Shift shifter = new Shift(initialMatrix);
        System.out.println("Original Matrix:");
        shifter.printMatrix();

        shifter.shuffleMatrix();
        System.out.println("Shuffled Matrix:");
        shifter.printMatrix();
    }
}

Output :=

output


15. Print Pattern - Recursion

Write a Java program to print a specific pattern using recursion:

1
1 2
1 2 3
1 2 3 4

The pattern consists of rows and columns of numbers, where each row contains numbers from 1 to the row number.

Answer :=

public class PatternPrinting {
    // Method to print the specified pattern using recursion
    public static void printPattern(int n) {
        if (n > 0) {
            printPattern(n - 1); // Print the pattern for n-1 rows
            
            // Print the numbers for the current row
            for (int i = 1; i <= n; i++) {
                System.out.print(i + " ");
            }
            
            System.out.println(); // Move to the next line after printing the row
        }
    }

    public static void main(String[] args) {
        int rows = 4; // You can change this to the desired number of rows
        
        System.out.println("Pattern:");
        printPattern(rows);
    }
}

Output :=

output


16. Find Maximum in an Array using Recursion

Write a Java program to find the maximum element in a given array using recursion. Find the largest element present in the array.

Answer :=

public class FindMaximum {
    // Method to find the maximum element in the array using recursion
    public static int findMax(int[] arr, int index) {
        // Base case: if the index reaches the end of the array, return the minimum possible value
        if (index == arr.length - 1) {
            return arr[index];
        }
        
        // Recursive case: find the maximum element in the rest of the array
        int maxInRest = findMax(arr, index + 1);
        
        // Compare the current element with the maximum element in the rest of the array
        if (arr[index] > maxInRest) {
            return arr[index];
        } else {
            return maxInRest;
        }
    }

    public static void main(String[] args) {
        int[] arr = { 12, 4, 78, 45, 67, 89, 100, 56 };
        int max = findMax(arr, 0);
        System.out.println("The maximum element in the array is: " + max);
    }
}

Output :=

output


17. Reverse Array using Recursion

Write a Java program to reverse a given array using recursion. Reverse the order of elements in the array.

Answer :=

public class ReverseArray {
    // Method to reverse the given array using recursion
    public static void reverse(int[] arr, int start, int end) {
        if (start >= end) {
            return;
        }

        // Swap elements at start and end indexes
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;

        // Recursive call to reverse the rest of the array
        reverse(arr, start + 1, end - 1);
    }

    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5};
        
        System.out.println("Original Array:");
        for (int num : array) {
            System.out.print(num + " ");
        }
        
        reverse(array, 0, array.length - 1);
        
        System.out.println("\nReversed Array:");
        for (int num : array) {
            System.out.print(num + " ");
        }
    }
}

Output :=

output


18. Check Palindrome using Recursion

Write a Java program to check if a given array is a palindrome or not using recursion. An array is a palindrome if it reads the same from the beginning and end.

Answer :=

public class ArrayPalindrome {
    // Method to check if the given array is a palindrome using recursion
    public static boolean isPalindrome(int[] arr, int start, int end) {
        // Base case: If the start index is greater than or equal to the end index,
        // then the array is a palindrome
        if (start >= end) {
            return true;
        }
        
        // Compare the elements at start and end indices
        if (arr[start] != arr[end]) {
            return false;
        }
        
        // Recur for the remaining subarray
        return isPalindrome(arr, start + 1, end - 1);
    }

    public static void main(String[] args) {
        int[] arr = { 1, 2, 3, 2, 1 }; // Sample input
        
        // Check if the array is a palindrome
        if (isPalindrome(arr, 0, arr.length - 1)) {
            System.out.println("The given array is a palindrome.");
        } else {
            System.out.println("The given array is not a palindrome.");
        }
    }
}

Output :=

output


19. Number of Occurrences in an Array

Write a Java program to count the number of occurrences of a specific element in a given array using recursion. Count how many times a particular element appears in the array.

Answer :=

public class ElementOccurrences {
    // Method to count the number of occurrences of a specific element in the array using recursion
    public static int countOccurrences(int[] arr, int element, int index) {
        // Base case: If index goes out of bounds, return 0
        if (index >= arr.length) {
            return 0;
        }
        
        // Check if the current element is equal to the target element
        // If yes, increment the count and continue searching in the rest of the array
        int count = (arr[index] == element) ? 1 : 0;
        
        // Recursive call to search in the remaining part of the array
        return count + countOccurrences(arr, element, index + 1);
    }

    public static void main(String[] args) {
        int[] arr = {2, 4, 6, 4, 8, 4, 10, 4, 12};
        int element = 4;
        
        int occurrences = countOccurrences(arr, element, 0);
        
        System.out.println("Number of occurrences of " + element + " in the array: " + occurrences);
    }
}

Output :=

output


20. Calculate Average using Recursion

Write a Java program to calculate the average of elements in a given array using recursion. The average is obtained by dividing the sum of all elements by the number of elements in the array.

Answer :=

public class CalculateAverage {
    // Method to calculate the sum of elements in the array using recursion
    public static int calculateSum(int[] arr, int index) {
        if (index < 0) {
            return 0;
        }
        return arr[index] + calculateSum(arr, index - 1);
    }

    // Method to calculate the average of elements in the array using recursion
    public static double calculateAverage(int[] arr) {
        int sum = calculateSum(arr, arr.length - 1);
        return (double) sum / arr.length;
    }

    public static void main(String[] args) {
        int[] array = { 10, 20, 30, 40, 50 };
        double average = calculateAverage(array);
        System.out.println("Average: " + average);
    }
}

Output :=

output


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment