I have really straight forward code, I am hoping that my issue is that I have just been looking at it too long. I am testing some calculations to make sure I am doing it right before I throw in a huge list. All I want to do is create a new objects through a for loop and toss them in my constructed array.
Contents of public static void main(String args[]) in my Main class:
PositionHolder[] positions = new PositionHolder[8];
PositionHolder currPosition;
int currPos = 0;
for(int i = 0; i <= 7; i++){
/* For Random Points */
currPosition = new PositionHolder(i);
System.out.println("Resetting " + i);
positions[i] = currPosition;
//positions[i].setxPos(100 * Math.random()); // these get set in the
//positions[i].setyPos(100 * Math.random()); // PositionHolder constructor
for(int k = i; k >= 0; k--){
System.out.println(k + ": " + positions[k].getxPos() + ", " + positions[k].getyPos());
}
}
Just for clarification, my PositionHolder class is as follows:
public class PositionHolder {
private static double xPos;
private static double yPos;
private static int point;
private static boolean visited;
public PositionHolder(int pointNumber){
setxPos(100 * Math.random());
setyPos(-100 * Math.random());
setPoint(pointNumber);
setVisited(false);
}
public double getxPos() {
return xPos;
}
public void setxPos(double xPos) {
PositionHolder.xPos = xPos;
}
public double getyPos() {
return yPos;
}
public void setyPos(double yPos) {
PositionHolder.yPos = yPos;
}
public int getPoint() {
return point;
}
public void setPoint(int point) {
PositionHolder.point = point;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
PositionHolder.visited = visited;
}
}
The problem is that for some reason each time through the for loop override the previous PositionHolders I have put in my array. As a quick example, here is the first few lines of my system output from the System.println towards the end of the for loop:
Resetting 0
0: 60.697435147416186, -96.35236848097432
Resetting 1
1: 57.98340997157546, -52.56948459757237
0: 57.98340997157546, -52.56948459757237
Resetting 2
2: 45.75236962694197, -32.03840605394901
1: 45.75236962694197, -32.03840605394901
0: 45.75236962694197, -32.03840605394901
So where I want 0 to stay at 60.69743.... and 1 to stay at 57.98340.... they are all getting set to the same (most resent) value. I wish I could say it is more complex than that, but that is it. What is going on?
--- The Answer, given below by Logan Murphy, is correct ---
As a note, not only should you take a break from time to time to avoid silly mistakes from code you have looked at too much, but you REALLY shouldn't rely on eclipses "fix" solutions to make good code :P
Because you set your variables to be static (shared between instances of the class). They need to be non-static like so
public class PositionHolder {
private double xPos;
private double yPos;
private int point;
private boolean visited;
public PositionHolder(int pointNumber){
setxPos(100 * Math.random());
setyPos(-100 * Math.random());
setPoint(pointNumber);
setVisited(false);
}
public double getxPos() {
return xPos;
}
public void setxPos(double xPos) {
this.xPos = xPos;
}
public double getyPos() {
return yPos;
}
public void setyPos(double yPos) {
this.yPos = yPos;
}
public int getPoint() {
return point;
}
public void setPoint(int point) {
this.point = point;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
}
This way each instance of the class PositionHolder has its own variables (instance variables are globally declared variables that are non-static)
Related
I have created the class angle as shown in the codebox below, I want to calculate the difference( called "minus" in the code) of two angles with the following command.
Angle.degrees(135).minus(Angle.degrees(90)).getDegrees()
Unfortunately, I always get zero as result, because the intern values are always overwritten.
import java.lang.Math;
public class Angle {
private static double gradmass = 0;
private static double bogenmass = 0;
public static Angle degrees(double angle) {
Angle angleD = new Angle();
// gradmass = angle;
// bogenmass = Math.toRadians(angle);
angleD.setDegrees(angle);
angleD.setRadians(Math.toRadians(angle));
return angleD;
}
public static Angle radians(double angle) {
Angle angleR = new Angle();
// gradmass = Math.toDegrees(angle);
// bogenmass = angle;
angleR.setDegrees(Math.toDegrees(angle));
angleR.setRadians(angle);
return angleR;
}
public double getDegrees() {
return gradmass;
}
public void setDegrees(double gradM) {
gradmass = gradM;
}
public double getRadians() {
return bogenmass;
}
public void setRadians(double bogenM) {
bogenmass = bogenM;
}
public Angle plus(Angle other) {
Angle temp = new Angle();
temp.setDegrees(this.getDegrees() + other.getDegrees());
temp.setRadians(other.getRadians() + other.getRadians());
return temp;
}
public Angle minus(Angle other) {
Angle temp = new Angle();;
temp.setDegrees(this.getDegrees() - other.getDegrees());
temp.setRadians(this.getRadians() - other.getRadians());
return temp;
}
public Angle neg() {
Angle temp = new Angle();
temp.setDegrees(-this.getDegrees());
temp.setRadians(-this.getRadians());
return temp;
}
public double sin() {
double temp;
temp = Math.sin(this.getDegrees());
return temp;
}
public double cos() {
double temp;
temp = Math.cos(this.getDegrees());
return temp;
}
public boolean similarTo(Angle other){
boolean gleich = false;
if( 0 == (this.getDegrees() - other.getDegrees()) || this.neg().getDegrees() == other.getDegrees()){
gleich = true;
}
return gleich;
}
public String toString(){
return
"GradM " + this.getDegrees() + " BogenM " + this.getRadians();
}
}
I did not make a constructor on purpose! I'm looking for a solution without a constructor or nonstatic methods.
Both your data members are static, meaning there's a single instance of them for the entire class. You should declare them as instance members so that each instance of Angle can have its own values:
public class Angle {
private double gradmass = 0;
private double bogenmass = 0;
// rest of the code...
Don't do this. Your class won't be thread-safe this way. What you want is kind of something like BigDecimal class in java, I guess. You can check the documentation of BigDecimal class of java if you want something like this.
https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html
But if you want the exact same thing you asked, you can see this (not thread safe and not recommended as well).
class Angle {
static Double angle1 = null;
static Double angle2 = null;
private static void setAngle(double angle) {
if (angle1 == null) angle1 = angle;
else angle2 = angle;
}
static Angle degrees(Double angle) {
setAngle(angle);
return new Angle();
}
static Double getDegrees() {
return angle1;
}
static Angle minus(Angle angle) {
angle1 -= angle2;
return new Angle();
}
}
public class SolutionAngle {
public static void main(String... args) {
System.out.println(Angle.degrees(135).minus(Angle.degrees(90)).getDegrees());
}
}
I am trying to write a public instance method names move()
It takes two integer arguments which showing the amount that the objects needs to change the values of xPos and yPos.
I don't want the method the return a value.
I have done this below but I get the following error message?
Compilation failed (18/01/2020 15:16:31)
Error: line 1 - method move in class StickFigure cannot be applied to given types;
required: no arguments
found: int,int
reason: actual and formal argument lists differ in length
Could I get some guidance where I am going wrong.
/*Instance variables*/
private int xPos;
private int yPos;
private Circle head;
private Triangle body;
private Rectangle leg;
public person()
{
super();
this.head = new Circle(30, OUColour.PINK);
this.body = new Triangle (50, 50, OUColour.RED);
this.leg = new Rectangle (6, 50, OUColour.PINK);
this.setXPos(25);
this.setYPos(220);
this.alignAll();
}
public void setXPos(int newPos)
{
this.xPos = newPos;
this.body.setXPos(newPos);//part (b)(iii)
}
public int getXPos()
{
return this.xPos;
}
public void setYPos(int newPos)
{
this.yPos = newPos;
this.body.setYPos(newPos);//part (b)(iii)
}
public int getYPos()
{
return this.yPos;
}
public Circle getHead()
{
return this.head;
}
public Triangle getBody()
{
return this.body;
}
public Rectangle getLeg()
{
return this.leg;
}
public void alignHead()
{
this.head.setXPos(this.body.getXPos() + (this.body.getWidth() - this.head.getDiameter())/2);
this.head.setYPos(this.body.getYPos() - this.head.getDiameter());
}
public void alignBody()
{
this.body.setXPos(25);
this.body.setYPos(220);
}
public void alignLeg()
{
this.leg.setXPos(this.body.getXPos() + (this.body.getWidth() - this.leg.getWidth())/2);
this.leg.setYPos(this.body.getYPos() + this.leg.getHeight());
}
public void alignAll()
{
this.alignBody();
this.alignHead();
this.alignLeg();
}
public void move(int newxPos, int newyPos)
{
this.body.setXPos(xPos + newxPos);
this.body.setYPos(yPos + newyPos);
this.alignAll();
this.delay(20);
}
If you want method move to take arguments, you have to declare it:
public void move(int xPos, int yPos)
instead of
public void move()
My singleton class:
public class XandY {
private double x, y;
private static XandY xy;
//Constructor sets an x and y location
private XandY() {
x = 210.0;
y = 100.0;
}
public static XandY getXandY() {
if (xy == null)
xy = new XandY();
return xy;
}
public void updateXandY() {
x += 10;
y += 5;
}
}
Other class that changes singleton values and tries to reinitialize. My question is if I call changeXandY a few times then want to call resetXandY how do I make it reset back to the original x and y?
public class GameWorld {
private List<GameObject> objects;
public void initialize() {
objects = new ArrayList<GameObject>();
objects.add(XandY.getXandY());
...add other objects that are not singletons
}
public void changeXandY {
for (int i=0; i<gameObject.size(); i++) {
if (gameObject.get(i) instanceof XandY)
((XandY)gameObject.get(i)).updateXandY();
}
public void resetXandY {
initialize();
}
}
For this use case, you could simply store them as default values. Such as
private double x, y;
private static XandY xy;
private static final double default_x = 210.0;
private static final double default_y = 100.0;
That way when you reset, just:
public void resetXandY {
this.x = default_x;
this.y = default_y;
}
That being said, you may want to change your default constructor to look the same way.
If you can make the XandY reference protected, you can use a static initializer in an anonymous subclass:
// I need to reset the singleton!
new XandY(){
{ xy = null; }
};
But really, if you need to be able to (re)initialize the singleton, you should put a method to that effect into its signature. Obscure solutions are, at best, still obscure...
Create a resetXandY() method to set default value:
public class XandY {
private double x, y;
private static XandY xy;
//Constructor sets an x and y location
private XandY() {
x = 210.0;
y = 100.0;
}
//reset x=0 and y=0
public void resetXandY() {
x = 0;
y = 0;
}
public static XandY getXandY() {
if (xy == null)
xy = new XandY();
return xy;
}
public void updateXandY() {
x += 10;
y += 5;
}
}
I'm learning the concept of neural networks. I decided to try making the neuron class by myself. What is the best way to implement different activation functions in my code? Now it uses only the binary step function.
It's my first try in coding neural networks so if you have any suggestions about my code, or it is completely dumb, please let me know.
Here is my code:
public class Neuron {
// properties
private ArrayList<Neuron> input;
private ArrayList<Float> weight;
private float pot, bias, sense, out;
private boolean checked;
// methods
public float fire(){
pot = 0f;
if (input != null) {
for (Neuron n : input){
if (!n.getChecked()){
pot += n.fire()*weight.get(input.indexOf(n));
} else {
pot += n.getOut()*weight.get(input.indexOf(n));
} // end of condition (checked)
} // end of loop (for input)
} // end of condition (input exists)
checked = true;
pot -= bias;
pot += sense;
out = actFunc(pot);
return out;
} // end of fire()
// getting properties
public float getPot(){return pot;}
public boolean getChecked(){return checked;}
public float getOut(){return out;}
// setting properties
public void stimulate(float f){sense = f;}
public void setBias(float b){bias = b;}
public void setChecked(boolean c){checked = c;}
public void setOut(float o){out = o;}
// connection
public void connect(Neuron n, float w){
input.add(n);
weight.add(w);
}
public void deconnect(Neuron n){
weight.remove(input.indexOf(n));
input.remove(n);
}
// activation function
private float actFunc(float x){
if (x < 0) {
return 0f;
} else {
return 1f;
}
}
// constructor
public Neuron(Neuron[] ns, float[] ws, float b, float o){
if (ns != null){
input = new ArrayList<Neuron>();
weight = new ArrayList<Float>();
for (Neuron n : ns) input.add(n);
for (int i = 0; i < ws.length; i++) weight.add(ws[i]);
} else {
input = null;
weight = null;
}
bias = b;
out = o;
}
public Neuron(Neuron[] ns){
if (ns != null){
input = new ArrayList<Neuron>();
weight = new ArrayList<Float>();
for (Neuron n : ns) input.add(n);
for (int i = 0; i < input.size(); i++) weight.add((float)Math.random()*2f-1f);
} else {
input = null;
weight = null;
}
bias = (float)Math.random();
out = (float)Math.random();
}
}
First, define interface of any activation function:
public interface ActivationFunction {
float get(float f);
}
Then write some implementations:
public class StepFunction implements ActivationFunction {
#Override
public float get() {return (x < 0) ? 0f : 1f;}
}
public class SigmoidFunction implements ActivationFunction {
#Override
public float get() {return StrictMath.tanh(h);}
}
Finally, set some implementation to your Neuron:
public class Neuron {
private final ActivationFunction actFunc;
// other fields...
public Neuron(ActivationFunction actFunc) {
this.actFunc = actFunc;
}
public float fire(){
// ...
out = actFunc.get(pot);
return out;
}
}
as following:
Neuron n = new Neuron(new SigmoidFunction());
Note, neural netoworks are using signal propagation through neurons, where weights are produced. Computing of weight depends also on first derivative of an activation function. Therefore, I would extend ActivationFunction by method, which will return first derivative at specified point x:
public interface ActivationFunction {
float get(float f);
float firstDerivative(float x);
}
So the implemenations will look like:
public class StepFunction implements ActivationFunction {
#Override
public float get(float x) {return (x < 0) ? 0f : 1f;}
#Override
public float firstDerivative(float x) {return 1;}
}
public class SigmoidFunction implements ActivationFunction {
#Override
public float get(float x) {return StrictMath.tanh(x);}
// derivative_of tanh(x) = (4*e^(2x))/(e^(2x) + 1)^2 == 1-tanh(x)^2
#Override
public float firstDerivative(float x) {return 1 - Math.pow(StrictMath.tanh(x), 2);}
}
Then, use actFunction.firstDerivative(x); in fire() method where weight is being computed.
I am currently working on a code that has to find the best solution. First I check whether one of the three is larger than the other two. Hence, there is a maximum that occurs only once. If there are two numbers larger than the third one, but equal to each other, I will have to compare the distance of those two and then the one with the smallest distance is chosen.
The profit functions and distances are calculated outside this method and not that important.
What I have come up with so far is to use a lot of if statements. However, I was wondering whether there would be a more efficient method to do this.
public void bestSolution(List<ROUTE> LS, List<ROUTE> SA, List<ROUTE> RR)
{
int profitLS = profitRoutes(LS);
int profitSA = profitRoutes(SA);
int profitRR = profitRoutes(RR);
int distanceLS = totalDistance(LS);
int distanceSA = totalDistance(SA);
int distanceRR = totalDistance(RR);
if ((profitLS > profitSA) & (profitLS > profitRR))
{
}
}
In case of finding max between three integers -
int mostProfit = Math.max(profitLS, Math.max(profitSA, profitRR));
Considering case - "distance of those two and then the one with the smallest distance is chosen"
class DistanceProfit{
private int profit;
private int distance;
public DistanceProfit(int profit, int distance){
this.profit = profit;
this.distance = distance;
}
}
...
//create DistanceProfit objects add to list
Collections.sort(distenceProfitList, new Comparator<DistenceProfit>{
public int compare(DistenceProfit dp1, DistenceProfit dp2){
if(dp1.getProfit()==dp2.getProfit())
return dp1.getDistance() - dp2..getDistance();
return dp1.getProfit() - dp2.getProfit();
}
});
You could create a TreeSet with the comparison results and select the 'greatest' element.
The comparison result could be something like:
public class ProfitCounter implements Comparable<ProfitCounter>
{
public ProfitCounter(List<ROUTE> route)
{
this.route = route;
profit = profitRoutes(route);
distance = totalDistance(route);
}
#Override
public int compareTo(ProfitCounter other)
{
int result;
result = profit - other.profit;
if (result == 0)
result = other.distance - distance;
return (result);
}
private List<ROUTE> route;
private int profit;
private int distance;
} // class ProfitCounter
Id use something on these lines. Does not limit u to 3 parameters.
public class RouteCalc implements Comparable<RouteCalc> {
private final List routes;
public RouteCalc(List routes) {
this.routes = routes;
}
public static int calcProfit(List routes) {
//use the list to calculate profit
return 0;
}
public static int calcDistance(List routes) {
//use the list to calculate distance
return 0;
}
#Override
public int compareTo(#NonNull RouteCalc another) {
final int profitA = calcProfit(this.routes);
final int profitB = calcProfit(another.routes);
//swap parameters to change from ascending to descending and vice-versa
final int compare = Integer.compare(profitA, profitB);
//if same profit, compare distance
if (compare == 0) {
final int distanceA = calcDistance(this.routes);
final int distanceB = calcDistance(another.routes);
return Integer.compare(distanceA, distanceB);
} else
return compare;
}
//sample usage
public static void main(String args[]) {
final List<RouteCalc> allRoutes = new ArrayList<>();
//add routes
final RouteCalc bestRoute = Collections.max(allRoutes);
}
}
static class CalculatedRoute {
public static CalculatedRoute mostProfitableOf(List<CalculatedRoute> calculatedRoutes) {
return Collections.max(calculatedRoutes, BY_PROFIT_AND_DISTANCE);
}
public static final Comparator<CalculatedRoute> BY_PROFIT_AND_DISTANCE = new Comparator<CalculatedRoute>() {
#Override
public int compare(CalculatedRoute o1, CalculatedRoute o2) {
int cmp = o2.profit - o1.profit;
if (cmp == 0) {
cmp = o1.distance - o2.distance;
}
return cmp;
}
};
private final List<ROUTE> routeList;
private final int profit;
private final int distance;
public CalculatedRoute(List<ROUTE> routeList, int profit, int distance) {
this.profit = profit;
this.distance = distance;
}
public List<ROUTE> getRouteList() {
return routeList;
}
public int getProfit() {
return profit;
}
public int getDistance() {
return distance;
}
}
public List<ROUTE> mostProfitableOf(List<ROUTE> LS, List<ROUTE> SA, List<ROUTE> RR) {
return CalculatedRoute.mostProfitableOf(Arrays.asList(
new CalculatedRoute(LS, profitRoutes(LS), totalDistance(LS)),
new CalculatedRoute(SA, profitRoutes(SA), totalDistance(SA)),
new CalculatedRoute(RR, profitRoutes(RR), totalDistance(RR))
)).getRouteList();
}