labs

Lab 11: Edge Detection

posted Dec 19, 2012, 5:56 AM by Samuel Konstantinovich   [ updated Dec 20, 2012, 10:10 AM ]

Critical: You should add this lab to lab 10, so that you reuse the image loading features.

Edge Detection overview: A pixel of an image is considered an 'edge' if there are vastly different shades of colors on either side of the patch. We will just look at the brightness of the patches for this (the ones digit) 

Whenever the term "brightness" is used, we are talking about the ones place. The brightness of the color 52 is just 2. The brightness of the color 97 is 7.

Simple EdgeDetect algorithm: 
1. Patches will have a variable edge_value
2. For all patches:
   Calculate the brightness difference by subtracting the brightness from the patch on the left from the patch on the right. Then take the absolute value this is the edge_value. The bigger this number the more likely it is an edge. 
3. For all patches:
   If the edge_value > some sensitivity value (slider from 0 to 10) then change the patch to black (it is an edge) otherwise make it white.  


BetterEdgeDetect:
1. Same as before
2. Average the up/down and left/right brightness difference (see step 2 from above). If the up/down difference is 2, and the left/right difference is 8, make the edge value 5 (the average of 2 and 8 is 5).
3. Same as before

ShadedEdges:
1,2: Same as before
3. Set the pcolor to the edge_value

Challenge: Reverse the black/white on shadedEdges, remember that numbers ending in 0 are hard to reverse. 

Lab 10 : Image Processing Program

posted Dec 18, 2012, 6:08 AM by Samuel Konstantinovich   [ updated Dec 18, 2012, 6:08 AM ]

Your goal: To make a image manipulation program

Reminder: A button should call a single function. If your button has more than 1 command in it, you did something wrong! 

Features of the Image Processing Program: 
note: you should choose your image, and adjust your patch size appropriately. No NSFW images, and you want at least a 50x50 screen size.

(each of the numbers 1-6 requires at least a button, some require an input field or slider)
(Warmup 1-3, to make sure you can load images and do basic operations)

1a. Load any file by name. You need a "load file" button, just like yesterday's demo.
1b. You must add a string 'input' box so you can type any file name to load. 

2. A grayscale button that removes color from the patches.

3. A reset button that reverts the patches to the last image loaded. Just like yesterday's demo.

(4-6 is more challenging)

4. A 'make darker' button, that calls a function that reduces the brightness of all patches as follows:
   Any color has its one's digit reduced by half. e.g. A pcolor of 46 becomes 43 (the 6 is cut in half), a pcolor of 95 becomes 92.5 (the 5 is cut in half)

5. A 'color reverse' button that inverts the darkness level of all patches as follows:
  1 becomes 9, 
  2 becomes 8, 
  1.5 becomes 8.5 etc. 
This can be accomplished by looking at the difference between a color's last digit and 5, then subtracting twice that result. 
E.G. 
If the color is 12, 2-5 is -3 , so you subtract twice that from 12. So 12 - 2*(-3) so it becomes 12+ 6 or 18.
If the color is 49, 9-5 is 4, so you subtract twice that from 49. You get 49 - 2 *  (4)   or 49-8 which is 41.
If the color is 0.1, (0.1 - 5) is -4.9 ,    0.5 - 2 * (-4.9) is   0.1 + 9.8, which is 9.9.

6. Create at least one more image filter that you come up with. Name It  "myFilter" , and make a button for it. 
Ideas: use sliders to adjust how much your button works, 
(note: I already gave sample code for some, so you cannot count those)

Lab 09 : Conway

posted Dec 18, 2012, 5:30 AM by Samuel Konstantinovich   [ updated Dec 21, 2012, 5:27 AM ]

Conway's Game of Life


Overview:

Each patch does one of two things (never do both):

Living cells: check if you stay alive or die.

Dead cells: check if you stay dead or come alive.


Rules :

1. living cells stay alive when there are 2 or 3 living neighbors, (die otherwise)
2. dead cells born (come to life) when there are 3 living neighbors (stay dead otherwise)


We abbreviate this rule as follows

S: 2, 3 (stay alive)

B: 3 (born)


Now you can make a Conway simulation to follow these rules:

1. Your setup should make a % of the patches alive randomly. We will use any color to be alive, and black to represent dead. (It would be nice to make a reporter function alive? As it would make your code very readable)

2. The function you will repeat forever should do two steps just like voting. Calculate the next state( counting your neighbors) , and change states(running the livingRules or the deadRules.

*Just like before you can store the next color, or you can store the counted neighbors) Use the rules defined above to decide what to do.

Make it better!

3. Add a slider to change the starting % of living patches in your setup.

4. Make patches that stay alive longer change to brighter colors. Try to start newly born cells at any color ending in 4 and go up by 1 every time it stays alive until it ends in 9, then just stay ending in 9 until you die. (e.g. start at 24 and go up to 30) If you do this, it really helps to have a reporter function (alive?) to use on a patch.


At this point you should have had the basic algorithm. Your code should have had a structure like this:

(the livestuff/deadstuff would be different in these two versions)

to go 

  ask patches [ counting ] ;separate the counting part from the changing part

  ask patches [ changeBasedOnCount]; look at the count and change your color based on the rules

end


to changeBasedOnCount

  ifelse alive? [ liveStuff ] [ deadStuff] ;separate the living/dead code so you cant do both

end

OR YOU CAN DO IT THIS WAY: (the livestuff/deadstuff would be different in these two versions)

to go 

  ask patches [ pickNextColor] ;decide what color to be, based on the neighbors

  ask patches [ changeColor] ;set the color to that color

end


to pickNextColor

  ifelse alive? [ liveStuff ] [ deadStuff] ;separate the living/dead code so you cant do both

end

Lab 08 - Cars and Pedestrians + Solutions

posted Dec 5, 2012, 6:26 AM by Samuel Konstantinovich   [ updated Dec 21, 2012, 5:26 AM ]

You will want to use new concepts: (I would not give you these hints on a test)

Concept 1: Talking to the turtles that are on the same patch as you:
turtles-here is the agent set of all turtles located on the same patch as the turtle that uses it. This can be used in turtle context, and it DOES INCLUDE YOURSELF unless you specify otherwise:
ask turtles-here [ commands ]

ask turtles-here [set size 3] ;everyone including myself 

OR you can reduce the agentset more using 'with'

ask turtles-here with [ boolean ] [commands]

ask turtles-here with [color = yellow] [commands]

OPTIONAL: ask other turtles-here [set size 3] ;this is how you exclude yourself from the turtles-here command. the other command removes yourself from the agentset, and it is optional for now. 

Concept 2: Random % chance

To make a boolean true 37% of the time you would say:   random 100 < 37

You can use this in an if statement like this:
if random 100 < 50 [fd 2]
;50% of the time move forward 2

or like this:
if random 100 < N [commands]
;N % of the time, do the commands

Concept 3:
The N from the last concept could be a variable OR REPORTER FUNCTION like this:

if random 100 < REPORTER [commands]

Concept 4:  Variables (from before)
Turtle variables are local to the turtle. Look up the turtles-own command.
Global variables are shared by everyone. Look up the globals command.

You can give a variable a specific value with set like:
set size 6
set color red

OR increase/decrease like this:
set heading heading + 1
set size size - .5

Now the lab:  (This is where a test question would start)
1. Start with your basic cars and people from the weekend.

to setup
  ca
  crt 5 
  [
    set shape "car" 
    set color red 
    set xcor (- abs random-xcor)
    set heading random 4 * 90
  ]
  crt 10
  [
    set shape "person"
    set color blue
    set xcor abs random-xcor
  ]
  ask turtles 
  [
    set ycor random-ycor
    set size 2
  ]
end

to go
  ask turtles with [shape = "person"] [peopleMotion]
  ask turtles with [shape = "car"] [carMotion]
  wait .06
end

to carMotion
  fd 1
end


to peopleMotion  
  fd .3
  rt random 10
  lt random 10
end


2. Now make the cars paint the gray roads like yesterday.
to carMotion
  set pcolor gray
  fd 1
end

3. Turtles should have a variable deathTimer.

turtles-own[deathTimer]


4. There should be global variables accidentDeath and naturalDeath. These will act as counters for the number of deaths that happen. We will use them in monitors.

globals [accidentDeaths naturalDeaths]


Additional Car Behavior:
5. When a car is on the same patch as a person (concept 1), it makes the person die right away. This will add 1 to the accidentDeath count. (concept 4) 

to carMotion
  set pcolor gray
  fd 1
  ;kill pedestrians
  ask turtles-here with [shape = "person"] 
  [  set accidentDeaths accidentDeaths + 1 
     die
  ] 
end


New Reporter function:

6. deathRate is a reporter function that reports 10 when there are more than 150 people, or it reports 6 otherwise. 
to-report deathRate
  ifelse count turtles with [shape = "person"] > 150
  [report 10]
  [report 6]
end


New Person Behavior:
7-DeathTimer logic:
 People should initialize their deathTimer to -1 when they are created.

Inside of the CRT 10 in your setup: set deathTimer -1
You don't have to do this in hatch because they copy the -1 from the parent

 People with a deathTimer that is > 0 reduce their timer by 1 and reduce their size by .1  every time they move. 
 People with a deathTimer that is = 0 should die. This increases naturalDeath by 1. 
 People have a 'deatRate' % chance (either 10 or 6) of starting to die. When they start to  die, they turn red, and set their deathTimer to 20.  (concept 3, use the deathrate function as your percent)


to peopleMotion
  ;death logic
  if deathTimer = 0 
  [ set naturalDeaths naturalDeaths + 1
    die
  ] 
  if deathTimer > 0 [set deathTimer deathTimer - 1 set size size - .1]
  if color = blue and random 100 < deathRate [set color red set deathTimer 20]

  fd .3
  rt random 10
  lt random 10 
end




8-Hatch Behavior:
 Blue people have an 8% chance of hatching a child. (dying people cannot hatch) (concept 2)

After your death logic above insert this: 

  ;birth logic
  if color = blue and random 100 < 8 [hatch 1 [rt 90]]
  

New Widgets:
9. Make a monitor for the number of naturalDeaths, and one for the number of accidentDeaths. Just put the name of the variable into the monitor, there is nothing fancy here.
10. Make a plot for the number of people. Count the number of people (not all turtles) on the plot. 
You need to use the following commands for a plot:
inside of setup after you clear-all use : reset-ticks
inside the go at the end use: tick


Final result:

globals [accidentDeaths naturalDeaths]
turtles-own[deathTimer]

to setup
  ca
  crt 5 
  [
    set shape "car" 
    set color red 
    set xcor (- abs random-xcor)
    set heading random 4 * 90
  ]
  crt 10
  [
    set shape "person"
    set color blue
    set xcor abs random-xcor
    set deathTimer -1
  ]
  ask turtles 
  [
    set ycor random-ycor
    set size 2
  ]
end

to go
  ask turtles with [shape = "person"] [peopleMotion]
  ask turtles with [shape = "car"] [carMotion]
  wait .06
end

to carMotion
  set pcolor gray
  fd 1
  ;kill pedestrians
  ask turtles-here with [shape = "person"] 
  [  set accidentDeaths accidentDeaths + 1 
     die
  ] 
end


to-report deathRate
  ifelse count turtles with [shape = "person"] > 150
  [report 10]
  [report 6]
end

to peopleMotion
  ;death logic
  if deathTimer = 0 
  [ set naturalDeaths naturalDeaths + 1
    die
  ] 
  if deathTimer > 0 [set deathTimer deathTimer - 1 set size size - .1]
  if color = blue and random 100 < deathRate [set color red set deathTimer 20]

  ;birth logic
  if color = blue and random 100 < 8 [hatch 1 [rt 90]]
  
  fd .3
  rt random 10
  lt random 10
end




Lab 07 : Tree

posted Nov 27, 2012, 8:44 AM by Samuel Konstantinovich   [ updated Dec 21, 2012, 5:26 AM ]

1. Basic tree (Should be finished by 11/27 at home if you have issues in class)
Write a turtle context function tree n 
*-It makes a size n fractal tree. The angle should be constant (it can be a slider) and the branch size should be constant (it can be a slider also)

Hints:
*-There is NO REPEAT command inside the tree command.
*-When you define tree you use brackets:
to tree[n]
  ...
end

*-When you CALL tree, you don't put brackets:
tree 5
tree x + 1
tree n - 2
etc.

2. Advanced tree. We will discuss this tomorrow at the start of class, then you have time to work on it (11/28)
Write a turtle context function BetterTree n angle branch.

You can still use a slider, but it should be for the STARTING angle and STARTING branch value:
You could have sliders TREE_SIZE BRANCH_ANGLE BRANCH_SIZE
you could have a button:    
   BetterTree TREE_SIZE BRANCH_ANGLE BRANCH_SIZE

Hints:
*-Multiple parameters are in the same brackets:   to betterTree [n angle branch]
*-Make sure you call BetterTree inside your function, not your old tree.
*-You can change the value of the angle and branch as you use recursion. So you can do things like:
2a) Make the branch size decrease every time you call tree.
2b) Make the angle change (smaller or bigger) every time you call the tree.
*-Example of decaying /random :
      betterTree n - 1 angle + random 3 - random 3 branch * .75
*-Parenthesis are not requred for this but you can use them to help you read the code:
      betterTree (n - 1)  (angle + random 3 - random 3)  (branch * .75)

3) Make the coolest looking tree function you can. I will compare them in class and choose the coolest looking ones. (My opinion judges) You can work on them at home, I will judge them at a later date. Your goal should be to make a somewhat organic looking tree, no to make a bunch of rainbow turtles. 

Lab 06

posted Oct 16, 2012, 6:15 PM by Samuel Konstantinovich   [ updated Dec 21, 2012, 5:25 AM ]

;********************************
;INTRODUCTION:

;I truly apologize for being absent this long. The only thing
;I can do to help you all is give you these little labs with 
;a small amount of new material so you learn something even
;when I am not there. That being said, only 2 people asked me
;questions about the work. So I will assume that if I were to 
;quiz you on lists when I return... you would all understand everything!
;(or at least try to do so now that I warned you)

;Computer science is more about reading than Mathematics is. You 
;never get a problem so straight forward as "Solve the following
;equation*" in a computer science class. Read this whole lab carefully
;and if you didn't read the previous ones carefully, I urge you 
;to go back and re-check them. 

;*To be fair, there are almost no such questions when you go to 
;college to study mathematics either

;Hint: I won't quiz you the day I come back... 
;but the day after is fair game. 






;********************************
;********************************
;LAB 6
;********************************
;********************************

;If you saw the long introduction and thought "tldr" then you should
;rethink your work ethic. I guarantee lazy makes you lose points in 
;my class. 


;Lets work with lists of numbers for now:

;DO NOW: (You can work with others but should try at least one on your own)

;****************************************
;Part 1 Function traces:

;For EACH of the 2 mystery functions:
;1. Trace through them both on paper using any list of numbers
;2. Then see if the result you got is the same as the function
;3. If not trace again, you can compare with others... 
;4. What is this function supposed to be named?

;MYSTERY FUNCTION 1:
(define (MST3K L)
  (cond
    ((null? L) 0)
    (else (+ (car L) (MST3K (cdr L))))))



;MYSTERY FUNCTION 2:
(define (MSTRE L)
  (cond
    ((null? L) 0)
    ((even? (car L))(MSTRE (cdr L)))
    (else (+ (car L) (MSTRE (cdr L))))))


;****************************************
;Part 2: evaluation with car and cdr

;Evaluate each of these without running them in racket:
;1 (car (cdr (cdr '( a b c d e f))))
;2 (cadddr '( a b c d e f))
;3 (caddddr '( a b c d e f))
;Check your answers in drRacket.

;Notice that c____r shortcuts (cddr L) or (caddr L) 
;only works with up to 4 a/d's inside. This is still 
;a useful shortcut however!!!
;cdr   
;cddr  
;cdddr  
;cddddr  
;next....
;(cdr (cddddr 
;(cddr (cddddr ... etc. 

;OK! Now try 4
;4. (car (car (cdr '( a b c d e f))))
;a. What must car and cdr be used on? 
;b. Can you use car on the results of a car?
;c. When would it be possible to use car twice? (hint: listCeption)


;****************************************
;Part 3: NEW COMMANDS

;I promise I will briefly go over these commands, but I strongly 
;urge you to copy these into drRacket and see what they do.
;You should modify them, and experiment to confirm/contradict your
;assumptions. Test them a little and you will learn more I promise. 

;(cons value list) -> list with value added as the 1st element.
;(cons 3 '(2 6)) -> (3 2 6)
;(cons 1 '()) -> (1)

;Semi strange:
;(define x 1)
;Compare the next two carefully:
;(cons x '( 2 3)) -> (1 2 3)
;(cons 'x '( 2 3)) -> (x 2 3)
;Explain to your neighbor why that happened. Confirm with a different neighbor. 



;Now is where the weird things happen:
;(cons '(1 2) '(3 4) ) -> ((1 2) 3 4)  
;the list got put at the start of the 2nd list

;(append list1 list2) -> the combination of both lists in order
;(append '(4 5 6) '(1 2 3)) -> (4 5 6 1 2 3) 
;the numbers stay in order , they don't change to the order you 
;may have expected. 


;Play with cons and append.
;Your goal should be to beable to verbalize to me how they are different/similar.
;You can try writing a function that tries to cons a bunch of numbers to a list
;then try the same thing with cons, and realize that:
;append requires two lists...
;cons can take   anything + 1 list:   such as list and a list, or integer and a list
;so you cant (cons 3 L), you need to (cons '(3) L)


;LAST NEW THING:
;how would you cons an integer x to a list?
;(cons '(x) L)  would put the LETTER x in the list.
;We can use the (list x) command
;(list 3) -> (3)
;(define x 3)
;(list x) -> ( THEVALUEOFX )  ;so if x was 3, that would be (3)


Lab 05

posted Oct 15, 2012, 9:42 PM by Samuel Konstantinovich   [ updated Dec 21, 2012, 5:25 AM ]

;The next topic you will learn about is lists
;this will show you how to write a list, and how to 
;access the data you put in the list

;in scheme the apostrophy ' tells the interpreter not to evaluate 
;the next item.

(display "SAMPLE OUTPUT 1:\n")
(define x 3)
x
(+ x 3)
'x
'(+ x 3)
(newline)

;notice how the 'x and '(+ x 3) didn't say 3 and 6?
;that is because of the '

;A list in scheme is just a set of parenthesis with some data
;inside it, except to prevent scheme from trying to evaluate the 
;parenthesis we use an '

(display "\n FIVE SAMPLE LISTS:\n")
'( this is a list)
'( 1 3 6 0 2)
'( + - * /)

;Oh and just in case you were wondering a list can be empty:
'()

;or have MORE LISTS inside it: 
;(This is more advanced we will talk about it later!)
'( (1 2) (3 9) 0)

(newline)


;NOW lets get stuff out of the list:
;we will use this list for testing purposes:
(define jenny '( 8 6 7 5 3 0 9))

;typing the variable name shows the value of the whole list:
(display "jenny=")
jenny

;Two functions that are critical for list processing are car and cdr
(display "(car jenny)=")
(car jenny)
(display "(cdr jenny)=")
(cdr jenny)

;car works on any list to get the 1st element
;cdr works on any list to get the whole list WITHOUT the 1st element. 
;Think of car as the 1st, and cdr as the rest. 
(newline)

(display "(cdr (cdr (cdr jenny)))=")
(cdr (cdr (cdr jenny)))
;we have a shortcut for that:
(display "(cdddr jenny)=")
(cdddr jenny)
(newline)

;Now the part where you start thinking... 
;You can only look at the first element of a list, so the only way to 
;look at the 2nd element is to make it the 1st element using cdr. 
(display "(car (cdr jenny))=")
(car (cdr jenny))

;When you want the 3rd element, you have to use cdr twice.
;When you want the 4th element, you have to use cdr three times.



;NOW YOU DO STUFF:
;NOW YOU DO STUFF:
;NOW YOU DO STUFF:
;NOW YOU DO STUFF:
;NOW YOU DO STUFF:


;PART 1
;Write a function that extracts the nth item from the list
;(getNth List Place)
;examples:
;(getNth jenny 0) -> 8
;(getNth jenny 1) -> 6
;(getNth jenny 2) -> 7
;(getNth jenny 6) -> 9
;If you havent noticed, the 0th element is the leftmost one.
;We index things starting at 0, not 1. 
;The 0th element is the "first".
;The 1st element is really the "second". 

;Almost all list functions need a special base case:
;Your base case should be when List is empty...
;(cond
;    ((null? list)  "List Is Empty or Index is too Large" )

; (null? list)  
;is the same as saying:
; (equal? list '() )

;Your recursion should use the REST of the list...
;Your stopping point should be when you get to the right place...




;PART 2
;Make a function myLength that counts how many elements a list has
;There is a built in function to do this called length
;(length jenny) is 7
;assume there are no lists inside the list.
;Test your function!
;Hint: How long is a list that is empty? That is your base case.



;PART 3
;Make a function that counts how many 0's are in the list
;Test your function!

Lab 04

posted Oct 14, 2012, 8:44 PM by Samuel Konstantinovich   [ updated Dec 21, 2012, 5:24 AM ]

;The goal today is to learn about the begin and display commands. 
;Used together they can show us how a recursive function progresses!

;The begin statement executes each command one after another
;the whole statement evaluates to the last part
;so in the case of countTo2, the last part is a display
;which has no numerical value, 
;CountTo1 has a countTo1 call last, which ultimately becomes 0. 
;notice that depending when you display the result, the numbers 
;appear in opposite order!

(define (countTo1 x)
  (if (> x 0)
      (begin
        (display x)
        (countTo1 (- x 1)))
      (begin 
        (display x)
        0)))
       
(define (countTo2 x)
  (if (> x 0)
      (begin
        (countTo2 (- x 1))
        (display x))
      (begin 
        (display x)
        0)))

(display "countTo1(4)=")
(countTo1 4)
(newline)
(display "countTo2(4)=")
(countTo2 4)
       
;Why is this useful to you?
;Haven't you wanted a way to see what values it finds as 
;it goes through the recursion? Haven't you wanted a way to 
;make it print the values along the way to the end result?
;Now you can! We don't normally print the values in scheme, but
;we can (display value) if we wanted to. 


;Lab4:
;Part 1: Sample sequence:
(define (sequence n)
  (if
   (= n 0)
   0;terminal value
   (begin
     ;instead of adding 1/n to the sum
     ;I just display it. 
     (display (/ 1 n))
     (display ",")
     (sequence (- n 1)))))

(display "\nSequence(8)=")
(sequence 8)

;Hailstone series
;Hailstone of n is defined as:
;n/2 for even values of n.
;3n+1 for odd values of n.
;Stop when n=1. 
;Since there are 3 possibilities... that should SCREAM: cond

;lets say n=5
;3(5)+ 1 -> 16
;(16)/2 -> 8
;(8)/2 -> 4
;(4)/2 -> 2
;(2)/2 -> 1
;OR:  5,16,8,4,2,1
;Lets say n=3
;3,10,5,16,8,4,2,1
;simple enough... if not google hailstone sequence and read more!

;So the final number in the sequence is always one. 
;This means that knowing the final value is not very interesting, 
;seeing the entire sequence is FAR more interesting. 

;PROBLEM 1:
;Your goal is to write a function that DISPLAYs the sequence
;(hailstone 32) would show:
;32,16,8,4,2,1
;This is similar to the sample sequence except you don't change n by
;subtracting 1 every time.

;PROBLEM 2:
;Once you get the working sequence, write a function that tells you
;how long the hailstone of a number is.
;(hailLength 1) should be 1
;(hailLength 32) should be 6
;(hailLength 3) should be 8  ... see the sequences above

;PROBLEM 3:
;Write a function that tells you the maximum hailstone value of the sequence. 
;(maxHail 32) -> 32
;(maxHail 3) -> 16
;(maxHail 5) -> 16

Lab 03

posted Oct 5, 2012, 6:11 AM by Samuel Konstantinovich   [ updated Dec 21, 2012, 5:23 AM ]

;##########################################
;Notes:

;###### Regular Recursion ###### 
;the recursive call requires the recursion to complete before the works is done

;example:   5+fact(4)  requires fact(4) to evaluate BEFORE the multiplication. 
;This means the work is done from the tail end and propagates back to the start.
(define (Fact n)
  (if (= n 0)
      1
      (* n (Fact (- n 1)))))

;###### Iterative style recursion ######
;The work is done, then it is passed into the recursive call for it to do the work. 
;This requires an extra parameter to store the partially completed answer
;like the GCF needed a helper function with a 3rd parameter
;When the recursion hits the base case, the answer should already be known
;This is great because there are no pending operations waiting to be completed.

(define (helpFact n partialSolution)
        (if 
         (= n 0) 
         partialSolution ;when you reach 0, use the partial solution
         (helpFact (- n 1) (* n partialSolution) ) ;when it is too big, update the partial solution and run it again
         ))

(define (iterFact n)
  (helpFact n 1))
;start the product at 1. Help will then keep calculating the solution


;##########################################
;Actual Lab:
;Make sure you save your files on your account or email them to yourself if you are sharing a computer/using Guest 
;If I ever ask you to open up an old lab for reference starting with lab3, and you cannot produce it, I will be VERY ANGRY.
;###   1   ###
;trace through both versions using the stepper...R
;(change your language to beginning student)
;view -> Show tracing
;now you can press the step button
(Fact 8)
(iterFact 8)

;BEFORE you start writing code, discuss the lettered points below each question. 
;If you are done and you need to find someone to talk to, ask me to move around the room.

;### 2 ###
;Now try to write (SumAtoB a b) using an Iterative Style Solution!!!
;a. use a helper, what parameters are required?
;b. remember you should keep the partial solution updated at each step AND change the value.
;c. the stopping condition should be when the a and b are the same value.
;d. assume a<=b.

;### 3 ###
;Try to do Fibonacci (you need to store the partial solution AND the previous two results...
;a. How many parameters fib numbers are required to get the next number? 
;b. How many parameters are required?  

Lab 02 - Conditionals

posted Sep 27, 2012, 5:53 AM by Samuel Konstantinovich   [ updated Dec 21, 2012, 5:23 AM ]

You must come up with your own test cases for each problem. 
You must test your solutions.
If you do not complete this in class, finish at home.
You have a test tomorrow.

Cond statements are great when we want more than two possibilities. You can have any number of different results and only 1 will happen. This is better than nested if statements as it looks much cleaner.

Example of a cond statement:
(cond      ;do the 1st statement with a true boolean, or none if they are all false. 
  (b1 s1)  ;boolean and statement
  (b2 s2)  ;boolean and statement
   ...
)

;example 1, three possibilities no chance for them all to be false:
(cond
  ( (< x 1) (+ x 1))  ;notice there are parenthesis around the whole line
  ( (= x 1) (+ x 2)) 
  ( (> x 1) (+ x 3))
)

;example 2, with a default case:
(cond
  ( (< x 10) (...)) 
  ( (< x 20) (...));What if the number is 20 or more???
  ( else   (...) )  ;this will catch any leftover values
)

;example 3: 
(cond
  ( (= x 1) "Hello")
  ( (= x 2) 5)
  ( (= x 3) 3.141592353)
  ( (= x 4) #t )
  ( #t 1)  ; else is the same as #t for a default case
)

LAB Directions:

1. Write a function weeklyPayCalc that calculates your weekly pay based on two parameters hours and wage. This function should account for overtime after 40 hours. Overtime means that any hours past 40 get 1.5x the pay.

(weeklyPayCalc hours wage)
examples:
(weeklyPayCalc 40 10) --> 400 (40 regular hours)
(weeklyPayCalc 42 10) --> 430 (40 regular hours + 2 overtime hours)

2. Write a function that determines how many roots a quadratic equation has as determined by the discriminant. Remember the discriminant is b*b-4*a*c.

Your function should return according to this table:
Discriminant    Roots
Negative           "No Real Roots"
0                       "One Root"
Positive            "Two Roots"

(rootsOfQuadratic a b c)
(rootsOfQuadratic 1 6 9) --> "One Root"
(rootsOfQuadratic 1 0 1) --> "No Real Roots"
(rootsOfQuadratic 1 0 -1) --> "Two Roots"

3. Improve your roots function as follows:
When a discriminant is positive, it can be 2 rational or 2 irrational roots. When the discriminant is a perfect square, the roots are rational but when it is not a perfect square the roots are irrational.

(rootsOfQuadratic2 1 0 1) --> "No Real Roots"
(rootsOfQuadratic2 1 0 -1) --> "Two Rational Roots"
(rootsOfQuadratic2 1 3 1) --> "Two Irrational Roots"

1-10 of 11