Right now, I'm trying to find the odd and even numbers of an array. Here's the code of what I have so far. I know my findEvens() and findOdds() methods are messed up because they keep giving me off values whenever I try to print the final result. For example, if I try to find the odds of {1,5,8,3,10}, it gives me {5,3,0}. And if I try to find the evens of {2,5,8,7,19}, it gives me {2,8,0}. Anyone know why?
public class Scores {
private int[] numbers;
public Scores(int[] numbersIn) {
numbers = numbersIn;
}
public int[] findEvens() {
int numberEvens = 0;
for (int i = 0; i < numbers.length; i++) {
if (i % 2 == 0) {
numberEvens++;
}
}
int[] evens = new int[numberEvens];
int count = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
evens[count] = numbers[i];
count++;
}
}
return evens;
}
public int[] findOdds() {
int numberOdds = 0;
for (int i = 0; i < numbers.length; i++) {
if (i % 2 == 0) {
numberOdds++;
}
}
int[] odds = new int[numberOdds];
int count = 0;
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] % 2 == 1) {
odds[count] = numbers[i];
count++;
}
}
return odds;
}
public double calculateAverage() {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return (double) sum / numbers.length;
}
public String toString() {
String result = "";
for (int i = 0; i < numbers.length; i++) {
result += numbers[i] + "\t";
}
return result;
}
public String toStringInReverse() {
String result = "";
for (int i = numbers.length - 1; i >= 0; i--) {
result += numbers[i] + "\t";
}
return result;
}
}
You're problem is in counting how many even numbers you have
public int[] findEvens() {
int numberEvens = 0;
for (int i = 0; i < numbers.length; i++) {
if (i % 2 == 0) {
numberEvens++;
}
}
this will always return a number that is half the size of the length of numbers because you're doing mod division on the number of elements in the array, not on the elements themselves. Add numbers[i] to the if statement
public int[] findEvens() {
int numberEvens = 0;
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 == 0) {
numberEvens++;
}
}
looks like you've got the same problem with odd count
'i' is used as conditional variable for looping. You should not divide this by 2. You have to divide the array element. like
if (numbers[i] % 2 == 0) {
numberEvens++;
}
then it should work. Thanks
Try This Code
import java.util.Scanner;
public class OddEven {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("enter number Elements in Array");
int n = s.nextInt();
int arr[] = new int[n];
System.out.println("enter Elements ");
for(int i=0; i<n; i++) {
arr[i]=s.nextInt();
}
int [] odd = filterOdd(arr);
try {
for(int i=0; i<n; i++) {
System.out.println("Odd" + odd[i]);
}
} catch(ArrayIndexOutOfBoundsException e) {}
int [] even = filterEven(arr);
try {
for(int i=0; i<n; i++) {
System.out.println("Even" + even[i]);
}
} catch(ArrayIndexOutOfBoundsException e) {}
}
public static int[] filterOdd(int[] a) {
int l = 0;
int j = 0;
for(int i=0; i<a.length; i++) {
if(a[i]%2==1) {
l++;
}
}
int k[]=new int[l];
for(int i=0; i<a.length; i++) {
if(a[i]%2==1) {
k[j] = a[i];
j++;
}
}
return k;
}
public static int[] filterEven(int[] a) {
int l = 0;
int j = 0;
for(int i=0; i<a.length; i++) {
if(a[i]%2==0) {
l++;
}
}
int k[] = new int[l];
for(int i=0; i<a.length; i++) {
if(a[i]%2==0) {
k[j] = a[i];
j++;
}
}
return k;
}
}
public class Array {
public static void main(String[] args) {
// TODO code application logic here
//Array declaration and value asign
int number[]=new int[]{1,2,3,4,5,6,7,8,9};
// for loop to move number
for(int p=0;p<number.length;p++)
{
// check number is even or odd??
if(number[p]%2==0)
System.out.println(number[p]+ " is Even number");
else
System.out.println( number[p]+" is odd umber");
}
}
}
Odd array one columns and another columns even array
public class OddEven {
public static void main(String[] args) {
int arr[]={1,2,3,4,5,6,7,8};
int ss[]=new int[10];
int odd[]=new int[10];
int i;
int k;
for( i=0;i<arr.length;i++)
{
if(arr[i]%2==0)
{
ss[i]=arr[i];
System.out.print(""+ss[i]);
System.out.print(" ");
}
if((arr[i]%2)!=0)
{
odd[i]=arr[i];
System.out.print(""+odd[i]);
System.out.print(" ");
}else
{
System.out.println(" ");
}
}
}
}
========================================output==============================
1 2
3 4
5 6
7 8
Related
I have a java code to read the length of an integer array, output the range, length of the gap, and any distinct elements inside. Additionally, it will output the numbers again with none repeated.
I would like to shorten the length of my main method.
My code produces the correct output, it is just very lengthy. Additionally, is there a way I can edit this main method to where it won't require a drastic change to my other methods? Thank you so much!
package ArrayPrograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
***public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
in.close();
}
}***
Sure thing. Here you go:
package arrayprograms;
import java.util.Scanner;
public class WIP{
static int LargestGap(int [] a, int n)
{
int diff = Math.abs(a[1] - a[0]);
for(int i = 1; i < a.length-1; i++)
if(Math.abs(a[i+1]-a[i]) > diff)
diff = Math.abs(a[i+1] - a[i]);
return diff;
}
int range(int a[], int n)
{
int max1 = Integer.MIN_VALUE;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (Math.abs(a[i] - a[j]) > max1)
{
max1 = Math.abs(a[i] - a[j]);
}
}
}
return max1;
}
int numberOfDistinctElement(int a[], int n)
{
int num = 1;
for (int i = 1; i < n; i++)
{
int j = 0;
for (j = 0; j < i; j++)
if (a[i] == a[j])
break;
if (i == j)
num++;
}
return num;
}
int[] distinctElements(int a[], int n,int numberofDistinct)
{
int index = 0;
int[] distinct= new int[numberofDistinct];
for (int i = 0; i < n; i++)
{
int flag = 0;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
flag = 1;
break;
}
}
if (flag == 0){
distinct[index] = a[i];
index++;
}
}
return distinct;
}
static void showResults(int[] array, int num, WIP obj){
System.out.println("The largest gap in the array is "+WIP.LargestGap(array,num)+".");
System.out.println("The range of the array is "+obj.range(array,num)+".");
int numberofDistinct=obj.numberOfDistinctElement(array,num);
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray=obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
{
System.out.print(distinctArray[i]+"]");
}
else {
System.out.print( distinctArray[i]+ ",");
}
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int num;
WIP obj=new WIP();
System.out.print("Enter the length of the array:");
num = in.nextInt();
int array[] = new int[num];
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
{
array[i] = in.nextInt();
}
in.close();
showResults(array, num, obj );
}
}
There's not a whole lot you can do, like most of the comments say, but you can remove and edit some of the braces around that aren't necessary for the bodies. Here is a rough draft of it. The only things you could change besides that is to store all of the WIP.tests in variables in one code block and then print them all out in another code block; which would improve readability.
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
WIP obj = new WIP();
System.out.print("Enter the length of the array:");
int num = in.nextInt();
int array[] = new int[num] ;
System.out.print("Enter the elements of the array: ");
for(int i = 0; i < num; i++)
array[i] = in.nextInt();
System.out.println("The largest gap in the array is " + WIP.LargestGap(array,num) + ".");
System.out.println("The range of the array is " + obj.range(array,num) + ".");
int numberofDistinct = obj.numberOfDistinctElement( array, num );
System.out.println("The number of distinct elements is "+numberofDistinct+".");
int[] distinctArray = obj.distinctElements(array,num,numberofDistinct);
System.out.print("The array of distinct elements is [");
for (int i = 0; i < distinctArray.length; i++)
if(i== distinctArray.length-1)
System.out.print(distinctArray[i]+"]");
else
System.out.print( distinctArray[i]+ ",");
in.close();
}
how I can sort and find the duplication in the array and return if there is a duplication?
I have an array with this code
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int r = input.nextInt();
int[] list = new int[r];
init(list);
static void init(int list[]) {
Random random = new Random();
for (int i = 0; i < list.length; i++) {
int n = (int) (Math.random() * 50 + 1);
list[i] = random.nextInt(50) + 1;
}
}
static void print(int list[]) {
for (int i : list) {
System.out.print(i + " ");
}
}
}
how can I sort it in another method and find the duplication
From you question I understand You want the duplicate items in an array.
Here is an example using naive approach. Please don't use it if you have very large array!!!
public static void main (String [] args) {
System.out.println("Hello world");
int [] myarray = {1,3,4,2,2,2,3};
int [] duplicates = findDuplicates(myarray);
System.out.println(Arrays.toString(duplicates));
}
private static int [] findDuplicates( int [] list) {
int [] countingArray = new int[1];
int n = 0;
for (int i = 0; i < list.length; i++) {
for (int j = i + 1 ; j < list.length; j++) {
if (list[i] == list[j]) {
boolean flag = true;
for (int k = 0; k < countingArray.length; k++) {
if ((countingArray[k] == list[i])) {
flag = false;
}
}
if (flag) {
if (n == countingArray.length) countingArray = resizeBy1(countingArray);
countingArray[n++] = list[i];
}
}
}
}
return countingArray;
}
private static int [] resizeBy1(int [] s) {
int [] newArray = new int[s.length +1];
for (int i = 0; i< s.length; i++) {
newArray[i] = s[i];
}
s = newArray;
return s;
}
If you want to know an advance approach please look at Finding repetition in array
This question already has answers here:
Return all prime numbers smaller than M
(9 answers)
Closed 3 years ago.
Can anyone help me to determine all prime numbers smaller than a given input value using scanner with java8 .
Input: N integer> 0
Output: the table with prime numbers.
Example: for N = 10 the Output is : 2 3 5 7
this is my work so far:
class Main {
public static void main(String[] args) {
int N;
int[] result = null;
try (Scanner scanner = new Scanner(new File(args[0]))) {
N = Integer.parseInt(scanner.nextLine());
for (int i = 0; i < (N/2)+1; i++) {
if (N%i==0)
result[i]=i;
for (int j = 0; j < result.length; j++) {
System.out.print(result[j]);
if (j < result.length - 1) {
System.out.print(" ");
}
}
}
System.out.println();
}
catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
}
your code problem is int i = 0 start with 0 and next line if (N%i==0) so 10/0 is not possible throw a error something like java.lang.ArithmeticException: / by zero is not possible
and you loop through result.length, you need to loop through i your parent loop and put condition inside if (N%i==0) and you need many changes saw my below answer and debug where you get unexpected output and follow.
brute Force
public static void main(String[] args) {
int N = 50;
List<Integer> result = new ArrayList<>();
for (int i = 1; i < N; i++) {
boolean isPrime = true;
for (int j = 2; j < i - 1; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result.add(i);
}
}
result.forEach(System.out::println);
}
optimize one using Math.sqrt reason
public static void main(String[] args) {
int N = 101;
List<Integer> result = new ArrayList<>();
for (int i = 1; i <= N; i++) {
boolean isPrime = true;
for (int j = 2; j < Math.sqrt(i - 1); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result.add(i);
}
}
result.forEach(System.out::println);
}
using BigInteger.isProbablePrime see
public static void main(String[] args) {
int N = 101;
List<Integer> result = new ArrayList<>();
for (long i = 1; i <= N; i++) {
BigInteger integer = BigInteger.valueOf(i);
if (integer.isProbablePrime(1)) {
result.add((int) i);
}
}
result.forEach(System.out::println);
}
Updated 1:- that something you want
try (Scanner scanner = new Scanner(new File(args[0]))) {
int N = Integer.parseInt(scanner.nextLine());
int[] result = new int[N];
int resultIncreamenter = 0;
// here for loop logic can be replaced with above 3 logic
for (int i = 1; i <= N; i++) {
boolean isPrime = true;
for (int j = 2; j < Math.sqrt(i - 1); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result[resultIncreamenter++] = i;
}
}
for (int j = 0; j < result.length; j++) {
System.out.print(result[j]);
if (j < result.length - 1) {
System.out.print(" ");
}
}
System.out.println();
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
You lost the overview, though you have all functionality within reach.
public static boolean isPrime(int n) {
for (int i = 0; i < (n/2)+1; i++) {
if (n%i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File(args[0]))) {
int N = Integer.parseInt(scanner.nextLine());
boolean printed = false;
for (int j = 2; j < N; j++) {
if (isPrime(j)) {
if (printed) {
System.out.print(" ");
}
System.out.print(j);
printed = true;
}
}
System.out.println();
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
Simply use abstractions like isPrime.
Now for improvements (your results array): use the already found primes instead of all numbers in testing:
public static boolean isPrime(int n, int[] priorPrimes, int primesCount) {
for (int p : priorPrimes) {
if (n%p == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
try (Scanner scanner = new Scanner(new File(args[0]))) {
int N = Integer.parseInt(scanner.nextLine());
int[] primes = new int[N];
int primesCount = 0;
boolean printed = false;
for (int j = 2; j < N; j++) {
if (isPrime(j)) {
primes[primesCount] = j;
++primesCount;
if (printed) {
System.out.print(" ");
}
System.out.print(j);
printed = true;
}
}
System.out.println();
} catch (FileNotFoundException ex) {
throw new RuntimeException(ex);
}
}
The algorithm using the Sieve of Eratosthenes taken from here:
private static int findNumberOfPrimes(int length) {
int numberOfPrimes = 1;
if (length == 2) {
return 1;
}
int[] arr = new int[length];
//creating an array of numbers less than 'length'
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
//starting with first prime number 2, all the numbers divisible by 2(and upcoming) is replaced with -1
for (int i = 2; i < arr.length && arr[i] != -1; i++) {
for (int j = i; j < arr.length; j++) {
if (arr[j] % arr[i] == 0) {
arr[j] = -1;
numberOfPrimes += 1;
}
}
}
return numberOfPrimes;
}
Update :
and this is how you list them :
package primelessthanN;
public class Main {
public static void main(String[] args) {
int j;
int n;
n = 10;
for (j = 2; j <=n; j++) {
if (isPrime(j))
System.out.println(j);
}
}
private static boolean isPrime(int m) {
for (int i = 2; i <= sqrt(m); i++) {
if (m % i == 0)
return false;
}
return true;
}
}
So I'm trying to create a program that creates a randomly generated array with numbers between 0 and 10.
Every time a number inside the 4x4 array is odd I want it to generate a brand new array and print every array discarded aswell until it creates a 4x4 array with only even numbers.
The problem right now is that I can't understand how to fix the last for and make it work properly with the boolean b that is supposed to restart the creation of the array.
import java.util.Scanner;
public class EvenArrayGenerator {
public static void main(String a[]) {
Boolean b;
do {
b = true;
int[][] Array = new int[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
Array[i][j] = (int) (Math.random() * 11);
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (Array[i][j] % 2 != 0)
b = false;
}
}
} while (b);
}
}
public class ArrayGen {
private int[][] array = new int[4][4];
private int iterations = 1; // you always start with one iteration
public static void main (String[] args) {
ArrayGen ag = new ArrayGen();
ag.reScramble();
while(!ag.isAllEven()) {
ag.reScramble();
ag.iterations++;
}
// this is just a nice visualisation
for (int i = 0; i < 4; i++) {
System.out.print("[");
for (int j = 0; j < 4; j++) {
System.out.print(ag.array[i][j] +((j != 3)? ", " : ""));
}
System.out.print("]\n");
}
System.out.println(ag.iterations + " iterations needed to get all-even array.");
}
private void reScramble () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
array[i][j] = (int)(Math.random() * 11);
}
}
}
private boolean isAllEven () {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (array[i][j] % 2 == 1) {
return false;
}
}
}
return true;
}
}
I think this is a good solution. Refactoring your code into structured methods is never a bad idea. I hope this helps!
You are looping until you get an array that's all even. You should initialize b to be false, and update it to true in the (nested) for loop. Note that once's you've set it to false, there's no reason checking the other members of the array, and you can break out of the for loop.
Note, also, that using stream could make this check a tad more elegant:
b = Arrays.stream(arr).flatMapToInt(Arrays::stream).anyMatch(x -> x % 2 != 0)
What about generating random numbers up to 5 and double it? Then you don't have two check if they are even.
Instead of your last for loop:
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(Array[i][j] % 2!=0){
b=false;
break;
}
}
if(!b){
break;
}
}
if(!b){
break;
}
Alternatively, you could do an oddity check when you are generating the elements. Something like:
int element;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
do{
element = (int)(Math.random()*11);
}while(element % 2 !=0)
Array[i][j] = element;
}
}
That way you don't have to check the values, they will always be even.
This should work:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
anyOdd |= Array[i][j] % 2!=0;
}
}
} while(anyOdd);
}
}
As you can see, I just modified the condition from b to anyOdd, so if there is any odd number, it will iterate again.
Also, you can check it when you generate the random numbers, so you avoid a second loop:
import java.util.Scanner;
public class EvenArrayGenerator{
public static void main(String a[]){
boolean anyOdd;
int array = 0;
do{
System.out.println ("Array " + ++array + ":");
anyOdd=false;
int[][] Array = new int[4][4];
for(int i=0;i<4;i++) {
for(int j=0;j<4;j++) {
Array[i][j] = (int)(Math.random()*11);
anyOdd |= array[i][j] % 2 != 0;
}
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
System.out.print(Array[i][j] + " ");
}
System.out.println();
}
} while(anyOdd);
}
}
public class EvenArrayGenerator {
public static void main(String a[]) {
int[][] arr = createAllEvenArray(4);
printArray(arr);
}
private static int[][] createAllEvenArray(int size) {
while (true) {
int[][] arr = createArray(size);
printArray(arr);
if (isAllEven(arr))
return arr;
}
}
private static int[][] createArray(int size) {
int[][] arr = new int[size][size];
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
arr[i][j] = (int)(Math.random() * 11);
return arr;
}
private static void printArray(int[][] arr) {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (j > 0)
System.out.print("\t");
System.out.format("%2d", arr[i][j]);
}
System.out.println();
}
System.out.println();
}
private static boolean isAllEven(int[][] arr) {
for (int i = 0; i < arr.length; i++)
for (int j = 0; j < arr.length; j++)
if (arr[i][j] % 2 != 0)
return false;
return true;
}
}
I was writing the code for the least occurring element in the array and for some reason my logic goes wrong and the compiler just prints either the first or the second element in the array? anyone know what's wrong?
package javaapplication10;
import java.util.*;
public class JavaApplication10 {
public static void main(String[] args) {
int m =1000;
int count = 0;
int store = 0;
int c = 0;
Scanner scan = new Scanner(System.in);
int[] a = new int[20] ;
int n;
System.out.print("Enter no of elements");
n = scan.nextInt();
for(int i =0; i<n;i++) {
a[i] = scan.nextInt();
}
for(int i =0; i <n ; i++) {
c = a[i] ;
for(int j =0; j <n ; j++) {
if(a[j] ==c) {
count++ ;
}
if(j == (n-1)) {
if(count<m ) {
store = a[i];
m = count;
}
}
count = 0;
}
}
System.out.print(store);
}
}
A better solution is to do sorting. We first sort the array, then linearly traverse the array.
static int leastFrequent(int arr[], int n)
// n is length of array
{
// Sort the array
Arrays.sort(arr);
// find the min frequency using
// linear traversal
int min_count = n+1, res = -1;
int curr_count = 1;
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1])
curr_count++;
else {
if (curr_count < min_count) {
min_count = curr_count;
res = arr[i - 1];
}
curr_count = 1;
}
}
// If last element is least frequent
if (curr_count < min_count)
{
min_count = curr_count;
res = arr[n - 1];
}
return res;
}
I guess you are trying to implement the following logic
Find the count of each element in the array
If you find an element with lower count - store the element
Repeat for each element in the array - to find the lowest element.
You should have rest the count at the end of the inner loop as,
package javaapplication10;
import java.util.*;
public class JavaApplication10 {
public static void main(String[] args) {
int m =1000;
int count = 0;
int store = 0;
int c = 0;
Scanner scan = new Scanner(System.in);
int[] a = new int[20] ;
int n;
System.out.print("Enter no of elements");
n = scan.nextInt();
for(int i =0; i<n;i++) {
a[i] = scan.nextInt();
}
for(int i =0; i <n ; i++) {
c = a[i] ;
for(int j =0; j <n ; j++) {
if(a[j] ==c) {
count++ ;
}
if(j == (n-1)) {
if(count<m ) {
store = a[i];
m = count;
}
}
}
count = 0;
}
System.out.print(store);
}
}
You have a single counter, so you'll lose this counting once you transition from one element to another.
You could hold an auxiliary map of counters and update it as you go, but frankly, using Java's streams will save you a lot of boilerplate code:
int leastOccuring =
Arrays.stream(a)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())
.entrySet()
.stream()
.min(Map.Entry.comparingByValue())
.map(Map.Entry::geyKey)
.get();
This would be the correct code for your program.
import java.util.*;
public class LeastOccuringElementInArray {
public static void main(String[] args) {
int m = 0;
int count = 0;
int store = 0;
int c = 0;
Scanner scan = new Scanner(System.in);
int[] a = new int[20] ;
int n;
System.out.print("Enter no of elements");
n = scan.nextInt();
for(int i =0; i<n;i++)
{
a[i] = scan.nextInt();
}
for(int i =0; i <n ; i++)
{ c = a[i] ;
for(int j =0; j <n ; j++)
{
if(a[j] == c)
{
count++ ;
}
if(j == (n-1))
{
if(m!=0 && m > count)
{
store = a[i];
m = count;
}
else {
m = count;
}
}
}
count = 0;
}
System.out.print(store);
scan.close();
}
}