r/javahelp • • Jul 07 '20

Define a function which takes any number of arguments

Hi all,

Define a function which can take any number of arguments and returns the sum of all the elements (only int and float type).

The arguments can include integers, string, char, floats, boolean (all the primitive data types) and arrays.

if you are passing an array, again it might have all the primitive data types.

its like:

float result = functionName(1, 0.5, "Hello", 'S', true, someArray, 100.5, 46, 24.332, someArray2, "Yes")

// the number of arguments can be any. The function should be able to take it.

This was asked to me in an interview. The interviewer told that your function should be able to return the sum of only integer and floats (not even byte or double. Only int and float)

I wrote the program although it was quite huge (not so much though). I wrote it on a piece of paper. When I came home, I tried to replicate it and ran on my PC. It didnt :/. I had used a try catch concept for this.

Can you guys help me out with an efficient program for this problem? Thanks!

22 Upvotes

32 comments sorted by

13

u/bean_factory Jul 07 '20 edited Jul 07 '20

If I understand the problem correctly then something like this should work:

float sumArgs(Object ... args) {
    float result = 0.0f;

    // edit: added null check thanks to /u/tsvk
    if (args == null) { return result; }

    for (Object arg : args) {
        if (arg == null) { continue; }

        if (arg instanceof Integer) {
            result += (Integer) arg;
        } else if (arg instanceof Float) {
            result += (Float) arg;
        } else if (arg instanceof int[]) {
            // note: cannot use recursion because the method's varargs
            //       wrap the arg with an additional array
            final int[] ints = (int[]) arg;
            for (int n : ints) {
                result += n;
            }
        } else if (arg instanceof float[]) {
            final float[] floats = (float[]) arg;
            for (float f : floats) {
                result += f;
            }
        }
    }
    return result;
}

Note that this implementation adds top-level boxed Integers and Floats to the sum, but does not do the same for elements of top-level Integers[] and Floats[]. You could add additional checks to the if statement if this is needed.

edit: The question is a little confusing because Strings are not a primitive type and Java has autoboxing and unboxing for other primitive types

8

u/xyphanite Quantum Brewer Jul 07 '20

This is a great solution to discuss, especially for a beginner.

  1. The three-dots in the method parameter list float sumArgs(Object ... args) - they aren't usually introduced until well past initial tutorials

  2. instanceof

  3. for loops without using an index - for(Object arg : args) {}

Addressingthese -

1), the three dots are shorthand for Varargs, which allows a variable number of parameters to be passed in a method. One of the most important caveats is that the parameters being passed have to be of the same type. Since you want to pass arguments that of different type, the type of object used is Object, from which all java objects inherit from. The issue we run into here is that you ( u/symoreo ), want to pass primitive types. It is not possible to pass a variable number of different primitive types. That's where Boxing comes into play. Float, Integer, Double etc are boxed types, they are a wrapper for primitives that inherit from Object and contain additional methods depending on which primitive type they box.

2) instanceof is an operator just like ==, <, >, <=, >= etc. It's used like (object) instanceof (type). In this above example example, arg instanceof Integer returns true if arg is of object type Integer. It's not much more than that.

3) shorthand for loops. WHen first learning Java, C++ or any strongly typed language, one usually writes a for loop like u/symoreo did, for (int i=0; i < ar.size(); i++) . In the case of the above solution, for(Object arg : args) {} ,this is what is known as a for-each loop. Effectively, for-each object arg in the object array args, iterate. This way, you don't need to keep track of an index, and iterate through, in whatever order is natural to the array of objects, one by one.

1

u/CedricRBR Jul 07 '20 edited Jul 07 '20

Wouldn't

float sumArgs(Number ... args)

be a better choice if all OP wants to add together are numbers ?

EDIT: forget what I said, didn't read the post fully :facepalm:

1

u/symoreo Jul 07 '20

Hi, sorry about the primitive thing. I thought since all builtin data types are considered primitive and since String (although a class) is builtin, I thought it was primitive. I will note this though.

And I ran your code for this input: sumArgs(1, 2, 3, "Hello", 56.7, 'S', true). Output: 6.0 // your func didnt add 56.7 Can you please explain your program? Thanks!

2

u/mjg123 Jul 07 '20 edited Jul 07 '20

56.7 is a double not a float. If you wanted it as a float it would have to be written as 56.7f.

1

u/symoreo Jul 07 '20

My bad. Thank you!

4

u/tsvk Jul 07 '20

You should be able to do the array-handling more neatly with recursion like this:

} else if (arg.getClass().isArray()) {
    result += sumArgs((Object[]) arg);
}

Casting the vararg-argument to Object[] should not cause an extra array wrapping.

EDIT: Also, you don't check if args is null before looping.

1

u/mjg123 Jul 07 '20

TIL, thanks! It's really surprising that casting args to an Object[] has that effect.

The question is vague on how to handle nested arrays, but casting to Object[] will fail if the arg is a primitive array.

2

u/tsvk Jul 07 '20

TIL, thanks! It's really surprising that casting args to an Object[] has that effect - it's already an Object[] so why does the cast make a difference?

It's not casting args, but arg. As arg is an Object (as it was an element of the args array of type Object[]), so it's not already an Object[].

1

u/mjg123 Jul 07 '20

:facepalm: thanks.

1

u/bean_factory Jul 07 '20

Good point about the null check, I'll update my post. Also, casting arg to Object[] throws an exception if arg is a primitive array (e.g. int[] or float[]) (I just tested and was surprised). Good tip with the Object[] cast, I didn't know this.

1

u/Yithar Intermediate Brewer Jul 08 '20 edited Jul 08 '20

Since I'm used to using Scala, looking at your solution, I was sort of rewriting it in a more functional style in my head.

Actually I ended up writing it in Scastie based off your solution:
https://scastie.scala-lang.org/PmcilPzZQNWiLAxSVSPlFg

The type hierarchy is a bit different in Scala. Object is AnyRef which is a child of Any. AnyVal is also a child of Any and contains Int, Float, etc.

EDIT: Recursive solution:
https://scastie.scala-lang.org/fma1/rgvOYiL5QWWUjJVaknapSA/1

9

u/[deleted] Jul 07 '20

Haven't run it, but this is a good use of streams:

private static float foo(Object ... vargs) {
    return (float)Stream.of(vargs)
          .filter( a -> a instanceof Float || a instanceof Integer )
          .mapToDouble( a -> (((Number) a).doubleValue())).sum();
}

2

u/symoreo Jul 07 '20

This works! I wasn't aware of Stream library. Guess I will need to look into it. Thanks!

1

u/xyphanite Quantum Brewer Jul 07 '20

Very nice use of streams. That said, streams are really scary for beginners.

2

u/[deleted] Jul 07 '20

Maybe. But in some cases they can be easier to understand their meaning. I think you could teach streams quite early.

1

u/xyphanite Quantum Brewer Jul 07 '20

I honestly think they could as well. Coming from a pure OOP background, it's harder for me to become effective with streams than if I had initially been taught functional programming. Knowing how universities generally teach older material, I unfortunately doubt this will occur, unless students are taught Python in addition to Java / C++.

2

u/xyphanite Quantum Brewer Jul 07 '20

Can you post the code of the program you wrote to see where you're at? If it's a huge amount of code, please follow the guidelines in the sidebar under Code Posting.

4

u/symoreo Jul 07 '20

Hi, this was my code. But it is wrong.

import java.util.ArrayList;

public class MyC {

public static int add(ArrayList ar)
{	float total = 0;
	for (int i=0; i < ar.size(); i++)
	{
		try { 
			total += float(ar.get(i))
		}
		catch (Exception e) {
			 e.printStackTrace();
		}
	}
	return total;
}

public static void main(String[] args) {
	
	ArrayList A1 = new ArrayList();
	A1.add(100.5);
	A1.add("Hello");
	A1.add('C');
	A1.add(90);
	A1.add(true);
	A1.add(106.79);
	
	System.out.println(add(A1));
	
}

}

1

u/tsvk Jul 07 '20

You are confusing the concept of arrays with the java.util.ArrayList class, that is an array-based implementation of the List interface.

1

u/saila456 Jul 07 '20

The function shouldn't be very large. What did you come up with?

1

u/desirecampbell Jul 07 '20

The best part of this question will be when you realize you've always been doing this.

0

u/tcbenkhard Jul 07 '20

There is no way you can write this in 1 function? I assume you misunderstood the question?

2

u/tsvk Jul 07 '20

It's quite doable, I tried it and came up with a 15-line method.

1

u/tcbenkhard Jul 07 '20

With primitives? I would like to see that signature?

2

u/mjg123 Jul 07 '20

float functionName(Object... args) does the trick, the ints and floats will be boxed.

1

u/tcbenkhard Jul 07 '20

Ah yes, autoboxing, my bad :)

1

u/MRH2 Intermediate Brewer Jul 07 '20

which version of Java did this appear in?

1

u/mjg123 Jul 07 '20

Varargs and autoboxing were part of Java 5 released in 2004.

1

u/MRH2 Intermediate Brewer Jul 07 '20

ha ha! Great.

I've just never used varargs

0

u/[deleted] Jul 07 '20

[deleted]

2

u/tsvk Jul 07 '20

Assumably you won't have access to 3rd-party libraries in a programming assignment.

1

u/symoreo Jul 07 '20

Hi, there were no limitations as such, Anything can be used.