Difference between revisions of "CSC212 Final Exam 2014"
Line 41: | Line 41: | ||
=Problem #9= | =Problem #9= | ||
− | * | + | * Assume we have a function that generates random RPN expressions: |
+ | <source lang="java"> | ||
+ | static String randomRPN( int n ) { | ||
+ | Random generator = new Random(); | ||
+ | generator.setSeed( 11 ); | ||
+ | String s = ""; | ||
+ | int noOps = 0; | ||
+ | int no11s = 0; | ||
+ | for ( int i=0; i<n; i++ ) { | ||
+ | int r = generator.nextInt(5); | ||
+ | int x =(1+generator.nextInt(10)); | ||
+ | int y =(1+generator.nextInt(10)); | ||
+ | switch ( r ) { | ||
+ | case 0: s += x + " " + y + " + "; noOps++; break; | ||
+ | case 1: s += x + " " + y + " - "; noOps++; break; | ||
+ | case 2: s += x + " " + y + " % "; noOps++; break; | ||
+ | case 3: s += "11 "; no11s++; break; | ||
+ | } | ||
+ | } | ||
+ | noOps--; | ||
+ | while ( noOps-- > 0 ) | ||
+ | s += "+ "; | ||
+ | while ( no11s-- > 0 ) | ||
+ | s += "- "; | ||
+ | return s; | ||
+ | } | ||
+ | </source> | ||
+ | * If we call it and pass it 200 as an argument, it prints a fairly long string, starting with "11 4 8 + 4 4 + 5 5 %" and ends with " - - - - - - - - - -". | ||
+ | * If we evaluate this RPN expression, the result is -725. True of False? | ||
+ | :(answer: False, it's -726) | ||
</onlydft> | </onlydft> |