How to find the most frequent digit in a number string? - java

/*I am a beginner in programming.As a part of an assignment, I have to find the most frequent digit in a number string.Though my code gets compiled, it doesn't give me the correct results.Please help me with this.
*/
import java.util.*;
public class program
{
public int test(String number)
{
int freq0,freq1,freq2,freq3,freq4,freq5,freq6,freq7,freq8,freq9;
freq0=0;
freq1=0;
freq2=0;
freq3=0;
freq4=0;
freq5=0;
freq6=0;
freq7=0;
freq8=0;
freq9=0;
for (int i =0; i<number.length();i++)
{
switch (number.charAt(i))
{
case 48: freq0++;
break;
case 49: freq1++;
break;
case 50: freq2++;
break;
case 51: freq3++;
break;
case 52: freq4++;
break;
case 53: freq5++;
break;
case 54: freq6++;
break;
case 55: freq7++;
break;
case 56: freq8++;
break;
case 57: freq9++;
break;
}
}
List<Integer> hope = new ArrayList<Integer>();
hope.add(freq0);
hope.add(freq1);
hope.add(freq2);
hope.add(freq3);
hope.add(freq4);
hope.add(freq5);
hope.add(freq6);
hope.add(freq7);
hope.add(freq8);
hope.add(freq9);
int temp=0;
for (int j=0; j<(hope.size());j++)
{
if (temp<hope.get(j))
{
temp=hope.get(j);
}
}
return temp;
}
}
//this class is called by another main class.I am writing it's code too.
public class checker
{
public static void main ( String args [])
{
int inputs[] = {1234, 11, 144, 97764 };
int outputs[] = {1, 1, 4, 7};
for(int i=0; i<inputs.length; i++) {
int input=inputs[i];
int oracle_output=outputs[i];
program p = new program();
String input_string = "" + input;
int output = p.test(input_string);
if(output==oracle_output) {
System.out.println("test passed for " + input);
} else {
System.out.println("test failed for " + input);
}
}
}
}

What you could do is just use a simple array.
long number = 12345612;
int []frequency = new int[10];
while(number > 0)
{
int digit = number % 10;
number /= 10;
frequency[digit] ++;
}
for(int i = 0; i < 10; ++i)
System.out.println(frequency[i]);
If it is a String.
String str = "12342352397235823050237238523";
int []frequency = new int[10];
for(int i = 0; i < str.length(); ++i)
{
int digit = str.charAt(i) - '0';
frequency[digit] ++;
}
for(int i = 0; i < 10; ++i)
System.out.println(frequency[i]);
To get the maximum occuring digit.
int maxFrequency = 0;
int index = 0;
for(int i = 0; i < 10; ++i){
if(frequency[i] > maxFrequency){
maxFrequency = frequency[i];
index = i;
}
}
System.out.println("The highest occuring digit is " + index + " occuring " + maxFrequency + " times(s)");
The mistake in your program was that you're not considering the digit which repeated many times, you're taking into account the number of times only. And hence you get only the frequency not the digit.

Like it is said in the comment, the code can be made simpler (and more readable)
However, the answer to your question is this: the return value (temp) is the frequency of the most frequent digit, instead of the digit itself (which is j, you hust need to "remember" it)

Here is more readable and simpler code:
import java.util.ArrayList;
import java.util.List;
public class MostFrequentDigits1 {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
long number = 12345612;
String str = "12342352397235823050237238523";
getMostFrequentDigitWInNumber(number);
getMostFrequentDigitInString(str);
}
public static void getMostFrequentDigitWInNumber(long number) {
List<Integer> list = new ArrayList<Integer>();
int[] frequency = new int[10];
int mostFrequentVal = 0;
while (number > 0) {
int digit = (int) (number % 10);
number /= 10;
frequency[digit]++;
if (frequency[digit] > mostFrequentVal) {
mostFrequentVal = frequency[digit];
}
}
for (int j = 0; j < frequency.length; j++) {
if (frequency[j] == mostFrequentVal) {
list.add(j);
}
}
System.out.println("most frequent digits in Number:" + list);
}
public static void getMostFrequentDigitInString(String str) {
List<Integer> list = new ArrayList<Integer>();
int mostFrequentVal = 0;
int[] frequency = new int[10];
for (int k = 0; k < str.length(); k++) {
char c = str.charAt(k);
int ind = Integer.valueOf(String.valueOf(c));
frequency[ind]++;
if (frequency[ind] > mostFrequentVal) {
mostFrequentVal = frequency[ind];
}
}
for (int j = 0; j < frequency.length; j++) {
if (frequency[j] == mostFrequentVal) {
list.add(j);
}
}
System.out.println("most frequent digits in string:" + list);
}
}

Related

unable to sort or print out array

I got a task to write the methods to 1. take information in and save it into array, 2. to copy the array(only with previously given arguments) and 3. to sort the array to be in descending order. it seems to me like i got the first 2 parts working but i have been stuck on the third method for 2 days without any progress. i am still learning java so i'm pretty sure i have made a dumb mistake somewhere. thanks in advance.
import java.util.*;
public class RevisionExercise {
public static void main(String[] args) {
int[] tempArray = new int[100];
System.out.println("Type in numbers. Type zero to quit.");
int amountOfNumbers = askInfo(tempArray);
int[] realArray = new int[amountOfNumbers];
copyInfo(realArray, tempArray);
setArray(realArray);
printArray(realArray);
}
public static int askInfo(int[] tempArray) {
Scanner reader = new Scanner(System.in);
int i;
for (i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
tempArray[i] = reader.nextInt();
if (tempArray[i] == 0) {
return tempArray[i];
}
}
return i;
}
private static int[] copyInfo(int[] realArray, int[] tempArray)
{
int targetIndex = 0;
for( int sourceIndex = 0; sourceIndex < tempArray.length; sourceIndex++ )
{
if( tempArray[sourceIndex] != 0 )
tempArray[targetIndex++] = tempArray[sourceIndex];
}
realArray = new int[targetIndex];
System.arraycopy( tempArray, 0, realArray, 0, targetIndex );
return realArray;
}
public static int[] setArray(int[] realArray)
{
int temp = 0;
for (int i = 0; i <realArray.length; i++) {
for (int j = i+1; j <realArray.length; j++) {
if(realArray[i] >realArray[j]) {
temp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = temp;
}
}
}
return realArray;
}
public static void printArray(int[] realArray ) {
System.out.println("\nOrdered array: ");
for(int i = 0; i < realArray .length; i++) {
System.out.println(realArray [i]);
}
}
}
the output i'm getting looks like this.
Type in numbers. Type zero to quit.
1. number: 3
2. number: 8
3. number: 5
4. number: 6
5. number: 9
6. number: 0
Ordered array:
while it should look like this:
Type in numbers. Type zero to quit.
1. number: 3
2. number: 8
3. number: 5
4. number: 6
5. number: 9
6. number: 0
Ordered array:
9
8
6
5
3
You made a mistake in calculating the total numbers entered by the user. Your function always return 0. So change it to something like this:
public static int askInfo(int[] tempArray) {
Scanner reader = new Scanner(System.in);
int totalNumbers = 0;
for (int i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
int number = reader.nextInt();
if (number != 0) {
totalNumbers++;
tempArray[i] = number;
} else {
break;
}
}
return totalNumbers;
}
Chage the sort function to this:
public static void setArray(int[] realArray) {
int temp = 0;
for (int i = 0; i < realArray.length; i++) {
for (int j = i+1; j < realArray.length; j++) {
// Use < for descending order and > for ascending order
if(realArray[i] < realArray[j]) {
temp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = temp;
}
}
}
}
Your main program
public static void main(String[] args) {
int[] tempArray = new int[100];
System.out.println("Type in numbers. Type zero to quit.");
int amountOfNumbers = askInfo(tempArray);
int[] realArray = new int[amountOfNumbers];
copyInfo(tempArray, realArray, amountOfNumbers);
setArray(realArray);
printArray(realArray);
}
public static int askInfo(int[] tempArray) {
Scanner reader = new Scanner(System.in);
int totalNumbers = 0;
for (int i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
int number = reader.nextInt();
if (number != 0) {
totalNumbers++;
tempArray[i] = number;
} else {
break;
}
}
return totalNumbers;
}
private static void copyInfo(int[] tempArray, int[] realArray, int size) {
for( int sourceIndex = 0; sourceIndex < size; sourceIndex++ )
{
realArray[sourceIndex] = tempArray[sourceIndex];
}
}
public static void setArray(int[] realArray) {
int temp = 0;
for (int i = 0; i < realArray.length; i++) {
for (int j = i+1; j < realArray.length; j++) {
if(realArray[i] < realArray[j]) {
temp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = temp;
}
}
}
}
public static void printArray(int[] realArray ) {
System.out.println("\nOrdered array: ");
for(int i = 0; i < realArray.length; i++) {
System.out.println(realArray [i]);
}
}
To begin with, in the askInfo method, the size of the realArray will always be 0, since amountOfNumbers is the return of
if (tempArray[i] == 0) {
return tempArray[i];
}
because your condition is tempArray[i] == 0, hence you are always returning 0. Then your copyInfo method is returning an array but you have nothing receiving the returned array. I would suggest changing your copyInfo method to
private static int[] copyInfo(int[] tempArray)
{
// same
int [] realArray = new int[targetIndex];
// same
}
and your main method to
public static void main(String[] args) {
//same
int[] realArray = new int[amountOfNumbers];
realArray = copyInfo(tempArray);
// same
}
General remark: Each of your methods returns an array but you never use this return value.
There are 2 modifications necessary to fix your code:
Keep the value of the method output:
realArray=copyInfo(realArray, tempArray);
So you put the result of the copy in the realArray variable.
You expect the askInfo method to return the number of entered numbers but in fact you return the value of the last entered number.
So instead of return tempArray[i]; you have to return i;

java assign even elements to even index and odd to odd places and if the numbers are not equal add zeros to the places

I am trying to write code to display the even elements to even indexes and odd to odd indexes and if the numbers added numbers are same then add zeros accordingly.
Example:
x = [1,2,3,4]
output: 2 1 4 3
x = [1 1 1 4]
output: 4 1 0 1 0 1
I reached to get even and odd positions but stuck after that.
Below is my code.
import java.util.*;
class ArrayDemo3 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Size of Array :: ");
int size = s.nextInt();
int[] x = new int[size];
System.out.println("Array Created having the size :: " + size);
System.out.println("Enter Elements for Array :: ");
for (int i = 0; i < size; i++) {
System.out.println("Enter element no-" + (i + 1) + " ::");
x[i] = s.nextInt();
}
System.out.println("Contents of Array ::");
for (int i = 0; i < size; i++) {
System.out.print(x[i] + " ");
}
for (int i = 0; i < size; i = i + 1) {
int even = 0;
int odd = 1;
if (i < size && x[i] % 2 == 0) {
System.out.print("even : ");
even = even + i;
System.out.print("position" + i + " " + x[i] + " ");
} else {
System.out.print("odd : ");
odd = odd + i;
System.out.print(i + " " + x[i] + " ");
}
if (even < size && odd < size) {
int temp = x[even];
x[even] = x[odd];
x[odd] = temp;
} else {
}
//System.out.print(x[i] + " ");
}
}
}
You can break up your problem in 3 parts:
First create two lists, one containing in encountered order the even numbers and the other the odd numbers:
private static List<List<Integer>> createOddityLists(int... numbers) {
List<Integer> numsList = Arrays.stream(numbers).boxed().collect(Collectors.toList());
List<List<Integer>> numsByOddity = new ArrayList<List<Integer>>();
numsByOddity.add(new ArrayList<>()); // List of odd numbers
numsByOddity.add(new ArrayList<>()); // List of even numbers
numsList.forEach(num -> numsByOddity.get(num % 2).add(num));
return numsByOddity;
}
Pad the shorter of the two lists with zeros (0s) to make it equal length as the other one:
private static void padShorterList(List<List<Integer>> numsByOddity) {
int sizeDiff = numsByOddity.get(0).size() - numsByOddity.get(1).size();
int listIndexToBePadded = sizeDiff < 0 ? 0 : 1;
List<Integer> padding = Collections.nCopies(Math.abs(sizeDiff), 0);
numsByOddity.get(listIndexToBePadded).addAll(padding);
}
Finally join intertwining both lists:
private static List<Integer> joinLists(List<List<Integer>> numsByOddity) {
List<Integer> resultList = new ArrayList<>(numsByOddity.get(1));
for (int idx = 0; idx < numsByOddity.get(0).size(); idx++)
resultList.add(idx * 2, numsByOddity.get(0).get(idx));
return resultList;
}
The following is the full working example:
public class ArrayRearrangement {
public static void main(String[] args) {
// int[] result = rearrange(1, 2, 3, 4);
int[] result = rearrange(1, 1, 1, 4);
System.out.println(Arrays.stream(result).boxed().collect(Collectors.toList()));
}
private static int[] rearrange(int... numbers) {
List<List<Integer>> numsByOddity = createOddityLists(numbers);
padShorterList(numsByOddity);
return joinLists(numsByOddity).stream().mapToInt(i->i).toArray();
}
private static List<List<Integer>> createOddityLists(int... numbers) {
List<Integer> numsList = Arrays.stream(numbers).boxed().collect(Collectors.toList());
List<List<Integer>> numsByOddity = new ArrayList<List<Integer>>();
numsByOddity.add(new ArrayList<>()); // List of odd numbers
numsByOddity.add(new ArrayList<>()); // List of even numbers
numsList.forEach(num -> numsByOddity.get(num % 2).add(num));
return numsByOddity;
}
private static void padShorterList(List<List<Integer>> numsByOddity) {
int sizeDiff = numsByOddity.get(0).size() - numsByOddity.get(1).size();
int listIndexToBePadded = sizeDiff < 0 ? 0 : 1;
List<Integer> padding = Collections.nCopies(Math.abs(sizeDiff), 0);
numsByOddity.get(listIndexToBePadded).addAll(padding);
}
private static List<Integer> joinLists(List<List<Integer>> numsByOddity) {
List<Integer> resultList = new ArrayList<>(numsByOddity.get(1));
for (int idx = 0; idx < numsByOddity.get(0).size(); idx++)
resultList.add(idx * 2, numsByOddity.get(0).get(idx));
return resultList;
}
}
Complete code on GitHub
Hope this helps.
Using arrays something like this we can do. Code needs to be optimised.
public static int[] arrangeInEvenOddOrder(int[] arr)
{
// Create odd and even arrays
int[] oddArr = new int[arr.length];
int[] evenArr = new int[arr.length];
int oCount = 0, eCount = 0;
// populate arrays even and odd
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 0)
evenArr[eCount++] = arr[i];
else
oddArr[oCount++] = arr[i];
}
int[] resArr = new int[oCount >= eCount?
2*oCount : 2*eCount-1];
// populate elements upto min of the
// two arrays
for (int i =0; i < (oCount <= eCount?
2*oCount : 2*eCount ); i++ )
{
if( i%2 == 0)
resArr[i] = evenArr[i/2];
else
resArr[i] = oddArr[i/2];
}
// populate rest of elements of max array
// and add zeroes
if (eCount > oCount)
{
for (int i=2*oCount,j=0;i<2*eCount-1; i++)
{
if (i%2 == 0)
{
resArr[i] = evenArr[oCount+j];
j++;
}
else
resArr[i] = 0;
}
}
else if (eCount < oCount)
{
for (int i=2*eCount,j=0;i<2*oCount; i++)
{
if ( i%2 != 0)
{
resArr[i] = oddArr[eCount+j];
j++;
}
else
resArr[i] = 0;
}
}
return resArr;
}
Sort element based on index i.e if the element is even, it must be at even position and vise-versa
int sortArrayByEvenOddIndex(int arr[]) {
int n = arr.length;
int res[] = new int[n];
int odd = 1;
int even = 0;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
res[even] = arr[i];
even += 2;
} else {
res[odd] = arr[i];
odd += 2;
}
}
return res;
}

Code compiles and executes, but does not print anything

The time-limit-extended is the status when executing the successfully compiled class file of the following code.
import java.io.*;
public class CandidateCode {
public static int ThirstyCrowProblem(int[] input1, int input2, int input3) {
int[] arrK = new int[input3];
int minstones = 0;
for (int i = 0; i < input3; i++) //create an array of k Os.
{
int smallest = input1[0], place = 0;
for (int j = 0; j < input2; j++) {
if ((smallest >= input1[j]) && (input1[j] >= 0)) {
smallest = input1[j];
place = j;
}
}
input1[place] = -1;
arrK[i] = smallest;
}
int n = input2, i = 0;
while (i < input3)
minstones = minstones + arrK[i] * (n - i);
return minstones;
}
public static void main(String[] args) {
int[] arr = new int[] {
5, 58
};
int stones_min = CandidateCode.ThirstyCrowProblem(arr, 2, 1);
System.out.println("The result is" + stones_min);
}
}
The cursor is waiting and waiting, but I don't think there is an error in the code!??
Option A :
Change your while into an if statement :
if(i<input3) {
minstones= minstones + arrK[i]*(n-i);
}
Option B : or increment i (i++) but I don't this that's what you want
while(i<input3) {
minstones = minstones + arrK[i]*(n-i);
i++;
}
You need to increment i in your while loop.Since you are not incrementing,its going in infinite loop.
while(i<input3)
{
minstones= minstones + arrK[i]*(n-i);
i++;
}
After making this change,I got
The result is10

Find smallest number K , if exists, such that product of its digits is N. Eg:when N = 6, smallest number is k=16(1*6=6) and not k=23(2*3=6)

I have made this program using array concept in java. I am getting Exception as ArrayIndexOutOfBound while trying to generate product.
I made the function generateFNos(int max) to generate factors of the given number. For example a number 6 will have factors 1,2,3,6. Now,i tried to combine the first and the last digit so that the product becomes equal to 6.
I have not used the logic of finding the smallest number in that array right now. I will do it later.
Question is Why i am getting Exception as ArrayIndexOutOfBound? [i couldn't figure out]
Below is my code
public class SmallestNoProduct {
public static void generateFNos(int max) {
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
}
}
smallestNoProduct(ar);
}
public static void smallestNoProduct(int x[]) {
int j[] = new int[x.length];
int p = x.length;
for (int d = 0; d < p / 2;) {
String t = x[d++] + "" + x[p--];
int i = Integer.parseInt(t);
j[d] = i;
}
for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}
}
public static void main(String s[]) {
generateFNos(6);
}
}
****OutputShown****
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at SmallestNoProduct.smallestNoProduct(SmallestNoProduct.java:36)
at SmallestNoProduct.generateFNos(SmallestNoProduct.java:27)
at SmallestNoProduct.main(SmallestNoProduct.java:52)
#Edit
The improved Code using array only.
public class SmallestNoProduct {
public static void generateFNos(int max) {
int s = 0;
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
s++;
}
}
for (int g = 0; g < s; g++) {
System.out.println(ar[g]);
}
smallestNoProduct(ar, s);
}
public static void smallestNoProduct(int x[], int s) {
int j[] = new int[x.length];
int p = s - 1;
for (int d = 0; d < p;) {
String t = x[d++] + "" + x[p--];
System.out.println(t);
int i = Integer.parseInt(t);
j[d] = i;
}
/*for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}*/
}
public static void main(String s[]) {
generateFNos(6);
}
}
Maybe it better:
public class SmallestNoProduct {
public static int smallest(int n) {
int small = n*n;
for(int i = 1; i < Math.sqrt(n); i++) {
if(n%i == 0) {
int temp = Integer.parseInt(""+i+""+n/i);
int temp2 = Integer.parseInt(""+n/i+""+i);
temp = temp2 < temp? temp2: temp;
if(temp < small) {
small = temp;
}
}
}
return small;
}
public static void main(String[] args) {
System.out.println(smallest(6)); //6
System.out.println(smallest(10)); //25
System.out.println(smallest(100)); //205
}
}
Problem lies in this line
String t=x[d++]+""+x[p--];
x[p--] will try to fetch 7th position value, as p is length of array x i.e. 6 which results in ArrayIndexOutOfBound exception. Array index starts from 0, so max position is 5 and not 6.
You can refer this question regarding postfix expression.
Note: I haven't checked your logic, this answer is only to point out the cause of exception.
We are unnecessarily using array here...
below method should work....
public int getSmallerMultiplier(int n)
{
if(n >0 && n <10) // if n is 6
return (1*10+n); // it will be always (1*10+6) - we cannot find smallest number than this
else
{
int number =10;
while(true)
{
//loop throuogh the digits of n and check for their multiplication
number++;
}
}
}
int num = n;
for(i=9;i>1;i--)
{
while(n%d==0)
{
n=n/d;
arr[i++] = d;
}
}
if(num<=9)
arr[i++] = 1;
//printing array in reverse order;
for(j=i-1;j>=0;j--)
system.out.println(arr[j]);

How to remove element from a raw array

I have a program that will push pop and display, but I cannot pop the pushed numbers in my program probably I can't delete the element of that array. This is my code so far:
import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class Class2 {
public static void main(String args[]) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out
.print("1.)Push\n2.)Pop\n3.)Display\n4.)Exit\n\nChoose Item :");
int x = Integer.parseInt(in.readLine());
int[] a = new int[10];
int b = 0;
int i = 0;
do
{
switch (x) {
case 1:
System.out.print("Enter Push number :");
int v = Integer.parseInt(in.readLine());
a[b] = v;
b += 1;
System.out.print("Item push :" + v + "\n");
System.out
.print("1.)Push\n2.)Pop\n3.)Display\n4.)Exit\n\nChoose Item :");
x = Integer.parseInt(in.readLine());
if (x == 3) {
for (i = 0; i < b; i++) {
System.out.print(a[i] + " ");
}
}
break;
case 2:
System.out.print("Enter Pop Number :");
int c = Integer.parseInt(in.readLine());
if (c == a[i]) {
}
System.out.print("Item Pop :" + c + "\n");
System.out
.print("1.)Push\n2.)Pop\n3.)Display\n4.)Exit\n\nChoose Item :");
x = Integer.parseInt(in.readLine());
if (x == 3) {
for (i = 0; i < b; i++) {
System.out.print(a[i] + " ");
}
}
break;
case 4:
break;
}
} while (x == 1 || x == 2);
}
}
First of all, if you want to change the elements of an array, then you should not use an array.
If you really don't want to use containers, then you could allocate dynamically a new array without the element you want to remove (not so a good idea probably because of bad performance and wasted memory).
This could be the method that returns the new array:
public static int[] removeElementAt(int [] array, int index){
if(index > 0 && index < array.length){
int [] newArray = new int[array.length - 1];
for(int i=0; i<index; i++)
newArray[i] = array[i]; // copying elements
for(int i=index+1; i<array.length; i++)
newArray[i-1] = array[i];
array = newArray;
}
return array;
}
This is just a simple example:
myArray = Class.removeElementAt(myArray, 5); // removes 6. element
You could also use the function removeElement from the API ArrayUtils, something like this:
array = ArrayUtils.removeElement(array, element)
Another alternative would be to convert your array to a list, remove the element, and then convert it back to an array: not so a good idea, because you could use directly an ArrayList.
So, the idea is to use dynamic containers when you want to modify the content, otherwise use a normal raw array.
you can use below code and it might solve your issue.
int brr[]= new int [a.length-1];
int j=0;
for(;j<a.length;j++)
{
if(c== a[j])
{
break;
}
else{
brr[j]=a[j];
}
}
for(j=j+1;j<a.length;j++)
{
brr[j-1] =a[j];
}
in display show brr array.
When you push 2, 5, and 6 you have a queue with 3 items in it:
a[0] == 2
a[1] == 5
a[2] == 6
When you pop 2, you want to remove it from the array. To do this, you need to copy everything after where 2 was popped from into the position above, so that you end up with:
a[0] == 5
a[1] == 6
The code for this would look something like:
int popPosition = findPopPosition();
for(int i = popPosition + 1; i < MAX; i++)
a[i - 1] = a[i];
b--; // Decrease effective queue size
Where findPopPosition() would need to find the index that 2 is at, so it would return 0 in this example.
Or, alternatively, the user could input the pop position directly (so pop element 0) instead of specifying what value they want to pop. That's probably more useful.
Not all test cases have been handled, but a sample working program as per your requirements.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ArrayDemo {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Array Max Capacity");
int maxSize = Integer.parseInt(br.readLine().trim());
int[] array = new int[maxSize];
int arrayCount = 0;
int choice = 0;
do {
System.out.println("\n1.Insert\n2.Delete\n3.Display\n4.Exit");
choice = Integer.parseInt(br.readLine().trim());
switch (choice) {
case 1:
boolean insertTrue = insertElement(br, maxSize, array,
arrayCount);
if (insertTrue) {
arrayCount++;
}
break;
case 2:
System.out.println("Enter Element to delete");
int delElement = Integer.parseInt(br.readLine().trim());
int numOccurrence = getOccurrenceCount(array, arrayCount,
delElement);
int newArrayCount = arrayCount - numOccurrence;
if (numOccurrence == 0) {
System.out.println("No Such Element to delete");
} else {
array = deleteElement(array, arrayCount, delElement,
newArrayCount,maxSize);
}
arrayCount =newArrayCount;
break;
case 3:
displayArray(array, arrayCount);
break;
case 4:
System.out.println("Exiting");
break;
default:
System.out.println("Invalid Choice, Exiting");
choice = 4;
}
} while (choice >= 1 && choice <= 3);
}
private static int[] deleteElement(int[] array, int arrayCount,
int delElement, int newArrayCount,int maxSize) {
int newArray[] = new int[newArrayCount];
int index=0;
for (int i = 0; i < arrayCount; i++) {
if (array[i] != delElement) {
newArray[index] = array[i];
index++;
}
}
resetArray(array, maxSize);
for(int i=0;i<newArrayCount;i++){
array[i]=newArray[i];
}
return array;
}
private static int[] resetArray(int[] array,int maxSize){
for(int i=0;i<maxSize;i++){
array[i]=0;
}
return array;
}
private static int getOccurrenceCount(int[] array, int arrayCount,
int delElement) {
int numOccurrence = 0;
for (int i = 0; i < arrayCount; i++) {
if (array[i] == delElement) {
numOccurrence++;
}
}
return numOccurrence;
}
private static void displayArray(int[] array, int arrayCount) {
if (arrayCount == 0) {
System.out.println("No Elements to Display");
} else {
System.out.println("Array is");
for (int i = 0; i < arrayCount; i++) {
System.out.print(array[i] + " ");
}
System.out.println("\n");
}
}
private static boolean insertElement(BufferedReader br, int maxSize,
int[] array, int arrayCount) throws IOException {
if (arrayCount < maxSize) {
System.out.println("Enter Element for Insertion");
array[arrayCount] = Integer.parseInt(br.readLine().trim());
return true;
} else {
System.out.println("Max Limit Reached, Insertion not possible");
return false;
}
}
}

Categories

Resources