0% found this document useful (0 votes)
21 views14 pages

Java Array Algorithms and Outputs

Uploaded by

LIBIN R K
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views14 pages

Java Array Algorithms and Outputs

Uploaded by

LIBIN R K
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PROGRAMS

[Link] SORTED UNIQUE ARRAY

import [Link].*;
public class Merge{
public static void main(String args[]){
int[] arr1={1,3,6,9,5};
int[] arr2={4,7,2,9,0};
Set<Integer> mergedSet=new TreeSet<>();
for(int num:arr1){
[Link](num);
}
for(int num:arr2){
[Link](num);
}
int[] mergedarray= new int[[Link]()];
int index=0;
for(int num:mergedSet){
mergedarray[index++]=num;
}
[Link]([Link](mergedarray));
}
}

OUTPUT:

[0, 1, 2, 3, 4, 5, 6, 7, 9]
[Link] WINDOW

import [Link].*;

public class SlidingWindowMaximum {

public static void main(String[] args) {

int[] arr = {3, 2, 7, 6, 5, 1, 2, 3, 4};

int k = 3;

// Deque to store indexes of useful elements in every window

Deque<Integer> deque = new LinkedList<>();

// Traverse the array

for (int i = 0; i < [Link]; i++) {

// Remove elements out of the current window

if (![Link]() && [Link]() < i - k + 1) {

[Link]();

// Remove elements that are smaller than the current element

while (![Link]() && arr[[Link]()] < arr[i]) {

[Link]();

// Add the current element at the back of the deque

[Link](i);

// The largest element in the window is at the front of the deque

if (i >= k - 1) {

[Link](arr[[Link]()] + " ");

OUTPUT:
7776534

[Link] FREQUENCY COUNTER

import [Link].*;
class HelloWorld {
public static void main(String[] args) {
int[] array1={1,1,3,2,2,2,5,8,9,8};
[Link](array1);
int count=1;
for(int i=0;i<[Link]-1;i++)
{
if(array1[i]==array1[i+1])
count++;
else
{
[Link](array1[i]+": "+count);
count=1;
}
}

}
}

OUTPUT:

1: 2
2: 3
3: 1
5: 1
8: 2

[Link] VALUE ,FIND COUNT


public class ThresholdPaths {
public static void main(String[] args) {
int[] arr = {5, 8, 10, 13, 6, 2};
int threshold = 3;
int count = 0;
for (int num : arr) {
while (num > 0) {
int step = [Link](threshold, num);
num -= step;
count++;
}
}
[Link]("count = " + count);
}
}
OUTPUT:
Count =17

[Link] HIGH LOW ARRAY

import [Link].*;
class AlternativeString{
public static void main (String[] args){
int arr[] = {5,2,8,7,4,3,9};
int n = [Link];
[Link](arr);
int i = 0, j = n-1;
while (i < j) {
[Link](arr[j--] + " ");
[Link](arr[i++] + " ");
}
if (n % 2 != 0)
[Link](arr[i])
}
}

OUTPUT:

9283745

[Link] THE ELEMENTS OF THE ARRAY GREATER THAN ITS PREVIOUS

public class GreaterThanPrevious {


public static void main(String[] args) {
int[] arr = {2, -3, -4, 5, 9, 7, 8};
// Print the first element
[Link](arr[0] + " ");
// Initialize a variable to keep track of the maximum value seen so far
int maxSoFar = arr[0];
// Traverse the array starting from the second element
for (int i = 1; i < [Link]; i++) {
if (arr[i] > maxSoFar) {
[Link](arr[i] + " ");
maxSoFar = arr[i];
// Update the maximum value seen so far
}
}
}
}
OUTPUT:
259

[Link] SUM CONTIGOUS SUBARRAY

public class MaxSumNonNegativeSubarray {


public static void main(String[] args) {
int[] arr = {2, 7, -5, 1, 3, 2, 9, -7};
int maxSum = 0;
int currentSum = 0;
int start = 0;
int end = 0;
int tempStart = 0;
for (int i = 0; i < [Link]; i++) {
if (arr[i] >= 0) {
if (currentSum == 0) {
tempStart = i;
//subarray
}
currentSum += arr[i];
if (currentSum > maxSum) {
maxSum = currentSum;
start = tempStart;
end = i;
}
} else {
currentSum = 0; // Reset current sum if a negative number is found
}
}
// Print the results
[Link]("Sum: " + maxSum);
[Link]("Elements: ");
for (int i = start; i <= end; i++) {
[Link](arr[i] + " ");
}
}
}

OUTPUT:
Sum:15
elements:1 3 2 9

[Link] SUM

import [Link];
import [Link];
public class CombinationSum {
public static void main(String[] args) {
int[] arr = {8, 3, 4, 7, 9};
int target = 7;
List<List<Integer>> results = new ArrayList<>();
findCombinations(arr, target, 0, new ArrayList<>(), results);
// Print the results
for (List<Integer> result : results) {
[Link](result);
}
}
private static void findCombinations(int[] arr, int target, int start, List<Integer> combination,
List<List<Integer>> results) {
if (target == 0) {
[Link](new ArrayList<>(combination));
return;
}
if (target < 0) {
return;
}
for (int i = start; i < [Link]; i++) {
[Link](arr[i]);
findCombinations(arr, target - arr[i], i + 1, combination, results);
[Link]([Link]() - 1);
}
}
}
OUTPUT:
[3, 4]
[7]

[Link] SORTED ARRAY INPUT

import [Link].*;
import [Link];
public class New{
public static void main(String[] args){
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of array: ");
int a = [Link]();
int[] arr1=new int[a];
[Link]("Enter the elements: "); for(int i=0;i<a;i++){
arr1[i]=[Link]();
}
Set<Integer> array = new TreeSet<>();
for(int num:arr1){
[Link](num);
}
for(int num:array){
[Link](num+", ");
}
}
}

OUTPUT:

Enter the size of array: 10


Enter the elements:
2345567892
2, 3, 4, 5, 6, 7, 8, 9,
[Link]
[Link] SECURITY OFFICIALS……

public class RiskSorter {


public static void main(String[] args) {
int[] arr = {1, 0, 2, 0, 1, 0, 2}; // Example input array
sortArray(arr);
// Print the sorted array
for (int num : arr) {
[Link](num);
}
}
public static void sortArray(int[] arr) {
int low = 0, mid = 0, high = [Link] - 1;
while (mid <= high) {
switch (arr[mid]) {
case 0:
// Swap arr[low] and arr[mid], then increment both
swap(arr, low++, mid++);
break;
case 1:
// Move to the next element
mid++;
break;
case 2:
// Swap arr[mid] and arr[high], then decrement high
swap(arr, mid, high--);
break;
}
}
}
public static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
OUTPUT:
0001122

[Link] SUNDAYS(ERROR)

[Link] NUMBER INTO BINARY NUMBER

public class DecimalToBinary {


public static void main(String[] args) {
int decimalNumber = 123; // Example input
String binaryString = convertToBinary(decimalNumber);
[Link](binaryString); // Output the binary representation
}
public static String convertToBinary(int decimalNumber) {
// Convert the decimal number to a binary string
String binaryString = [Link](decimalNumber);
return binaryString;
}
}
OUTPUT:
1111011

[Link] OF ADJACENT ELEMENTS(OUTPUT IS NOT IN PROPER FORMAT)

public class XorAdjacent {


public static void main(String[] args) {
int[] arr = {1, 0, 1, 0, 1, 1}; // Input array
int iterations = 5; // Number of iterations

// Perform XOR operation for the specified number of iterations


for (int i = 0; i < iterations; i++) {
arr = xorAdjacent(arr);
printArray(arr);
}
}

// Method to perform XOR on adjacent elements


private static int[] xorAdjacent(int[] arr) {
int[] newArr = new int[[Link] - 1];
for (int i = 0; i < [Link] - 1; i++) {
newArr[i] = arr[i] ^ arr[i + 1]; // XOR operation
}
return newArr;
}

// Method to print the array


private static void printArray(int[] arr) {
for (int num : arr) {
[Link](num);
}
[Link](); // New line after printing the array
}
}
OUTPUT:
11110
0001
001
01
1

[Link] PRODUCT PRIZE CALCULATOR

public class PriceCalculator {


public static void main(String[] args) {
int N = 5244;
int product = 1;
int a=N;
while (N > 0) {
int digit = N % 10; // Get the last digit
product *= digit; // Multiply the digit to the product
N /= 10; // Remove thdigit
}
[Link]("The price of the item with code " + a + " is: " + product);
}
}

OUTPUT:

The price of the item with code 5244 is: 160

16. PEAK AND BOTTOM PROGRAM

import [Link];
public class New{
public static void main(String args[]){
Scanner scanner = new Scanner([Link]);
[Link]("Enter the size of the array: ");
int a=[Link]();
int[] one=new int[a];
[Link]("Enter the elements: ");
int peak = 0;
int bottom =0;
for(int i=0; i<a;i++){
one[i]=[Link]();
}
for(int i=1;i<a-1;i++){
if(one[i]>one[i+1] && one[i]>one[i-1]){
peak++;
}
if(one[i]<one[i+1] && one[i]<one[i-1]){
bottom++;
}
}
[Link]("Peak: "+peak);
[Link]("Bottom: "+bottom);
}
}

OUTPUT:

Enter the size of the array: 3


Enter the elements: 2 3 4
Peak: 0
Bottom: 0

17. ZEROS SHOULD COME END

public class New{


public static void main(String args[]){
int[] one={0,1,0,5,0,0,6,0,7,0};
int count=0; for(int i=0;i<[Link];i++){
if(one[i]!=0){
[Link](one[i]);
}
else{
count++;
}
}
for(int i=0;i<count;i++){
[Link](0);
}
}
}
OUTPUT:

1567000000

Common questions

Powered by AI

The threshold value algorithm decrements each element of the array by a specified threshold until it reaches zero. Each decrement step counts toward the total count. Iterations are required because elements may be larger than the threshold, necessitating multiple decrements to reduce them to zero .

The process starts by sorting the array and then alternately selects the highest and lowest available elements. It uses two pointers, one starting at the beginning and the other at the end of the array, printing elements from each end in turn until they meet, achieving a high-low sequence .

The algorithm employs a recursive approach to explore all possible combinations of array elements to reach a target sum. The recursive depth can be a concern if the array is large or if the target is large in relation to the values, leading to deeper recursion and potential stack overflow. Using each element only once limits the potential combinations and controls the recursion depth, increasing efficiency .

The algorithm uses two integer arrays and merges them into a single set using a TreeSet, which inherently sorts and removes duplicate values. Elements from both arrays are added to the TreeSet, and then the elements are retrieved in sorted order to form the final unique and sorted array .

The method counts non-zero elements and prints them in order, maintaining their sequence. It then appends zeros based on the count of zero elements in the array, ensuring all zeros are moved to the end without sorting the array or changing the order of non-zero elements .

In each iteration, consecutive elements are XORed to form a new, smaller array, reducing size by one at each step. This iterative reduction significantly alters the array's original data by emphasizing changes in binary bits through XOR operations, potentially leading to zero elements by obliterating matched element bits after repeated iterations .

The temporary start pointer marks potential starting points for subarrays and resets whenever a new positive subarray begins. When a subarray with a greater sum is found, these pointers provide the subarray's start and end by updating current subarray boundaries around non-negative sums, helping in achieving the maximum sum identification .

Not considering boundary conditions can lead to incorrect results or runtime errors. In the implementation, starting from the first element, which has no preceding element, avoids out-of-bound errors. This method inherently assumes the first element is valid without validation and requires comparison logic for subsequent elements .

The algorithm employs a deque to track indexes of useful elements within each window. It removes elements outside the current window and elements smaller than the current element to maintain only potential maximums. The front of the deque always contains the maximum element for the window, and it outputs the maximum value once the window has reached the desired size .

The algorithm continuously retrieves the last digit of the integer using the modulo operation, multiplies it into an accumulating product, and then removes the last digit using integer division. This continues until the integer is reduced to zero, efficiently calculating the product of its digits without explicitly storing them .

You might also like