APSC 142 CHEAT SHEET Precedence=(!-)(*/%)(+-)(<,>,<=,>=)(==,!=)(&&)(||)(= += -= *= /=) 16-bit integer (2 bytes) int,32-bit integer (4 bytes) long,floating point (32-bit) float,character byte (in RobotC),% modulo (or “remainder”) +=, -=, *= add, etc. and assign %e scientific (always has exponent) %g gives %f or %e, whichever is shorter %c character (called “byte” in RobotC) - byte can hold 28 = 256 values (-128 through +127) - int can hold 216 = 65,536 values (range is 32,764 through +32,763) - long can hold 232 = 4,294,967,296 values (range is – 2,147,483,648 through +2,147,483,647) - float can hold 232 = 4,294,967,296 values (range is ± (2-2-23)127 ~ ± 1038.53 ) casting: num2= (int) num1 -float num= 2/3, give 0.000000, need (float) 2/3 – e.g., %7.2f leaves 7 spots for the number (incl. decimal point), with 2 of them being for the digits to right of decimal Passing 2D Array typedef float FLOAT2D[2][3]; float getMinGrade(FLOAT2D); task main () { float min; float grades[2][3]={{1.8, 27.4, 55.9}, {23.2, 77.0, 98.0}}; min = getMinGrade(grades); nxtDisplayTextLine(0, "min is %f", min); } float getMinGrade(FLOAT2D gradeArray) { float minResult; int i,j; minResult = gradeArray[0][0]; //initialize min to first element in array for (i = 0; i < 2; i++) for (j = 0; j < 3; j++) { if (gradeArray[i][j] < minResult) minResult = gradeArray[i][j]; } return minResult; } Reversing array: task main() {int array[10][10]; int temp; int i,j; int max=0,min=100; for(i=0;i<(10/2);i++) //Reversal { for(j=0;j<(10/2);j++) {temp = array[i][j]; array[i][j] = array[i][10-1-j]; array[i][10-1-j] = temp; } } for(i=0;i<(10/2);i++) //Max/Min { for(j=0;j<(10/2);j++) {if(array[i][j]>max) array[i][j] = max; if(array[i][j]<min) array[i][j] = min; } } } switch((int) number) [must be integer] { case 3: volume = 7.2; area = 3.4; break; //jumps execution to ending brace case 5: volume = 11.5; area = 8.3; break; } is equivalent to: if (number == 3 ) { volume = 7.2; area = 3.4; } else if (number == 5) { volume = 11.5; area = 8.3; } INITIALIZING ID ARRAY int array[256]; for(int: 0; int < 256; int++) int littlearrayls]: {2,4,6,8, l0); { PASSING 2D ARRAY typedef float FLOAT2D[256] [ I 00] ; void scale(float s, FLOAT2D A, int N, int M) { int i, j; for(i:0;i<N;i++){ for(j=0;j<M;j++){ A[i][j]= s * A[i][j] } }} To the power of Function: Float power(float num, int p) {int i; float y=1; for(i=1; i<=p; i++) { y=y*num return y; } EXAM EXAMPLES 2010 1.program comprehension A) show screen output task main() {float f=2.6;int i; i=f; nxtDisplayTextLine(1,"%d, %0.2f", i, f); f=i*f; i=i*i; nxtDisplayTextLine(3,"%d, %0.1f", i,f); } line 1: 2,2.60 line 3: 4,5.2 B) screen output task main() {int i=0, j=1; do { nxtDisplayTextLine(i,"%d",j); i++; j=j+i; } while (j<11); } Display: 1,2,4,7 line 0=4 C)swaps values so val1 is never greater than val2, if swapped returns 1, otherwise returns 0. task main() { int swap(int &val1, int &val2) int temp; if(val1<=val2) return 0; else { temp=val1; val1=val2; val2=temp; return 1; } return swapped; } 2. Computation and Output: calculates values of the polynomial 2x3-100x2+200x-35 atx=0 x=0.1,x=3. Your program should then display the max value, min value and max x value task main() { float values[31]; int i, j; float x, max, xmax, xmin, min; for(i=0;i<31;i++) { x=0.1*i; values[i]=2*x*x*x100*x*x+200*x-35; } max=0; min=0; for (i=0;i<31;i++) { if(values[i]>max) { max=values[i]; xmax=i; } } xmax= xmax*0.1; nxtDisplayTextLine(0,"max is %0.2f at ",max); nxtDisplayTextLine(1,"x=%0.2f",xmax); for (j=0;j<31;j++) { if(values[j]<min) { min=values[j]; xmin = x; } } xmin= xmin*0.1; nxtDisplayTextLine(4,"min is %0.2f at ",min); nxtDisplayTextLine(5,"x=%0.2f",xmin); } } 3. NXT Robot Operation Complete 360 turn in 10 degree increments,meaure distance and less than 40 cm emit tone given by f=1600-20(d). task main() {int distance, count; sensorType[1]=sensorSonar; distance=SensorValue[1]; for (i=0;i<36;i++) rotate(10); distance=SensorValue[1]; if(distance<40) {playTone(1600-20*distance,5); count=count+1; } if (count!=0) nxtDisplayTextLine(1,"Too Close"); else nxtDisplayTextLine(1,"Okay"); } } 4. Function and 1DArray Problem: Compute the floating point averages at three readings. Call the getAverages() function to pass the meas1List[]-avgList[]. The function will compute the and fill N averages into the passed avgList[] array. This getAverages function should also return a value of 1 if any two measurements differ by more than 0.3. //function call from main to getaverages() alarm=getAverages(meas1list,meas2list,meas3list,avg List); //show the definition of the getAverages() function getAverages(meas1list,meas2list,meas3list,avgList) { int i; for(i=0;i<N;i++) {avgList[i]=1/3(meas1list[i]+meas2list[i]+m eas3list[i]); if(abs(meas1list[i]meas2list[i])>0.3) return 1; else if(abs(meas1list[i]meas2list[i])>0.3) return 1; else if(abs(meas3list[i]meas2list[i])>0.3) return 1; else return 0; }} QUESTION 6: 2-D Array Pixels can now be displayed as red blue green or off. A new function is provided which reads the current contents of the screen and puts it into a 2-D array of integers 100 by 64. void nxtReadScreen(INT2D screen); typedef int INT2D[100][64]; int calcScreenStats(INT2D screen, int &r, int&g, int &b) { int rows=100,cols=64, i, j; int redcount,greencount,bluecount,offcount; for(i=0;i<rows,i++) {for(j=0;j<cols,j++) {if(screen[i][j]==0) offcount++; if(screen[i][j]==1) redcount++; if(screen[i][j]==2) greencount++; if(screen[i][j]==3) bluecount++; } if(offcount!=0) return 1; else return 0; r=redcount; b=bluecount; g=greencount; } EXAMPLES 2009 EXAM QUESTION 2: MIN MAX Problem see 2010 QUESTION 3 The robot drives down a short hallway that has white 12-inch floor tiles, but with a few black floor tiles. When it bumps into the wall at the end of the hallway, the robot should stop and report if it passed over a black tile or not (it always starts over a white tile). The message from the robot should say either "ALL WHITE" or "SAW BLACK" when done. void Drivelinch (int speed); int GetReflective(); task main() {int leftbump=0, rightbump=0; int lightval; int result =0; int speed = 50; lightval = 0; //Drive to wall while (rightbump == 0 && leftbump == 0) {Drive1inch (speed); leftbump= SensorValue[0]; rightbump= SensorValue[3]; lightval = GetReflective(); if (lightval <= 25) {result = 1; } } //report if (blackcount ==1) nxtDisplayTextLine(0, "Saw black"); else nxtDisplayTextLine(0, "Saw all White"); QUESTION 4 floating point distances d[] from the origin at each time step, distanced = √(x^2 + y^2). It will do this by calling a distances( ) function to which it will pass the x[] , y[] , and d[] arrays – the function will compute and fill in the N distance values into the passed d[] array (N is a defined constant at the top of the program)The distances( ) function does not have a return value to send back to main(). //function call distances (x, y, d); //body of distances function void distances (INT1D a, INT1D b, FLOAT1D c) { int i; for (i=0;i<N;i++) { c[i] = sqrt(a[i]*a[i] + b[i]*b[i]); } return; } nxtDisplayTextLine(5,"x=%0.2f QUESTION 5 If there is an element of value 255 in the array (that is, if the diamond is in the image), then the function returns the value true (that is, 1), and the row and column of the diamond’s location are passed back through the parameters &row and &col. If there is no element of value 255 (that is, the diamond has been stolen), then the function returns the value false (that is, 0), and the row and column parameters are set to result = searchForDiamond(picture); if(result==1) {nxtD...(1, “The Diamond is at”); nxtD...(2, “%d, %d”, row, col); } else nxtD...(1, “NOT FOUND”); searchForDiamond( int picture) int i, j, result=0; row=-1; col=-1; for(i=0; i<ROWS; i++) for(j=0; j<COLS; j++) {if(image[i][j]==255) row=i; col=j; result=1} return result; QUESTION 6 Write a program in task main() that determines the length of time a ball freefalls for after being dropped from the CN Tower. A function for accel given air resistance is 9.81 – 0.017*v*v. Evaluate using delta t value of 0.01 sec. Hint (initial h) is 346. typedef float FLOAT1D[256]; void makeNegArray(FLOAT1D newArray, int arraySize); task main () {float newArray[]={-6.54, 0, 77.2, 12.3, -19.4}; makeNegArray(newArray,5); } void makeNegArray(FLOAT1D nums, int size) {int i; for(i = 0; i < size; i++) {if (nums[i] > 0) nums[i]=nums[i]*(-1); } return; } Write a function makeNegArray that takes a 1dimensional array input and if any of the array’s elements are positive, it replaces those elements with their negative counterpart. The function make NegArray will need two arguments: the array and the size of the array. In main(), initialize an array to [6.54, 0, 77.2, 12.3, -19.4], then call makeNegArray. If you were running this program on QNXTBotSim, the call to makeNegArray should change the above array to [-6.54, 0, -77.2, -12.3, -19.4] typedef float FLOAT1D[256]; void makeNegArray(FLOAT1D newArray, int arraySize); task main () {float newArray[]={-6.54, 0, 77.2, 12.3, -19.4}; makeNegArray(newArray,5); } void makeNegArray(FLOAT1D nums, int size) {int i; for(i = 0; i < size; i++) {if (nums[i] > 0) nums[i]=nums[i]*(-1); } return; } Write a function isDivisible(INT2D inArray, BYTE2D outArray, int n) that checks every element of the 2-D array inArray and if an element in row i, column j is divisible by n, the function puts a 1 in row i, column j of outArray and if the element in inArray is not divisible by n, it puts a 0 in row i, column j of outArray. You do not need to write the complete program, only the function. #define ROWS 25 #define COLS 75 typedef int INT2D[25][75]; typedef byte BYTE2D[25][75] void isDivisible(INT2D inArray, BYTE2D outArray,int n) { int i, j; for(i=0; i<=ROWS-1; i++) { for (j=0; j<=COLS-1; j++) { if (inArray[i][j]%n==0) outArray[i][j]=1; else outArray[i][j]=0; }}} inverse_cross.c#define ROWS 8 #define COLS 8 typedef byte BYTE2D[8][8]; void display(BYTE2D pixels, int left, int top); //THIS IS THE DECLARATION OF AN inverse() FUNCTION void inverse(BYTE2D pixels); task main() { int i, j; byte image[8][8]={{0,0,0,1,1,0,0,0}, {0,0,0,1,1,0,0,0}, {0,0,0,1,1,0,0,0}, {1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1}, {0,0,0,1,1,0,0,0}, {0,0,0,1,1,0,0,0}, {0,0,0,1,1,0,0,0} }; display(image, 45, 30); wait10Msec(50); //wait 500 msecs inverse(image); display(image, 45, 30); } void display(BYTE2D pixels, int left, int top) { int i, j; for(i=0; i<=ROWS-1; i++) { for(j=0; j<=COLS-1; j++) { if(pixels[i][j] == 0) nxtClearPixel(j+left, top-i); else if(pixels[i][j] == 1) nxtSetPixel(j+left, top-i); } } } void inverse(BYTE2D pixels) { int i, j; //FILL IN NESTED LOOPS HERE TO REPLACE //ALL "1" PIXEL VAUES BY "0", AND VICE-VERSA for(i=0; i<=ROWS-1; i++) { for(j=0; j<=COLS-1; j++) { if(pixels[i][j] == 0) pixels[i][j] = 1; else if(pixels[i][j] == 1) pixels[i][j]=0; } } } Write a program to solve the quadratic equation ax^2+bx+c = 0 where you assign values for a, b and c. The solution will have three possible outcomes, depending on the value of b2 - 4ac : 1) Roots are real and equal, 2) Roots are real but not equal, and 3) Roots are complex. task main() { float a,b,c,t,x1,x2,real,imag; a=5; b=15; c=10; nxtDisplayTextLine(0,"a= %0.3f , b= %0.3f",a,b); nxtDisplayTextLine(1,"c= %0.3f",c); t=b*b-4*a*c; if(abs(t-0)<0.00001) //this is an alternative equality check to (t==0) { x1= -b/(2*a); nxtDisplayTextLine(3,"Roots are real"); nxtDisplayTextLine(4,"and equal"); nxtDisplayTextLine(6,"x1 = x2 = %0.3f", x1); } else if(t>0) { x1= (-b+sqrt(t))/(2*a); x2= (-b-sqrt(t))/(2*a); nxtDisplayTextLine(3,"Roots are real"); nxtDisplayTextLine(5,"x1=%0.3f, x2=%0.3f", x1,x2); } else { real=-b/(2*a); // calculating real part alone imag=sqrt(-t)/(2*a); // calculating imaginary part alone nxtDisplayTextLine(3,"Roots are complex"); nxtDisplayTextLine(5,"x1= %0.3f + i%0.3f",real,imag); nxtDisplayTextLine(7,"x1= %0.3f - i%0.3f",real,imag); }} Vacuum function- simulates the motion of a vacuum task main() { int leftbump, rightbump, bump_count=0, back_time=200; nMotorPIDSpeedCtrl[1] = mtrSpeedReg; nMotorPIDSpeedCtrl[2] = mtrSpeedReg; SensorType[0] = sensorTouch; SensorType[3] = sensorTouch; while(bump_count<=20) { motor[1]=100; // move forward motor[2]=100; rightbump = SensorValue[0]; leftbump = SensorValue[3]; if(rightbump==1 || leftbump==1 ) { motor[1]=-60; motor[2]=-60; wait10Msec(random(back_time)+100); motor[1]=0; motor[2]=0; wait10Msec(20); motor[1]=60; // turning 90 degrees motor[2]=-60; wait10Msec(38); motor[1]=0; motor[2]=0; wait10Msec(20); bump_count++; // increase bumping counter } } } Steve and William are competing in a 100 m race. Each has his own running strategy: Steve: accelerates at his full power of 2m/s2 until he reaches a speed of 6 m/s and then maintains this speed till the end of the race (i.e. his acceleration becomes zero). William: accelerates at only 1.2m/s2 but reaches a speed of 7 m/s and then is also able to maintain it till the end of the race. task main() { float a1=2; float a2=1.2; float d; float v1,v1prev,v1avg; float v2,v2prev,v2avg; float timeS,timeW,deltaT; v1 = 0; v2 = 0; timeS = 0; timeW = 0; deltaT = 0.04; d=0; while(d<100) {v1prev = v1; v1 = v1prev + a1*deltaT; v1avg = (v1 + v1prev) /2; d = d + v1avg*deltaT; timeS = timeS + deltaT; if(v1avg>=6) a1=0; } d=0; //reset distance for William while(d <100) { v2prev = v2; v2 = v2prev + a2*deltaT; v2avg = (v2 + v2prev) /2; d = d + v2avg*deltaT; timeW = timeW + deltaT; if(v2avg>=7) a2=0; } nxtDisplayTextLine(1,"Steve: %0.3fsec",timeS); nxtDisplayTextLine(2,"William: %0.3fsec",timeW); } ________________________________ Then consider the more challenging situation where more than one peak has the lowest/highest values, and we want all the indexes of lowest and highest peaks. For example if, int mountains[]={6750,9145,4215,8395,7855,5070,4215, 9145,8705,5625}; then the highest peak (9145) occurs for mountain with index 1 and 7 task main() { int mountains[]={6750,9145,4215,8395,7855,5070,4215, 9145,8705,5625}; int i,low,high,lcount=0,hcount=0; int low_index[10],high_index[10]; low=mountains[0]; //initialize low to be the first element high=mountains[0]; //initialize high to be the first element for(i=1;i<=9;i++) // finding lowest and highest peaks { if(mountains[i]<low) low=mountains[i]; if(mountains[i]>high) high=mountains[i]; } for(i=0;i<=9;i++) // searching for all indexes that match the lowest and highest peaks { if(mountains[i]==low) { low_index[lcount]=i; lcount++; // increase low_index array 'index counter' } if(mountains[i]==high) { high_index[hcount]=i; hcount++; } } nxtDisplayTextLine(0,"Lowest peak= %dft",low); for(i=0;i<lcount;i++) //printing all the values of the low_index array nxtDisplayTextLine(i+1,"Peak Index= %d",low_index[i]); nxtDisplayTextLine(4,"Highest peak= %dft",high); for(i=0;i<hcount;i++) nxtDisplayTextLine(i+5,"Peak Index= %d",high_index[i]); } BISECTION FIND ROOTS float f(float x); float bisection(float x1,float x2,float epsilon); task main() {float b, a, root; float epsilon = 0.001; b = random(10); // guess one end of the interval a = b; while(f(a)*f(b) >=0) // guess second end until a=random(10); // it is on other side of x axis root = bisection(a, b, epsilon); // find the root nxtDisplayTextLine(3, "the root = %0.6f", root); } float f(float x) { float y; y = your function return y; } float bisection(float x1, float x2, float epsilon) { float mid; while(abs(x1-x2) > epsilon) { mid = 0.5*(x1+x2); if(f(mid)*f(x1) <0) // mid opposite x1 x2=mid; // then the new x2 else // otherwise mid is opp. x2 x1=mid; // change x1 {return (0.5*(x1+x2)); } MONTE CARLO INTEGRATION #define NUMDARTS 1000 float f(float x); // f(x)=sin(x)+2; float randomNum(float low, float hi); task main() { float x1 = 0; // lower bound float x2; // upper bound float y2 = 4.0; //y >f (x), 0…2*PI float x,y; float area;float ratio; int numDarts = 0; int numRed = 0; int numBlue = 0; x2 = 2 * PI; while (numDarts < NUMDARTS) {x = randomNum(x1,x2); y = randomNum(0,y2); if (y < f(x) numBlue++; else numRed++; numDarts++; } area = y2 * (x2-x1); ratio = (float)numBlue / numDarts; nxtDisplayTextLine(0, “intgrl is: %f”, area * ratio); } float f(float x) {float y; y = sin(x) + 2; return y;} float randomNum(float min, float max) { float num; int maxRandom = 512; num = random(maxRandom+1); num = (min + (max - min)*num/maxRandom); return(num); }