Next graded assignment :
Test on System Implementation - Mon 12 May 2014 |
Links : Java
Stuff IB Comp
Sci Text PPT Slides IB Syllabus Guide Glossary of Computing Terms IA Project Web Science |
== HOMEWORK ==
Thur 12 June and Mon 16 June -
Work on any of the following:Friday 13 June
Tuesday 17 June
Here are some Simple Start Prototypes for projects.
Here are copies of the Final Exam and "correct" answers.
In many cases, other answers are also acceptable.
The goal is to write clear, sensible answers that actually answer the
question.
The answers shown here are correct and concise.
Being concise will save time during exams.
Final Exam June 2014 Answers (with help from George)
We will use the last few days of class to start the IA Project.
Here is a working link to the Logic
Simulator
that we used back in October.
In case that doesn't
work, here is another Logic Gate Simulator -
the old one seems to be broken.
PRACTICE WRITING ON PAPER!
When you are writing programming code (Java or Javascript)
- start on a page with plenty of empty space
- write your solution on every second line - skipping a line each
command -
so that you have space to make additions and corrections
Review the entire year. For large topics, where we spent lots of
time,
like the box packing program, spend a little more time than
on the smaller topics, like Linux. But there probably will be at
least one question about Linux, since we never had a test or
a quiz about it.
Study with a friend - you will both help each other,
even if one is asking more questions and the other has more answers.
HL students - we will continue with recursion AFTER the exams,
so there will not be any recursion questions (or questions about
the towers of Hanoi) on the Final Exam. However, there will
be questions about all the OTHER HL topics that we studied
this year.
Both SL and HL must expect questions about Operating Systems
on the final exam.
Keep studying! Keep practicing writing!
Looking back through the class BLOG, and thinking about what we did,
it seems the following topics are significant and will probably
be included in the EYE (End of Year Exam):
Java Programming
- Strings - substring, indexOf, charAt, length, toUpperCase, equals,
parsing, etc.
- Numbers - int, double, float, division & truncation, bits,
bytes, binary, hexadecimal
- if.. commands - == , != , && , ||
- loops - for , while
- methods - parameters, return values
- Arrays - .length, loops for searching, nested loops for sorting,
various algorithms like counting, finding
highest/lowest, matching items, inserting, deleting
simulations with random numbers, simulating games
- Parallel arrays - names and numbers
- algorithms - search (linear/sequential), sorting (Bubble sort,
Selection sort), Big O Efficiency
Computer Systems
- Input - processing - storage - output
- Hardware+Software+Meatware
- Binary storage, system monitor, hex editor
- Processors (CPU) - speed, machine language, Fetch-decode-execute-store
- Memory (RAM, ROM) and Storage - files, disk drives
- Motherboard, data-bus, CPU-Cache-RAM, data-flow, transmission speed
- Operating Systems - times, dates, multitasking
- Logic circuits and logic gates - AND, OR, NOT, XOR, NAND, NOR
Javascript
- GUI Components - button, textfield, textarea
- Parsing with .split and other String commands
- all the same concepts from JAVA can be transferred here as well
System Implementation and Operating Systems
- incompatibilities, business problems, business choices
- dates, languages, time zones, etc
- comparing Windows, Mac OS, Linux
When you are practicing programming, to prepare for the final exam,
try to do it like this:
(1) choose a task, like sorting an array
(2) write a solution on paper (quickly)
(3) type your solution into the editor
(4) test and debug your solution
(5) write the working solution on paper
PRACTICE WRITING!
Begin reviewing for your End of Year Exam (EYE).
We haven't done much programming lately, so that's probably a good place
to start.
Make sure you know how to program in Java and Javascript,
and especially how to manipulate Strings and Arrays.
HL students will do some recursive programming
tomorrow,
but today just refresh your memory about Java and Javascript.
Keep in mind that in the exam, you will be writing algorithms
without a computer, on a sheet of paper.
We will review student answers to these questions.
You should search for answers by:
- watching videos
for example : http://www.cnet.com/videos/reporters-roundtable-chrome-os-and-the-future-of-operating-systems/
- doing Google searches
for example : [which operating systems are most
popular]
- reading articles
for example : http://www.hpl.hp.com/personal/Dejan_Milojicic/OS.pdf
==============================================
We will start discussing RECURSION, using this example:
Hanoi.jar
Java was first created between 1991 and 1994 by a group of programmers at Sun Microsystems. Their goal was to create a modern Object Oriented Language that would run on many platforms. Cross-platform software was possible before then, but always required a special executable program that would run on a specific platform - so every program ended up with many different versions on various OSs. The Java programmers decided on creating a Virtual Machine for each platform - those would be different and "target" specific requirements on the platform - and then create ONE finished Java program that would run on any JVM (Java Virtual Machine). So it should be possible to simply copy a Java program onto any computer and it will run. In actual fact, it isn't quite that perfect, but it comes very close.
If you write a Java program in Processing, you can use Export Application to create an EXECUTABLE program (that means it runs without installing Processing), and you can target Linux, Windows or Mac OS, or all three. Then you can copy the result to the corresponding OS and it should run the same on all platforms. If you are very careful, it actually is possible to create one single target file (a .jar file) that will run on multiple platforms - but this is not as simple as we would like. Still, the JVM concept has indeed made Java a very popular language for producing applications that run on many platforms - Mac OS, Windows, Linux, Android (sort of - see JavaEmulator.com for Android) and others. Apparently it does not run in iOS (iPad, iPhone). Steve Jobs said: "Java's not worth building in. Nobody uses Java anymore. It's this big heavyweight ball and chain." (www.theipadguide.com) That might make us wonder why it runs on MacBooks.
You should try this out today.
The teacher will show another Linux distro - Ubuntu.
This has a different user interface. We will talk a bit
about future improvements in OS design, like:
- What could/should be added to a Smartphone
to improve usability?
- What could/should be added to a desktop operating system
to improve security - something beyond passwords?
- How does Java provide cross-platform software compatibility?
- How else could cross-platform compatibility for software
be improved?
- What are some new hardware that might become common
in the new feature and require new driver support?
In the notes about Operating Systems (below), one very important OS responsibility was left out. What is it?
Watch the teacher demonstrate Linux running on a machine where
it is actually installed. Why is the Virtual Box version so much
slower?
Continue investigating Linux and comparing it to Mac OS and Windows.
Read these notes about Operating Systems and Investigating Linux.
Here are some comparison notes you might like to read:
Linux vs Mac OS Linux vs Windows Mac OS vs Windows
When investigating Operating Systems, you should think
in MODULAR terms, as illustrated here:
We will have a test on Monday 12 May.
The test will cover sections 1.1.1 - 1.1.10 of the
syllabus.
Here are some study questions that you can discuss with other
students.
(1) In September our school has recently installed Haiku to replace
Studywiz.
Teachers started posting assignments in Haiku,
but they will
continue to use Studywiz for collecting
assignments - until
Haiku was functioning well and we are certain it
would work.
(a) Was this a Direct Changeover, a Phased Implementation, or
Parallel Running?
(b) The school offered little Haiku training for teachers and
students.
Describe likely consequences of not
offering extensive training.
(c) Describe who was in charge of the change management for
this implementation.
(d) Describe some underlying technology required for Haiku
to function.
(2) Describe a situation when legacy data formats might cause
problems
when implementing a new computer system.
(3) Outline some compatibility issues that are likely to
occur when
a British company merges with an American
company. These should
be issues that would probably not occur when a
single British company
implements a new computer system only for itself.
(4) Assume that an insurance company has a local email server.
They wish to change to using GMail, which runs on
Google's servers.
(a) Decide whether this would be an example of
Software-as-a-Service.
(b) Outline 2 compatibility issues that might
occur during this implementation.
(c) Outline one advantage and one disadvantage of
making this change.
(5) Describe a situation where data migration is not easy.
(6) (a) Describe 3 different types of software testing
involved in developing
and selling a computer system.
(b) Outline the type of testing that should be
performed by a company
before they convert completely from
one system to a new system.
(7) Outline 4 incompatibilities existing in TIME and DATE data in 2 different countries.
(8) (a) Describe a situation that you experienced when a computer system
did not function as it should, and
you discovered that you could
fix the problem but using the system
differently.
(b) Describe a situation when a computer system
did not work correctly
and you suspected that it was caused by a
"bug" in the software.
(9) Explain why commercial software companies - like Microsoft and Apple
-
sell and distribute software that
still contains "bugs".
Here are some questions to answer.
You should search for answers by:
- watching videos
for example : http://www.cnet.com/videos/reporters-roundtable-chrome-os-and-the-future-of-operating-systems/
- doing Google searches
for example : [which operating systems are most
popular]
- reading articles
for example : http://www.hpl.hp.com/personal/Dejan_Milojicic/OS.pdf
You should have answers and be prepared to discuss your answers
when you come to our next HL meeting. Students who missed class
for a field trip must also find answers to these questions.
You may WORK TOGETHER with other students if you wish - but keep in mind
that the other students may produce inappropriate or incorrect answers.
Still, splitting up the searching might save time.
Questions - Why does "professional" software contain "bugs"?
What is a "bug" anyway? We need to think of some examples.
Why is Javascript likely to contain more bugs
that Java?
We will discuss Syllabus section 1.1.7-1.1.9.
Here are some Date/Time notes at W3schools.
Here are some examples about Date/Time Functions.
We will discuss Syllabus section 1.1.6.
Here are some notes about internationalization in Javascript:
http://www1.kokusaika.jp/advisory/org/en/js_point.html
http://www.w3schools.com/jsref/jsref_tolocalestring.asp
http://devproconnections.com/jquery/localize-your-client-side-javascript-applications
== Practice ==
All these require AUTOMATED solutions - unless it says to "ask the user".
You might want to use Google to find solutions.
Notes about System Implementation
IB Syllabus Guide - Topic 6 = Resource Management
We will discuss standard values for various resources,
as well as how these fit into designing a new computer system.
Homework (before next HL meeting)
(1) Read this page : some notes about various computer types.
(2) Think of a type of computer that was NOT listed on the page above
Topic 1 = System Implementation
You might wish to glance over the following notes:
Notes
about
System Implementation
Here are some study questions that you can discuss with other students.
(1) Our school has recently installed Haiku to replace Studywiz.
Teachers will start posting assignments in Haiku,
but they will
continue to use Studywiz for collecting
assignments - until
Haiku is functioning well and we are certain it
will work.
(a) Is this a Direct Changeover, a Phased Implementation, or
Parallel Running?
(b) The school has offered little Haiku training for teachers and
students.
Describe likely consequences of not
offering extensive training.
(c) Describe who is in charge of the change management for
this implementation.
(d) Describe some underlying technology required for Haiku
to function.
(2) Describe a situation when legacy data formats might cause
problems
when implementing a new computer system.
(3) Outline some compatibility issues that are likely to
occur when
a British company merges with an American
company. These should
be issues that would probably not occur when a
single British company
implements a new computer system.
(4) Assume that an insurance company has a local email server.
They wish to change to using GMail, which runs on
Google's servers.
(a) Decide whether this would be an example of
Software-as-a-Service.
(b) Outline 2 compatibility issues that might
occur during this implementation.
(c) Outline one advantage and one disadvantage of
making this change.
(5) Describe a situation where data migration is not easy.
(6) Describe 3 different types of software testing involved in
developing
and selling a computer system.
(7) Outline a typical backup strategy that is used by personal
computer owners,
but which would probably not be used by a
large corporation.
(8) (a) Explain two reasons that a business might NOT accept automatic
software updates.
(b) Describe two disadvantages of not accepting
automatic software updates.
*** Here
is a solution to the SATvocabulary web-page below ***
*** You might want to review this before your test tomorrow ***
The words are in an Excel spreadsheet file. We cannot copy the
words
directly from the Excel file to a web-page. Instead, we must
export the Excel file into a .CSV file (Comma Separated Values).
Here is the resulting text file.
The basic format of the file is:
word , importance number, another number, definition
Eventually, we would like to SORT the words in order of IMPORTANCE -
hence placing the largest importance numbers at the top,
and the smallest numbers at the bottom. But we will do that later.
Today, we have a simpler problem -
(1) find the largest IMPORTANCE value
(2) display all the words that have that value
Now this file is a bit of a mess, because the export function
did not do exactly what we expected. That doesn't matter so much,
but we may have some ERRORS while searching through the list.
Here
is a starting web-page that just prints the first 10 words
together with the definition. There are instructions for more tasks.
Here is a solution to yesterday's homework.
Here are two web-sites with links to LOTS of BIG data sets.
http://www.scaleunlimited.com/datasets/public-datasets/
Here is a
solution to yesterday's homework.
We will continue making this program page better.
Test Announcement - We will have a 45 min
test on Wed 9 Apr (during period 3).
The test will focus on data-processing and
String methods (especially .split).
It will be a written test - no computers, no notes.
Homework
(1) Add the LOWEST Temperature and the HIGHEST Precipitation to
the [Hi's and Low's] Button
(2) Add a [FIND COUNTRY] Button that inputs the name of a country
and outputs the Abbreviation,
OR inputs the Abbreviation and outputs the
Country. If you use .indexOf, these can
both be accomplished by the same function.
(3) Improve the [Hi's and Low's] output so that it automatically
FINDS the country name
corresponding to an Abbreviation and prints the
country name in the output box.
Here is a solution to Monday's homework:
Under2Million.html
Today
We will study this program : weather.html
- HOMEWORK -This data is from the World Bank's web-site, at
http://databank.worldbank.org/data/download/catalog/cckp_historical_data_0.xls
This is an Excel spreadsheet file, containing 4 spreadsheet tables.
The data was first converted to Comma-Separated-Files (CSV).
These are text files with one row of data per line, data items separated
by commas.
Then two of the text files were copied into <textarea> elements in
the HTML file.
Finally, a Javascript function is used to extract the data from the
<textarea>,
and to search for a specific country code.
We will add further features to this program page.
For example, a function that finds a country and prints the highest and
lowest temperatures.
We will have a look at these data tables :
http://data.worldbank.org/data-catalog/cckp_historical_data
Then we will write
a program (a web-page)
to analyze some temperature data.
We will discuss these notes : Data Analysis Notes
Here is a web-page containing some data.
Homework - In the web-page above, write a method that does the
following:
- use .innerHTML to get all the data from the TopTenCountries
textarea
- use .split to take apart the data into single lines and store these in
an array
- use a loop to count through all 10 countries
- at each country, use .split to chop the line into 3 pieces,
like "3." , "China", "3,456,789"
separating at the TAB (\t) character
- take the area number and .split it into 3 pieces, splitting at the
COMMAS ","
- take the 3 pieces of numbers, e.g. "3" , "456" , "789" and use
concatenation (+) to stick them back together into a
single String
- use parseInt() to change this long String, containing a big number, into
an actual number
- check whether the number is smaller than 2 million. If so, display
(alert) the name of the country.
We will discuss this Homework on Wednesday.
HL students - finish your Tic-Tac-Toe program and bring it to class on Tuesday.
Data
Analysis Notes
Homework : Read these notes for general
concepts. We will NOT
be writing a Java program, but rather using Javascript,
so don't bother downloading the Java program(s).
Just for Fun - Google Whacking -
Do a Google search that returns EXACTLY ONE RESULT.
If you succeed, try to succeed with fewer words.
You must turn in your ePortfolio - including the Word Game -
TODAY.
If your game isn't finished, or it is not working, please write A
NOTE
in Haiku describing the problem(s) - but you still need to turn in your
work TODAY.
If you finish early, you can ask another student to TEST your page,
and you can test theirs. How? Figure something out.
Here
is another idea for clues for your game.
You can make lots more buttons, but don't just let the user
click any button they like - that will make it too easy.
Maybe allow them to click two buttons, then make them
all disappear.
Deadline - you will turn in your Word Game on Thursday 27 March,
before 18:00.
You must turn in your entire ePortfolio, so your Word Game must be
in a sub-folder in IBWORK, with a link in the Log.html file.
Continue working on your Word Game.
Here are some more ideas for hints:
Notice that these hints can be given several times.
Here
is a sample word-game page that shows how you
can include longer lists of words - and many lists -
in your word-game.
We will discuss this new version of our Tic-Tac-Toe program.
Homework :
Finish the part that checks for a winner. Then you should have
a complete and functional Tic-Tac-Toe game for 2 players.
If you can cleverly use loops for to check all 3 rows or all 3 columns,
please do. But that is very tricky. You will probably find it
easier
to simply write 2 IF commands for each row -
one for the X's and another for the O's -
then 2 IF commands for each column,
and 2 IF commands for each diagonal.
Finish this before NEXT HL class, so that you
are prepared for the QUIZ that you will have
about the Tic-Tac-Toe program.
Things to add:
We will continue working on this game for about a week.
Do as much as you can each day, but don't spend many hours at home.
Spend 30 minutes at home each day - that is enough.
Use your time in class productively - this is your chance to get
help from the teacher, especially if your program is "broken".
ePortfolio Check -
Compress your IBWORK folder into a .ZIP archive
and upload it to Haiku before 18:00 today.
- Making a Javascript Word Game -
We will make a Javascript Word Game.
In the game, the user must guess a secret word.
They will receive hints. When they try to guess the word,
the computer will tell them whether they are correct or not.
If the program always has the same secret word,
then the game will not be interesting for very long.
So we need a LIST of words, and the computer
must choose a word at RANDOM from this list.
The simple way to make a list is to use an ARRAY, like this:
var words =
["computer","teacher","student","book","document"] ;
Now we can choose a random word like this:
var num = Math.floor(Math.random()*5) ;
var secret = words[num] ;
Now the program must give hints, for example:
alert("The secret word has " + secret.length + " letters" )
;
alert("The first letter of the word is " + secret.charAt(0) )
;
alert("The letter 'e' occurs in position " +
secret.indexOf("e") ) ;
... or something like that. The commands above might be incorrect -
they have not been tested - but they are at least CLOSE to correct.
For more information about STRING methods,
try this
link at W3Schools.
- Today's Practice -
(1) Create the IBWORK folder on your hard-disk -
use
this template
(2) In the template folder, you will find JOKESPAGE.HTML
Make the following improvements:
(a) Change the green DIV to a white (invisible)
DIV with white text
Then put the DIV
somewhere else. It should still work correctly
for freezing
the jumping button.
(b) Make 3 more buttons. These must be
clicked in a SPECIFIC ORDER.
If clicked in the right order,
each button disappears
and after the last button
disappears, it says "success" in an ALERT dialog.
If the buttons are clicked in the wrong
order,
they all reappear and the user
must start over again.
(3) On Tuesday (not earlier) you must compress your IBWORK folder
into a .ZIP archive and upload it to HAIKU.
Homework - before class on Monday, make sure that you
have a working account for either of the following (or both is even
better):
- Dropbox at http://www.dropbox.com
- Weebly at http://education.weebly.com
Read about an artificial heart
Solutions
to yesterday's practice (dates2.html)
We will discuss the IA Project which is due next March.
We will start making a Tic-Tac-Toe game in Javascript,
starting with this page:
Here is a better version that uses a FUNCTION to create each button.
Before next HL class, make the following improvements:
(1) Change the Javascript to use a LOOP instead of 3 MakeButton commands.
(2) Add 2 more loops to make the next 2 rows of buttons.
(3) Try to change this so that it has NESTED loops instead of 3 separate loops.
(4) Change the nested loops to make 5 rows of 5 columns - a 5x5 board.
Read the first half of Chapter 4 in Eloquent
Javascript.
You can stop at Ex. 4.2 .
For each example [code in a box] you should:
- read the preceding explanation
- read the code in the box
- predict what will happen when the code runs
- click on the little [=] text icon at the right
and then [RUN] the code and check your answer
- if your prediction was incorrect,
read the code again. Then try changing something
and running it again, until you understand the code.
If you don't understand it within a few minutes,
you need to write down a question and bring it to class.
- if your prediction was correct, continue reading and learning.
The teacher will explain how variables and objects
work in Javascript.
Then we will continue making the web-page we started yesterday.
In case you finished all the work yesterday, here are some more things to
try:
We will discuss ACTUAL Dates tomorrow.
Use Komodo (or some other editor) to create a web-page as follows:
Start with a NEW page and type your own HTML and Javascript. Don't start with a page that the teacher created - you need lots of practice TYPING the code, not just copying.
Read these notes about Web Basics.
We will look
at this web-page carefully, to start learning
how to write HTML and JavaScript, to create a "Web-App".
You will need a good text editor, like Komodo.
Download and
install Komodo before our next class.
The following exercises were created at a time when it was possible
for student laptops to communicate with each other. This seems to
have been disabled. So we will modify the instructions slightly.
Your lab partner will be the TEACHER'S laptop. So you need to
talk to the teacher. If, by some odd chance, you can succeed
in accessing the web-servers on other students' laptops, then
please do carry on with a student as a lab partner.
We will start class by connecting your web-servers to the teacher's PC.
You need an installed copy of ABYSS
WEB SERVER (X1)
or any other web-server program that will run on your laptop.
Then do the following exercises.
Once you have completed all these exercises successfully, you have homework.
Homework -
You and your lab partner must attempt to "see" or "visit"
each other's web-server from one house to another. This is not
actually more difficult due to distance - indeed, it SHOULDN'T even
matter
if you are on a different continent. However, it might fail due to
You need to agree on a time to do this, and you need to exchange
IP addresses - by phone or eMail or .... no, please don't use Facebook.
You do NOT need to succeed, but you must ATTEMPT to connect.
If you spend more than 15 minutes on this you can give up.
Bring stories about your experience to class on Monday 3 March.
Homework - start reading chapter 15 in your textbook Computer
Science Illuminated
read section 15.1 before class tomorrow
Also, download and install ABYSS
WEB SERVER (X1).
Questions and Experiments
Here is Wikipedia's explanation of IPv6
Internet Protocol version 6 (IPv6) is the latest revision of the Internet Protocol (IP), the communications protocol that provides an identification and location system for computers on networks and routes traffic across the Internet. IPv6 was developed by the Internet Engineering Task Force (IETF) to deal with the long-anticipated problem of IPv4 address exhaustion. IPv6 is intended to replace IPv4, which still carries the vast majority of Internet traffic as of 2013.[1] As of February 2014, the percentage of users reaching Google services over IPv6 surpassed 3% for the first time.[2] Every device on the Internet must be assigned an IP address in order to communicate with other devices. With the ever-increasing number of new devices being connected to the Internet, the need arose for more addresses than IPv4 is able to accommodate. IPv6 uses a 128-bit address, allowing 2128, or approximately 3.4×1038 addresses, or more than 7.9×1028 times as many as IPv4, which uses 32-bit addresses. IPv4 allows only approximately 4.3 billion addresses. The two protocols are not designed to be interoperable, complicating the transition to IPv6. IPv6 addresses are represented as eight groups of four hexadecimal digits separated by colons, for example 2001:0db8:85a3:0042:1000:8a2e:0370:7334, but methods of abbreviation of this full notation exist. |
5 min start - What
is a browser?
(watch the video) Question: Which is correct? "Less than 8%" or "Fewer than 8%" If you are not sure, how can you find out? |
Future Web Growth and its Consequences for Web Search Architectures
Student Questions
|
Five Minutes Start - watch this video about nano-scale storage
Bring any questions you wish to ask about the Kurzweil video.
Todays Lecture = Questions and some answers
Homework -
HL Students - start reading this document:
Future
Web Growth and its Consequences for Web Search Architectures
You must read ALL THE CHARTS (graphs). Write questions
to bring to HL class on Wednesday. If you also want to read
some of the text, please feel free to do so. We will discuss
the various charts during class on Wednesday.
SL Students - start reading the IB Syllabus
Guide
. . . Section C = Web Science Option
Find 3 vocabulary words that you DO understand.
Find 3 vocabulary words that you DO NOT understand.
Bring questions to class on Thursday.
You watched Michio Kaku's speech about exponential growth as homework.
Today in class we will watch Ray Kurzweil's TED speech on the same subject.
Homework -
SL Students - watch the Ray Kurzweil video again
and write down questions - especially if there
there are words that you don't understand.
HL Students - start reading this document:
Future
Web Growth and its Consequences for Web Search Architectures
You must read ALL THE CHARTS (graphs). Write questions
to bring to HL class on Wednesday. If you also want to read
some of the text, please feel free to do so. But we will discuss
various charts during class on Wednesday.
You have 50 minutes for the test.
Homework -
Watch this video: Michio Kaku - The World in 2030 (start at 5:30 - it lasts one hour)
We will have another video to watch in class on Monday.
*** Next Week ***
The two videos - Michio Kaku and Ray
Kurzweil - will launch
our investigation of BIG DATA, EXPONENTIAL GROWTH and
WEB SCIENCE.
HL students will discuss the following
paper in depth:
Future Web Growth and its Consequences for Web Search Architectures
You might wish to begin reading this. You need to readHere is the
finished program LotsOfWords,
with a TEST button and all 3 Search algorithms.
You might want to study it, do some experiments, etc.
Friday's test will include questions about the EFFICIENCY (speed)
of various algorithms, including sorting and searching in an
array of integers, and Packing Boxes, as well as searching in an array of
Strings.
You do not need to memorize the methods for a Binary Search
or a Dictionary Search, but you should be able to write
the method for a Sequential Search.
String
Algorithms
Homework :
Download the program above. Run it. Load the words, but
DON'T show them.
Use the TEST button to find the word "potato". Use any
algorithm/system
that you wish. Then write the code for a Sequential Search -
that is a simple loop that examines all the words, looking for the
requested word.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We will discuss the future of computer systems next week,
starting with a video of Ray Kurzweil discussing
"The Singularity is Near". Meanwhile, you might be
interested in some articles about the future of
Hard Disk storage:
- 60 TB Disk Drives Could Be a Reality in 2016
- The Future of Computing Power- Massive Increase in Hard Drive Storage in 3-5 Years
Read these notes about Algorithm Efficiency.
Make sure you understand the three types of search:
and understand the different EFFICIENCIES of these searches.
** TEST **
Plan on a test on Friday 14 Feb about Algorithm Efficiency.
Here is the final
version of Kings. Give it a try.
You can try changing MAXI to 7 - that is simpler.
We spent enough time investigating Kings.
Time for a more problem.
Traveling Salesman Problem
Read about the TSP here:
Traveling SalesmanImagine a salesman must start in Paris, and fly to 4 cities (
London, Berlin, Rome, and Athens). What is the shortest
route he can take? This is a famous problem which cannot
be solved efficiently. The straightforward method is to
examine all possible route, calculate the length of each
trip, and choose the smallest. Here is the list of all of
the 24 possible trips (he always starts and finishes in Paris):
Why are there 24 possibilities? There are 4 choices for the first city, then 3 choices for the next, then 2 choices for the next, then 1 choice left for the last city. So the number of possible trips is 4*3*2*1 = 4! (factorial) If the salesmen must visit 10 cities, there are 10! = 3,628,800 - over 3 million trips to examine. The number of trips grows very fast as the number of cities grows. The efficiency of the Travelling Salesman algorithm is O( N ! ) The Travelling Salesman problem is an example of a problem desperately in need of a more efficient algorithm. Although some clever programs have been written for this problem, the programs only guarantee to get a good result, not necessarily the best result. This remains an unsolved problem in Computer Science. |
Wikipedia has some interesting demo applets.
This is a very famous Computer Science problem.
So you can search in Google and find lots more information if you wish,
probably including some simulator programs that "solve" the problem.
Homework : Start with the TSP program that you received
on paper.
You can copy
the text from here.
Add any code that would be useful in solving the TSP problem,
especially answering the questions at the top of the page.
Real World
In reality, a salesman faces a different kind of problem
than the theoretical TSP. For example, what is the SHORTEST ROUTE
to get from one place in a city to another place in the city?
This is the GPS (navigation) problem.
Read about how a GPS finds the shortest route.
Here is an Applet showing Dijkstra's algorithm in practice.We will use the programs that you did for homework.
We will test how FAST an algorithm can find a solution.
How fast (efficient) is the Bubble Sort? O(n^2) in the worst case scenario, also the average case O(n) in the best case not linear = for example 1 sec for 10000, won't take 2 sec for 20000 I ran it on 4000 numbers, took 20 sec I ran it again, and it took 0.1 sec -I think they were already sorted How did this happen? P … 0 to N X … 0 to N if… this happens N*N times On the order of N^2 = O(N^2) Bubble sort can stop early IF it makes ONE ENTIRE PASS with NO SWAPS O(N) in the BEST CASE SCENARIO (already sorted) 50000 in 2 minutes (50 000^2)* constant 100000 (100 000 ^ 2 ) * constant N^2 (2N)^2 = 4 N^2 = 4 times as long for 2 x numbers 100000 took 8 min 1 000 000 = 10 * 100 000 = 10^2 times as long = 100 times as long Random Triples Best case = O(1) Average case = O(1000 seconds) = constant Worst case = number of repetitions (never) AI Hint = sorts, takes 1st number and looks for a match if not, takes 1st and last O(N^2) to sort O(1) O(N) ======================================== HOMEWORK Straightforward analysis of all the algorithms in the PACKING program We did 3 (above) - you do the other 3 for homework Use your computer to check, but also make predictions/explanations |
How good are our Packing algorithms?
Do they work for bigger lists?
What about bigger numbers and bigger boxes?
Are they RELIABLE?
Are they CORRECT?
Are they EFFICIENT (fast)?
Here is a "final" version of the Packing Boxes program.
Here are some NOTES about ALGORITHMS for the Packing Problem.
Homework :
(1) Download the program above
(2) Familiarize yourself with all the buttons in the program
(3) Improve the RECURSIVE solution so that it always
prints a solution, even when it
cannot find 50 or 49 or 48 -
write a LOOP that checks for all
numbers, down to 1
This new
version of PackBoxes contains our first attempt at Artificial
Intelligence (AI) -
the computer makes a HINT of which two items could be packed together.
It is not very good. You can quickly invent a better ALGORITHM than
this one.
Download the program and improve the HINT method. Choose a
reasonable goal,
like "Don't always try the first item." Then improve it more with
any even
better, but more difficult, idea.
What is an algorithm? Definition? Explanation?
Examples? Counter-examples?
Try this from Webopedia: http://www.webopedia.com/TERM/A/algorithm.html
"... set of steps for solving a particular
problem. To be an algorithm, a set of rules must be unambiguous
and have a clear stopping point. Algorithms can be
expressed in any language,
from natural
languages like English or French to programming
languages like FORTRAN"
... and of course Java |
Notice that the concept of an algorithm is not only
limited to computers.
While human algorithms (a set of steps for a person to
follow)
are interesting and instructive, the goal in Computer Science
is to construct a computational algorithm - that means
it
can be executed (followed) by a computer system.
Automation and reliability are significant issues in
Computational Algorithms.
The level of detail is different for computers and
human beings.
We can tell a human being to buy lunch as follows:
For a robot, the commands might be more detailed:
So what is an algorithm for solving the Packing Problem?
Read these notes about the Packing (aka Knapsack) problem.
Here
is a new version of Kings that contains a BoardFull method,
and it displays a message when the human or the computer wins.
Discussion Question : How can we make the computer "think ahead"
so that it chooses the BEST possible move, rather than a random move?
HOMEWORK - work on SOME of the following problems:
/*****
To Do List:
- When computer wins, display it's last move before the message
- If computer plays first, should always take the middle
?? even boards ??? 4 in the middle
- Add more for the computer -
it should choose the square that's the mirror image of the human
- Do you have a better idea?
- What about EVEN boards? How does MIRRORING work there?
******/
After you finish the test (35 minutes) you can start reading
about
famous Cyber Attacks.
Here is a .zip archive for NetBeans containing some Sorting Test Algorithms.
*** In case this doesn't run (heap error), you will need to ***We will study the EFFICIENCY (speed) of these algorithms.
To prepare for your Test on Monday, study the following algorithms:
Sorting and Other Algorithms for an Array of ints
****************************************
*** Remember : Test on Monday (35 minutes) ***
*** about ALGORITHMS like
:
***
*** Sorting an
array
***
*** Reversing an
array
***
*** Inserting in a sorted
array
***
*** Counting specific
items
***
***
etc
***
*** The test will ONLY involve
algorithms ***
*** for one array containing
integers. ***
*** There will be no questions
about
***
*** Parallel arrays, nor about
pseudocode. ***
*** But you must be able to read and write ***
*** Java methods for array
algorithms. ***
****************************************
Here is a .zip archive containing a NetBeans program with a Sorting method.
We will investigate this.
Homework: STUDY the BEHAVIOR of the BUBBLE SORT and the
SELECTION SORT.
You can use the program from the .zip archive (above),
or use either of the following demonstration sites:
- demo with Java source : http://www.solidware.com/sort/
- demo with "bars" but no Java : http://math.hws.edu/TMCM/java/xSortLab/
Homework :
Write a method that REVERSES the numbers in an array.
Notes from NetBeans
private
void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
int temp = nums[0]; nums[0] = nums[numsSize-1]; nums[numsSize-1] = temp; showData(); } private void insert(int nn) { int temp = 0; while(nn>=nums[temp] && temp<numsSize) { temp = temp+1; } for(int x=numsSize-1; x >= temp ; x=x-1) { nums[x+1] = nums[x]; } nums[temp] = nn; numsSize = numsSize+1; } |
Here is a Pseudocode Algorithm that inserts a new element
into an array at position [0].
// Move all the elements in
an array up one position // and then write a new element into position [0] NUMS = [3,5,7,11] SIZE = 4 NN = 2 // New Number loop C from 1 to SIZE POS = SIZE-C NUMS[POS+1] = NUMS[POS] end loop NUMS[0] = NN SIZE = 5 output "Size = " , SIZE loop C from 0 to SIZE-1 output NUMS[C] end loop |
Here are solutions for the searching methods from Friday (below):
https://dl.dropboxusercontent.com/u/275979/ibcomp/arrays/searches.txt
Today we will discuss SORTING.
We will start with SINGLE arrays (not parallel arrays).
Eventually we will see how we can also sort PARALLEL arrays.
Here is a Java Applet animation that demonstrates several Sorting
ALGORITHMS,
as well as showing Java source code for the algorithms.
http://www.solidware.com/sort/
We will write methods for these 3 algorithms.
Pseudocode
Looking ahead, we see that the IB Comp Sci syllabus requires students
to write PSEUDOCODE solutions in exam Paper 1, which counts twice
as much as exam paper 2. So we not only need to learn to write
ALGORITHMS,
and write them in Java, but also to write them in PSEUDOCODE.
One of the IB Computer Science teachers has been kind enough
to create a Pseudocode
Practice Tool that we can use to practice.
Here is a Pseudocode algorithm that finds the smallest number in an array:
NUMS = [3,8,5,2,6,8,7,4,9]; SMALLEST = NUMS[0] loop X from 0 to 8 if NUMS[X] < SMALLEST then SMALLEST = NUMS[X] end if end loop output SMALLEST |
Search methods generally RETURN a single value.
How is it possible to return multiple results?
Today, practice programming with PARALLEL ARRAYS
(using the same arrays from Wednesday) - People.zip
Write methods for as many of the following as you can:
(1) findEmail(name)
(2) findAge(name)
(3) findLargestAge()
(4) findName(email)
(5) calcAverageAge()
(6) findStrangeGrades() .... such as 37, then print out the name
(7) findFamily(last name) ... print all names matching the last name
(8) countPeople(grade) ... count the number of people in a specific grade
(9) allData(name) ... find all the data for a specific name
On Monday, we will be learning to write SORTING methods.
Here is a new
version of Kings, using graphics
and with rules that prevent illegal moves.
Homework - using this new version of Kings,
add a method: checkBoardFull()
and use this in ComputerChooses()
so the computer will know if it wins -
after it makes a move, it does checkBoardFull()
and says "I win" if the board is full.
Rather than saving a RECORD as a single STRING containing several FIELDS,
we can save separate FIELDS in separate ARRAYS -
we call these PARALLEL ARRAYS. For example:
index |
ID |
Full Name |
Age |
Grade | |
0 | 2345 | Lee, Kim | 15 | 10 | KimLee@live.com |
1 | 1978 | Anderson, Alice | 16 | 10 | AliceAnderson@yahoo.de |
2 | 1111 | Farkel, Fred | 15 | 9 | FF99@supermail.mx |
3 | 2222 | Simpson, Homer | 56 | 37 | phonydude@nothing |
4 | 2999 | Sinatra, Frank | 127 | 0 | Frankie@forestlawn.us |
5 | 2500 | Simpson, Prince | 44 | 0 | unknown |
6 | 1234 | Madonna | 44 | 0 | ciccone@gmail.uk |
.... | .... | .... | .... | .... | .... |
Now we need 5 arrays, like this:
int[] ids =
{2354,1978,1111,2222,2999,2500,1234}; String[] names = {"Lee, Kim","Anderson, Alice","Farkel, Fred",....}; int[] ages = {15,16,15,56,127,44,44}; int[] grades = {10,10,9,...}; String[] emails = {"KimLee@live.com",...}; |
Then we can search for an email address like this:
public String
findEmail(String name) { for(int x=0; x < names.length; x = x+1) { if(names[x].equals(name)) { return emails[x]; } } return "Not found"; } |
Hopefully the findEmail method is correct. If not, find the mistake.
Now we can write lots of useful methods, for example:
(1) findEmail(name)
(2) findAge(name)
(3) findLargestAge()
(4) findName(email)
(5) calcAverageAge()
(6) findStrangeGrades() .... such as 37, then print out the name
(7) findFamily(last name) ... print all names matching the last name
(8) countPeople(grade) ... count the number of people in a specific grade
(9) allData(name) ... find all the data for a specific name
(10) SORT ages
(11) SORT names
Homework - Before class on Friday:
1 - make a new NetBeans projectToday we will see how to PARSE the Country Name from each data file,
as well as how to REVEAL WHITE SPACE in NetBeans.
At the end of the period, we will have a 5 minute quiz.
Here are the vocabulary notes from today's lecture:
DATA FILES Information (data) is generally stored in multiple FILES - in our sample program, we have 10 text files - the CIA Factbook has a few hundred files. A FILE is broken into RECORDS - one line in a text file Each RECORD is broken into FIELDS - one data item For example: 97 Germany $ 1,234,567,890 Is the GDP file Sorted? Yes, sorted by: -- GDP highest to lowest -- by RANKING, from 1 to 250 In each RECORD (line) FIELDS can be separated by DELIMITERS - slashes, tabs, etc. Fields could also be FIXED WIDTH, occupying a specific number of characters We can use WHITE SPACE (spaces, tabs) to line things up Data is generally NOT WELL organized = not PERFECTLY organized For example, Tuvalu does not appear in every file, and "United States" is sometimes contained in other names We must learn how to PARSE text files = take data files apart into pieces Our first example of PARSING is getting the RANK number out of a record and turning into an int value. |
Here is the code for finding the data and adding up rankings
for a single country from 10 text files. It contains a getRanking
method,
which starts with a String S and extracts the Ranking field
at the beginning of the String.
String[]
filenames = |
Here is a
NetBeans program that inputs and displays data from
text files that have been downloaded from the CIA
Factbook.
Here are some notes about the program.
Homework:
Make the button (and method) for finding 10 results for 1
country.
It needs to do ALL 10 files - you complete the names in the filenames
array.
Then improve this method so that it ADDS UP the 10 ranking results.
For each result, it needs to:
- use SUBSTRING to extract the number at the beginning
- use Integer.parseInt to change this to an actual number
- add the number to the total with total = total +
number
Here is the method we wrote in class to collect data about Germany.
You need to type it into your copy of the original CIA program.
We will do some of the programming exercises for the KINGS puzzle.
This is done in Processing.
Homework (due at the next HL class)
(4) Change moving (in setup()) so
it prevents illegal moves
that would be
next to a King or on top of a King.
It needs some IF.. commands similar to these:
if (board[row][col] == 'K')
{ bad = true; }
if (board[row+1][col] == 'K') { bad =
true; }
if (board[row][col-1] == 'K') { bad =
true; }
...
Be
careful that you don't check [row+1] when row == 4,
and
don't check [row-1] when row == 0. Same for col = 0 or 4.
Quiz - 10 minute limit
After finishing the quiz, investigate the CIA Factbook.
For example, try to answer the following questions:
(1) Where do people earn the most money :
The
USA
Germany Japan
Some other idea?
(2) Which country has the longest life-expectancy?
(3) In which country is Internet access most available?
(4) Which country is the most "livable" - that is, in which country
are various aspects of living the
best? Which criteria do
you think are most significant?
After the break, we will write a Java program that automatically
answers questions like these.
Here is a good attempt at a solution for the "Oldest CD" problem:
int
oldest = 2013; for(int x=0; x < years.length; x = x+1) { if(years[x] < oldest) { oldest = years[x]; IBIO.output(years[x] + " - " + titles[x]); } } |
Here is a Processing
program that contains a very long list of words.
Download this program and open it in Processing.
Here are some practice exercises - do these in Processing
so you can concentrate on the actual mehods. Do as many
as time permits.
(1) Print the words in locations 5000,10000,15000,20000,...45000.
Use a LOOP to do this.
(2) Make a countLetters method that inputs one single letter, like 's',
and then COUNTS how many words begin with that
letter.
(3) Print the first word in the list that is exactly 3 letters long.
The word might be "ace", but that is uncertain.
(4) Change the search() method so that it will display the
first word it finds that STARTS with the letters
the user types.
For example, if the user types "tot", then the
search()
method displays "total" . It should not
print any more words,
like "totter".
(5) Change the search() method so that it uses a BOOLEAN FLAG
to keep track of whether it found the word or did
not find it.
If the word is NOT found, it should try
again. This time it
should search for the first word that CONTAINS
the user's request.
For example, if the user types "wkw", then
search() prints "awkward".
(6) ADD UP the LENGTHS of all the words, then divide by the total
number of words to find the AVERAGE length
of a word in the list.
(7) Make (or get) a new text file called NAMES.TXT .
Use TextEdit or Notepad to create the
file, typing
one name on each line in the
file. Then copy the
file into the DATA folder in your
processing program folder.
Check that all your methods above
still function correctly
using this different text file.
The first version of the CDList program had a list of titles, like this:
String[] titles = {"Beatles White Album - 1970", "Valtari - 2003", "Nature One - 2005", "James Taylor - 1971", "Netsky - 2003", "DJ Kicks - 2011", "Cher's Hits - 1999" }; |
The data shown above is a bad idea, because:
- it mixes two different kinds of data together in one String -
a TITLE and a YEAR
- the YEAR is no longer in a number format, so it is difficult
to do calculations or comparisons
We will fix these problems today.
Here is a new version of CDListVersion2.
This contains 2 separate PARALLEL ARRAYS - titles[] and years[] .
Parallel Arrays are two arrays that contain connected
lists of data.
String[] titles = {"Okay","Valtari","Nature One","James Taylor"....,"Madonna"}; int[] years = { 1970, 2003, 2005, 1971, ............... ,1999 }; |
Now titles[3] contains a title (James Taylor),
and years[3] contains the corresponding year (1970).
This means that it's possible to manipulate the years as actual numbers -
for example, to check whether a year is between 1970 and 1980, like this:
if( years[x] >= 1970 &&
years[x] <= 1980 )
{ output( titles[x] ); }
So whenever the years[x] value matches the criteria,
we display the corresponding titles[x] .
Version 2 of the CDList program contains a method to search for a
specific year.
The teacher will explain how the [Search Years] method works.
PRACTICE
(1) Download Version 2
(2) Change the Search Years
method to search BETWEEN
two years, e.g. 1970-1980
(3) Make a button to COUNT
all the "new" CDs - like after 2009
It should say a NUMBER, like 3
(4) Make a BUTTON that automatically
finds the OLDEST CD - that would
be the White Album. It needs to
examine the years[ ] array and find
the smallest number.
Here is a simple program that searches for a String
in an array of Strings :
https://dl.dropboxusercontent.com/u/275979/ibcomp/arrays/CDarrays.zip
Here is the Processing version - just for reading the notes.
Homework :
Make a really good SEARCH method that can
- search for a CD name
- search for part of a CD name
- can even find a year like 1970
More work on DiceSimulation -
here
is Version 2 to download.
Now the program has been simplified to display
the rolls and totals in one List box, and all the
statistics in a second List box. There is also
a new button that rolls the dice 1000 times.
Now it will be easier to "study" the simulation.
Now add buttons and write methods to answer
the following questions:
Today's Vocabulary
SCALABILITY : a Computer SYSTEM can easily be made BIGGER RELIABILITY : works in ALL (or at least many) situations SYSTEMATIC : reliable due to repetition and dependable actions REUSABILITY : use METHODS - NOT copy and paste AUTOMATION : the computer does things without being prompted(often loops) |
How do calendars work?
How can we store a calendar in Java?
How do board games work?
How can we store Tic-Tac-Toe or Mine Sweeper or KINGS in Java?
Here is the dice program so far (you need to create the GUI controls):
int[] dice1 = new int[10000]; int[] dice2 = new int[10000]; int[] totals= new int[10000]; int c = 0; private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { int d1 = (int)Math.floor(Math.random()*6 + 1); int d2 = (int)Math.floor(Math.random()*6 + 1); dice1[c] = d1; dice2[c] = d2; totals[c] = d1+d2; c = c+1; tCount.setText(c+""); t1.setText(d1+""); t2.setText(d2+""); list1.add(d1+""); list2.add(d2+""); list3.add((d1+d2)+""); } private void t1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { double tens = 0; for(int x=0; x < c; x = x+1) { if(totals[x]==10) { tens = tens+1; } } tc10.setText( String.format(java.util.Locale.US ,"%.2f",(tens/c)*100) ); IBIO.output(String.format(java.util.Locale.US ,"%.2f %n is a good thing",(tens/c)*100)); } |
Before continuing on the significant problems below (2 Dec),
do the following quick exercises:
- predict what will be printed by this algorithm:
for(int d = 0; d < 5; d = d+1)
{
System.out.println(
dice1[d] );
}
- predict what will be printed by this algorithm:
if( dice1[2] == dice2[2])
{ System.out.println("yes"); }
else
{ System.out.println("no"); }
- predict what will be printed by this algorithm:
for(int d=0; d < 2 ; d=d+1)
{
System.out.println( dice1[d] *
dice2[d] );
}
Now spend the period writing as many of the methods
as you can that are listed below in 2 Dec 2013.
Quiz tomorrow - like the problems above
Homework -
- Download
this NetBeans project.
- Add a text field that shows the COUNT of the number of dice rolls
This is the variable C in the program
- Fix the [Count 10s] so that it counts the number of 10 totals
and then divides by the COUNT (c) to produce a
percentage
- Use String.format("%.2f", value) to display the 10's percent
nicely with 2 decimal places
- Choose any of the tasks below and program one of them
We will do all the tasks below, plus a few, during classes this week.
There are lots of problems to solve.
We need to write Java methods for all of these:
- count the number of times that a 6 appears on Die1
Express the answer as a percent.
This should be 16.666% of the time.
- Calculate the percent of rolls that 1 appears, that 2 appears,
and 3, 4, 5 and 6 on Die1. Express each as a percent.
Put the answers in a set of TextField boxes.
- Round the answers (the percents) to a whole number,
e.g. 17% rather than 0.166666...
Try using this: String.format("%.2f", num*100)
Try reading this: http://www.homeandlearn.co.uk/java/java_formatted_strings.html
Here is a quick
summary about String.format
Or read this longer, clear explanation: Learning
Java p.315-320
- Calculate the percent of times that 7 is the total.
- Calculate percents for all totals: 2,3,4,5,...,10,11,12
- Calculate percents for the number of times that a PAIR
is rolled - that is when dice1[x] and dice2[x] are equal.
- Calculate the percent of rolls that produce an EVEN total,
as well as the percent that produce an ODD total.
- add 3 more dice, so there is a total of 5 dice.
Change the TOTALS so that it reflects 5 dice.
Your methods above (like even and odd totals)
should still work correctly.
1. Do your quiz
2. If you finish early, you can start creating this program in
NetBeans:
private void jButton1ActionPerformed (java.awt.event.ActionEvent evt) { int d1 = (int)Math.floor(Math.random()*6 + 1); int d2 = (int)Math.floor(Math.random()*6 + 1); t1.setText(d1+""); t2.setText(d2+""); list1.add(d1+""); list2.add(d2+""); list3.add((d1+d2)+""); } |
We will expand this program to study probability in dice rolls.
Here is a solution for yesterday's homework:
// This also needs IBIO class
in the project double[] prices = new double[10000]; int c = 0; private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { double money = IBIO.inputDouble("Money"); prices[c] = money; showAllPrices(); c = c+1; } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { // SUM and AVERAGE double sum = 0; for(int x=0; x < c; x = x+1 ) { sum = sum + prices[x]; } jTextField1.setText(sum+""); double ave = sum / c; jTextField2.setText(ave+""); } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { // finding BIGGEST price double biggest = 0; for(int x = 0; x < c; x=x+1) { if(prices[x] > biggest) { biggest = prices[x]; } } jTextField3.setText(biggest + ""); } public void showAllPrices() { list1.removeAll(); for(int x = 0; x <= c; x=x+1) { list1.add(prices[x]+""); // index variable } } |
More Practice -
Predict what each of the following methods will do
and explain the purpose (why it is useful):
- output(prices[c-1]);
- output( c );
- int howMany = 0;
for(int x = 0; x < c ; x = x+1)
{
if( prices[x] < 1.00 )
{ howMany = howMany + 1; }
}
output( howMany + " prices found");
- list1.removeAll();
for(int x = 0; x < c; x = x+2)
{
list1.add( prices[x] + "");
}
Write a METHOD (and possibly add a Button) for each of these:
- find the smallest number in PRICES[]
- display (in the list box) all PRICES that are below 2.00
- COUNT the number of BIG prices - those over 10.00
- input a LIMIT, and count all the prices that are BELOW that LIMIT
- Make a DISCOUNT button
This inputs a price, subtracts 0.50 as a discount, and saves the
discounted price
- Make a CORRECTION button.
When this is pressed, the LAST price (the one at position C-1)
is removed from the list. This must subtract 1 from
C.
This is useful if a wrong price is typed, or a customer
does not have enough money to pay.
Plan on a QUIZ (about 15 minutes) next class, with questions
similar to the practice above.
The very simple example of the Counselor
Appointments
is not the normal way to use arrays - but it is very simple
to understand when you are just starting.
The more normal way to use arrays is to collect data,
in such a way that the actual position in the array is unimportant.
For example, the cafeteria can collect a list of all the transactions
(money collected) that occurs on one day, like this:
index |
Transaction |
0 |
5.50 |
1 |
9.00 |
2 |
1.50 |
3 .... |
3.20 .... more data ... |
At the end of each day, the total amount collected is calculated.
The cafeteria staff may want some other information.
For example:
- what is the largest amount collected from one customer?
- what is the average amount collected?
- how many transactions were less than 1.50?
Each time a price is typed in, it needs to be saved in the array.
But each time, it needs to be saved in the NEXT POSITION
in the array. Here is a simple solution that doesn't quite do
everything we want:
double[] data = new double[1000000];
.......
for(int c = 0; c < 1000000; c = c+1)
{
double price =
IBIO.inputDouble("Price");
data[c] = price;
}
This needs to run all day long. After each price is entered,
another inputDouble box pops up on the screen. It never stops
(at least not before 1 million prices have been entered)
so there is no way to see the total at the end of the day.
Here is a better solution:
double[] data = new double[1000000];
int count = 0;
public void jButton1ActionPerformed(......)
{
double price =
IBIO.inputDouble("Price");
data[count] =
price;
count = count + 1;
}
public void jButton2ActionPerformed(....)
{
showTotal();
showHighest();
showUnder150();
showAverage();
}
The cashier needs to click Button1 for each customer and type a price.
Then they need to click Button2 at the end of the day
(or any other time they wish). We still need to write
the methods that calculate all the statistics.
An even better solution would be calculating all the statistics
after each price is entered, and display these on the screen continually.
Homework :
- write the program that the teacher did in class
- add an AVERAGE button
- add a [BIGGEST] button for the largest price in the array
Counselor
Appointments Stored in an Array
Homework -
- create the same program (above) that the teacher showed in class
- read section 8.1
in this chapter about arrays
IBIO JETS Standard Input/Output
We can use IBIO Input/Output commands in NetBeans, by
adding the IBIO class to a project.
Then you can use input/output commands like this:
IBIO io = new IBIO(); void example() { int x = io.inputInt("Type a number"); int y = io.inputInt("Another number"); if( x == y ) { io.output("You are not very creative"); } else { io.output("The sum is " + (x+y) ); } } |
Practice -
In NetBeans, create a new Project.
Add a BUTTON for each of the following tasks,
and use the IBIO methods for input and output:
- input 2 numbers and output the SUM and the PRODUCT
- input 3 numbers, decide which is the largest
and output that number
- input a "user name" and a "password",
then output "correct" if the user name and the password
contain the same number of letters, e.g. :
"fred" and "magic" ==> wrong
"Bobby" and "magic" ==>
correct
- find one of the problems we did earlier in the year
on this page
of sample programs.
Choose one of the programs and implement this in
NetBeans.
This is our last day to discuss GUI programming.
We will spend a bit more time discussing LIST boxes,
and write a program that removes a name from
one LIST box and copies it into another LIST box.
We created a JFrame Form with a Button and 2 AWT List boxes.
Then we added this code:
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
list1.add("William"); list1.add("Alex"); list1.add("Jung Woo"); list1.add("Paul"); list1.add("Tilman"); } private void list1ActionPerformed(java.awt.event.ActionEvent evt) { String name = list1.getSelectedItem(); list1.remove(name); list2.add(name); } private void list2ActionPerformed(java.awt.event.ActionEvent evt) { String name = list2.getSelectedItem(); list2.remove(name); list1.add(name); } |
Now when the user double-clicks on the first List box (the one containing
names),
the name is moved from List1 into List2. When the user double-clicks
on List2,
the name moves from List2 into List1.
A solution to yesterday's homework:
https://dl.dropboxusercontent.com/u/275979/ibcomp/netbeans/SimpleCalcutator.zip
How to do RadioButtons - a clear and complete tutorial:
http://dwachira.hubpages.com/hub/Programming-In-Java-NetBeans-A-Step-By-Step-Tutorial-For-Beginners-Lesson-41
This is part of a COMPLETE Java tutorial based on NetBeans.
If you want to learn more on your own, this is a good resource.
Today's Discussion -
GUI Controls (Swing and AWT) and OOP (Object Oriented
Programming)
Homework -
Do ONE of the following tutorials - read it and create the
corresponding program:
37. Lesson 37: Working with GUI controls: Label and Text field
38. Lesson 38: Working with GUI controls: Command buttons
39. Lesson 39: Working with GUI controls: Combo box
40. Lesson 40: Working with GUI controls: Check box & Text area
41. Lesson 41: Working with GUI controls: Radio buttons
42. Lesson 42: Working with GUI controls: Java Menus
This
set of tutorials is just the right level for IB students, and covers
pretty
much exactly what you need to learn. It is clear, complete and
straightforward.
If you prefer a reference site, here is a good one:
http://www.leepoint.net/notes-java/index.html
This covers all the basics and many advanced features.
It's not really a tutorial, but it's a good place to find lists of
methods.
For example, here is a summary of String methods:
http://www.leepoint.net/notes-java/summaries/summary-string.html
If you prefer learning from a book, there are many available for
free online,
for example:
(beginner) Java
: A Beginner's Guide
(intermediate) Java Notes by
David Eck Schmidt
Java Course
(advanced) Learning
Java by Niemeyer and Knudsen
Code Snippets and How To's are bits of code that tell you how
to program for a specific task. For example: "How can I change
the background color of a button when the mouse rolls-over it?"
Here are a few "snippet" sites:
(basic) Fluffy Cat
(advanced) Real's How To
(click on [Java])
Homework Practice -
- Create the Data List
- Make a TextField with an [Enter] event
that adds data to the Data List
- Make a Button that adds up all the
numbers in the Data List
NumberA NumberB Total |
// Elapsed Time Solution Hex viewer/editor
void setup() { String first = input("First time"); String second = input("Second time"); if( validTime(first) == true && validTime(second) == true ) { int elapsed = difference(first,second); output(elapsed + " minutes"); } } int difference(String first, String second) { int m1 = Integer.parseInt(first.substring(3,5)) + Integer.parseInt(first.substring(0,2))*60; int m2 = Integer.parseInt(second.substring(3,5)) + Integer.parseInt(second.substring(0,2))*60; return m2 - m1; } public boolean validTime(String time) { boolean okay = true; if(time.length() != 5) { okay = false; } if( !time.substring(2,3).equals(":") ) { okay = false; } char ha = time.charAt(0); char hb = time.charAt(1); char ma = time.charAt(3); char mb = time.charAt(4); if(mb < '0' || mb > '9') { okay = false; } if(ma < '0' || ma > '5') { okay = false; } if(ha < '0' || ha > '2') { okay = false; } if(ha == '2' && hb > '3') { okay = false; } return okay; } public void output(String message) { javax.swing.JOptionPane.showMessageDialog(this,message); } public String input(String prompt) { return javax.swing.JOptionPane.showInputDialog(this,prompt); } |
Keyword
Cipher
Code
Breaking Video
1. Parsing
Strings
2. Homework : Parsing Strings #3 - Email Validation
Do the 3 tasks listed, plus one more of your
choosing.
This can be any rule that is required for email
addresses,
for example the period (dot) cannot be at
the end of the address.
E-Mail your program to Dave_Mulkey@fis.edu
BEFORE class on Friday.
Homework - In the reading
(Savitch) try out
all the String methods on pages 38-41.
Keyword Cipher
Code
Breaking Video
The quiz is postponed until Tuesday 17 Sept 2013.
What happens INSIDE Processing when you click the [Run] button?
What are some SYNTAX RULES that Java programmers must obey?
Homework : Look through (don't read entirely) the
handout from Savitch.
Find 5 things that you already knew about Java.
Find
1 thing that is new to you and sounds important or useful.
HOMEWORK : Type (or copy) the following code into Processing
(you
will also need the IBIO input and output methods):
void setup(){char symbol = 0x00BC;output(symbol + "");println(symbol);}
This will run correctly and print 1/4.
Then try pressing the [Enter] key at various places in that line.
Find out where it's okay to split the line, and where it is not okay.The computer can also store and manipulate words -
we need to use String variables for this task.
We will start our investigation of Strings with this sample program:
void
setup() // the program starts here { String word = input("Type a German word"); if(word.equals("hilfe")) { output("help"); } if(word.equals("essen")) { output("eat"); } if(word.equals("Geld")) { output("money"); } } //====== IBIO Input and Output Commands =========== // You are not required to understand the code below // but you do need to be able to USE Input and Output commands. //------------------------------------------------- public void output(String message) { javax.swing.JOptionPane.showMessageDialog(this,message); } public String input(String prompt) { return javax.swing.JOptionPane.showInputDialog(this,prompt); } //====== Use BIG FONTS in IBIO ==================== // The following just makes all the Fonts bigger. // It's really only necessary for the teacher when // he presents something on the board. //------------------------------------------------- Object big = bigFonts(); public Object bigFonts() { javax.swing.UIManager.put( "OptionPane.messageFont", new javax.swing.plaf.FontUIResource(new java.awt.Font("Verdana", java.awt.Font.BOLD, 24)) ); javax.swing.UIManager.put( "OptionPane.buttonFont", new javax.swing.plaf.FontUIResource(new java.awt.Font("Verdana", java.awt.Font.BOLD, 24)) ); javax.swing.UIManager.put( "TextField.font", new javax.swing.plaf.FontUIResource(new java.awt.Font("Verdana", java.awt.Font.BOLD, 24)) ); return null; } |
This contains numerous new words.
The teacher will explain what it all means.
Then we will turn this into a useful program.
Background Reading : Automation
Homework (complete before HL class on
Friday 13 Sep):
- read all the notes (in Automation above), watch all the videos,
and investigate some SENSORS in some real devices,
especially your toaster at home. How does the toaster
"know"
when the toast is done and should "pop up".
-------------------------------------------------------------
IB Syllabus 7.1.1 : Discuss a range of control systems.
A variety of control systems should be examined such as automatic
doors, heating systems , taxi meters, elevators,
washing machines, process control, device drivers,
domestic robots, GPS systems, traffic lights
and other common devices.Technical knowledge of specific systems is not expected but
students should be able to analyze a specified system.
IB Computer Science Course Guide p.39
We will study some sample control systems.
In each case, consider the following questions:
Here are some useful links for the discussion:
http://www.nasa.gov/mission_pages/msl/index.html
http://www.howstuffworks.com/robot.htm
We want to answer the following questions:
Today's Assignment
How do we define the term computer?
We will discuss these notes Computer
Systems
Notes .
Homework
Read chapter
1.1 in your textbook.
==== Read the information below as time permits ====
Welcome to IB Computer
Science ~~~~ |