Saturday 30 September 2017

Java method that takes an array of float values and determines if all the numbers are different from each other (that is, they are distinct).

Problem:

Write a Java method that takes an array of float values and determines if all the
numbers are different from each other (that is, they are distinct).

Solution:

package com.basics;

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class ArrayHasDistnctFloatNumbers {

float[] floatNumbers;
int arrayLimit;

public static void main(String[] args) {
ArrayHasDistnctFloatNumbers arrayHasDistnctFloatNumbers = new ArrayHasDistnctFloatNumbers();
arrayHasDistnctFloatNumbers.initializeTheArray();
System.out.println("is the given array has distinct float numbers ?? " + arrayHasDistnctFloatNumbers.distinctValues());
}

public void initializeTheArray(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the array limit");
arrayLimit = scanner.nextInt();
floatNumbers = new float[arrayLimit];
for (int i = 0; i < floatNumbers.length; i++) {
System.out.println("enter the float value");
floatNumbers[i] = scanner.nextFloat();
}

scanner.close();
}

public  boolean distinctValues(){
    Set<Float> foundNumbers = new HashSet<Float>();
    for (float num : floatNumbers) {
        if(foundNumbers.contains(num)){
            return false;
        }
        foundNumbers.add(num);
    }             
    return true;         
}

}


Output:

enter the array limit
3
enter the float value
2.34
enter the float value
4.56
enter the float value
5.67
is the given array has distinct float numbers ?? true


enter the array limit
3
enter the float value
3.45
enter the float value
4.56
enter the float value
3.45
is the given array has distinct float numbers ?? false


Java program that can take a positive integer greater than 2 as input and write out the number of times onemust repeatedly divide this number by 2 before getting a value less than 2.

Problem:

Write a Java program that can take a positive integer greater than 2 as input and
write out the number of times onemust repeatedly divide this number by 2 before
getting a value less than 2.

Solution:

package com.basics;

import java.util.Scanner;

public class CountTheNumberOfDivisibles {

int number;

public static void main(String[] args) {
CountTheNumberOfDivisibles countTheNumberOfDivisibles = new CountTheNumberOfDivisibles();
countTheNumberOfDivisibles.getTheNumber();
System.out.println("the number of times one must repeatedly divide this number by 2 is: " + countTheNumberOfDivisibles.countTheNumberOfDivisibles());

}

public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the number greater than 2");
number = scanner.nextInt();
if(number < 2){
number = 0;
System.out.println("the given number is less than 2. please give the number greater than 2");
}
scanner.close();
}

public int countTheNumberOfDivisibles(){
int count = 0;
while(true){
if(number < 2){
break;
}
else {
number = number - 2;
count++;
}
}
return count;
}

}


Output:
enter the number greater than 2
127
the number of times one must repeatedly divide this number by 2 is: 63





Java method that takes an array of int values and determines if there is a pair of distinct elements of the array whose product is even

Problem:

Write a short Java method that takes an array of int values and determines if there
is a pair of distinct elements of the array whose product is even.

Solution:

package com.basics;

import java.util.Scanner;

public class FindProductOfArrayDistinctElements {

int numberArray[];
int arrayLimit;

public static void main(String[] args) {
FindProductOfArrayDistinctElements findProductOfArrayDistinctElements = new FindProductOfArrayDistinctElements();
findProductOfArrayDistinctElements.initializeArray();
System.out.println("is the given array contains a pair of distinct elements whose product is even. " + findProductOfArrayDistinctElements.isEvenProduct());
}

public void initializeArray(){
Scanner scanner = new Scanner(System.in);
System.out.println("how many numbers you want to store in an array");
arrayLimit = scanner.nextInt();
numberArray = new int[arrayLimit];
for (int i = 0; i < numberArray.length; i++) {
System.out.println("enter the number");
numberArray[i] = scanner.nextInt();
}
scanner.close();
}

public boolean isEvenProduct(){
boolean isEvenProduct = false;
for (int i = 0; i < numberArray.length; i++) {
for (int j = 1; j < numberArray.length; j++) {
if(numberArray[i] != numberArray[j] && ((numberArray[i] * numberArray[j]) % 2 == 0)){
isEvenProduct = true;
}
}
}
return isEvenProduct;
}


}


Output:

how many numbers you want to store in an array
3
enter the number
3
enter the number
5
enter the number
3
is the given array contains a pair of distinct elements whose product is even. false


how many numbers you want to store in an array
3
enter the number
2
enter the number
4
enter the number
2
is the given array contains a pair of distinct elements whose product is even. true


how many numbers you want to store in an array
2
enter the number
2
enter the number
2
is the given array contains a pair of distinct elements whose product is even. false


how many numbers you want to store in an array
5
enter the number
3
enter the number
3
enter the number
3
enter the number
3
enter the number
3
is the given array contains a pair of distinct elements whose product is even. false


Friday 29 September 2017

Java program that takes as input three integers, a, b, and c, from the Java console and determines if they can be used in a correct arithmetic formula.

Problem:

Write a short program that takes as input three integers, a, b, and c, from the Java
console and determines if they can be used in a correct arithmetic formula (in the
given order), like “a+b = c,” “a = b−c,” or “a ∗ b = c.”

Solution:

package com.basics;

import java.io.ObjectInputStream.GetField;
import java.util.Scanner;

public class FormulaFormation {

static int a;
static int b;
static int c;

public static void main(String[] args) {
FormulaFormation arithmeticFormula = new FormulaFormation();
arithmeticFormula.getTheNumber();
float value = 1;
int oper2Range;
for (int i = 0; i < 4; i++) {
if (i < 2)
oper2Range = 4;
else
oper2Range = 2;
for (int j = 0; j < oper2Range; j++)
if ((value = valueOf(a, b, c, i, j)) == 0) {
System.out.print("Your inputs can form the equation: ");
displayEquation(i, j);
break;
}
}
if (value != 0)
System.out.println("Your inputs can't form any equation.");
}

private static float valueOf(int a, int b, int c, int oper1, int oper2) {
if (oper2 == 2 || oper2 == 3)
return calculate(a, calculate(b, c, oper2), oper1);
else
return calculate(c, calculate(a, b, oper1), oper2);
}

private static float calculate(float x, float y, int oper) {
switch (oper) {
case 0:
return x + y;
case 1:
return x - y;
case 2:
return x * y;
default:
return (float) x / y;
}
}

private static void displayEquation(int oper1, int oper2) {
if (oper1 == 0 || oper1 == 1)
// a +- b */ c = 0 -> a = -+ b * c
if (oper2 == 2 || oper2 == 3)
System.out.printf("a = %cb %c c\n",
(toChar(oper1) == '+') ? '-' : '\u0000', toChar(oper2));
// a +- b +- c = 0 -> a +- b = -+ c
else
System.out.printf("a %c b = %cc\n", toChar(oper1),
(toChar(oper2) == '+') ? '-' : '\u0000');
// a */ b +- c = 0 -> a */b = -+ c
else
System.out.printf("a %c b = %cc\n", toChar(oper1),
(toChar(oper2) == '+') ? '-' : '\u0000');
}


private static char toChar(int operator) {
switch (operator) {
case 0:
return '+';
case 1:
return '-';
case 2:
return '*';
default:
return '/';
}
}

public void getTheNumber() {
Scanner scanner = new Scanner(System.in);
System.out.println("enter number a: ");
a = scanner.nextInt();
System.out.println("enter number b: ");
b = scanner.nextInt();
System.out.println("enter number c: ");
c = scanner.nextInt();
scanner.close();
}

}


Output:

enter number a:
1
enter number b:
1
enter number c:
1
Your inputs can form the equation: a = b * c
Your inputs can form the equation: a * b = c
Your inputs can form the equation: a / b = c

Java method that uses a StringBuilder instance to remove all the punctuation from a string s storing a sentence

Problem:

Write a short Java method that uses a StringBuilder instance to remove all the
punctuation from a string s storing a sentence

Solution:

package com.basics;

import java.util.Scanner;

public class RemovePunctuationFromAString {

String sentence = "";

public static void main(String[] args) {
RemovePunctuationFromAString removePunctuationFromAString = new RemovePunctuationFromAString();
removePunctuationFromAString.getTheNumber();
System.out.println("After removing all the punctuations: " + removePunctuationFromAString.removePunctuation());

}

public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter a sentence with punctuation");
sentence = scanner.nextLine();
scanner.close();
}

public String removePunctuation(){
StringBuilder outputStr = new StringBuilder();
char[] characters = sentence.toCharArray();
int asciiValue = 0;
for (int i = 0; i < characters.length; i++) {
asciiValue = (int)characters[i];
if(!(asciiValue > 32 && asciiValue < 48)){
outputStr.append(characters[i]);
}
}

return outputStr.toString();
}

}


Output:

enter a sentence with punctuation
Let's try, Mike!
After removing the all punctuations: Lets try Mike


Java method that counts the number of vowels in a given character string.

Problem:

Write a short Java method that counts the number of vowels in a given character
string.

Solution:

package com.basics;

import java.util.Scanner;

public class CountTheNumberOfVowels {

String word = "";

public static void main(String[] args) {
CountTheNumberOfVowels countTheNumberOfVowels = new CountTheNumberOfVowels();
countTheNumberOfVowels.getTheNumber();
System.out.println("the number of vowels in a given character string is: " + countTheNumberOfVowels.countVowels());

}

public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter a word");
word = scanner.next();
scanner.close();
}

public int countVowels(){
int numberOfVowels = 0;
char[] characters = word.toLowerCase().toCharArray();
for (int i = 0; i < characters.length; i++) {
if(characters[i] == 'a' || characters[i] == 'e' || characters[i] == 'i' || characters[i] == 'o' || characters[i] == 'u'){
numberOfVowels ++;
}
}
return numberOfVowels;
}

}


Output:

enter a word
Banglore
the number of vowels in a given character string is: 3


Java method that takes an integer n and returns the sum of the squares of all positive integers less than or equal to n.

Problem:

Write a short Java method that takes an integer n and returns the sum of the
squares of all positive integers less than or equal to n.

Solution:

package com.basics;

import java.util.Scanner;

public class SumOfSquares {

static int number;

public static void main(String[] args) {
SumOfSquares findSum = new SumOfSquares();
findSum.getTheNumber();
System.out.println("the sum of the squares of all positive integers less than or equal to n is:  " + findSum.findSum(number));

}

public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the number");
number = scanner.nextInt();
scanner.close();
}

public int findSum(int number){
int sum = 0;
for (int i = 1; i <= number; i++) {
sum = sum + (i * i);
}
return sum;
}

}


Output:

enter the number
4
the sum of the squares of all positive integers less than or equal to n is:  30


Java method that takes an integer n and returns the sum of all the odd positive integers less than or equal to n.

Problem:

Write a short Java method that takes an integer n and returns the sum of all the
odd positive integers less than or equal to n.

Solution:

package com.basics;

import java.util.Scanner;

public class SumOfOddPositiveIntegers {

static int number;
int oddNumbers[];

public static void main(String[] args) {
SumOfOddPositiveIntegers findSum = new SumOfOddPositiveIntegers();
findSum.getTheNumber();
findSum.findOddNumbers(number);
System.out.println("the odd numbers are");
findSum.printOddNumbers();
System.out.println();
System.out.println("the sum of all odd positive integers less than or equal to n is:  " + findSum.findSum());

}

public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the number");
number = scanner.nextInt();
oddNumbers = new int[number/2  + 1];
scanner.close();
}

public int findSum(){
int sum = 0;
for (int i = 0; i < oddNumbers.length; i++) {
sum = sum + oddNumbers[i];
}
return sum;
}

public void findOddNumbers(int n){
int j = 0;
for (int i = 1; i <= n; i++) {
if((i % 2) != 0){
oddNumbers[j++] = i;
}
}
}

public void printOddNumbers(){
for (int i = 0; i < oddNumbers.length; i++) {
System.out.print(oddNumbers[i] + " ");
}
}

}


Output:

enter the number
6
the odd numbers are
1 3 5 0
the sum of all odd positive integers less than or equal to n is:  9

enter the number
15
the odd numbers are
1 3 5 7 9 11 13 15 
the sum of all odd positive integers less than or equal to n is:  64


Java method that takes an integer n and returns the sum of all positive integers less than or equal to n.

Problem:

Write a short Java method that takes an integer n and returns the sum of all
positive integers less than or equal to n.

Solution:

package com.basics;

import java.util.Scanner;

public class FindSum {

static int number;

public static void main(String[] args) {
FindSum findSum = new FindSum();
findSum.getTheNumber();
System.out.println("the sum of all positive integers less than or equal to n is:  " + findSum.findSum(number));

}

public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the number");
number = scanner.nextInt();
scanner.close();
}

public int findSum(int number){
int sum = 0;
for (int i = 1; i <= number; i++) {
sum = sum + i;
}
return sum;
}

}


Output:

enter the number
10

the sum of all positive integers less than or equal to n is:  55


Java Method to find the given number is even or not without using multiplication, division and modulus operators.

Problem:

Write a short Java method, isEven, that takes an int i and returns true if and only
if i is even. Your method cannot use the multiplication, modulus, or division
operators, however.

Solution:

package com.basics;

import java.util.Scanner;

public class EvenOperations {

static int number;

public static void main(String[] args) {
EvenOperations evenOperations = new EvenOperations();
evenOperations.getTheNumber();
if(evenOperations.isEvenNumber(number)){
System.out.println("the given number is even number");
}
else {
System.out.println("the given number is not even number");
}

}

public void getTheNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the number");
number = scanner.nextInt();
scanner.close();
}

public boolean isEvenNumber(int number){
boolean isEvenNumber = false;
while(true){
number = number - 2;
if(number == 0){
isEvenNumber = true;
break;
}
else if(number == -1){
break;
}
}
return isEvenNumber;
}

}


Output:

enter the number
1222223
the given number is not even number

enter the number
234
the given number is even number

Tuesday 12 September 2017

Java Code for Binary Search

Problem:

Given an element x and a set of data that is in strictly ascending numerical order find whether or not x is preset in the set.

Solution:

package array.programs;

import java.util.Arrays;
import java.util.Scanner;

public class BinarySearch {

int[] array;
int lower;
int middle;
int upper;
int searchElement;
int arrayLimit;

public static void main(String[] args) {
BinarySearch binarySearch = new BinarySearch();
binarySearch.initializeTheArray();
int result = binarySearch.doBinarySearch(0, binarySearch.arrayLimit - 1);
        if (result == -1)
            System.out.println("Element not present");
        else
            System.out.println("Element found at index "+result);
}

private void initializeTheArray(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the array elements limit");
arrayLimit = scanner.nextInt();
array = new int[arrayLimit];
for (int i = 0; i < array.length; i++) {
System.out.println("enter the element");
array[i] = scanner.nextInt();
}

System.out.println("enter the element which need to be found");
searchElement = scanner.nextInt();
scanner.close();
Arrays.sort(array);
}

private int doBinarySearch(int lowerLimit, int upperLimit){
while(lowerLimit <=  upperLimit){
int middleIndex = lowerLimit + (upperLimit - lowerLimit) / 2;
if(array[middleIndex] == searchElement){
return middleIndex;
}
if(array[middleIndex] < searchElement ){
lowerLimit = middleIndex + 1;
}
else {
upperLimit = middleIndex - 1;
}
}
return -1;
}
}


Output:

enter the array elements limit
5
enter the element
3
enter the element
23
enter the element
43
enter the element
44
enter the element
55
enter the element which need to be found
44
Element found at index 3

Saturday 9 September 2017

Java Code for quick Sort

Problem:

Java Code for quick Sort

Solution:

package array.programs;

public class MyQuickSort {
private int array[];
    private int length;

    public void sort(int[] inputArr) {
       
        if (inputArr == null || inputArr.length == 0) {
            return;
        }
        this.array = inputArr;
        length = inputArr.length;
        quickSort(0, length - 1);
    }

    private void quickSort(int lowerIndex, int higherIndex) {
       
        int i = lowerIndex;
        int j = higherIndex;
        // calculate pivot number, I am taking pivot as middle index number
        int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
        // Divide into two arrays
        while (i <= j) {
            /**
             * In each iteration, we will identify a number from left side which
             * is greater then the pivot value, and also we will identify a number
             * from right side which is less then the pivot value. Once the search
             * is done, then we exchange both numbers.
             */
            while (array[i] < pivot) {
                i++;
            }
            while (array[j] > pivot) {
                j--;
            }
            if (i <= j) {
                exchangeNumbers(i, j);
                //move index to next position on both sides
                i++;
                j--;
            }
        }
        // call quickSort() method recursively
        if (lowerIndex < j)
            quickSort(lowerIndex, j);
        if (i < higherIndex)
            quickSort(i, higherIndex);
    }

    private void exchangeNumbers(int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
   
    public static void main(String a[]){
       
        MyQuickSort sorter = new MyQuickSort();
        int[] input = {24,2,45,20,56,75,2,56,99,53,12};
        sorter.sort(input);
        for(int i:input){
            System.out.print(i);
            System.out.print(" ");
        }
    }
}


Output:

2 2 12 20 24 45 53 56 56 75 99

Java Code for shell sort

Problem:

Java Code for Shell Sort

Solution:

package array.programs;

import java.util.Arrays;

public class ShellSort {

private static int ia[] = { 1, 54, 6, 3, 78, 34, 12, 45, 56, 3 };

private static int[] shellSort(int[] a) {
//the increment;
int step = a.length / 2;

// The result has mostly sorted at the previous step of step=1;
//Just change the condition step> = 1 to step > 1 if you want to observe it ;
while (step >= 1) {

for (int i = step; i <a.length; i++) {
int temp = a[i];
int j;

// use insert sort to sort the part of a;
for (j = i - step; j >= 0 && a[j] > temp; j -= step) {
a[j + step] = a[j];
}
a[j + step] = temp;
}
//narrow the increment.
step = step / 2;
}
return a;
}


public static void main(String[] args) {
System.out.println(Arrays.toString(shellSort(ia)));
}
}


Output:

[1, 3, 3, 6, 12, 34, 45, 54, 56, 78]


Friday 8 September 2017

Java code to sort an array by using insertion sort

Problem:

Java code to sort an array by using insertion sort


Solution:

package array.programs;

public class InsertionSort {
public static void main(String []args) {

int[] arr1 = {11,35,21,56,7,67,88,42};
        int[] arr2 = doInsertionSort(arr1);
        for(int i:arr2){
            System.out.print(i);
            System.out.print(", ");
        }
}
        public static int[] doInsertionSort(int[] input){
           
            int temp;
            for (int i = 1; i < input.length; i++) {
                for(int j = i ; j > 0 ; j--){
                    if(input[j] < input[j-1]){
                        temp = input[j];
                        input[j] = input[j-1];
                        input[j-1] = temp;
                    }
                }
            }
            return input;
        }
}


Output:

7, 11, 21, 35, 42, 56, 67, 88,

Wednesday 6 September 2017

Java Code to reverse an array using bubble sort

Problem:

Design and implement a bubble sort that incorporates exchange in the reverse direction of fixed lenght

Solution:

package array.programs;

public class BubbleSort {
public static void main(String []args) {

     int[] array = {10,8,6,4,2,9,7,5,3,1};

     System.out.print("Before sort: " );    
     for(int x = 0; x < array.length; x++) {
        System.out.print( " " + array[x]);    
     }
     System.out.println(" ");    

     int remaining = array.length - 1;
     for(int x = 0; x < (array.length-1); x++) {
        for(int y = 0; y < (remaining); y++) {
           int tmp;
           if ( array[y] < array[y+1] ) {
             tmp =  array[y+1];
             array[y+1] = array[y];
             array[y] = tmp;
           }
        }
        remaining--;
     }

     System.out.print("After sort: " );    
     for(int x = 0; x < array.length; x++) {
        System.out.print( " " + array[x]);    
     }
     System.out.println(" ");    
  }
}


Output:

Before sort:  10 8 6 4 2 9 7 5 3 1
After sort:  10 9 8 7 6 5 4 3 2 1


Java Code to sort an array by using bubble sort

Problem:

Given a randomly ordered set of n numbers sort them into non-descending order using bubble sort method.

Solution:

package array.programs;

public class BubbleSort {
public static void main(String []args) {

     int[] array = {10,8,6,4,2,9,7,5,3,1};

     System.out.print("Before sort: " );    
     for(int x = 0; x < array.length; x++) {
        System.out.print( " " + array[x]);    
     }
     System.out.println(" ");    

     int remaining = array.length - 1;
     for(int x = 0; x < (array.length-1); x++) {
        for(int y = 0; y < (remaining); y++) {
           int tmp;
           if ( array[y] > array[y+1] ) {
             tmp =  array[y+1];
             array[y+1] = array[y];
             array[y] = tmp;
           }
        }
        remaining--;
     }

     System.out.print("After sort: " );    
     for(int x = 0; x < array.length; x++) {
        System.out.print( " " + array[x]);    
     }
     System.out.println(" ");    
  }
}

Output:

Before sort:  10 8 6 4 2 9 7 5 3 1
After sort:  1 2 3 4 5 6 7 8 9 10

Java Code to sort an array by exchange method

Problem:

Given a randomly ordered set of n numbers sort them into non-descending order using an exchange method.

Solution:

package array.programs;

import java.util.Scanner;

public class SortByExchange {

int[] array;
int limit;

public static void main(String[] args) {
SortByExchange sortByExchange = new SortByExchange();
sortByExchange.initilizeTheArray();
sortByExchange.doSort();
sortByExchange.printTheArray();
}

public void initilizeTheArray(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the first array elements limit");
limit = scanner.nextInt();
array = new int[limit];
for (int i = 0; i < array.length; i++) {
System.out.println("enter the element");
array[i] = scanner.nextInt();
}
scanner.close();
}

public void doSort(){
int temp = 0;
for (int i = 0; i < array.length - 1; i++) {
for (int j = i + 1 ; j < array.length; j++) {
if(array[j] < array[i]){
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
}

public void printTheArray(){
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}


Output:

enter the first array elements limit
10
enter the element
23
enter the element
4
enter the element
2
enter the element
345
enter the element
32
enter the element
44
enter the element
5555
enter the element
33
enter the element
34
enter the element
555
2 4 23 32 33 34 44 345 555 5555 

Monday 4 September 2017

Java Code to find the array is in non-descending order or not

Problem:

Implement a function that examines an array and returns the Boolean value sorted which is true if the array is in non-descending order and false otherwise.

Solution:

package array.programs;

import java.util.Scanner;

public class FindTheArraySortedorNot {

int[] array;
int limit;

public static void main(String[] args) {
FindTheArraySortedorNot findTheArraySortedorNot = new FindTheArraySortedorNot();
findTheArraySortedorNot.initilizeTheArray();
findTheArraySortedorNot.printTheArray();
System.out.println();
System.out.println("is sorted array in ascending order?? " + findTheArraySortedorNot.isSortedArray(findTheArraySortedorNot.array));
}

public void initilizeTheArray(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the array elements limit");
limit = scanner.nextInt();
array = new int[limit];
for (int i = 0; i < array.length; i++) {
System.out.println("enter the element");
array[i] = scanner.nextInt();
}
scanner.close();
}

public void printTheArray(){
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}

public boolean isSortedArray(int[] array){
boolean isSortedArray = true;
for (int i = 0; i < array.length - 1; i++) {
for(int j = i+1; j < array.length; j++){
if(array[i] > array[j]){
isSortedArray = false;
break;
}
if(!isSortedArray){
break;
}
}
}
return isSortedArray;
}

}


Output:

enter the array elements limit
5
enter the element
23
enter the element
34
enter the element
45
enter the element
56
enter the element
67
23 34 45 56 67
is sorted array in ascending order?? true


enter the array elements limit
5
enter the element
23
enter the element
33
enter the element
4
enter the element
33
enter the element
22
23 33 4 33 22 
is sorted array in ascending order?? false

Java Code to remove the duplicate elements in an ordered array

Problem:

Remove the duplicate elements from an ordered array which are sorted by using selection sort.

Solution:

package array.programs;

import java.util.Arrays;
import java.util.Scanner;

public class RemoveDuplicatesUsingSelectionSort {

int[] array;
int limit;

public static void main(String[] args) {
RemoveDuplicatesUsingSelectionSort selectionSort = new RemoveDuplicatesUsingSelectionSort();
selectionSort.initilizeTheArray();
selectionSort.doSelectionSort();
selectionSort.removeDuplicates(selectionSort.array);
selectionSort.printTheArray();

}

public void initilizeTheArray(){
Scanner scanner = new Scanner(System.in);

System.out.println("enter the first array elements limit");
limit = scanner.nextInt();
array = new int[limit];
for (int i = 0; i < array.length; i++) {
System.out.println("enter the element");
array[i] = scanner.nextInt();
}
scanner.close();
}

public void doSelectionSort(){
int position = 0;
int temp = 0;
for (int i = 0; i < array.length - 1; i++) {
position = i;
for (int j = i + 1; j < array.length; j++) {
if(array[position] > array[j]){
position = j;
}
}

temp = array[position];
array[position] = array[i];
array[i] = temp;
}
}

public void removeDuplicates(int[] numbers){
Arrays.sort(numbers);
int j = 0;
int[] temp = new int[numbers.length];
for (int i = 0; i < numbers.length - 1; i++) {
if(numbers[i] != numbers[i+1]){
temp[j++] = numbers[i];
}
}
temp[j++] = numbers[numbers.length - 1];
for (int i = 0; i < temp.length; i++) {
numbers[i] = temp[i];
}
}

public void printTheArray(){
for (int i = 0; i < array.length; i++) {
System.out.print( array[i] + " ");
}
}

}


Output:

enter the first array elements limit
5
enter the element
22
enter the element
33
enter the element
2
enter the element
33
enter the element
2
2 22 33 0 0


Java Code for selection sort in descending order

Problem:

Sort an array into descending order.

Solution:

package array.programs;

import java.util.Scanner;

public class SelectionSortForDescendingOrder {

int[] array;
int limit;

public static void main(String[] args) {
SelectionSortForDescendingOrder selectionSort = new SelectionSortForDescendingOrder();
selectionSort.initilizeTheArray();
selectionSort.doSelectionSort();
selectionSort.printTheArray();

}

public void initilizeTheArray(){
Scanner scanner = new Scanner(System.in);

System.out.println("enter the first array elements limit");
limit = scanner.nextInt();
array = new int[limit];
for (int i = 0; i < array.length; i++) {
System.out.println("enter the element");
array[i] = scanner.nextInt();
}
scanner.close();
}

public void doSelectionSort(){
int position = 0;
int temp = 0;
for (int i = 0; i < array.length - 1; i++) {
position = i;
for (int j = i + 1; j < array.length; j++) {
if(array[position] < array[j]){
position = j;
}
}

temp = array[position];
array[position] = array[i];
array[i] = temp;
}
}

public void printTheArray(){
for (int i = 0; i < array.length; i++) {
System.out.print( array[i] + " ");
}
}

}


Output:

enter the first array elements limit
8
enter the element
20
enter the element
35
enter the element
18
enter the element
8
enter the element
14
enter the element
41
enter the element
3
enter the element
39
41 39 35 20 18 14 8 3 

Java Code for sorting by selection

Problem:

Given a randomly ordered set of n integers, sort them into non-descending order using the selection sort.

Solution:

package array.programs;

import java.util.Scanner;

public class SelectionSort {

int[] array;
int limit;

public static void main(String[] args) {
SelectionSort selectionSort = new SelectionSort();
selectionSort.initilizeTheArray();
selectionSort.doSelectionSort();
selectionSort.printTheArray();

}

public void initilizeTheArray(){
Scanner scanner = new Scanner(System.in);

System.out.println("enter the first array elements limit");
limit = scanner.nextInt();
array = new int[limit];
for (int i = 0; i < array.length; i++) {
System.out.println("enter the element");
array[i] = scanner.nextInt();
}
scanner.close();
}

public void doSelectionSort(){
int position = 0;
int temp = 0;
for (int i = 0; i < array.length - 1; i++) {
position = i;
for (int j = i + 1; j < array.length; j++) {
if(array[position] > array[j]){
position = j;
}
}

temp = array[position];
array[position] = array[i];
array[i] = temp;
}
}

public void printTheArray(){
for (int i = 0; i < array.length; i++) {
System.out.print( array[i] + " ");
}
}

}


Output:

enter the first array elements limit
10
enter the element
23
enter the element
455
enter the element
65
enter the element
43
enter the element
1
enter the element
3
enter the element
456
enter the element
778
enter the element
98
enter the element
66
1 3 23 43 65 66 98 455 456 778 

Java Code to merge three arrays.

Problem:

Design and implement an algorithm for three arrays.

Solution:

package array.programs;

import java.util.Scanner;

public class MergeThreeArrays {

int[] firstArray;
int[] secondArray;
int[] thirdArray;
int[] resultArray;
int[] resultArray2;
int firstArrayLimit;
int secondArrayLimit;
int thirdArrayLimit;

public static void main(String[] args) {
MergeThreeArrays mergeArrays = new MergeThreeArrays();
mergeArrays.initializeTheArray();
mergeArrays.mergeArrays(mergeArrays.firstArray, mergeArrays.secondArray, mergeArrays.firstArrayLimit, mergeArrays.secondArrayLimit, mergeArrays.resultArray);
mergeArrays.mergeArrays(mergeArrays.resultArray, mergeArrays.thirdArray, mergeArrays.resultArray.length, mergeArrays.thirdArrayLimit, mergeArrays.resultArray2);
mergeArrays.printTheArray();
}

public void initializeTheArray(){
Scanner scanner = new Scanner(System.in);

System.out.println("enter the first array elements limit");
firstArrayLimit = scanner.nextInt();
firstArray = new int[firstArrayLimit];
for (int i = 0; i < firstArray.length; i++) {
System.out.println("enter the element");
firstArray[i] = scanner.nextInt();
}

System.out.println("enter the second array elements limit");
secondArrayLimit = scanner.nextInt();
secondArray = new int[secondArrayLimit];
for (int i = 0; i < secondArray.length; i++) {
System.out.println("enter the number");
secondArray[i] = scanner.nextInt();
}

System.out.println("enter the third array elements limit");
thirdArrayLimit = scanner.nextInt();
thirdArray = new int[thirdArrayLimit];
for (int i = 0; i < thirdArray.length; i++) {
System.out.println("enter the number");
thirdArray[i] = scanner.nextInt();
}

resultArray = new int[firstArrayLimit + secondArrayLimit];
resultArray2 = new int[resultArray.length + thirdArrayLimit];
scanner.close();

}

public void mergeArrays(int[] arrayOne, int[] arrayTwo, int n1, int n2, int[] outputArray){
int i = 0;
int j = 0;
int k = 0;
while (i < n1 && j < n2 ) {
if(arrayOne[i] < arrayTwo[j]){
outputArray[k++] = arrayOne[i++];
}
else {
outputArray[k++] = arrayTwo[j++];
}
}

while(i < n1){
outputArray[k++] = arrayOne[i++];
}

while(j < n2){
outputArray[k++] = arrayTwo[j++];
}
}

public void printTheArray(){
for (int i = 0; i < resultArray2.length; i++) {
System.out.print( resultArray2[i] + " ");
}
}

}


Output:

enter the first array elements limit
2
enter the element
1
enter the element
2
enter the second array elements limit
2
enter the number
3
enter the number
4
enter the third array elements limit
2
enter the number
5
enter the number
6
1 2 3 4 5 6

Sunday 3 September 2017

Java Code to merge two files

Problem:

Design and implement a merging  algorithm that reads the data sets from two files of known length.


Solution:

package array.programs;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MergeTwoFiles {

File file1;
File file2;
File resultFile;

List<String> firstFileData = new ArrayList<String>();
List<String> secondFileData = new ArrayList<String>();

public static void main(String[] args) throws IOException {
MergeTwoFiles mergeTwoFiles = new MergeTwoFiles();
mergeTwoFiles.mergeFiles();
}

public void mergeFiles() throws IOException{
file1 = new File("D:\\hemanth\\DS&Al\\Programs\\src\\array\\programs\\file1.txt");
file2 = new File("D:\\hemanth\\DS&Al\\Programs\\src\\array\\programs\\file2.txt");
resultFile = new File("D:\\hemanth\\DS&Al\\Programs\\src\\array\\programs\\resultFile.txt");

FileReader fileReader = new FileReader(file1);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String data;
while ((data = bufferedReader.readLine()) != null) {
firstFileData.add(data);
}

fileReader = new FileReader(file2);
bufferedReader = new BufferedReader(fileReader);

while ((data = bufferedReader.readLine()) != null) {
secondFileData.add(data);
}

FileWriter fileWriter = new FileWriter(resultFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
for(String str: firstFileData){
bufferedWriter.write(str);
bufferedWriter.write("\n");
}

for(String str: secondFileData){
bufferedWriter.write(str);
bufferedWriter.write("\n");
}
bufferedReader.close();
bufferedWriter.close();
}

}





Friday 1 September 2017

Java Code to Merge Two Arrays

Problem:

Merge two arrays of integers, both with their elements in ascending order, into a single ordered array.

Solution:

package array.programs;

import java.util.Scanner;

public class MergeTwoArrays {

int[] firstArray;
int[] secondArray;
int[] resultArray;
int firstArrayLimit;
int secondArrayLimit;

public static void main(String[] args) {
MergeTwoArrays mergeTwoArrays = new MergeTwoArrays();
mergeTwoArrays.initializeTheArray();
mergeTwoArrays.mergaTwoArrays();
mergeTwoArrays.printTheArray();
}

public void initializeTheArray(){
Scanner scanner = new Scanner(System.in);

System.out.println("enter the first array elements limit");
firstArrayLimit = scanner.nextInt();
firstArray = new int[firstArrayLimit];
for (int i = 0; i < firstArray.length; i++) {
System.out.println("enter the element");
firstArray[i] = scanner.nextInt();
}

System.out.println("enter the second array elements limit");
secondArrayLimit = scanner.nextInt();
secondArray = new int[secondArrayLimit];
for (int i = 0; i < secondArray.length; i++) {
System.out.println("enter the number");
secondArray[i] = scanner.nextInt();
}

resultArray = new int[firstArrayLimit + secondArrayLimit];

scanner.close();

}

public void mergaTwoArrays(){
int i = 0;
int j = 0;
int k = 0;
while (i < firstArrayLimit && j < secondArrayLimit) {
if(firstArray[i] < secondArray[j]){
resultArray[k++] = firstArray[i++];
}
else{
resultArray[k++] = secondArray[j++];
}

}

while(i < firstArrayLimit){
resultArray[k++] = firstArray[i++];
}

while(j < secondArrayLimit){
resultArray[k++] = secondArray[j++];
}
}

public void printTheArray(){
for (int i = 0; i < resultArray.length; i++) {
System.out.print( resultArray[i] + " ");
}
}

}


Output:

enter the first array elements limit
4
enter the element
15
enter the element
18
enter the element
42
enter the element
51
enter the second array elements limit
8
enter the number
8
enter the number
11
enter the number
16
enter the number
17
enter the number
44
enter the number
58
enter the number
71
enter the number
74
8 11 15 16 17 18 42 44 51 58 71 74 

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...