Java programming test for interview - java

Here is a programming test used in a job interview. I find it has a very strange non-OO perspective and wonder why anyone would approach a constructor from this perspective. As a very experienced Java programmer, I immediately question the ability of the individual who wrote this code and the strange perspective of the question.
I find these strange out of context questions on interviews disturbing. I would love feedback from other experienced OO Java programmers.
Complete the Solver constructor so that a call to solveAll return a list with 2 values
including the square root and the inverse of the integer passed as parameter.
public interface MathFunction {
double calculate(double x);
}
public class Solver {
private List<MathFunction> functionList;
public Solver() {
//Complete here
}
public List<Double> solveAll(double x) {
List<Double> result = new ArrayList<Double>();
for (MathFunction function : this.functionList) {
result.add(new Double(function.calculate(x)));
}
return result;
}
}

This is testing your design patterns, by using the simplest possible method. I think this could be the Strategy (or some other behavioural pattern). See these:
http://en.wikipedia.org/wiki/Strategy_pattern
http://en.wikipedia.org/wiki/Behavioral_pattern
If you are going for a Java interview, you should be able to identify the design pattern they are hinting at and that should prevent you from being too unsettled!
To answer the question, create two classes that implement MathFunction as required, then create two instances and store them in functionList.
The point here is not 'can you do calculations in this strange way', it is 'can you identify design patterns'.

I agree that it's confusing and over-engineered.
But I do think the code is reasonably object-oriented. It's an instance of the strategy pattern. The code that generates a list of answers doesn't care how the answers are calculated - the two concerns are separated and a different calculation strategy could be applied without having to touch the code that generates the list.
To make the class more useful, these functions should be passed in from the outside (i.e. dependency injection) rather than being instantiated in the constructor.
You know the answer, I assume, but for what it's worth...
public Solver() {
functionList = new ArrayList<MathFunction>();
functionList.add(new MathFunction() {
#Override
public double calculate(double x) {
return 1d/x;
}
});
functionList.add(new MathFunction() {
#Override
public double calculate(double x) {
return Math.sqrt(x);
}
});
}

IMHO, it is indeed a strange approach. The name Solver is generic, it shouldn't implement specific operations by default. However, maybe that was part of the interview? Part one: simply fulfill the request. Part two: say that it is strange to do so.
I would say that a much nicer approach would be to have an addMathFunction(MathFunction mf) method. And if wanted, to create subclasses that extend the Solver class and add MathFunctions in their constructor.

I think they wanted you to add two items in the functionlist. Each one would implement the MathFunction interface, one for the square root and one for the inverse.
The prboblem lies in the details:
1- You have a function which returns 2 values because it does two different things, that is bad
2- If you want to have this "do-it-all" class,m it would be interesting to receive the Mathfunctions as a parameter so you can do any sort of MathFunctions, the MathFunctions would be parameterizable

Here's my solution. This is a simple illustration of a factory class.
public Solver() {
functionList = new ArrayList<MathFunction>();
MathFunction sqrt = new MathFunction() {
#Override
public double calculate(double x) {
return Math.sqrt(x);
}
};
functionList.add(sqrt);
MathFunction inverse = new MathFunction() {
#Override
public double calculate(double x) {
return 1.0D / x;
}
};
functionList.add(inverse);
}
This question shows two things:
Whether the programmer understands math terms like inverse.
Whether the programmer understands that instances of interfaces or classes can be stored in a list, and iterated over later.

While I agree that this probably isn't the best way, or most OO way to do this, I would have to assume that the point of this exercise is to see how well you understand Inheritance, Interfaces and maybe anonymous inner classes. That's the only thing I can figure.

Ok, I coded the solution to my own question. My instinct that nothing should be in the constructor seems to be correct. The functionList is not static so you need an instance to initialize it. It specifies integer so I round to integer. The inverse function is not advanced math in any way.
import java.util.ArrayList;
import java.util.List;
import java.lang.Math;
public class Solver {
private List<MathFunction> functionList = new ArrayList<MathFunction>();;
public Solver() {
// Complete here
}
public void initFunctionList() {
MathFunction functionSquareRoot = new MathFunction(){
#Override
public double calculate(double x) {
return (x<0 ? 0: Math.sqrt(x)); // maybe we need throw an exception here for negative numbers, but we'll just set it to 0
}};
MathFunction functionInverse = new MathFunction(){
#Override
public double calculate(double x) {
return (x!=0.0 ? 1/x : 0);
}
};
functionList.add(functionSquareRoot);
functionList.add(functionInverse);
}
public List<Double> solveAll(double x) {
List<Double> result = new ArrayList<Double>();
for (MathFunction function : this.functionList) {
result.add(new Double(function.calculate(x)));
}
return result;
}
}
public interface MathFunction {
double calculate(double x);
}
public class TestSolver {
/**
* #param args
*/
public static void main(String[] args) {
Solver s = new Solver();
s.initFunctionList();
System.out.println(s.solveAll(16.0));
}
}
I mislead myself the constructor can be
public Solver() {
// Complete here
MathFunction functionSquareRoot = new MathFunction(){
#Override
public double calculate(double x) {
return (x<0 ? 0: Math.sqrt(x)); // maybe we need throw an exception here for negative numbers, but we'll just set it to 0
}};
MathFunction functionInverse = new MathFunction(){
#Override
public double calculate(double x) {
return (x!=0.0 ? 1/x : 0);
}
};
functionList.add(functionSquareRoot);
functionList.add(functionInverse);
}

Somewhat contrived, seems closer to the decorator pattern to me.
Not sure what I would say during an interview but here is how I would code it:
package math;
import java.util.ArrayList;
import java.util.List;
public class DecoratorMath
{
interface MathFunction
{
double calculate(double x);
}
public static void main(String[] args)
{
DecoratorMath decoratorMath = new DecoratorMath();
decoratorMath.go();
}
public void go()
{
Solver solver = new Solver();
decorate(solver);
List<Double> results = solver.solveAll(02);
for (Double d :results)
{
System.out.println(d);
}
}
public void decorate(Solver solver)
{
solver.addFunction(new MathFunction()
{
#Override
public double calculate(double x)
{
return Math.sqrt(x);
}
});
solver.addFunction(new MathFunction()
{
#Override
public double calculate(double x)
{
return 1d/x;
}
});
}
class Solver
{
private List<MathFunction> mathFunctions = new ArrayList<MathFunction>();
public void addFunction(MathFunction mathFunction)
{
mathFunctions.add(mathFunction);
}
public List<Double> solveAll(double x)
{
List<Double> result = new ArrayList<Double>();
for (MathFunction function : mathFunctions)
{
result.add(new Double(function.calculate(x)));
}
return result;
}
}
}

Doing this all within the Constructor is just poor practice. Anyway my all-in-one solution.
import java.util.*;
import java.math.*;
//sqrt / inverse
public class Solver{
private List<MathFunction> functionList;
public interface MathFunction{
double calculate(double x);
}
class X implements MathFunction {
public double calculate(double x) {
return Math.sqrt(x);
}
}
class Y implements MathFunction {
public double calculate(double y) {
return 1/y;
}
}
public Solver(){
//here
functionList = new ArrayList<MathFunction>();
MathFunction f = (MathFunction) new X();
functionList.add(f);
MathFunction f2 = (MathFunction) new Y();
functionList.add(f2);
}
public List<Double> solveAll(double x){
List<Double> result=new ArrayList<Double>();
for (MathFunction function : this.functionList){
result.add(new Double(function.calculate(x)));
}
return result;
}
public static void main(String... args) {
System.out.println("result="+new Solver().solveAll(123));
}
}

Related

How do you return the total value of two methods that each take in a value?

My teacher wanted us to create program to compute the bills of our home. In java we were just going over objects and classes so I made
class Bills{
Bills... etc
The problem I am having is I dont know how to get a total of two methods that take in a value.
public double getWifepay(double x){
return x;
}
public double getHusbandpay(double y){
return y;
}
public double getTotalmoney(){
???
}
Your methods should probably just return some value that is stored within the object. So you would have something like:
public double getWifePay(){
return wifePay;
}
public double getHusbandPay(){
return husbandPay;
}
And
public double getTotalmoney(){
return getWifePay() + getHusbandPay();
}
and then you probably would want to write some setter methods like:
public void setWifePay(double wifePay) {
this.wifePay = wifePay;
}
public void setHusbandPay(double husbandPay) {
this.husbandPay = husbandPay;
}
And in your class definition you should have declared these fields:
public class Bills {
double wifePay;
double husbandPay;
// And then the methods from above
}
Create the previous two method (getwifepay, gethusbandpay) as static and call them in getTotalmoney function with class name. suppose class name is A so call as A.getwifePay(value)
Not sure I understand your model classes, but as you mention, for the "getTotalMoney" method to return the sum, the elements (the numbers in this case) should be given as parameters.
On the other hand, your "getWifepay" and "getHusbandpay" methods don't make much sense, as they are returning the same parameter which is given.
With all of this, you would need to have the method "getTotalmoney" call the other two and then make the sum, like this:
public double getWifepay(){
return x;
}
public double getHusbandpay(){
return y;
}
public double getTotalmoney(){
getWifepay() + getHusbandpay();
}
Finally, I suppose that these methods are within a given class (you mentioned Bill), making it maybe something like this:
class Bill {
private double x;
private double y;
private double getWifepay(){
return x;
}
private double getHusbandpay(){
return y;
}
public double getTotalmoney(){
getWifepay() + getHusbandpay();
}
}
Hope that solves your problem.

Driver class for Array

How would I develop the driver class for this code ive written ?
Array Class:
import java.util.Scanner;
public class Array
{
Scanner sc = new Scanner(System.in);
private double[] array = new double[];
public void setArray(double[] arr)
{
//I must set a value for the array length. set by user.
//user must input data
}
public boolean isInIncreasingOrder()
{
//must test if input is in increasing order
}
public boolean isInDecreasingOrder()
{
//must test if input is in descending order
}
public double getTotal()
{
//must find the total of all input
//total +=total
}
public double getAverage()
{
//must calculate average
//average = total/array.length
}
}
I guess what I'm asking is what exactly do i call in the DriverClass and how do I do it.
Thanks
The simplest way to test a class is to have a "public static void main(String[] args)" method in the class itself.
In this "main" method, you first create an instance of the class, and then call the various methods in the class, and verify that they do what you expect. To make testing easier, you might want to print out a message after each call to the class under test, showing the expected result, the actual result, and a friendly "OK" or "FAIL" to let you see easily if the method did what you wanted.
Example:
class MyClass {
private int x = 0;
public int getX() { return x;}
public void setX(int x) { this.x = x; }
public static void main(String[] args) {
MyClass instance = new MyClass();
instance.setX(42);
int value = instance.getX();
System.out.print("Expected 42, got "+value);
if (value == 42) {
System.out.println("OK");
}
else {
System.out.println("FAIL");
}
}
}
Once you're familiar with this approach to testing, you might look into unit test frameworks such as JUnit, which provide better ways to "assert" that a particular test is passing, and to understand the results of your testing.

Encapsulation of array with reference variables

I intend to write a program that simulates particles collisions in one or more dimension. For the 2D case, I would also like to make a GUI that shows the particles.
I have a main class, ParticleCollider, which contains an inner class, Particle, an array of said Particlesas well as some methods for updating the positions and velocities of the particles. The class roughly looks like this:
class ParticleCollider {
class Particle {
private double mass;
private double[] pos;
//plus some other private class variables
public Particle(double mass, double[] pos) {
this.mass = mass;
this.pos = pos;
}
}
private Particle[] pArray;
//Details of constructor are irrelevant
public ParticleCollider() {
}
//Do stuff to particles in pArray, i.e. change their positions and velocitites
public void update() {
//For example
pArray[0].pos[0] = 0;
}
}
In the graphics class, I want to be able to access the Particles so that I can find their positions and radii for drawing purposes. One way would of course be to add a method getParticlesin ParticleColliderto return the array of Particles, pArray. My question is now if this would be considered a violation of encapsulation. Because the Particleclass has no setters, I cannot change the Particles. Also, because an array hase fixed length, I cannot add any Particles. The only thing I could do, which I guess is pretty bad, is take some Particleand assign it the value of null.
EDIT
It has been suggested that I use a List instead of an array and provide an iterator to said List. It would seem to me that this would not solve the encapsulation problem. Regardless, I'm relucant to abandon the array because I need to be able to select a random Particle in the collection of Particles and then iterate it cyclically.
How about using this pattern:
public class Particle {
// Particle code
}
public class Particles implements Iterable<Particle> {
ArrayList<Particle> myParticles = new ArrayList<Particle>();
public void add(Particle particle) { myParticles.add(particle); }
public Iterator<Particle> iterator() {
return myParticles.iterator();
}
// more code on particles
}
void bla() {
Particles particles = new Particles();
particles.add(new Particle());
particles.add(new Particle());
for (Particle particle : particles) {
System.out.println("P="+particle);
}
}
If you want to inhibit the remove() on this iterator you might use this pattern:
public static class Particles implements Iterable<Particle> {
ArrayList<Particle> myParticles = new ArrayList<Particle>();
public void add(Particle particle) { myParticles.add(particle); }
public Iterator<Particle> iterator() {
return new Iterator<Particle>() {
Iterator<Particle> listIterator = myParticles.iterator();
#Override
public boolean hasNext() {
return listIterator.hasNext();
}
#Override
public Particle next() {
return listIterator.next();
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}

How can I share instantiated objects between methods?

I have:
public class HFSim extends ApplicationTemplate
{
private static class AppFrame extends ApplicationTemplate.AppFrame
{
void setBuoy()
{
//code
Position buoypos=Position.fromDegrees(buoylat, buoylon);
}
void setVehicle()
{
//code
Position vehiclepos=Position.fromDegrees(lat, lon, elev);
}
double findDistance()
{
//find distance between marker (vehicle) and a buoy
Earth earth= new Earth();
double radius = earth.getEquatorialRadius();
double distancebetween=LatLon.ellipsoidalDistance(buoypos, vehiclepos, radius, 6356752.3);
return distancebetween;
}
How can I use the objects buoypos and vehiclepos in the setBuoy and setVehicle methods in the findDistance() method?
You have two clearcut options here:
Make buoypos and vehiclepos instance variables, or..
Provide more descriptive names for setVehicle() and give it a Position return type.
Option 1 would look like this:
...classname...
{
private Position vehiclePosition;
private Position bouyPosition;
public void setVehiclePosition()
{
this.vehiclePosition = ....
}
}
Option 2 would look like this:
...classname...
{
public Position createVehiclePosition()
{
vehiclePosition = ....
return vehiclePosition.
}
}
Finally, you would use them as either:
...classname...
{
public double findDistance()
{
...this.vehiclePosition...
or
Position vehiclePos = this.createVehiclePosition();
}
}
The option you choose is highly dependent on how the class is supposed to behave.
Use variables with the class scope. This essentially means
///outside of a method but within the class you'll want to set:
private this.bouypos = new Position;
private this vehiclepos = new Position;
//method1 {
Position this.buoypos=Position.fromDegrees(buoylat, buoylon);
//method2 {
Position this.vehiclepos=Position.fromDegrees(lat, lon, elev);
//method3 calls things set in method1 & 2
findDistance(){
//code
double distancebetween=LatLon.ellipsoidalDistance(this.buoypos, this.vehiclepos, radius, 6356752.3);
}
Make the findDistance method take two Positions as parameters
double findDistance(Position buoypos, Position vehiclepos){
}

PropertyAccess: Is there a way to create access functions dynamically?

Here is the thing.. I want to draw some lines into some charts for a website.
These charts sometimes will have sometimes one or two lines.. but sometimes a few more where each is defined by an arbitrary mathematical function.
As for now, I only know this possibility to draw e.g. three lines:
public class ArbitraryFunctionData {
private double x1;
private double x2;
private double x3;
private double y;
public ArbitraryFunctionData(double x1, doouble x2, double x3, double y) {
this.x1 = x1;
this.x2 = x2;
this.x3 = x3;
this.y = y;
}
public double getX1() {
return x1;
}
public double getX2() {
return x2;
}
public double getX3() {
return x3;
}
public double getY() {
return y;
}
public void setX1(double x1) {
this.x1 = x1;
}
public void setX2(double x2) {
this.x2 = x2;
}
public void setX3(double x3) {
this.x3 = x3;
}
public void setY(double y) {
this.y = y;
}
}
Somewhere there is a need to define this interface:
public interface ArbitraryFunctionAccess extends
PropertyAccess<ArbitraryFunctionData> {
ValueProvider<ArbitraryFunctionData, Double> x1();
ValueProvider<ArbitraryFunctionData, Double> x2();
ValueProvider<ArbitraryFunctionData, Double> x3();
#Path("x")
ModelKeyProvider<ArbitraryFunctionData> xKey();
}
So I can add these access function as fields to the chart:
horizontalAxis.addField(arbFuncAccess.x1());
horizontalAxis.addField(arbFuncAccess.x2());
horizontalAxis.addField(arbFuncAccess.x3());
This is a very uncomfortable way to create a chart. Is there any better way to do this?
ArbitraryFunctionData needs to be pre defined and one needs to add every single access method by hand. I'd rather do something like that:
ArbitraryFunction f1 = new ArbitraryFunction(0, 5, 0, 5) {
#Override
public double f(double x) {
return x+1;
}
};
ArbitraryFunction f2 = new ArbitraryFunction(0, 5, 0, 5) {
#Override
public double f(double x) {
return x+2;
}
};
store.add(0, f1.getData()); // a line
store.add(1, f2.getData()); // another line
where ArbitraryFunctions function public double f(double x) needs to be overwritten and ArbitraryFunction.getData() is defined as public List<ArbitraryFunctionData> getData(). This would add more dynamic to the whole thing but the problem is, that I can not add the fields to the chart since they need to be pre-defined in public interface ArbitraryFunctionAccess.
I hope I described my need properly. Does anyone know a possible solution to this?
PropertyAccess isn't the point here - ValueProvider is. The PropertyAccess type is just a nice way to auto-generate a bunch of really boring ValueProvider/ModelKeyProvider/LabelProvider types that you could easily do by hand. Your time is valuable, so we don't make you do it by hand.
This means that you can make a hand-made implementation of ValueProvider that does whatever you want it to. I'm not really clear what 0,5,0,5 means or what f1.getData() is intended to return/do, but you could define f1 as a ValueProvider type that can find objects in that list.
public class AribtraryDataVP implements
ValueProvider<ArbitraryFunctionData, Double>() {
private final int index;
public AribtraryDataVP(int index) {
this.index = index;
}
public Double getValue(ArbitraryFunctionData object) {
return object.getData().get(index);
}
public void setValue(ArbtraryFunctionData object, Double value) {
object.getData().set(index, object);
}
public String getPath() {
return "data[" + index + "]";
}
}
The purpose of the ValueProvider type is to allow access to reading and writing properties of objects. In your case, you probably don't care about setValue, but it is usually good to either implement it or at least throw an exception so you know that someone tried to call it and it didn't work. Likewise, the getPath method is used to tell the difference between properties, sometimes for debugging purposes, and sometimes for sorting or filtering on the server, which needs the name of the property it is supposed to sort/filter. Again, probably not needed in your case, but it is usually good to get right.
I think this then will do what you were trying to do, adding those ValueProviders (i.e. properties, now mapped to list items) to the chart.
//f1, f2
axis.addField(new AribtraryDataVP(1));
axis.addField(new AribtraryDataVP(2));

Categories