Count passed arguments to a method - java

is there a possibility in java to count the number of passed arguments into a method?
Got something like this:
public class practise7 {
public static void main(String[] args) {
int[] array3 = new int[]{1};
int[] array4 = new int[]{1, 3, 4};
int[] array5 = new int[]{2, 3,};
combine(array3, array4, array5);
}
public static void combine(int[] array3, int[] array4, int[] array5) {
//Here i need the number of passed arguments (here 3 e.g.)
int count = args.length; //found this on google but didn't worked
System.out.println(count);
}
}
Thanks a lot!

Try this. It uses the var...arg syntax.
public static void main(String[] args) {
int[] array3 = new int[]{1};
int[] array4 = new int[]{1, 3, 4};
int[] array5 = new int[]{2, 3,};
combine(array3, array4, array5);
}
// uses the variable arguments syntax
public static void combine(int[]...v) {
//Here i need the number of passed arguments (here 3 e.g.)
int count = v.length;
System.out.println(count);
for (int[] k : v) {
System.out.println(Arrays.toString(k));
}
}
}
Prints
3
[1]
[1, 3, 4]
[2, 3]
Note that combining arrays and non-arrays in the argument list can sometimes provide unexpected results. The variable syntax argument must be the last one in the signature.

Your solution doesn't work because with 'args.length' you can only get the number of arguments that were passed in the main function. You can use variable arugments feature of Java as follows:
public static void combine(int[] ... arrays)
{
int count = arrays.length;
System.out.println(count);
}

Related

sorting array of arrays in descending order using arrays.sort function is resulting in errors in java

problem:https://leetcode.com/problems/maximum-units-on-a-truck/
I am supposed to sort array of arrays of size 2(eg. [[1,3],[2,2],[3,1]]) in descending order according to 2nd value of the inner element. i.e for 1st element[1,3]according to value 3. , but my code is resulting in error: no suitable method found for sort().Some Help would be appreciated.
here is my code in java
class Solution {
public int maximumUnits(int[][] boxTypes, int truckSize) {
Arrays.sort(boxTypes, new Comparator<int[][]>() {
public int compare(final int[][] entry1, final int[][] entry2) {
if (entry1[0][0] < entry2[0][0])
return 1;
else return -1;
}
}
);
for (int i = 0; i < boxTypes.length; i++)
System.out.println(boxTypes[i]);
return 0;
}
}
As mentioned in comments, you are sorting by inner element, which is int[], so you need Comparator<int[]>.
public class Solution {
public static void main(String[] args) {
int[][] input = new int[][]{new int[]{2, 2}, new int[]{1, 3}, new int[]{3, 1}};
Arrays.sort(input, new Comparator<int[]>() {
#Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[1], o1[1]);
}
});
System.out.println(Arrays.deepToString(input));
}
}
Note return Integer.compare(o2[1], o1[1]);, second parameter is compared to first in order to achieve descending order.
You could also achieve same effect using lambda, to make it shorter and more readable.
public class Solution {
public static void main(String[] args) {
int[][] input = new int[][]{new int[]{2, 2}, new int[]{1, 3}, new int[]{3, 1}};
System.out.println("Initial array - " + Arrays.deepToString(input));
Arrays.sort(input, (o1, o2) -> Integer.compare(o2[1], o1[1]));
System.out.println("Sorted array - " + Arrays.deepToString(input));
}
}
First, you can't use native type in <>, you need to use Integer instead. Then what you need to compare is the inner array Integer[] if I'm not mistaken so your comparator can't work. Here you are just trying to sort 2 arrays of arrays based on the first element of the first array.
Here is what I would do (using stream):
Integer[][] sortedBoxTypes = Arrays.stream(boxTypes).sorted(Comparator.comparing(entry -> entry[1])).toArray(Integer[][]::new);

Adding a variables in the array into another array

Today, I have a question about the list. I want to put the variables in the array into the another array. For example, if there is a int[] list1 and int[] list2 = {1,2,3,4} and int[] list3 = {5,6,7}, I want to put the variables in list2 and list3 into the list1, making the list1 into {1,2 + 5, 3 + 6, 4 + 7}. Below is the code that I have made:
public int function(int[] parameter) {
int[] intlist;
for (int i = 0; i < intlist.length; i++) {
intlist = addVariable(int[] anotherlist); //the function addVariable(int[] parameter) gets a
//int[] as a paremeter, makes a new int[](which has the same size as the parameter) at the
//inside of the function, add parameter's each and every varibles into the new int[] and
//returns the new int[]. and anotherlist keeps changing in the for statement. This is the
//function that I want to make.
}
return intlist;
}
Next is the code of addVariable:
public static int[] addVariables(int[] intlist) {
int[] intlist2 = new int[intlist.length];
for(int i = 0; i < intlist.length; i++) {
intlist2[i] += intlist[i];
}
return intlist2;
}
So, what I want to do is making the intlist whole, by using for statement and addVariable function. But, the addVariable fuction is not complete, as the two lists can have different size, and the function that I've made didn't consider this. Also, the changes that I've made in the for statement doesn't last, so this is a problem as well. How can I fix this situation? Please help!
This is the code you need
public class Test {
public static void main(String args[]) {
int[] intlist = {1, 2, 3, 4};
int[] anotherlist = {5, 6, 7};
Test.addVariables(intlist, anotherlist);
for (int i : intlist) {
System.out.println(i);
}
}
public static void addVariables(int[] intlist, int[] anotherlist) {
for (int i = intlist.length - 1, j = anotherlist.length - 1; i >= 0 && j >= 0; i--, j--) {
intlist[i] += anotherlist[j];
}
}
}

Function in java outputs different results when called multiple times

I have a function called tournamentTreeKSelection which finds the K-th largest element in an array. The function takes three parameters, the array, the same array again and the value of K. The purpose of sending two copies of the array is so that during recursive calls, I can modify one copy of the array and still keep the original array I sent in during that call. Here is the code:
import java.util.ArrayList;
import java.util.Arrays;
public class TournamentTree {
public static int max(int a, int b) {
return a > b ? a : b;
}
public static int[] toArray(ArrayList<Integer> list) {
int[] arr = new int[list.size()];
for(int i = 0; i < arr.length; ++i)
arr[i] = list.get(i);
return arr;
}
public static ArrayList<Integer> toList(int[] arr) {
ArrayList<Integer> list = new ArrayList<>();
for(int i : arr)
list.add(i);
return list;
}
public static int tournamentKSelection(int[] data, int[] data_copy, int k) {
ArrayList<Integer> winners = new ArrayList<>();
for(int i = 0; i < data.length; i += 2) {
winners.add(max(data[i], data[i + 1]));
}
if(k > 1 && winners.size() == 1) {
for(int i = 0; i < data_copy.length; i++)
if(data_copy[i] == winners.get(0))
data_copy[i] = -1;
return tournamentKSelection(data_copy, data_copy, --k);
}
if(winners.size() % 2 == 1 && winners.size() != 1) winners.add(-1);
if(winners.size() == 1) return winners.get(0);
return tournamentKSelection(toArray(winners), data_copy, k);
}
}
Now I am going to test it :
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] arr = {9, 10, 8, 7, 6, 500, 4, 3, 2, 1};
System.out.println(TournamentTree.tournamentKSelection(arr,arr,1));
System.out.println(TournamentTree.tournamentKSelection(arr,arr,2));
System.out.println(TournamentTree.tournamentKSelection(arr,arr,3));
}
}
This produces the following results:
500 // ok this is the first largest number
10 // ok this is the second largest number
8 // this is the fourth largest number, not the third
Now let me make the call to System.out.println(TournamentTree.tournamentKSelection(arr,arr,3)); alone without the call to k = 1 and k = 2
import java.util.Arrays;
public class Test {
public static void main(String[] args) {
int[] arr = {9, 10, 8, 7, 6, 500, 4, 3, 2, 1};
System.out.println(TournamentTree.tournamentKSelection(arr,arr,3));
}
}
Now this produces the correct result, which is 9. What's going on ? Individually, the result is correct but when I make previous calls to the same function first the subsequent results are wrong.
The only explanation I can think of at the moment is that something in my TournamentTree class is static that shouldn't be.
Any insight ?
I think you should call your function in this way:
System.out.println(TournamentTree.tournamentKSelection(arr.clone(), arr.clone(), 1));
And I recommend also interesting thread about arrays and passing them to function:
Are arrays passed by value or passed by reference in Java?
In the call TournamentTree.tournamentKSelection(arr,arr,3), you are passing in the same array for both args, so even though you are not changing the array through the second argument, you are changing it by the first. Java uses pass by reference, not pass by value. To maintain the original, you have to make a copy and pass in each, like:
public static void main(String[] args) {
int[] arr = {9, 10, 8, 7, 6, 500, 4, 3, 2, 1};
int[] arr_copy = java.util.Arrays.copyOf(arr, arr.length);
System.out.println(TournamentTree.tournamentKSelection(arr,arr_copy,3));
}

Call Overloaded Function in Java?

How can I call the array function in Java?
Currently it looks like:
public static void WriteLine(Object Array[]) {
for (int I = 0; I < Array.length; ++I) {
Out.println(Array[I]);
}
}
public static void WriteLine(Object Text) {
Out.println(Text);
}
I also tried:
public static <T> void WriteLine(T Array[]) {
for (int I = 0; I < Array.length; ++I) {
Out.println(Array[I]);
}
}
and in my main, I do:
int[] I = new int[]{1, 2, 3, 4, 5};
WriteLine(I);
I also tried:
WriteLine<int[]>(I);
Doesn't work..
It prints:
[I#2f56f920
aka the address of the int Array. How can I call the specific array function explicitly or how can I make the compiler know which one to call automatically (implicitly)?
I'm not used to Java/Generics/Object yet.. Just moved from C++ and used to templates :(
An int is not an Object so an int[] is not an Object[]:
Integer[] I = new Integer[]{1, 2, 3, 4, 5};
WriteLine(I);
Or you should have WriteLine overloaded for all the primitive types:
public static void WriteLine(int Array[]) {
...
public static void WriteLine(long Array[]) {
...
I would go for
System.out.println(Arrays.toString(myArray));
I would name your array something other than "Array," as Java is confusing the Array class with the Object or T generic class. You may want to also consider using StringBuilder, if all you want is to print each element of your array.
public static void write(Object arr[]) {
for (int i = 0; i < arr.length; ++i) {
System.out.println(arr[i]);
}
}
Should be good enough.
If you really want to use StringBuilder, and then print, do this:
public static void write(Object arr[]) {
sb = new StringBuilder();
for (int i = 0; i < arr.length; ++i) {
sb.append(arr[i] + " ");
}
System.out.println(sb.toString());
}
array of primitive are subtype of java.lang.Object. Overloading is resolved at compile time and the most specific method is selected which in case is writeLine(Object text).
You have two options to make sure that the right function is called:
1-
Object[] objArray = new Object[] { 1, 2, 3, 4, 5 };
2-
Integer[] integerArray = new Integer[] { 1, 2, 3, 4, 5 };
On a side note, you should follow Java naming conventions. for example method name should be writeLine and the index variable in the loop should be small case

Modifying Array Size Via Static Method

I am trying to resize an array by adding the array size by 1 per method invoke.
I have created a static method and it takes array as its argument.
public static void addArray(int arrayName[]) {
int tempNum[] = new int[arrayName.length]; // save the numbers before add array size
for (int i = 0; i < arrayName.length; i++) { // because by adding/removing array size, it would clear element array
tempNum[i] = arrayName[i];
}
arrayName = new int[arrayName.length + 1]; // adds array size by 1
for (int i = 0; i < arrayName.length - 1; i++) { // sets all the saved numbers to the new element in the array
arrayName[i] = tempNum[i]; // stops at (length - 1) because I want to leave it blank at the last element
}
}
(sorry if the code is messed up, I don't know how to properly post code in here)
In the main, I do this;
public static void main(String[] args) {
int num[] = {0, 1, 2, 3, 4};
addArray(num);
System.out.println(num.length);
}
As you can see, the default array size (length) should be 5, but no matter how many times I invoke the method, it always print as 5.
Now I'm starting to think that static method does not allow the array from main to be resized ?
If it can't, do you have another way to resize an array by specifically using static method only ?
You need to return the array from the function:
public static int[] addArray(int arrayName[]) {
...
arrayName = new int[arrayName.length + 1]; // adds array size by 1
...
return arrayName;
}
public static void main(String[] args) {
int num[] = {0, 1, 2, 3, 4};
num = addArray(num);
System.out.println(num.length);
}
You can simply do this:
int num[] = {0, 1, 2, 3, 4};
num = Arrays.copyOf(num, num.length + 1);
System.out.println(num.length);
This should then print 6.
The issue with your code is that when you call a method, the method receives a copy of the reference. Thus, the method cannot change what object is referenced by the variable in the calling method.
Another approach is to make num a static field::
static int num[] = {0, 1, 2, 3, 4};
public static void main(String[] args) {
addArray(); // or use Arrays.copyOf() as above
System.out.println(num.length);
}
public static void addArray() {
int tempNum[] = new int[num.length + 1];
System.arraycopy(num, 0, tempNum, 0, num.length);
num = tempNum;
}
What you can't do (without complex reflection code) is pass a variable name to the method and have it change the length of an array with that name.

Categories