Having issues trying to decipher the principal variation (PV) results.
"The principal variation is a path from the root to a leaf node, in which every node has the same value. This leaf node, whose value determines the minimax value of the root, is called the principal leaf."
The game demo below PV (move,eval) shows this line:
4,0 7,0 6,0 5,0 2,1
How can this be a valid PV since not ALL eval nodes have the same value? The AI never loses, but since the dizzying PV seems bogus, it casts a dark shadow on the AI logic. :( Hopefully, it's just a PV bug!
| | 0 | 1 | 2
---|---|--- ---|---|---
| | 3 | 4 | 5
---|---|--- ---|---|---
| | 6 | 7 | 8
Your move: 8
Thinking Cycles....: 2784300
Boards Generated...: 3956
Principal Variation: 4,0 7,0 6,0 5,0 2,1
Alpha-Beta Cutoffs.: 931
Computer Evaluation: 0
Computer Move......: 4
| | 0 | 1 | 2
---|---|--- ---|---|---
| X | 3 | 4 | 5
---|---|--- ---|---|---
| | O 6 | 7 | 8
Your move: 7
Thinking Cycles....: 410484
Boards Generated...: 575
Principal Variation: 6,0 5,0 2,1
Alpha-Beta Cutoffs.: 63
Computer Evaluation: 0
Computer Move......: 6
| | 0 | 1 | 2
---|---|--- ---|---|---
| X | 3 | 4 | 5
---|---|--- ---|---|---
X | O | O 6 | 7 | 8
Your move: 2
Thinking Cycles....: 42808
Boards Generated...: 45
Principal Variation: 5,0 3,0 1,0 0,0
Alpha-Beta Cutoffs.: 1
Computer Evaluation: 0
Computer Move......: 5
| | O 0 | 1 | 2
---|---|--- ---|---|---
| X | X 3 | 4 | 5
---|---|--- ---|---|---
X | O | O 6 | 7 | 8
Your move: 3
Thinking Cycles....: 6892
Boards Generated...: 4
Principal Variation: 0,0 1,0
Alpha-Beta Cutoffs.: 0
Computer Evaluation: 0
Computer Move......: 0
X | | O 0 | 1 | 2
---|---|--- ---|---|---
O | X | X 3 | 4 | 5
---|---|--- ---|---|---
X | O | O 6 | 7 | 8
Your move: 1
X | O | O 0 | 1 | 2
---|---|--- ---|---|---
O | X | X 3 | 4 | 5
---|---|--- ---|---|---
X | O | O 6 | 7 | 8
A draw! (*_*)
If anyone sees a bug in my code, please let me know. Thanks.
// Tic-Tac-Toe - Iterative implementation of alpha beta tree search.
// Built with Microsoft Visual Studio Professional 2013.
#include "stdafx.h"
#include <windows.h>
#include <intrin.h>
#include <stdint.h>
#define INFINITY 9999
#define NO_MOVE 9
#define NO_EVAL 2
#define X 1
#define O -1
#define Empty 0
struct values
{
int nodeMove;
int nodeEval;
int alpha;
int beta;
int player;
int board[9];
};
struct line
{
int nodeMove;
int nodeEval;
};
struct values moves[9];
int bestMove, bestEval;
int nodesCreated;
int abCutoffs;
int pvDepth, pvBestDepth;
// The principal variation pv[9] is a path from the root to a leaf node, in which every node
// has the same value. This leaf node, whose value determines the minimax value of the root,
// is called the principal leaf.
struct line pv[9] = {
{ NO_MOVE, NO_EVAL }, { NO_MOVE, NO_EVAL }, { NO_MOVE, NO_EVAL },
{ NO_MOVE, NO_EVAL }, { NO_MOVE, NO_EVAL }, { NO_MOVE, NO_EVAL },
{ NO_MOVE, NO_EVAL }, { NO_MOVE, NO_EVAL }, { NO_MOVE, NO_EVAL }
};
struct line bestPV[9] = {
{ NO_MOVE, NO_EVAL }, { NO_MOVE, NO_EVAL }, { NO_MOVE, NO_EVAL },
{ NO_MOVE, NO_EVAL }, { NO_MOVE, NO_EVAL }, { NO_MOVE, NO_EVAL },
{ NO_MOVE, NO_EVAL }, { NO_MOVE, NO_EVAL }, { NO_MOVE, NO_EVAL }
};
int board_eval(int *b)
{
// Rows.
if (b[0] && b[0] == b[1] && b[1] == b[2]) return b[0];
if (b[3] && b[3] == b[4] && b[4] == b[5]) return b[3];
if (b[6] && b[6] == b[7] && b[7] == b[8]) return b[6];
// Cols.
if (b[0] && b[0] == b[3] && b[3] == b[6]) return b[0];
if (b[1] && b[1] == b[4] && b[4] == b[7]) return b[1];
if (b[2] && b[2] == b[5] && b[5] == b[8]) return b[2];
// Center is empty.
if (!b[4]) return 0;
// Diags.
if (b[0] == b[4] && b[4] == b[8]) return b[0];
if (b[2] == b[4] && b[4] == b[6]) return b[2];
return 0;
}
void displayboard(int depth)
{
const char *t = "O X";
printf("\n\t %c | %c | %c\t\t 0 | 1 | 2\n", t[moves[depth].board[0] + 1], t[moves[depth].board[1] + 1], t[moves[depth].board[2] + 1]);
printf("\t---|---|---\t\t---|---|---\n");
printf("\t %c | %c | %c\t\t 3 | 4 | 5\n", t[moves[depth].board[3] + 1], t[moves[depth].board[4] + 1], t[moves[depth].board[5] + 1]);
printf("\t---|---|---\t\t---|---|---\n");
printf("\t %c | %c | %c\t\t 6 | 7 | 8\n\n", t[moves[depth].board[6] + 1], t[moves[depth].board[7] + 1], t[moves[depth].board[8] + 1]);
}
int find_move(int *board_arr, int nodeMove)
{
int i;
// Speedup loop using nodeMove instead of 0.
for (i = nodeMove; i < 9; i++) {
if (board_arr[i] == Empty)
return i;
}
return NO_MOVE;
}
int move_up_tree(int depth)
{
depth--;
if (depth == 0 && (moves[depth + 1].nodeEval > moves[depth].nodeEval))
{
bestMove = moves[depth].nodeMove;
bestEval = moves[depth + 1].nodeEval;
pvBestDepth = pvDepth;
pv[depth] = { bestMove, bestEval };
for (int i = 0; i < pvDepth; ++i)
{
bestPV[i].nodeMove = pv[i].nodeMove;
bestPV[i].nodeEval = pv[i].nodeEval;
pv[i] = { NO_MOVE, NO_EVAL };
}
}
if (moves[depth].player == X)
{
moves[depth].nodeEval = max(moves[depth].nodeEval, moves[depth + 1].nodeEval);
moves[depth].alpha = max(moves[depth].alpha, moves[depth].nodeEval);
}
else
{
moves[depth].nodeEval = min(moves[depth].nodeEval, moves[depth + 1].nodeEval);
moves[depth].beta = min(moves[depth].beta, moves[depth].nodeEval);
}
pv[depth] = { moves[depth].nodeMove, moves[depth].nodeEval };
moves[depth].nodeMove++;
moves[depth].nodeMove = find_move(moves[depth].board, moves[depth].nodeMove);
return depth;
}
int move_down_tree(int depth)
{
int eval;
depth++;
moves[depth] = moves[depth - 1];
nodesCreated++;
if (moves[depth].player == X)
{
moves[depth].board[moves[depth].nodeMove] = X;
moves[depth].player = O;
moves[depth].nodeEval = INFINITY;
}
else
{
moves[depth].board[moves[depth].nodeMove] = O;
moves[depth].player = X;
moves[depth].nodeEval = -INFINITY;
}
eval = board_eval(moves[depth].board);
// Leaf node.
if (eval || find_move(moves[depth].board, 0) == NO_MOVE)
{
moves[depth].nodeEval = eval;
moves[depth].nodeMove = NO_MOVE;
pvDepth = depth;
}
else
{
moves[depth].nodeMove = find_move(moves[depth].board, 0);
}
return depth;
}
void computer_move()
{
int depth = 0;
uint64_t c1, c2;
nodesCreated = 0;
abCutoffs = 0;
bestMove = NO_MOVE;
bestEval = -INFINITY;
moves[0].nodeMove = find_move(moves[0].board, 0);
moves[0].nodeEval = -INFINITY;
moves[0].alpha = -INFINITY;
moves[0].beta = INFINITY;
moves[0].player = X;
if (moves[0].nodeMove != NO_MOVE)
{
c1 = __rdtsc();
while (TRUE)
{
if (moves[depth].nodeMove == NO_MOVE)
{
if (depth == 0) break;
depth = move_up_tree(depth);
}
else if (moves[depth].alpha >= moves[depth].beta)
{
abCutoffs++;
moves[depth].nodeMove = NO_MOVE;
}
else
{
depth = move_down_tree(depth);
}
}
c2 = __rdtsc();
moves[0].board[bestMove] = X;
printf("\n");
printf("Thinking Cycles....: %d\n", c2 - c1);
printf("Boards Generated...: %d\n", nodesCreated);
printf("Principal Variation: ");
for (int i = 0; i < pvBestDepth; ++i) printf("%d,%d ", bestPV[i].nodeMove,bestPV[i].nodeEval);
printf("\n");
printf("Alpha-Beta Cutoffs.: %d\n", abCutoffs);
printf("Computer Evaluation: %d\n", bestEval);
printf("Computer Move......: %d\n", bestMove);
}
}
void init_board()
{
moves[0].board[0] = Empty;
moves[0].board[1] = Empty;
moves[0].board[2] = Empty;
moves[0].board[3] = Empty;
moves[0].board[4] = Empty;
moves[0].board[5] = Empty;
moves[0].board[6] = Empty;
moves[0].board[7] = Empty;
moves[0].board[8] = Empty;
}
void human_move()
{
int move;
char *p, s[100];
printf("Your move: ");
while (fgets(s, sizeof(s), stdin)) {
move = strtol(s, &p, 10);
if (p == s || *p != '\n') {
printf("Your move: ");
}
else break;
}
moves[0].board[move] = O;
}
int main(int argc, char **argv)
{
init_board();
displayboard(0);
while (1)
{
human_move();
computer_move();
displayboard(0);
if (board_eval(moves[0].board))
{
printf("Computer Wins! (-_-)\n");
init_board();
displayboard(0);
}
else if (find_move(moves[0].board, 0) == NO_MOVE)
{
printf("A draw! (*_*)\n");
init_board();
displayboard(0);
}
}
return 0;
}
Related
I have a dataset that lists different activities done in each day in a string array, similar concept asked here. Each activity is delimited and can easily be separated into columns, as I've had no problem doing in Excel.
activites
Work | family | date | gaming | relax | good sleep | shopping
Work | family | date | Nature | Crusin | reading | gaming | relax | good sleep | cooking | laundry
family | date | movies & tv | gaming | sport | relax | medium sleep | cooking
Work | family | date | Photography | gaming | relax | good sleep | medium sleep | cooking
Work | family | date | Nature | reading | gaming | relax | good sleep | cleaning
What I am trying to do is make each activity into a boolean variable which has its own column as such, so it indicates 0 for not having done the activity on that day and 1 for having done the activity. It would look something like this:
Work Family Date Gaming Relax
1 1 0 1 0
1 1 1 0 0
0 0 1 0 1
So, what I ended up doing was using my knowledge of Java to reformat data. I first separated the activities into their own variables, each containing a numerical (binary) value to indicate whether or not that activity had been done that day. I had to treat sleep quality separately, so that part looks a little wonky. Here's the code, which produced the correct output:
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(new FileReader("activities.txt"));
String[] actList = { "Work", "school", "family", "friends", "date", "nature", "crusin", "photography",
"making music/piano", "movies & tv", "reading", "gaming", "sport", "relax", "sleep", "shopping", "cleaning",
"cooking", "laundry" };
int row = 0;
while (scan.hasNextLine()) {
row++;
int col = 0;
int activityNo = 0;
int[] actValue = new int[actList.length];
String pipeDelim = scan.nextLine();
String[] actName = pipeDelim.split(" \\| ");
int sleepTagsUsed = 0;
while (activityNo < actName.length) {
col = 0;
for (String a : actName) {
if (a.contains("sleep")) {
col = 14;
if (a.equalsIgnoreCase("bad sleep") || a.equalsIgnoreCase("bad sleep\t")) {
if (col < actList.length) {
actValue[col] = 0;
if (sleepTagsUsed == 0) {
col++;
}
sleepTagsUsed++;
} else {
break;
}
if (!(activityNo > actName.length)) {
activityNo++;
}
} else if (a.equalsIgnoreCase("medium sleep") || a.equalsIgnoreCase("medium sleep\t")) {
if (col < actList.length) {
actValue[col] = 1;
if (sleepTagsUsed == 0) {
col++;
}
sleepTagsUsed++;
} else {
break;
}
if (!(activityNo > actName.length)) {
activityNo++;
}
} else if (a.equalsIgnoreCase("good sleep") || a.equalsIgnoreCase("good sleep\t")) {
if (col < actList.length) {
actValue[col] = 2;
if (sleepTagsUsed == 0) {
col++;
}
sleepTagsUsed++;
} else {
break;
}
if (!(activityNo > actName.length)) {
activityNo++;
}
} else if (a.equalsIgnoreCase("sleep early") || a.equalsIgnoreCase("sleep early\t")) {
if (col < actList.length) {
actValue[col] = 3;
if (sleepTagsUsed == 0) {
col++;
}
sleepTagsUsed++;
} else {
break;
}
if (!(activityNo > actName.length)) {
activityNo++;
}
} else {
if (col < actList.length) {
actValue[col] = -1;
} else {
break;
}
System.out.println("No sleep logged error");
}
} else {
int j = 0;
for (String i : actList) {
if (a.equalsIgnoreCase(i) || a.equalsIgnoreCase(i + "\t")) {
actValue[col] = 1;
if (activityNo > actName.length) {
break;
} else {
activityNo++;
break;
}
} else {
if (col < actList.length) {
j++;
if (j > col) {
actValue[col] = 0;
col++;
}
} else {
break;
}
}
}
col++;
}
}
}
for (int p : actValue) {
System.out.print(p + "\t");
}
System.out.println();
}
scan.close();
}
Here is the code for the initial character:
public class Player extends Mob {
private InputHandler input;
private int colour = Colours.get(-1, 111, 145, 543);
private int scale = 1;
protected boolean isSwimming = false;
private int tickCount = 0;
public Player(Level level, int x, int y, InputHandler input) {
super(level, "Player", x, y, 1);
this.input = input;
}
public void tick() {
int xa = 0;
int ya = 0;
if (input.up.isPressed()) {
ya--;
}
if (input.down.isPressed()) {
ya++;
}
if (input.left.isPressed()) {
xa--;
}
if (input.right.isPressed()) {
xa++;
}
if (xa != 0 || ya != 0) {
move(xa, ya);
isMoving = true;
} else {
isMoving = false;
}
if (level.getTile(this.x >> 3, this.y >> 3).getId() == 3) {
isSwimming = true;
}
if (isSwimming && level.getTile(this.x >> 3, this.y >> 3).getId() != 3) {
isSwimming = false;
}
tickCount++;
this.scale = 1;
}
public void render(Screen screen) {
int xTile = 0;
int yTile = 28;
int walkingSpeed = 4;
int flipTop = (numSteps >> walkingSpeed) & 1;
int flipBottom = (numSteps >> walkingSpeed) & 1;
if (movingDir == 1) {
xTile += 2;
} else if (movingDir > 1) {
xTile += 4 + ((numSteps >> walkingSpeed) & 1) * 2;
flipTop = (movingDir - 1) % 2;
}
int modifier = 8 * scale;
int xOffset = x - modifier / 2;
int yOffset = y - modifier / 2 - 4;
if (isSwimming) {
int waterColour = 0;
yOffset += 4;
if (tickCount % 60 < 15) {
waterColour = Colours.get(-1, -1, 225, -1);
} else if (15 <= tickCount % 60 && tickCount % 60 < 30) {
yOffset -= 1;
waterColour = Colours.get(-1, 225, 115, -1);
} else if (30 <= tickCount % 60 && tickCount % 60 < 45) {
waterColour = Colours.get(-1, 115, -1, 225);
} else {
waterColour = Colours.get(-1, 225, 115, -1);
}
screen.render(xOffset, yOffset + 3, 0 + 27 * 32, waterColour, 0x00, 1);
screen.render(xOffset + 8, yOffset + 3, 0 + 27 * 32, waterColour, 0x01, 1);
}
// upper body
screen.render(xOffset + (modifier * flipTop), yOffset, xTile + yTile * 32, colour, flipTop, scale);
screen.render(xOffset + modifier - (modifier * flipTop), yOffset, (xTile + 1) + yTile * 32, colour, flipTop,
scale);
if (!isSwimming) {
// lower body
screen.render(xOffset + (modifier * flipBottom), yOffset + modifier, xTile + (yTile + 1) * 32, colour,
flipBottom, scale);
screen.render(xOffset + modifier - (modifier * flipBottom), yOffset + modifier,
(xTile + 1) + (yTile + 1) * 32, colour, flipBottom, scale);
}
}
public boolean hasCollided(int xa, int ya) {
int xMin = 0;
int xMax = 7;
int yMin = 1;
int yMax = 7;
for (int x = xMin; x < xMax; x++) {
if (isSolidTile(xa, ya, x, yMin)) {
return true;
}
}
for (int x = xMin; x < xMax; x++) {
if (isSolidTile(xa, ya, x, yMax)) {
return true;
}
}
for (int y = yMin; y < yMax; y++) {
if (isSolidTile(xa, ya, xMin, y)) {
return true;
}
}
for (int y = yMin; y < yMax; y++) {
if (isSolidTile(xa, ya, xMax, y)) {
return true;
}
}
return false;
}
}
can get another character to load at a given location; however, I cannot figure out an algorithm to have it follow the initial player. In other words the second one will follow these same collision and commands. Any help understanding is appreciated, thank you!
I have a vector Type which contains 100 values: [ 'City', 'Town', 'City', 'City',......, 'Town']
I want to associate/ map each of the string's in this vector with an integer/ double 10 and 20.
My attempt at the same:
int s = 20;
int o = 10;
for (int q = 0; q < 100; q++) {
if (Type[q] == 'City') {
'City' == s;
}
else (Type[q] == 'Town'){
'Town' == o;
}
}
This does not work. I would appreciate any help on the topic.
You can use std::map<std::string, int> (or std::map<std::string, double>) like this:
std::vector<std::string> Type = { "City", "Town", "City", "City", "Town" };
std::map<std::string, int> m;
int s = 20;
int o = 10;
for (size_t q = 0; q < Type.size(); q++) {
if (Type[q] == "City") {
m["City"] = s;
}
else if (Type[q] == "Town") {
m["Town"] = o;
}
}
You'll get a map with two values:
{ "City": 20 }, { "Town": 10 }
If you want to have pairs or type and number you can use vector of pairs or tuples:
std::vector<std::tuple<std::string, int>> tuples(Type.size());
int s = 20;
int o = 10;
for (size_t q = 0; q < Type.size(); q++) {
if (Type[q] == "City") {
tuples[q] = std::make_tuple("City", s);
}
else if (Type[q] == "Town") {
tuples[q] = std::make_tuple("Town", o);
}
}
You'll get a vector with values:
{"City", 20 }, {"Town", 10 }, { "City", 20 }, { "City", 20 }, {"Town", 10 }
I have been looking all over the web site, Internet, and of course SO and can't seem to find a description or specification for the markup language being used in umlet.
In the example sequence diagram for example:
title: sample
_alpha:A~id1_|_beta:B~id2_|_gamma:G~id3_
id1->>id2:id1,id2
id2-/>id1:async Msg.
id3->>>id1:id1,id3
id1.>id3:id1,id3:async return Msg
id1->id1:id1:self
iframe{:interaction frame
id2->id3:id1,id3:async Msg.
iframe}
The ->, -->, etc are fairly obvious, but what the colons do?
Why are underlines needed, etc. Inquiring minds would like to know as this looks like a useful tool for sketching.
Found an annotated script (that doesn't seem valid as of 14.2):
//UML2 style titles are optional.
title:sequence diagram
//the participating objects are separated using the pipe symbol "|". Their names may be underlined using underscores.
_alpha:A_|_beta:B_|_gamma:G_
//The following line describes a (synchonuous) message originating from the first object sent to the second object, while both objects are active.
1->>2:1,2
//This message is asynchronous being sent from the second object to the first object. The messages is named.
2-/>1:async Msg.
//A message from the third object to the first object; both objects are active.
3->>>1:1,3
//A named asynchronous return message in UML2 style (using a stick arrow head).
1.>3:1,3:async return Msg
//This is a self call of the first object.
1->1:1:self
//Interaction frames may be used to show optional or conditional blocks within sequence diagrams.
iframe{:interaction frame
2->3:2,3:async Msg.
iframe}
RE: BNF, there's umlet-elements/src/main/javacc/SequenceAllInOneParser.jj in the source:
options {
static = false;
IGNORE_CASE = false;
JAVA_UNICODE_ESCAPE = true;
JDK_VERSION = "1.6";
// Not yet detected as a valid option by the Eclipse plugin, but works nonetheless. This is essential for GWT compatible generated code.
JAVA_TEMPLATE_TYPE = "modern";
}
PARSER_BEGIN(SequenceAllInOneParser)
package com.baselet.element.facet.specific.sequence_aio.gen;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import com.baselet.control.enums.LineType;
import com.baselet.element.facet.specific.sequence_aio.Lifeline;
import com.baselet.element.facet.specific.sequence_aio.Message.ArrowType;
import com.baselet.element.facet.specific.sequence_aio.SequenceDiagramBuilder;
import com.baselet.element.facet.specific.sequence_aio.SequenceDiagramException;
public class SequenceAllInOneParser {
private static final Logger log = LoggerFactory.getLogger(SequenceAllInOneParser.class);
private boolean autoTick;
/**
* Replaces "\\\\" with "\\" in the output so that any further specified match replace pair can't match the replaced "\\".
* #param matchReplacePairs
* #return the string with the replacements
*/
public static String backslashReplace(String input, String... matchReplacePairs) {
if (matchReplacePairs.length % 2 == 1) {
throw new IllegalArgumentException("matchReplacePairs must have an even number of elements.");
}
String split = "\\\\";
StringBuilder strBuilder = new StringBuilder(input.length());
int firstIndex = 0;
// use the indexOf function instead of a split, because split uses regex and regex is not 100% supported by GWT
int foundIndex = input.indexOf(split, firstIndex);
while (firstIndex < input.length()) {
int lastIndex = foundIndex == -1 ? input.length() : foundIndex;
String tmp = input.substring(firstIndex, lastIndex);
for (int j = 0; j < matchReplacePairs.length - 1; j += 2) {
tmp = tmp.replace(matchReplacePairs[j], matchReplacePairs[j + 1]);
}
strBuilder.append(tmp);
if (foundIndex != -1) {
strBuilder.append('\\');
}
firstIndex = lastIndex + split.length();
foundIndex = input.indexOf(split, firstIndex);
}
return strBuilder.toString();
}
/**
* Small data container to pass all informations.
*/
private class MessageArrowInfo {
boolean fromLeftToRight;
LineType lineType;
ArrowType arrowType;
}
private class InteractionConstraint {
private String lifelineId = null;
private String text = "";
}
private class LifelineInterval {
private String startId;
private String endId;
}
}
PARSER_END(SequenceAllInOneParser)
/* defines input to be ignored */
< * > SKIP:
{
" "
| "\t"
}
< DIAGRAM_DEF_TEXT > SKIP:
{
"\n" : DEFAULT
| "\r\n" : DEFAULT
| "\r" : DEFAULT
}
< DEFAULT > TOKEN:
{
< DIAGRAM_OPTION_OVERRIDE_ID :"overrideIds=" >
| < DIAGRAM_OPTION_AUTO_TICK: "autoTick=" >
| < TRUE: "true" >
| < FALSE: "false" >
| < DIAGRAM_TITLE: "title=" > : DIAGRAM_DEF_TEXT
| < DIAGRAM_DESC: "desc=" > : DIAGRAM_DEF_TEXT
| < LIFELINE_DEFINITIONS: "obj=" > : LIFELINE_DEF
}
< DIAGRAM_DEF_TEXT > TOKEN:
{
< DIAGRAM_DEFINITION_TEXT:
(
~ ["\\","\r","\n"]
| ("\\" ["\\", "n"] )
)+> : DIAGRAM_DEF_TEXT
}
< LIFELINE_DEF > TOKEN :
{
< LL_DEF_NEW_LINE: "\n" | "\r\n" | "\r" > : DEFAULT
| < LIFELINE_DEF_DELIMITER: "|" >
/*| < LIFELINE_TITLE_DELIMITER: "~" > integrated in the title */
| < LIFELINE_ACTOR: "ACTOR" >
| < LIFELINE_ACTIVE: "ACTIVE" >
| < LIFELINE_CREATED_LATER :"CREATED_LATER" >
| < LIFELINE_EXEC_SPEC_FROM_START: "EXECUTION" >
| < LIFELINE_TITLE: /* since | and ~ are special characters which delimit the title they need to be escaped */
(
~["~","\\","\n","\r","|"]
| ("\\" ["\\","~","|","n"])
)+
"~" >
}
< DEFAULT > TOKEN :
{
< TEXT_DELIMITER: ":" > : DIAGRAM_SEQ_TEXT
| < LIST_DELIMITER: "," >
| < OPEN_CURLY_BRACKET: "{" >
| < CLOSE_CURLY_BRACKET: "}" >
| < COMMAND_DELIMITER: ";" >
| < T_DASH: "-" >
| < T_DOT: "." >
| < T_DDOT: ".." >
| < T_EQ: "=" >
| < MESSAGE_ARROW_LEFT_OPEN: "<" >
| < MESSAGE_ARROW_LEFT_FILLED: "<<<" >
| < MESSAGE_ARROW_RIGHT_OPEN: ">" >
| < MESSAGE_ARROW_RIGHT_FILLED: ">>>" >
| < MESSAGE_DURATION_INC: "+" >
| < LOST: "lost" >
| < FOUND: "found" >
| < GATE: "gate" >
| < START_COREGION: "coregionStart=" >
| < END_COREGION: "coregionEnd=" >
| < INVARIANT: "invariant=" >
| < STATE_INVARIANT: "stateInvariant=" >
| < EXEC_SPEC_START: "on=" >
| < EXEC_SPEC_END: "off=" >
| < LL_DESTROY: "destroy=" >
| < REF: "ref=" >
| < CONTINUATION: "continuation=" >
| < TEXT_ON_LIFELINE: "text=" >
| < TICK: "tick=" >
| < COMBINED_FRAGMENT: "combinedFragment=" > : CF_OPERATOR
| < INTERACTION_CONSTRAINT: "constraint=" >
| < UNSIGNED_INT_CONSTANT: ( ["0" - "9"] ) + >
| < DEFAULT_NEW_LINE: "\n" | "\r\n" | "\r" >
}
< LIFELINE_DEF, DEFAULT > TOKEN :
{
< LIFELINE_ID: ["a"-"z","A"-"Z"] (["a"-"z","A"-"Z","0"-"9"])* >
}
< DIAGRAM_SEQ_TEXT > TOKEN :
{
< TEXT_UNTIL_NEXT_COMMAND : ( /* since ; is special characters which delimit the text it must be escaped */
~["\\","\n","\r",";"]
| ("\\" ["\\",";","n"])
)+ > : DEFAULT
}
< CF_OPERATOR > TOKEN :
{
< COMBINED_FRAGMENT_OPERATOR: /* since ; and ~ are special characters which delimit the operator they need to be escaped */
(
~["~","\\","\n","\r",";"]
| ("\\" ["\\","~","|","n",";"])
)+
"~" > : DEFAULT
}
/* general Tokens */
/* skip comments */
< * > SKIP :
{
<"//"(~["\n","\r"])*>
}
< * > TOKEN :
{
<LAST_LINE_COMMENT: "//"(~["\n","\r"])*>
}
/**
* The main function which parses the whole diagram.
* Line comments are skipped (see Tokens)
*/
SequenceDiagramBuilder start() :
{
String titleText = "";
String descText = "";
SequenceDiagramBuilder diagram = new SequenceDiagramBuilder();
autoTick = true;
}
{
(
(
titleText=DiagramTitle() /* NL skip and change state to DEFAULT */
| descText = DiagramDescription() /* NL skip and change state to DEFAULT */
| Option(diagram) < DEFAULT_NEW_LINE >
| LifelineDefinitions(diagram) /* NL part of the nonterminal */
)+//diagram definition as new NT followed by NL alternating with sequence so that the sequence= can be removed
Sequence(diagram)
)
(< LAST_LINE_COMMENT >)?
<EOF>
{
diagram.setTitle(titleText);
diagram.setText(descText);
return diagram;
}
}
String DiagramTitle() :
{
String text = "";
}
{
< DIAGRAM_TITLE >
(
< DIAGRAM_DEFINITION_TEXT > { text = backslashReplace(token.image, "\\n","\n");}
)?
{return text;}
}
String DiagramDescription() :
{
String desc = "";
}
{
< DIAGRAM_DESC >
< DIAGRAM_DEFINITION_TEXT > { desc = backslashReplace(token.image, "\\n","\n");}
{return desc;}
}
/**
* Options for the whole diagram
*/
void Option(SequenceDiagramBuilder diagram) :
{
boolean overrideIds;
}
{
< DIAGRAM_OPTION_OVERRIDE_ID > overrideIds = booleanConstant()
{
diagram.setOverrideDefaultIds(overrideIds);
}
| < DIAGRAM_OPTION_AUTO_TICK > autoTick = booleanConstant()
}
/**
* Defines all Lifelines
*/
void LifelineDefinitions(SequenceDiagramBuilder diagram) :
{}
{
< LIFELINE_DEFINITIONS > LifelineDef(diagram) (< LIFELINE_DEF_DELIMITER > LifelineDef(diagram))* < LL_DEF_NEW_LINE >
}
/**
* Defines one Lifeline, the id can't be LIFELINE_ACTOR, LIFELINE_ACTIVE
* or LIFELINE_CREATED_LATER because these are keywords.
*/
void LifelineDef(SequenceDiagramBuilder diagram) :
{
String name = "";
String id = null;
boolean createdOnStart = true;
Lifeline.LifelineHeadType headType = Lifeline.LifelineHeadType.STANDARD;
boolean execSpecFromStart = false;
}
{
name = LifelineDefTitleText() (id=LifelineId())?
(
< LIFELINE_ACTOR > { headType = Lifeline.LifelineHeadType.ACTOR; }
| < LIFELINE_ACTIVE > { headType = Lifeline.LifelineHeadType.ACTIVE_CLASS; }
| < LIFELINE_CREATED_LATER > { createdOnStart = false; }
| < LIFELINE_EXEC_SPEC_FROM_START > { execSpecFromStart = true; }
) *
{
if("lost".equals(id) || "found".equals(id)) {
throw new SequenceDiagramException("'lost' and 'found' are keywords and can not be used as lifeline identifiers.");
}
diagram.addLiveline(name, id, headType, createdOnStart, execSpecFromStart);
}
}
/** can could be multiple lines */
String LifelineDefTitleText() :
{}
{
< LIFELINE_TITLE >
{
/* remove trailing ~ and handle the escaping of \, |, n and ~ */
return backslashReplace(token.image.substring(0, token.image.length() - 1), "\\n", "\n", "\\~", "~", "\\|", "|");
}
}
/**
* Can't be one of the following, because these are keywords in the lifeline definition!
* < LIFELINE_ACTOR: "ACTOR" >
* < LIFELINE_ACTIVE: "ACTIVE" >
* < LIFELINE_CREATED_LATER :"CREATED_LATER" >
*/
String LifelineId() :
{}
{
< LIFELINE_ID >
{
return token.image;
}
}
void Sequence(SequenceDiagramBuilder diagram) :
{}
{
(
SequenceTick(diagram) < DEFAULT_NEW_LINE >
| (
SequenceElement(diagram)
( LOOKAHEAD(2) < COMMAND_DELIMITER > SequenceElement(diagram))*
(< COMMAND_DELIMITER >)?
< DEFAULT_NEW_LINE >
{ if(autoTick) { diagram.tick(); } }
)
| < DEFAULT_NEW_LINE >
)*
}
void SequenceTick(SequenceDiagramBuilder diagram) :
{
int tickCount = 1;
}
{
< TICK > (tickCount = unsignedIntConstant())?
{ diagram.tick(tickCount); }
}
void SequenceElement(SequenceDiagramBuilder diagram) :
{}
{
(
MessageOrGeneralOrderingOrText(diagram) /* Message, GeneralOrdering have a common prefix for more clarity a new nonterminal was created*/
| Coregion(diagram)
| DestroyLL(diagram)
| ExecutionSpecification(diagram)
| StateInvariant(diagram)
//| (diagram) //general ordering, TimeConstraint TimeObservation and DurationConstraint Duration Observation missing
| InteractionUse(diagram)
| Continuation(diagram)
| CombinedFragment(diagram)
)
}
void MessageOrGeneralOrderingOrText(SequenceDiagramBuilder diagram) :
{}
{
/*
* (Message and GeneralOrdering) A common prefix is: <LIFELINE_ID> "." <LIFELINE_ID> "<"
* All three have <LIFELINE_ID > as common prefix
* therefore use LOOKAHEAD(2) if it is a text, if not use a LOOKAHEAD(5) to determine if it is a message or a general ordering
*/
LOOKAHEAD(2) TextOnLifeline(diagram)
| LOOKAHEAD(5) Message(diagram)
| GeneralOrdering(diagram)
}
void CombinedFragment(SequenceDiagramBuilder diagram) :
{
LifelineInterval interval = new LifelineInterval();
String operator = "";
String id = null;
}
{
(
< COMBINED_FRAGMENT >
(
< COMBINED_FRAGMENT_OPERATOR >
{ operator = backslashReplace(token.image.substring(0, token.image.length() - 1), "\\n", "\n", "\\;", ";", "\\~", "~"); }
)
[
id = LifelineId()
[interval = LifelineInterval()]
]
{ diagram.beginCombinedFragment(interval.startId, interval.endId, id, operator); }
)
| (
< T_DASH > < T_DASH > (< T_EQ > id=LifelineId())?
{ diagram.endCombinedFragment(id); }
)
| (
< T_DDOT > (< T_EQ > id=LifelineId())?
{ diagram.endAndBeginOperand(id); }
)
}
void Message(SequenceDiagramBuilder diagram) :
{
String leftLifelineId = null;
String rightLifelineId = null;
String leftLifelineLocalId = null;
String rightLifelineLocalId = null;
MessageArrowInfo messageArrowInfo;
String msgText = "";
int lostCount = 0;
int foundCount = 0;
int gateCount = 0;
int duration = 0;
}
{
(
(
leftLifelineId = LifelineId() [LOOKAHEAD(2)< T_DOT > leftLifelineLocalId = LifelineId()]
| < LOST > { leftLifelineId = "lost"; lostCount++; }
| < FOUND > { leftLifelineId = "found"; foundCount++; }
| < GATE > { leftLifelineId = "gate"; gateCount++; }
)
messageArrowInfo = MessageArrow()
(
rightLifelineId = LifelineId() [< T_DOT > rightLifelineLocalId = LifelineId()]
| < LOST > { rightLifelineId = "lost"; lostCount++; }
| < FOUND > { rightLifelineId = "found"; foundCount++; }
| < GATE > { rightLifelineId = "gate"; gateCount++; }
)
(duration = MessageDuration())?
(msgText = TextUntilNewLine())?
)
{
if(lostCount + foundCount + gateCount > 1) {
throw new SequenceDiagramException("Error: 'lost', 'found' and 'gate' can only occur once per message.");
}
String send;
String receive;
String sendLocalId;
String receiveLocalId;
if(messageArrowInfo.fromLeftToRight) {
send = leftLifelineId;
receive = rightLifelineId;
sendLocalId = leftLifelineLocalId;
receiveLocalId = rightLifelineLocalId;
}
else {
send = rightLifelineId;
receive = leftLifelineId;
sendLocalId = rightLifelineLocalId;
receiveLocalId = leftLifelineLocalId;
}
if(gateCount > 0) {
if(duration != 0) {
throw new SequenceDiagramException("Error: a messages with a gate can only have a duration of 0, but the duration was " + duration + ".");
}
if(send.equals("gate")) {
diagram.addSendGateMessage(receive, msgText, messageArrowInfo.lineType, messageArrowInfo.arrowType, receiveLocalId);
}
else {
diagram.addReceiveGateMessage(send, msgText, messageArrowInfo.lineType, messageArrowInfo.arrowType, sendLocalId);
}
}
else if(send.equals("lost")) {
throw new SequenceDiagramException("Error: 'lost' can only be on the receiving end of a message.");
}
else if(send.equals("found")) {
if(duration != 0) {
throw new SequenceDiagramException("Error: 'lost' and 'found' messages can only have a duration of 0, but the duration was " + duration + ".");
}
diagram.addFoundMessage(receive, msgText, messageArrowInfo.lineType, messageArrowInfo.arrowType, receiveLocalId);
}
else
{
if(receive.equals("lost")) {
if(duration != 0) {
throw new SequenceDiagramException("Error: 'lost' and 'found' messages can only have a duration of 0, but the duration was " + duration + ".");
}
diagram.addLostMessage(send, msgText, messageArrowInfo.lineType, messageArrowInfo.arrowType, sendLocalId);
}
else if(receive.equals("found")) {
throw new SequenceDiagramException("Error: 'found' can only be on the sending end of a message.");
}
else {
diagram.addMessage(send, receive, duration, msgText, messageArrowInfo.lineType, messageArrowInfo.arrowType, sendLocalId, receiveLocalId);
}
}
}
}
MessageArrowInfo MessageArrow():
{
MessageArrowInfo messageArrowInfo = new MessageArrowInfo();
}
{
(
(
messageArrowInfo.lineType = MessageArrowLineType()
(
< MESSAGE_ARROW_RIGHT_OPEN > { messageArrowInfo.arrowType = ArrowType.OPEN; }
| < MESSAGE_ARROW_RIGHT_FILLED > { messageArrowInfo.arrowType = ArrowType.FILLED; }
)
)
{
messageArrowInfo.fromLeftToRight = true;
}
| (
(
< MESSAGE_ARROW_LEFT_OPEN > { messageArrowInfo.arrowType = ArrowType.OPEN; }
| < MESSAGE_ARROW_LEFT_FILLED > { messageArrowInfo.arrowType = ArrowType.FILLED; }
)
messageArrowInfo.lineType = MessageArrowLineType()
)
{
messageArrowInfo.fromLeftToRight = false;
}
)
{ return messageArrowInfo; }
}
LineType MessageArrowLineType() :
{
LineType lineType;
}
{
(
< T_DASH > { lineType = LineType.SOLID; }
| < T_DOT > { lineType = LineType.DASHED; }
)
{
return lineType;
}
}
int MessageDuration() :
{
int duration;
}
{
(
(
< MESSAGE_DURATION_INC > { duration = 1; }
(
duration = unsignedIntConstant()
| (< MESSAGE_DURATION_INC > { duration++; })*
)
)
| (
< T_DASH > { duration = -1; }
(
duration = unsignedIntConstant() { duration = -duration; }
| (< T_DASH > { duration--; })*
)
)
)
{
return duration;
}
}
void GeneralOrdering(SequenceDiagramBuilder diagram):
{
String leftLifelineId = null;
String rightLifelineId = null;
String leftLifelineLocalId = null;
String rightLifelineLocalId = null;
boolean leftEarlier;
}
{
leftLifelineId = LifelineId()
< T_DOT >
leftLifelineLocalId = LifelineId()
(
< MESSAGE_ARROW_RIGHT_OPEN > { leftEarlier = true; }
| < MESSAGE_ARROW_LEFT_OPEN > { leftEarlier = false; }
)
rightLifelineId = LifelineId()
< T_DOT >
rightLifelineLocalId = LifelineId()
{
if(leftEarlier) {
diagram.addGeneralOrdering(leftLifelineId, leftLifelineLocalId, rightLifelineId, rightLifelineLocalId);
}
else {
diagram.addGeneralOrdering(rightLifelineId, rightLifelineLocalId, leftLifelineId, leftLifelineLocalId);
}
}
}
void Coregion(SequenceDiagramBuilder diagram) :
{
String lifelineId;
boolean start;
}
{
(
< START_COREGION > { start = true; }
| < END_COREGION > { start = false; }
)
lifelineId = LifelineId()
{
diagram.addCoregion(lifelineId, start);
}
}
void DestroyLL(SequenceDiagramBuilder diagram) :
{
String lifelineId;
}
{
< LL_DESTROY >
lifelineId = LifelineId()
{
diagram.destroyLifeline(lifelineId);
}
}
void ExecutionSpecification(SequenceDiagramBuilder diagram) :
{
String lifelineId;
boolean on;
}
{
(
< EXEC_SPEC_START > { on = true; }
| < EXEC_SPEC_END > { on = false; }
)
lifelineId = LifelineId()
{
diagram.changeExecutionSpecification(lifelineId, on);
}
( (< LIST_DELIMITER >)? lifelineId = LifelineId()
{
diagram.changeExecutionSpecification(lifelineId, on);
}
)*
}
void StateInvariant(SequenceDiagramBuilder diagram) :
{
String lifelineId;
String text = "";
boolean stateStyle;
}
{
(
< INVARIANT > { stateStyle = false; }
| < STATE_INVARIANT > { stateStyle = true; }
)
lifelineId = LifelineId()
(text = TextUntilNewLine())?
{
diagram.addStateInvariant(lifelineId, text, stateStyle);
}
}
void TextOnLifeline(SequenceDiagramBuilder diagram) :
{
String lifelineId;
String text = "";
}
{
[< TEXT_ON_LIFELINE >]
lifelineId = LifelineId()
text = TextUntilNewLine() /* text is mandatory, if not lookahead with message and general ordering would not work*/
{
diagram.addTextOnLifeline(lifelineId, text);
}
}
String TextUntilNewLine() :
{
}
{
< TEXT_DELIMITER >
< TEXT_UNTIL_NEXT_COMMAND >
{
return backslashReplace(token.image, "\\n", "\n", "\\;", ";");
}
}
void InteractionUse(SequenceDiagramBuilder diagram):
{
LifelineInterval interval;
String text = "";
}
{
(
< REF >
interval = LifelineInterval()
(text = TextUntilNewLine())?
)
{
diagram.addInteractionUse(interval.startId, interval.endId, text);
}
}
void Continuation(SequenceDiagramBuilder diagram):
{
LifelineInterval interval;
String text = "";
}
{
(
< CONTINUATION >
interval = LifelineInterval()
(text = TextUntilNewLine())?
)
{
diagram.addContinuation(interval.startId, interval.endId, text);
}
}
/**
* #return the start and end of the interval.
*/
LifelineInterval LifelineInterval():
{
LifelineInterval interval = new LifelineInterval();
}
{
interval.startId = LifelineId()
(< LIST_DELIMITER >)?
interval.endId = LifelineId()
{
return interval;
}
}
boolean booleanConstant() :
{ boolean value;}
{
(
<FALSE> { value = false;}
| <TRUE> { value = true;}
) {return value; }
}
int unsignedIntConstant() :
{}
{
<UNSIGNED_INT_CONSTANT> {
int value;
try {
value = Integer.parseInt(token.image);
} catch(NumberFormatException e) {
// only digits are accepted by the gramer, so the only reason for a NumberFormatException should be that the number is too big for int
throw (ParseException) new ParseException("Error: The string '" + token.image + "' couldn't be parsed as integer. The most probable reason is that the number is too big.").initCause(e);
}
return value;
}
}
I have to make a code that sums and subtracts two or more numbers using the + and - chars
I managed to make the sum, but I have no idea on how to make it subtract.
Here is the code (I'm allowed to use the for and while loops only):
int CM = 0, CR = 0, A = 0, PS = 0, PR = 0, LC = 0, D;
char Q, Q1;
String f, S1;
f = caja1.getText();
LC = f.length();
for (int i = 0; i < LC; i++) {
Q = f.charAt(i);
if (Q == '+') {
CM = CM + 1;
} else if (Q == '-') {
CR = CR + 1;
}
}
while (CM > 0 || CM > 0) {
LC = f.length();
for (int i = 0; i < LC; i++) {
Q = f.charAt(i);
if (Q == '+') {
PS = i;
break;
} else {
if (Q == '-') {
PR = i;
break;
}
}
}
S1 = f.substring(0, PS);
D = Integer.parseInt(S1);
A = A + D;
f = f.substring(PS + 1);
CM = CM - 1;
}
D = Integer.parseInt(f);
A = A + D;
salida.setText("resultado" + " " + A + " " + CR + " " + PR + " " + PS);
The following program will solve your problem of performing addition and subtraction in a given equation in String
This sample program is given in java
public class StringAddSub {
public static void main(String[] args) {
//String equation = "100+500-20-80+600+100-50+50";
//String equation = "100";
//String equation = "500-900";
String equation = "800+400";
/** The number fetched from equation on iteration*/
String b = "";
/** The result */
String result = "";
/** Arithmetic operation to be performed */
String previousOperation = "+";
for (int i = 0; i < equation.length(); i++) {
if (equation.charAt(i) == '+') {
result = performOperation(result, b, previousOperation);
previousOperation = "+";
b = "";
} else if (equation.charAt(i) == '-') {
result = performOperation(result, b, previousOperation);
previousOperation = "-";
b = "";
} else {
b = b + equation.charAt(i);
}
}
result = performOperation(result, b, previousOperation);
System.out.println("Print Result : " + result);
}
public static String performOperation(String a, String b, String operation) {
int a1 = 0, b1 = 0, res = 0;
if (a != null && !a.equals("")) {
a1 = Integer.parseInt(a);
}
if (b != null && !b.equals("")) {
b1 = Integer.parseInt(b);
}
if (operation.equals("+")) {
res = a1 + b1;
}
if (operation.equals("-")) {
res = a1 - b1;
}
return String.valueOf(res);
}
}