I'm trying to run a method that calls my class method below. Everytime I call the method computeIterative(), I get an ArrayIndexOutOfBoundsException. I added some code to print out the loop, and I see that the exception occurs around the second time through the loop, but the loop continues until complete. What am I doing wrong that I can't solve this array exception?
static int computeIterative(int n) {
efficiency = 0;
int[] a = new int[n];
int firstInt = 0;
int secondInt = 1;
int results = 0;
if (n > 1) {
a[0] = 0;
a[1] = 1;
for (int i = 2; i <= n; ++i) {
efficiency++;
firstInt = a[i-1];
secondInt = a[i-2];
results = 2 * firstInt + secondInt;
System.out.println("Loop " + efficiency + " of " + n );
System.out.println(firstInt);
System.out.println(secondInt);
System.out.println("Results: " + results);
a[i] = results;
}
} else {
a[0] = 0;
a[1] = 1;
}
return a[n];
}
Thank you for the help.
the error lies in the line
a[i] = results;
since in your for loop, you have been using :
for(i=2;i<=n;i++)
You will find that the array index starts from 0 and goes up to n-1. So when you are using :
i <= n
you will encounter an array out of bounds exception because it does not have a 'n'th element.
Change your for loop condition from :
i <= n
to :
i < n
and your code should work.
You have initiated array with size "n", you are trying to access a[n] element, array index starts from 0 to n-1.So when you access a[n] you are getting Arrayindexboundexception.
change this line from
int[] a = new int[n]; to int[] a = new int[n+1]; (line 3)
Works!!
If n is 2, you access a[2] (a[i] = results;) but there are only element 0 and 1
I have an addition program:
import java.io.*;
public class sum
{
int num;
int sum = 0;
int result;
public void findsum() throws IOException
{
BufferedReader Br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("enter the value for N : ");
num = Integer.parseInt(Br.readLine());
int nums[] = new int[num+1];
for(int i = 1; i <= num; i++)
{
System.out.print("\n Enter " + i + " number: ");
nums[i]= Integer.parseInt(Br.readLine());
sum = sum + nums[i];
}
System.out.print("\n Sum is : " + sum );
}
public static void main(String args[]) throws IOException
{
sum sm = new sum();
sm.findsum();
}
}
Output:
It takes N Integer values as input from the user and returns sum of those N numbers.
But I want if any of the number is equal to the other one it will automatically ignore them in addition.
Just verify if the input number isn't in the array yet.
Change your for loop with this and it will work fine:
for (int i = 1; i <= num; i++) {
System.out.print("\n Enter the " + i + " number : ");
int x = Integer.parseInt(Br.readLine());
int j=0;
while(j<num && nums[j]!=x) {
j++;
}
if(j>=num) {
nums[i] = x;
}
sum = sum + nums[i];
}
From your question
i want if any of the number is equal to the other one it will
automatically ignore them in addition
It will easy if you use Set here
Set<Integer> numbers=new HashSet<>();
for(int i = 1;i<=num;i++){
System.out.print("\n Enter " + i + " number : ");
numbers.add(Integer.parseInt(Br.readLine())); // add to set
}
Now duplicate values not consider. Then simply add elements in the Set.
There are couple of issues:
Your for loop starts with 1 and the index of array that you used is nums[i] which means your array will start with 1. Array start with 0th index so used i-1 when you are referring index in for loop for your array or use loop starting from 0 till n-1.
If you want to stick with your implementation with Array then in every for loop, before doing the sum you need to iterate over each earlier element to check if element already exist in an array something like:
numberFound = false;
for (int j = 1; j < i; j++) {
if (nums[j - 1] == nums[i - 1]) {
numberFound = true;
System.out.println("Duplicate number " + nums[i - 1]
+ " will be ignored");
break;
}
}
if (!numberFound) {
sum = sum + nums[i - 1];
}
Use Set to remove redundancy
Set<Integer> num = new HashSet<Integer>();
num.add(123);
num.add(123);
num.add(1);
num.add(1);
Integer sum=0;
for(Object a: num.toArray()){
sum+=(Integer)a;
}
System.out.println(sum); //124
When using Java 8 you can let the Stream API do the work:
Stream#distinct()
From the JavaDoc:
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.
How to use:
final int[] nums = new int[] {1, 2, 2, 3, 4, 4, 4};
final int sum = IntStream.of(nums)
.distinct()
.sum();
System.out.println(sum); // prints 10 (1 + 2 + 3 + 4);
I am attempting to find the occurrence frequency of a number in a sequence.
for example when sequence is :
1, 1, 3, 4
output should be
1 found 3 times
, 3 found 1 times
, 4 found 1 time
and so on. I have the following code
import java.util.*;
class fre {
public static void main(String a[]) {
int c = a.length;
int d[] = new int[c];
int num = 0;
for (int p = 0; p < c; p++)
d[p] = Integer.parseInt(a[p]);
for (int z : d)
System.out.println(z);
for (int i = 0; i < c - 1; i++) // FROM THIS LINE ERROR IS THROWN
{
for (int t = 0; t < c - 1; i++) {
if (d[i] == d[t]) {
num++;
}
}
System.out.println("the element" + i + "found" + num + "times");
}
}
}
ERROR : ARRAY OUT OF BOUND INDEX
Shouldn't
for (int t = 0; t < c - 1; i++)
be
for (int t = 0; t < c - 1; t++)
You are incrementing i again in the second loop.
Well, first of all, you increment i instead of t in the inner loop.
Changing this, the program seems to work.
Change the output line to sth. like
System.out.println("the element " + d[i] + " found " + num + " times");
To make it readable.
Not saying there is no better way to solve this...
ok
Benno
a is an array that holds all the command line parameters. You are using a.length which determines the amount of command line parameters given. I guess you probably want to pass the length of the array by a command line parameter instead. If I am correct, you should use something like int c = a[0]; to get the first command line parameter. Of course that is not good style without any checks, but if I get started on that I had to rewrite your whole code ;)
Your example is wrong.
Untested:
public static void main(String args[])
{
Map<Integer, Integer> result = new HashMap<>();
for (String s : args) {
Integer currentNumber = Integer.parseInt(s);
// don't forget error handling if s is not a number
Integer currentCount = result.get(currentNumber);
if (currentCount == null) { // you could also check with result.containsKey(..)
currentCount = 0;
}
result.put(currentNumber, currentCount + 1);
}
for (Map.Entry<Integer, Integer> entry : result) {
System.out.println("The element: " + entry.getKey() + " found " + entry.getValue() + " times");
}
}
This is probably slower than your version, but easier to understand.
I'm not sure why the hashmap is printing out different things inside this while loop and outside of the while loop. I declared the map outside the while loop, so I assumed that it should be the same inside and outside. In the code, I have the same print statement inside the while loop and outside of it, but they are printing different things. The key for the map is personCounter, which increments and should be unique. Would really appreciate your help.
public Map<Integer, double[]> setRating(CSVReader r, int taskNum, int taskWeightNumHeader)
throws NumberFormatException, IOException {
String[] line;
int personCounter = 0;
Map<Integer, double[]> indivTaskRating = new HashMap<Integer, double[]>();
while ((line = r.readNext()) != null) {
double[] perTaskWeight = new double[5];
personCounter++;
int multiplier = taskNum * 5;
perTaskWeight[2] = Double.parseDouble(line[taskWeightNumHeader + multiplier]);
perTaskWeight[1] = Double.parseDouble(line[taskWeightNumHeader + multiplier + 1]);
perTaskWeight[0] = Double.parseDouble(line[taskWeightNumHeader + multiplier + 2]);
perTaskWeight[3] = Double.parseDouble(line[taskWeightNumHeader + multiplier + 3]);
perTaskWeight[4] = Double.parseDouble(line[taskWeightNumHeader + multiplier + 4]);
indivTaskRating.put(personCounter, perTaskWeight);
for (int j = 0; j < 5; j ++) {
System.out.println("personID: " +1+ ", rating: " +indivTaskRating.get(1)[j]);
}
}
for (int j = 0; j < 5; j ++) {
System.out.println("personID: " + 1+ ", rating: " +indivTaskRating.get(1)[j]);
}
return indivTaskRating;
}
You are using the same double array in every entry you place in the map. At the end it will be populated with the same values for each entry!
You need to reallocate the array on each iteration of your while loop to fix the problem.
while ((line = r.readNext()) != null) {
double[] perTaskWeight = new double[5];
// ....
}
You keep reusing the same array, so you actually overwrite its content at each loop (while).
You need to create a new instance (double[] perTaskWeight = new double[5];) within the while loop.
I have to find the element with highest occurrences in a double array.
I did it like this:
int max = 0;
for (int i = 0; i < array.length; i++) {
int count = 0;
for (int j = 0; j < array.length; j++) {
if (array[i]==array[j])
count++;
}
if (count >= max)
max = count;
}
The program works, but it is too slow! I have to find a better solution, can anyone help me?
Update:
As Maxim pointed out, using HashMap would be a more appropriate choice than Hashtable here.
The assumption here is that you are not concerned with concurrency. If synchronized access is needed, use ConcurrentHashMap instead.
You can use a HashMap to count the occurrences of each unique element in your double array, and that would:
Run in linear O(n) time, and
Require O(n) space
Psuedo code would be something like this:
Iterate through all of the elements of your array once: O(n)
For each element visited, check to see if its key already exists in the HashMap: O(1), amortized
If it does not (first time seeing this element), then add it to your HashMap as [key: this element, value: 1]. O(1)
If it does exist, then increment the value corresponding to the key by 1. O(1), amortized
Having finished building your HashMap, iterate through the map and find the key with the highest associated value - and that's the element with the highest occurrence. O(n)
A partial code solution to give you an idea how to use HashMap:
import java.util.HashMap;
...
HashMap hm = new HashMap();
for (int i = 0; i < array.length; i++) {
Double key = new Double(array[i]);
if ( hm.containsKey(key) ) {
value = hm.get(key);
hm.put(key, value + 1);
} else {
hm.put(key, 1);
}
}
I'll leave as an exercise for how to iterate through the HashMap afterwards to find the key with the highest value; but if you get stuck, just add another comment and I'll get you more hints =)
Use Collections.frequency option:
List<String> list = Arrays.asList("1", "1","1","1","1","1","5","5","12","12","12","12","12","12","12","12","12","12","8");
int max = 0;
int curr = 0;
String currKey = null;
Set<String> unique = new HashSet<String>(list);
for (String key : unique) {
curr = Collections.frequency(list, key);
if(max < curr){
max = curr;
currKey = key;
}
}
System.out.println("The number " + currKey + " happens " + max + " times");
Output:
The number 12 happens 10 times
The solution with Java 8
int result = Arrays.stream(array)
.boxed()
.collect(Collectors.groupingBy(i->i,Collectors.counting()))
.values()
.stream()
.max(Comparator.comparingLong(i->i))
.orElseThrow(RuntimeException::new));
I will suggest another method. I don't know if this would work faster or not.
Quick sort the array. Use the built in Arrays.sort() method.
Now compare the adjacent elements.
Consider this example:
1 1 1 1 4 4 4 4 4 4 4 4 4 4 4 4 9 9 9 10 10 10 29 29 29 29 29 29
When the adjacent elements are not equal, you can stop counting that element.
Solution 1: Using HashMap
class test1 {
public static void main(String[] args) {
int[] a = {1,1,2,1,5,6,6,6,8,5,9,7,1};
// max occurences of an array
Map<Integer,Integer> map = new HashMap<>();
int max = 0 ; int chh = 0 ;
for(int i = 0 ; i < a.length;i++) {
int ch = a[i];
map.put(ch, map.getOrDefault(ch, 0) +1);
}//for
Set<Entry<Integer,Integer>> entrySet =map.entrySet();
for(Entry<Integer,Integer> entry : entrySet) {
if(entry.getValue() > max) {max = entry.getValue();chh = entry.getKey();}
}//for
System.out.println("max element => " + chh);
System.out.println("frequency => " + max);
}//amin
}
/*output =>
max element => 1
frequency => 4
*/
Solution 2 : Using count array
public class test2 {
public static void main(String[] args) {
int[] a = {1,1,2,1,5,6,6,6,6,6,8,5,9,7,1};
int max = 0 ; int chh = 0;
int count[] = new int[a.length];
for(int i = 0 ; i <a.length ; i++) {
int ch = a[i];
count[ch] +=1 ;
}//for
for(int i = 0 ; i <a.length ;i++) {
int ch = a[i];
if(count[ch] > max) {max = count[ch] ; chh = ch ;}
}//for
System.out.println(chh);
}//main
}
Here's a java solution --
List<Integer> list = Arrays.asList(1, 2, 2, 3, 2, 1, 3);
Set<Integer> set = new HashSet(list);
int max = 0;
int maxtemp;
int currentNum = 0;
for (Integer k : set) {
maxtemp = Math.max(Collections.frequency(list, k), max);
currentNum = maxtemp != max ? k : currentNum;
max = maxtemp;
}
System.out.println("Number :: " + currentNum + " Occurs :: " + max + " times");
int[] array = new int[] { 1, 2, 4, 1, 3, 4, 2, 2, 1, 5, 2, 3, 5 };
Long max = Arrays.stream(array).boxed().collect(Collectors.groupingBy(i -> i, Collectors.counting())).values()
.stream().max(Comparator.comparing(Function.identity())).orElse(0L);
public static void main(String[] args) {
int n;
int[] arr;
Scanner in = new Scanner(System.in);
System.out.println("Enter Length of Array");
n = in.nextInt();
arr = new int[n];
System.out.println("Enter Elements in array");
for (int i = 0; i < n; i++) {
arr[i] = in.nextInt();
}
int greatest = arr[0];
for (int i = 0; i < arr.length; i++) {
if (arr[i] > greatest) {
greatest = arr[i];
}
}
System.out.println("Greatest Number " + greatest);
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (greatest == arr[i]) {
count++;
}
}
System.out.println("Number of Occurance of " + greatest + ":" + count + " times");
in.close();
}
In continuation to the pseudo-code what you've written try the below written code:-
public static void fetchFrequency(int[] arry) {
Map<Integer, Integer> newMap = new TreeMap<Integer, Integer>(Collections.reverseOrder());
int num = 0;
int count = 0;
for (int i = 0; i < arry.length; i++) {
if (newMap.containsKey(arry[i])) {
count = newMap.get(arry[i]);
newMap.put(arry[i], ++count);
} else {
newMap.put(arry[i], 1);
}
}
Set<Entry<Integer, Integer>> set = newMap.entrySet();
List<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set);
Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
#Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
for (Map.Entry<Integer, Integer> entry : list) {
System.out.println(entry.getKey() + " ==== " + entry.getValue());
break;
}
//return num;
}
This is how i have implemented in java..
import java.io.*;
class Prog8
{
public static void main(String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Input Array Size:");
int size=Integer.parseInt(br.readLine());
int[] arr= new int[size];
System.out.println("Input Elements in Array:");
for(int i=0;i<size;i++)
arr[i]=Integer.parseInt(br.readLine());
int max = 0,pos=0,count = 0;
for (int i = 0; i < arr.length; i++)
{
count=0;
for (int j = 0; j < arr.length; j++)
{
if (arr[i]==arr[j])
count++;
}
if (count >=max)
{
max = count;
pos=i;
}
}
if(max==1)
System.out.println("No Duplicate Element.");
else
System.out.println("Element:"+arr[pos]+" Occourance:"+max);
}
}
Find the element with the highest occurrences in an array using java 8 is given below:
final Long maxOccurrencesElement = arr.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.max((o1, o2) -> o1.getValue().compareTo(o2.getValue()))
.get()
.getKey();
You can solve this problem in one loop with without using HashMap or any other data structure in O(1) space complexity.
Initialize two variables count = 0 and max = 0 (or Integer.MIN_VALUE if you have negative numbers in your array)
The idea is you will scan through the array and check the current number,
if it is less than your current max...then do nothing
if it is equal to your max ...then increment the count variable
if it is greater than your max..then update max to current number and set count to 1
Code:
int max = 0, count = 0;
for (int i = 0; i < array.length; i++) {
int num = array[i];
if (num == max) {
count++;
} else if (num > max) {
max = num;
count = 1;
}
}
Here is Ruby SOlution:
def maxOccurence(arr)
m_hash = arr.group_by(&:itself).transform_values(&:count)
elem = 0, elem_count = 0
m_hash.each do |k, v|
if v > elem_count
elem = k
elem_count = v
end
end
"#{elem} occured #{elem_count} times"
end
p maxOccurence(["1", "1","1","1","1","1","5","5","12","12","12","12","12","12","12","12","12","12","8"])
output:
"12 occured 10 times"