bool checkBrackets(char * text) { Stack<char> st; int size = strlen(text); for (int i = 0; i < size; i++) if (text[i] == '(' || text[i] == '{' || text[i] == '[' || text[i] == '<') st.Push(text[i]); else if (text[i] == ')' || text[i] == '}' || text[i] == ']' || text[i] == '>') { if (st.IsEmpty()) return false; if (((char)st.Peek() == '(' && text[i] == ')') || ((char)st.Peek() == '{' && text[i] == '}') || ((char)st.Peek() == '[' && text[i] == ']') || ((char)st.Peek() == '<' && text[i] == '>')) { st.Pop(); } else return false; } if (st.IsEmpty()) return true; else return false; }
void ToPostFix(char *indata, char *postfix) { int len = strlen(indata); // now transform the infix into postfix Stack<char> pst; int i = 0; int j = 0; for(i = 0; i < len; i++) { cout << "Token " << indata[i] << endl; if(indata[i] >= '0' && indata[i] <= '9') postfix[j++] = indata[i]; else { switch(indata[i]) { case '+': case '-': while(pst.Top()!='(' && !(pst.IsEmpty())) { postfix[j++] = pst.Top(); pst.Pop(); } pst.Push(indata[i]); break; case '*': case '/': while(pst.Top()!='(' && pst.Top()!='+' && pst.Top()!='-' && !(pst.IsEmpty())) { postfix[j++] = pst.Top(); pst.Pop(); } pst.Push(indata[i]); break; case '(': pst.Push(indata[i]); break; case ')': while(pst.Top()!='(' && !(pst.IsEmpty())) { postfix[j++] = pst.Top(); pst.Pop(); } pst.Pop(); break; } } pst.Show(); } while(!(pst.IsEmpty())) { postfix[j++] = pst.Top(); pst.Pop(); } postfix[j] = 0; }
ExpType Postfix::Count(const string& poststring, map<char, ExpType> values) { if (poststring == "") throw exception("String is empty"); Stack<ExpType> result; char tmp; ExpType leftOperand; ExpType rightOperand; for (int i = 0; i < poststring.length(); i++) { tmp = poststring[i]; if (poststring[poststring.length() - 1] == '=') values[poststring[0]] = 0; if (((tmp >= 'a') && (tmp <= 'z')) || ((tmp >= 'A') && (tmp <= 'Z'))) { if (!values.count(tmp)) { cout << "Enter " << tmp << ": "; cin >> values[tmp]; } result.Push(values[tmp]); continue; } if (result.IsEmpty()) throw exception("There is no result"); rightOperand = result.Pop(); if ((result.IsEmpty()) && (tmp == '-')) { result.Push(-rightOperand); continue; } if (result.IsEmpty()) throw exception("There is no result"); leftOperand = result.Pop(); switch (tmp) { case '+': result.Push(leftOperand + rightOperand); break; case '-': result.Push(leftOperand - rightOperand); break; case '*': result.Push(leftOperand * rightOperand); break; case '/': if (rightOperand == 0) throw exception("You can't divide by 0"); result.Push(leftOperand / rightOperand); break; } }
int main(int argc, char *argv[]) { //Error if there are not at least two commandline arguments if(argc < 2) output_usage_and_exit(argv[0]); //Open specified file, quit if cannot open std::ifstream in(argv[1]); if(!in){ std::cerr << "Couldn't open " << argv[1] << std::endl; exit (2); } //convert the infix expressions to postfix string infix; Stack<string> postfix; while(in>>infix){ //substrings out the infix expression minus the line return and //semi-colon. string temp = infix.substr(0,infix.length()-2); //splits the infix expression on spaces for easier processing. Stores in //it in vector. std::vector<string> vec = temp.split(' '); //function for converting infix expressions to postfix format. string result = infix2postfix(vec); //places the resulting string from the the conversion on the stack. postfix.push(result); } //done using the input file in.close(); //handles if an output file was specified on commandline if(argc==3){ std::ofstream out(argv[2]); if(!out){ std::cerr << "Couldn't open " << argv[2] <<std::endl; } while(!postfix.IsEmpty()){ out<< postfix.pop() << std::endl;} }else{ while(!postfix.IsEmpty()){ std::cout << postfix.pop() << std::endl;} } //successful return 0; }
static int GFG_LongestSubstringParen( char* string, int length ) { Stack<int> subStringIndices; int result = 0; subStringIndices.Enqueue(-1); for(int i = 0; i < length; i++) { if( string[i] == '(' ) { subStringIndices.Enqueue(i); } else if( string[i] == ')' ) { delete subStringIndices.Dequeue(); if( !subStringIndices.IsEmpty() ) { int newLength = i - subStringIndices.Peek()->data; if( result < newLength) result = newLength; } else { subStringIndices.Enqueue(i); } } } return result; }
void main(void) { Stack<int> stack; stack.PushBack(1); stack.PushBack(2); stack.PushBack(3); stack.PushBack(4); stack.PushBack(5); cout << "Stack size : " << stack.Size() << endl; cout << "Top element : " << stack.Top() << endl; stack.PopBack(); stack.PopBack(); cout << "Stack size : " << stack.Size() << endl; stack.Show(); stack.Clear(); if ( stack.IsEmpty() ) { cout << "Stack is empty" << endl; } else { cout << "Stack is not empty" << endl; } system("@pause"); }
TEST(Corrector, can_pass_correct_word) { Lexema *word = new Lexema[6]; word[0] = Lexema(Type_Lexems::open_bracet, "(", 0); word[1] = Lexema(Type_Lexems::digit, "1", 1); word[2] = Lexema(Type_Lexems::add, "+", 2); word[3] = Lexema(Type_Lexems::digit, "2", 3); word[4] = Lexema(Type_Lexems::close_bracket, ")", 4); word[5] = Lexema(Type_Lexems::terminal, "", 5); Corrector c; Stack<Error>* errors; Error res; errors = c.CheckExpression(word); if (errors->IsEmpty()) { res = Error(-2, "Ура, ошибок нет!"); } else { res = errors->Put(); } EXPECT_EQ(-2, res.GetPosition()); EXPECT_EQ("Ура, ошибок нет!", res.GetText()); }
// ------ Main (Driver) ------ int main(void) { ItemType Item1 = {'A', 4.1}; ItemType Item2 = {'B', 3.1}; ItemType Item3 = {'C', 2.1}; ItemType Item4 = {'D', 1.0}; ItemType tmpItem; Stack dStack; std::cout << " Stack created" << std::endl; std::cout << " Stack is " << (dStack.IsEmpty() ? "" : "Not ") << "Empty" << std::endl; std::cout << " Adding Items to Stack " << std::endl; dStack.Push(Item1); dStack.Push(Item2); dStack.Push(Item3); dStack.Push(Item4); std::cout << " Stack is " << (dStack.IsEmpty() ? "" : "Not ") << "Empty" << std::endl; std::cout << " Top of the Stack is : " ; tmpItem = dStack.Top(); std::cout << " Key = " <<tmpItem.key << " Data = " <<tmpItem.data << std::endl; std::cout << " Stack contains the following Items:" << std::endl; int iloop = 0; while (!dStack.IsEmpty()) { iloop++; std::cout << " Item " << iloop << " : " ; tmpItem = dStack.Pop(); std::cout << " Key = " <<tmpItem.key << " Data = " <<tmpItem.data << std::endl; } return 0; }
void trans(char* infix,Stack<T> &stck) { stck.Push('#'); for(int i=0;i<strlen(infix);i++) { if(infix[i]>='0'&&infix[i]<='9') cout<<infix[i]; else if(infix[i]==')') { for(;stck.Top()!='(';stck.Pop()) cout<<stck.Top(); stck.Pop(); } else { if(infix[i]!='(') for(;OpPriority(stck.Top())>=OpPriority(infix[i]);stck.Pop()) cout<<stck.Top(); stck.Push(infix[i]); } } for(;!stck.IsEmpty();stck.Pop()) if(stck.Top()!='#') cout<<stck.Top(); cout<<endl; // if(isdigit(infix)) // cout<<infix; // else if(IsOperator(infix)) // { // if(stck.IsEmpty()) // stck.Push(infix); // else // { // char temp=stck.Top(); // if(OpPriority(temp)>=OpPriority(infix)) // { // if(stck.Top()==')') // { // while(stck.Top()!='(') // { // cout<<stck.Top(); // stck.Pop(); // } // } // else // { // while(!stck.IsEmpty()) // { // cout<<stck.Top(); // stck.Pop(); // } // stck.Push(infix); // } // } // else // stck.Push(infix); // } // } }
int printstack(Stack &stack) { // Prints the stack if ( stack.IsEmpty() ) { cout << "Stack is empty" << endl; } else { cout << "Stack contents: " << stack.PrintStack() << endl; } }
static bool GFG_IsBST_GivenPreOrderTraversal( int* array, int n ) { Stack<int> parents; int prevMin; bool prevMinInitialised = false; //Continue pushing parents onto the stack until we discover a right subtree //If a right subtree is discovered, pop all the left nodes off the stack onto the array until the stack is empty or we find a parent of the right subtree for(int i = 0; i < n; i++) { if( parents.IsEmpty() || parents.Peek()->data > array[i] ) { parents.Enqueue(array[i]); } else //right subtree discovered { while( !parents.IsEmpty() && parents.Peek()->data < array[i] ) { int Value = parents.Dequeue()->data; //Test to see that the resulting array is sorted if( prevMinInitialised && prevMin > Value ) { return false; } prevMinInitialised = true; prevMin = Value; } parents.Enqueue(array[i]); } } //Put all of the remaining parents into our array while( !parents.IsEmpty() ) { int Value = parents.Dequeue()->data; //Test to see that the resulting array is sorted if( prevMinInitialised && prevMin > Value ) { return false; } prevMinInitialised = true; prevMin = Value; } return true; }
int square(Stack &stack) { // Checks if the stack has enough values. if ( stack.IsEmpty() ) { cout << "Not enough values in the stack!" << endl; return 1; } double temp = stack.Pop(); double out = temp * temp; stack.Push( out ); }
int duplicate(Stack &stack) { // Checks if the stack has enough values. if ( stack.IsEmpty() ) { cout << "Not enough values in the stack!" << endl; return 1; } double temp = stack.Pop(); stack.Push( temp ); stack.Push( temp ); }
bool StackPushTests() { Test t("Stack Pushing tests"); Stack s; for (int i=0;i<10000; i++) { s.Push(i); t.VerifyTrue(s.Top()==i,"Top should be i"); t.VerifyTrue(s.GetSize()==i+1,"Size should be i+1"); t.VerifyTrue(s.Peek()==i-1,"Peeked value should be i-1"); t.VerifyTrue(s.IsEmpty()==false,"Stack should not be empty"); } return t.isPassed(); }
int main() { Stack<int> stack; std::cout << "Stack created." << std::endl; if(stack.IsEmpty()) std::cout << "Stack is empty." << std::endl; else std::cout << "Stack is not empty." << std::endl; std::cout << "Pushing elements to the stack..." << std::endl; stack.Push(1); stack.Push(2); stack.Push(3); stack.Push(4); stack.Push(5); std::cout << "Top element of the stack right now: " << stack.Peek() << std::endl; if(stack.IsEmpty()) std::cout << "Stack is empty." << std::endl; else std::cout << "Stack is not empty." << std::endl; std::cout << std::endl; std::cout << "Popping the stack:" << std::endl; while(!stack.IsEmpty()) { std::cout << stack.Peek() << std::endl; stack.Pop(); } if(stack.IsEmpty()) std::cout << "Stack is empty." << std::endl; else std::cout << "Stack is not empty." << std::endl; return 0; }
int main(int argc, char** argv) { // Stack test Stack<int> s; s.Push(10); s.Push(20); s.Push(30); s.Push(40); s.Push(1); s.Push(2); s.Push(3); s.Push(4); s.Push(5); s.Push(6); s.Push(7); s.Push(8); while(!s.IsEmpty()) { printf("%d\n", s.Top()); s.Pop(); } printf("-----\n"); // Queue test Queue<int> q; q.Enque(10); q.Enque(20); q.Enque(30); q.Enque(40); q.Enque(1); q.Enque(2); q.Enque(3); q.Enque(4); q.Enque(5); q.Enque(6); q.Enque(7); q.Enque(8); while(!q.IsEmpty()) { printf("%d\n", q.Front()); q.Deque(); } printf("-----\n"); // Maze test path(argv[1]); return 0; }
template<typename T>void BinaryTree<T>::StackOrder(TNode<T> *Current){ if(Current!=NULL){ Stack<TNode<T> *> stack; // 栈 stack.Push(Current); TNode<T>* p; while(!stack.IsEmpty()) { // 栈非空 p = stack.Pop(); cout<<p->info<<'\t'; // 访问p结点 if(p->rchild) stack.Push(p->rchild); if(p->lchild) stack.Push(p->lchild); } } }
int multiply(Stack &stack) { double temp = stack.Pop(); // Checks if the stack has enough values. if ( stack.IsEmpty() ) { cout << "Not enough values in the stack!" << endl; if (temp) stack.Push(temp); return 1; } // Multiplies double temp2 = stack.Pop(); double out = temp2 * temp; stack.Push( out ); }
int subtract(Stack &stack) { double temp = stack.Pop(); // Checks if the stack has enough values. if ( stack.IsEmpty() ) { cout << "Not enough values in the stack!" << endl; if (temp) stack.Push(temp); return 1; } // Subtracts double temp2 = stack.Pop(); double out = temp2 - temp; stack.Push( out ); }
int add(Stack &stack) { double temp = stack.Pop(); // Checks if the stack has enough values. if ( stack.IsEmpty() ) { cout << "Not enough values in the stack!" << endl; if (temp) stack.Push(temp); return 1; } // Adds values double temp2 = stack.Pop(); double out = temp2 + temp; // Pushes output stack.Push( out ); }
int swap(Stack &stack) { double temp = stack.Pop(); // Checks if the stack has enough values. if ( stack.IsEmpty() ) { cout << "Not enough values in the stack!" << endl; if (temp) stack.Push(temp); return 1; } double temp2 = stack.Pop(); // Swaps the top two values stack.Push( temp ); stack.Push( temp2 ); }
int square_root(Stack &stack) { // Checks if operand is negative if ( stack.Top() < 0 ) { cout << "Cannot get square root of negative number!" << endl; return 1; } // Checks if the stack has enough values. if ( stack.IsEmpty() ) { cout << "Not enough values in the stack!" << endl; return 1; } double temp = stack.Pop(); double out = sqrt(temp); stack.Push( out ); }
int main() { cout << "RPN Calculator v1.0 by Alex McNurlin" << endl; string s; Stack stack; while (1) { // Statusline to prompt a new command if ( stack.IsEmpty() ){ cout << "RPN " << "(empty)" << " > "; } else { double top = stack.Top(); cout << "RPN " << top << " > "; } // Reads user input. Exits on error (including user hitting ctrl-D) if (!getline(cin,s)) { exit(0); } // Thanks to http://stackoverflow.com/questions/236129/split-a-string-in-c // Credit to user 'kev' -> http://stackoverflow.com/users/348785/kev // Takes the input line and parses it with space delimiters (word by word) string buf; // Have a buffer string stringstream ss(s); // Insert the string into a stream vector<string> tokens; // Create vector to hold our words while (ss >> buf) { tokens.push_back(buf); } // End stackoverflow code. // Loops over each of the input commands for (int i=0; i< tokens.size(); i++) { // This is where the bulk of the processing is. parse_input( tokens[i], stack ); } } return 0; }
int divide(Stack &stack) { // Avoids dividing by 0 if ( stack.Top() == 0 ) { cout << "Cannot divide by zero!" << endl; return 1; } double temp = stack.Pop(); // Checks if the stack has enough values. if ( stack.IsEmpty() ) { cout << "Not enough values in the stack!" << endl; if (temp) stack.Push(temp); return 1; } // Divides double temp2 = stack.Pop(); double out = temp2 / temp; stack.Push( out ); }
Stack operator+(const Stack& s) const { // copy the first list Stack t = *this; Stack u = *this; Node *n = s.top; // iterate through the second list and copy each element to the new list while (n != NULL && !t.IsFull()) { t.Push(n->data); n = n->link; } n = t.top; while (n != NULL && !t.IsEmpty()) { u.Push(n->data); t.Pop(); n = t.top; } return u; }
string ExpressionNotationConverter::ConvertInfixToPostfix(string expression) { Stack operatorStack; Stack operandStack; string outputString = ""; auto tmp = expression; while (tmp.length() > 0) { auto strLength = tmp.length(); auto numberToSkip = 0; auto skip = 1; do { auto tmp1 = tmp.substr(numberToSkip, 1); if (!isdigit(tmp1[0])) break; numberToSkip++; } while (numberToSkip - 1 < strLength); if (numberToSkip > 0) { skip = numberToSkip; } auto subString = tmp.substr(0, strLength - (strLength - skip)); auto currentCharacterPrecedence = DeterminePrecidence(subString); if (subString == "(") { operatorStack.Push(subString); } else if (subString == ")") { while (!operatorStack.IsEmpty() && operatorStack.Peek() != "(") { auto currentOperator = operatorStack.Pop(); auto lhs = stoi(operandStack.Pop()); auto rhs = stoi(operandStack.Pop()); auto result = to_string(ApplyOperation(currentOperator, lhs, rhs)); operandStack.Push(result); if (currentOperator != "(" && currentOperator != ")") { outputString += currentOperator + " "; } } auto paren = operatorStack.Pop(); } else if (currentCharacterPrecedence == OPERAND) { operandStack.Push(subString); outputString += subString + " "; } else { while (!operatorStack.IsEmpty() && currentCharacterPrecedence <= DeterminePrecidence(operatorStack.Peek())) { auto currentOperator = operatorStack.Pop(); outputString += currentOperator + " "; if (currentOperator != "(" && currentOperator != ")") { auto lhs = stoi(operandStack.Pop()); auto rhs = stoi(operandStack.Pop()); auto result = to_string(ApplyOperation(currentOperator, lhs, rhs)); operandStack.Push(result); } } operatorStack.Push(subString); } tmp = string(tmp.substr(skip)); } while (!operatorStack.IsEmpty()) { auto currentOperator = operatorStack.Pop(); if (currentOperator == "(" || currentOperator == ")") { outputString = "Invalid Expression!"; break; } auto lhs = stoi(operandStack.Pop()); auto rhs = stoi(operandStack.Pop()); auto result = to_string(ApplyOperation(currentOperator, lhs, rhs)); operandStack.Push(result); outputString += currentOperator + " "; } if (outputString == "Invalid Expression!") { return outputString; } auto result = operandStack.Pop(); return outputString += " : " + result; }
int main(void) { int *data; // 用來接收一副牌的資料 int times = 1,total = 0; int faceu[SIZE][7] = {0}; // 7 plies of face-up cards Queue stockcards; // storage facedown stock cards Stack wastecards; // storage face-up waste plie cards Stack faced[7]; // 7 piles of facedown cards int Spade, Heart, Diamond, Club; // output plies Number num[7] = {0}; // record faceu's status while(times <= 100) { int i = 0, j = 0, k = 0, action = 0; // counter, action是動作計數器 int counter = 0; // 判斷步驟用的變數 int score = -52; // 分數 Club = Diamond = Heart = Spade = 0; // output plies initial data = new_set_of_cards(times); // 要一副洗好的牌資料 , times為100次中的第幾次 for(i = 1; i <= 28 ;) // 發牌到下面七個row裡 { for(j = k; j < 7; j++ ,i++) { faced[j].Push(data[i-1]); num[j].fst = num[j].nth = (data[i-1] - 1) % 13; num[j].fstcardno = num[j].cardno = data[i-1]; } k++; } for(i = 28 ; i < 52 ; i++) // 發剩下的牌到牌堆裡 { stockcards.Add(data[i]); } for(i = 0 ; i < 7 ; i++) // 翻開playing plie最下面的牌 { faceu[0][i] = faced[i].Pop(); num[i].sheets = 1; } wastecards.Push(stockcards.Delete()); // 從牌堆翻一張牌到waste plie while(counter == 0) { counter = 1; //(a)從wasteplie和playing plie把最上方的牌移至output區 ( counter = 1 ) // 如果wasteplie空了,就從牌堆翻開一張牌放到wasteplie /*-------------------------------------------------------------------------------------------------------*/ while(counter == 1) { /*----------wastecards part----------*/ if((wastecards.Top() - 1) == (13 * 0) + Spade ||(wastecards.Top() - 1) == (13 * 1) + Heart ||(wastecards.Top() - 1) == (13 * 2) + Diamond ||(wastecards.Top() - 1) == (13 * 3) + Club) {/*----------可以放上去的狀況---------*/ score += 5; switch((wastecards.Top() - 1) / 13) { case 0: Spade++; break; case 1: Heart++; break; case 2: Diamond++; break; case 3: Club++; break; } wastecards.Pop(); action++; if(wastecards.IsEmpty()) { wastecards.Push(stockcards.Delete()); } counter = 0; break; } /*------playing plies part-------*/ for(i = 0 ; i < 7 ; i++) { if((num[i].cardno - 1) == (13 * 0) + Spade || (num[i].cardno - 1) == (13 * 1) + Heart || (num[i].cardno - 1) == (13 * 2) + Diamond || (num[i].cardno - 1) == (13 * 3) + Club) {/*-------可以放上去的狀況-------*/ score += 5; switch((num[i].cardno - 1) / 13) { case 0: Spade++; break; case 1: Heart++; break; case 2: Diamond++; break; case 3: Club++; break; } num[i].sheets--; faceu[num[i].sheets][i] = 0; num[i].nth++; action++; if(num[i].sheets != 0) // faceu non-empty { num[i].cardno = faceu[num[i].sheets-1][i]; } else // faceu empty { if(!faced[i].IsEmpty()) // faced non-empty { faceu[0][i] = faced[i].Pop(); num[i].fstcardno = num[i].cardno = faceu[0][i]; num[i].nth = num[i].fst = (faceu[0][i]-1) % 13; num[i].sheets = 1; } else// faced empty { num[i].sheets = num[i].fstcardno = num[i].cardno = num[i].nth = num[i].fst = 0; } } counter = 0; break; } else // have no action { counter = 2; // jump to step(b) } } } /*-------------------------------------------------------------------------------------------------------*/ //(b)從wasteplie移動最上方的牌到playing plie,可以移動的話以最左邊為主 ( counter = 2 ) // 如果wasteplie空了,就從牌堆翻一張牌到wasteplie /*-------------------------------------------------------------------------------------------------------*/ while(counter == 2) { for(i = 0 ; i < 7 ; i++) { if(num[i].sheets != 0) // faceu non-empty { if( (wastecards.Top() - 1) / 13 + (num[i].cardno - 1) / 13 != 3 && (wastecards.Top() - 1) / 13 != (num[i].cardno- 1) / 13) // different color { if((wastecards.Top() - 1) % 13 == num[i].nth - 1) // point continue { num[i].nth--; num[i].cardno = wastecards.Pop(); faceu[num[i].sheets][i] = num[i].cardno; num[i].sheets++; action++; if(wastecards.IsEmpty()) { wastecards.Push(stockcards.Delete()); } break; } } } else// faceu empty { if(wastecards.Top() % 13 == 0 && wastecards.Top() != 0) // K { num[i].fstcardno = num[i].cardno = faceu[num[i].sheets][i] = wastecards.Pop(); num[i].fst = num[i].nth = 12; num[i].sheets = 1; action++; if(wastecards.IsEmpty()) { wastecards.Push(stockcards.Delete()); } break; } } } if(action != 0) // have action { counter = 0; // jump to step(a) } else // have no action { counter = 3; // jump to step(c) } } /*-------------------------------------------------------------------------------------------------------*/ /*(c)從最左邊找已經faceup的playing plie,是否可以移動至其他playing plie ( counter = 3 ) 此移動為所有同一個playing plie下所有faceup的牌一起移動 */ /*-------------------------------------------------------------------------------------------------------*/ while(counter == 3) { for(i = 0 ; i < 7 ; i++) { if(action != 0) // have action { break; } for(j = 0 ; j < 7 ; j++) { int k = 0; // program counter if(num[i].sheets != 0 && i != j)// faceu non empty (source) { if(num[j].sheets != 0)// faceu non empty (target) { if( (num[i].fstcardno - 1) / 13 + (num[j].cardno - 1) / 13 != 3 && (num[i].fstcardno - 1) / 13 != (num[j].cardno - 1) / 13) // different color { if(num[i].fst == num[j].nth - 1) // point continue { while(k < num[i].sheets) { num[j].cardno = faceu[num[j].sheets][j] = faceu[k][i]; faceu[k][i] = 0; num[j].sheets++; num[j].nth = (num[j].cardno - 1) % 13; k++; } action++; num[i].sheets = num[i].fstcardno = num[i].cardno = num[i].nth = num[i].fst = 0; // null, after move if(!faced[i].IsEmpty()) { faceu[0][i] = faced[i].Pop(); num[i].fstcardno = num[i].cardno = faceu[0][i]; num[i].nth = num[i].fst = (faceu[0][i]-1)%13; num[i].sheets = 1; } } } } else// faceu empty { if((num[i].fst) == 12 && !faced[i].IsEmpty()) // K { num[j].fst = num[j].nth = 12; num[j].fstcardno = num[i].fstcardno; while(k < num[i].sheets) { num[j].cardno = faceu[num[j].sheets][j] = faceu[k][i]; faceu[k][i] = 0; num[j].sheets++; num[j].nth = (num[j].cardno - 1) % 13; k++; } action++; num[i].sheets = num[i].fstcardno = num[i].cardno = num[i].nth = num[i].fst = 0; if(!faced[i].IsEmpty()) { faceu[0][i] = faced[i].Pop(); num[i].fstcardno = num[i].cardno = faceu[0][i]; num[i].nth = num[i].fst = (faceu[0][i]-1)%13; num[i].sheets = 1; } } } } if(action != 0) { break; } } } if(action != 0) // have action { counter = 0; // jump to step (a) } else // have no action { counter = 4; // jump to step (e) } } /*-------------------------------------------------------------------------------------------------------*/ //(e)如果(a).(b).(c)都不能移動的話,從牌堆翻開一張牌放到wasteplie,然後從(a)步驟重新判斷 ( counter = 4 ) /*-------------------------------------------------------------------------------------------------------*/ while(counter == 4) { if(!stockcards.IsEmpty()) { wastecards.Push(stockcards.Delete()); } counter = 0; // jump to step (a) } /*-------------------------------------------------------------------------------------------------------*/ for(i = 0 ; i < 7 ; i++) // 檢查playing plie 裡面是不是還有可以放在output裡的牌, waste plie裡是否 { // 可以放在playing plie裡以及playing plie 是否還可以移動, 若可移動則action++ if((num[i].cardno - 1) == (13 * 0) + Spade || (num[i].cardno - 1) == (13 * 1) + Heart ||(num[i].cardno - 1) == (13 * 2) + Diamond || (num[i].cardno - 1) == (13 * 3) + Club) { action++; } if( (wastecards.Top() - 1) / 13 + (num[i].cardno - 1) / 13 != 3 && (wastecards.Top() - 1) / 13 != (num[i].cardno- 1) / 13) // different color { if((wastecards.Top() - 1) % 13 == num[i].nth - 1) // point continue { action++; } } for(j = 0 ; j < 7 ; j++) { if(num[i].sheets != 0 && i != j)// faceu non empty (source) { if(num[j].sheets != 0)// faceu non empty (target) { if( (num[i].fstcardno - 1) / 13 + (num[j].cardno - 1) / 13 != 3 && (num[i].fstcardno - 1) / 13 != (num[j].cardno - 1) / 13) // different color { if(num[i].fst == num[j].nth - 1) // point continue { action++; } } } else { if((num[i].fst) == 12 && !faced[i].IsEmpty()) // K { action++; } } } } } if((wastecards.Top() - 1) == (13 * 0) + Spade || (wastecards.Top() - 1) == (13 * 1) + Heart ||(wastecards.Top() - 1) == (13 * 2) + Diamond || (wastecards.Top() - 1) == (13 * 3) + Club) { // 檢查waste plie裡面是不是還有可以放在output裡的牌, 若有則action++ action++; } if(stockcards.IsEmpty() && action == 0) // 牌堆沒牌以及所有牌不可再移動時結束遊戲 { break; } action = 0; } //play finish total += score; printf("%3d times score = %3d\n", times, score); //print score and times printf("\n"); /*---------------------------清空資料動作---------------------------*/ for(i = 0 ; i < 7 ; i++) { while(!faced[i].IsEmpty()) { faced[i].Pop(); } num[i].sheets = num[i].fstcardno = num[i].cardno = num[i].nth = num[i].fst = 0; for(j = 0 ; j < SIZE ; j++) { faceu[j][i] = 0; } } while(stockcards.IsEmpty() && wastecards.IsEmpty()) { stockcards.Delete(); wastecards.Pop(); } free(data); // 釋放記憶體 times++; // 次數增加準備執行下一次 } printf(" total = %5d\n",total); //print total score return 0; }
TEST(Stack, empty_stack_IsEmpty_1) { Stack<int> *S = new Stack<int>; EXPECT_EQ(1, S->IsEmpty()); }
TEST(Stack, isnt_empty_stack_IsEmpty_0) { Stack<int> *S = new Stack<int>; S->Push(1); EXPECT_EQ(0, S->IsEmpty()); }
/* * vislib::sys::Path::MakeDirectory */ void vislib::sys::Path::MakeDirectory(const StringA& path) { Stack<StringA> missingParts; StringA firstBuilt; StringA curPath = Resolve(path); while (!File::Exists(curPath)) { StringA::Size pos = curPath.FindLast(SEPARATOR_A); if (pos != StringA::INVALID_POS) { missingParts.Push(curPath.Substring(pos + 1)); if (missingParts.Peek()->IsEmpty()) { // Remove empty directories as the incremental directory // creation later on will fail for these. missingParts.Pop(); } curPath.Truncate(pos); } else { // Problem: No Separators left, but directory still does not exist. #ifdef _WIN32 throw vislib::sys::SystemException(ERROR_INVALID_NAME, __FILE__, __LINE__); #else /* _WIN32 */ throw vislib::sys::SystemException(EINVAL, __FILE__, __LINE__); #endif /* _WIN32 */ } } // curPath exists if (!File::IsDirectory(curPath)) { // the latest existing directory is not a directory (may be a file?) #ifdef _WIN32 throw vislib::sys::SystemException(ERROR_DIRECTORY, __FILE__, __LINE__); #else /* _WIN32 */ throw vislib::sys::SystemException(EEXIST, __FILE__, __LINE__); #endif /* _WIN32 */ } while (!missingParts.IsEmpty()) { curPath += SEPARATOR_A; curPath += missingParts.Pop(); #ifdef _WIN32 if (CreateDirectoryA(curPath, NULL) != 0) { #else /* _WIN32 */ if (mkdir(curPath, S_IRWXG | S_IRWXO | S_IRWXU) == 0) { // TODO: Check #endif /* _WIN32 */ // success, so go on. if (firstBuilt.IsEmpty()) { firstBuilt = curPath; } } else { DWORD errorCode = GetLastError(); try { // failure, so try to remove already created paths and throw exception. DeleteDirectory(firstBuilt, true); } catch(...) { } throw vislib::sys::SystemException(errorCode, __FILE__, __LINE__); } } // we are done! } /* * vislib::sys::Path::MakeDirectory */ void vislib::sys::Path::MakeDirectory(const StringW& path) { #ifdef _WIN32 Stack<StringW> missingParts; StringW firstBuilt; StringW curPath = Resolve(path); while (!File::Exists(curPath)) { StringW::Size pos = curPath.FindLast(SEPARATOR_W); if (pos != StringW::INVALID_POS) { missingParts.Push(curPath.Substring(pos + 1)); if (missingParts.Peek()->IsEmpty()) { // Remove empty directories as the incremental directory // creation later on will fail for these. missingParts.Pop(); } curPath.Truncate(pos); } else { // Problem: No Separators left, but directory still does not exist. throw vislib::sys::SystemException(ERROR_INVALID_NAME, __FILE__, __LINE__); } } // curPath exists if (!File::IsDirectory(curPath)) { // the latest existing directory is not a directory (may be a file?) throw vislib::sys::SystemException(ERROR_DIRECTORY, __FILE__, __LINE__); } while (!missingParts.IsEmpty()) { curPath += SEPARATOR_W; curPath += missingParts.Pop(); if (CreateDirectoryW(curPath, NULL) != 0) { // success, so go on. if (firstBuilt.IsEmpty()) { firstBuilt = curPath; } } else { DWORD errorCode = GetLastError(); try { // failure, so try to remove already created paths and throw exception. DeleteDirectory(firstBuilt, true); } catch(...) { } throw vislib::sys::SystemException(errorCode, __FILE__, __LINE__); } } // we are done! #else /* _WIN32 */ // linux is stupid MakeDirectory(W2A(path)); #endif /* _WIN32 */ }