Java Code Examples: Prime Numbers, Array Rotation, Tree Depth
Finding Special Prime Numbers in Java
This code finds two-digit integers where the digit ‘3’ is the most frequent digit. For example, the output will be [13, 23, 31, 37, 43, 53, 73, 83].
“`java import java.util.ArrayList; import java.util.List; import java.util.Scanner;
public class SpecialPrimeFinder {
// Method to get special prime numbers private List getSpecialPrimeNo(int digits, int frequentNo) { List resLst = new ArrayList<>(); int lowerBound = (int) Math.pow(10, digits – 1); int upperBound = (int) Math.pow(10, digits); for (int num = lowerBound; num < upperBound; num++) { if (isPrimeNum(num) && String.valueOf(num).contains(String.valueOf(frequentNo))) { resLst.add(num); } } return resLst; }
// Method to check if a number is prime private boolean isPrimeNum(int num) { if (num <= 1) return false; if (num == 2) return true; for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) return false; } return true; }
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); SpecialPrimeFinder obj = new SpecialPrimeFinder();
// Take user input for the number of digits System.out.print(“Enter the number of digits: “); int digits = scanner.nextInt();
// Take user input for the frequent digit System.out.print(“Enter the digit to look for in primes: “); int frequentNo = scanner.nextInt();
// Get and display special primes List specialPrimes = obj.getSpecialPrimeNo(digits, frequentNo); System.out.println(“Special Prime Numbers: ” + specialPrimes); scanner.close(); } } “`
Party Game Elimination in Java
Danny’s party game involves guests sitting in a circle and passing a ball. Guests who don’t receive the ball are eliminated. This code determines the IDs of the eliminated guests.
“`java import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set;
public class PartyGame {
public static List findEliminatedGuests(int numGuests, int passingInterval) { if (numGuests < 1 || passingInterval < 1) { throw new IllegalArgumentException(“Invalid input”); } int guestId = 0; Set nonEliminated = new HashSet<>(); nonEliminated.add(guestId);
// Pass the ball until it returns to the first guest while ((guestId + passingInterval) % numGuests != 0) { guestId = (guestId + passingInterval) % numGuests; nonEliminated.add(guestId); }
// Identify eliminated guests List eliminated = new ArrayList<>(); for (int id = 0; id < numGuests; id++) { if (!nonEliminated.contains(id)) { eliminated.add(id + 1); // Convert to 1-based indexing } } return eliminated; }
public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
// Take user input for the number of guests System.out.print(“Enter the number of guests: “); int numGuests = scanner.nextInt();
// Take user input for the passing interval System.out.print(“Enter the passing interval: “); int passingInterval = scanner.nextInt();
// Find and display the eliminated guests try { List eliminatedGuests = findEliminatedGuests(numGuests, passingInterval); System.out.println(“Eliminated guests: ” + eliminatedGuests); } catch (IllegalArgumentException e) { System.out.println(e.getMessage()); } scanner.close(); } } “`
Rotating an Array to its Minimum Element in Java
This code rotates an array to place its minimum element at the beginning.
“`java import java.util.Arrays; import java.util.Scanner;
public class Main {
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter the number of elements in the array: “); int n = scanner.nextInt(); int[] arr = new int[n]; System.out.println(“Enter the elements of the array:”); for (int i = 0; i < n; i++) { arr[i] = scanner.nextInt(); } rotateArrayToMin(arr); System.out.println(“Rotated Array: ” + Arrays.toString(arr)); }
public static void rotateArrayToMin(int[] arr) { if (arr.length == 0) { return; // If the array is empty, no rotation is needed } int minIndex = 0; for (int i = 1; i < arr.length; i++) { if (arr[i] < arr[minIndex]) { minIndex = i; } }
// Swap the minimum element with the first element int temp = arr[0]; arr[0] = arr[minIndex]; arr[minIndex] = temp;
// Reverse the rest of the array int left = 1; int right = arr.length – 1; while (left < right) { temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left++; right–; } } } “`
Calculating Maximum Depth of a Tree in Java
This code calculates the maximum depth of a tree given its adjacency list representation.
“`java import java.util.*;
class Tree { private Map> adjacencyList; private int maxDepth;
public Tree(int n) { adjacencyList = new HashMap<>(); maxDepth = 0; // Initialize adjacency list for (int i = 0; i < n; i++) { adjacencyList.put(i, new ArrayList<>()); } }
public void addEdge(int u, int v) { adjacencyList.get(u).add(v); adjacencyList.get(v).add(u); // For undirected graph }
public int maxDepth() { boolean[] visited = new boolean[adjacencyList.size()]; dfs(0, 0, visited); return maxDepth; }
private void dfs(int node, int depth, boolean[] visited) { visited[node] = true; maxDepth = Math.max(maxDepth, depth + 1); for (int neighbor : adjacencyList.get(node)) { if (!visited[neighbor]) { dfs(neighbor, depth + 1, visited); } } }
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); Tree tree = new Tree(n); // Build adjacency list for (int i = 0; i < n – 1; i++) { int u = scanner.nextInt(); int v = scanner.nextInt(); tree.addEdge(u, v); } System.out.println(“Maximum Depth: ” + tree.maxDepth()); } } “`
Calculating the Goodness Value of a Tree in Java
This code calculates the “goodness value” of a tree, which is the maximum distance from any node to a leaf node.
“`java import java.util.*;
class Tree { private Map> adjacencyList;
public Tree(int n) { adjacencyList = new HashMap<>(); for (int i = 0; i < n; i++) { adjacencyList.put(i, new ArrayList<>()); } }
public void addEdge(int u, int v) { adjacencyList.get(u).add(v); adjacencyList.get(v).add(u); // For undirected graph }
public int goodnessValue() { int maxGoodness = 0; boolean[] visited = new boolean[adjacencyList.size()]; // Perform DFS from each node to find the maximum distance to leaf nodes for (int node = 0; node < adjacencyList.size(); node++) { int[] distances = new int[adjacencyList.size()]; dfs(node, node, 0, visited, distances); // Update maxGoodness int maxDistance = Arrays.stream(distances).max().getAsInt(); maxGoodness = Math.max(maxGoodness, maxDistance); } return maxGoodness; }
private void dfs(int startNode, int currentNode, int distance, boolean[] visited, int[] distances) { visited[currentNode] = true; distances[currentNode] = distance; // Update distances for neighboring nodes for (int neighbor : adjacencyList.get(currentNode)) { if (!visited[neighbor]) { dfs(startNode, neighbor, distance + 1, visited, distances); } } }
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); Tree tree = new Tree(n); // Build adjacency list for (int i = 0; i < n – 1; i++) { int u = scanner.nextInt(); int v = scanner.nextInt(); tree.addEdge(u, v); } System.out.println(“Goodness Value: ” + tree.goodnessValue()); } } “`
Calculating Happiness in Cities with the Newton Function in Java
This code calculates a “happiness” value based on input parameters using a custom function.
“`java import java.util.Scanner;
public class Main {
public static int newston(int T, int[] Z, int[] K) { int result = 0; for (int i = 0; i < T; i++) { // Calculate the number of sequences long sequences = 1; for (int j = 0; j < K[i]; j++) { sequences *= (Z[i] * Z[i] – j); } result += sequences; } return result; }
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter the number of test cases (T): “); int T = scanner.nextInt(); int[] Z = new int[T]; int[] K = new int[T]; for (int i = 0; i < T; i++) { System.out.print(“Enter the happiness constant (Z) for test case ” + (i + 1) + “: “); Z[i] = scanner.nextInt(); System.out.print(“Enter the sequence length (K) for test case ” + (i + 1) + “: “); K[i] = scanner.nextInt(); } int result = newston(T, Z, K); System.out.println(“Result: ” + result); } } “`
Counting Ways to Make a Number Divisible by 3 in Java
Given a string representing a number, this code calculates the number of ways to make the number divisible by 3 by changing at most one digit.
“`java public class Main {
public static int countWays(String str) { int n = str.length(); int sum = 0; int res = 0;
// Calculate the sum of digits for (char c : str.toCharArray()) { sum += c – ‘0’; }
// Check for each digit replacement for (int i = 0; i < n; i++) { int orig = str.charAt(i) – ‘0’; for (int dig = 0; dig <= 9; dig++) { int newSum = sum – orig + dig; if (newSum % 3 == 0) { res++; } } }
// Subtract the original number if it’s already divisible by 3 if (sum % 3 == 0) { res–; } return res; }
public static void main(String[] args) { String str = “23”; System.out.println(“Number of ways: ” + countWays(str)); } } “`
Finding the Longest Substring with Even Character Counts in Java
This code finds the length of the longest substring where every character appears an even number of times.
“`java public class Main {
public static int longestEvenSubstring(String s) { int n = s.length(); int maxLen = 0; int[] count = new int[256]; // ASCII size
// Initialize count array for (int i = 0; i < 256; i++) { count[i] = 0; }
int oddCount = 0; for (int i = 0; i < n; i++) { // Count occurrences of each character count[s.charAt(i)]++;
// Update odd count if (count[s.charAt(i)] % 2 != 0) { oddCount++; } else { oddCount–; }
// If odd count is 0, update max length if (oddCount == 0) { maxLen = i + 1; } }
// Handle cases with at most one odd count for (int i = 0; i < n; i++) { if (count[s.charAt(i)] % 2 != 0) { // Remove this character and update max length maxLen = Math.max(maxLen, n – 1); break; } } return maxLen; }
public static void main(String[] args) { String s = “aabacdb”; System.out.println(“Length of longest even substring: ” + longestEvenSubstring(s)); } } “`
Calculating the Length of the Longest Increasing-Decreasing Sequence in Java
This code determines the length of the longest increasing-decreasing sequence that can be formed from an array, where duplicates are not allowed.
“`java import java.util.HashMap; import java.util.Map; import java.util.Scanner;
public class Main {
public static int longestIncreasingDecreasingSequence(int[] arr) { Map freqMap = new HashMap<>();
// Count frequency of each element for (int num : arr) { freqMap.put(num, freqMap.getOrDefault(num, 0) + 1); }
int maxCount = 0; int uniqueCount = 0;
// Count unique elements and max occurrences for (int count : freqMap.values()) { uniqueCount++; maxCount = Math.max(maxCount, count); }
// Return length of longest increasing decreasing sequence return uniqueCount + (maxCount – 1); }
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter the number of elements: “); int n = scanner.nextInt(); int[] arr = new int[n]; System.out.println(“Enter the elements:”); for (int i = 0; i < n; i++) { arr[i] = scanner.nextInt(); } int result = longestIncreasingDecreasingSequence(arr); System.out.println(“Length of longest increasing decreasing sequence: ” + result); } } “`
Counting Words Formable from a Given String in Java
Given a string and a word, this code determines how many times the word can be formed using the characters of the string.
“`java import java.util.HashMap; import java.util.Map; import java.util.Scanner;
public class Main {
public static int countWords(String str, String word) { Map strMap = new HashMap<>(); Map wordMap = new HashMap<>();
// Count frequency of characters in str for (char c : str.toLowerCase().toCharArray()) { strMap.put(c, strMap.getOrDefault(c, 0) + 1); }
// Count frequency of characters in word for (char c : word.toLowerCase().toCharArray()) { wordMap.put(c, wordMap.getOrDefault(c, 0) + 1); }
int count = Integer.MAX_VALUE;
// Find minimum occurrences for each character for (Map.Entry entry : wordMap.entrySet()) { char c = entry.getKey(); int wordFreq = entry.getValue(); int strFreq = strMap.getOrDefault(c, 0); if (strFreq == 0) { return 0; // Character not found in str } count = Math.min(count, strFreq / wordFreq); } return count; }
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(“Enter the string: “); String str = scanner.nextLine(); System.out.print(“Enter the word: “); String word = scanner.nextLine(); System.out.println(“Number of words: ” + countWords(str, word)); } } “`