(us)acm working group on algorithmic transparency and...
TRANSCRIPT
(US)ACMWorkingGrouponAlgorithmicTransparencyandAccountability
“...[discussing]thegrowingimpactofalgorithmicdecision-makingonoursociety...”
or,inotherwords,whyyoushouldbeconcernedaboutcomputeralgorithmsdeciding...• whetheryourresumeisselectedortrashed• whatwebsitesshouldbedisplayedinyoursearchresults• howmuchyoushouldpayforcarinsurance• howlikelyyouaretocommitacrime• ...etc
readthestatementhttp://www.acm.org/public-policy/algorithmic-panel
watchthepanelhttps://www.youtube.com/watch?v=DDW-nM8idgg&feature=youtu.be
Today’sbigideas
• Aniterator isanobjectthatreturnsoneelementatatime.Itcanreturnelementsfromadatastructureoranysequencewewant.
• BymakingIteratoraninterface,wecanwritecodethatusesaniteratorbutdoesn’tneedtoknowwhatdatastructuretheelementscamefrom
• Itishelpfultoidentifyaninvariantwhenimplementinganiterator.
• Wecanusegenerictypestowriteadatastructureonceandhaveitworkforanyelementtype
whyyoushouldcareaboutIterators
class ListPrinter {public static void print(LinkedList ls) {
for (int i=0; i<ls.size(); i++) {System.out.print(ls.get(i));System.out.print(",");
}}
}
IfNisthesizeofthelinkedlist,givethetightestupperboundonrunningtimeinbig-Oh.a) 𝑂(1)b) 𝑂(𝑁)c) 𝑂(𝑁𝑙𝑜𝑔𝑁)d) 𝑂(𝑁-)e) 𝑂(𝑁/)
https://b.socrative.com/login/student/roomCS2230Xids1000-2999roomCS2230Yids3000+
Iterator
iterator:Anobjectthatprovideselementsoneatatimeuntiltherearenomore
public interface Iterator {// return the next element or throw error if there is no next elementint next();
// return true if the Iterator has more elementsboolean hasNext();
}
searchenginesendsme15searchresultsthenIscrolltothebottomofthepage...
...andgetthenext15...
CanthinkofthesearchresultsbeingprovidedbyanIterator.Eachcalltonext()returns15moreresultsfromthelistofthousandsofresults
Example:Listiterator
listis[1,5,7,8,14]
Iteratoriter =list.iterator()iter.hasNext()=>trueiter.next()=>1iter.hasNext()=>trueiter.next()=>5iter.hasNext()=>trueiter.next()=>7iter.hasNext()=>trueiter.next()=>8iter.hasNext()=>trueiter.next()=>14iter.hasNext()=>false
Peerinstruction
listis[1,5,8,14]
SupposethatEvens,isanIteratorthatreturnstheevendataofthegivenlistinorder.Whatarethereturnvaluesofthelast5linesofcode?
a) true,8,true,14,falseb) 1,5,8,14,nullc) true,8,true,14,ERRORd) false,null,false,null,truee) false,1,false,5,truef) true,1,true,5,trueg) 8,14,null,null,nullh) 8,14,ERROR
Iteartor iter =newEvens(list);iter.hasNext()iter.next()iter.hasNext()iter.next()iter.hasNext()
https://b.socrative.com/login/student/roomCS2230Xids1000-2999roomCS2230Yids3000+
Iteratorsprovideelement-at-a-timeaccessto“streams”Example:Thestreamofprimenumbers
primes=[2,3,5,7,11,13,17,...]
infinitesequence,sowecannotstoreitinadatastructure,butwecanpretend...
justcalculatethenextprimewhensomeoneasksforit
Whatdoesthiscodeprint?public class Streams2 {
public static class PeerInstruction implements Iterator<Integer> {private int z;private int y;public PeerInstruction() {
z = 0;y = 1;
}public boolean hasNext() {
return true;}public Integer next() {
int t = z;z = y;y = y + t;return t;
}}
public static void main(String[] args) {Iterator<Integer> mystery = new PeerInstruction();while(mystery.hasNext()) {
System.out.print(mystery.next()); System.out.print(“,”);}
}}
a) 1,1,2,3,5,8,13,...b) 0,1,1,2,3,5c) 0,1,2,3,4,5,6,...d) 0,1,1,2,3,5,8,13,...e) 1,2,3,4,5,6
...meansneverends
https://b.socrative.com/login/student/roomCS2230Xids1000-2999roomCS2230Yids3000+
whyyoushouldcareaboutIteratorsPartII
Nisthesizeofthelinkedlist.Assumingareasonableimplementationoftheiterator,whichisthetightestupperboundofrunningtimeofListPrinter.print?a) 𝑂(1)b) 𝑂(𝑁)c) 𝑂(𝑁𝑙𝑜𝑔𝑁)d) 𝑂(𝑁-)e) 𝑂(𝑁/)
https://b.socrative.com/login/student/roomCS2230Xids1000-2999roomCS2230Yids3000+
class ListPrinter {public static void print(LinkedList ls) {Iterator iter = ls.iterator();
while (iter.hasNext()) {System.out.print(iter.next());
}}
}
Returnofinvariants
Whatnon-trivialinvariantsarethereinthefollowingcode?
int sum = 0;for (int i=0; i<5; i++) {
sum += i;}
invariant:anexpressionthatisalwaystrue(somethingthatdoesnotvaryisinvariant)
InvariantsaregoingtobeusefulwhenimplementingIterators
ImplementationofaniteratorforLinkedList
class LinkedList {private ListNode header;public LinkedList() {
header = new ListNode(0);}public Iterator iterator() {
return new LinkedListIterator(header.next);}private class LinkedListIterator implements Iterator {
private ListNode current;public ListIterator(ListNode first) {
this.current = first;}public boolean hasNext() {
return this.current != null;}public Object next() {
if (!hasNext()) throw new NoSuchElementException();
int result = (Integer) current.data;current = current.next;return result;
}}
}
WhatistheinvariantforaLinkedListIterator?(shouldbeintermsofcurrent)
class RepeatsIterator implements Iterator {private Iterator fromIter;private int count;private int currentElement;public RepeatsIterator(Iterator from) {
fromIter = from;count = 0;currentElement = 0; // okay because 0 is never returned findNext();
}private void findNext() {
while (count == currentElement && fromIter.hasNext()) {currentElement = (Integer) fromIter.next();count = 0;
}}public boolean hasNext() {
return count < currentElement;}public Object next() {
if (!hasNext()) throw new NoSuchElementException();int result = currentElement;count++; // invariant broken herefindNext(); // findNext() fixes the invariantreturn result;
}} WhatistheinvariantforaRepeatsIterator beforeandafter(butnot
necessarilyduring)eachcalltonext()?(shouldbeintermsoffromIter, count, currentElement)
RepeatsIterator returnsxcopiesofeachelementxforlist[3,1,2]theiteratorwillreturn3,3,3,1,2,2
PeerinstructionGreaterThanIterator willreturnonlytheelementsoflist whosevalueisgreaterthanK
private class GreaterThanIterator implements Iterator<Integer> {private int nextEle; // index of next element to returnprivate ArrayList<Integer> list; // list being iterated overprivate final int K;
}
Whichoftheseoptionswouldbethemostusefulinvariant?
a) list.get(nextEle) >K||nextEle >=list.size()b) list.get(nextEle)<=K&&nextEle <list.size()c) nextEle ==0d) nextEle >Ke) nextEle <list.size()f) nextEle >=list.size() https://b.socrative.com/login/student/
roomCS2230Xids1000-2999roomCS2230Yids3000+
Buildingpartofadatabasemanagementsystem
Queryprocessor(HW5)
“HowmanyflightsdidSkyWestAirlineshavein2015?”data
(textoratable)
Answer:45001
Thekey:Iteratorsdoalltheworkofprocessingthedata!
HW5
QueryprocessedbyachainofiteratorsHW5
Yourjob:• buildvariousiterators• usethemtoanswersomequeriesonrealdata
TextFileReader("flights.csv")
Filter(airline == "SkyWest" and year == 2015)
Count
while(iter.hasNext()){print(iter.next())
}
next
next
next
SkyWest, 2015, 4:45pmSkyWest, 2010, 12:02pmDelta, 2015, 11:20pm
SkyWest, 2015, 4:45pm
1
Generics:timetostopcasting
// B. compiles but poor code
// C. compiles and good code
// A. does not compile
// 1DogList x = DogLinkedList();x.add(new Dog("pug"));Dog element = x.get(0);CatList y = CatLinkedList();y.add(new Cat("Tabby"));Cat element2 = y.get(0);
// 2List x = LinkedList();x.add(new Dog("pug"));Dog element = x.get(0);List y = LinkedList();y.add(new Cat("tabby"));Cat element2 = y.get(0);
Scrambled:Matchthecodetothecomment// 3List x = LinkedList()x.add(new Dog("pug"));Dog element = (Dog) x.get(0);List y = LinkedList()y.add(new Cat("tabby"));Cat element2 = (Cat) y.get(0);
// 4List<Dog> x = LinkedList<>()x.add(new Dog("pug"));Dog element = x.get(0);List<Cat> y = LinkedList<>()y.add(new Cat("tabby"));Cat element = y.get(0);
(assumeallclassesexist)
Definingaclasses/interfaceswithagenerictype
interface List<T> {T get(int i);T remove(int i);void append(T element);
}
class LinkedList<T> implements List<T> {private ListNode<T> header;
private class ListNode<T> {public T data;public ListNode<T> next;
}T get(int i) { ... }T remove(int i) { ... }void append(T element) { ... }
}
Today’sbigideas
• Aniterator isanobjectthatreturnsoneelementatatime.Itcanreturnelementsfromadatastructureoranysequencewewant.
• BymakingIteratoraninterface,wecanwritecodethatusesaniteratorbutdoesn’tneedtoknowwhatdatastructuretheelementscamefrom
• Itishelpfultoidentifyaninvariantwhenimplementinganiterator.
• Wecanusegenerictypestowriteadatastructureonceandhaveitworkforanyelementtype