Separate delimited string values in array into boolean variables - excel

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();
}

Related

Blackjack Card Display Issue

For my App Dev 2 project, we were told to make a basic Blackjack game on Android Studio. The problems revolve around the Stand button. Anytime I press it, the app closes. Another issue is that whenever the button does work, it will replace the dealer's first card with their second card, when I need the second facedown card to be replaced with the second faceup card. I will link everything pertaining to this issue, as the whole program is too large for stackoverflow.
public ImageView dealer_Card1, dealer_Card2, dealer_Card3, dealer_Card4, dealer_Card5;
public ImageView player_Card1, player_Card2, player_Card3, player_Card4, player_Card5;
public void btn_Stand_Click() {
do {
dealer_Call();
calculate_Dealer_Score();
if (dealer_Score > 21) {
for (int i = 0; i < 5; i++) {
if (dealer_Card_Array[i] == 'A' && dealer_Score_Count[i] == 11) {
dealer_Score_Count[i] = 1;
break;
}
}
calculate_Dealer_Score();
}
} while (dealer_Score < 17 && dealer_Score <= player_Score && dealer_Card_Number < 5);
results();
}
public void btn_Stand(View view) {
do {
dealer_Call();
calculate_Dealer_Score();
if (dealer_Score > 21) {
for (int i = 0; i < 5; i++) {
if (dealer_Card_Array[i] == 'A' && dealer_Score_Count[i] == 11) {
dealer_Score_Count[i] = 1;
break;
}
}
calculate_Dealer_Score();
}
} while (dealer_Score < 17 && dealer_Score <= player_Score && dealer_Card_Number < 5);
if (player_Score == 21) {
black_Jack();
} else if (dealer_Score == 21) {
dealer_black_Jack();
} else if (dealer_Score > 21) {
total = total + (bet * 2);
Toast toast = Toast.makeText(getApplicationContext(), "Dealer Bust! You won!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
disable_Buttons();
alert_Box();
} else results();
}
private void card_Image_Switcher() {
dealer_Card1.setImageResource(R.drawable.cardback);
dealer_Card2.setImageResource(R.drawable.cardback);
dealer_Card3.setImageResource(R.drawable.cardback);
dealer_Card4.setImageResource(R.drawable.cardback);
dealer_Card5.setImageResource(R.drawable.cardback);
player_Card1.setImageResource(R.drawable.cardback);
player_Card2.setImageResource(R.drawable.cardback);
player_Card3.setImageResource(R.drawable.cardback);
player_Card4.setImageResource(R.drawable.cardback);
player_Card5.setImageResource(R.drawable.cardback);
}

Why does Rust not see a variable after a loop is read?

I have a function, the abbreviated version of which might look like:
loop {
let mut changed = false;
for p in 0..sys.len() {
k = ...
if k == None { continue; }
// some stuff
for (v, _) in &key.0 {
// some stuff
loop {
if n == 2 {
changed = true;
} else if n % 2 == 0 {
changed = true;
} else if n >= 2 {
changed = true;
} else {
changed = true;
}
}
}
}
if !changed { return; }
}
You can see that flag is accessed in the last if statement. But I get this warning message:
warning: value assigned to `changed` is never read
202 | changed = true;
| ^^^^^^^
|
= note: #[warn(unused_assignments)] on by default
And I get no other warning/error messages. Why is this?
Because you never exit from the inner loop?

What is the markup language specification for umlet?

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;
}
}

Tic-Tac-Toe - Iterative implementation of alpha beta tree search

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;
}

Substring algorithm

Can someone explain to me how to solve the substring problem iteratively?
The problem: given two strings S=S1S2S3…Sn and T=T1T2T3…Tm, with m is less than or equal to n, determine if T is a substring of S.
Here's a list of string searching algorithms
Depending on your needs, a different algorithm may be a better fit, but Boyer-Moore is a popular choice.
A naive algorithm would be to test at each position 0 < i ≤ n-m of S if Si+1Si+2…Si+m=T1T2…Tm. For n=7 and m=5:
i=0: S1S2S3S4S5S6S7
| | | | |
T1T2T3T4T5
i=1: S1S2S3S4S5S6S7
| | | | |
T1T2T3T4T5
i=2: S1S2S3S4S5S6S7
| | | | |
T1T2T3T4T5
The algorithm in pseudo-code:
// we just need to test if n ≤ m
IF n > m:
// for each offset on that T can start to be substring of S
FOR i FROM 0 TO n-m:
// compare every character of T with the corresponding character in S plus the offset
FOR j FROM 1 TO m:
// if characters are equal
IF S[i+j] == T[j]:
// if we’re at the end of T, T is a substring of S
IF j == m:
RETURN true;
ENDIF;
ELSE:
BREAK;
ENDIF;
ENDFOR;
ENDFOR;
ENDIF;
RETURN false;
Not sure what language you're working in, but here's an example in C#. It's a roughly n2 algorithm, but it will get the job done.
bool IsSubstring (string s, string t)
{
for (int i = 0; i <= (s.Length - t.Length); i++)
{
bool found = true;
for (int j = 0; found && j < t.Length; j++)
{
if (s[i + j] != t[j])
found = false;
}
if (found)
return true;
}
return false;
}
if (T == string.Empty) return true;
for (int i = 0; i <= S.Length - T.Length; i++) {
for (int j = 0; j < T.Length; j++) {
if (S[i + j] == T[j]) {
if (j == (T.Length - 1)) return true;
}
else break;
}
}
return false;
It would go something like this:
m==0? return true
cs=0
ct=0
loop
cs>n-m? break
char at cs+ct in S==char at ct in T?
yes:
ct=ct+1
ct==m? return true
no:
ct=0
cs=cs+1
end loop
return false
This may be redundant with the above list of substring algorithms, but I was always amused by KMP (http://en.wikipedia.org/wiki/Knuth–Morris–Pratt_algorithm)
// runs in best case O(n) where no match, worst case O(n2) where strings match
var s = "hippopotumus"
var t = "tum"
for(var i=0;i<s.length;i++)
if(s[i]==t[0])
for(var ii=i,iii=0; iii<t.length && i<s.length; ii++, iii++){
if(s[ii]!=t[iii]) break
else if (iii==t.length-1) console.log("yay found it at index: "+i)
}
Here is my PHP variation that includes a check to make sure the Needle does not exceed the Haystacks length during the search.
<?php
function substring($haystack,$needle) {
if("" == $needle) { return true; }
echo "Haystack:\n$haystack\n";
echo "Needle:\n$needle\n";
for($i=0,$len=strlen($haystack);$i<$len;$i++){
if($needle[0] == $haystack[$i]) {
$found = true;
for($j=0,$slen=strlen($needle);$j<$slen;$j++) {
if($j >= $len) { return false; }
if($needle[$j] != $haystack[$i+$j]) {
$found = false;
continue;
}
}
if($found) {
echo " . . . . . . SUCCESS!!!! startPos: $i\n";
return true;
}
}
}
echo " . . . . . . FAILURE!\n" ;
return false;
}
assert(substring("haystack","hay"));
assert(!substring("ack","hoy"));
assert(substring("hayhayhay","hayhay"));
assert(substring("mucho22","22"));
assert(!substring("str","string"));
?>
Left in some echo's. Remove if they offend you!
Is a O(n*m) algorithm, where n and m are the size of each string.
In C# it would be something similar to:
public static bool IsSubtring(char[] strBigger, char[] strSmall)
{
int startBigger = 0;
while (startBigger <= strBigger.Length - strSmall.Length)
{
int i = startBigger, j = 0;
while (j < strSmall.Length && strSmall[j] == strBigger[i])
{
i++;
j++;
}
if (j == strSmall.Length)
return true;
startBigger++;
}
return false;
}
I know I'm late to the game but here is my version of it (in C#):
bool isSubString(string subString, string supraString)
{
for (int x = 0; x <= supraString.Length; x++)
{
int counter = 0;
if (subString[0] == supraString[x]) //find initial match
{
for (int y = 0; y <= subString.Length; y++)
{
if (subString[y] == supraString[y+x])
{
counter++;
if (counter == subString.Length)
{
return true;
}
}
}
}
}
return false;
}
Though its pretty old post, I am trying to answer it. Kindly correct me if anything is wrong,
package com.amaze.substring;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class CheckSubstring {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter the main string");
String mainStr = br.readLine();
System.out.println("Enter the substring that has to be searched");
String subStr = br.readLine();
char[] mainArr = new char[mainStr.length()];
mainArr = mainStr.toCharArray();
char[] subArr = new char[subStr.length()];
subArr = subStr.toCharArray();
boolean tracing = false;
//System.out.println("Length of substring is "+subArr.length);
int j = 0;
for(int i=0; i<mainStr.length();i++){
if(!tracing){
if(mainArr[i] == subArr[j]){
tracing = true;
j++;
}
} else {
if (mainArr[i] == subArr[j]){
//System.out.println(mainArr[i]);
//System.out.println(subArr[j]);
j++;
System.out.println("Value of j is "+j);
if((j == subArr.length)){
System.out.println("SubString found");
return;
}
} else {
j=0;
tracing = false;
}
}
}
System.out.println("Substring not found");
}
}

Resources