This is the full work book for introduction of Programming Logic. I am not saying to just pull off of this work and use it as your own. Use it as a reference to ensure you are doing your work correctly. All information is 100% accurate and holds an "A" in the class.
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
IT-106 Pseudo-Coding Wk 5
1. Contents
Phase 1: Design Concepts............................................................................................................... 1
Project Description...................................................................................................................... 1
Use Cases .................................................................................................................................... 1
Data Dictionary........................................................................................................................... 3
High Level Design Components ................................................................................................. 4
Detailed Design: Checkout Diagrams......................................................................................... 7
Design Analysis ....................................................................................................................... 8
Detailed Design: Product Research........................................................................................... 10
Diagrams................................................................................................................................ 10
Design – Using Pseudocode...................................................................................................... 11
Product Profit......................................................................................................................... 11
Phase 2: Sequential Logic Structures............................................................................................ 12
Design........................................................................................................................................ 12
Product Profit......................................................................................................................... 12
Phase 3: Problem Solving with Decisions .................................................................................... 13
Safe Discount......................................................................................................................... 14
Return Customer Bonus......................................................................................................... 16
Applying Discounts ............................................................................................................... 18
Phase 4: Problem Solving with Loops .......................................................................................... 21
Total order ............................................................................................................................. 21
Problems to Solve .................................................................................................................. 22
Calculate Profits..................................................................................................................... 22
Rock, Paper, Scissors............................................................................................................. 24
Number Guessing Game........................................................................................................ 27
Phase 5: Using Abstractions in Design ......................................................................................... 29
Seeing Abstractions................................................................................................................... 29
Refactoring................................................................................................................................ 29
2. 1
Phase 1: DesignConcepts
Project Description
Althoughwe maybe late to the game,we will nevertheless jointhe worldof e-commerce tosell our
fantasticproducton the Internet. Todo so,we needa Website that will allow forcommerce andsales.
To be quickaboutit, we require the following:
Searchable inventoryandshoppingpages
A shoppingcart
A place forcustomersto registerwhentheymake purchases
A checkoutprocesstomake the purchase
Withinthismainprocess,there are a bunch of otherneedsthatmustbe met,as follows:
We wantto track the date of the lastpurchase a customermake so we can offerincentivesand
discountsbasedonthe lasttime theyshopped.
We will offersalesbasedonthe numberof differentitems thata personpurchases.
We will alsogive discountsfor bulkordersadiscountwhena personbuysmanyof the same
item
In additiontosalesfeature,the solutionmustprovide the abilitytomanage andresearchthe salesof
products. It mustinclude the following:
Must be able toadd, update andremove product inventoryinreal time onthe site
Needstohave researchcapabilitiestodetermine how well aproductisselling, suchasthe
following:
o How oftenthe itemisviewed,addedtoshoppingcarts,andthenpurchased
o How a price change affectssalesandprofit
Use Cases
From the descriptionabove,we canrelate thistothe followinguse cases,whichdescribe how the user
will interactwithoursystem. Eachuse case isa set of screens that the userswouldinteractwithto
accomplishsomethingtheyneedonthe site.
4. 3
Data Dictionary
Variable Name Type Description
todaysDate Date Today’sdate,whenthe programis running
creationDate Date The date the customercreatedtheiraccount
priorPurchases Integer Numberof Purchasesthiscustomerhasmade in
the past
lastPurchaseDate Date The date of the lastpurchase the customermade
lineItemPrice Array The price of each line itemthe customerhas
addedto the cart
lineItemQuantity Array The quantityof each line itemthe customerhas
addedto the cart
membershipLevel Integer The account nature of the customer
1 – Guest
2 – Registered
3 – Preferred
totalPurchaseAmount Double The cost of all the itemsintheircurrentpurchase
salesTaxRate Double The salestax to be chargedon a purchase
productCategory Integer An indicatorof the categoryof the product
1 – ConsumerGoods
2 – Electronics
3 – Clothing
productPrice Double The price of the product as soldto the customer
wholesalePrice Double The price at whichwe purchase the product
numberInCarts Integer The total numberof timesthisproducthas been
addedto a shoppingcart
numberOfPurchases Integer The numberof timesthis producthasbeen
purchased
allProductSalesNumbers Array A listforeach product of the numberof timesa
producthas sold
allProductPrices Array A listforeach productof the productprice
allProductWholesalePrices Array A listforeach productof the productwholesale
price
6. 5
Fill outthe followingtable todescribe whichcomponentsare usedbyeachuse case and how each
componentwill helprealize the use case:
Use Case Component ServicesProvided
Date todaysDate Today’sdate,whenthe programis running
Search/Browse
Inventory
productInventory Providesaccessto the databaseof inventory of
all productsand theirdescriptionsand prices
and such.
searchEngine Allowsfor searching on many criteria within the
productdatabase
productCategory 1 – ConsumerGoods
2 – Electronics
3 – Clothing
lineItemPrice The price of each line itemthe customerhas
addedto the cart
lineItemQuantity The quantityof each line itemthe customerhas
addedto the cart
RegisterAsCustomer customerManager Createand managecustomerprofileand
personalinformation
creationDate The date the customercreatedtheiraccount
priorPurchases Numberof Purchasesthiscustomerhasmade in
the past
lastPurchaseDate The date of the lastpurchase the customer
made
userSecurity Providesecurity solutionsforthe visitors to the
site
Choose Products numberInCarts 1-Item
2-Item
3-Item
totalPurchaseAmount The cost of all the itemsintheircurrent
purchase
salesTaxRate The salestax to be chargedon a purchase
ApplyDiscounts membershipLevel 1 – Guest
2 – Registered
3 – Preferred
Manage Products wholesalePrice The price at whichwe purchase the product
productPrice The price of the product as soldto the customer
allProductPrices A listforeach productof the productprice
allProductWholesalePrices A listforeach productof the productwholesale
price
ResearchSales numberOfPurchases The numberof timesthisproducthasbeen
purchased
allProductSalesNumbers A listforeach productof the numberof timesa
producthas sold
7. 6
My interpretation of graph above ↑ and below ↓ is yours.
Use Case Component ServicesProvided
Search/Browse
Inventory
ProductInventory Provides accessto the databaseof inventory of all
productsand theirdescriptionsand prices and such.
SearchEngine Allowsfor searching on many criteria within the
productdatabase
RegisterAs Customer CustomerManager Createand managecustomerprofile and personal
information
UserSecurity Providesecurity solutionsforthe visitors to the site
Choose Products Search Engine Allowsfor searchingon manycriteria withinthe
product database
Purchasing Types ofproducts beingpurchasedand placed in
cart
Checkout ShoppingCart Whatcan be seen inthe cart for purchaseor return.
UserSecurity Keepsusersecure while accessingsite for shopping
preferencesandcheckout for creditcards
Card Processing Monitors typesof payment and encrypts contents
for secure transfer
Apply Discounts Card Discount Amountof allowablediscountbasedonnew,
returning or bulkbuyer.
Manage Products Product Inventory Reviews the amountofproducts soldverses
productsin stock
Purchasing Assesswholesale versesretail and profits
establishedthroughinput variables
Research Sales Product Inventoy Reviews the amountofproducts soldverses
productsin stock
Purchasing Monitors numberof timesitempurchased, overall
itemssold
9. 8
Figure 2: Sequence Diagram for calculateOrderTotal
DesignAnalysis
Giventhe designsabove,we needtoanalyze whichapproachwe shouldtake andhow the code
realizationwill differ.
StructureDesign
Describe the implementationof the structure designin Figure 1and how it relatestothe
Checkoutuse case.
ANSWER: Implementationof the structure designcanbe usedwiththe decoratorstyle method
as it ensures additional responsibilitiesare attachedtoan objectdynamicallykeepingthe same
interface.Decoratorsprovide aflexiblealternativetosub-classingforextendingfunctionality.
What proceduresand functionsare beingcreatedinthe design?
ANSWER:A procedure is a finite sequenceof well-defined instructions,each of which can be
mechanically carried outin a finite amountof time. A functionisthe computerreadingthe
variablesandconstantstofigure an outputcalculationbasedoncalculationsran. There are six
executable functionsandprocedureswithinthisdesign.
What data wouldbe passedbetweenthese procedures andfunctions?
ANSWER: The data isthe “calculateOrderTotal;bigBuyerDiscount;bulkBuyerDiscount;
returnCustomerBonus”;passedto“discountManager; daysSinceLastPurchase;
calculateSubtotal”;customer;calculateTotal. These wouldsendnumericalcalculationsthrough
the psuedocode algorithmtogive afinal costassessmenttothe customer.
;Order ;DiscountManager ;Customer ;Taxes
bigBuyerDiscount()
bulkBuyerDiscount()
returnCustomerBonus()
daysSinceLastPurchase()
calculateSubtotal()
11. 10
Figure 2 and howit relatestothe Checkoutuse case.
ANSWER:Unlike a procedural language,where the programisa seriesof tasksthatmust be
performed,object-orientedlanguage ismade upof objectsthatinteractwithone another. Each
objectismade up of a seriesof tasksthat can be performedindependentlyof otherobjects.
These tasksare generallyhidden fromotherobjects,which preventsthemfrominterfering.Only
the endresultsof the object’soperationsare thenseenbyotherobjects
What methodsare beingcreatedinthe design?
ANSWER:A methodisreallythe same asa procedure, function orroutinein procedural
programminglanguages.The onlydifference isthatinobject-orientedprogramming,amethod
isalwaysassociatedwithaclass. The class definesall the commonproperties of the different
objectsthatbelongtoit. In thisdesignthere are fourmethodsbeingcompiled. Theyare order;
dicountManager;customer;taxes.
What data wouldbe passedbetweenthese methods?
ANSWER: The discounts, bonuses,dayssince lastpurchase,calculationsubtotal andtaxes.
Comparison
How dothese approaches(StructuredversusOO) differ?
ANSWER: Structuredcodingruns ina sequential format,whichrunseachfunctioninastep-by-
stepprocess. Structureddesignisalsobetterforsmallerprogrammingcode asitismore
efficientanddoesn’tuse asmanyfactorsto functionas OOPdoes. Asthe numberof functions
withinthe structure increase,itbecomesintensivelydifficultforthe programtomanage data
and operate efficiently. Youmayevenbe able to runa procedure withinthe OOPdesign. OOP
has polymorphismwhere structureddoesn’t. Structuredmaybe identifiedasaclass within
12. 11
OOP. The classesworktogethertobettermanage the whole flow of the programdependenton
informationthatisinputted.
Whenwe get to code,howmuchwill the detailedimplementationdifferbecause of the high
level designapproachwe have chosen?
ANSWER: Unlike low-level languages,high-level languageshave highabstraction.Inother
words,theyare much more similartothe language youspeakthanare the low-level languages.
Many high-level languagesare verysimilarinsyntax tonatural language. Thismakes
programmingmucheasier. High-level programminglanguagesuse abstractconceptssuchas
loops,variables,andarrays.The mostrecenthigh-levellanguagesuse objectsthatare reusable.
The drawback to high-levellanguagesisthattheyuse a lotof memoryandtake a lotof time to
process.However,moderncomputersare fasterallowingthemtohandle these largerprograms.
High-level languageprogramscanoftenbe compiledfordifferentplatforms.
Detailed Design: Product Research
Diagrams
For the product research use case,take a stab at eithera structureddesigndiagramora sequence
diagramthat wouldfulfill atleastpartof the functionalityof the use case. We will compare whatyou
create here to the detaileddesignwe create throughthe restof the course as a wayof measuringyour
progress.
Provide adiagramof yourchoice here to show a flow forresearchingproducts.
The exact detailsare flexible within the descriptionof the functionality,sodoyourbestto create a
flowthatlookslike acode solutionusingthe componentsabove oronesyouthinkyouneed. Thisis
practice that will give youameasuringstickforyour learningaswe see problemslater inthe course
relatedtothissystem.
Yes
No
No
Yes
NoYes
No
No
Yes
Yes
Yes
Yes
Yes
No
Yes
Yes
Product Research
HP Computer
Is item in stock?
Input “n”
quantity
left
Customer purchase +1
Add to cart/Purchase ?
Adjust inventory = 0
Purchase
Re-order
item ?
Adjust
inventory -1 New Customer
Gather information
High Selling item Phase out
Returning Customer
Apply discount ?
Visitor
Discount
applied
First Name
Last Name
Proceed to Checkout?Continue
Shopping?
13. 12
Design – Using Pseudocode
ProductProfit
Description
It isimportantto knowthe profiteachproduct isprovidingtothe bottomline. Giventhatwe knowthe
wholesalecost, the retail costto consumersand the numberof items we have sold, calculate the profit
for a givenproduct.
Pseudocode
{function productProfit(productPrice : Double,
wholesalePrice : Double,
numberOfPurchases : Integer}
Return Double
{
Input = createVariable(productPrice)
Input2 = createVariable(wholesalePrice)
profitPrice = (productPrice – wholesalePrice)
returnProductprofit
}
End function
14. 13
Phase 2: Sequential Logic Structures
Design
ProductProfit
Description
Continuingwiththe same example of calculationproductprofit,utilize the same scenariotocreate a
flowchart.
Description - Itis importanttoknowthe profiteach productisprovidingtothe bottomline. Giventhat
we knowthe wholesale cost,the retail costtoconsumersandthe numberof itemswe have sold,
calculate the profitfora givenproduct.
Flowchart
profitPrice = (productPrice
– wholesalePrice)
Return ProductProfit
endFunction
productProfit(productPrice :
Double
15. 14
AdditionalPseudocode
Discusshowinput/output,operators,andexpressionsare presentedin pseudocode aswell ashowthey
are usedto accommodate needsforsequentiallogicwithinbusinessapplications. Additionally,discuss
howvariousdata typesmaybe usedwithinsequential logicstructures.
ANSWER: Pseudocode isdeliveredinafive-stepmethod. Aspartof these steps,input/output,
expressionsandoperatorsare addressed. The firststepinvolvesdefiningthe elementsandother
variablesof the functionthatyouwill needforthe pseudocode. Itwill alsoinclude the dimensional data
variables,whichare partof the “INPUT” valuesof the code beingused. The input/outputoperatorscan
alsobe establishedinthisprocesstouse informationfromthe keyboard,applyittothe functionand
outputto the screenor printer. The final step,instepone,istoset upthe control functionsyouwill use.
Be ittextand imagesorbasic controlsfromsimplerlanguages. Step2involvesaddingfunctional
pseudocode toaddspecific“eventdriven”code toinitiate the projectonce youhave completedthe
initial controls. Functional pseudocode normallyusesthe parametersof the “if”,“then”,“while”and
“else”. Functional code alsoincorporatesthe expressionsof “READ”,“WRITE”, and“PRINT”. Step3
involvescheckingyourpseudocode forcompliance conventions. Ensure the above elementsare inyour
code. These elementsadiversifiedthroughoutmanycode languagesandare an intrinsicpartof the
processingof the function. Under step-4of the process,commentsshouldbe enteredtoensure the
role of differenttaskandpartsof the code to the reader. Commentstonothave to riveteveryline of
the processbut are goodfor transferringtoothersteps.Finally,step-5looksatreviewingthe syntax or
pseudocode youhave justwritten. Ensure properspelling,markerpoint’s parenthesisare inkey
positionsandsoon.
SequentialLogicstructure isconsideredthe oldestformandmostusedtype of structure. The
nice thingaboutsequential logicisitisbasicallyadesignerwritingastep-by-stepfunctionto be
accomplishedforsearching,mappingoranyotheroperationneedingtobe conductedona system.
Sequentiallogicislike writingashoppinglistandcanbe utilizedinanyprogrammingcode format,
whetheritisone of the lowerendorhighendcoding programs. Itemsbelow are fortestingdata.
> Greaterthan
< Lessthan
≥ Greaterthan or equal to
≤ Lessthan or equal to
or && and symbol
or | | the “or” symbol
¬ “is Not”
== logically equivalent
16. 15
Phase 3: Problem Solving with Decisions
SafeDiscount
Description
We wantto ensure thatthe systemwill notaccidentallydiscountaproductbelow the price thatitis
purchasedfor. Thus, we want an operationto ensure that, whenadiscountisapplied,italwaysstays
more than the original purchase price.
Sample datacouldinclude the following:
A productat $10 witha wholesale price of $5and a discountof 10% returning$9.
A productat $10 witha wholesale price of $6and a discountof 50% returning$6.
Pseudocode
function applyDiscount(productPrice : Double,
wholesalePrice : Double,
applyDiscount : Double)
Return Double
createVariable (finalPrice : Double){
if finalPrice = 𝑝𝑟𝑜𝑑𝑢𝑐𝑡 𝑝𝑟𝑖𝑐𝑒 −
𝑝𝑟𝑜𝑑𝑢𝑐𝑡𝑃𝑟𝑖𝑐𝑒 𝑋 𝑑𝑖𝑐𝑜𝑢𝑛𝑡
100
return discount
}
if (finalPrice ≥ wholesalePrice)then{
returnPrice
} else {return wholesalePrice
)
]return productPrice
}fi
End function
18. 17
ReturnCustomerBonus
Description
We want to reward customers for returning to make a purchase. To incentivize,
they receive a bonus discountas by the following levels.
• Less than a week = 10%
• More than 6 months = 6%
• Otherwise, 1% for each month (consider a month to be 30 days)
Sample data for testing:
Scenario todaysDate lastPurchaseDate totalPuchaseAmount Return amount
1 2/1/2014 1/25/2014 $100 $90
2 2/1/2014 3/17/2013 $100 $94
3 2/1/2014 12/11/2013 $100 $99
customerReward todaysDate LstPurchDate TotPurchAmnt dicount
1 string string double 10
2 string string double 6
3 string string double 1
19. 18
Pseudocode
function returnCustReward (todaysDate : Date,
lastPurchaseDate : Date,
totalPurchaseAmount : Double)
returns double
function returnCustomerBonus(customerBonus:double)then{
createVariable (TodaysDate:String)
createVariable lastPurchaseDate:string
crateVariable totalDays : intger
createVariable totalPurchaseAmount:Double)return{
If totalDays = (todaysDate – lastPurchaseDate)
return totalDays
if (totalDays ≤ 7){
return customerBonus
customerBonus = TotalPurchaseAmount X
0.10)
} else {
if (totaldays ≥ 30){
customerBonus = TotalPurchaseAmount X
0.01)
} else {
If (totalDays > 180)
customerBonus = TotalPurchaseAmount X
0.06)
return customerBonus
]
}fi
endFunction
20. 19
Flowchart
.
T
Return Customer
Bonus
If totalDays =
(todaysDate –
lastPurchaseDate) Return totalDays
if (totalDays ≤ 7 = customerPurchase x 0.10)
if (totalDays ≥ 30 = customerPurchase x 0.01)
If (totalDays > 180 = customerPurchase x 0.06)
F
newCustomer=NoBonus Return customerBonus
End Function
21. 20
ApplyingDiscounts
Description
A customerreceives hisorherdiscountbasedon hisor hermembershipstatus. Preferredmembers
receive areturnmemberbonus, andall registeredmembersreceiveabulkdiscount,butguestsdonot
receive anydiscounts.
Thisshouldreuse the discountsfromthe priorwork,sotestcases fromthere wouldapply. Justmake
sure that guestsreceive nodiscount,registeredmembersjustgetadiscountforany itemsforthe bulk
discount, andpreferredmembersgetboththe bulkdiscountandthe returncustomerbonus.
Status bonusDiscount bulkDiscount noDiscount returnDiscount
Preferred 10% 6%
Registerd 6%
Guests 0%`
Pseudocode
function applyDiscounts (todaysDate : Date,
lastPurchaseDate : Date,
totalPurchaseAmount : Double,
membershipLevel : Integer)
returns double
if membershipLevelDiscount=(todaysDate – lastPurchasedate)
x365
return days
if (guest = membershipLevel < 7){
membershipLevelDiscount = guestDiscount
(todaysDate,lastPurchaseDate,purchaseAmount,)
} else if {
if (membershipLevel = registered > 30)
membershipLevelBonus = bulkDiscount
(todaysDate,lastPurchaseDate,purchaseAmount)
} else if{
If (membershipLevel = preferred > 180)
membershipLevelDiscount = preferredDiscount +
bulkDiscount
(todaysDate,lastPurchaseDate,purchaseAmount)
}
Return membershipLevelDiscount
}fi
end function
22. 21
(Flowchart)
.bulk
Start Apply
Discount
(membershipLevelDiscount = (todaysDate – lastPurcahsedate,
purchaseAmount X membershipLevelDiscount)
if (guest =
membershipLevel < 7)
membershipLevelDiscount =
guestDiscount)
T
F
T
T
F
F
if (registered =
membershipLevel > 30)
if (preferred =
membershipLevel > 180)
membershipLevelDiscount =
(bulkDiscount)
membershipLevelDiscount =
preferredDisount)
Return
membershipLevelDiscount
endFunction
23. 22
Phase 4: Problem Solving withLoops
Total order
Once the final pricesare calculatedforeach product,we needtototal up the order andthenadd in
salestax. We needto go throughthe line itemsin anorderand figure outthe final price.
Flowchart
v
Pseudocode
function totalOrder (lineItemPrice: Array,
lineItemQuantity : Array,
saleTaxRate : Double)
returns double
Create variable Double : subtotal
for (index = each item in lineItemPrice){
lineItemTotal = lineItemPrice[array] * lineItemQuantity[array]
subtotal =subtotal + lineItemTotal
end loop
}
return calculateSubtotal (subtotal x salesTaxRate)
end function
orderTotal
Return
calculateSubtotal (subtotal, salesTaxRate)
Subtotal = subtotal
+lineItemTotal
index = each item in
lineItemPrice
lineItemTotal=
lineItemPrice[index] x
lineItemQuantity[index]
End
T
Start
24. 23
Problemsto Solve
Fill inthe followingtable by walkingthroughthe logicabove. The ideaistoanalyze how the chart and
pseudocode wascreated, because youwill be doingthisinafew minutes,so donotjustjumpto the
easyanswer. Followthe stepsasif youare the computerexecutingthe software designed.
Problem lineItemPrice lineItemQuantity saleTaxRate Return amount
1 [5.50, 3.00, 2.25] [12, 3, 10] 5% (5.5 x 12)x 0.05 =
$69.30
(3.0 x 3) x 0.05 = $9.27
($2.25 x 10) x 0.05 =
$23.63
2 [5.50] [5] 5% ($5.50 x 5) x 0.05 =
$28.88
3 [0] [0] 5% ($0.00 x 0) x 0.05 =
$0.00
CalculateProfits
Description
Giventhe listof all the product pricesandwholesale pricesaswell asa listof all the itemssoldforeach
productcalculate the netprofitfor all the products.
Problem allProductPrices allWholesalePrices allSalesNumbers returnNetProfits
(50,30,20,10,5) (35, 15,10,5,2) (60,80,20,45,70) $2735.00
allProductPrices:array
-
allWholsalePrices:array
x
allSalesNumbers:array
=
netReturns
25. 24
Flowchart
Pseudocode
function netProfits (allProductSalesNumbers: Array,
allProductPrices : Array,
allProductWholesalePrices : Array)
returns double
creatVariable Double : netProfits{
for (array = each item in allProductPrices,
allWholesalePrices, allSalesNumbers )
netProfits=(allSalesNumbers) x allProductPrices –
allPriductWholesalePrices
netProfits = netprofits x allSalesNumbers
}
end Loop
returnCalculateNetProfits (allSalesNumbers x allProductPrices -
allWholesalePrices )
}fi
end function
createVariable Double : netProfits
array = each item in
allProductPrices,
allWholesalePrices,
allSalesNumbers
netProfits =
allSalesNumbers(array)x
allProductPrices[array] –
allPriductWholesalePrices[array)
netProfits = netprofits x
allSalesNumbers(array)
returnCalculateNetProfits
(allSalesNumbers x
allProductPrices -
allWholesalePrices )
End
26. 25
Rock,Paper, Scissors
Description
To expandfurther,we wanttotry out logicininteractingwithusers. Here isasample of a game,using
loopsanddecisionstoallowapersonto play rock-paper-scissors withacomputer.
Pseudocode
We have a helperfunction thatwe will use here thattellsuswhowon. Itwill resultin +1if the player
wins,a -1 if the computerwins,anda 0 if it isa tie.
function compareOutcome(computerChoice: Integer,
playerChoice : Integer)
returns Integer
Andthe main flowof my logicis as such.
createVariable computerChoice : integer
createVariable playerChoice : interger
while (true)
Integer : computerChoice = randomChooser()
Integer : playerChoice = prompt “Enter a value”
print “Enter a value”
read value
If (playerChoice is not a valid input)
returnPrint “You picked bad number. Try again”
Else
Integer : outcome = compareOutcome(computerChoice,
playerChoice)
If (outcome = 0)
Prompt user “It is a tie, try again”
Else if (outcome = -1)
Prompt user “You lost”
Break out of loop
Else
Prompt user “You win”
Break out of loop
End if
End if
end loop
27. 26
Flowchart
playerEntry is not
a valid input
outcome =
0
outcome =
-1
Integer : computerChoice = ramdonChooser()
Integer : playerChoice = prompt “Enter a value”
Prompt user “You picked bad
number, try again”
Integer : outcome =
compareOutcome(computerChoice, playerChoice)
Prompt user ”It is a tie, try again”
Prompt user “You lost”
BreakPrompt “You won”
End of game
Break
whileTrue
28. 27
Note:Inthiscase, note the advantagesanddisadvantagesof flowchartsand psuedocode.The flowchart
iseasyto followthe logicforone scenario,butdoesitmake it easierorharderto understandthe code
as a whole? There isno strictanswer,butone that tellsyoua bitabout yourway of thinkingand
personal preference.
InteractionScenario
For eitherof the solutionsabove, follow the logicandmap outyour interactionstep-by-step,tryingto
exercise all pathsof the logic. Youwill have totake at least2 timesthroughthe game to mapall
scenarios.
Scenario1 = 1 rock
2 paper
3 scissors
Step UserInput SystemResponse
1 User chooses50 Systemsayslower
2 User chooses(1) Systemsays(1) “Tie” Select “Go” to play again"
3 User chooses(3) Systemsays(1) “ I Win” Select “Go” to play again"
4 User chooses(2) Systemsays(1) “YouWin” Select “Go” to play
again"
Scenario2
Step UserInput SystemResponse
1 User chooses(4) Systemsayslower
2 User chooses(2) Systemsays(1) “You Win” Select“Go”to playagain"
3 User chooses(3) Systemsays(1) “ I Win”Select“Go”to play again"
4 User chooses(1) Systemsays(1) “Tie” Select“Go”to playagain"
Step UserInput SystemResponse
1 User chooses(10) Systemsayslower
2 User chooses(3) Systemsays(1) “ I Win”Select“Go” to playagain"
3 User chooses(1) Systemsays(1) “Tie” Select“Go”to playagain"
4 User chooses(2) Systemsays(1) “You Win”Select“Go” to play
again"
29. 28
NumberGuessingGame
Description
Nowit isyour turnto try out userinteractionwithasimple game. Thisgoesbackto the number
guessinggame. The userwill inputanumbereachtime,saybetween 1and100. The computerwill
randomlyselect1numbereachgame (note thisisdifferentthanthe example above whereitselectsa
newanswereachround),andthe game continuesuntil the userguessesthe rightnumber.
Like above,yoursolutionshouldaccommodateforinvalidinput,butdonotworryabout how to make
that logicworkfor now. Your solutionshouldgivesome hintsthoughif the guessthe usermade wastoo
highor too low,tohelpthemon theirway.
Flowchart
30. 29
Pseudocode
function guessNumber(randomNumber: Integer,
create Variable RandomNumber(1,100) : Integer
create Variable enterNumber(1,100) : Integer
create variable guessesTaken = (Φ) : Integer)
returns Integer
while enteredNumber = randomNumber(Φ){
Interger(1,100) return
printString “Thinking number 1 thru 100”
}
while guessesTaken > (?){
returnPrintString “Make a Guess”
guess = input()
guess = integer{
if enteredNumber > random_number
printreturn “too high”
}if else{ enteredNumber < random_number
printReturn “too low”
enteredNumber = input;
when done
return “You have a match”
}
}fi
endFunction
31. 30
Phase 5: Using Abstractions inDesign
Seeing Abstractions
Throughoutthiscourse,we have beenrealizingthe detaileddesignforthe piecesof the whole picture
we startedwithat the beginningof the course. We have builtmanyabstractions, solet’sgoback and
documentwhatwe have foundandsee the abstractionswe have created.
Abstraction Name Parameter List Scope/Purpose
calculateSubtotal (totalPurchaseAmount :double,
salesTaxRate : double)
Appliessalestax andcomputesthe
final amountdue.
calculateProductProfit (productProfit Double,
wholesalePrice : Double
numberOfPurchases : Integer)
Takesthe product retail price minus
the wholesale price togetnet
profits.
applySafeDiscount (productPrice : Double,
wholesalePrice : Double,
applyDiscount : Double)
Ensuresthat the systemwill not
accidentallydiscountaproductbelow
the wholesale price.
Return Customer
Bonus
createVariable todaysDate:String
createVariable lastPurchaseDate:
string
crateVariable totalDays : intger
createVariable totalPurchaseAmount
:Double)
We wantto rewardcustomersfor
returningtomake a purchase.
Apply DiscountsFor
Members
(todaysDate : Date, lastPurchaseDate
: Date,
totalPurchaseAmount : Double,
membershipLevel : Integer)
Memberdiscounts basedonhisor
hermembershipstatus.
Order Total with Sales
Tax
(lineItemPrice: Array,
lineItemQuantity : Array,
saleTaxRate : Double)
Appliestototalingupthe orderand
thenaddinginsalestax.
Calculate Profits (allProductSalesNumbers: Array,
allProductPrices : Array,
allProductWholesalePrices : Array)
Appliestocalculatingprofitsfromall
businessoperationsof sales.
Rock, Paper, Scissors (computerChoice: Integer,
playerChoice : Integer)
Applieslogicloopsthatinteractwith
others.
The NumberGuessing
Game
create Variable (RandomNumber(1,100)
:Integer
create Variable enterNumber(1,100)
:Integer
create variable guessesTaken = 0 :
Integer)
A guessinggame createdtointeract
withuserusingloops.
Refactoring
Sometimesitiseasyto see howthe whole solutioncanbe brokenintopieces,andothertimesitisdone
as yousee abstractionsandopportunitiesforreuse inthe resultingdesign. Thisiscalled refactoring. For
the pseudocode yousee below,lookforabstractionsyoucouldcreate andcreate a flowchartusingyour
simplifications.
32. 31
PsuedocodeinNeed of Refactoring
NOTE: Comparisontable. WORKAREA –NOT FINAL. FIANLON NEXT PAGE(P-31)
OLD: Color coded for inspection SWAG-1/(Scientific Wild Ass Guess)
Array : namesInSystem
Array : phoneNumbersInSystem
String : nameInput
While (nameInput is not valid){
nameInput = prompt user for input
if (nameInput is provided and not blank){
break out of loop
}end loop
Prompt user the input is required and not blank
]End loop
Integer : indexForName = -1
For (index = all items in namesInSystem
If (nameInput = namesInSystem[index]){
indexForName = index
}endFi
}End loop
If (indexForName = -1){
Prompt user “We cannot find your account, please
call us”
}Else{
String : phoneNumberInput
While (phoneNumber is not valid){
phoneNumber = prompt user for input
if (phoneNumber is provided and not blank){
break out of loop
}end loop
Prompt user the input is required and not
blank
}End loop
If (phoneNumber =
phoneNumbersInSystem[indexForName])
Prompt “we found your account welcome”
Else
Prompt “we cannot validate your account,
try again later”
End if
End if
Array : namesInSystem
Array : phoneNumbersInSystem
String : nameInput
nameInput = Validate (“User Name”);
Integer : indexForName = -1
userExist = (CheckNameInSytem/nameInput,nameInSytem)
If
indexForName = index
}Else{
Prompt user “We cannot find your account,
please call us”
}End Loop
String : phoneNumberInput
phoneNumberInput = validate (“Phone Number”);
If (phoneNumber = phoneNumbersInSystem
[indexForName]){
Prompt “we found your account welcome”
}Else{
Prompt “we cannot validate your account, try
again later”
}End Loop
functionValidate (identifier:string) returnString{
createVariable valueString
Repeat{
Print “Enter” identifier
readValue
Until (value < > empty)
return Value
}
]endFi
33. 32
SWAG-3/ Pseudocode FINAL
Array : namesInSystem
Array : phoneNumbersInSystem
String : nameInput
Intger : userExist
nameInput = validate (“User Name”);
Integer : indexForName = -1
userExist=checkUserNameInSytem(nameInput,nameInSytem)
if (userExist==-1){
Prompt user “We cannot find your account, please call us”
}
String : phoneNumberInput
phoneNumberInput = validate(“Phone Number”)
if phoneNumberInput == phoneNumbersInSystem(userExist){
Prompt “we found your account welcome”
}Else{
Prompt “we cannot validate your account, try again later”
}End Loop
functionValidate (identifier:string) returnString{
createVariable value:String
Repeat{
Print “Enter” identifier
readValue
Until (value < > empty)
return Value
}
]endFi
Refactored Flowchart
The above pseudocode islong,butyoucan omitmuch of the details. Youcan accomplishthe same logic
removingmore than30 lines. Youdonot have to show all of the detailsremovedif movedintoan
abstraction,simplyname the abstractionanddefinethe parameters tobe passedtothe call replacing
the linesof code.
34. 33
Enter flowchart:
T
Start
Array : namesInSystem
Array : phoneNumbersInSystem
String : nameInput
functionValidate
(identifier:string)
Print “Enter”
identifier
nameInput = validate
(“User Name”)
readValue
Until (value < >
empty)
If (nameInput =
namesInSystem[index]
F
if phoneNumberInput ==
phoneNumbersInSystem){
Prompt user “We cannot find
your account, please call us”
phoneNumberInput =
validate (“Phone Number
F Prompt “we cannot validate
your account, try again
later”
T
T
Prompt “we found your
account welcome””
EndFi