Instantly share code, notes, and snippets.

# nint22/gist:6214694 Created Aug 12, 2013

What would you like to do?
[08/13/13] Challenge #135 [Easy] Arithmetic Equations (2nd Attempt)
 #include #include #include using namespace std; struct ExpressionElement { bool isValue; union { int value; char op; } data; }; int main() { int min, max; char opChars[3] = { '+', '-', 'x' }; scanf("%d %d", &min, &max); int consts[4]; char ops[3]; // Infinite loop unless user exists... bool correct = true; int correctResult = 0; while(true) { // If correct, generate new challenge if(correct) { for(int i = 0; i < 4; i++) consts[i] = min + rand() % (max - min + 1); // +1 since we're inclusive for(int i = 0; i < 3; i++) ops[i] = opChars[rand() % 3]; // Place equation into ExpressionElement list, so we can compute a solution vector< ExpressionElement > expressionList; for(int i = 0; i < 4; i++) { ExpressionElement element; element.isValue = true; element.data.value = consts[i]; expressionList.push_back(element); if(i < 3) { element.isValue = false; element.data.op = ops[i]; expressionList.push_back(element); } } // Do all multiplication first, storing the result to the right of the op for(int i = 0; i < expressionList.size() / 2; i++) { int index = i * 2; ExpressionElement arg0 = expressionList.at(index + 0); ExpressionElement op = expressionList.at(index + 1); ExpressionElement arg1 = expressionList.at(index + 2); if(arg0.isValue && !op.isValue && arg1.isValue && op.data.op == 'x') { expressionList.erase(expressionList.begin() + index); expressionList.erase(expressionList.begin() + index); expressionList.at(index).data.value = arg0.data.value * arg1.data.value; i--; } } // Add/sub for(int i = 0; i < expressionList.size() / 2; i++) { int index = i * 2; ExpressionElement arg0 = expressionList.at(index + 0); ExpressionElement op = expressionList.at(index + 1); ExpressionElement arg1 = expressionList.at(index + 2); if(arg0.isValue && !op.isValue && arg1.isValue) { expressionList.erase(expressionList.begin() + index); expressionList.erase(expressionList.begin() + index); if(op.data.op == '+') expressionList.at(index).data.value = arg0.data.value + arg1.data.value; else expressionList.at(index).data.value = arg0.data.value - arg1.data.value; i--; } } correctResult = expressionList.at(0).data.value; correct = false; } printf("%d %c %d %c %d %c %d\n", consts[0], ops[0], consts[1], ops[1], consts[2], ops[2], consts[3]); char input[512]; fgets(input, 511, stdin); if(input[0] == 'q' || input[0] == 'Q') { break; } else { int value = -1; int scanned = sscanf(input, "%d", &value); if(scanned != 1) printf("Incorrect input format, try again\n"); else if(value != correctResult) printf("Incorrect...\n"); else if(value == correctResult) { printf("Correct!\n"); correct = true; } } } // All done return 0; }