I planned to develop an equation solver from basic and able to do basic mathematics operations using below code. I have used a token stack structure which will used to store the deliminator and number token. Though this implementation is too basic, I want to improve it on later version. I just need some helps the way I use the data structure to store the token as a set of stacks. Please kindly suggest any mistake ?
import java.util.ArrayList;
import java.util.Stack;
class TokenStack<N, D> {
private Stack<N> numberStack;
private Stack<D> delimStack;
public TokenStack() {
numberStack = new Stack<N>();
delimStack = new Stack<D>();
}
public void pushN(N num) {
numberStack.push(num);
}
public N popN() {
return numberStack.pop();
}
public void pushD(D delim) {
delimStack.push(delim);
}
public D popD() {
return delimStack.pop();
}
public boolean isEmptyN() {
return numberStack.isEmpty();
}
public boolean isEmptyD() {
return delimStack.isEmpty();
}
}
public class GeneralST {
private static final char SPACE_DELIM = ' ';
private static final char ADD_DELIM = '+';
private static final char SUB_DELIM = '-';
private static final char MUL_DELIM = '*';
private static final char DIV_DELIM = '/';
protected static final char EQU_DELIM = '=';
private TokenStack<String, Character> tokens = new TokenStack<String, Character>();
protected ArrayList<Character> acceptedDelims = new ArrayList<Character>();
protected ArrayList<Character> mathsDelims = new ArrayList<Character>();
protected double result;
public double getResult() {
return result;
}
protected void setupDelims() {
acceptedDelims.add(SPACE_DELIM);
mathsDelims.add(ADD_DELIM);
mathsDelims.add(SUB_DELIM);
mathsDelims.add(MUL_DELIM);
mathsDelims.add(DIV_DELIM);
acceptedDelims.addAll(mathsDelims);
}
private void tokenize(String str) {
String reverse = "";
for (int i = str.length() - 1; i >= 0; i--) {
char charAt = str.charAt(i);
if (i > 1) {
char charPre = str.charAt(i - 1);
if (acceptedDelims.indexOf(charAt) == -1 && (charPre == '-' || charPre == '+')) {
reverse = reverse + charPre + charAt;
i--;
} else {
reverse = reverse + charAt;
}
} else {
reverse = reverse + charAt;
}
}
int i = 0;
while (reverse.length() > 2) {
char charAt = reverse.charAt(i);
char chartNext = reverse.charAt(i + 1);
if (acceptedDelims.indexOf(charAt) != -1 && acceptedDelims.indexOf(chartNext) != -1) {
String previous = reverse.substring(0, i);
if (!previous.equals("") && !previous.equals(" ")) {
tokens.pushN(previous);
}
if (mathsDelims.indexOf(charAt) != -1) {
tokens.pushD(charAt);
}
reverse = reverse.substring(i + 1);
i = i - previous.length() - 1;
}
i++;
}
if (!reverse.equals("")) {
tokens.pushN(reverse);
}
}
private double equate() {
double val = 0;
int step = 1;
int side = 1;
while (!tokens.isEmptyN() && !tokens.isEmptyD()) {
char delim = tokens.popD();
double val1 = Double.valueOf(tokens.popN());
double val2 = side * Double.valueOf(tokens.popN());
switch (delim) {
case ADD_DELIM:
val = val1 + val2;
break;
case SUB_DELIM:
val = val1 - val2;
break;
case MUL_DELIM:
val = val1 * val2;
break;
case DIV_DELIM:
try {
val = val1 / val2;
break;
} catch (Exception exception) {
exception.printStackTrace();
break;
}
case EQU_DELIM:
val = val1 - val2;
side = -1;
delim = '-';
}
String outString = "Step %d : %s %c %s = %f";
String printString = String.format(outString, step, val1, delim, val2, val);
step++;
System.out.println(printString);
tokens.pushN(String.valueOf(val));
}
return val;
}
public GeneralST(String str) {
System.out.println("--------------------------------------");
System.out.println("[EXP] : " + str);
setupDelims();
tokenize(str);
result = equate();
System.out.println("--------------------------------------");
}
public void PrintResult() {
System.out.println("Result = " + result);
}
}
class EquateST extends GeneralST {
public EquateST(String str) {
super(str);
}
#Override
protected void setupDelims() {
mathsDelims.add(EQU_DELIM);
super.setupDelims();
}
public void PrintResult() {
if (result == 0) {
System.out.println("Result = True");
} else {
System.out.println("Result = False");
}
}
}
class Main {
public static void main(String[] args) {
String[] equations = {"6 + 2 + -4 * 4 - 5", "6 + 2 - 4 * 4 = -5", "6 + -2 - 4 = 4 - 5"};
calculate(equations);
}
private static void calculate(String... equations)
{
for (String equation : equations) {
if (equation.contains("=")) {
EquateST equateST = new EquateST(equation);
equateST.PrintResult();
} else {
GeneralST generalST = new GeneralST(equation);
generalST.PrintResult();
}
}
}
}
Sample Results
--------------------------------------
[EXP] : 6 + 2 + -4 * 4 - 5
Step 1 : 6.0 + 2.0 = 8.000000
Step 2 : 8.0 + -4.0 = 4.000000
Step 3 : 4.0 * 4.0 = 16.000000
Step 4 : 16.0 - 5.0 = 11.000000
--------------------------------------
Result = 11.0
--------------------------------------
[EXP] : 6 + 2 - 4 * 4 = -5
Step 1 : 6.0 + 2.0 = 8.000000
Step 2 : 8.0 - 4.0 = 4.000000
Step 3 : 4.0 * 4.0 = 16.000000
Step 4 : 16.0 - -5.0 = 21.000000
--------------------------------------
Result = False
--------------------------------------
[EXP] : 6 + -2 - 4 = 4 - 5
Step 1 : 6.0 + -2.0 = 4.000000
Step 2 : 4.0 - 4.0 = 0.000000
Step 3 : 0.0 - 4.0 = -4.000000
Step 4 : -4.0 - -5.0 = 1.000000
--------------------------------------
Result = False
Your problem is "arithmetic evaluation".
It was mentioned in many book "Algorithm".
Best and simple way to solve it : using stack and "postfix notation".
You can find a lot of article with your favorite programming languages.
Related
This code uses Swing and awt to compute prime factorization, the code works, but it shows only one prime factor, for example: if i compute 56 the answer is just 7, how can i fix it?
thanks in advance
calculate6.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Get values from text fields
try {
int a = Integer.parseInt(input1.getText());
result.setText(String.valueOf(a + " "));
for (int i = 2; i <= a; i++) {
while (a % i == 0) {
result.setText(String.valueOf(i + " "));
// System.out.println(i + " ");
a = a / i;
}
}
if (a < 1)
result.setText(String.valueOf(a + " "));
// System.out.println(a + " ");
}
catch (Exception f) {
JOptionPane.showMessageDialog(rootPane, "ERROR: " + (f.getMessage()));
}
String aField = input1.getText();
if (e.getSource() == calculate6) {
if ("".equals(aField)) {
String emptyFieldWarning;
emptyFieldWarning = "One field is empty!";
JOptionPane.showMessageDialog(rootPane, emptyFieldWarning);
}
}
}
});
Edit 1: i have changed the operation part
Your Swing part is fine. If you just try to execute
int a = 56;
for(int i = 2; i< a; i++) {
while (a % i == 0) {
a = a / i;
}
}
System.out.println(a);
you get 7,so the problem is in this part, you shoul look over here
Problem is in the while loop. It is not accumulating the factors. Try this getPrimeFactors() in this sample program.
import java.util.*;
public class PrimeFactors {
public static void main(String[] args) {
System.out.println("56 -> " + PrimeFactors.getPrimeFactors(56));
System.out.println("30 -> " + PrimeFactors.getPrimeFactors(30));
System.out.println("154 -> " + PrimeFactors.getPrimeFactors(154));
}
public static List<Integer> getPrimeFactors(int input) {
List<Integer> factors = new ArrayList<>();
for (int i = 2; i <= input; i++) {
while (input%i == 0) {
input = input/i;
factors.add(i);
}
}
return factors;
}
}
public static final IntFunction<String> getPrimeFactorsAsString = num -> {
List<Integer> res = new ArrayList<>();
for (int i = 2, sqrt = (int)Math.sqrt(num); i <= sqrt; i++) {
while (num % i == 0) {
res.add(i);
num /= i;
}
}
return res.stream().map(String::valueOf).collect(Collectors.joining(" "));
};
Demo
System.out.println(getPrimeFactorsAsString.apply(56)); // 2 2 2 7
System.out.println(getPrimeFactorsAsString.apply(660)); // 2 2 3 5 11
I want launch various method(exercise) with an other method with Scanner.
When the machine asks which exercises, I want to answer with a tapping answer and when I say the exercise(method), the machine launch this method with my tapping answer.
Exemple:
Which exercises?
me - "W34"
(The machine launches the method W34)
You have to use reflection.
Note: For more please write your code in question I will change it accordingly
obj.getClass().getMethod(methodName).invoke.invoke(obj);
Sorry i m not a professional, and sorry for the code it was my first question on this site, i only put in some exercises because there are so many.
Code :
public class Main {
public static String CapitalizeEachWord(String st) {
String result = "";
st = st.replaceAll("() ([A-Z])", "$1 $2");
String[] words = st.split(" ");
for (String word : words)
if (word.length() > 0)
result += Character.toUpperCase(word.charAt(0)) + word.substring(1) + " ";
return result;
}
public static String Scann() {
Scanner in = new Scanner(System.in);
System.out.println("Wich exercises? (W + exNumb)");
int x = in.nextInt();
return null;
}
public static String W1() {
System.out.println("Hello");
System.out.println("Antoine Sidot!");
System.out.println();
return null;
}
public static String W2() {
int result = 74 + 36;
System.out.println(result);
return null;
}
public static String W3() {
System.out.println(50/3);
return null;
}
public static String W4() {
System.out.println(-5 + 8 * 6);
System.out.println((55 + 9) % 9);
System.out.println(20 + -3*5 / 8);
System.out.println(5 + 15 / 3 * 2 -8 % 3);
return null;
}
public static String W5() {
int nb1 = 25;
int nb2 = 5;
System.out.println(nb1 + " x " + nb2 + " = " + nb1*nb2);
return null;
}
}
I plan in JavaFX a new Game 'Number-Shape-System'. Basically its a little memory game where pictures are associated with numbers. So '2'='Swan', '5'='Hand(Fingers)' and so on. So the player see the exercise 'Swan + Fingers = ?'.
What I want is all possible mathematically operations following rules:
/*
* Generate all possible mathematical operations to the console with the numbers
* 0-12, where every result is (>= 0 && <= 12).
* - Mathematical operations are '+', '-', '*' and '/'.
* - The rule 'dot before line' shouldn't be used, instead the operations will
* be executed from left to right.
* - Every among result must be between (>= 0 && <= 12) and a whole number.
* - Only different numbers are allowed for the operations (an operation have
* 2 numbers). For example 2+3 is allowed, 3*3 not.
*
* A solution with recursive methods would be preferred. I want the output for
* the length 2-10.
*
* Example output with different length:
* - Length 3: 2+3(=5)*2(=10)
* - Length 5: 2+3(=5)*2(=10)+2(=12)/4(=3)
*/
I have prepared a example implementation, but I don't know how to convert it to a recursive functionality.
import java.util.ArrayList;
import java.util.List;
public class Generator {
private static final List<Double> numbers = new ArrayList<>();
private static final List<String> operations = new ArrayList<>();
static {
numbers.add(0.0);
numbers.add(1.0);
numbers.add(2.0);
numbers.add(3.0);
numbers.add(4.0);
numbers.add(5.0);
numbers.add(6.0);
numbers.add(7.0);
numbers.add(8.0);
numbers.add(9.0);
numbers.add(10.0);
numbers.add(11.0);
numbers.add(12.0);
operations.add("+");
operations.add("-");
operations.add("*");
operations.add("/");
}
private int lineCounter = 0;
public Generator() {
this.init();
}
private void init() {
}
public void generate() {
// Length 2 ###########################################################
boolean okay = false;
int lineCounter = 0;
StringBuilder sbDouble = new StringBuilder();
for (Double first : numbers) {
for (Double second : numbers) {
for (String operation : operations) {
if (first == second) {
continue;
}
if (operation.equals("/") && (first == 0.0 || second == 0.0)) {
continue;
}
double result = perform(first, operation, second);
okay = this.check(result, operation);
if (okay) {
++lineCounter;
sbDouble = new StringBuilder();
this.computeResultAsString(sbDouble, first, operation, second, result);
System.out.println(sbDouble.toString());
}
}
}
}
System.out.println("Compute with length 2: " + lineCounter + " lines");
// Length 2 ###########################################################
// Length 3 ###########################################################
okay = false;
lineCounter = 0;
sbDouble = new StringBuilder();
for (Double first : numbers) {
for (Double second : numbers) {
for (String operation1 : operations) {
if (first == second) {
continue;
}
if (operation1.equals("/") && (first == 0.0 || second == 0.0)) {
continue;
}
double result1 = perform(first, operation1, second);
okay = this.check(result1, operation1);
if (okay) {
for (Double third : numbers) {
for (String operation2 : operations) {
if (second == third) {
continue;
}
if (operation2.equals("/") && third == 0.0) {
continue;
}
double result2 = perform(result1, operation2, third);
okay = this.check(result2, operation2);
if (okay) {
++lineCounter;
sbDouble = new StringBuilder();
this.computeResultAsString(sbDouble, first, operation1, second, result1);
this.computeResultAsString(sbDouble, operation2, third, result2);
System.out.println(sbDouble.toString());
}
}
}
}
}
}
}
System.out.println("Compute with length 3: " + lineCounter + " lines");
// Length 3 ###########################################################
// Length 4 ###########################################################
okay = false;
lineCounter = 0;
sbDouble = new StringBuilder();
for (Double first : numbers) {
for (Double second : numbers) {
for (String operation1 : operations) {
if (first == second) {
continue;
}
if (operation1.equals("/") && (first == 0.0 || second == 0.0)) {
continue;
}
double result1 = perform(first, operation1, second);
okay = this.check(result1, operation1);
if (okay) {
for (Double third : numbers) {
for (String operation2 : operations) {
if (second == third) {
continue;
}
if (operation2.equals("/") && third == 0.0) {
continue;
}
double result2 = perform(result1, operation2, third);
okay = this.check(result2, operation2);
if (okay) {
for (Double forth : numbers) {
for (String operation3 : operations) {
if (third == forth) {
continue;
}
if (operation3.equals("/") && forth == 0.0) {
continue;
}
double result3 = perform(result2, operation3, forth);
okay = this.check(result3, operation3);
if (okay) {
++lineCounter;
sbDouble = new StringBuilder();
this.computeResultAsString(sbDouble, first, operation1, second, result1);
this.computeResultAsString(sbDouble, operation2, third, result2);
this.computeResultAsString(sbDouble, operation3, forth, result3);
System.out.println(sbDouble.toString());
}
}
}
}
}
}
}
}
}
}
System.out.println("Compute with length 4: " + lineCounter + " lines");
// Length 4 ###########################################################
}
private boolean check(double result, String operation) {
switch (operation) {
case "+":
case "-":
case "*": {
if (result > 0 && result <= 12) {
return true;
}
break;
}
case "/": {
if (
(Math.floor(result) == result)
&& (result >= 0 && result <= 12)
) {
return true;
}
break;
}
}
return false;
}
private double perform(double first, String operation, double second) {
double result = 0.0;
switch (operation) {
case "+": { result = first + second; break; }
case "-": { result = first - second; break; }
case "*": { result = first * second; break; }
case "/": { result = first / second; break; }
}
return result;
}
private void computeResultAsString(StringBuilder sbDouble, String operation, double second, double result) {
sbDouble.append(operation);
sbDouble.append(second);
sbDouble.append("(=");
sbDouble.append(result);
sbDouble.append(")");
}
private void computeResultAsString(StringBuilder sbDouble, double first, String operation, double second, double result) {
sbDouble.append(first);
sbDouble.append(operation);
sbDouble.append(second);
sbDouble.append("(=");
sbDouble.append(result);
sbDouble.append(")");
}
public static void main(String[] args) {
final Generator generator = new Generator();
generator.generate();
}
}
As you can see in your own code, for each increase in "length", you have to nest another block of the same code. With a dynamic length value, you can't do that.
Therefore, you move the block of code into a method, and pass in a parameter of how many more times it has to "nest", i.e. a remainingLength. Then the method can call itself with a decreasing value of remainingLength, until you get to 0.
Here is an example, using an enum for the operator.
public static void generate(int length) {
if (length <= 0)
throw new IllegalArgumentException();
StringBuilder expr = new StringBuilder();
for (int number = 0; number <= 12; number++) {
expr.append(number);
generate(expr, number, length - 1);
expr.setLength(0);
}
}
private static void generate(StringBuilder expr, int exprTotal, int remainingLength) {
if (remainingLength == 0) {
System.out.println(expr);
return;
}
final int exprLength = expr.length();
for (int number = 0; number <= 12; number++) {
if (number != exprTotal) {
for (Operator oper : Operator.values()) {
int total = oper.method.applyAsInt(exprTotal, number);
if (total >= 0 && total <= 12) {
expr.append(oper.symbol).append(number)
.append("(=").append(total).append(")");
generate(expr, total, remainingLength - 1);
expr.setLength(exprLength);
}
}
}
}
}
private enum Operator {
PLUS ('+', Math::addExact),
MINUS ('-', Math::subtractExact),
MULTIPLY('*', Math::multiplyExact),
DIVIDE ('/', Operator::divide);
final char symbol;
final IntBinaryOperator method;
private Operator(char symbol, IntBinaryOperator method) {
this.symbol = symbol;
this.method = method;
}
private static int divide(int left, int right) {
if (right == 0 || left % right != 0)
return -1/*No exact integer value*/;
return left / right;
}
}
Be aware that the number of permutations grow fast:
1: 13
2: 253
3: 5,206
4: 113,298
5: 2,583,682
6: 61,064,003
7: 1,480,508,933
This question already has answers here:
Comparing version number strings (major, minor, revision, beta)
(3 answers)
Closed 7 years ago.
For one of my projects i would like to get a version from a string which has multiple decimals, is it possible to convert it into a multi decimal point double or is it not possible. I would like to use this to see if it is more than the previous one, which would also have multiple decimals.
What I am using at the moment is
if (!vers.equalsIgnoreCase(plugin.getDescription().getVersion())) { // Do stuff
But I would like to make it so I can do
if (vers > plugin.getDescription().getVersion()) { // do stuff
vers is equal to 1.0.1, and the plugin.getDescription().getVersion() is equal to 1.0.2
thanks!
You could implement this way, if you assume all the portions are numbers.
public static int compareVersions(String vers1, String vers2) {
String[] v1 = vers1.split("\\.");
String[] v2 = vers2.split("\\.");
for (int i = 0; i < v1.length && i < v2.length; i++) {
int i1 = Integer.parseInt(v1[i]);
int i2 = Integer.parseInt(v2[i]);
int cmp = Integer.compare(i1, i2);
if (cmp != 0)
return cmp;
}
return Integer.compare(v1.length, v2.length);
}
and
System.out.println(compareVersions("1.0.1", "1.0.2"));
System.out.println(compareVersions("1.0.1", "1.0"));
System.out.println(compareVersions("1.0.2", "1.0.10"));
prints
-1
1
-1
A more complex version supports letters inside versions
public static int compareVersions(String vers1, String vers2) {
String[] v1 = vers1.split("\\.");
String[] v2 = vers2.split("\\.");
for (int i = 0; i < v1.length && i < v2.length; i++) {
String [] w1 = v1[i].split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
String [] w2 = v2[i].split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
for(int j=0;j<w1.length&&j<w2.length;j++) {
try {
int i1 = Integer.parseInt(w1[j]);
int i2 = 0;
try {
i2 = Integer.parseInt(w2[j]);
} catch (NumberFormatException e) {
return -1;
}
int cmp = Integer.compare(i1, i2);
if (cmp != 0)
return cmp;
} catch (NumberFormatException e) {
try {
Integer.parseInt(w2[j]);
return +1;
} catch (NumberFormatException e1) {
int cmp = w1[j].compareTo(w2[j]);
if (cmp != 0)
return cmp;
}
}
}
int cmp = Integer.compare(w1.length, w2.length);
if (cmp != 0)
return cmp;
}
return Integer.compare(v1.length, v2.length);
}
and
System.out.println(compareVersions("1.0.2", "1.0.2a"));
System.out.println(compareVersions("1.0.2b", "1.0.2a"));
System.out.println(compareVersions("1.8.0_66", "1.8.0_65"));
System.out.println(compareVersions("1.7.0_79", "1.8.0_65"));
prints
-1
1
1
-1
It seems that you would like to compare versions. Or to take decisions based on some string represented version. If the plugin.getDescription().getVersion() is a String, then you should be able to use a simple String comparison to establish the order between versions. Something like this should work:
String pluginVersion=plugin.getDescription().getVersion();
if (ensureValidVersion(pluginVersion)
&& compareVersions(vers,pluginVersion)>0) {
// do staff is vers is greater then plugin version
}
ensureValidVersion method will validate if you have a valid version number representation. And compareVersions will do a comparison for each version subcomponent.
Assuming you have a version number of the following form: x.y.z
You can use a similiar approach as suggested by Viacheslav Vedenin:
String versionNumber = "1.3.45";
String[] singleParts = versionNumbers.split(".");
int[] versionParts = new int[singleParts.length];
for(int i=0; i<singleParts.length; i++) {
versionParts[i] = Integer.parseInt(singleParts[i]);
}
Now you have an array of the single parts of your version number. To compare it to a previous one you could do as follow:
public static boolean isGreater(int[] firstVersion, int[] secondVersion) {
if(secondVersion.length > firstVersion.length) {
return false;
}else {
if(firstVersion.length > secondVersion.length) {
return true;
}else {
for(int k=0; k< firstVersion.length; k++) {
int v1 = firstVersion[k];
int v2 = secondVersion[k];
if(v1 < v2) {
return true;
}
}
return false;
}
}
}
If you want to compare versions using the equality/inequality operators (==, <, >, <=, and >=), you have two options.
Use a language like C++ that supports operator overloading
Set a limit on the length for each string in major.minor.build and convert each version to an integer before comparing them. For example, if the limit on each of them is 3 (i.e. the longest version you can have is abc.def.ghi), then you can just use build + minor * 10^3 + major * 10^6.
Alternatively, you can just implement Comparable<Version> and have a nice OOP solution.
public class Example {
static class Version implements Comparable<Version> {
private int major;
private int minor;
private int build;
public Version(String s) {
final String[] split = s.split("\\.");
major = Integer.parseInt(split[0]);
minor = Integer.parseInt(split[1]);
build = Integer.parseInt(split[2]);
}
public int getMajor() {
return major;
}
public int getMinor() {
return minor;
}
public int getBuild() {
return build;
}
#Override
public int compareTo(Version v) {
if (getMajor() < v.getMajor()) {
return -1;
} else if (getMajor() > v.getMajor()) {
return 1;
} else {
if (getMinor() < v.getMinor()) {
return -1;
} else if (getMinor() > v.getMinor()) {
return 1;
} else {
if (getBuild() < v.getBuild()) {
return -1;
} else if (getBuild() > v.getBuild()) {
return 1;
} else {
return 0;
}
}
}
}
}
public static void main(String[] args) {
String s1 = "1.0.1";
String s2 = "1.0.2";
compare(s1, s2);
compare(s1, s1);
compare(s2, s2);
compare(s2, s1);
}
private static void compare(String s1, String s2) {
Version v1 = new Version(s1);
Version v2 = new Version(s2);
final int compareTo = v1.compareTo(v2);
if (compareTo == -1) {
System.out.println(s1 + " was released before " + s2);
} else if (compareTo == 0) {
System.out.println(s1 + " is the same as " + s2);
} else {
System.out.println(s1 + " was released after " + s2);
}
}
}
Output:
1.0.1 was released before 1.0.2
1.0.1 is the same as 1.0.1
1.0.2 is the same as 1.0.2
1.0.2 was released after 1.0.1
String[] numbers = version.split(".");
String[] numbers2 = version2.split(".");
int index = numbers.length-1;
while(numbers[index] != "."){
index--;
}
String lastnumber = version.substring(index+1, numbers.length];
index = numbers2.length-1;
while(numbers2[index] != "."){
index--;
}
String lastnumber2 = version.substring(index+1, numbers2.length];
if(lastnumber > lastnumber2){
//later version
}else{
//use the same thing to check the other numbers
}
I'm working on a method, that takes steps between 3 and -3. My program will not print out the steps in a numerical order, and I can't quite figure out how to do it, and I can't find anything elsewhere.
public static final int SENTINEL = Math.abs(3);
public static void randomWalk(Random rand) {
int walk = 0;
while (walk != SENTINEL) {
walk = (rand.nextInt((3 - (-3)) + 1) - 3);
System.out.println("Position = " + walk);
}
}
If that is what you are looking for :
int walk = 0;
int randomStep = 0;
Random rand = new Random();
while (Math.abs(walk) != 3) {
randomStep = rand.nextInt(2) > 0 ? 1 : -1; // -1 or 1 with 50% probability
walk += randomStep;
System.out.print(walk + " ");
}
//sample output: -1 -2 -1 0 1 2 1 2 3
public static void randomWalk(Random rand) {
int walk = 0;
while (walk != SENTINEL) {
walk += rand.nextInt(3) - 1;
if(walk>3) walk = 3;
if(walk<-3) walk = -3;
System.out.println("Position = " + walk);
}
}
I guess you want this.
while (walk != SENTINEL) {
int walk = 0;
walk = (rand.nextInt((3 - (-3)) + 1) - 3);
System.out.println("Walk is = " + walk);
int temp = walk;
if (walk >= -3) {
System.out.println("Wlak plus = " + (temp + 1));
System.out.println("Wlak minus =" + (temp - 1));
}
}
Could this be what you are looking for?
package com.stackoverflow.random;
import java.util.Random;
public class Walking {
private final int bounds;
public Walking(int bounds) {
this.bounds = bounds;
}
private boolean isWithinBounds(int walk) {
return Math.abs(walk) < bounds;
}
public String randomWalk() {
int walk = 0;
StringBuilder sb = new StringBuilder();
while(isWithinBounds(walk)) {
sb.append(walk);
walk = getNextStep(walk);
}
return sb.toString();
}
private Random random = null;
private int getNextStep(int walk) {
if (random == null)
random = new Random();
boolean increase = random.nextBoolean();
return increase?++walk:--walk;
}
public static void main(String[] args) {
Walking app = new Walking(3);
System.out.println("walking: " + app.randomWalk());
}
}