fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. char logicalExpressionEvaluation(string str, int& idx) {
  5. if (str[idx] == '0' || str[idx] == '1') {
  6. return str[idx++];
  7. }
  8.  
  9. if (str[idx] == '[') {
  10. idx++; // Move past the '['
  11. vector<char> operands;
  12. char op = str[idx]; // Get the operator
  13. idx++; // Move past the operator
  14.  
  15. // Loop to collect operands
  16. while (str[idx] != ']') {
  17. if (str[idx] == ',') {
  18. idx++; // Skip comma
  19. } else if (str[idx] == '[') {
  20. operands.push_back(logicalExpressionEvaluation(str, idx)); // Recursively evaluate sub-expression
  21. } else {
  22. operands.push_back(str[idx++]); // Push the operand (0 or 1)
  23. }
  24. }
  25. idx++; // Move past the closing ']'
  26.  
  27. if (op == '!') {
  28. // Ensure we only have one operand for '!'
  29. if (operands.size() == 1) {
  30. return operands[0] == '1' ? '0' : '1';
  31. }
  32. } else if (op == '&') {
  33. char result = '1'; // Assume AND is true
  34. for (char operand : operands) {
  35. if (operand == '0') {
  36. result = '0'; // If any operand is 0, result is 0
  37. break;
  38. }
  39. }
  40. return result;
  41. } else if (op == '|') {
  42. char result = '0'; // Assume OR is false
  43. for (char operand : operands) {
  44. if (operand == '1') {
  45. result = '1'; // If any operand is 1, result is 1
  46. break;
  47. }
  48. }
  49. return result;
  50. }
  51. }
  52. return '0'; // Default case if something goes wrong
  53. }
  54.  
  55. char logicalExpressionEvaluation(string str) {
  56. int idx = 0;
  57. return logicalExpressionEvaluation(str, idx);
  58. }
  59.  
  60. vector<int> circuitsOutput(vector<string> circuitsExpression) {
  61. vector<int> result;
  62. for (string expression : circuitsExpression) {
  63. result.push_back(logicalExpressionEvaluation(expression) - '0');
  64. }
  65. return result;
  66. }
  67.  
  68. int main() {
  69. vector<string> circuits = {
  70. "[|, [&, 1, [!, 0]], [!, [|, [|, 1, 0], [!, 1]]]]"
  71. };
  72.  
  73. vector<int> outputs = circuitsOutput(circuits);
  74.  
  75. // Print the result for each circuit
  76. for (int output : outputs) {
  77. cout << output << endl;
  78. }
  79.  
  80. return 0;
  81. }
  82.  
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
0