OOD – Basic Elements of ADTs – Cryptography – Shannon

Screen Shot 2015-05-01 at 11.18.58 AM

In.java

Screen Shot 2015-04-29 at 10.32.07 AM

Basic elements of a data type.

  • API.
  • Class.
  • Access modifiers.
  • Instance variables.
  • Constructors.
  • Instance methods.
  • Variable names in methods.

Basic components that you need to understand to be able to build data types in Java.

classcharge

 

NOTE:

You should be working on the programming assignment and gradient assignments before you start working on OOD programs.

 

Classwork/Homework: NO DUE DATE HAS BEEN ASSIGNED YET

These assignments are to be developed using the basic elements of data types.

Generating cryptograms. A cryptogram is obtained by scrambling English text by replacing each letter with another letter. Write a program, YI_Crypto1.java to generate a random permutation of the 26 letters and use this to map letters. Give example: Don’t scramble punctuation or whitespace.

crypto

Entropy. The Shannon entropy measures the information content of an input string and plays a cornerstone role in information theory and data compression.

Screen Shot 2015-05-05 at 8.21.45 PM        Screen Shot 2015-05-05 at 8.23.34 PM    Shannon Entropy Calculator

Shannon is famous for having founded information theory.
It was proposed by Claude Shannon in 1948, borrowing upon the concept in statistical thermodynamics. Assuming each character i appears with probability p(_{i}), the entropy is defined to be H = – sum p(_{i}) log(_{2})p(_{i}), where the contribution is 0 if p(_{i}) = 0. Compute entropy of DNA sequence.
(a) Write a program, YI_Entropy1.java to read in a ASCII text string from standard input, count the number of times each ASCII character occurs, and compute the entropy, assuming each character appears with the given probabilities.
(b) Repeat part (a) but use Unicode.

entropy1

Screen Shot 2015-05-25 at 1.40.56 AM

OOD: BallDriver and CollidingBalls Videos

BallDriver Video #1
A short video for Ball and BallDriver – Looking at the geometry behind the relative distance between 2 balls.
Oops: I meant radius.

BallDriver Video #2
Going over the first changes we did to the original code.

BallDriver Video #3
Integrating the geometry into the implementation to have a better way to determine the distance apart from a pair of balls.

BallDriver Video #4
Overloading
A quick look at two constructors for the same class.

BallDriver Video #5
Ball ADT and BallDriver Complete
This is the final version of the BallDriver assignment. The important concept to learn is how accessor methods are used to get information from the input argument which is an object of the Ball ADT. This illustrates ENCAPSULATION since instance fields are private and public methods are needed to get access to their values.

BallDriver Video #6
Last video and final implementation (no color)

BallDriver Video #7
Code for color changing of the balls

BallDriver Video #8
Putting color in the BallDriver assignment.

CollidingBalls Video #9
Overloading Trick

How to make a short video of your animations using QuickTime

OOD: ADT Intro

January 30th, 2015

Start reading the material in this site:
Screen Shot 2015-01-30 at 10.41.45 AM

Slides
Screen Shot 2015-01-30 at 10.40.17 AM

The Math class:
Math.pow(10, 3)

In Java, numbers as primitive data types are not objects, so you can never invoke a method on a number.
Instead, you pass a number as an explicit parameter to a method
ClassName.methodName(parameters)
1. What happens to this code fragment when you compile it?

int x = 2;
System.out.println(x.pow(3));

2. What is the difference between an ADT and a primitive data type? What can you create with an ADT?

The String Class
In Java, strings are objects that belong to the class String.
You do not need to call a constructor to create a string object.

A string is a sequence of characters. Strings are objects of the String class.

The substring method computes substrings of a string.

The call s.substring(start, pastEnd)

returns a string that is made up of the characters in the string s, starting at position start, and containing all characters up to, but not including, the position pastEnd.

Here is an example:
String greeting = “Hello, World!”;
String sub = greeting.substring(0, 5); // sub is “Hello”

H e l l o , W o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12

The position number of the last character (12 for the string “Hello, World!”) is always 1 less than the length of the string.

Let us figure out how to extract the substring “World”.
Count characters starting at 0, not 1. You find that W, the eighth character, has position number 7. The first character that you don’t want, !, is the character at position 12 .

<—–5—->
H e l l o , |W o r l d | !
0 1 2 3 4 5 6 |7 8 9 10 11 | 12

String sub2 = greeting.substring(7, 12);

You can easily compute the length of the substring: It is pastEnd – start. For example, the string “World” has length 12 – 7 = 5.

If you omit the second parameter of the substring method, then all characters from the starting position to the end of the string are copied.

For example,
String tail = greeting.substring(7); // tail is “World!”

3. Why can you have multiple substring methods doing something different?

If you supply an illegal string position (a negative number, or a value that is larger than the length of the string), then your program terminates with an error message.

4. Will it be an error during compilation or at run time?

Strings and the char Type
Strings are sequences of Unicode characters.
Character literals look like string literals, but we use single quotes: ‘M’ is a character, “M” is a string containing a single character.

Characters have integer values.
ASCII link attached below

You can use escape sequences inside character literals. For example, ‘\n’ is the newline character, and ‘\u00E9’ is the character é.

“When Java was first designed, each Unicode character was encoded as a two-byte quantity. The char type was intended to hold the code of a Unicode character. However, as of 2003, Unicode had grown so large that some characters needed to be encoded as pairs of char values. Thus, you can no longer think of a char value as a character. Technically speaking, a char value is a code unit in the UTF-16 encoding of Unicode. That encoding represents the most common characters as a single char value, and less common or supplementary characters as a pair of char values.” Clay Horstmann
More on this in the stackoverflow link

The charAt method of the String class returns a code unit from a string. As with the substring method, the positions in the string are counted starting at 0.
For example, the statement

String greeting = “Hello”;
char ch = greeting.charAt(0);

sets ch to the value ‘H’.

5. How do you find out the number of characters a string has?
6. How can you create an array of char type containing all the characters of a string?

OOD: Chapter 2: VN 2.1 BlueJ

OOD Resources
BlueJ – Objects First

Chapter 2: VN 2.1 The naive ticket machine project


Chapter 2: VN 2.2 introduction to source code – fields and constructors


Chapter 2: VN 2.3 Creating, documenting and testing a new class


Chapter 3: VN 3.1 Fields of class types


Chapter 3: VN 3.2 Constructors and field initialization


Chapter 3: VN 3.3 Solving the 12-hour clock exercise

OOD – My School: Multi – ADT application And More

/**
 * Teacher t1 = new Teacher("Sarah", "Clark", 35, "female", "Hello, class!");
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Teacher
{
    private String firstName;
    private String lastName;
    private String age;
    private String gender;
    private String greeting;
    private Course course;
    private Student aStudent;

    public Teacher(String firstName, String lastName,Course course,Student stu)
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.course = course;
        aStudent = stu;
    }

    // draw teacher(s)
    public void draw()
    {
        StdDraw.picture(-1,-1.5,"school_teachers.png",2,1);
    }
    
    // getter/accessor methods
    public String getName()
    {
        return firstName+ " " + lastName;
    }

    public String getAge()
    {
        return age;
    }    

    public String getGender()
    {
        return gender;
    }

    public String getGreeting()
    {
        return greeting;
    }

    public String toString()
    {
        String output = "";
        output += "Teacher name: " + firstName + " " + lastName + "\nCourse Taught: " + course + "\nStudent: " + aStudent ;

        return output;
    }
}

/**
 * Cistomized driver to test all the different parts of my class MySchoolTest
 *
 * @RA & mrs.e
 * @1.8 3/13/18 & 5/10/19
 */
public class MySchoolTest
{
    public static void main(String [] args)
    {
        //StdDraw.setXscale(-2.03,2.03);
        //StdDraw.setYscale(-2.03,2.03);
        StdDraw.setXscale(-2,2);
        StdDraw.setYscale(-2,2);
        
        //create an object of student
        //then create 3 objects of course
        //afterwards we add the 3 objects of course to the student 
        Student konoa = new Student("Konoa", "Smith", "15", "female", "1234");  
        konoa.draw();

        Course c1 = new Course("Biology", "5", "102");
        Course c2 = new Course("precalculus", "4", "136");
        Course c3 = new Course("APUSH", "7", "117");

        // create an object of Teacher
        Teacher mrBill = new Teacher("Jasmine", "Flores", "28", "MYOB", "Namaste", c1);
        // print a teacher
        System.out.println("\n" + mrBill);
        mrBill.draw();

        // print a course information
        System.out.println("Print a course ");
        System.out.println(c1);

        // add all courses to an array
        Course [] courses = { c1,c2,c3};

        // assign all courses to a student
        konoa.setCourses(courses);
        c1.draw();
        //print a student info and courses
        System.out.println("\n" + konoa);
        
        /**
        *  I omitted the school object for easier understanding 
        *  of few interacting ADT objects
        */
    }

}

/* 
 * Teacher name: Jasmine Flores
 * Course Taught: 
 * Class name: Biology
 * Room Number: 102
 * Period:  5
 * 
 * Print a course 
 * Class name: Biology
 * Room Number: 102
 * Period:  5

 * Student name: Konoa Smith
 * Courses: 

 * Class name: Biology
 * Room Number: 102
 * Period:  5

 * Class name: precalculus
 * Room Number: 136
 * Period:  4

 * Class name: APUSH
 * Room Number: 117
 * Period:  7

 * 
 */

OOD Project: LFSR by steps

Animations using java
duke

Screen Shot 2015-02-23 at 12.19.21 AM

REMINDER: Ms. Newman should be coming to PHS after school

  1. Simulate one step. The step() method simulates one step of the LFSR and returns the rightmost bit as an integer (0 or 1). For example,
// LFSR lfsr1 = new LFSR("01101000010", 9);
// for this assignment the seed and tap can be hardcoded or input
String lfsr1 = "01101000010";
int tap = 9;
StdOut.println(lfsr1);
for (int i = 0; i < 10; i++) {
    // int bit = lfsr1.step();
    // code to create a sequence of 0s and 1s like the example below
    StdOut.println(lfsr1 + " " + bit);
}

outputs
01101000010
11010000101 1
10100001011 1
01000010110 0
10000101100 0
00001011001 1
00010110010 0
00101100100 0
01011001001 1
10110010010 0
01100100100 0

  1. Extracting multiple bits. The method generate() takes a positive integer k as an argument and returns a k-bit integer obtained by simulating k steps of the LFSR. This task is easy to accomplish with a little arithmetic:
  • initialize a variable to zero
  • for each bit extracted, double the variable
  • add the bit returned by step()

For example, extracting (from left to right) each bit from the sequence 1 1 0 0 1, the variable takes on the values 1, 3, 6, 12, and 25, ending with the binary representation of the bit sequence.

gen = 0
gen = gen * 2 + new_bit = 0 * 2 + 1 = 1
gen = gen * 2 + new_bit = 1 * 2 + 1 = 3
gen = gen * 2 + new_bit = 3 * 2 + 0 = 6
gen = gen * 2 + new_bit = 6 * 2 + 0 = 12
gen = gen * 2 + new_bit = 12 * 2 + 1 = 25

For example,

// LFSR lfsr2 = new LFSR("01101000010", 9); 
// for this assignment the seed and tap can be hardcoded or input
String lfsr2 = "01101000010";
int tap = 9;
StdOut.println(lfsr2);
for (int i = 0; i < 10; i++) {
    // int r = lfsr2.generate(5);
    // code to generate a number like 25 in the example above
    StdOut.println(lfsr2 + " " + r);
}

outputs
01101000010
00001011001 25
01100100100 4
10010011110 30
01111011011 27
01101110010 18
11001011010 26
01101011100 28
01110011000 24
01100010111 23
01011111101 29

Classwork:
Write a java program, YI_LFSRSim.java to generate an output like the one right above for a given seed.
NOTE: It doesn’t have to be OOP.

OOD Project: LFSR Assignment

Animations using java
duke

Screen Shot 2015-02-23 at 12.19.21 AM

[spoiler title=’Picture.java’]

import java.awt.Color;
import java.awt.FileDialog;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;


/**
 *  This class provides methods for manipulating individual pixels of
 *  an image. The original image can be read from a .jpg, .gif,
 *  or .png file or the user can create a blank image of a given size.
 *  This class includes methods for displaying the image in a window on
 *  the screen or saving it to a file.
 *
  • Pixel (x, y) is column x and row y. * By default, the origin (0, 0) is upper left, which is a common convention * in image processing. * The method setOriginLowerLeft() change the origin to the lower left. *

  • For additional documentation, see * Section 3.1 of * Introduction to Programming in Java: An Interdisciplinary Approach * by Robert Sedgewick and Kevin Wayne. * * @author Robert Sedgewick * @author Kevin Wayne */ public final class Picture implements ActionListener { private BufferedImage image; // the rasterized image private JFrame frame; // on-screen view private String filename; // name of file private boolean isOriginUpperLeft = true; // location of origin private final int width, height; // width and height /** * Initializes a blank width-by-height picture, with width columns * and height rows, where each pixel is black. * * @param width the width of the picture * @param height the height of the picture */ public Picture(int width, int height) { if (width < 0) throw new IllegalArgumentException(“width must be nonnegative”); if (height < 0) throw new IllegalArgumentException(“height must be nonnegative”); this.width = width; this.height = height; image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // set to TYPE_INT_ARGB to support transparency filename = width + “-by-” + height; } /** * Initializes a new picture that is a deep copy of the argument picture. * * @param picture the picture to copy */ public Picture(Picture picture) { width = picture.width(); height = picture.height(); image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); filename = picture.filename; for (int col = 0; col < width(); col++) for (int row = 0; row < height(); row++) image.setRGB(col, row, picture.get(col, row).getRGB()); } /** * Initializes a picture by reading from a file or URL. * * @param filename the name of the file (.png, .gif, or .jpg) or URL. */ public Picture(String filename) { this.filename = filename; try { // try to read from file in working directory File file = new File(filename); if (file.isFile()) { image = ImageIO.read(file); } // now try to read from file in same directory as this .class file else { URL url = getClass().getResource(filename); if (url == null) { url = new URL(filename); } image = ImageIO.read(url); } if (image == null) { throw new IllegalArgumentException(“Invalid image file: ” + filename); } width = image.getWidth(null); height = image.getHeight(null); } catch (IOException e) { // e.printStackTrace(); throw new RuntimeException(“Could not open file: ” + filename); } } /** * Initializes a picture by reading in a .png, .gif, or .jpg from a file. * * @param file the file */ public Picture(File file) { try { image = ImageIO.read(file); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(“Could not open file: ” + file); } if (image == null) { throw new RuntimeException(“Invalid image file: ” + file); } width = image.getWidth(null); height = image.getHeight(null); filename = file.getName(); } /** * Returns a JLabel containing this picture, for embedding in a JPanel, * JFrame or other GUI widget. * * @return the JLabel */ public JLabel getJLabel() { if (image == null) return null; // no image available ImageIcon icon = new ImageIcon(image); return new JLabel(icon); } /** * Sets the origin to be the upper left pixel. This is the default. */ public void setOriginUpperLeft() { isOriginUpperLeft = true; } /** * Sets the origin to be the lower left pixel. */ public void setOriginLowerLeft() { isOriginUpperLeft = false; } /** * Displays the picture in a window on the screen. */ public void show() { // create the GUI for viewing the image if needed if (frame == null) { frame = new JFrame(); JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu(“File”); menuBar.add(menu); JMenuItem menuItem1 = new JMenuItem(” Save… “); menuItem1.addActionListener(this); menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask())); menu.add(menuItem1); frame.setJMenuBar(menuBar); frame.setContentPane(getJLabel()); // f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setTitle(filename); frame.setResizable(false); frame.pack(); frame.setVisible(true); } // draw frame.repaint(); } /** * Returns the height of the picture. * * @return the height of the picture (in pixels) */ public int height() { return height; } /** * Returns the width of the picture. * * @return the width of the picture (in pixels) */ public int width() { return width; } /** * Returns the color of pixel (col, row). * * @param col the column index * @param row the row index * @return the color of pixel (col, row) * @throws IndexOutOfBoundsException unless both 0 ≤ col < width * and 0 ≤ row < height */ public Color get(int col, int row) { if (col < 0 || col >= width()) throw new IndexOutOfBoundsException(“col must be between 0 and ” + (width()-1) + “: ” + col); if (row < 0 || row >= height()) throw new IndexOutOfBoundsException(“row must be between 0 and ” + (height()-1) + “: ” + col); if (isOriginUpperLeft) return new Color(image.getRGB(col, row)); else return new Color(image.getRGB(col, height – row – 1)); } /** * Sets the color of pixel (col, row) to given color. * * @param col the column index * @param row the row index * @param color the color * @throws IndexOutOfBoundsException unless both 0 ≤ col < width * and 0 ≤ row < height * @throws NullPointerException if color is null */ public void set(int col, int row, Color color) { if (col < 0 || col >= width()) throw new IndexOutOfBoundsException(“col must be between 0 and ” + (width()-1) + “: ” + col); if (row < 0 || row >= height()) throw new IndexOutOfBoundsException(“row must be between 0 and ” + (height()-1) + “: ” + row); if (color == null) throw new NullPointerException(“can’t set Color to null”); if (isOriginUpperLeft) image.setRGB(col, row, color.getRGB()); else image.setRGB(col, height – row – 1, color.getRGB()); } /** * Returns true if this picture is equal to the argument picture. * * @param other the other picture * @return true if this picture is the same dimension as other * and if all pixels have the same color; false otherwise */ public boolean equals(Object other) { if (other == this) return true; if (other == null) return false; if (other.getClass() != this.getClass()) return false; Picture that = (Picture) other; if (this.width() != that.width()) return false; if (this.height() != that.height()) return false; for (int col = 0; col < width(); col++) for (int row = 0; row < height(); row++) if (!this.get(col, row).equals(that.get(col, row))) return false; return true; } /** * This operation is not supported because pictures are mutable. * * @return does not return a value * @throws UnsupportedOperationException if called */ public int hashCode() { throw new UnsupportedOperationException(“hashCode() is not supported because pictures are mutable”); } /** * Saves the picture to a file in a standard image format. * The filetype must be .png or .jpg. * * @param name the name of the file */ public void save(String name) { save(new File(name)); } /** * Saves the picture to a file in a PNG or JPEG image format. * * @param file the file */ public void save(File file) { filename = file.getName(); if (frame != null) frame.setTitle(filename); String suffix = filename.substring(filename.lastIndexOf(‘.’) + 1); suffix = suffix.toLowerCase(); if (suffix.equals(“jpg”) || suffix.equals(“png”)) { try { ImageIO.write(image, suffix, file); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println(“Error: filename must end in .jpg or .png”); } } /** * Opens a save dialog box when the user selects “Save As” from the menu. */ @Override public void actionPerformed(ActionEvent e) { FileDialog chooser = new FileDialog(frame, “Use a .png or .jpg extension”, FileDialog.SAVE); chooser.setVisible(true); if (chooser.getFile() != null) { save(chooser.getDirectory() + File.separator + chooser.getFile()); } } /** * Unit tests this Picture data type. * Reads a picture specified by the command-line argument, * and shows it in a window on the screen. */ public static void main(String[] args) { Picture picture = new Picture(args[0]); System.out.printf(“%d-by-%d\n”, picture.width(), picture.height()); picture.show(); } }

[/spoiler]

Write a java program, YI_Pixels30x30.java to display the RGB colors of the top area of the image in this format:

R     G    B
196   200  105
155   0    50
...

OOD Project: LFSR

Animations using java
duke

Screen Shot 2015-02-23 at 12.19.21 AM

If you are still trying to fit all the piece together, look again at the transform method from PhotoMagic.java:

The transform() method
Takes a Picture and an LFSR as arguments and returns a new Picture object that is the result of transforming the argument picture using the LFSR as follows:

  1. For each pixel (col, row), in column-major order—(0, 0), (0, 1), (0, 2), … —extract the red, green, and blue components of the color (each component is an integer between 0 and 255).
  2. Then, xor the red component with a newly-generated 8-bit integer.
  3. Do the same for the green (using another new 8-bit integer) and, finally, the blue.
  4. Create a new Color object using the result of the xor operations, and set the pixel in the new picture to that color.

OOD: Dodge Ball Game Videos

Dodge Game Video #1
Project Setup

Dodge Game Video #2
Mouse Follower

Dodge Game Video #3
Simple Weighted Attraction

Dodge Game Video #4
Dodge Game Spring Moti

Dodge Ball video #5
Changing the MouseFollower into an ADT part 1 of 2

Dodge Ball video #6
Changing the MouseFollower into an ADT part 2 of 2

Dodge Ball video #7
Player and CollidingBalls integrated into the driver, DodgeGame (1 of 2)

Dodge Ball video #8
Player and CollidingBalls integrated into the driver, DodgeGame (2 of 2)

How to make a short video of your animations using QuickTime