Tag Archives: Java Program

[Java] Print characters having prime frequencies in order of occurrence.


Question : Print characters having prime frequencies in order of occurrence

Given a string str containing only lowercase characters. The task is to print the characters having prime frequency in the order of their occurrence. Note that repeated elements with prime frequencies are printed as many times as they occur in order of their occurrence.

Examples:

  • Input: str = “facingissuesonit”
    Output: facingissuesonit Frequency
    ‘f’ 1
    ‘a’ 1
    ‘c’ 1
    ‘i’ 3
    ‘n’ 2
    ‘g’ 1
    ‘s’ 3
    ‘u’ 1
    ‘e’ 1
    ‘o’ 1
    ‘t’ 1

    ‘i’, ‘n’ and ‘s’ are the only characters with prime frequencies.
    Output: insinsis

  • Input: str = “aeroplane”
    Output: aeae

Algorithm

  • Step 1: Ask the user to input String
  • Step 2: Get count of each character occurrence and insert in character-based sorted map
  • Step 3: Remove Character those occurrences are not Prime
  • Step 4: Print Character in alphabetical order and reduce the count by one
  • Step 5: Remove an entry from the map if the count is zero
  • Step 6: Repeat step 4 and 5 until map get empty

Java Program

 

public class Program2 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
System.out.print("Enter a text String: ");
String inputStr = input.nextLine();
System.out.println("Result :" + primePlacesString(inputStr));
}

private static List primePlacesString(String inputStr) {
List charList = null;
char[] chars = inputStr.toCharArray();
// Enter Character and respected occurence in map
TreeMap map = new TreeMap();
for (Character c : chars) {
if (map.get(c) == null) {
map.put(c, 1);
} else {
map.put(c, map.get(c).intValue() + 1);
}
}
// Removed character those occurence are not prime
Character[] keys = (Character[]) map.keySet().toArray(new Character[map.size()]);
for (Character key : keys) {
if (!isPrimeNumber(map.get(key))) {
map.remove(key);
}
}
// get list of character in sequence as per counts
if (map != null && !map.isEmpty()) {
charList = new ArrayList();
printMapInSquence(map, charList);
}
return charList;
}

// Code to check number is prime or not
private static boolean isPrimeNumber(Integer number) {
boolean isPrimeNumber = true;
if (number == 0 || number == 1) {
isPrimeNumber = false;
} else {
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
isPrimeNumber = false;
break;
}
}
}

return isPrimeNumber;
}

private static void printMapInSquence(Map map, List charList) {
if (map != null && !map.isEmpty()) {

Character[] keys = (Character[]) map.keySet().toArray(new Character[map.size()]);
for (Character key : keys) {
charList.add(key);
if (map.get(key) == 1) {
// remove characters those are already printed and count are 1
map.remove(key);
} else {
// reduce counts of printed characters and counts more than one
map.put(key, map.get(key) - 1);
}
}
printMapInSquence(map, charList);
}
}

}

Output


Enter a text String: facingissuesonit
Result :[i, n, s, i, n, s, i, s]

Enter a text String: aeroplane
Result :[a, e, a, e]

Java Program : Get all possible values of X such that A % X = B


Question:  Write a java program to get  all possible values of X such that A % X = B. Input two integers A and B. The task is to find the  all possible values X such that A % X = B. If there are infinite number of possible values then print -1.

Examples:

  1. Input: A = 21, B = 5
    Output: 2
    8 and 16 are the only valid values for X.
  2. Input: A = 5, B = 5
    Output: -1
    X can have any value > 5

Algorithm

  • Step 1: Ask the user to input values of A and B
  • Step 2: Find out all possible factors of (A-B) which are greater than B
  • Step 3: Use StringJoiner to print the possible value in comma separated form.

Java Program

public class Program1 {
public static void main(String[] args) {
System.out.println("Enter values of A and B to get possible values of X from expression A % X = B");

Scanner input = new Scanner(System.in);
System.out.print("Please Enter an integer A: ");
int A = input.nextInt();

System.out.print("Please Enter an integer B: ");
int B = input.nextInt();

System.out.println("Possible Values of X :" + getAllowedValues(A, B));
}

private static String getAllowedValues(int A, int B) {
//Use to print value in comma separated form
StringJoiner joiner = new StringJoiner(",");

if (A - B > 0) {
//find out all possible factor of(A-B) which are greater than B
for (int C = (A - B); C > 0 & C > B; C /= 2) {
if ((A - B) % C == 0)
joiner.add(Integer.toString(C));
}
} else {
joiner.add("-1");
}
return joiner.toString();
}

}

Output


Enter values of A and B to get possible values of X from expression A % X = B
Please Enter an integer A: 21
Please Enter an integer B: 5
Possible Values of X :16,8

Enter values of A and B to get possible values of X from expression A % X = B
Please Enter an integer A: 5
Please Enter an integer B: 5
Possible Values of X :-1

Frequently Asked Algorithms & Java Programs


Below are most frequently asked algorithms and programs in interview to test interviewee programming and logical skill. These question can be asked with fresher and any senior level programmers to check hands on with the code or not.

  1. Write a program to print alphabet using java loop
    Output:
    a b c d e f g h i j k l m n o p q r s t u v w x y z
    a b c d e f g h i j k l m n o p q r s t u v w x y z
    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
  2. Write a program to check odd or even number.
    Input:  5
    Output: Odd Number
  3. Write a program to convert Fahrenheit to Celsius.
    Input: 50
    Output: 10.0
  4. Write a java program to print fibonacci series without using recursion and using recursion.
    Input: 12
    Output: 0 1 1 2 3 5 8 13 21 34 55 89 144
  5. Write a java program to check prime number.
    Input: 42
    Output: Not prime number
    Input: 13
    Output: Prime number
  6. Write a java program to check palindrome number.
    Input: 349
    Output: Not palindrome number
    Input: 1234321
    Output: Palindrome number
  7. Write a java program to print factorial of a number.
    Input: 4
    Output: 24
    Input: 5
    Output: 120
  8. Write a java program to check Armstrong number.
    Input: 153
    Output: Armstrong number
    Input: 22
    Output: Not Armstrong number
  9. Write a program to swap numbers without using third variable.
    Input: 20 30
    Output: 30 20
  10. Write a program to reverse of number.
    Input:    123456
    Output: 654321
  11. Write a program to find largest of three numbers.
    Input: 10 30 40
    Output: 40
  12. Write a program to print Floyd triangle.
    Input: 7
    Output:

    1
    2 3
    4 5 6
    7 8 9 10
    11 12 13 14 15
    16 17 18 19 20 21
    22 23 24 25 26 27 28

Sorting Program

  1. Write a java program to sort an array elements using bubble sort algorithm.
    Input:    2 6 3 8 4 1 5 0
    Output: 0 1 2 3 4 5 6 8
  2. Write a java program to sort an array elements using selection sort algorithm.
    Input:    2 6 3 8 4 1 5 0
    Output: 0 1 2 3 4 5 6 8
  3. Write a java program to sort an array elements using insertion sort algorithm.
    Input:    2 6 3 8 4 1 5 0
    Output: 0 1 2 3 4 5 6 8
  4. Write a java program to sort an array elements using quick sort algorithm.
    Input:    12 24 45 56 10 9 49 30 5 15
    Output: 5 9 10 12 15 24 30 45 49 56
  5. Write a java program to sort an array elements using heap sort algorithm.
    Input:    2 6 3 8 4 1 5 0
    Output: 0 1 2 3 4 5 6 8
  6. Write a java program to sort an array elements using merge sort algorithm.
    Input:    12 24 45 56 10 9 49 30 5 15
    Output: 5 9 10 12 15 24 30 45 49 56
  7. Write a java program to sort an array elements using shell sort algorithm.
    Input:    2 6 3 8 4 1 5 0
    Output: 0 1 2 3 4 5 6 8
  8. Write a java program to sort an array elements using radix sort algorithm.
    Input:   170 45 75 90 2 802 2 66
    Output: 2 2 45 66 75 90 170 802
  9. Write a java program to sort an array elements using bucket sort algorithm.
    Input:   0.23 0.67 0.32 0.25 0.88 0.45 0.86 0.16 0.59 0.38 0.19 0.43 0.02
    Output: 0.02 0.16 0.19 0.23 0.25 0.32 0.38 0.43 0.45 0.59 0.67 0.86 0.88
  10. Write a java program to sort an array elements using counting sort algorithm.
    Input:    2 6 3 2 8 4 8 1 5 3 1 4 0
    Output: 0 1 1 2 2 3 3 4 4  5 6 8 8

Java Searching Programs

  1. Write a java program to perform linear search in java.
  2. Write a java program to perform binary search in java.

[Java] How to Reverse Number by Java Program?


Here in below program logic you will see how can be reverse number by using multiplication, reminder and division operations.

In this  below program follow steps for reverse number:

  1. Reverse number initialize with zero.
  2. Run loop till number of digits in insert number.
  3. Take reminder of number by mod 10.
  4. Add this reminder value with reverse number .
  5. Multiply this reverse number with 10 .
  6. Divide insert number by 10 and steps 2 to 6 repeat continuously.
import java.util.Scanner;

class ReverseNumber
{
public static void main(String args[])
{
int n, reverse = 0;

System.out.println("Enter the integer number to reverse");
Scanner in = new Scanner(System.in);
n = in.nextInt();

while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}

System.out.println("Reverse of entered integer number is "+reverse);
}
}

Output

Enter the integer number to reverse
12345
Reverse of entered integer number is 54321

Enter the integer number to reverse

54535251
Reverse of entered integer number is 15253545

More

For more Algorithms and Java Programing Test questions and sample code follow below links

[Java] How to Swap two Numbers with and without temporary variable.


Here I will show you how you can swap two numbers A=20 and B=10 with and without temporary variables as A=10 and B=20.

Swap Numbers with Temporary Variable

I will take one more temporary variable as temp to keep value of B so that during  copy of value A to B value of B is in temp and now we can copy value of temp to A. As below

temp=B       (This state : A=20, B=10, temp=10)

B=A;            (This state : A=20, B=20, temp=10)

A=temp      (This state : A=10, B=20, temp=10)

By applying above logic you can swap values of two variables. In below Java example I will implement same logic two swap numbers.

Swap Numbers without Temporary Variable

There are two ways two swap two numbers without using any temporary variable.

Addition and Subtraction

Here you will see how to swap numbers A=20 and B=10 by using addition and subtraction operations.

A=A+B           (This state : A=30, B=10)

B=A-B           (This state : A=30, B=20)

A=A-B           (This state : A=10, B=20)

By applying above addition and subtraction logic you can swap values of two variables. In below Java example I will implement same logic two swap numbers.

Multiplication and Division

Here you will see how to swap numbers A=20 and B=10 by using multiplication and division operations.

A=A*B           (This state : A=200, B=10)

B=A/B           (This state : A=200, B=20)

A=A/B           (This state : A=10, B=20)

By applying above multiplication and division logic you can swap values of two variables. In below Java example I will implement same logic two swap numbers.

Swap Numbers Java Program

package test;

import java.util.Scanner;

public class SwapNumbers {

public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.println("Please Enter First Number");
int A=scan.nextInt();

System.out.println("Please Enter Second Number");
int B=scan.nextInt();

//swap Numbers with temporary variable
swapNumbersWithTemp(A,B);
//swap Numbers without temporary variable : Add and Sub
swapNumbersWithoutTempAddSub(A,B);
//swap Numbers without temporary variable : Mul and Div
swapNumbersWithoutTempMulDiv(A,B);
}

private static void swapNumbersWithTemp(int A, int B)
{
int temp=B;
B=A;
A=temp;

System.out.println("Numbers after swap with temporary variables");
System.out.println("A="+A+"and B="+B);
}

private static void swapNumbersWithoutTempAddSub(int A, int B)
{
A=A+B;
B=A-B;
A=A-B;

System.out.println("Numbers after swap without temporary variables: Add and Sub operation");
System.out.println("A="+A+"and B="+B);
}

private static void swapNumbersWithoutTempMulDiv(int A, int B)
{
A=A*B;
B=A/B;
A=A/B;

System.out.println("Numbers after swap without temporary variables: MUl and Div operation");
System.out.println("A="+A+"and B="+B);
}

}

Output

Please Enter First Number
20
Please Enter Second Number
10
Numbers after swap with temporary variables
A=10and B=20
Numbers after swap without temporary variables: Add and Sub operation
A=10and B=20
Numbers after swap without temporary variables: MUl and Div operation
A=10and B=20
<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span><span 			

 

 

More Info

For more Algorithms and Java Programing Test questions and sample code follow below links

 

Binary Search Java Program


Binary search, also known as half-interval search,binary chop or logarithmic search.

How it Works?

Binary search works on sorted arrays values. Binary search begins by comparing the middle element of the array with the target value. If the target value matches the middle element, its position in the array is returned. If the target value is less than or greater
than the middle element, the search continues in the lower or upper half of the array, respectively, eliminating the other half from consideration.If the search ends with the remaining half being empty, the target is not in the array.

Time and Space Complexity?

Binary search runs in at worst logarithmic time, making O(log n) comparisons and takes constant (O(1)) space.

where n is the number of elements in the array, the O is Big O notation, and log is the logarithm.

Java API  for Binary Search

Java Arrays class also provide api’s for Binary Search. You can use as below

import java.util.Arrays;

public class BinarySearchByJavaAPI {

	public static void main(String[] args) {
		char characters[] = { 'l', 'm', 'n', 'p', 'q<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>' };

	    System.out.println(Arrays.binarySearch(characters, 'a'));
	    System.out.println(Arrays.binarySearch(characters, 'p'));

	}

}

Java Program for Binary Search

import java.util.Scanner;

class BinarySearch
{
  public static void main(String args[])
  {
    int c, first, last, middle, n, search, array[];

    Scanner in = new Scanner(System.in);
    System.out.println("Enter number of elements");
    n = in.nextInt();
    array = new int[n];

    System.out.println("Enter " + n + " sorted integers");

    for (c = 0; c < n; c++)
      array[c] = in.nextInt();

    System.out.println("Enter value to find");
    search = in.nextInt();

    first  = 0;
    last   = n - 1;
    middle = (first + last)/2;

    while( first <= last )
    {
      if ( array[middle] < search )                 first = middle + 1;                else if ( array[middle] == search )     {                System.out.println(search + " found at location " + (middle + 1) + ".");                break;        }        else                last = middle - 1;           middle = (first + last)/2;     }     if ( first ><span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span> last )
      System.out.println(search + " is not present in the list.\n");
  }
}

More Info

For more Algorithms and Java Programing Test questions and sample code follow below links