Java - ArrayIndexOutOfBoundsException - java

I am working on a java program that generates random numbers and then puts them in an array. Then the program is supposed to go through the array, put the even and the odd numbers in two new arrays, and present them to the user. The program also tells the user how many odd and even numbers there are in the array.
I get "ArrayIndexOutOfBoundsException" when trying to compile this code.
Can someone tell me why?
import java.util.Scanner;
import java.util.Random;
import java.util.Arrays;
class Randomnumbers
{
public static void main ( String[] args )
{
Random random;
int i;
int numberOfNumbers=0;
int upperRange=999;
int lowerRange=0;
int randomNumber=0;
int even=0;
int odd=0;
int currentOdd=0;
int currentEven=0;
int[] oddNumbers=new int[0];
int[] evenNumbers=new int[0];
Scanner in = new Scanner(System.in);
System.out.println("Please enter how many random numbers you want(0-999)");
numberOfNumbers=in.nextInt();
int[] numbers=new int[numberOfNumbers];
random = new Random();
for (i = 0; i < numbers .length; i++){
randomNumber = random.nextInt(upperRange-lowerRange) + lowerRange;
numbers[i] = randomNumber;
}
System.out.println("\n" +"These are the random numbers:");
System.out.println(Arrays.toString(numbers));
for(i=0; i < numbers .length; i++){
if((numbers[i] % 2) == 0)
{
even = even + 1;
}
else
{
odd = odd + 1;
}
}
evenNumbers=new int[even];
oddNumbers=new int[odd];
for(i=0; i < numbers .length; i++){
if((numbers[i] % 2) == 0)
{
evenNumbers[i]=numbers[i];
}
else
{
// this is the code line the compiler does not like:
oddNumbers[i]=numbers[i];
}
}
System.out.println("The following " +even +" numbers are even:");
System.out.println(Arrays.toString(evenNumbers));
System.out.println("The following " +odd +" numbers are odd:");
System.out.println(Arrays.toString(oddNumbers));
}

It is really not a good practice to run through the loop multiple times.
I would the code to only traverse the random array a single time.
List<Integer> evenNumbers = new ArrayList<>();
List<Integer> oddNumbers = new ArrayList<>();
for (i = 0; i < numbers.length; ++i) {
if (numbers[i] % 2 == 0) {
evenNumbers.add(numbers[i]);
}
else {
oddNumbers.add(numbers[i]);
}
}
You can get the total number of evens/odds from the size of the respective Lists, and you can print them out, iterate them, etc.
Of course, this approach assumes you can actually use Java objects as opposed to merely arrays.
If you must use arrays, then change the final part of the code to after the allocation for the evenNumbers and oddNumbers arrays to:
int evenIdx = 0;
int oddIdx = 0;
for (i = 0; i < numbers.length; ++i) {
if (numbers[i] % 2 == 0) {
evenNumbers[evenIdx++] = numbers[i];
}
else {
oddNumbers[oddIdx++] = numbers[i];
}
}

The problem is:
oddNumbers[i]=numbers[i];
Because: the number of elements in oddNumbers is not the same as numbers
When you use the index i to access the element in the array number, you accidentally, try to access the i^th element in the oddNumber that causes ArrayIndexOutOfBound.
Fix: At least, make sure the index i< oddNumber.length and i< numbers.length
For example
for(i=0; i <numbers .length && i<oddNumbers.length; i++){

Problem statements are below. Depending on the random numbers generated either of the statements will result in ArrayIndexOutBoundsException.
evenNumbers[i]=numbers[i];
oddNumbers[i]=numbers[i];
Here are some of the options to resolve this:
Maintain separate indexes for evenNumbers and oddNumbers in
for(i=0; i < numbers.length; i++){
if((numbers[i] % 2) == 0)
{
evenNumbers[eIndex++] = numbers[i];
}
else
{
oddNumbers[oIndex++] = numbers[i];
}
}
Use List<Integer> for oddNumbers & evenNumbers.
List<Integer> oddNumbers = new ArrayList<Integer>();
List<Integer> evenNumbers = new ArrayList<Integer>();
for(i=0; i < numbers.length; i++){
if((numbers[i] % 2) == 0)
{
evenNumbers.add(numbers[i]);
}
else{
oddNumbers.add(numbers[i]);
}
}

Related

I don't know how assign new value to the empty array

I am a beginner in coding. I have to write a code that will divide array with random numbers into two different arrays. One array will contain odd numbers, the other one even numbers. But something is wrong, and i don't really know what to do.
According to the console the problem is in the place where there is a lot of exclamation marks. when i change those lines to System.out.println("x") it works perfectly fine.
public void P_N () {
int I_E = 0; // amount of even numbers
int I_O = 0; // amount of odd numbers
for (int i = 0; i < tab2.length; i++) { // tab2 is a array with random numbers
if (tab2[i] % 2 == 0)
I_E = I_E + 1;
else
I_O = I_O+1;
}
int [] tab_E = new int[I_E]; // array with even numbers
int [] tab_O = new int [I_O]; // array with odd numbers
for (int i = 0; i < tab2.length; i++){
if (tab2[i] % 2 == 0){
tab_E[i] = tab2[i]; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
for (int i = 0; i < tab2.length; i++){
if (tab2[i] % 2 != 0){
tab_O[i] = tab2[i]; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
for (int i = 0; i< tab_E.length; i++) {
System.out.println("Even array: " + tab_E[i]);
System.out.println("------------------------------------------------");
}
for (int i = 0; i< tab_O.length; i++) {
System.out.println("Odd array: " + tab_O[i]);
}
}
Problem is in going out of bounds for arrays tab_E and tab_O, when variable i is more tab_E.length. Just create another variable, for example "j". And iterate throug your array using it. Like I'v written below
int j = 0;
for (int i = 0; i < tab2.length; i++) {
if (tab2[i] % 2 == 0) {
tab_E[j++] = tab2[i];
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
j = 0;
for (int i = 0; i < tab2.length; i++) {
if (tab2[i] % 2 != 0) {
tab_O[j++] = tab2[i];
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
I would rather use 2 ArrayLists one for even numbers and another one is for odd numbers and later convert it into array using toArray() method.
public void P_N(){
ArrayList<Integer> evenNumberList = new ArrayList<Integer>();
ArrayList<Integer> oddNumberList = new ArrayList<Integer>();
for (int i = 0; i < tab2.length; i++) { // tab2 is a array with random numbers
if (tab2[i] % 2 == 0) {
evenNumberList.add(tab2[i]);
} else {
oddNumberList.add(tab2[i]);
}
}
int[] evenNumberArray = evenNumberList.toArray();
int[] oddNumberArray = oddNumberList.toArray();
}
This will take some extra space but makes your application more efficient, I hope this helps.
You have initialized the even/odd number arrays with a quantity of the even/odd numbers accordingly:
int [] tab_E = new int[I_E]; // array with even numbers
int [] tab_O = new int [I_O]; // array with odd numbers
Ii is reasonable to assume that the sizes of even or odd number arrays are might be much smaller than the size of the original source array.
But in this even number filtering loop (as well as in the odd filtering loop) you use source array index values to address target array positions, end eventually face the ArrayIndexOutOfBoundsException.
for (int i = 0; i < tab2.length; i++)
{
if (tab2[i] % 2 == 0)
{
tab_E[i] = tab2[i]; //here the same i value is used to address non existing index in tab_E array
}
}
A quick fix might be the following:
int tab_E_index = 0;
for (int i = 0; i < tab2.length; i++){
if (tab2[i] % 2 == 0){
tab_E[tab_E_index] = tab2[i]; //i value gets incremented every loop iteration
tab_E_index++; //tab_E_index value get incremented only when even number is added to the tab_E array
}
}
Please don't just copy/paste it, but try to understand what caused the issue on the first place. Good luck and happy coding.

Is there any way for Array Elements to be created through a for-loop?

So, I wanted to write a method that would create an array containing all divisors of a certain number. So I created an empty array (int[] divisors) that would later get it's numbers through a for-loop but it says that the array hasn't been initialized yet. What should I do?
The output of the method would later be used to find the greatest common divisor of two numbers, so it's important that the numbers in the array are ordered from smallest to biggest. I know there's a much easier solution to do this, but I want do it using arrays, because I want to focus on learning those at the moment.
public static int[] allDivisors(int number) {
int[] divisors;
int counter= 0;
for (int i = 0; i <= number; i++) {
if(number % i == 0) {
divisors[counter]= i;
counter++;
}
}
return divisors;
}
I couldn't find any proper solutions to my problem online so I hope someone we'll be able to help me out here. All I need is a way to add specific elements to an array which I can't define beforehand (in that case, all divisors of a certain number.) Thanks in advance for all your answers!
Array is not the proper data structure for this case because you need to initialize it with a size (integer number) prior of its use.
But you don't know how many items you will store in the array, right?
So you must use an ArrayList like this:
public static ArrayList<Integer> allDivisors(int number) {
ArrayList<Integer> divisors = new ArrayList<>();
for (int i = 1; i <= number; i++) {
if(number % i == 0) {
divisors.add(i);
}
}
return divisors;
}
I also changed in the loop:
int i = 0
to
int i = 1
to avoid division by 0 later in:
number % i
Also you don't need counter.
You can call this method in your code:
int number = 30;
ArrayList<Integer> list = allDivisors(number);
System.out.println("The divisors of " + number + " are:");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
and it will print:
The divisors of 30 are:
1 2 3 5 6 10 15 30
If you strictly want to do this using arrays, try below changes to your program.
public static int[] allDivisors(int number) {
int[] divisors = new int[number]; // Have to initialize the array
int counter= 0;
for (int i = 1; i <= number; i++) { // i should start from 1; not from zero. Otherwise you get ArithmeticException (divide by zero)
if(number % i == 0) {
divisors[counter]= i;
counter++;
}
}
int[] trimmedDivisors = new int[counter];
System.arraycopy(divisors, 0, trimmedDivisors, 0, counter);
return trimmedDivisors;
}
In java before you use array you must be initializate it.
public static int[] allDivisors(int number) {
int[] divisors = new int[number];
int counter= 0;
for (int i = 0; i <= number; i++) {
if(number % i == 0) {
divisors[counter]= i;
counter++;
}
}
Arrays.sort(divisors);
return divisors;
}

randomly generate 100 unique numbers using Math.random [duplicate]

my intend is to use simplest java (array and loops) to generate random numbers without duplicate...but the output turns out to be 10 repeating numbers, and I cannot figure out why.
Here is my code:
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
do {
for (int i=0; i<number.length; i++) {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
}
} while (!repeat);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
How about you use a Set instead? If you also want to keep track of the order of insertion you can use a LinkedHashSet.
Random r = new Random();
Set<Integer> uniqueNumbers = new HashSet<>();
while (uniqueNumbers.size()<10){
uniqueNumbers.add(r.nextInt(21));
}
for (Integer i : uniqueNumbers){
System.out.print(i+" ");
}
A Set in java is like an Array or an ArrayList except it handles duplicates for you. It will only add the Integer to the set if it doesn't already exist in the set. The class Set has similar methods to the Array that you can utilize. For example Set.size() is equivalent to the Array.length and Set.add(Integer) is semi-equivalent to Array[index] = value. Sets do not keep track of insertion order so they do not have an index. It is a very powerful tool in Java once you learn about it. ;)
Hope this helps!
You need to break out of the for loop if either of the conditions are met.
int[] number = new int[10];
int count=0;
int num;
Random r = new Random();
while(count<number.length){
num = r.nextInt(21);
boolean repeat=false;
do{
for(int i=0; i<number.length; i++){
if(num==number[i]){
repeat=true;
break;
}
else if(i==count){
number[count]=num;
count++;
repeat=true;
break;
}
}
}while(!repeat);
}
for(int j=0;j<number.length;j++){
System.out.print(number[j]+" ");
}
This will make YOUR code work but #gonzo proposed a better solution.
Your code will break the while loop under the condition: num == number[i].
This means that if the pseudo-generated number is equal to that positions value (the default int in java is 0), then the code will end execution.
On the second conditional, the expression num != number[i] is always true (otherwise the code would have entered the previous if), but, on the first run, when i == count (or i=0, and count=0) the repeat=true breaks the loop, and nothing else would happen, rendering the output something such as
0 0 0 0 0 0...
Try this:
int[] number = new int[10];
java.util.Random r = new java.util.Random();
for(int i=0; i<number.length; i++){
boolean repeat=false;
do{
repeat=false;
int num = r.nextInt(21);
for(int j=0; j<number.length; j++){
if(number[j]==num){
repeat=true;
}
}
if(!repeat) number[i]=num;
}while(repeat);
}
for (int k = 0; k < number.length; k++) {
System.out.print(number[k] + " ");
}
System.out.println();
Test it here.
I believe the problem is much easier to solve. You could use a List to check if the number has been generated or not (uniqueness). Here is a working block of code.
int count=0;
int num;
Random r = new Random();
List<Integer> numbers = new ArrayList<Integer>();
while (count<10) {
num = r.nextInt(21);
if(!numbers.contains(num) ) {
numbers.add(num);
count++;
}
}
for(int j=0;j<10;j++){
System.out.print(numbers.get(j)+" ");
}
}
Let's start with the most simple approach, putting 10 random - potentially duplicated - numbers into an array:
public class NonUniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
number[count++] = ThreadLocalRandom.current().nextInt(21);
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
So that gets you most of the way there, the only thing you know have to do is pick a number and check your array:
public class UniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
int candidate = ThreadLocalRandom.current().nextInt(21);
// Is candidate in our array already?
boolean exists = false;
for (int i = 0; i < count; i++) {
if (number[i] == candidate) {
exists = true;
break;
}
}
// We didn't find it, so we're good to add it to the array
if (!exists) {
number[count++] = candidate;
}
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
The problem is with your inner 'for' loop. Once the program finds a unique integer, it adds the integer to the array and then increments the count. On the next loop iteration, the new integer will be added again because (num != number[i] && i == count), eventually filling up the array with the same integer. The for loop needs to exit after adding the unique integer the first time.
But if we look at the construction more deeply, we see that the inner for loop is entirely unnecessary.
See the code below.
import java.util.*;
public class RandomDemo {
public static void main( String args[] ){
// create random object
Random r = new Random();
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
int i=0;
do {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
i++;
} while (!repeat && i < number.length);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
}
}
This would be my approach.
import java.util.Random;
public class uniquerandom {
public static void main(String[] args) {
Random rnd = new Random();
int qask[]=new int[10];
int it,i,t=0,in,flag;
for(it=0;;it++)
{
i=rnd.nextInt(11);
flag=0;
for(in=0;in<qask.length;in++)
{
if(i==qask[in])
{
flag=1;
break;
}
}
if(flag!=1)
{
qask[t++]=i;
}
if(t==10)
break;
}
for(it=0;it<qask.length;it++)
System.out.println(qask[it]);
}}
public String pickStringElement(ArrayList list, int... howMany) {
int counter = howMany.length > 0 ? howMany[0] : 1;
String returnString = "";
ArrayList previousVal = new ArrayList()
for (int i = 1; i <= counter; i++) {
Random rand = new Random()
for(int j=1; j <=list.size(); j++){
int newRand = rand.nextInt(list.size())
if (!previousVal.contains(newRand)){
previousVal.add(newRand)
returnString = returnString + (i>1 ? ", " + list.get(newRand) :list.get(newRand))
break
}
}
}
return returnString;
}
Create simple method and call it where you require-
private List<Integer> q_list = new ArrayList<>(); //declare list integer type
private void checkList(int size)
{
position = getRandom(list.size()); //generating random value less than size
if(q_list.contains(position)) { // check if list contains position
checkList(size); /// if it contains call checkList method again
}
else
{
q_list.add(position); // else add the position in the list
playAnimation(tv_questions, 0, list.get(position).getQuestion()); // task you want to perform after getting value
}
}
for getting random value this method is being called-
public static int getRandom(int max){
return (int) (Math.random()*max);
}

Non-repeating random numbers inside array JAVA

I would like to generate 6 numbers inside an array and at the same time, having it compared so it will not be the same or no repeating numbers. For example, I want to generate 1-2-3-4-5-6 in any order, and most importantly without repeating. So what I thought is to compare current array in generated array one by one and if the number repeats, it will re-run the method and randomize a number again so it will avoid repeating of numbers.
Here is my code:
import javax.swing.*;
public class NonRepeat
{
public static void main(String args[])
{
int Array[] = new int [6];
int login = Integer.parseInt(JOptionPane.showInputDialog("ASD"));
while(login != 0)
{
String output="";
for(int index = 0; index<6; index++)
{
Array[index] = numGen();
for(int loop = 0; loop <6 ; loop++)
{
if(Array[index] == Array[loop])
{
Array[index] = numGen();
}
}
}
for(int index = 0; index<6; index++)
{
output += Array[index] + " ";
}
JOptionPane.showMessageDialog(null, output);
}
}
public static int numGen()
{
int random = (int)(1+Math.random()*6);
return random;
}
}
I've been thinking it for 2 hours and still cant generate 6 numbers without repeating.
Hope my question will be answered.
Btw, Im new in codes so please I just want to compare it using for loop or while loop and if else.
You can generate numbers from, say, 1 to 6 (see below for another solution) then do a Collections.shuffle to shuffle your numbers.
final List<Integer> l = new ArrayList<Integer>();
for (int j = 1; j < 7; j++ ) {
l.add( j );
}
Collections.shuffle( l );
By doing this you'll end up with a randomized list of numbers from 1 to 6 without having twice the same number.
If we decompose the solution, first you have this, which really just create a list of six numbers:
final List<Integer> l = new ArrayList<Integer>();
for (int j = 1; j < 7; j++ ) {
l.add( j );
}
So at this point you have the list 1-2-3-4-5-6 you mentioned in your question. You're guaranteed that these numbers are non-repeating.
Then you simply shuffle / randomize that list by swapping each element at least once with another element. This is what the Collections.shuffle method does.
The solutions that you suggested isn't going to be very efficient: depending on how big your list of numbers is and on your range, you may have a very high probability of having duplicate numbers. In that case constantly re-trying to generate a new list will be slow. Moreover any other solution suggesting to check if the list already contains a number to prevent duplicate or to use a set is going to be slow if you have a long list of consecutive number (say a list of 100 000 numbers from 1 to 100 000): you'd constantly be trying to randomly generate numbers which haven't been generated yet and you'd have more and more collisions as your list of numbers grows.
If you do not want to use Collections.shuffle (for example for learning purpose), you may still want to use the same idea: first create your list of numbers by making sure there aren't any duplicates and then do a for loop which randomly swap two elements of your list. You may want to look at the source code of the Collections.shuffle method which does shuffle in a correct manner.
EDIT It's not very clear what the properties of your "random numbers" have to be. If you don't want them incremental from 1 to 6, you could do something like this:
final Random r = new Random();
final List<Integer> l = new ArrayList<Integer>();
for (int j = 0; j < 6; j++ ) {
final int prev = j == 0 ? 0 : l.get(l.size() - 1);
l.add( prev + 1 + r.nextInt(42) );
}
Collections.shuffle( l );
Note that by changing r.nextInt(42) to r.nextInt(1) you'll effectively get non-repeating numbers from 1 to 6.
You have to check if the number already exist, you could easily do that by putting your numbers in a List, so you have access to the method contains. If you insist on using an array then you could make a loop which checks if the number is already in the array.
Using ArrayList:
ArrayList numbers = new ArrayList();
while(numbers.size() < 6) {
int random = numGen(); //this is your method to return a random int
if(!numbers.contains(random))
numbers.add(random);
}
Using array:
int[] numbers = new int[6];
for (int i = 0; i < numbers.length; i++) {
int random = 0;
/*
* This line executes an empty while until numGen returns a number
* that is not in the array numbers yet, and assigns it to random
*/
while (contains(numbers, random = numGen()))
;
numbers[i] = random;
}
And add this method somewhere as its used in the snippet above
private static boolean contains(int[] numbers, int num) {
for (int i = 0; i < numbers.length; i++) {
if (numbers[i] == num) {
return true;
}
}
return false;
}
Here is the solution according to your code -
You just need to change the numGen method -
public static int numGen(int Array[])
{
int random = (int)(1+Math.random()*6);
for(int loop = 0; loop <Array.length ; loop++)
{
if(Array[loop] == random)
{
return numGen(Array);
}
}
return random;
}
Complete code is -
import javax.swing.*;
public class NonRepeat
{
public static void main(String args[])
{
int login = Integer.parseInt(JOptionPane.showInputDialog("ASD"));
while(login != 0)
{
int Array[] = new int [6];
String output="";
for(int index = 0; index<6; index++)
{
Array[index] = numGen(Array);
}
for(int index = 0; index<6; index++)
{
output += Array[index] + " ";
}
JOptionPane.showMessageDialog(null, output);
}
}
public static int numGen(int Array[])
{
int random = (int)(1+Math.random()*6);
for(int loop = 0; loop <Array.length ; loop++)
{
if(Array[loop] == random)
{
return numGen(Array);
}
}
return random;
}
}
Use List instead of array and List#contains to check if number is repeated.
you can use a boolean in a while loop to identify duplicates and regenerate
int[] array = new int[10]; // array of length 10
Random rand = new Random();
for (int i = 0 ; i < array.length ; i ++ ) {
array[i] = rand.nextInt(20)+1; // random 1-20
boolean found = true;
while (found) {
found = false;
// if we do not find true throughout the loop it will break (no duplicates)
int check = array[i]; // check for duplicate
for (int j = 0 ; j < i ; j ++) {
if ( array[j] == check ) {
found = true; // found duplicate
}
}
if (found) {
array[i] = rand.nextInt(20)+1 ; // replace
}
}
}
System.out.println(Arrays.toString(array));
You may use java.util.Random. And please specify if you want any random number or just the number 1,2,3,4,5,6. If you wish random numbers then , this is a basic code:
import java.util.*;
public class randomnumber
{
public static void main(String[] args)
{
Random abc = new Random();
int[] a = new int[6];
int limit = 100,c=0;
int chk = 0;
boolean y = true;
for(;c < 6;)
{
int x = abc.nextInt(limit+1);
for(int i = 0;i<a.length;i++)
{
if(x==a[i])
{
y=false;
break;
}
}
if(y)
{
if(c!=0)if(x == (a[c-1]+1))continue;
a[c]=x;
c++;
}
}
for (Integer number : a)
{
System.out.println(number);
}
}
}
if you don't understand the last for loop , please tell , i will update it.
Use List and .contains(Object obj) method.
So you can verify if list has the random number add before.
update - based on time you can lost stuck in random loop.
List<Integer> list = new ArrayList<Integer>();
int x = 1;
while(x < 7){
list.add(x);
x++;
}
Collections.shuffle(list);
for (Integer number : list) {
System.out.println(number);
}
http://docs.oracle.com/javase/7/docs/api/java/util/List.html#contains(java.lang.Object)

Given an array with 2 integers that repeat themselves the same no. of times, how do i print the two integers

i'm new to this, Say if you typed 6 6 6 1 4 4 4 in the command line, my code gives the most frequent as only 6 and i need it to print out 6 and 4 and i feel that there should be another loop in my code
public class MostFrequent {
//this method creates an array that calculates the length of an integer typed and returns
//the maximum integer...
public static int freq(final int[] n) {
int maxKey = 0;
//initiates the count to zero
int maxCounts = 0;
//creates the array...
int[] counts = new int[n.length];
for (int i=0; i < n.length; i++) {
for (int j=0; j < n[i].length; j++)
counts[n[i][j]]++;
if (maxCounts < counts[n[i]]) {
maxCounts = counts[n[i]];
maxKey = n[i];
}
}
return maxKey;
}
//method mainly get the argument from the user
public static void main(String[] args) {
int len = args.length;
if (len == 0) {
//System.out.println("Usage: java MostFrequent n1 n2 n3 ...");
return;
}
int[] n = new int[len + 1];
for (int i=0; i<len; i++) {
n[i] = Integer.parseInt(args[i]);
}
System.out.println("Most frequent is "+freq(n));
}
}
Thanks...enter code here
Though this may not be a complete solution, it's a suggestion. If you want to return more than one value, your method should return an array, or better yet, an ArrayList (because you don't know how many frequent numbers there will be). In the method, you can add to the list every number that is the most frequest.
public static ArrayList<Integer> freq(final int[] n) {
ArrayList<Integer> list = new ArrayList<>();
...
if (something)
list.add(thatMostFrequentNumber)
return list;
}
The solutions looks like this:
// To use count sort the length of the array need to be at least as
// large as the maximum number in the list.
int[] counts = new int[MAX_NUM];
for (int i=0; i < n.length; i++)
counts[n[i]]++;
// If your need more than one value return a collection
ArrayList<Integer> mf = new ArrayList<Integer>();
int max = 0;
for (int i = 0; i < MAX_NUM; i++)
if (counts[i] > max)
max = counts[i];
for (int i = 0; i < MAX_NUM; i++)
if (counts[i] == max)
mf.add(i);
return mf;
Well you can just do this easily by using the HashTable class.
Part 1. Figure out the frequency of each number.
You can do this by either a HashTable or just a simple array if your numbers are whole numbrs and have a decent enough upper limit.
Part 2. Find duplicate frequencies.
You can just do a simple for loop to figure out which numbers are repeated more than once and then print them accordingly. This wont necessarily give them to you in order though so you can store the information in the first pass and then print it out accordingly. You can use a HashTable<Integer,ArrayList<Integer> for this. Use the key to store frequency and the ArrayList to store the numbers that fall within that frequency.
You can maintain a "max" here while inserting into our HashTable if you only want to print out only the things with most frequency.
Here is a different way to handle this. First you sort the list, then loop through and keep track of the largest numbers:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int n[] = { 6, 4, 6, 4, 6, 4, 1 };
List<Integer> maxNums = new ArrayList<Integer>();
int max = Integer.MIN_VALUE;
Integer lastValue = null;
int currentCount = 0;
Arrays.sort(n);
for( int i : n ){
if( lastValue == null || i != lastValue ){
if( currentCount == max ){
maxNums.add(lastValue);
}
else if( currentCount > max ){
maxNums.clear();
maxNums.add(lastValue);
max = currentCount;
}
lastValue = i;
currentCount = 1;
}
else {
currentCount++;
}
System.out.println("i=" + i + ", currentCount=" + currentCount);
}
if( currentCount == max ){
maxNums.add(lastValue);
}
else if( currentCount >= max ){
maxNums.clear();
maxNums.add(lastValue);
}
System.out.println(maxNums);
}
}
You can try it at: http://ideone.com/UbmoZ5

Categories