Simulating archers hitting a target monte carlo method - java

3 archers are shooting at a target with probabilities p1, p2, p3. With a Monte Carlo simulation I am supposed to find an approximation of the probabilities of the following events:
randomly chosen archer hits the target // already solved
the target will be hit if all three shoot at it with a single bullet. // no idea how to approach
This is the first problem of this type that I am approaching. I can solve it easily using probabilities formulas, but I have no idea how to approach the problem using a simulation.

I would do something like this:
public class Archer {
private Random random = new Random();
public final double chance;
public Archer(double chance) {
this.chance = chance;
}
public boolean shoot() {
return random.nextDouble() < chance;
}
}
// ...
public boolean sample_problem2() {
for (Archer archer : archers) {
if (archer.shoot()) return true;
}
return false;
}
public double estimate_sample2(long count) {
long positive = 0;
for (long i = 0; i < count; i++) {
if (sample_problem2()) positive++;
}
return (double)positive / (double)count;
}
Here, the archer objects shoot method will return true or false with their respective probabilities. sample_problem2 will simulate an event you need. The latter method will take count samples, and will estimate the probability of the simulated event.
If you have some example code, we can help you develop a solution which fits better to what you already have.

Related

How to convert two ints (swings, hits) to accuracy

How would I convert swings and hits to accuracy? I know how to calculate the swing/hit ratio but I don't know how to convert it to accuracy.
This is what I've tried:
public double convertToMeleeAccuracy(int swings, int hits) {
try {
double classicHitAccuracy = Double.valueOf(swings - hits); //I know the math for getting the ratio is swings / hits but i don't know how to calculate accuracy.
if (classicwlr < 0) {
return 0.0;
}
return classicwlr;
} catch (ArithmeticException e) {
return 0.0;
}
}
I'm going to try to explain this to you in a way that helped me calculate percentages easily throughout my life.
Let's look at this like so:
Say swings is always 10, so in this scenario, each swing is worth 10% of the accuracy. (because the max accuracy will always be 100%) In that case the function will look something like this:
public class Main {
public static void main(String[] args) {
System.out.println(convertToMeleeAccuracy(3)); // Can be any number you'd like under 10.
}
public static double convertToMeleeAccuracy(int hits) {
int swings = 10;
double percentage = 100.0 / swings;
return hits * percentage;
}
}
In this scenario, the program will output 30.0 which means 30% of the hits have hit.
In the scenario above I only used the number 10 because it's an easy number to work with, here's an example of how this would work with any number of swings:
public class Main {
public static void main(String[] args) {
System.out.println(convertToMeleeAccuracy(22, 21)); // Can be any numbers you'd like.
}
public static double convertToMeleeAccuracy(int swings, int hits) {
double percentage = 100.0 / swings;
return hits * percentage;
}
}
In this scenario, the function will output 95.45454545454547 which is the correct accuracy and you can use any numbers you'd like.
You can also add some checks in the function to make sure hits isn't higher than swings etc..
I hope I helped you understand!

Creating a Vehicle Program

Right now I'm doing some tasks from a java e-book that I've acquired, and unfortunately, I'm stuck. The main thought of this program is to create a Vehicle class, which along with a test program can increase, decrease and break the current speed.
The starting speed should be 0. I want the user to specify what speed the car should drive to (for an example 90 km/h). After hitting the speed(90 in this case) I want the program to ask the user if he wants to decrease the speed to a given value, stay at the same speed, or break to 0. Should all of this be done in the testprogram, or should it be implemented into the Vehicle class?
I'm supposed to create a program from the following UML: https://i.stack.imgur.com/01fgM.png
This is my code so far:
public class Vehicle {
int speed;
//Constructor
public Vehicle () {
this.speed = 0;
}
public void increaseSpeed (int differenceInc) {
this.speed += differenceInc;
}
public void decreaseSpeed (int differenceDec) {
this.speed -= differenceDec;
}
public void brake() {
}
public int getSpeed () {
return this.speed;
}
}
And this is my empty test class.
public class VehicleTest {
public static void main(String[] args) {
Vehicle golf = new Vehicle();
//Speed which should be accelerated to:
Vehicle myHybrid = new Vehicle();
System.out.println("You've hit the given speed. Do you want to stay at this speed, break, or decrease to another given speed?");
}
}
Well , first of all, welcome to Stack Overflow.
If you want a method to accept arguments (parameters) then you must declare said arguments and the arguments' types in the mehtod declaration:
public void increaseSpeed (int augmentValue) {
this.speed += augmentValue;
}
You're also asking about software design: "should the component (Vehicle) user or client be able to set the augment value of the increaseSpeed mehtod?" . The answer relies on the design of said component. If your method will accept an argument then perhaps the method should also validate the input value and establish pre and post conditions.
Hope this helps.
Probably the idea is to take an int for increaseSpeed(), so that you can increase the speed by that given integer. Also add the logic for hitting the speed limit in your increaseSpeed method.
So...
public void increaseSpeed (int amount) {
if (speed + amount < MAX_SPEED) { // Where MAX_SPEED is a static final int of value 90
this.speed += amount;
} else {
System.out.println("Max speed reached. Want to exceed (y/n)?");
Scanner scanner = new Scanner(System.in);
char c = scanner.next().charAt(0);
if (c == 'y') {
this.speed += amount;
}
}
}
You can do the same for decreaseSpeed(), of course. Don't forget to check if decreasing the speed doesn't result in a negative speed (unless, you consider a negative value of speed to be driving in reverse.
By the way, here I have hard-coded MAX_SPEED for simplicity. This is, of course, dependent on the road you are driving, so it is probably better to do this differently (e.g., a Road class that includes the particular attributes of a given road, or by passing both an integer for the amount you want to speedup with and an integer for the maximum speed).

Shortest path in Rat in a Maze with option to remove one wall

This is the problem:
You have maps of parts of the space station, each starting at a prison exit and ending at the door to an escape pod. The map is represented as a matrix of 0s and 1s, where 0s are passable space and 1s are impassable walls. The door out of the prison is at the top left (0,0) and the door into an escape pod is at the bottom right (w-1,h-1).
Write a function answer(map) that generates the length of the shortest path from the prison door to the escape pod, where you are allowed to remove one wall as part of your remodeling plans. The path length is the total number of nodes you pass through, counting both the entrance and exit nodes. The starting and ending positions are always passable (0). The map will always be solvable, though you may or may not need to remove a wall. The height and width of the map can be from 2 to 20. Moves can only be made in cardinal directions; no diagonal moves are allowed.
To Summarize the problem: It is a simple rat in a maze problem with rat starting at (0,0) in matrix and should reach (w-1,h-1). Maze is a matrix of 0s and 1s. 0 means path and 1 means wall.You have the ability to remove one wall(change it from 0 to 1). Find the shortest path.
I've solved the problem but 3 of 5 testcases fail and I don't know what those test cases are. and I'm unable to figure out why. Any help would be greatly appreciated.Thanks in Advance. Here is my code:
import java.util.*;
class Maze{//Each cell in matrix will be this object
Maze(int i,int j){
this.flag=false;
this.distance=0;
this.x=i;
this.y=j;
}
boolean flag;
int distance;
int x;
int y;
}
class Google4_v2{
public static boolean isPresent(int x,int y,int r,int c)
{
if((x>=0&&x<r)&&(y>=0&&y<c))
return true;
else
return false;
}
public static int solveMaze(int[][] m,int x,int y,int loop)
{
int r=m.length;
int c=m[0].length;
int result=r*c;
int min=r*c;
Maze[][] maze=new Maze[r][c];//Array of objects
for(int i=0;i<r;i++)
{
for(int j=0;j<c;j++)
{
maze[i][j]=new Maze(i,j);
}
}
Queue<Maze> q=new LinkedList<Maze>();
Maze start=maze[x][y];
Maze[][] spare=new Maze[r][c];
q.add(start);//Adding source to queue
int i=start.x,j=start.y;
while(!q.isEmpty())
{
Maze temp=q.remove();
i=temp.x;j=temp.y;
int d=temp.distance;//distance of a cell from source
if(i==r-1 &&j==c-1)
{
result=maze[i][j].distance+1;
break;
}
maze[i][j].flag=true;
if(isPresent(i+1,j,r,c)&&maze[i+1][j].flag!=true)//check down of current cell
{
if(m[i+1][j]==0)//if there is path, add it to queue
{
maze[i+1][j].distance+=1+d;
q.add(maze[i+1][j]);
}
if(m[i+1][j]==1 && maze[i+1][j].flag==false && loop==0)//if there is no path, see if breaking the wall gives a path.
{
int test=solveMaze(m,i+1,j,1);
if(test>0)
{
test+=d+1;
min=(test<min)?test:min;
}
maze[i+1][j].flag=true;
}
}
if(isPresent(i,j+1,r,c)&&maze[i][j+1].flag!=true)//check right of current cell
{
if(m[i][j+1]==0)
{
maze[i][j+1].distance+=1+d;
q.add(maze[i][j+1]);
}
if(m[i][j+1]==1 && maze[i][j+1].flag==false && loop==0)
{
int test=solveMaze(m,i,j+1,1);
if(test>0)
{
test+=d+1;
min=(test<min)?test:min;
}
maze[i][j+1].flag=true;
}
}
if(isPresent(i-1,j,r,c)&&maze[i-1][j].flag!=true)//check up of current cell
{
if(m[i-1][j]==0)
{
maze[i-1][j].distance+=1+d;
q.add(maze[i-1][j]);
}
if(m[i-1][j]==1 && maze[i-1][j].flag==false && loop==0)
{
int test=solveMaze(m,i-1,j,1);
if(test>0)
{
test+=d+1;
min=(test<min)?test:min;
}
maze[i-1][j].flag=true;
}
}
if(isPresent(i,j-1,r,c)&&maze[i][j-1].flag!=true)//check left of current cell
{
if(m[i][j-1]==0)
{
maze[i][j-1].distance+=1+d;
q.add(maze[i][j-1]);
}
if(m[i][j-1]==1 && maze[i][j-1].flag==false && loop==0)
{
int test=solveMaze(m,i,j-1,1);
if(test>0)
{
test+=d+1;
min=(test<min)?test:min;
}
maze[i][j-1].flag=true;
}
}
}
return ((result<min)?result:min);
}
public static int answer(int[][] m)
{
int count;
int r=m.length;
int c=m[0].length;
count=solveMaze(m,0,0,0);
return count;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter row size ");
int m=sc.nextInt();
System.out.println("enter column size ");
int n=sc.nextInt();
int[][] maze=new int[m][n];
System.out.println("Please enter values for maze");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
maze[i][j]=sc.nextInt();
}
}
int d=answer(maze);
System.out.println("The maze can be solved in "+d+" steps");
}
}
Found the problem. maze[i][j].flag=true; needs to be put as soon as the cell is visited, inside the if(m[i+1][j]==0) condition. Otherwise, the distance for same cell can be added by more than one cells
Unfortunately it's quite hard to help you because your code is very difficult to read. The variables are generally single characters which makes it impossible to know what they are supposed to represent. Debugging it would be more help than most of us are willing to give :-)
I suggest you go about debugging your code as follows:
Split your solveMaze method into a number of smaller methods that each perform much simpler functions. For example, you have very similar code repeated 4 times for each direction. Work to get that code in a single method which can be called 4 times. Move your code to create the array into a new method. Basically each method should do one simple thing. This approach makes it much easier to find problems when they arise.
Write unit tests to ensure each of those methods do exactly what you expect before attempting to calculate the answer for entire mazes.
Once all the methods are working correctly, generate some mazes starting from very simple cases to very complex cases.
When a case fails, use an interactive debugger to walk through your code and see where it is going wrong.
Good luck.

java simple neural network setup

I have decided to play around with some simple concepts involving neural networks in Java, and in adapting somewhat useless code I found on a forum, I have been able to create a very simple model for the typical beginner's XOR simulation:
public class MainApp {
public static void main (String [] args) {
Neuron xor = new Neuron(0.5f);
Neuron left = new Neuron(1.5f);
Neuron right = new Neuron(0.5f);
left.setWeight(-1.0f);
right.setWeight(1.0f);
xor.connect(left, right);
for (String val : args) {
Neuron op = new Neuron(0.0f);
op.setWeight(Boolean.parseBoolean(val));
left.connect(op);
right.connect(op);
}
xor.fire();
System.out.println("Result: " + xor.isFired());
}
}
public class Neuron {
private ArrayList inputs;
private float weight;
private float threshhold;
private boolean fired;
public Neuron (float t) {
threshhold = t;
fired = false;
inputs = new ArrayList();
}
public void connect (Neuron ... ns) {
for (Neuron n : ns) inputs.add(n);
}
public void setWeight (float newWeight) {
weight = newWeight;
}
public void setWeight (boolean newWeight) {
weight = newWeight ? 1.0f : 0.0f;
}
public float getWeight () {
return weight;
}
public float fire () {
if (inputs.size() > 0) {
float totalWeight = 0.0f;
for (Neuron n : inputs) {
n.fire();
totalWeight += (n.isFired()) ? n.getWeight() : 0.0f;
}
fired = totalWeight > threshhold;
return totalWeight;
}
else if (weight != 0.0f) {
fired = weight > threshhold;
return weight;
}
else {
return 0.0f;
}
}
public boolean isFired () {
return fired;
}
}
In my main class, I've created the simple simulation in modeling Jeff Heaton's diagram:
However, I wanted to ensure my implementation for the Neuron class is correct..I've already tested all possible inputs ( [true true], [true false], [false true], [false false]), and they all passed my manual verification. Additionally, since this program accepts the inputs as arguments, it also seems to pass manual verification for inputs such as [true false false], [true true false], etc..
But conceptually speaking, would this implementation be correct? Or how can I improve upon it before I start further development and research into this topic?
Thank you!
It looks like a good starting point. I do have a few suggestions:
For scalability, fire() should be restructured so that a neuron that's already fired with the current input set doesn't have to recalculate each time. This would be the case if you had another hidden layer, or more than one output node.
Consider splitting your threshold calc into its own method. Then you can subclass Neuron and use different types of activation functions (bipolar sigmoid, RBF, linear, etc).
To learn more complex functions, add a bias input to each neuron. It's basically like another input with it's own weight value, but the input is always fixed at 1 (or -1).
Don't forget to allow for training methods. Backpropagation will need something like the inverse of fire(), to take a target output and ripple the weight changes through each layer.
From the (limited) work I've done with neural nets, that implementation and model looks correct to me - the output is what I'd expect and the source looks solid.

Java solving a maze with recursion problem

I have an assignment where I am supposed to be able to display the path of a maze from the entrance to the exit and I have gotten it to work to a degree but when the maze gets more complicated with dead ends and such the program goes into infinite recursion. If you could give me any help to point me in the right direction it would be much appreciated.
Mu current theory can be found in the Room class.
Here is the Room class where the references to each room connecting the maze are stored, kind of like a linked list linked in 6 directions, north, south, east, west, up, and down.
import java.util.ArrayList;
public class OurRoom
{
private OurRoom exits[];
private String name;
private static ArrayList<OurRoom> list;
public OurRoom()
{
this(null);
}
public OurRoom(String name)
{
this.name = name;
this.list = new ArrayList<OurRoom>();
exits = new OurRoom[Direction.values().length];
for(OurRoom exit : exits)
{
exit = null;
}
}
public void connectTo(OurRoom theOtherRoom, Direction direction)
{
exits[direction.ordinal()] = theOtherRoom;
theOtherRoom.exits[direction.getOpposite().ordinal()] = this;
}
public OurRoom getExit(Direction direction)
{
return exits[direction.ordinal()];
}
public boolean lookExit(Direction direction)
{
return exits[direction.ordinal()] != null;
}
public String getName() {
return name;
}
public OurRoom solveRecursively(OurRoom exit) {
list.add(this);
if(this == exit) {
return this;
}else {
OurRoom temp = null;
if(lookExit(Direction.east)) {
temp = exits[Direction.east.ordinal()].solveRecursively(exit);
}
else if(lookExit(Direction.up)) {
temp = exits[Direction.up.ordinal()].solveRecursively(exit);
}
else if(lookExit(Direction.south)) {
temp = exits[Direction.south.ordinal()].solveRecursively(exit);
}
else if(lookExit(Direction.down)) {
temp = exits[Direction.down.ordinal()].solveRecursively(exit);
}
else if(lookExit(Direction.west)) {
temp = exits[Direction.west.ordinal()].solveRecursively(exit);
}
else if(lookExit(Direction.north)) {
temp = exits[Direction.north.ordinal()].solveRecursively(exit);
}
return temp;
}
}
public ArrayList<OurRoom> getList() {
return list;
}
}
Here is the Direction enum
public enum Direction
{
north, south, east, west, up, down;
public Direction getOpposite()
{
switch(this)
{
case north:
return south;
case south:
return north;
case east:
return west;
case west:
return east;
case up:
return down;
case down:
return up;
default:
return this;
}
}
}
And here is an example of how the maze is built.
import java.util.ArrayList;
import java.util.Iterator;
public class OurMaze
{
private OurRoom entrance, exit;
public OurMaze()
{
this(1);
}
public OurMaze(int mazeNumber)
{
entrance = null;
exit = null;
switch(mazeNumber)
{
case 0:
break;
case 1:
this.buildMaze1();
break;
default:
}
}
public OurRoom getEntrance()
{
return entrance;
}
public OurRoom getExit()
{
return exit;
}
public Iterator<OurRoom> findPathRecursively() {
entrance.solveRecursively(exit);
ArrayList<OurRoom> list = entrance.getList();
return list.iterator();
}
private void buildMaze1()
{
OurRoom room1, room2;
room1 = new OurRoom("Room 1");
room2 = new OurRoom("Room 2");
room1.connectTo(room2, Direction.north);
entrance = room1;
exit = room2;
}
public static void main(String[] args) {
OurMaze maze = new OurMaze(1);
}
}
You just need to keep two-dimensional array with values indicating whether the cell was visited or not: you don't want to go through the same cell twice.
Apart from that, it's just breadth-first-search (depth-first-search is fine too, if you don't want shortest path).
Some links
http://en.wikipedia.org/wiki/Flood_fill
http://en.wikipedia.org/wiki/Breadth-first_search
http://en.wikipedia.org/wiki/Depth-first_search
Sample search routine.
void dfs(int i, int j) {
if cell(i, j) is outside of maze or blocked {
return
}
if visited[i][j] {
return
}
visited[i][j] = true;
dfs(i + 1, j);
dfs(i - 1, j);
dfs(i, j + 1);
dfs(i, j - 1);
}
Path itself can be found if, like with visited, for each cell you keep cell from which you came to it. So, printing would look like this (just a pseudocode).
var end = exit_point;
while (end != start_point) {
print end;
end = came_from[end];
}
edit
The code above is for two-dimensional maze and I just noticed that you have three-dimensional version. But it's easy to introduce third coordinate in the example above.
Let me know if there're any difficulties.
Others have described appropriate approaches to solving this problem, but I think it's worth pointing out exactly why your program won't scale to more complex mazes.
As duffymo hinted, the problem is that your algorithm doesn't do any backtracking correctly - when it takes a branch that turns out to be a dead end, and returns to a previous square, it doesn't remember this at all. And since it tries the exits in a fixed order, it will always retry that failed exit immediately.
Look at how the solveRecursively function is defined, and you'll see that from any given room, only one direction would ever be tried. If a room has an exit to the east, then it doesn't even matter if it has any other exits since the if-else block would never consider them.
So as it turns out, your solving logic will fail (i.e go into an infinite loop between two rooms) in any case where the correct solution isn't the "first" exit from each room in the order you've defined there.
(A quick fix would be to store a simple boolean flag against each room/direction. Set it before you call the recursive call, then if you end up back in that room again, you know that direction doesn't work out and can let the if block fall through to try one of the other exits. Refactoring this to use typical BFS logic, as Nikita suggests, would be better overall)
I'd bet you need a tree of some kind to keep track of where you've been.
When recursion fails, it usually means that the person writing the method didn't expression the stopping condition properly. What's yours?
I think this was the first game I ever encountered on a computer. It was an IBM mainframe at the school where I got my undergraduate degree. The I/O was on a paper teletype. Many salt tears were wept at the account dollars that were flushed away playing this maze game. Great fun.
When solving the maze, represent it as a 6-ary graph where each node is a room and each edge represents travel in one of the six directions. You can then apply some of the well known algorithms for finding shortest paths.
This page describes various solutions for finding paths through graphs that are structured as such. Your graph is easier than the ones that describe real-world maps, since the cost of traveling down any edge is equal to the cost of traveling down any other edge.
Be especially sure to look at Dijkstra's algorithm.

Categories

Resources