Dataset Viewer
Auto-converted to Parquet Duplicate
instruction
stringlengths
38
3.13k
output
stringlengths
288
7.87k
__index_level_0__
int64
34
58.2k
Create a Java program that prints out the contents of a given two-dimensional array in a spiral pattern. The array will have dimensions M x N, where M represents the number of rows and N represents the number of columns. The program should print the elements of the array in a clockwise spiral pattern, starting from the...
Here is an example of a Java program that prints the contents of a given two-dimensional array in a spiral pattern: ```java public class SpiralArrayPrinter { public static void printSpiralArray(int[][] arr) { int m = arr.length; int n = arr[0].length; int topRow = 0, bottomRow = m - 1; ...
34
Create a Java program which takes an integer array as a parameter, sorts the array in descending order using a merge sort algorithm, and returns the sorted array. Additional Requirements: - The time complexity of the sorting algorithm should be O(n log n). - The space complexity should be O(1) (constant space). - You ...
To fix the erroneous code, we need to correct the initialization of the `left` and `right` arrays in the `mergeSort` method. Instead of creating arrays of size `mid`, we need to create `left` and `right` arrays of sizes `mid` and `arr.length - mid`, respectively. This will ensure that all elements of the original array...
146
Create a Java program to take a given string and replace all occurrences of a given letter with another given letter. Additionally, the program should only replace the given letter if it is at the beginning or the end of a word in the string. The program should also count and display the total number of replacements ma...
Here is a Java program that fulfills the given requirements: ```java import java.util.Scanner; public class ReplaceLetterInString { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input the string, letter to replace, and replacement letter System.out....
149
Write a Java program to calculate the product of two given integers. The program should take two integers as input from the user and display the product. Additional Requirements: 1. Validate the input to ensure that the user enters valid integers. If the input is not a valid integer, display an error message and ask t...
Here's an example Java program that calculates the product of two given integers: ```java import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int num1, num2; // Validate the input for the first integer w...
184
Implement a Java program for finding the index of the first occurrence of a target element in a sorted array. The array can contain duplicates. Requirements: - The time complexity of your solution should be O(log n), where n is the size of the array. - The space complexity of your solution should be O(1), i.e., it sho...
Here is a Java program that implements the requirements mentioned above: ```java public class FirstOccurrence { public static int findFirstOccurrence(int[] arr, int target) { int left = 0; int right = arr.length - 1; int result = -1; while (left <= right) { int mid = l...
436
Create a for loop in Java that iterates over the given array and prints only the prime numbers in ascending order. Additionally, the loop should terminate once it encounters the first composite number in the array. Array: int[] arr = {2, 3, 4, 5, 6, 7, 8, 9, 10};
Here is a for loop in Java that iterates over the given array, prints only the prime numbers in ascending order, and terminates once it encounters the first composite number in the array: ```java int[] arr = {2, 3, 4, 5, 6, 7, 8, 9, 10}; for (int num : arr) { boolean isPrime = true; if (num < 2) { isPrime ...
466
Create an array in Java with 100,000,000 floating-point values and output the average, median, and mode of these values. Additionally, implement the calculation of the standard deviation of the array.
To create an array in Java with 100,000,000 floating-point values, you can use the following code: ```java import java.util.Arrays; public class Statistics { public static void main(String[] args) { int size = 100000000; float[] array = new float[size]; // Fill the array with rand...
509
Write a Java program to find all pairs of distinct integers in an array that sum up to a given target integer. The program should print the indices of these pairs. The input consists of an array of unique integers and a target integer. The output should be a list of pairs, where each pair is represented by the indices...
Here is one possible implementation of the program: ```java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class PairSum { public static void main(String[] args) { int[] array = {2, 3, 4, 5, 6, 7, 7, -3, -1, -5}; int target = 9; L...
595
Write a Java program to find the sum of elements in an n x n matrix, where n is a positive integer. The matrix is represented as a two-dimensional array of integers. The program should take input from the user for the size of the matrix and then prompt the user to enter the elements of the matrix. The program should t...
Here is a Java program that addresses all the mentioned scenarios: ```java import java.util.Scanner; public class MatrixSumRecursive { private static double[][] matrix; private static double[][] memo; public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Syste...
636
Implement a stack data structure in Java with the following additional requirements: 1. The stack should have a maximum capacity of 1000 elements. If an attempt is made to push an element onto a full stack, it should throw a StackOverflowException. 2. The stack should support an additional operation called "getMinimum...
Here is an implementation of the stack with the additional requirements: ```java import java.util.Arrays; public class Stack { private int[] stack; private int top; private int min; private double median; public Stack() { stack = new int[1000]; top = -1; min = Integer.MAX_...
665
Implement a heap sort algorithm in Java without using any additional data structures or libraries. The algorithm should only use a fixed-size array to perform the sorting. Additionally, the array size should be limited to 100 elements and the implementation should be able to handle duplicate elements in the array effic...
Here is a Java implementation of heap sort algorithm using a fixed-size array of maximum 100 elements. This implementation can handle duplicate elements efficiently. ```java public class HeapSort { private static int heapSize; public static void sort(int[] array) { buildHeap(array); ...
673
Create a generic array of size N (where N is a positive integer) using Java and sort it using the bubble sort algorithm. Additionally, add a condition to the sorting algorithm that allows for sorting the array in descending order instead of ascending order. The array should contain objects of a custom class that implem...
Here is an example implementation that meets all the requirements mentioned: ```java import java.util.Comparator; interface CustomInterface { // method to be implemented by custom class void customMethod(); } class CustomClass implements CustomInterface { private int value; public CustomClass(int va...
678
Write a Java Method that takes an array of integers and returns true if the array is sorted in ascending order, does not contain any duplicate values, has a size greater than 5, and all the elements are prime numbers.
Here is a Java method that satisfies the given conditions: ```java public static boolean isSortedAscendingNoDuplicatesPrime(int[] arr) { // Check if array size is greater than 5 if (arr.length <= 5) { return false; } // Check if array is sorted in ascending order for (int i = 0; i < arr.le...
779
Write a method that prints out all the prime numbers between 1 and 1,000,000,000 and also calculates the sum of all these prime numbers.
To find all the prime numbers between 1 and 1,000,000,000, and calculate their sum, we can use the Sieve of Eratosthenes algorithm, which efficiently identifies all prime numbers up to a given limit. Here's a method in Java that implements this algorithm: ```java public static void printAndSumPrimes(int limit) { ...
785
Write a Java method that takes a string and prints out the number of occurrences of each unique vowel in the string, while also keeping track of the total count of consonants in the string. Ignore case sensitivity and consider vowels to be the letters 'a', 'e', 'i', 'o', and 'u'. The string may contain special characte...
Here's the Java method that meets the requirements mentioned: ```java import java.util.HashMap; import java.util.Map; public class VowelCount { public static void main(String[] args) { String input = "Hello World!"; try { countVowelsAndConsonants(input); } catch (InvalidString...
797
Write a Java program that takes an integer as input and checks if it is a prime number. If the input is a prime number, print "The number is prime." If the input is not a prime number, print "The number is not prime." Additionally, handle the case when the input is not a valid integer and print "Invalid input." The pro...
Here is a Java program that takes an integer as input and checks if it is a prime number, while also handling the mentioned edge cases: ```java import java.util.Scanner; public class PrimeNumberChecker { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out....
816
Implement a custom LinkedList class in Java without using any built-in data structures or collections libraries. The custom LinkedList should have the following methods: - addFirst(element): adds the specified element to the beginning of the list - addLast(element): adds the specified element to the end of the list - r...
Here is an implementation of a custom LinkedList class in Java: ```java public class LinkedList<T> { private Node<T> head; private Node<T> tail; private int size; public void addFirst(T element) { Node<T> newNode = new Node<>(element); if (head == null) { head = newNode; ...
821
Implement the following algorithm in Java, with a slight modification to the original bubble sort algorithm. // Modified Bubble sort algorithm for i in 1 to n-1 for j in 0 to n-i-1 if array[j] < array[j+1] swap array[j] and array[j+1] Your task is to modify the bubble sort algorithm to sort the array ...
Here is the modified bubble sort algorithm implemented in Java to sort an array in descending order: ```java public class BubbleSortDescending { public static void bubbleSortDescending(int[] array) { int n = array.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { ...
910
Create a method that prints all elements of an array, but also includes the following conditions: - Only print elements greater than 2. - Only print elements that are even numbers. - Sort the elements in descending order before printing them. - The array must contain at least 5 elements. - The array must not contain an...
Here is a possible implementation in Java: ```java import java.util.Arrays; public class ArrayPrinter { public static void printElements(int[] arr) { // Check if the array contains at least 5 elements if (arr.length < 5) { System.out.println("Array must contain at least 5 elements."); ...
975
Write a Java program that prompts the user to enter 5 integers and stores them in an array. The program should then calculate and display the sum, average, maximum, and minimum values of the entered integers.
Here is a Java program that prompts the user to enter 5 integers and calculates the sum, average, maximum, and minimum values of the entered integers: ```java import java.util.Scanner; public class IntegerArray { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); ...
995
Write a code in Java to replace all the occurrences of a given value in an array with a new value. If the given value is not found in the array, the code should print an error message "Value not found". arr = [2, 5, 1, 5, 8] Additional Requirements: 1. The code should handle both primitive integer arrays and array li...
For the first part of the question, where we need to replace occurrences of a given value in a one-dimensional array, we can use the following code: ```java import java.util.ArrayList; import java.util.Arrays; public class ArrayReplacement { public static void replaceValue(int[] arr, int oldValue, int newVal...
1,021
Write a Java program that creates a GUI window with a button. When the button is clicked, display a message box with a customized message based on the user's name and the selected option from a drop-down menu. Additionally, implement the following features: 1. Allow the user to enter their name in a text field. The cu...
Here's an example Java program that fulfills all the mentioned requirements: ```java import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.Random; public class CustomizedMessageGUI extends JFrame { private JLabel nameLabel; private JTextField nameField; private JButton button;...
1,053
Generate a for loop in Java to display all prime numbers between 1 and 50, excluding the numbers 7 and 13.
Here is an example of a for loop in Java to display all prime numbers between 1 and 50, excluding the numbers 7 and 13: ```java public class PrimeNumbers { public static void main(String[] args) { for (int i = 2; i <= 50; i++) { if (i == 7 || i == 13) { continue; // Skip numbers...
1,101
Implement a recursive Insertion Sort algorithm in Java. Additional requirement: The implementation must not use any additional data structures (such as arrays, lists, or queues) for sorting. Reference code: ``` public class InsertionSort { public static void main(String[] args) { int[] arr = {5, 2, 8, 1, ...
Here is the corrected code for the recursive Insertion Sort algorithm in Java: ```java public class InsertionSort { public static void main(String[] args) { int[] arr = {5, 2, 8, 1, 9}; insertionSort(arr); for (int num : arr) { System.out.print(num + " "); } } p...
1,139
Write a Java program to generate a random number between 1000 and 5000, but ensure that the generated number is divisible by both 7 and 11 and does not contain the digit 5.
Here is a Java program that generates a random number between 1000 and 5000, ensuring that the generated number is divisible by both 7 and 11 and does not contain the digit 5: ```java import java.util.Random; public class RandomNumberGenerator { public static void main(String[] args) { Random random = new...
1,236
Implement a thread pool in Java that supports dynamic resizing of the pool based on the current workload. Additionally, the thread pool should have a scheduling mechanism that prioritizes tasks based on their urgency, estimated execution time, and resource requirements, and assigns them to threads accordingly. The sche...
Below is an example of how you can implement a thread pool in Java with dynamic resizing, task scheduling, and error handling mechanisms: ```java import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.BlockingQ...
1,347
Write a Java method to check if a numerical value is within a specified range and return the number of times the value appears in the range. The method should have a time complexity of O(n), where n is the length of the input array `nums`. Signature: ```java public static int countValuesInRange(int[] nums, int startRa...
To solve this problem within the given time complexity constraint, we can use a simple iterative approach. We will iterate over each element in the array `nums` and count the number of elements that fall within the specified range `[startRange, endRange]`. Here is the Java code that implements this logic: ```java pu...
1,382
Create a for loop in Java using the given array and print out the sum of all prime numbers in the array. Additionally, handle any exceptions that may occur while calculating the sum.
Sure, here's an example of a for loop in Java that calculates the sum of all prime numbers in a given array, and handles any exceptions that may occur: ```java public class PrimeNumberSum { public static void main(String[] args) { int[] numbers = { 2, 5, 8, 11, 13, 15, 17, 19 }; int sum = 0; ...
1,400
Write a Java program that calculates the volume of a triangular prism, given the length of the base, the height of the triangle, and the height of the prism. Erroneous code reference: ``` double baseLength = 6.5; double triangleHeight = 4.8; double prismHeight = 9.2; // Calculate the area of the base triangle double...
Here is the corrected Java code: ```java public class TriangularPrismVolumeCalculator { public static void main(String[] args) { double baseLength = 6.5; double triangleHeight = 4.8; double prismHeight = 9.2; // Calculate the area of the base triangle double baseArea = (ba...
1,569
Create a Java program that reads an array of integers from the console and prints out the largest number. The program should also check if the input array contains any negative numbers and display an error message if it does. Additionally, the program should ensure that the array contains at least 5 integers and that t...
Here is a Java program that meets the given requirements: ```java import java.util.InputMismatchException; import java.util.Scanner; public class LargestNumber { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int[] numbers = new int[5]; try { ...
1,577
Create an algorithm in Java to sort an array in descending order using the "QuickSort" sorting algorithm. However, there are two bugs in the provided code that need to be fixed before the array can be correctly sorted. Find and correct the bugs in the code. array = [10, 15, 7, 2, 13, 18] Note: The bugs may be relate...
Here is the corrected code to sort an array in descending order using the QuickSort algorithm: ```java public class QuickSortDescending { public static void main(String[] args) { int[] array = {10, 15, 7, 2, 13, 18}; quickSortDescending(array, 0, array.length - 1); // Prin...
1,594
Write a Java program to find the second maximum and second minimum values in an array of integers, excluding any duplicates. The program should handle cases where all elements in the array are duplicates by only considering one instance of each duplicate value. If the array is empty or contains only one element, the pr...
Here is the Java program to find the second maximum and second minimum values in an array of integers, excluding any duplicates: ```java import java.util.Arrays; public class SecondMinMax { public static void findSecondMinMax(int[] arr) { int n = arr.length; if (n < 2) { ...
1,681
Create a Java program to convert a 2D array of positive integers into a single positive integer. The 2D array represents a matrix, where each element in the array represents a digit. The resulting integer should be obtained by reading the digits row by row, from left to right. The input array is guaranteed to have at l...
Here is the Java program that converts a 2D array of positive integers into a single positive integer: ```java public class MatrixToIntegerConverter { public static void main(String[] args) { int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int number = convertMatrixToInteg...
1,802
Create a Java program to find the maximum element of an array that also meets the following criteria: 1. The maximum element must be odd. 2. The maximum element must be a prime number. 3. The program must not use any built-in Java libraries or methods for finding prime numbers. 4. The program must have a time complexit...
Here is an example implementation of a Java program that meets the given criteria: ```java import java.util.ArrayList; import java.util.List; public class MaximumElementFinder { public static void main(String[] args) { // Create an array with at least 10000 elements int[] arr = new int[10000]; // ......
1,901
Write a method which takes 4 parameters: a positive integer, a negative integer, a floating-point number, and a string. The method should return the sum of the positive integer and the negative integer, rounded to the nearest integer. However, if the floating-point number is negative, or if the string contains any spec...
Here is a method that satisfies the given requirements: ```java public static String calculateSum(int positiveInt, int negativeInt, double floatingPoint, String text) { // Check if any of the parameters are out of range if (positiveInt < -1000 || positiveInt > 1000 || negativeInt < -1000 || negativeInt > 1000 ...
1,964
Write a Java program to convert a binary string to a decimal number. The binary string can have a maximum length of 128 characters. Additionally, the program should handle cases where the binary string contains leading or trailing whitespace characters. #Additional Requirements# 1. The program should validate that the...
Here is a Java program that fulfills all the additional requirements: ```java public class BinaryToDecimalConverter { public static int convertBinaryToDecimal(String binaryString) { binaryString = binaryString.trim(); validateBinaryString(binaryString); boolean isNegative = false; ...
2,042
Write a Java program to multiply two large numbers of any length, but without using the `*` operator or any built-in libraries for multiplication. Note: You can assume that the two numbers will be positive and will not exceed the maximum value of `Long`. Provide a piece of erroneous code as a reference to increase mi...
Here is the corrected code: ```java public class Main { public static void main(String[] args) { String num1 = "12345678901234567890"; String num2 = "98765432109876543210"; int len1 = num1.length(); int len2 = num2.length(); int[] result = new int[len1 + len2]; fo...
2,045
Create a class in Java that takes two arguments, a name of type String and an id of type int. The name should be limited to a maximum length of 15 characters and should only consist of alphabetic characters. The id should be a positive integer between 1000 and 10000. In addition, the name should be converted to lowerc...
The code provided does not check if the id is a positive integer between 1000 and 10000. The error can be fixed by adding an additional check in the constructor: ```java public class Person { private String name; private int id; public Person(String name, int id) { if (name.length() <= 15 && name....
2,057
Write a Java program to sort the given array of integers using Quick Sort in descending order. Implement the Quick Sort algorithm iteratively instead of recursively. The program should have a time complexity of O(nlogn) and space complexity of O(logn). Additionally, you are not allowed to use any additional data struct...
Here's the Java program that implements Quick Sort iteratively in descending order: ```java import java.util.Arrays; public class QuickSortIterative { public static void quickSort(int[] arr) { int len = arr.length; int[] stack = new int[len]; int top = -1; stack[++top] =...
2,138
Create a Java method that takes in a two-dimensional array of integers and prints the array in a spiral order. The array will always have an odd number of rows and columns. The method should start printing from the top left element and move in a clockwise direction. Additionally, the method should also return the sum o...
Here is the Java method that fulfills the requirements: ```java public static int printSpiral(int[][] array) { int sum = 0; int rows = array.length; int cols = array[0].length; int top = 0; int bottom = rows - 1; int left = 0; int right = cols - 1; while (top <= bottom && left <= right...
2,327
Create a loop in Java for printing all elements of an array of strings in reverse order, while also ignoring any elements that contain a specific character. The array is given below: ["String4", "String3", "String2", "String1", "Hello_World"] New Requirements: 1. The solution should be implemented using a recursive m...
Here's a solution that meets all the given requirements: ```java public class ReverseArray { private static int ignoredCount = 0; public static void main(String[] args) { // Checking if the specific character is provided as a command-line argument if (args.length < 1) { System.out.println("Plea...
2,342
Write a code in Java to find the factorial of a number using recursion. However, you are not allowed to use the '*' operator to multiply numbers. Instead, you should implement your own recursive multiplication method to calculate the factorial. Additionally, you should optimize your code to handle larger numbers effic...
Here is an implementation of the factorial calculation using recursion and a custom multiplication method. It also handles negative numbers, zero, and uses memoization to improve efficiency: ```java import java.util.HashMap; import java.util.Map; public class Factorial { private static Map<Integer, Long> memo = n...
2,350
Generate a random alphanumeric string of length n in Java, where n is an input provided by the user. The generated string should include at least one uppercase letter, one lowercase letter, one digit, and one special character. The time complexity of the solution should be O(n), and the space complexity should be O(1)....
Here's a possible solution to the modified problem: ```java import java.util.Random; public class RandomAlphanumericStringGenerator { private static final String UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; private static final String LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz"; private static f...
2,381
Create a Java object for a student with the fields 'Name', 'Marks', 'Attendance', and 'ExtraCurricularActivities'. The 'Attendance' field should be a list of integers representing the student's attendance record for each class. The 'Marks' field should be a map where the key is the subject name (String) and the value i...
Here is a Java class representing a student with the given fields and methods: ```java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Student { private String name; private Map<String, List<Integer>> marks; private List<Integer> attendance; ...
2,427
Create a method in Java to read input from the console and handle different types of input, including integers, floating-point numbers, and strings. The method should validate the input against specific criteria for each type, as follows: - If the user enters an integer, the method should return the integer and valida...
Here's an example implementation of the method in Java: ```java import java.util.Scanner; public class ConsoleInputHandler { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Object userInput = readInput(scanner); System.out.println("User input: " + userInp...
2,545
Create a class in Java to store student information such as name, age, course, and grade point average. Implement a method that calculates the student's cumulative GPA by taking into account the credits earned for each course. The GPA should be rounded to two decimal places. Additionally, include a method that returns ...
Here is an implementation of the class in Java: ```java import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; public class Student { private String name; private int age; private String course; private double gpa; public Student(String name,...
2,639
Create a Java program to print a square diamond pattern with '*' characters. However, the program should only print the diamond pattern if the input number is prime, falls within the range of 1 to 1000, and is a multiple of 3. Additionally, the program should also include a method to check if a given number is a perfec...
Here is a Java program that meets the given requirements: ```java import java.util.Scanner; public class SquareDiamondPattern { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter a number: "); int number = scanner.nextInt(); ...
2,793
Create an array of 1 million elements using Java and initialize each element with a unique value. The unique values should be randomly generated within a specified range. Additionally, ensure that the generated values are prime numbers.
Here's a Java code snippet that creates an array of 1 million elements, with each element initialized with a unique prime number randomly generated within a specified range. ```java import java.util.Arrays; import java.util.Random; public class PrimeNumberArray { public static void main(String[] args) { i...
2,821
Generate a Java program that prints the longest palindrome word in a sentence, considering that the sentence may contain multiple palindrome words with the same length. If there are multiple longest palindrome words, the program should print all of them. Additionally, the program should ignore any punctuation marks and...
Here is a Java program that finds and prints the longest palindrome word(s) in a sentence, ignoring punctuation marks and whitespace characters: ```java import java.util.ArrayList; import java.util.List; public class LongestPalindrome { public static void main(String[] args) { String sentence = "A man, a ...
2,852
Write a Java method that takes two positive integers less than or equal to 1,000,000 and returns the sum of their digits. The method should also handle negative integers and zero as input, returning -1 for negative integers and 0 for zero input. Additionally, the method should check if the input integers are prime num...
Here's a possible implementation of the Java method: ```java public static int sumOfDigits(int num1, int num2) { if (num1 < 0 || num2 < 0) { return -1; // Return -1 for negative integers } else if (num1 == 0 || num2 == 0) { return 0; // Return 0 for zero input } else { int sum = 0; ...
2,999
Write Java code for converting a string to an array, but exclude any vowels and special characters from the resulting array. Additionally, remove any duplicate elements from the array and sort the array in ascending order. String: "Hello @#& World"
Here's a Java code that converts the given string to an array, excluding vowels and special characters, removing duplicate elements, and sorting the array in ascending order: ```java import java.util.Arrays; import java.util.HashSet; public class StringToArray { public static void main(String[] args) { St...
3,078
Write a Java program to create a thread which prints the prime numbers between 1 and 1000 in ascending order, but only considers numbers that are palindromic. Additionally, the program should display a message "Thread is interrupted" if the thread is interrupted before completing its task.
Here is a Java program that creates a thread to print the palindromic prime numbers between 1 and 1000 in ascending order. It also handles the case when the thread is interrupted: ```java public class PalindromicPrimeThread extends Thread { @Override public void run() { try { for (int i = 1...
3,081
Write a Java program to compare two strings lexicographically and return the index of the first different character. Two strings: string1="GeeksforGeeks" and string2="GeeksGforGeks". Use a nested loop to compare each character of the two strings. If a different character is found, return its index. If the strings are e...
Here is the Java program that compares two strings lexicographically and returns the index of the first different character: ```java public class CompareStrings { public static int compareStrings(String string1, String string2) { // Check if either string is null if (string1 == null || string2 == n...
3,101
Write a code in Java to find all the prime numbers between 0 and n, where n can be as large as 10^9. Additionally, the code should be optimized to run within a time complexity of O(nlog(logn)). The code should also handle cases where n is negative or zero by displaying an error message.
Here's a code in Java that finds all prime numbers between 0 and n, with a time complexity of O(nlog(logn)). It also handles cases where n is negative or zero by displaying an error message: ```java import java.util.ArrayList; public class PrimeNumbers { public static void main(String[] args) { int n = 10...
3,149
Implement a password validator in Java that meets the following requirements: - The password must contain at least two uppercase letters. - The password must contain at least two lowercase letters. - The password must contain at least two digits. - The password must contain at least two special characters (!, @, #, $, ...
Here is a possible implementation of the password validator in Java: ```java import java.util.regex.Matcher; import java.util.regex.Pattern; public class PasswordValidator { public static boolean validatePassword(String password) { // Check length if (password.length() < 10 || password.length...
3,151
Create an array in Java that contains ten elements, each of type String. Additionally, ensure that each element in the array is unique, contains only lowercase alphabets, and is sorted in ascending order.
Here's an example of how you can create an array in Java that meets all the given requirements: ```java import java.util.Arrays; public class Main { public static void main(String[] args) { String[] array = {"apple", "banana", "cherry", "grape", "kiwi", "mango", "orange", "peach", "pear", "strawberry"}; ...
3,209
Write a Java program that asks the user to input a character and then performs the following operations on it: 1. Check if the character is a letter (either uppercase or lowercase). 2. If it is a letter, determine if it is a vowel or a consonant. 3. If it is a vowel, display a message saying "The entered character is a...
Here is the Java program that fulfills the given requirements: ```java import java.util.Scanner; public class CharacterOperations { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter a character:"); String input = scanner.nextLine(...
3,283
Write a Java code to perform binary search on the given sorted array. The code should handle cases where the array may contain duplicate elements. Additionally, the code should return the index of the first occurrence of the target element in the array.
Here is the Java code that performs a binary search on a given sorted array and returns the index of the first occurrence of the target element: ```java public class BinarySearch { public static int binarySearch(int[] arr, int target) { int left = 0; int right = arr.length - 1; int result =...
3,343
Write a Java method that takes in a string and returns an array containing all the possible permutations of this string. Additionally, each permutation should only contain unique characters. The time complexity of the algorithm should be less than O(n!), where n is the length of the string. You are not allowed to use ...
Here's one possible solution to the problem: ```java import java.util.ArrayList; public class Permutations { public static ArrayList<String> getPermutations(String input) { ArrayList<String> permutations = new ArrayList<>(); backtrack(permutations, new StringBuilder(), input.toCharArray(), ne...
3,747
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
3