AP exam format - PowerPoint PPT Presentation

1 / 95
About This Presentation
Title:

AP exam format

Description:

Usually, you are asked write a method or class for the free response questions. ... return 'lemming'; default: return 'small bird'; 50. Practice Exam Three, 4a ... – PowerPoint PPT presentation

Number of Views:144
Avg rating:3.0/5.0
Slides: 96
Provided by: lowel3
Category:
Tags: exam | format | lemming

less

Transcript and Presenter's Notes

Title: AP exam format


1
AP exam format
  • Both A and AB are two sections
  • 40 multiple choice questions 115
  • 4 free response questions 145
  • Usually, you are asked write a method or class
    for the free response questions. For methods you
    will be given a header and a task.
  • One free response question will be about the
    MBSCS (the same question is usually on both
    exams)
  • 5 or 6 multiple choice questions will be about
    the MBCS
  • You will be given a "quick reference guide" to
    the AP Java classes and MBSCS code

2
AP exam grading
  • Here are the statistics for the 1999 exam
  • Grade A exam AB exam
  • 5 75 70
  • 4 56 60
  • 3 41 41
  • 2 30 31
  • 1 0 0

3
Ap exam tips
  • Distribute the !
  • !(true false)
  • //is the same as
  • !true !false
  • //is the same as
  • false true
  • //is the same as
  • false

4
Ap exam tips
  • Q What does a sub (child) class never inherit
    from the super (parent) class?

5
Ap exam tips
  • Q What does a sub (child) class never inherit
    from the super (parent) class?
  • A The constructors. Instead of inheriting the
    constructors, there is an "invisible" call to
    super() on the first line of each sub (child)
    class constructor

6
Ap exam tips
  • Q What do you have to do to implement
    Comparable?

7
Ap exam tips
  • Q What do you have to do to implement
    Comparable?
  • A An interface is a list of methods that must be
    written. In Comparable, there is only one method
    compareTo()

8
Ap exam tips
  • Q What is an abstract class?

9
Ap exam tips
  • Q What is an abstract class?
  • A It's an unfinished class, kind of like an
    interface. If you extend an abstract class, you
    have to write all the abstract (unfinished)
    methods, or your must make your class abstract

10
Ap exam tips
  • Q What is an abstract class?
  • A If you use an abstract class in your program,
    you must have another (sub) class that extends
    the abstract class

11
Ap exam tips
  • How can a sub (child) class initialize the
    private members of the super (parent) class?

12
Ap exam tips
  • How can a sub (child) class initialize the
    private members of the super (parent) class?
  • Only by calling super()
  • (remember that super() must be the first thing
    the constructor does)

13
Ap exam tips
  • ArrayList l new ArrayList()
  • l.add(new Integer(3))
  • Integer m new Integer(3)
  • l.get(0).equals(m)
  • // or
  • ((Integer) l.get(0)).equals(m)

14
Ap exam tips
  • l.get(0).equals(m)
  • // or
  • ((Integer) l.get(0)).equals(m)
  • This is trickynormally you'd need to cast
    l.get(0) back to its type, but all Objects have a
    .equals method (and toString and hashCode())
  • Both Work!

15
AP AB exam tips
Last
first
last
In this circular linked list, the next pointer of
the last node points back to the first node in
the list. There is also a pointer to the last
node, so we can always find it. How many steps
to use the last pointer to add a node after
the last node? How many steps to delete the
first node in the list
16
AP AB exam tips
  • What's the Big-O?
  • Visiting all the elements in an array, tree or
    linked list

17
AP AB exam tips
  • What's the Big-O?
  • Visiting all the elements in an array, tree or
    linked list
  • O(n)

18
AP AB exam tips
  • What's the Big-O?
  • In a sports tournament, half of the teams are
    eliminated each round

19
AP AB exam tips
  • What's the Big-O?
  • In a sports tournament, half of the teams are
    eliminated each round
  • O(log n)

20
AP AB exam tips
  • What's the Big-O?
  • In a sports tournament, half of the teams are
    eliminated each round
  • How many rounds to get to a winner if there are
    500 teams? (Hint 27128)

21
AP AB exam tips
  • What's the Big-O?
  • How many rounds to get to a winner if there are
    500 teams? (Hint 27128)
  • 9 (29512)

22
AP AB exam tips
  • What's the Big-O?
  • How many rounds to get to a winner if there are
    1000 teams?

23
AP AB exam tips
  • What's the Big-O?
  • Adding or retrieving items from a "hash" (hashMap
    or hashSet)

24
AP AB exam tips
  • What's the Big-O?
  • Adding or retrieving items from a "hash" (hashMap
    or hashSet)
  • O(1) (best case)

25
What's the output?
  • public class SwappingObjectsVsPrimitives
  • public static void main(String args)
  • int x 6, y 8
  • int z 6,8
  • Swapper swap new Swapper()
  • swap.swapper(x,y)
  • System.out.println(x ", " y)
  • swap.swapper(z)
  • System.out.println(z0 ", " z1)
  • class Swapper
  • public void swapper(int a, int b)
  • int temp a
  • a b

26
What's the output?
  • public void swapper(int a, int b)
  • int temp a
  • a b
  • b temp
  • . . .
  • swap.swapper(x,y)

x
6
y
8
a
6
8
b
8
6
27
What's the output?
  • public void swapper(int a)
  • int temp a0
  • a0 a1
  • a1 temp
  • . . .
  • swap.swapper(z)

a
0
6
8
1
8
6
z
28
Constructors
  • Should always be public
  • No return type, not even void

29
The worst mistake
  • Never display what you should return!
  • Problem Write a method that returns the sum of
    two numbers
  • double Sum(double dOne, double dTwo)
  • System.out.println(dOne dTwo)
  • NO NO NO NO!

30
The worst mistake
  • Never display anything unless you are asked!
  • Problem Write a method that returns the sum of
    two numbers
  • double Sum(double dOne, double dTwo)
  • System.out.println(dOne dTwo)
  • return dOne dTwo
  • NO NO NO NO!

31
The worst mistake
  • Now it's correct!
  • Problem Write a method that returns the sum of
    two numbers
  • double Sum(double dOne, double dTwo)
  • return dOne dTwo
  • Beginning programmers typically want to display
    everything. If they can't see it, they don't
    believe it exists. Don't let the grader think
    you're a rookie!

32
Exam security
  • The following are forbidden
  • Bringing a cellphone or other electronic device
    to the exam
  • Discussing or attempting to reproduce the
    multiple choice questions with anyone (including
    your teacher) after the exam
  • Discussing or attempting to reproduce the essay
    questions with anyone (including your teacher)
    within 48 hrs after the exam

33
Compete the answer form using 2 pencil for pages
  • fill our areas A, B and F. Leave C,D,E,G and H
    blank. Fill out areas I Q only ONCE during the
    two week exam cycle
  • leave blank
  • leave blank
  • Fill out areas T,W X only if you have not
    already done this year. Bubble 5 for CA,Bubble
    zip code starting with left column. School code
    is 052970, 1101 Eucalyptus Dr. SF, CA 94132.
    Leave U,V and Y blank

34
Practice Exam One, 1a
  • public class StockItem
  • private String myDescription
  • private int myIdNum, myNumOnShelf
  • private double myPrice
  • public StockItem(String s, int id, double p,
  • int num)
  • public String getDescription()
  • public int getIdNum()
  • public double getPrice()
  • public int getNumOnShelf()
  • public void setPrice(double p)
  • public void remove(int q)
  • public void add(int q)

35
Practice Exam One, 1b
  • public void removeAll(int idNum)
  • int I 0
  • while((StockItem)myStockList.get(I)).getIdNum()
  • ! idNum)
  • I
  • StockItem item (StockItem)myStockList.get(I)
  • item.remove(item.getNumOnShelf())
  • //or
  • public void removeAll(int idNum)
  • for(int I 0 IltmyStockList.size()I)
  • StockItem item (StockItem)myStockList.get(I
    )
  • if (item.getIdNum()idNum)
  • item.remove(item.getNumOnShelf())
  • break

36
Practice Exam One, 2a, b
  • public static int countNegatives(NumberSet s)
  • int count 0
  • while(count lt s.size()
  • s.findkth(count1).intValue() lt 0 )
  • count
  • return count
  • public static removeNegatives(NumberSet s)
  • int n countNegatives(s)
  • for(int nI1 nIltn nI)
  • s.remove(s.findkth(1))
  • //or
  • public static removeNegatives(NumberSet s)
  • while(s.findkth(1).intValue() lt 0)

37
Practice Exam One, 2c
  • public static NumberSet commonElements(
  • NumberSet s1, NumberSet s2)
  • NumberSet temp new NumberSet()
  • for(int I1 Ilts1.size() I)
  • if(s2.contains(s1.findkth(I)))
  • temp.insert(s1.findkth(I))
  • return temp

38
Practice Exam One, 3a b
  • public class Sentence(String str)
  • mySentence str
  • myNumWords 1 //not zero!
  • for(int nI0 nIltstr.length() nI)
  • if(mySentence.charAt(nI)' ')
  • myNumWords
  • private static boolean isPalindrome(String s,
  • int start, int end)
  • if(end-start lt 2)
  • return true
  • else
  • return s.charAt(start) s.charAt(end)
  • isPalindrome(s,start1,end-1)

39
Practice Exam One, 4a
  • Start by using nextLocation() and
    emptyNeighbors() as a guide in writing code
  • protected Location nextLocation()
  • ArrayList emptyNbrs emptyNeighbors()
  • Direction oppositeDir direction().reverse()
  • Location locationBehind
  • environment().getNeighbor(location(),opposi
    teDir)
  • emptyNbrs.remove(locationBehind)
  • if ( emptyNbrs.size() 0 )
  • return location()
  • Random randNumGen RandNumGenerator.getInstanc
    e()
  • int randNum randNumGen.nextInt(emptyNbrs.size
    ())
  • return (Location) emptyNbrs.get(randNum)

40
Practice Exam One, 4a
  • Start by using nextLocation() and
    emptyNeighbors()as a
  • guide in writing code
  • protected ArrayList emptyNeighbors()
  • ArrayList nbrs
  • environment().neighborsOf(locati
    on())
  • ArrayList emptyNbrs new ArrayList()
  • for ( int index 0 index lt nbrs.size()
    index )
  • Location loc (Location) nbrs.get(index)
  • if ( environment().isEmpty(loc) )
  • emptyNbrs.add(loc)
  • return emptyNbrs

41
Practice Exam One, 4a
  • / use nextLocation() and emptyNeighbors()as a
  • guide in writing code /
  • protected ArrayList targetLocations()
  • ArrayList targets new ArrayList()
  • ArrayList nbrs environment().neighborsOf(locat
    ion())
  • Location behind envronment().getNeighbor(
  • location().OppositeDir())
  • nbrs.remove(behind)
  • for (int nI0 nIltnbrs.size() nI)
  • Location loc (Location)nbrs.get(nI)
  • Direction d environment().getDirection(
  • location(),loc)
  • Location target env.getNeighbor(loc,d)
  • if(!environment().isEmpty(loc)
  • enviroment().isEmpty(target))
  • targets.add(target)

42
Practice Exam One, 4b
  • / use nextLocation() and emptyNeighbors()as a
  • guide in writing code /
  • protected Location nextLocation()
  • ArrayList targets targetLocations()
  • if(targets.size()0)
  • return super.nextLocation()
  • else
  • Random randNumGen
  • RandNumGenerator.getInstance()
  • int randNum
  • randNumGen.nextInt(targetLocs.size())
  • return (Location) targets.get(randNum)

43
Single Sheet "Question 4" a,b
  • private int findItem(String name)
  • for(int nI0 nIltstock.length nI)
  • if(stocknI.getName().equals(name))
  • return nI
  • return 1
  • public boolean oneSale(String name)
  • int nI findItem(name)
  • if(nI -1)
  • return false
  • else if(stocknI.getNumInStock() lt0)
  • return false
  • else
  • stocknI.sellOne()
  • return true

44
Single Sheet "Question 4" c
  • public ArrayList allSales(String orders)
  • ArrayList failures new ArrayList()
  • for(int nI0 nI lt orders.length nI)
    if(!oneSale(ordersnI))
  • failures.add(ordersnI)
  • return failures

45
Practice Exam Three, 1a, 1b
  • public HashTable(int tableSize)
  • size tableSize
  • count 0
  • T new LinkedListsize
  • for(int I Iltsize I)
  • TI new LinkedList()
  • public void delete(Object key)
  • LinkedList L Thash(key)
  • for(int nI 0 nIltL.size() nI)
  • if(((TableEntry)L.get(nI)).getKey().equals(ke
    y))
  • L.remove(nI)
  • break

46
Practice Exam Three, 1b, 1c
  • //1b using an iterator
  • public void delete(Object key)
  • int pos hash(key)
  • boolean found false
  • ListIterator I Tpos.listIterator()
  • while(I.hasNext() !found)
  • if(((TableEntry)I.next()).getKey().equals(ke
    y))
  • I.remove()
  • found true
  • public void insert(Object key, DataType data)
  • delete(key)
  • LinkedList L Thash(key)
  • L.add(new TableEntry(key,data)

47
Practice Exam Three, 2a
super (parent) class on top, sub (child) class
points to it's parent
Animal
Mammal
Bird
Goat
Pig
Owl
Turkey
Elf Owl
Snowy Owl
48
Practice Exam Three, 2b
  • abstract class Animal
  • private String myName
  • private String myCover
  • private String myNoise
  • public Animal(String n, String c, String s)
  • myName n
  • myCover c
  • myNoise s
  • public String getName()return myName
  • public String getCover()return myCover
  • public String getNoise()return myNoise
  • public abstract String getFood()

49
Practice Exam Three, 2c, 2d
  • abstract class Owl extends Bird
  • public Owl(String n)
  • super(name,"Hoot!")
  • class SnowyOwl extends Owl
  • public SnowyOwl(String n)
  • super("Snowy Owl") //why not Bob?
  • public String getFood()
  • Random rand Random.getInstance()
  • //or
  • static Random rand new Random()
  • switch(rand.nextInt(3))

50
Practice Exam Three, 4a
  • private Locatable find(TreeNode p, Location loc)
  • if(p null)
  • return null
  • else
  • if( ((Locatable)p.getValue()).equals(loc) )
  • return p
  • else if((Locatable)p.getValue()).

  • compareTo(loc)lt0)
  • return find(p.getRight(),loc)
  • else
  • return find(p.getLeft(), loc)
  • Note that you could probably get away with
    casting p as a Fish and calling location()
  • ((Fish)p.getValue()).location().equals(loc)
  • which works as long as everything is a Fish

51
Practice Exam Three, 4b
  • Start by looking at objectAt() from UnboundedEnv
  • //from UnboundedEnv
  • public Locatable objectAt(Location loc)
  • int index indexOf(loc)
  • if ( index -1 )
  • return null
  • return (Locatable) objectList.get(index)
  • public Locatable objectAt(Location loc)
  • TreeNode t find(objectTree,loc)
  • if(tnull) //if(!isValid())?
  • return null
  • return (Locatable)find.getValue()

52
Practice Exam Three, 4c
  • /this is just like the insert method from
    Assignment 5/
  • private Locatable add(TreeNode t, Locatable obj)
  • if(t null)
  • return new TreeNode(obj,null,null)
  • else
  • if((Locatable)t.getValue()).compareTo(obj)lt0)
  • t.setRight(add(p.getRight(),loc))
  • else
  • t.setLeft(add(p.getLeft(), loc))
  • return t

53
Question 4a,b p212
  • public int findAccount(int accountNum)
  • for(int nI0 nIltaccounts.length nI)
  • if(accountsnI.getAccountNum()accountNum)
  • return nI
  • return 1
  • public void oneTransaction(Transaction trans)
  • int nI findAccount(trans.getAccountNum())
  • if(trans.getTransactionType().equals("d"))
  • accountsnI.doDeposit(trans.getAmount())
  • else
  • accountsnI.doWithdrawal(trans.getAmount())

54
Question 4c p212
  • public ArrayList daysTransactions
  • (Transaction
    transactions)
  • ArrayList problems new ArrayList()
  • for(int nI0 nIlttransactions.lengthnI)
  • oneTransaction(transactionsnI)
  • for(int nI0 nIltaccounts.lengthnI)
  • if(accountsnI.getBalance()lt0)
  • problems.add(accountsnI)
  • return problems
  • /Note two loops The first processes all the
    transactions, the second then goes through all
    bank accounts
  • some bank accounts may be overdrawn and not on
    the transaction list, others may have had more
    than one transaction where the first caused the
    account to be overdrawn, but a later transaction
    fixed it /

55
Computer Science exam is Tuesday May 4th (morning)
  • May conflict with AP Spanish Language (contact
    Mr. Jow or Ms. Dacanay)
  • This week
  • Monday (Practice essay questions, student
    corrected)
  • Tuesday (Practice essay questions, teacher
    corrected)
  • Wednesday (Practice multiple choice)
  • Thursday (Practice essay questions, teacher
    corrected)
  • Friday Mondaygo over answers, review and relax
  • After the AP?
  • complete missing program assignments
  • Robocode?

56
Practice A Exam 2a,b
  • public static int numInArray(StringA, String s)
  • int nCount 0
  • for(int nI0 nIltA.length nI)
  • if(anI.equals(s))
  • nCount
  • return nCount
  • public static void printAllNums(StringA,
  • StringB)
  • for(int nI0nIltA.lengthnI)
  • System.out.println(AnI
  • " "
    numInArray(B,AnI)

57
Question 2, p 206
  • private int getDollars()
  • return (int) amount
  • private int getCents()
  • double dCents amount-getAmount()
  • dCents dCents .005
  • return (int)(dCents100)
  • / dCents 12.3995 12
  • dCents .3995 .005 (.4045)
  • return (int)(40.45) /

58
Question 2c, p 206
  • public String toString()
  • return getAmount() " dollars and "
  • getCents() " cents"

59
Question 3a, p 209
  • private double average()
  • if(grades.length 0)
  • return 0
  • int nTotal 0
  • for(int nI0 nIltgrades.length nI)
  • nTotal gradesnI
  • return ((double)nTotal)/grades.length
  • public StudentInfo(String theName, int
    theGrades)
  • name theName
  • grades theGrades
  • averageGrade average()

60
Question 3b, p 209
  • public APCS()
  • int nNumStudents readInt()
  • students new StudentInfonNumStudents
  • for(int nI 0 nI lt nNumStudents nI)
  • String sName readString()
  • int nNumGrades readInt()
  • int theGrades new intnNumGrades
  • for(int nJ0nJltnNumGradesnJ)
  • theGradesnJreadInt()
  • studentsnI new StudentInfo(sName,theGrad
    es)
  • highestAverage findHighAverage()
  • private String findHighAverage()
  • int nHighPosition 0
  • for(int nI 0 nI lt students.length nI)

61
Question 3b, p 209
  • public APCS()
  • int nNumStudents readInt()
  • students new StudentInfonNumStudents
  • for(int nI 0 nI lt nNumStudents nI)
  • String sName readString()
  • int nNumGrades readInt()
  • int theGrades new intnNumGrades
  • for(int nJ0nJltnNumGradesnJ)
  • theGradesnJreadInt()
  • studentsnI new StudentInfo(sName,theGrad
    es)
  • double dMax students.getAverageGrade()
  • highestAverage students0.getName()
  • for(int nI 0 nI lt students.length nI)
  • if(studentsnI.getAverageGrade()gtdMax)
  • highestAverage studentsnI.getName()

62
Question 1a, p246
  • //isMale helper function
  • //note plants.length is x dimension (5)
  • //plants0.length is y dimension (3)
  • private boolean isMale(int x, int y)
  • if(xlt0 x gt plants.length
  • ylt0 y gt plants0.length)
  • return false
  • return plantsxy.equals("male")

63
Question 1a, p246
  • //brute force
  • public boolean willFruit(Point p)
  • int x p.getX()
  • int y p.getY()
  • return isMale(x-1,y) isMale(x-2,y)
  • isMale(x1,y) isMale(x2,y)
  • isMale(x,y-1) isMale(x,y-2)
  • isMale(x,y1) isMale(x,y2)
  • isMale(x-1,y-1) isMale(x-1,y1)
  • isMale(x1,y-1) isMale(x1,y1)

64
Question 1a, p246
  • //Using a loop
  • public boolean willFruit(Point p)
  • int x p.getX()
  • int y p.getY()
  • for(int nX x-1 nXltx1 nX)
  • for(int nYy-1 nYlty1 nY)
  • if(isMale(nX,nY))
  • return true
  • return isMale(x-2,y) isMale(x2,y)
  • isMale(x,y-2) isMale(x,y2)

65
Question 1a, p246
  • public boolean willFruit(Point p)
  • int x p.getX()
  • int y p.getY()
  • for(int nX 0 nXltplants.length nX)
  • for(int nY0 nYltplants0.length nY)
  • int nXdistance Math.abs(nX x)
  • int nYdistance Math.abs(nY y)
  • int nTotal nXdistance nYdistance
  • if(isMale(nX,nY) nTotal lt 3 )
  • return true
  • return false

66
Question 1b, p246
  • //Using a loop
  • public ArrayList willNotFruit()
  • ArrayList noFruit new ArrayList()
  • for(int nX 0 nXltplants.length nX)
  • for(int nY0 nYltplants0.length nY)
  • if(plantsnXnY.equals("female")
  • !willFruit(new Point(nX,nY))
  • noFruit.add(new Point(nX,nY))
  • return noFruit

67
class ListNode
  • public class ListNode
  • public ListNode (Object initValue, ListNode
    initNext)
  • value initValue
  • next initNext
  • public Object getValue() return value
  • public ListNode getNext() return next
  • public void setValue(Object theNewValue)
  • value theNewValue
  • public void setNext(ListNode theNewNext)
  • next theNewNext
  • private Object value
  • private ListNode next

68
Question 2a, p250
  • private ListNode personBefore(int age)
  • ListNode current peopleList
  • Person young(Person)current.getValue()
  • ListNode before null
  • while(current ! null)
  • Person curr (Person)current.getValue()\
  • if(curr.getAge() lt young.getAge())
  • break
  • if(curr.getAge() lt age)
  • young(Person)current.getValue()
  • before current
  • current current.getNext()
  • return before

69
Question 2a, p250
  • private ListNode personBefore(int age)
  • ListNode tmp peopleList
  • Person currentPerson
  • if(tmp null)
  • return null
  • currentPerson (Person)tmp.getValue()
  • if(currentPerson.getAge() gt age)
  • return null
  • while(tmp.getNext()!null)
  • currentPerson ((Person)tmp.getNext().getV
    alue())
  • if(currentPerson.getAge() gt age)
  • return tmp
  • tmptmp.getNext()
  • return tmp

70
Question 2b, p251
  • public void addPerson(Person p)
  • ListNode curr personBefore(p.getAge())
  • if(curr null)
  • peopleList new ListNode(p,peopleList)
  • else
  • curr.setNext(new ListNode(p,curr.getNext())
    )

71
String methods
  • Note that the "Java Quick Reference" sheet lists
    two versions of substring
  • String sString "hello"
  • sString.substring(2,4) //"ll"
  • sString.substring(3) // "lo"
  • and an indexOf() method
  • sString.indexOf("lo") //3

72
"Sample Questions for A",1a p61
  • VoterBallots, Ballots candidateLists
  • candidateList Chris,Jamie,Pat,Sandy

In position 0, Chris, Jamie, Pat, Sandy is one
Ballot There are six Ballots inside the one
instance of VoterBallots shown above
73
"Sample Questions for A",1a p61
  • If we restrict the candidateList, we get
    different results
  • candidateList Chris,Pat

(Ballot)ballotList.get(0) is Chris, Jamie, Pat,
Sandy ((Ballot)ballotList.get(0)).firstChoiceFro
m(candidateList) is "Chris"
74
"Sample Questions for A",1a p61
  • //a member of VoterBallots which has a list of
    ballots called ballotList
  • public int numFirstVotes(String candidate,
    ArrayList candidateList)
  • int nVotes 0
  • for(int nI0 nIltballotList.size() nI)
  • Ballot currentBallot (Ballot)ballotList.get(
    nI)
  • String firstChoice
  • currentBallot.firstChoiceFrom(candida
    teList)
  • if(candidate.equals(firstChoice))
  • nVotes
  • return nVotes

75
"Sample Questions for A",1b p61
  • //a member of VoterBallots which has a list of
    ballots called ballotList
  • public ArrayList candidatesWithFewest(
  • ArrayList
    candidateList)
  • String sFirst (String)candidateList.get(0)
  • int nSmallestNumber numFirstVotes(sFirst,candi
    dateList)
  • for(int nI1 nIltballotList.size() nI)
  • String sCurrent (String)candidateList.get(nI
    )
  • int nVotes numFirstVotes(sCurrent,candidateL
    ist)
  • if(nVotes lt nSmallestNumber)
  • nSmallesNumber nVotes
  • ArrayList losers new ArrayList()
  • for(int nI1 nIltballotList.size() nI)
  • String sCurrent (String)candidateList.get(nI
    )
  • int nVotes numFirstVotes(sCurrent,candidateL
    ist)
  • if(nVotes lt nSmallestNumber)

76
"Sample Questions for A",2 p67
  • public void insert(String str, int index
  • myLine myLine.substring(0,index)
  • str
  • myLine.substring(index)
  • //or myLine.substring(index,myLine.leng
    th())
  • public void delete(String str)
  • int nPosition myLine.indexOf(str)
  • if(nPosition gt -1)
  • myLine myLine.substring(0,nPosition)
  • myLine.substring(nPostion
    str.length)
  • public void deleteAll(String str)
  • while(myLine.indexOf(str) gt -1)

77
"Sample Questions for A",3a p75
  • class SavingsAccount extends Account
  • private double dInterestRate
  • public SavingsAccount(int idNum,
  • double startBal,
    double dI)
  • super(idNum,startBal)
  • dInterestRate dI
  • public void withdraw(double dAmount)
  • decreaseBalance(dAmount)
  • public double monthlyInterest()
  • return dInterestRate /12
    currentBalance()

78
"Sample Questions for A",3b p76
  • public class SpecialCheckingAccount extends
    CheckingAccount
  • private double dMinimum
  • private double dInterestRate
  • public SpecialCheckingAccount(int idNum,double
  • startBal,double chkCharge,double dMin,
    double dInt)
  • super(idNum, startBal,chkCharge)
  • dInterestRate dInt
  • dMinimum dMin
  • public double monthlyInterest()
  • if(currentBalance()ltdMinimum)
  • return super.monthlyInterest()
  • else
  • return dInterestRate /12
    currentBalance()
  • public void clearCheck(double amount)

79
"Sample Questions for A",3c p78
  • public void postMonthlyInterest()
  • for(int nI0nIltaccounts.size()nI)
  • Account theAccount (Account)accounts.get(nI
    )
  • double dInterest theAccount.monthlyInterest
    ()
  • theAccount.deposit(dInterest)

80
"Sample Questions for A",4a,b p78
  • class CircleFish extends Fish
  • private boolean bIsTurning
  • public CircleFish(Environment env, Location
    loc)
  • super(env,loc)
  • bIsTurning false
  • protected Location nextLocation()
  • Location ahead
  • environment().getNeighbor(location(
    ),direction())
  • Location right
  • environment().getNeighbor(ahead,directio
    n().toRight())
  • if(bIsTurning environment().isEmpty(right
    ))
  • return right
  • else if(!bIsTuring environment().isEmpty(
    ahead))
  • return ahead
  • else

81
"Sample Questions for A",4c p78
  • class CircleFish extends Fish
  • protected void move()
  • Location nextLoc nextLocation()
  • if ( ! nextLoc.equals(location()) )
  • Location oldLoc location()
  • changeLocation(nextLoc)
  • if(bIsTurning)
  • changeDirection(direction().toRight())
  • bIsTurning !bIsTurning
  • else
  • changeDirection(direction().toRight())
  • bIsTurning false

82
"Sample Questions for AB",1a p108
  • //
  • private static Queue itemsToQueues(int nums,
    int k)
  • Queue qnew Queue10
  • for(int nI0 nI lt 10 nI)
  • qnInew ListQueue()
  • for(int nI0 nIltnums.length nI)
  • int nQ getDigit(numsnI,k)
  • qnQ.enqueue(new Integer(numsnI))
  • return q

83
"Sample Questions for AB",1b p108
  • //
  • private static int queuesToArray(Queue
    queues,
  • int
    numVals)
  • int naArray new intnumVals
  • int nPos 0
  • for(int nI0 nIlt10 nI)
  • while(!queuesnI.isEmpty())
  • Integer I(Integer)queuesnI.dequeue()
  • naArraynPosI.intValue()
  • nPos
  • return naArray

84
"Sample Questions for AB",1c p108
  • //
  • public static int sort(int nums,int
    numDigits)
  • for(int k 0 kltnumDigits k)
  • nums
  • queuesToArray(itemsToQueues(nums,k),nums.
    length)
  • return nums
  • //or
  • public static int sort(int nums,int
    numDigits)
  • Queue q
  • for(int k 0 kltnumDigits k)
  • q itemsToQueues(nums,k)
  • numsqueuesToArray(q,nums.length)
  • return nums

85
The Map interface
  • Implemented by HashMap and TreeMap
  • Each item must have unique "key"
  • No iterator! (You must get a Set of keys and use
    those to iterate through the Map)
  • public interface Map
  • Object put(Object key, Object value)
  • Object get(Object key)
  • Object remove(Object key)
  • boolean containsKey(Object key)
  • int size()
  • Set keySet()

86
"Sample Questions for AB",2a p111
  • public void addCityToMap(CityInfo theCity)
  • //First attempt
  • theMap.put(theCity.state(),theCity)
  • For a tree, put is O(log n), so it seems like the
    obvious solution
  • The trick here is that Maps don't allow duplicate
    keys, so we are replacing the previous city with
    a new one. If we read the problem carefully,
    each entry in the map is a Set of Cites. We need
    to add our city to the Set of cities.

87
"Sample Questions for AB",2a p111
  • public void addCityToMap(CityInfo theCity )
  • Set cities (Set) theMap.get(theCity.state())
  • if (cities null)
  • cities new HashSet()
  • theMap.put(theCity.state(), cities)
  • cities.add(theCity.city())
  • Note that it must be a HashSet, not a TreeSet.
    get() is O(log n) so we can't spend any more time
    with the put() command. With a hash, put() is
    O(1), with a tree put() is O(log n)

88
"Sample Questions for AB",2b p111
  • public void printOneState(String theState)
  • System.out.print(theState)
  • Set cities (Set) theMap.get(theState)
  • Iterator i cities.iterator()
  • while(i.hasNext())
  • System.out.print(" " i.next())
  • System.out.println()

89
"Sample Questions for AB",2c p111
  • public void printAllStates()
  • Set keys theMap.keySet()
  • Iterator i keys.iterator()
  • while(i.hasNext())
  • printOneState((String)i.next())

90
TreeNode
  • class TreeNode
  • private Object value //note Object!
  • private TreeNode left
  • private TreeNode right
  • public TreeNode(Object initValue, TreeNode
  • initLeft, TreeNode initRight)
  • value initValue left initLeft
  • right initRight
  • public Object getValue() return value
  • public TreeNode getLeft() return left
  • public TreeNode getRight() return right
  • public void setValue(Object theNewValue)
  • value theNewValue
  • public void setLeft(TreeNode theNewLeft)
  • left theNewLeft
  • public void setRight(TreeNode theNewRight)
  • right theNewRight

91
"Sample Questions for AB",3a p118
  • private TreeNode smallerChild(TreeNode t)
  • if(t null)
  • return null
  • else if(t.getLeft()null)
  • return t.getRight()
  • else if(t.getRight()null)
  • return t.getLeft()
  • else
  • Comparable left
  • (Comparable)(t.getLeft().getV
    alue())
  • Comparable right
  • (Comparable)
    (t.getRight().getValue())
  • if (left.compareTo(right) lt 0)
  • return t.getLeft()
  • else
  • return t.getRight()

92
"Sample Questions for AB",3b p118
  • private boolean isHeapOrdered(TreeNode t)
  • TreeNode smaller smallerChild(t)
  • if (smaller null)
  • return true
  • else
  • Comparable temp
  • (Comparable) (t.getValue())
  • return
  • (temp.compareTo(smaller.getValue()) lt 0)
  • isHeapOrdered(t.getLeft())
  • isHeapOrdered(t.getRight())

93
"Sample Questions for AB",3c p118
  • // precondition t is not null
  • private TreeNode removeMinHelper(TreeNode t)
  • TreeNode smaller smallerChild(t)
  • if (smaller null)
  • return null
  • t.setValue(smaller.getValue())
  • if (smaller t.getLeft())
  • t.setLeft(removeMinHelper(t.getLeft()))
  • else
  • t.setRight(removeMinHelper(t.getRight()))
  • return t

94
"Sample Questions for AB",4a
  • public Locatable allObjects()
  • Locatable theObjects
  • new LocatablenumObjects()
  • int tempObjectCount 0
  • for(int nI0 nIltnumRows()nI)
  • ListNode curNode theGridnI
  • while(curNode!null)
  • theObjectstempObjectCount
  • (Locatable)(curNode.getValue())
  • curNode curNode.getNext()
  • nTempObjectCount
  • return theObjects

95
"Sample Questions for AB",4b
  • public void add (Locatable obj)
  • Location loc obj.location()
  • if(!isEmpty(loc))
  • throw new IllegalArgumentException()
  • if(theGridloc.row() null
  • ((Locatable)theGridloc.row().getValue())
  • .location().col() gt loc.col() )
  • theGrid new ListNode(obj,theGridloc.row()
    )
  • else
  • ListNode curNode theGridloc.row()
  • while(curNode.getNext()!null
  • ((Locatable)(curNode.getNext().getValue()
    )
  • .location().col() lt loc.col() )
  • curNode curNode.getNext()
  • ListNode temp new ListNode(obj,curNode.get
    Next())
  • curNode.setNext(temp)
Write a Comment
User Comments (0)
About PowerShow.com