I couldn't create a method to count the number of occurrences - java

I've created a method to count the number of occurrences in an array, but I can't compile and run it.
Compiler gives the error:
The method occurence(int[]) in the type countOfOccurence is not applicable for the arguments (int)
public class countOfOccurence {
public static void main(String[] args) {
int[] number = {15,16,14};
System.out.print(occurence(number[15]));
}
public static int occurence(int[] number) {
int count = 0;
for(int i = 0 ; i < number.length; i++) {
for(int k = 0 ; i < number.length; i++) {
if(number[k] == number[i]) {
count++;
}
}
}
return count;
}
}

Your occurrence method is expecting an array, but you are just passing an int to it (the 15th element from your array, which will also cause a runtime error as there are only 3 elements in your array).
But I also think your logic is off here, your current method (given that it would compile) will count all occurrences of all duplicate numbers in your array, not just the number you would want.
First off all, your occurrence method would need 2 arguments, the actual array and the number you want to count the occurrences of. You don't need an inner loop, just keep your outer loop and check inside whether the array element equals your desired number.
public static void main(String[] args) {
int[] number = {15,16,14};
System.out.print(occurence(number, 15));
}
public static int occurence(int[] numberArray, int number) {
int count = 0;
for(int i = 0 ; i < numberArray.length; i++) {
if(numberArray[i] == number) {
count++;
}
}
return count;
}
Of course there are better / cleaner ways to count occurrences of elements in an array, for example using the Streams api, if you would want to optimize.

occurence(int[] number) function accepts the integer array parameter. And, you are calling the function with occurence(number[15]). By number[15], it means 15th-index position from number array, which is also not valid in your code.
For your scenario to work, occurence function should be changed to accept two parameters like public static int occurence(int[] numbers, int number). And, call it by occurence(number, 15).

Related

Finding the sum of common elements between n number of arrays in java

I have a program that sums the common elements of two arrays. For that I used two for loops and if I have three then I could use three for loops. But how to sum the common elements of n number of arrays where n is coming during run time.
I don't know how to change the number of loops during run time or is there any other relevant concept for this ?
Here is the code I've tried for summing twoarrays:
import java.util.Scanner;
public class Sample {
public static void main(String... args)
{
Scanner sc=new Scanner(System.in);
int arr1[]={1,2,3,4,5},arr2[]={4,5,6,7,8},sum=0;
for (int i=0;i<arr1.length;i++)
{
for (int j=0;j<arr2.length;j++)
{
if (arr1[i]==arr2[j])
{
sum+=(arr1[i]);
}
}
}
}
}
There can be different implementation for that. You can use the following approach. Here is the pseudo code
use a 2D array to store the array. if the number of array is n and size is m then the array will be input[n][m]
Use a ArrayList commonItems to store the common items of. Initiate it with the elements of input[0]
Now iterate through the array for i = 1 to n-1. compare with every input[i], store only the common items of commonItems and input[i] at each step. You can do it by converting the input[i] into a list and by using retainAll method.
At the end of the iteration the commonItem list will contains the common numbers only. Now sum the value of this list.
There is actually a more general method, that also answers the question "how to change the number of loops during run time?".
The general question
We are looking for a way to implement something equivalent to this:
for (i1 = 0; i1 < k1; i1++) {
for (i2 = 0; i2 < k2; i2++) {
for (i3 = 0; i3 < k3; i3++) {
...
for (in = 0; in < kn; in++) {
f(x1[i1], x2[i2], ... xn[in]);
}
...
}
}
}
where, n is given at runtime and f is a function taking a list of n parameters, processing the current n-tuple.
A general solution
There is a general solution, based on the concept of recursion.
This is one implementation that produces the desired behavior:
void process(int idx, int n, int[][] x, int[] k, Object[] ntuple) {
if (idx == n) {
// we have a complete n-tuple,
// with an element from each of the n arrays
f(ntuple);
return;
}
// this is the idx'th "for" statement
for (int i = 0; i < k[idx]; i++) {
ntuple[idx] = x[idx][i];
// with this recursive call we make sure that
// we also generate the rest of the for's
process(idx + 1, n, x, k, ntuple);
}
}
The function assumes that the n arrays are stored in a matrix x, and the first call should look like this:
process(0, n, x, k, new Object[n]);
Practical considerations
The solution above has a high complexity (it is O(k1⋅k2⋅..⋅kn)), but sometimes it is possible to avoid going until the deepest loop.
Indeed, in the specific problem mentioned in this post (which requires summing common elements across all arrays), we can skip generating some tuples e.g. if already x2[i2] ≠ x1[i1].
In the recursive solution, those situations can easily be pruned. The specific code for this problem would probably look like this:
void process(int idx, int n, int[][] x, int[] k, int value) {
if (idx == n) {
// all elements from the current tuple are equal to "value".
// add this to the global "sum" variable
sum += value;
return;
}
for (int i = 0; i < k[idx]; i++) {
if (idx == 0) {
// this is the outer "for", set the new value
value = x[0][i];
} else {
// check if the current element from the idx'th for
// has the same value as all previous elements
if (x[idx][i] == value) {
process(idx + 1, n, x, k, value);
}
}
}
}
Assuming that the index of the element is not important: a[1] = 2 and a[5] = 2, you only need two nested loops.
First you need to put n-1 arrays in a list of sets. Then loop over nth array and check if each element exists in all of the sets in the list. If it does exist then add to total.

New to Java, Method X in class y cannot be applied

I'm new to java and was looking for some advice. I was assigned the problem below and I cannot get the compare method to run for the life of me. It won't compile. I receive the following error:
error: method compare in class Plateau cannot be applied to given types;
compare(a[N]);
required: int[],int
found: int
reason: actual and formal argument lists differ in length
Any help would be greatly appreciated.
1.4.21 Longest plateau. Given an array of integers, find the length and location of the longest contiguous sequence of equal values where the values of the elements just before and just after this sequence are smaller. The array should be passed to a method and the results should be printed to the screen.
public class Plateau{
public static void main(String[] args) {
int N = args.length;
int[] a = new int [N];
for (int i=0; i < N; i++){
int number = Integer.parseInt(args[i]);
a[i]=number;
}
compare(a[N]);
}
public static void compare(int[] a, int N){
int comp = a[0];
int current_length=0;
int max=0;
int maxlength=0;
for(int l=0; l < N; l++){
if (a[l] > comp){
current_length = 0;
comp = a[l];
max = a[l];
}
if (a[l] == comp){
current_length+=1;
comp = a[l];
}
else if (a[l] < comp && a[l] < max){
comp = a[l-1];
current_length=maxlength;
l++;
}
}
System.out.println(max);
System.out.println(maxlength);
}
}
It is quite obvious: the arguments expects an array and a value (length? index), but you are just passing one value from the array.
Just turn
compare(a[N]);
to
compare(a, N);
The problem is an issue with parameters and method signature. As I can see that you are learning, I will not give you a full solution. I will only point you to a way to solve it
The method compare expects two parameters int[] a, int N, but you are only calling it with one compare(a[N])
a[N] is wrong, because it would index an element outside of the array (mind that array index goes from 0 to N-1)
a is the array of type int[], so you need to use this as the first parameter of the call to compare
N is the number of elements (of type int) in the array, so this could be the second parameter
Your method signature doesn't match the way you are trying to invoke it. In your main method, you are trying to call a method called compare that takes an array of integers, but the only definition you have is for a compare method that takes both an array of integers and a single integer. The usage and definition need to be consistent, or the compiler won't know what you are trying to do.
Your method
public static void compare(int[] a, int N){
takes two parameters one is integer array and other is a integer
When you call that method in your main method you are passing only one parameter
public static void main(String[] args) {
int N = args.length;
int[] a = new int [N];
for (int i=0; i < N; i++){
int number = Integer.parseInt(args[i]);
a[i]=number;}
compare(a,N); // pass a integer along with your integer array (you have to use your array variable which is a and not a[N])
}
and thats why you are getting that error pass an integer along with that and it will work
Also you are passing the array incorrectly
int[] a = new int [N];
you have declared array here and thus you need to pass the variable a and not a[N]

How to find all possible numbers with a Recursion method

i want to write a Recursion method that prints all possible arrangements for these
numbers , the integers 1 to 9
arranged randomly in a grid of three rows and three column.for example :
6 2 1
5 4 7
3 9 8
sorry i don't have any code , because it's very hard to me.
public class Test {
public static void main (String[] args){
String x = "123456789";
System.out.println(test(x,0));
}
public static String test(String x , int y){
if(x.length()==1)return "";
return x.charAt(y)+test(x.substring(y),y);
}
There are many ways to implement something like this, this is one example. I will use int[] instead of String for convenience sake:
public static void main(String[] args) {
nextPermutation(new int[9], 0, new boolean[9]);
}
public static void nextPermutation(int[] perm, int index, boolean[] alreadyUsed) {
if(index == perm.length) {
//the permutation is complete
//you can store it or print it
} else {
for(int i = 0 ; i < alreadyUsed.length ; i++) {
if(alreadyUsed[i]) continue;
perm[index] = i+1;
boolean[] newAlreadyUsed = Arrays.copyOf(alreadyUsed, alreadyUsed.length);
newAlreadyUsed[i] = true;
nextPermutation(Arrays.copyOf(perm, perm.length), index+1, Arrays.copyOf(newAlreadyUsed, newAlreadyUsed.length));
}
}
}
This will generate all possible combinations of 1-9. The idea of the algorithm is that you keep track of which digits you already used, run through a loop and select all available digits.
Note that it's important to pass copies of perm and alreadyUsed, otherwise you will just pass the same array and overwrite previous permutations.
pass values ​​to an array, randomize and create a loop to generate the matrix.
loop: make a generic loop starting to generate matrix with i0 , j0 like position i1 , j1 of matrixand add the values of array
int j = 0;
for( int i = 0; i <= YOURARRAY.length(); i++)
{
System.out.println( i POSITIONOFARRAY );
j+1
}

How to add to array without ArrayIndexOutOfBoundsException?

Can anyone answer this question?
public class AddingArray {
public static void main(String[] args){
int arry1[] = {2,3,4,5,6,7,9};
int arry2[] = {4,3,7,9,3,5};
for(int i = 0; i <arry1.length; i++){
int result = arry1[i] + arry2[i];
System.out.println("Result "+result);
}
}
}
Whenever I try executing the above code I get the error Exception in
thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at
basics.AddingArray.main(AddingArray.java:9)
But,my output should be like this 6,6,11,14,9,12,9
As people have mentioned, one of yours arrays is literally shorter than the other. Take two blocks and overlay them over only one block. The second (in this case index 1 block) would fall into the abyss, because the block that was supposed to catch it never existed.
I would make sure both of them are of the same size. If you do want to leave em as they are, I would do this:
int result = 0;
try
{
for(int i = 0, length = array2.length; i < length; i++)
{
result = array1[i] + array2[i];
System.out.println("Result is: " + result);
}
catch(Exception e)
{
System.out.println("You tried to do something that resulted in an error");
System.out.println("Your previous result was: " + result);
}
}
SO, assuming that I still recall how to do basic arrays, what this code will do is that it will catch any errors thrown by your code.
Let's make this as simple and understandable as possible, with no fancy annotations:
You have two int arrays, of not equal lengths, and you wish to add the index-paired numbers to an array of the sums. However, if one of the arrays does not have any more numbers, the value of the longest array will be the result.
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
You need to determine the length of the longest array. You can do this with a Math.max()-method, where you give the length of each array as parameters:
int biggestArrayLength = Math.max(arry1.length, arry2.length);
Then, instead of for(int i=0;i<arry1.length;i++){, you write:
for(int i=0;i<biggestArrayLength;i++){
Now it doesn't matter which of the two arrays is the biggest one.
Inside the loop, I would define two ints, representing a value from each of the two arrays:
int value1 = arry1[i];
int value2 = arry2[i];
however, this will give an error when the smallest array does not have any more elements. We need to check if the array actually has an element with index i. index numbers in arrays start with 0. so if the length is 7, the 7 elements will have index numbers from 0-6. In other words, only index numbers that are lower (and not equal) to length, is valid numbers:
int value1 = 0;
int value2 = 0;
if(arry1.length > i){
value1 = arry1[i];
}
if(arry2.length > i){
value2 = arry2[i];
}
int result = value1 + value2;
System.out.println("Result "+result);
}
}
}
Now, if you need to put these in a third array, say named sumArray, this would be the complete code:
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
int biggestArrayLength = Math.max(arry1.length, arry2.length);
int[] sumArray = new int[biggestArrayLength];
for(int i=0;i<biggestArrayLength;i++){
int value1 = 0;
int value2 = 0;
if(arry1.length > i){
value1 = arry1[i];
}
if(arry2.length > i){
value2 = arry2[i];
}
int result = value1 + value2;
sumArray[i] = result;
System.out.println("Result "+result);
}
}
}
It is because your loop will go from 0 to 6 (which is the array1.length - 1) and your array2 only has 6 elements (so from 0 to 5).
So when you are accessing arry2[6]; It will give you the java.lang.ArrayIndexOutOfBoundsException.
You could change your for loop to go to the length of the smallest array:
for(int i = 0; i < arry2.length; i++){ /*Do what you want */ }
Or add an element in array2, but that is yours to decide since I do not know your requirements.
Because arry1 is longer than arry2 when you make the last iteration through the loop arry2[i] returns null because there is no element to return.
either do:
if(arry2[i] != null) {
//run your adding code
}
or change your arrays to be the same size
Edit: The reason it is not working properly is because you are using the length of the largest array as the conditional within the for loop. This condition allows you to attempt to access the 2nd array at a location that does not exist, which is why you are getting an ArrayIndexOutOfBoundsException.
Can we stop the downvoting?
End edit----
If you want to add up all of the elements in the array use this code.
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
int result = 0;
for(int i=0;i<arry1.length;i++){
result+=arry1[i];
}
for(int j=0; j < array2.length; j++){
result += array2[j];
}
System.out.println("Result: "+ result);
}
}
if you are trying to sum individual elements as you loop you can do the following. This will properly handle 2 arrays of different length regardless of which one is longer.
public class AddingArray {
public static void main(String[] args){
int arry1[]={2,3,4,5,6,7,9};
int arry2[]={4,3,7,9,3,5};
int result = 0;
for(int i=0;i<arry1.length;i++){
result=arry1[i];
if(i < array2.length){
result += array2[i];
}
System.out.println("Result: "+ result);
}
for(int j = i; j < array2.length; j++){
System.out.println("Result: "+ array2[j]);
}
}
}

create a method that can count negative numbers in an array

public class negativeTest {
public static int Negativenum (int[] array) {
int negative = 0;
for (int i = 0; i < array.length; i++){
if(array[i] < 0){
negative = negative + 1;
}
System.out.println(negative);
}
}
}
I am trying to count how many elements in array are negative. This is what i have so far. My question is: eclipse is telling me that i should return a void instead of static int? How can i do this without using void?
I'd want to use
public static int negativenum(int[] array){
Only way i can get this working is create an array with positive and negative numbers and count them, but i want to be able to have method that does that without creating array of numbers. Can you help me?
Try giving a return statement , your method is expecting a int as a return parameter.
Therefore it will give compiler error.
public class negativeTest {
public static int Negativenum (int[] array) {
int negative = 0;
for (int i = 0; i < array.length; i++){
if(array[i] < 0){
negative = negative + 1;
}
System.out.println(negative);
}
return negative;
}
}
Ther error you are getting is because you have not declared the main function inside the class.
You have to call Negativenum from the main function.
you can do it like this :
public static void main (String args[])
{
negativeTest nt = new negativeTest();
int [] array = new int[]{ 100,200 };
int count = nt.Negativenum(array);
System.out.println(count); // It will print **2**
}
Regarding your doubts you have asked in comments.
You have to return anything from function only when you want to use that use that return value from the calling function.
Otherwise if you want to just print that value on console or log that value , you can easily do it in the negativeTest function and you can change the return type of this function to void.
FYI , you should not begin your classname with the lower case character.
The error is because you are not returning anything from the function which is expected to return an int.
If you want the function to count the number of negative numbers and return the count so that the caller of the function gets the count, you can add an
return negative;
before the end of the function.
Alternatively if you don't want to return anything from the function and want to just print the count as part of the function call, you can change the return type of the function from int to void:
public static void Negativenum (int[] array) {
Your function signature suggest a return type of int, but you aren't returning anything from the function. I suspect this is why Eclipse is suggesting you change the function signature to return void.
If you add return negative; it should avoid the notice from Eclipse.
If your intention is to simply print the count, then you should change the return type.
if you dont want to return anything, set your method signature to void, but add an out variable, like so:
public static void NegativeNum(int[] array, out int negative)
{
negative = 0;
foreach(int i in array) { if (i < 0) negative++;
}
then you just declare negative wherever this method is called from, and pass it in as an out variable:
int negative = 0;
NegativeNum(array, out negative);
After that call, negative will contain the count of negative numbers determined by the method.

Categories