Here x1 and v1 are initial position and velocity of car1, and x2 and v2 for car2. I need to find if the two cars meet at any point. It gives me error displaying "No" always.Any suggestions?
if (v1 > v2) {
while ((x1 + (v1 * i)) > (x2 + (v2 * i))) {
if ((x1 + (v1 * i)) == (x2 + (v2 * i))) {
prime = true;
break;
}
System.out.println(""+i);
i++;
}
if (prime == true) {
s = "Yes";
} else {
s = "No";
}
}
if (v2 > v1) {
while ((x2 + (v2 * i)) > (x1 + (v1 * i))) {
if ((x1 + (v1 * i)) == (x2 + (v2 * i))) {
prime = true;
break;
}
System.out.println(""+i);
i++;
}
if (prime == true) {
s = "Yes";
} else {
s = "No";
}
}
if (v1 == v2) {
if (x1 == x2) {
s = "Yes";
} else s = "No";
}
System.out.println(""+s);
}
}
This is a mathematical question not so much a programming one. Basically you don't need any loops and stuff to answer it. I assume (since there are no other implications) that both cars go in the same X direction with speed V where both X and V are positive numbers.
So basically your logic can be -> If the faster car is behind the slower one they will eventually meet. Otherwise they won't. And in this case you won't need any loops. The last check in the example below is if they are already in the same spot.
if((x1<x2 && v1>v2) || (x1>x2 && v1<v2) || (x1==x2)) {
System.out.println("Yes");
} else {
System.out.println("No");
}
If V can be negative (for example to show going backwards which is a bit strange way because velosity cannot be negative) then it is still the same. You might go for a loop only if you want to know the point on the vector X where they met. But with some calculations you can still calculate it without loops. For example :
int vDiff=Math.abs(v1-v2);
int xDiff=Math.abs(x1-x2);
System.out.println("Meeting point: "+(((double)xDiff)/((double)vDiff)*v1+x1));
I think you're complicating the problem, with your iterations you're essentially finding the time step at which the cars meet, if they do meet.
There are actually only five possibilities for these two cars, when considered in one direction:
1) Car 1 is ahead of car 2, and moving faster than or the same speed as car 2 => Cars never meet
2) Car 1 is behind car 2, and moving faster than car 2 => Cars meet
3) Car 1 is ahead of car 2, and moving slower than car 2 => Cars meet
4) Car 1 is behind car 2, and moving slower than or the same speed as car 2 => Cars never meet
5) Cars have already met.
In code this might look like the following:
boolean carsMeet(x1,v1,x2,v2){
boolean output = false;
if(x1 > x2){
// Conditions 1 and 3. Car 1 is ahead of car 2
if (v2 > v1){
// Condition 3
output = true;
}
} else if (x1 < x2){
// Conditions 2 and 4. Car 2 is ahead of car 1
if (v1 > v2){
// Condition 2
output = true;
}
} else {
// Condition 5. Car 1 has already met car 2
output = true;
}
return output;
}
I haven't run this code to check it for syntax errors, but in general this is how I advise tackling the problem, rather than your current approach.
s = "No";
if (x1 == x2) {
s = "Yes";
} else if (v1 == v2) {
s = "No";
} else if ((x2-x1)/(v1-v2) > 0) {
s = "Yes";
}
Related
I'm working on a project for school that requires me to move a robot. How far the robot will move each second (variable t) is calculated by the function below.
The first function is easy. The 2nd and 3rd on the other are where I'm stuck. How would I write F(t-1)? Below is what I have so far.
if (t == 0) {
distance = 2;
} else if (t > 0 && <=6 || t > 12) {
// No clue on how to write the 2nd distance equation.
} else if (t >= 7 && <=12) {
// No clue on how to write the 3rd distance equation.
}
Recursion really isn't necessary to solve this.
Note that in each of the non-zero time cases, F(t) = F(t-1) + something.
So you can simply do:
double f = 2; /* Initial value at t=0 */
for (int t = 1; t <= maxT; ++t) { // maxT is the maximum value of t.
if (t <= 6 || t > 12) {
f += /* something for case 2 */;
} else {
f += /* something for case 3 */;
}
}
System.out.println(f);
You can do this with recursion, but you will get a StackOverflowError if maxT becomes modestly large; by contrast, using a loop will work for arbitrarily large maxT (modulo floating point errors).
As pointed out by #Andreas, you can do this without looping over all values of t:
double f = 2 * (maxT + 1);
for (int t = 7; t <= maxT && t <= 12; ++t) {
f += log(t) - 2;
}
and you can eliminate that loop too by precomputing the values.
This is a problem which involves the use of recursion. By and large, pay close attention to the notation Ft-1, since that refers to an evaluation of the specific function at t-1.
I won't write out all of the code, but I'll give you some of the basics:
When t = 0, return 2. This is your base case.
When t is between 0 and 6 inclusive or greater than 12, return an evaluation of the function at t-1 and add 2.
When t is between 7 and 12 both inclusive, return an evaluation of the function at t-1 and add log2(t).
Here's something to get you at least started in the right direction.
public double evaluateDistance(int t) {
if(t == 0) {
return 2;
} else if(t > 0 && t <= 6) || (t > 12) {
// Think about this - it would involve another call to evaluateDistance, but what is t again?
} else if(t >= 7 && t <= 12) {
// Another evaluation involving the function.
// For free, the change of base operation you'll need to get base-2 evaluation for the log:
return ??? + Math.log(t)/Math.log(2);
}
}
Think I figured it out. Sorry if I wasn't clear on what I needed, just needed to figure out how to write the equations in the function. Think I figured it out though.
public double move()
{
int t = 0;
if(t == 0) // After the first second, robot moves 2
{
distance = 2;
}
else if(t > 0 && t <= 6 || t > 12) // From seconds 0 to 6 and after 12, robot moves distance equation
{
distance = (2*t)+2;
}
else if(t >= 7 && t <= 12) // From seconds 7 to 12, robot moves distances equation
{
distance = (2*t)+(Math.log(t)/Math.log(2));
}
position = position + distance;
return position;
}
}
I'm trying to implement
in my ThreePoint program in java.
Here is my getLength method to calculate the sides
private double getLength(int side){
if(side == 0 && isTriangle()){
return Math.sqrt((x2-x1) * (x2-x1) + (y2-y1) * (y2-y1));
} else if (side == 1 && isTriangle()){
return Math.sqrt((x2-x0) * (x2-x0) + (y2-y0) * (y1-y0));
} else if (side == 2 && isTriangle()){
return Math.sqrt((x1-x0) * (x1-x0) + (y1-y0) * (y1-y0));
}else{ return 0;
}
}
The parameter vertex should be 0, 1, or 2 and is used to specify angle a0, a1, or a2. The method returns the angle of the specified vertex. If the three points do not form a triangle, this method should return zero. To determine the angles of the triangle you can use the law of cosines.(as above)
so below is what the skeleton would look like, how do I implement the diagram though?
public double getAngle(int vertex){
if(vertex == 0 && isTriangle()) {
return a0 here; }
else if(vertex == 1 && isTriangle()) {
return a1 here; }
else if(vertex == 2 && isTriangle()) {
return a2; }
My java is a little rusty, and my trig is even rustier, but I think what you want for a0 is below. You can figure out a1 and a2 from below. Also note that Java trigonometry uses Radians not degrees, but that shouldn't be a problem here.
double s02 = Math.pow(this.getLength(0),2);
double s12 = Math.pow(this.getLength(1),2);
double s22 = Math.pow(this.getLength(2),2);
a0 = Math.acos((-s02+s12+s22)/(2*s12*s22));
Note: I assume s0 s1 and s2 are the lengths of side 0,1, and 2 correct?
The standard Ackermann formula as written in Java:
public static int ack(int x, int y) {
if (x == 0) {
return y + 1;
} else if (y == 0) {
return ack(x-1, 1);
} else {
// perforce (x > 0) && (y > 0)
return ack(x-1, ack(x,y-1));
}
}
I've been wondering - is there a faster version to implement this? I'm thinking maybe there is by using an accumulator or a loop.
Yes, for example by "cheating". If m is 5 or higher, none of the results can be represented by an int. For m = 4, only the n < 2 cases can be represented. For m < 4, there are simple closed formula's based on n.
Everything else would overflow anyway, so let's pretend those cases don't even happen (or you could throw an error or whatever).
Not tested:
int Ackerman(int m, int n) {
switch (m) {
case 0:
return n + 1;
case 1:
return n + 2;
case 2:
return n * 2 + 3;
case 3:
return (int)((1L << (n + 3)) - 3);
case 4:
return n == 0 ? 13 : 65533;
}
}
I can tell you one thing... int will not suffice for very many values of x and y
If you're going to be calling the function repetitively, you can create a int[][] array to store various values so you can look them up the second+ time around and only need to compute it once. But as for speeding up a single execution... not sure.
This variation is faster:
public static int ack(int x, int y) {
while (x != 0) {
y = y == 0 ? 1 : ack(x, y - 1);
x--;
}
return y + 1;
}
This question already has answers here:
Algorithm for Determining Tic Tac Toe Game Over
(26 answers)
Closed 9 years ago.
I'm looking for the most efficient java way to test if somebody has won at tic tac toe. The data is in a 2d array like so...
char[][] ticTacToe =
{{'X',' ','O'},
{'O','X','O'},
{'X',' ','X'},};
I know this isn't the professional way to initialize an array but I'm just testing here.
The best I can do for right now is an exhaustive if/else tree.
Here's one of those trees...
if (ticTacToe[1][1] == 'X'){
if (ticTacToe[0][0] == 'X'){
if (ticTacToe[2][2] == 'X'){
System.out.println("X wins");
}
}
else if (ticTacToe[0][1] == 'X'){
if (ticTacToe[2][1] == 'X'){
System.out.println("X wins");
}
}
else if (ticTacToe[1][0] == 'X'){
if (ticTacToe[1][2] == 'X'){
System.out.println("X wins");
}
}
else if (ticTacToe[2][0] == 'X'){
if (ticTacToe[0][2] == 'X'){
System.out.println("X wins");
}
}
}
This one only cares about what's in the middle
This is very basic and I want to improve it as far as minimizing lines of code goes.
Just for fun, keep two numbers, starting as zeros, one for X, one for O. Update them by oring with the moves. To check for a winner, first and, then xor with the mask.
277 & 273 ^ 273
0 ==> we have a winner.
276 & 273 ^ 273
1 ==> not.
277 == parseInt("100010101",2)
273 == parseInt("100010001",2)
276 == parseInt("100010100",2)
For more fun, here's an example that plays O in your favorite JavaScript console:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
</head>
<body>
<script>
var x = 0, o = 0, count = 0, w = 0
ws = [0007,0070,0700,0111,0222,0444,0124,0421]
function t1(v){
var w1 = 0
for (var i in ws)
w1 |= !(v & ws[i] ^ ws[i])
return w1
}
function t(i){
var ot = count % 2, m = 1 << (9 - i), bd = x | o
if (!ot && (i > 9 || i < 1 || i != Math.floor(i)))
return "Out of bounds."
else if (m & bd)
return "Position taken."
if (ot){
var n1 = 0, a1 = -2
while (bd & (1 << n1))
n1++
var n = n1
while (n1 < 9){
var m1 = 1 << n1
if (!(bd & m1)){
var bt = -mx(x,o | m1,count + 1)
if (bt > a1){
a1 = bt
n = n1
}
}
n1++
}
w = t1(o |= 1 << n)
}
else
w = t1(x |= m)
var b = "\n", p = 0400
while (p > 0){
if (p & x)
b += "X"
else if (p & o)
b += "O"
else b += "."
if (p & 0110)
b += "\n"
p >>= 1
}
if (w)
b += "\n\n" + (ot ? "O" : "X") + " wins!"
else if (!(bd ^ 0777))
b += "\n\nDraw."
if (!ot){
console.log(b + '\n\n"""')
count++
console.log(t(-1))
count++
}
else
return b + "\n"
return '"'
}
function mx(x1,o1,c1){
var ot1 = c1 % 2, w1 = ot1 ? t1(x1) : t1 (o1),
b1 = x1 | o1, p = 0400
if (w1)
return -1
if (!(b1 ^ 0777))
return 0
var a = -2
while (p > 0){
if (!(b1 & p))
a = Math.max(a,-mx(ot1 ? x1 : x1 | p,ot1 ? o1 | p : o1,c1 + 1))
p >>= 1
}
return a
}
console.log(' Plays O!'
+ '\nTo play, type t(MOVE); MOVE is from 1-9')
</script>
</body>
</html>
Mark board as 3x3 magicSquare and you have win when sum in line is 15.
It's a bit verbose, but I think this is probably the most efficient way to do it (unless someone can come up with a clever way to check both diagonals at once).
public class TicTacToe
{
char[][] ticTacToe =
{{'X',' ','O'},
{'O','X','O'},
{'X',' ','X'},};
private Character winner = null;
public Character getWinner()
{
return this.winner;
}
public boolean isSolved()
{
this.checkSolved();
return this.winner != null;
}
private void checkSolved()
{
for(int i = 0; i < ticTacToe.length; i++)
{
Character win = checkRow(i);
if(win != null || (win = checkColumn(i)) != null)
{
this.winner = win;
return;
}
}
//Check diagonal top left to bottom right
if(this.ticTacToe[0][0] != ' ')
{
if(this.ticTacToe[0][0] == this.ticTacToe[1][1] &&
this.ticTacToe[1][1] == this.ticTacToe[2][2])
{
this.winner = this.ticTacToe[0][0];
}
}
//Check diagonal top right to bottom left
else if(this.ticTacToe[0][2] != ' ')
{
if(this.ticTacToe[0][2] == this.ticTacToe[1][1] &&
this.ticTacToe[1][1] == this.ticTacToe[2][0])
{
this.winner = this.ticTacToe[0][2];
}
}
}
private Character checkRow(int row)
{
if(this.ticTacToe[row][0] == ' ')
{
return null;
}
if(this.ticTacToe[row][0] == this.ticTacToe[row][1] &&
this.ticTacToe[row][1] == this.ticTacToe[row][2])
{
return this.ticTacToe[row][0];
}
return null;
}
private Character checkColumn(int column)
{
if(this.ticTacToe[0][column] == ' ')
{
return null;
}
if(this.ticTacToe[0][column] == this.ticTacToe[1][column] &&
this.ticTacToe[1][column] == this.ticTacToe[2][column])
{
return this.ticTacToe[column][0];
}
return null;
}
public static void main(String[] args)
{
TicTacToe ttt = new TicTacToe();
if(ttt.isSolved())
{
System.out.println(ttt.getWinner()); // X
}
}
}
For a player, say 'x', there are 8 ways to win and each corresponds to 3 'x' in a row/column/diagonal.
Hence, you can create an array of length 8 and each item corresponds to the number of 'x' in that row/column/diagonal.
When the player chooses a move, then you update the array and check whether there exists 3 in the array.
Although it needs more space, it is easier to generalize to a large board.
There are four different ways to win at tick-tack-toe:
form a horizontal line
form a vertical line
form a diagonal line from the upper-left to the lower-right corner
form a diagonal line from the lower-left to the upper-right corner
All of these four win-conditions can be solved with a for-loop. The advantage of this solution is that it can be applied to any matrix-size.
I'm trying to create a baseball simulation game within java. I'm utilizing instances of 'pitches' as the the iteration for my system. Within this, I have several different possibilities for the outcome. Hit, miss(strike), foul ball(no effect). I created an array of players from another class that read in specific attributes of my players that I design. The only attributes I'm trying to utilize currently are the power of the hitters and their consistency. I'm using random numbers to generate a certain and depending on where that value lies, determines whether it is a ball or a strike. The 'ball' logic is simple and works effectively; however, I'm only receiving counts of balls for the hitters. I'm stuck on how to implement the logic of probability of a strike(a missed swing) or a hit in regards to the pitch being a strike. The constructor I'm using for the player goes as follows
Player a = new Player(false, false, true, 10, 20, 0.75, true, null);
you can ignore the false's and true's and null, just pay attention to the numbers
the first number(10) indicates the speed, not relevant.
The second number(20) indicates the power.
The third indicates the consistency of the hitter.
I apologize if this may be confusing or too elementary, I've only been programming for a little over a month. All help would be greatly appreciated. Currently the only thing printing for me looks a little like
Press 'p' to initiate pitches
p
Ball count is: (0,0)
Ball count is: (0,0)
Ball count is: (0,0)
Ball count is: (0,0)
Ball!
Ball count is: (1,0)
Ball count is: (1,0)
Ball!
Ball count is: (2,0)
Ball count is: (2,0)
Ball count is: (2,0)
Ball!
Ball count is: (3,0)
I don't understand why the program is only recognizing balls and not describing what is printing as nothing, which I assume to be the foul ball(however its not printing my statement)
Please help, and thank you so much!
import java.util.Scanner;
public class Game {
public static void main(String[] args) {
System.out.println("Press 'p' to initiate pitches");
Scanner kb = new Scanner(System.in);
String s = kb.nextLine();
if(s.equalsIgnoreCase("p"))
{
int ball = 0;
int strike = 0;
//10 instances of pitches
for(int i = 0; i < 10; i++)
{
double number = Math.random();
if(number > 0.5)
{
ball++;
if(ball == 4)
{
System.out.println("Ball four, take your base");
break;
}
System.out.print("Ball!");
}
else if(strike() == true)
{
{
if(isMiss() == true)
{
System.out.print(" Strike!");
strike++;
}
else if(isFoul() == true)
{
System.out.println("Foul ball!");
}
}
if(strike == 3)
{
System.out.print(" Player struck out!");
break;
}
}
else
{
if(isHit() == true)
{
System.out.println("The ball was hit!");
System.out.println(isHit());
break;
}
}
System.out.println(" Ball count is: " + "(" + ball + "," + strike + ")");
}
}
}
public static boolean strike()
{
if(isMiss() == true)
{
return true;
}
else if(isFoul() == true)
{
return false;
}
else if(isHit() == true)
{
return true;
}
return false;
}
public static boolean isHit()
{
double probability = Math.random();
Player a = new Player(false, false, true, 10, 20, 0.75, true, null);
if(a.power > 5)
{
if(a.consistency > 0.5)
{
if(probability > 3 && probability < 6)
{
return false;
}
if(probability > 6 && probability < 9)
{
return false;
}
if(probability > 9 && probability < 12)
{
return true;
}
return true;
}
System.out.println("The ball was hit!");
}
return false;
}
public static boolean isMiss()
{
double probability = Math.random();
Player a = new Player(false, false, true, 10, 20, 0.75, true, null);
if(a.power > 5)
{
if(a.consistency > 0.5)
{
if(probability > 3 && probability < 6)
{
return true;
}
if(probability > 6 && probability < 9)
{
return false;
}
if(probability > 9 && probability < 12)
{
return false;
}
return false;
}
}
return false;
}
public static boolean isFoul()
{
double probability = Math.random();
Player a = new Player(false, false, true, 10, 20, 0.75, true, null);
if(a.power > 5)
{
if(a.consistency > 0.5)
{
if(probability > 3 && probability < 6)
{
return false;
}
if(probability > 6 && probability < 9)
{
return true;
}
if(probability > 9 && probability < 12)
{
return false;
}
}
}
return false;
}
I suggest you use your debugger to step through your code as there are many sections which don't make sense to me and I cannot run your code for you using with the Player class (and I cannot make it up as it doesn't make sense ;)
Sections of code which don't make sense are
double probability = Math.random();
so probability is a number between [0, 1)
if(probability > 3 && probability < 6) // always false.
if(probability > 6 && probability < 9) // always false
if(probability > 9 && probability < 12) // always false.
// prints the ball was hit but returns `false` to isHit
System.out.println("The ball was hit!");
}
return false;
For strikes:
if (Math.random() > consistency) { /* strike! */ }
You might want a constant foul ball chance (like if they hit the ball, they have a 10% chance of foul ball:
else if (Math.random() < 0.1) { ... }
And same for power, but maybe multiply it by 0.3 (since home runs are rare):
if (Math.random() < power * 0.3) { ... }
Note that for these to work, your consistency and power variables have to be decimals.
For example, 50% consistency would be 0.5. 20% consistency would be 0.2. Similarly, 1 is the maximum amount of power and 0 is really weak.
0.5 would be in between.