Friday, December 6, 2013

Simpleton Geek Teaches Computer Programming Book 2 ch 10



10. Branching
10.1 Don't use GOTO! Use it!
The students were still stinging from the last lesson. In truth, the students were hurting near every class session. This is because the teacher kept the lesson plan at high-strung level. Think of a waterfall being dumped onto the students. This day was no exception.
“Alright, class! It's obvious to me that your problem solving skills is near non-existent!” The teacher began with dismal performance report as usual. “Therefore, I decided that we should do something about it. Here is a piece of code that output some numbers. I want you to try to find some kind of pattern on it. Whatever it is, try to find it. Some degree of experimentation is necessary.” 
The last sentence was practically a death sentence to the students. They haven't been taught how to properly do experimentation. The lesson will come later, after grading session is over. The student trembled in fear. 
B=21
INPUT N
@LOOP
?N:WAIT 60
N=N*B+1%100
GOTO @LOOP
Inputting the program into the computer isn't a trouble at all. However, none of the students are able to find any discernable pattern whatsoever. The teacher isn't much help, either. “This exercise is to develop your pattern recognition skill! Therefore, I want you to concentrate deeply into the numbering sequence and tell me everything that you notice! Think of it as stream-of-consciousness exercise. You need to write everything that you're thinking. Do not leave anything out.”
“Must we write everything?” asked Nancy.
“There are certain things I'm looking for, and if I don't see them, then you'll get zero. Simple as that.”
The students redoubled their effort, but try as they may, they never did see a pattern forming. Even Peter couldn't do it. However, having seen the teacher after class on daily basis means that he will not give up. In desperation, Peter wrote: “No noticeable pattern except that the numbers are all between 0 and 99.”
He then wrote a simple program to count the numbers, and wrote “The numbers seem to go through the range 0-99 only once, yet completely. Furthermore, the numbers are repeated with the same sequence. Regardless of where the numbers started, it's always the same sequence.”
By that time, the teacher has sensed the students' frustration and he simply collected their papers. Most were blank. “What's the matter? Can't even write what you're thinking? That'll be zero for you!”
He paused at Peter's paper, though. “Same exact sequence, eh? Well, you're right about that. Ah, I see you actually wrote a program to tabulate the result. I think you deserve 100 points for that!” Peter was very happy, and his smile was very wide.
The rest of the students protested. “But teacher! You never said anything about writing another program!”
“True, that I did not. But remember that you need to analyze the numbers. If you cannot do it by hand,” he waved another blank piece of paper, “then, by all means, you should write a little program to help you. Don't be stupid!”
10.2 GOTO as CYOA Pages
“Okay, now who among you have made further progress about the observation exercise yesterday?” The teacher was commenting about total blank pages, being turned in. No student responded. Then Peter said, “If B is anything other than 21, the numbers don't fill the whole range.”
The teacher smiled. “Very astute observation. In fact, this is something that will trip most people. They simply do things without thinking it through. When you have a good solution, you need to find a better one! Therefore, some degree of experimentation is necessary.
“What you have done yesterday is something called 'Linear Congruent theory'. The idea is to have a certain number sequence that cannot be recognized as a pattern. In other words, a random sequence.”
All the students wailed in frustration. The teacher expected them to recognize random numbers? No wonder they couldn't do it!
“There are certain things you need to follow. I did modulus 100. In fact, that number should be as large as possible. I set B as 21. In fact, that number should be a large number ending with x21, with x being an even number. There are some choices there, but if you pick a bad number, then the whole number space would not be filled and you have a bad random number generator.”
The students weren't listening very well. They were still stuck at 'random'.
“If you notice, the sequence is repeatable. Therefore, the algorithm isn't exactly a random number generator, but a pseudo-random number generator. The numbers aren't really random, but repeatable given a certain seed.”
“But what good is it, if the numbers are repeatable?” asked a student. “Isn't this supposed to be random?”
“The repeatability is actually desirable because it mostly being used in simulating experiments, and if it has a surprising result, we want to be able to repeat the experiment, and therefore be able to observe the events in action.
“Now let's say we want to roll a six sided dice. Who can tell me what changes you need to do in order to get 0 to 5 random numbers?”
Nancy raised her hand, “Just divide by 6. So instead of %100, you just do %6! Easy.” The rest of the students didn't say anything. 
The teacher stamped Nancy's head. “Fail! Didn't I just tell you that you need to keep that number as high as possible? What is the matter with you? Can't even listen to your teacher?” He was staring at Nancy with great scary look. Nancy shrank in fear. “Anybody else?” No one else dare ventured a guess.
“Well, obviously, you take N and divide THAT with 6. So, something like this:”
D=N%6
“Therefore, you keep the original value of N, and will not restrict the range at all. Are you kidding me? You can't even see that?” All the students felt embarrassed. Such a simple solution! They should have thought of that.
“Anyway, let's move on. You actually don't need to go to the trouble of calculating the random number unless you want a pseudo random sequence. For normal use, simply use the command RND. Like this:
R=RND(6):'1 six sided dice
R=RND(6)+RND(6):'2 six sided dice
R=RND(100):'Percent dice  
“Let's do a quick show and tell. Who can tell me the snake and ladder game?” asked the teacher.
“It has 100 squares.” said a student.
“You roll a dice to move.”
“Snakes go down. Ladders go up.”
“You win if you reach the last square.”
“Great. I can see that although your pattern recognition skill is still non-existent, at least your show and tell skill is good enough. Now, who thinks they can design the program real quick? As in 5 minutes or less?” No students said anything or even moved. The teacher fumed. “Are you kidding me? Your understanding of it doesn't translate to programming skill? Unbelievable! You guys better take a piece of paper and do it now, or I'll fail all of you.” The students scrambled in panic.
REM SNAKES AND LADDERS
CLS:CLEAR
DIM SQ[150]:'100 SQUARES
DIM P[4]:'NUMBER OF PLAYERS
CP=0:'CURRENT PLAYER
'SNAKES/LADDERS
SQ[RND(80)+10]=RND(80)+10
SQ[RND(80)+10]=RND(80)+10
SQ[RND(80)+10]=RND(80)+10
SQ[RND(80)+10]=RND(80)+10
SQ[RND(80)+10]=RND(80)+10
SQ[RND(80)+10]=RND(80)+10

@LOOP
REM ROLL DICE
D=RND(6)
?”PLAYER “;CP;” ROLLS “;D
P[CP]=P[CP]+D
?”PLAYER “;CP;” MOVES TO SQUARE “;P[CP]
IF SQ[P[CP]]==0 GOTO @LOOP1
IF SQ[P[CP]]<P[CP] THEN ?”SNAKE! MOVE BACK TO “;SQ[P[CP]]
IF SQ[P[CP]]>P[CP] THEN ?”LADDER! MOVE UP TO “;SQ[P[CP]]
  IF SQ[P[CP]]==P[CP] THEN ?”WHEW! FALSE ALARM.”
P[CP]=SQ[P[CP]]
@LOOP1
REM WINNING CONDITION
IF P[CP]>99 THEN ?”PLAYER “;CP;” WINS”:GOTO @END
CP=(CP+1)%4
WAIT 60
GOTO @LOOP

@END
?”GAME OVER”
END
And that's all there is to it. Of course, there are several gotchas. The big one is that Snake/Ladder determination is done randomly, instead of manually. Also, array for the square greatly exceeded the 100 counts. What surprised the students the most, though, is the fact that the game is fully automatic. The player has no chance for input at all. All they do is watch the gameplay unfold before their eyes. They wouldn't have believed it if they didn't see it with their own eyes.
“So, I'm surprised at you guys. Don't you know how the game Snakes and Ladders play by now? Or perhaps you never played the game? Hmmmm?” teased the teacher.
The students were all just speechless!
“Okay guys, since you're all so pathetically stupid, I'm going to repeat the assignment from before. You remember the story telling program? Well, we're going to do it again. Of course, it's not fun if we're doing the exact same thing, so this time, we're going to do it using arrays. Oh, one more thing,” the teacher grinned evilly, “I want you to include the ability to calculate damages, so that it behaves like a simple Role Playing Game (RPG). And it would be nice to have it, so that you can play music and display graphics as well. It's completely optional, but at least there should be hooks into it.”
The students just slumped in resignation. One impossible assignment after another. Even when it's something they have already done, it's still a challenge. It's like a waterfall being dumped on their head. Sometimes, it can be too much.
“Come on, guys. What are you thinking?” The teacher was amused. “You do have notes from back then, right? Why don't you read that a bit?”
The student listlessly turned the pages back. Like sheeps to the slaughter. What difference does it make? They see that they have some things that are necessary. In fact, they realized, the requirements are only a few lines.
The students brightened. A bit. Just a bit, mind you, because the challenge is still great. Then they started thinking, and started to scribble the design anew. 
Just as they're getting good, the teacher threw down another challenge. “Oh, by the way. I forgot to mention. You want the whole top screen to display the page. The bottom screen is used to display the choices. We'll limit the choices to just 7. But you should set the array to 99, just in case. It's just that we won't be using it all.”
The student scribbled in the noted changes. But the teacher isn't finished, yet. “And, I want the user to be able to choose using the DPAD, and the touch screen. With the DPAD, you use button A to make the selection, whereas with the touch screen, you make the selection when the user LIFT UP their stylus, not when it's touching down like before.”
The students all looked up to the teacher. They don't know how to do it, since it wasn't taught to them.
“Now, I know I haven't taught you that skill, but as there is more than one way to do it, I'm sure you'll do just fine in researching the process. After all, there are only 4 different commands regarding touch screen. I'm sure you'll manage.”
Of course, every time the teacher said “You'll manage”, it has been proven that the students could not manage. Well, Peter could sometimes managed, but the rest of the students held no pretension that they can actually manage. It has been their experience that they will try to do their best. Fail, and have the teacher blame them for their incompetence.
The students looked at their teacher for guidance, but he non-chalantly just sit back and relax, and totally not saying anything. He put up his feet on the desk, which is not a teacherly way to do things. As he kept reminding the students: He's not a teacher, but a professional.
The students valiantly tried to do it, but obviously, they needed help. A few minutes before the bell rang, the teacher walked among the students to look over their work. He laughed at some students' work.
“Come on, guys, you can do better than that! Think of Snake and Ladder game. Every turn is the same. Well, on this project, every PAGE is the same! Do it as homework and show me tomorrow!”
10.3 Project: CYOA
GOTO isn't the culprit. It's the programmer. Spaghetti code exists because the computer programmer does not know how to properly use GOTO. The simplest form of GOTO is that of infinite loop. Once the program reached a certain point, simply use GOTO to the beginning of the program. Given enough breakpoints and states, you can actually write a program without having subroutines or functions.
The teacher looked at a few samples of the homework. It is obvious that although they somewhat know what to do, they still do not completely understand the process. As such, there are inefficiencies here and there. Therefore, the teacher decided to adopt “Top-Down” design principle.
“Alright, class, listen up! Do you think that just putting stuff up, and checking off items on your checklist is good enough? You need to think like the user! How would a user use your program? Once you do that, you write down the desired user experience. None of you wrote that, and very few of you actually got it. So, let's do that now. What does a user see in a CYOA program?”
“A title screen. And maybe music.”
“Text screen on top. Choices bottom.”
“Calculator option on data.”
“Pages of text for stories.”
The teacher listened to these things. “So, what happens if you have more than one screen of text?”
“Press 'A' to continue.”
“And how would you implement that? Option one, as a single choice on the bottom screen. Option two, as a pause button for multiple screen. Option three, scrolling text.”
“Which one is better?” asked the student.
“That is for you to try and find out. Each problem must be solved three times. That's how you get a good solution, a better solution, and the best solution.”
“But teacher,” said Nancy, “Why don't you just teach us the best solution?”
The teacher stamped her forehead immediately. “Fail! Didn't I just tell you that you need to find 3 different solutions? How else are you going to find out which one is the best solution if you do only one? Coming up with a good solution is not acceptable! You need to find the best solution possible. That means coming up with 3 different solutions to a problem! You never know which one is the best unless you try them all.”
Of course, the students didn't feel like solving a problem three times. Once is hard enough, thank you very much. Still, they fear the stamps more, so they kept quite on the subject. Only Peter, having been advised on the subject beforehand, nodded his head in approval.
“So, here are the major, overview steps in a CYOA program:”
@INIT
@LOOP
Load/Read Data
Text[P],Pages,Choices,Commands
Display Text[P] on top screen
Display Choices[P] on bottom
Highlight first choice
Wait for inputs
Process Input
Set new P
GOTO @LOOP
“Anybody know what a 'sand-boxing' technique is all about?” asked the teacher. “It's a way to build the code piecemeal so that you don't have to do everything all at once. So, I suggest creating an array for text on top screen, text on bottom screen, and the inputs.”
@INIT
T[0]=”Line of text 1”:'repeated for whole screen
C[0]=”Choice 1”:'repeated 7 times
@LOOP
'Display Text
'Display Choices
S=0: Selection Highlight
@INPUT
'Show Highlight
'Read button/touch screen
'Update S
'If choice is made, goto @PROC else GOTO @INPUT
@PROC
'Process commands
'Set P
'GOTO @LOOP
(See Appendix H)
As simple as that task was, some students were struggling. Especially in the highlighting selection area. The teacher had to explain the math, and after that no problem. Of course, the teacher expressed his displeasure at what he thought was a simple math problem. The students redoubled their effort. At last, even Nancy the perpetual slowpoke, managed to finish, albeit with a lot of help from her fellow students. By this time, the clock was nearing class end time. The teacher sighed.
“Well, for your homework, you need to do a story that will fit this format. That's 24 lines of text, first line title. I also want you to do some kind of calculation. Something like having gold and buying something. So, you substract the amount approriately. Tomorrow, we're going to integrate the calculator into the program. Right under this @PROC subroutine. Also, in addition to the arithmetic and memory bank operations (26 entries for a-z), I also want these operations as well:”
% Modulus aritmetic
< Given M & B, M copies the lower value
> Given M & B, M copies the higher value
# Comparison M<B=0,M==B=1,M>B=2
? B=RND(B)
! Copies B to S0
@ Copies B to PROC$ 
The bell rang. “Make sure you have good and varied story because you'll need it to test your calculator implementation!” The students felt sudden chill descending upon them.
The next day, the students was showing the teacher their incomplete stories. “Ha! Why are you so intent on writing long stories? I just want a simple one so you can test your programs. No need for plot. Also, you need to add a few more data fields in your stories:
1. @PRE code
2. Title Line
3. Story Text
4. Data Line
5. Choices
6. MACRO code
7. @POST code
“Here's a hint,” said the teacher. “You want to separate the code from the data. Also, you want to have a template that you can simply APPEND to existing story line. That way, you don't have to type everything all over again.” Half the students did face palm. “Furthermore,” the teacher continued, “You can initialize the data just before going to the pages. So, you don't have to have long stretches of blank lines in your story.”
Of course, the students were rather disorganized, and it took them the rest of the class period to successfully integrate the calculator function into the story engine. Yet, there are some students who were falling behind. Their homework was obvious: Test the code!
Interestingly enough, since the pages are simply BASIC code, it is a simple matter to integrate BASIC code right there in the pages. However, for convenience, there exists PRE$ and POST$ variables. The idea is that these subroutines would be called in sequence. First, the subroutine PRE$ would be called. Then the display is shown, and the program waits for user input from the choices available. Then any Macro would be executed. Macros, actually string to be fed into the calculator, are simply there for the programming challenged. Otherwise, a simple code implementation would be fine. Then subroutine POST$ would be called. Finally, the program would GOTO to the specified subroutine, and repeat the whole process all over again. 
Fortunately, the addition of the calculator makes it easy to “program” the game. To be honest, the students all have the skills to write the program in BASIC code. However, as an introduction of virtual computer programming, this is as easy as can be. Furthermore, the resulting program will be of wider audience due to the lack of “programming”. In fact, all the calculations are actually optional. There's no rule that says an interactive story must contain calculations. Should that be desired, however, the writer can simply pull a “calculator” and enter the steps (or macro) to the appropriate string in the template.
The reason there's more choice than what is displayed isn't so that the display can be scrolled, but rather for the purpose of decision making. There is a comparison operator, and it will result in 0,1, or 2. This value can then be added to an index, and the appropriate page can be called.
Some students have difficulties in understanding the process involved. That's why it is recommended for them to implement a stand-alone calculator so they can play with it and understand the internals. Of course, the register contents should be displayed as well as the keystroke sequences.
And yet, since this is actually code, the whole power of Petit Computer can be called upon. In fact, you can write a complete game within the framework. Such is the power of this program.
As simple as it is, the program is actually useful. It would be even more useful, had the graphic display capability is implemented, as well as music capability. Although loading up graphic is as simple as “LOAD” command, the required bitmap does take a lot of space, as well as taking a long time to scan the numerous QR codes.
All the students' hard work paid off, though, because in the end, they did have fun in making stories to play. In fact, some students made a habit of expanding their adventure one screen per day. For them, the teacher recommends writing in the notebook all the pages, those that are planned, and those that are implemented. Easily enough done. And before they know it, some actually ended up with a long and enjoyable story.
“Well, that was unexpected,” said the teacher.
“What was?” asked the student.
“That everything went so well! I'd have expected some hiccups. I was ready to whack some heads, but you all did a good job.” The students were happy. Not only they were learning and actually doing something, but they were actually did very well. “Too bad none of this is graded. There would have been a lot of As going on.”
“What? Not graded?” The students were disappointed. They could've had some easy high scores.
“I didn't think it'll come together as neatly and easily as this, so I was planning to do it later. After all, why bother grading it if you're just going to do bad on it? Oh, well, I guess I should've prepared for this unexpected performance!”
Of course, the students were disappointed, but they cannot say anything. What was done cannot be undone. “Can't you create a quiz or something?”
“Like what? Everything is just about review. You already did the story engine, and the calculator. The only thing you do new would be the stories! And well, it won't do when the story is done before the grading was done. Also, it won't do for you to make new stories because it's going to take a long time, and we need to move on.
“Understand that the current program is as good as can be. In fact, better than most amateur effort. However, we're going to improve it even better. Next thing on our agenda would be learning graphics. You like making computer games, right? Well, don't expect to be stuck in text only program!”
“Will we be making Mario games?” asked a student.
“Mario games encompass such a diverse gameplay, so you need to be specific. If you're asking about platformers, then not immediately. I'm thinking more about Turtle Graphics, since it's so easy to do, and then moving on to Backgrounds and Sprites. You'll love the sprite manipulation capabilities on Petit Computer. It's so powerful, you can make quite a lot of sprite-based games simply by setting a few variables. Just like you did in your interactive stories. It's that easy!”
The students were happy. “So, what kind of games will we be making?”
“Lots. But examples of sprite based games would be PONG, Breakout, Galaga, Space Invader, most shoot-em up, and scrollers.”
The students were unfamiliar with the games. These games were before their time. 
“Never mind. You'll see it when the time comes. In the meantime, you'll be making programming tools. Remember that we just made a programming tools for making interactive stories?” The students nodded. “Well, we'll be making tools for making sprite-based games.”
“Teacher, why do we have to make all these tools? Doesn't Petit Computer come with tools already? Why must we made them all over again?” asked Nancy the perpetual whiner.
“Fail! Oh, did I just stamped your head?” He did. “I guess I didn't have to. Must be force of habit.” Nancy was just about to cry. “Never mind that! See, the thing about those tools is that they were already made for you. Certainly you can look through them to see what made them tick, but as long as you are learning how to program the computers, you need to design and implement your own tools. It's the best way to learn!”
The students weren't convinced that's a good solution, but as they were the students, they really didn't have any choice.
10.4 Computer as Data Storage
Peter was consulting with teacher in the office afterschool, per usual. “The way I see it, the program is about 120 lines, but the data is in thousands! That's rather unbelievable!”
“What do you mean 'unbelievable'?” The teacher frowned. “What kind of ratio do you expect?”
“Well, I don't know.” Peter was scrambling. “I would think that computer programs would take longer than 120 lines for it to be good.”
“Ha! That shows how much you know. What kind of computer programs are you looking at anyway?” the teacher sneered.
“Well, I was looking at those computer program repositories. Github and others like it.”
“Oh, that. Well, first of all, most computer language are structured. Half the program size can be eliminated if you don't have to follow such a strict structure! And the other half, well, it boils down to implementation. People are so focused on using fancy techniques that their size is larger than it needs to be.”
“Shouldn't fancy techniques be advanced? Meaning it should be more powerful, which should lead to smaller size?”
“Nope. Not really. If you look at object-oriented technique, there's constructors, destructors, try, and all that. Of course, methods got it's own lines and all. The more functions you have, the more space you use. If you look at our program, we don't use too many subroutines.”
Peter nodded his understanding.
“We're using string as look-up table. Python would use list or tuples. Why would we want that? A simple table would be fine. In fact, there's a saying 'Show me your code and hide me your tables, and I'll continue to be mystified. Show me your tables, and I don't need your code. They'll be obvious.'”
“Who said that?” asked Peter.
“Pascal inventor. Nicholas Wirth.” 
“Oh, so Pascal uses tables?”
“Nah, it's all so structured! The point is that with the correct problem solving approach, the solution can be simple. In fact, that is the approach that Perl uses. I bet this program can be even shorter when written in Perl!”
“Really?”
“Yup. Not that you'll be able to read it afterwards. Gya ha ha ha!”
The joke was lost on Peter, who never bothered to learn Perl. “So, then, you can handle large quantities of data with just a small program?” asked Peter.
“Of course. By the way, you know how big current games are?”
“They're rather big. Most program runs in Megabytes.”
“The graphic library alone can be 5 Megabytes. Unbelievable! We'll be doing something similar, but will only be a couple pages long. Now imagine, if we're using it to render complex graphic. The amount of data it processes would be quite large. It can even be in Mega or Terabytes in size. Yet, the program itself would still be the same size.”
“That's true. Can such program be really that short?”
“I've done Turtle Graphic programming in one hour.”
“You mean, actually programming it? Not just using it?” asked Peter. How can implementing it be a one hour exercise?
“Of course, programming it. You don't think you'll be learning LOGO, do you? Anyway, turtle programming design is only one paragraph. You'll be able to do it easy. In fact, maybe I should do it as an exam! Gya ha ha ha!”

Tuesday, November 26, 2013

Simpleton Geek Teaches Computer Programming Book 2 Ch 9D


9.4 The first significant program
“Well,” the teacher said. “It's good that you have it. Too bad that you didn't get it early enough to get points for it. What took you so long, anyway?”
Peter was in the teacher's office, reviewing the day's event as usual. Though he expected some other students to show up, nobody else showed up.
“Well,” Peter said carefully, “I guess it's the fact that parsing is such a difficult subject that I gave up immediately. It's not until I see that there really is no parsing involved that I understood the difficulty of the problem.”
“Which is?”
“Pulling one character off a string at a time, until the string becomes empty.”
“Is that a hard problem?”
“Not really.” Peter said, “I mean, it's not that easy. I'm still grasping the concept of string manipulation. But once I realize that you took a detour in explaining string operation, I knew that the knowledge is necessary to solve this problem, and I did some trial and error programming to try to understand it.”
“Ah, that's why it took you a long time. Had you done your homework properly and did the trial and error at home, you would have made it.”
“It's possible that it's true.” Peter acknowledged the possibility.
“You see, when you are faced with insurmountable problem, the first thing you did was to seek guidance. In this case, me, your teacher.”
“There's nothing wrong with that. Isn't that what school is all about?” asked Peter.
“Academia, maybe, but remember, I'm a professional. What would a professional do in such instances? Give up? Go back to school?”
“I guess not.”
“Then what would you do if you're a professional?”
Peter thought about it for awhile. “I guess, I'll be doing what I just did today.”
“Which was?”
“Just do my best in understanding the problem. Try as many solution as possible and see if I can solve the problem.”
“In fact, that is what professionals would do. And what everybody should do. The thing is, this is a school. Therefore, you know that you CAN solve the problem. The only question is how.
“Unfortunately, in the real world, that's not necessarily true. There are many problems in the real world that has no guarantee of having a solution at all. It may be one of those impossible problem. Do you understand?”
“I guess so.” said Peter. “I guess in that instance, it's okay for you not to solve the problem.”
“Well, there is a standard that we all have to adhere to. It's not okay to say that the problem is unsolvable. You have to provide PROOF that the problem is unsolvable. Otherwise, everybody can say that they worked on the problem. No standard.
“The most important thing,” the teacher continued, “is not that you actually solve the problem. But that you do enough work to see how close you can get to solve the problem. In the end, either you prove that the problem is an impossible problem, or you solve the problem.”
Peter thought for a while. “I guess next time I ran into a impossible problem, I have to show that it is impossible.”
“That's all I ask.” said the teacher.

Simpleton Geek Teaches Computer Programming Book 2 Ch 9C


9.3 Strings
“Alright, everybody! Show me what you have!”. With that opening statement, the class began. The teacher have them filled this table:
L0 D C D C
L1 D D C C
A A A=AopB A A=AopB
B B=(B*10)+C B C B
C D 0 D 0
OP OP op OP op
What that table means is that L0 and L1 denote the type of commands that is entered. D for digits and C for aritmetic operation. L0 is the last keypress, while L1 is the previous keypress (what was previously L0). A,B,C stands for variables, where A and B are variables for calculation and C is the digit being entered. OP is the variable holding the aritmetic operator, where 'op' lowercase is the actual operator.
“Now, that you have learned string operation, L0 and L1 are a piece of cake!” said the teacher. “Here is the modified main program. You see how simple this can be.”
REM CALCULATOR
CLS:CLEAR
DIM OP$[5]
@INIT
A=0:B=0:C=0:OP=0
OP$[0]=”NOP”:OP$[1]=”ADD”
OP$[2]=”SUB”:OP$[3]=”MUL”
OP$[4]=”DIV”
L0=0:L1=0

@MAIN
VSYNC 1:CLS
?”A= “;A:?”B= “;B:?”C= “;C
?”OP= “;OP$[OP]
?”L0= “;L0”?”L1= “;L1
@MAIN1
CH$=INKEY$:IF CH$==”” GOTO @MAIN1
IF CH$==”C” GOTO @INIT
IF CH$==”E” THEN B=0:GOTO @MAIN
L1=L0:L0=0:'0=D,1=C
IF INSTR(“0123456789”,CH$)<0 THEN L0=1
ON (L1*2+L0) GOTO @ADD,@ADC,@ACD,@ACC
@ADD
GOTO @MAIN
@ADC
GOTO @MAIN
@ACD
GOTO @MAIN
@ACC
GOTO @MAIN
“And there you go. All you have to do is fill in the blanks. Now that you have all the table set up, it's easy! Of course, if you fill in the table wrong, then you will have trouble doing it. Do you understand now why I'm not grading your homework? I'd rather see you suffer all the bugs you yourself created!
“And then I will see you try to overcome the bugs. The way you approach your debugging will reveal your character. If you blame yourself, then you'll be alright. If you blame the tool, then you will never make it! Gya ha ha ha!”
@ADD
C=INSTR(“0123456789”,CH$)
B=(B*10)+C
GOTO @MAIN
@ADC
IF OP==0 THEN A=B
IF OP==1 THEN A=A+B
IF OP==2 THEN A=A-B
IF OP==3 THEN A=A*B
IF OP==4 THEN A=A/B
C=0
IF INSTR(“=+-*/”,CH$)>0 THEN OP=INSTR(“=+-*/”,CH$)
GOTO @MAIN
@ACD
C=INSTR(“0123456789”,CH$)
B=C
GOTO @MAIN
@ACC
GOTO @ADC
GOTO @MAIN
Filling the routines then becomes a simple exercise. The students need to be careful regarding some order or execution, but otherwise, it's not a problem. The problem, of course, is in design, and with bad design, comes bad program. Peter, the smart one in the class, has actually programmed in the routines just to be sure what he has actually works. In fact, that's the best way to do it. The other students, being beginners, never thought to do it that way. They still think that coding remains the most difficult phase of computer programming.
The whole process of filling in data takes less than 10 minutes. Testing, of course, takes longer. One by one, however, the students finally managed to get their program going. There are two special commands involved: All Clear (AC) and Clear Entry (CE). These corresponded with character 'C' and 'E' respectively. If you see the code, they are very simple. 'C' will simply shuffle the program execution to @INIT function, whereas 'E' will simply reset B to 0.
“Alright.” the teacher said. “Now that everybody got it, the next step is to create a graphical calculator. Now, don't worry about it because it doesn't involve anything you haven't done. In fact, if you remember your piano playing program, then it's the same exact thing. The only thing different is the key or button arrangement. So, what I want you to do now is to draw some character text on screen and shape that as calculators. So, get out your journal and start drawing!
“Remember, program design starts on paper! Those of you who tries to shortcut the step will find out that the whole process will take 2 to 3 times longer. If you don't believe me, just try it! Gya ha ha ha!”
The students dutifully drew the design on their journal. A 4 by 4 design emerged. In the end, there was no place to put the equal sign command, and the function is placed on the display instead. The final code is listed in Appendix G.
And so it goes. The students finally managed to draw a rough draft of the calculator, and it did start to look like a real calculator. Certainly there are some features that are missing, and some of the calculation behavior isn't quite right, but these are just little nits. The fact is, even beginning students are perfectly capable of doing a calculator program that is not dependent upon INPUT commands.
“Right, guys. Now for homework, I want you to think very carefully about how strings work because I will take the character patterns away from you. You will have to use character arrays for your on-screen keyboard input.”
The students all moaned their displeasure.
The teacher banged on their desk. “What's this? You're all complaining on such a little task? Well, well, why don't I add this to your homework, then: Memory button. Remember, you have 4 different operations on it. Memory Add, Memory Clear, Memory Reset, and Memory Substract.”
The students regretted their outburst already, but the teacher isn't finished yet. “Come to think of it, that's still too easy. So, not only you will have to come up with 8 memory banks, but also a way to read a script so you can do the operation automatically.”
“Teacher, what do you mean a 'script'?” asked a student.
“What I mean is that you have automatic input. Coming from a string. You need to parse the string and automatically give the answer.”
Peter raised his hand. “Parse the string? Isn't parsing a difficult thing to do? As in Graduate Student level?”
The teacher waved his hand, dismissing Peter's concern. “Nah. I learned it in College Senior level. So, should be fine.”
All the students looked at one another. College Level? Yikes! What kind of trouble have their teacher got them into? They couldn't believe it!
“Will this be graded?” asked Peter. There is hope yet at salvation.
“Of course. If you managed to do this, you will be amply rewarded.” The teacher nodded his head. “Of course, if you fail miserably, then you will be severely punished, considering that it will have the highest scoring criteria. So, good luck on working on that problem. Gya ha ha ha!” The bell rang, and there's nothing more to say on the subject.
On the next day, the students compared their notes. The first criteria turns out to be easy. Instead of using PRINT and CHKCHR, the solution is simply use a string array instead of PRINT for the row, and use MID$ for the column. That's it. It's very trivial to do.
The second solution is a bit harder. However, the AC/CE button provided a hint on the solution. It's a simple matter to just add more command to it. The most important function is READ/WRITE command equivalent. What about this 8 bank memory? Another array solves the problem. Simply by setting aside 8 characters for each bank, the memory bank problem is trivially solved. What remains are the task of Memory Add, Sub, Read, and Clear. An extension of AC/CE buttons solved that one also.
Of course, the students only had so much time in a day, and they were unable to solve the last problem. Parsing! A whole book can, and have been, written on the subject. In the end, they gave up and on the next day, they entered the class with fear, just waiting for the hammer to fall.
There was nothing they could do. How can mere high school students compete with University Level students? How can they, as beginner, do what 4 year college students are expected to do? Impossible!
Of course, this doesn't sit well with the teacher. “What do you mean you have no idea what to do? Well, well, it's lucky that I have my favorite stamp with me, today.” The students coiled in terror!
“So everybody got the first problem? Of course, it only scored 5 points. That's so easy. All you have to do is create a string array, and then check against it. Like this:”
DIM SC$[25]
@DIS
CLS:PNLTYPE “OFF”
SC$[0]=”====================”
SC$[1]=SC$[0]:SC$[2]=SC$[0]
SC$[3]=”111112222233333+++++”
SC$[4]=SC$[3]:SC$[5]=SC$[3]:SC$[6]=3:SC$[7]=3
SC$[8]=”444445555566666-----”
and so on...
'Checking
CH$=MID$(SC$[TCHY/8],TCHX/8,1)
For memory bank problem, simply set aside a memory array. Then set some keys to select them. “C” and “E” are taken, but “a”-”h” are not. As for Memory key operations, “M”-”P” are available. This simply lends itself to this implementation:
DIM MM[8]:'MEMORY BANK STORAGE
MI=0:'MEMORY BANK INDEX

IF INSTR('abcdefgh',CH$)>=0 THEN MI=INSTR('abcdefgh',CH$):GOTO MAIN
IF CH$==”M” THEN MM[MI]=MM[MI]+B:GOTO @MAIN
IF CH$==”N” THEN MM[MI]=MM[MI]-B:GOTO @MAIN
IF CH$==”M” THEN MM[MI]=0:GOTO @MAIN
IF CH$==”M” THEN B=MM[MI]:GOTO @MAIN
IF CH$==”C” GOTO @INIT
“Does everybody got that? They are all so easy, if you cannot do it, you should be ashamed of yourself! Well, now that you've got 15 points out of 100, ready to get the other 85 points?” the teacher asked. Of course, this is where none of the students have any solution whatsoever. The teacher gleefully put 15 points for everybody. “What a bunch of losers! Gya ha ha ha!”
All the students are just so frustrated. They simply do not know what to do. Instead of resuming teaching, however, the teacher simply went back to his desk, put his feet up, and went to sleep. Snoozing. At first, the student were patiently waiting for the teacher to wake up. After a while, it's clear that the students are left to fend for themselves.
None of the students know what to do. Some started doodling. Others decided to take a snooze as well. Only Peter was alert. He knew that the teacher did this for a reason. What could that be?
What was the assignment? To have automated entry? That's parsing. Parsing is difficult. But since the teacher said that it isn't impossible, that means it's possible, and within the limits of the lectures so far. So, how can that be?
It was not after Peter stared at the problem for 20 minutes that he looked at this line one more time:
CH$=MID$(SC$[TCHY/8],TCHX/8,1)
The key isn't in TCHX/TCHY. The key is in CH$! That's one single character. What's a single character? LEFT$(S$,1). If he can find a way to pull a single character each time...
IS$=”1+2+3+4+5=”
@LOOP
IF LEN(I$) THEN CH$=LEFT$(IS$,1) ELSE END
IS$=RIGHT$(IS$,LEN(IS$)-1)
?CH$:GOTO @LOOP
Peter confidently raised his hand. “Teacher! I got it!” All the rest of the students couldn't believe it!

Simpleton Geek Teaches Computer Programming Book 2 Ch 9B


9.2 Arithmetic: Add, sub, mul,div,mod
The students were all sitting in their seats. The teacher was standing in front of the blackboard. “Today, we are going to teach the computer how to calculate! That means addition, substraction, multiplication, division, and maybe even some modular arithmetic.”
The students were confused. “Didn't we learn all that before?”
“Hey, what did I tell you about more than one way of doing things? Have you forgotten that already?” The students kept silent.
“Alright, take a look of this program. You see three variables, A, B and C. Furthermore, there's another variable. This one denotes the arithmetic operator. That's add, substract, multiply, and divide.”
REM CALCULATOR
CLS:CLEAR
DIM OP$[5]
@INIT
A=0:B=0:C=0
OP=0
OP$[0]=”NOP”:OP$[1]=”ADD”
OP$[2]=”SUB”:OP$[3]=”MUL”
OP$[4]=”DIV”

@MAIN
CLS
?”A= “;A:?”B= “;B:?”C= “;C
?”OP= “;OP$[OP]:?
?”MAIN MENU”
?”1. INPUT A”
?”2. INPUT B”
?”3. SET OP TO ADD”
?”4. SET OP TO SUB”
?”5. SET OP TO MULTIPLY”
?”6. SET OP TO DIVIDE”
?”7. CALCULATE”
?”WHICH?”
LINPUT CH$:CH=(VAL(CH$))%8
ON CH GOTO @NOP,@STA,@STB,@ADD,@SUB,@MUL,@DIV,@CAL
@NOP
GOTO @MAINEND
@STA
GOTO @MAINEND
@STB
GOTO @MAINEND
@ADD
GOTO @MAINEND
@SUB
GOTO @MAINEND
@MUL
GOTO @MAINEND
@DIV
GOTO @MAINEND
@CAL
GOTO @MAINEND
@MAINEND
GOTO @MAIN
“There's the main structure of the program. All you have to do is fill in the blanks. You have 10 minutes! Go do it!”
The students went all panicky, but quickly entered the program. 10 minutes later, a few struggling students got their heads whacked by the teacher. Most, however, managed to finish the program. It's all very easy:
@NOP: OP=0
@STA: INPUT A
@STB: INPUT B
@ADD: OP=1
@SUB: OP=2
@MUL: OP=3
@DIV: OP=4
@CAL:IF OP==1 THEN C=A+B
IF OP==2 THEN C=A-B
IF OP==3 THEN C=A*B
IF OP==4 THEN C=A/B
The students tried out their program. All managed to have the program running correctly. It's all very easy. It's just a question of how quickly you can get the program running. The teacher then compared their program with the existing one provided as a sample demo (SAMPLE2) program.
“Now, count the number of lines, which one is shorter? How about convenience? Would you like to enter the numbers repeatedly or would you like to just enter the numbers once? You already know how long it takes you to do this. How long do you think it takes them to do this? One more thing. I want you to draw the tables of operations in your journal. Not that I'll be grading this since this is so easy! Gya ha ha ha!”
“As you notice, this is where most people stop working. Once you have the functionalities of a calculator, they simply stop programming and move on to another program. Well, that's not good enough! We want to have a program that is not only works as expected, but also easy and convenient to use! Therefore, you are going to learn how to do a calculator, like a real calculator. Notice that there is no 'INPUT A' or 'INPUT B' on the calculator. So, we're going to do the same. We will simply concentrate on the buttons, and see if we can duplicate the interface. That means INKEY$.
“Now, if you first begin using the calculator, everything is zero. When you press the operator button, just assign the operator. Simple enough. If you press the equal sign button, that means calculate. Also simple. But what happens when you press the number button? There are different responses.
1. Add the number to the display
2. Clear the display and show the number.
“That's right. 2 different actions, depending upon whether or not you are simply adding digits to the number or you are inputting a new number. So, can anyone tell me the difference?”
The student were listening intently to the lecture, and expected the teacher to tell them the difference. They simply didn't expect to solve the problem by themselves.
All was quite. What would be the difference between adding a digit and inputting new number? Finally, Peter raised his hand. “You add a new number after an operator.” The teacher smiled.
“You got it! It's so simple, isn't it? Take a look at this: 23*45+67. You reset the display when the last key was an operator. What does that mean in our program? We set a flag to clear the display when the last key was an operator. That's it! Now, modify the program so that instead of INPUT, we use INKEY$. Also see if you can do automatic calculation whenever we press any of the four arithmetical operators!”
@INIT
L=0:'0 NORMAL, 1-CLEAR DISP

@MAIN
VSYNC 1:CLS
?”A= “;A:?”B= “;B:?”C= “;C
?”L= “;L:?”OP= “;OP$[OP]:?
@MAIN1
C=0:CH$=INKEY$:IF CH$=”” GOTO @MAIN1
IF CH$==”+” THEN L=1:GOTO @ADD
IF CH$==”-” THEN L=1:GOTO @SUB
IF CH$==”*” THEN L=1:GOTO @MUL
IF CH$==”/” THEN L=1:GOTO @DIV
IF CH$==”=” THEN L=1:GOTO @CAL
C=VAL(CH$)
IF L==1 THEN A=B:B=C
IF L==0 THEN B=B*10+C
L=0
GOTO @MAIN

@CAL:IF OP==1 THEN B=A+B
IF OP==2 THEN B=A-B
IF OP==3 THEN B=A*B
IF OP==4 THEN B=A/B
GOTO @MAIN
“You see we do not do anything different in algorithmic sense. Everything is still the same. Later on, I'll show you a bit more advance knowledge. Now get to it! you have 15 minutes!”
After all the students finished the program and tested it to their satisfaction, the teacher pointed out that their program is actually a poorly designed one.
“You can see, after all, that you need to press equal sign everytime you want to calculate. If you look at the regular calculator, then you see that it calculates automatically after every calculation. So, in that sense, your program works as designed. No one can say that your program is buggy, because it's not. It performs as designed. The program isn't bad, it's the design that is bad!
“So, for your next project, you want to duplicate the function of regular calculator as close as possible. I'll tell you right now that your program must be thrown away and you need to build the new program from scratch!”
All the students moaned in disappointment. “Teacher, why must we rebuild the whole thing? Can't we just modify the existing program?”
“Anything is possible.” said the teacher. “It's just a question of time and money. Sometimes the core (the main program flow) is so different, that it's easier and faster to just do the whole program from scratch. The thing is, sometimes you have gone down the wrong path so far, that you need to redo the whole thing.”
All the students aren't convinced at all. That's just double the work! All that work for nothing!
“Here's the key: You cannot just throw existing program willy-nilly. You must first understand what the problem is, what your solution is, and what your plan is going to be. Once you have those, then you can make the decision whether starting from scratch is the right thing to do. Since I have done the work already, I KNEW that starting from scratch is the right thing to do. So, do your homework!”
“But before that, I want to teach you something really quick: STRING. That is string variables and what you can do with it. Now, you already know what string is. You've been using it with LINPUT, so you have the basic understanding of what it is already. That's why I'm confident that the 15 minutes of class time that we have left is more than sufficient to teach you everything you need to know about strings.”
The teacher then smiled, “Of course, if it turns out that you haven't been doing your homework, and that your understanding of string variables is faulty, then you will be clueless and will not be able to do your homework properly. But in that case, it's your fault! Gya ha ha ha!”
The students are all scared and confused. Learning a whole new concept in 15 minutes? Is that even possible? But since there's no time left on the clock, the students don't have any choice but to go along with the lesson.
“Now, tell me what you know about string.” the teacher started.
“Strings are variables that has value between two quotes.”
“Great. Now let's say there's a string with the value: 'HELLO AND GOODBYE'. Now I want you to tell me the following:
1. The length of the string.
2. The first 5 characters of the string
3. The last 3 characters of the string
4. The string from 7 to 9 position
5. Finding the position of substring “GOOD”
6. Finding the position of substring “END”
“That's should be enough for now. In fact, it's so easy, I don't have to say anything other than it's all described on Help page #32. So get to it! I'll be scoring your work this time around. After all, there's nothing better to make the students fail the quiz than giving precious little time to do it. Gya ha ha ha!”
All the students moaned and get to work immediately. In fact, the answers are all obvious. It's just straight implementation of the commands in help page.
1. LEN(“HELLO AND GOODBYE”)
2. LEFT$(“HELLO AND GOODBYE”,5)
3. RIGHT$(“HELLO AND GOODBYE”,3)
4. MID$(“HELLO AND GOODBYE”,7,3)
5. INSTR(“HELLO AND GOODBYE”,“GOOD”)
6. INSTR(“HELLO AND GOODBYE”,“END”)
The students barely managed to type those into the computer, just to make sure that they have it correct. Of course, smart students would put C$=”HELLO AND GOODBYE”, and use C$ as the variable inside the commands. Doing it that way certainly saved quite a lot of time.
Some of the students actually managed to miss the instruction. Typing 'AND' instead of 'END' for example. Others still didn't follow the instructions too closely and switch MID$, LEFT$, and RIGHT$ in various orders. With predictable bad scores on the quiz.
Just because there's basic understanding on how string works, does not mean the students can just ignore the tasks presented in front of them. They still have to pay attention to details.
“Time's up! Let's see those papers! For homework, I want you to fill in this table. Make sure to do this properly. It is of the utmost importance that you do it right!”
“The grading is that important?” asked a student.
“Oh, I'm not grading it. If you do it wrong, you will certainly suffer greatly tomorrow. Gya ha ha ha!”