Java and Robotics - Assignment List
Computer Science and Java
1 Hello World!
Create a new project in Eclipse and name it “Day One Assignments” then add a class to it named “HelloWorld” (omit the quotation marks in both cases). Write a statement in the main method to print the words “Hello World!” to the screen. Often times, engineers write a simple program like this to test if their programming environment is working and to get used to the syntax of a new language they are learning. When you are done, save your program, export it to a zip file, and upload it to the class dropbox. From now on, you will back up all of your programs at the end of the day like this. Remember to hit the save button frequently when programming!
2 The Area of a Trapezoid
Write a method that calculates the area of a trapezoid. The area of a trapezoid can be calculated with this equation:
A = h × (b1+ b2)
2 (1)
Your method should take as input h, b1 and b2, and return the area of the trapezoid.
3 Quadratic Equation Solver
Write a method that calculates the roots of a function that looks like y = ax2+ bx + c. The roots of a function are the values of x that make y equal to 0. They can be found using this equation:
x = −b ± √
b2− 4ac
2a (2)
Your method should take as input a, b, and c and return two values of x. Also print the values of x to the screen.
4 The Boolean Satisfiability Problem
Consider the following series of pseudo-Java statements. Initialize the values of the boolean variables w, x, y, and z such that the boolean variable exp1 evaluates to true. Do the same for exp2, exp3, and exp4. Verify your answers by programming a short method. Note: all statements are satisfiable.
1 boolean w = ---; 2 boolean x = ---; 3 boolean y = ---; 4 boolean z = ---; 5
6 boolean exp1 = !(x && y) || z;
7 boolean exp2 = (x || (y && z)) && (y && !x);
8 boolean exp3 = (!w || x) && (x || y) && (w || z) && (y || z);
9 boolean exp4 = (!w || y || z) && (x || !y || z) && (w || !y || !z);
5 Conditional Statements
What will be printed on the screen after the following code runs? Which code blocks (A, B, C, or D) will the Java Virtual Machine run? What about when x is initialized to 25 and y is initialized to 5? First try to solve it by running through the code in your head. Then check your answer by writing a Java method with this code and running it. Use print statements to understand which code blocks get executed and which do not.
1 int x = 5; 2 int y = 25;
3 boolean isJavaCool = true; 4 5 if ( x < 10 && y > 10 ) { 6 // Block A 7 x = x + 5; 8 y = y - 15; 9 } else if ( x >= 10 && y <= 10 ) { 10 // Block B 11 x = x - 5; 12 y = y + 25; 13 isJavaCool = false; 14 } else { 15 // Block C 16 x = 0; 17 y = 0; 18 } 19 20 if ( !isJavaCool ) { 21 // Block D 22 x = x*5; 23 y = y*15; 24 } 25
26 System.out.println("x = " + x "and y = " + y); 27 System.out.println("Java is cool: " + isJavaCool);
6 Getting Loopy with Loops
Write a for loop to print out the following pattern of numbers up to the 100thnumber: 2, 5, 8, 11, 14, 17 . . .
Can you write a for loop to print out the Fibonacci sequence of numbers up to the 100thnumber: 0, 1, 1, 2, 3, 5, 8 . . .
The nth term of the Fibonacci sequence, f
n, is the sum of the two previous terms: fn= fn−1+ fn−2
7 Finding the Maximum Value of an Array
Write a method that takes as input an array of floats and returns the highest number in this array and its location. Also print the highest value and its location to the screen. Can you write another method that finds the minimum value of an array and its location? Comment this code well because you might be using it later in the course!
8 Calculating Statistics
Write a method that takes as input an array of doubles, calculates the statistical mean and returns it. The mean of n numbers is defined as:
¯
x = x1+ x2+ x3+ . . . + xn
n (3)
Write another method that takes as input an array of doubles and returns the standard deviation. The standard deviation of n numbers is defined as:
σx= r
(x1− ¯x)2+ (x2− ¯x)2+ (x3− ¯x)2+ . . . + (xn− ¯x)2
n (4)
9 Multidimensional Distance Formula
This distance between two points in n-dimensional space is given by the following formula:
distance =p(x1− x2)2+ (y1− y2)2+ (z1− z2)2+ . . . (5) Where subscript 1 denotes the coordinates of the first point and subscript 2 denotes coordinates of the second point. Program a method that takes as input two arrays of doubles (of the same length) and returns the distance between the two points.
10 Nested For Loops
Calculate the value of x after the following code executes without programming it.
1 int x = 0;
2
3 for ( int i = 0; i < 100; i++ ) {
4 x++;
5 }
6 for ( int j = 100; j >= 0; j-- ) {
7 x++;
8 }
What is the value of x after the following code executes? Intuitively, which of these two blocks of code do you think takes longer to execute?
1 int x = 0;
2
3 for ( int i = 0; i < 100; i++ ) {
4 for ( int j = 100; j >= 0; j-- ) {
5 x++;
6 }
7 }
11 Printing Out Arrays
Write a method that takes as input two parameters: an integer array called inputArray and an integer called rowLength and prints out the array with no more than rowLength integers on any given line. For example, if inputArray is {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} and rowLength is 3, the method should print out the following:
1 2 3 4 5 6 7 8 9 10
Write another method that takes as input an integer array called inputArray and an integer called colLength and prints out the array with no more than colLength integers in any given column. You may assume that the length of the array is evenly divisible by colLength. For example, if inputArray is {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} and colLength is 4, the method should print out the following:
1 5 9 2 6 10 3 7 11 4 8 12
12 The Bubble Sort Algorithm
Program a method called bubbleSort that takes an integer array as input and returns a sorted integer array as output. Make sure you understand how the Bubble Sort algorithm works by sorting a small array by hand. Demonstrate your understanding of Bubble Sort to an Instructor, then implement the algorithm inside your method and test it out with several larger arrays.
13 The Insertion Sort Algorithm
Program a method called insertionSort that takes an integer array as input and returns a sorted integer array as output. Make sure you understand how the Insertion Sort algorithm works by sorting a small array by hand. Demonstrate your understanding of Insertion Sort to an Instructor, then implement the algorithm inside your method and test it out with several larger arrays.
14 Maximum Sum of a Subsequence of an Array1
Write a method that takes as input an array of integers and returns the indices of the start and end of a contiguous subsequence of the array that has the highest sum. For example, given the following array as input:
{3, 6, 7, -3, 8, -10, -4, 3, 0, 1, 4, 9, -5, 3, 2, 8}
Your method should return 7 and 15 because the sum 3+0+1+4+9-5+3+2+8 is higher than the sum of any other contiguous subsequence in this array.
15 Palindrome Finder
A palindrome is a sequence of words or numbers that reads exactly the same if reversed. An example of a palindrome (ignoring capitalization) is “Euston saw I was not Sue.” Write a method that takes as input a string and returns any palindromes that are a substring of the input.
16 Object Oriented Programming with Animals
Make a class that represents an animal of your choice, e.g. tiger or unicorn or blue whale. Give your class methods and instance variables to represent behavior and state appropriate to your particular type of animal. Your class should be well encapsulated and have a constructor. Make a second class that will test out your animal class by making several instances of it and calling their methods.
17 Meal Plan 2
Program a class that represents a student’s weekly meal plan. The class will have 2 instance variables, 2 constructors, and 3 methods. The first constructor should make a meal plan that has a default value of 21 meals assigned to it while the second constructor should take a parameter that will be assigned as the number of meals. Every time somebody swipes their ID card, the method eatMeal will be called. When you finish, test out your class from another test class. Below is a template for your class:
1 private int mealsLeft; 2 private int weeklyMeals; 3
4 public MealPlan() {
5 // set number of meals to 21
6 }
7 public MealPlan(int numMealsPerWeek) {
8 // set number of meals to numMealsPerWeek
9 }
1Problem from Programming Pearls (second edition) by Jon Bentley. 2Problem from Stanford CS106A course.
10 public boolean eatMeal() {
11 // check if meals are available and if so, subtract 1 and return true,
12 // otherwise return false.
13 }
14 public int mealsLeft() {
15 // return the number of meals available
16 }
17 public void resetMeals() {
18 // reset the number of meals available
19 }
18 Generating a Random Permutation with ArrayList 3
A random permutation is an ordering of items in a list where any item is just as likely to appear next. When you set your music player to “shuffle” it creates a random permutation of all the songs in the album you are listening to, then plays the songs in that order. Demonstrate your understanding of the algorithm for generating a random permutation to an Instructor, then write a method with an appropriate name that takes as input an ArrayList of Strings and returns an ArrayList with the same elements as the input except in a random order.
19 The Linked List Data Structure
Previously, you learned about data structures such as arrays and ArrayList that can hold many elements of data. In this assignment, you will design and implement your own data structure called a Linked List that will hold Strings. After learning about Linked Lists in class, write two classes: MyLinkedList and Element to implement this data structure. Element will have two instance variables, one constructor, and get methods for its instance variables:
1 // represents the String that is held by this Element 2 String data;
3
4 // an object reference variable referring to the next Element in this
5 // Linked List
6 Element nextElement;
7
8 // constructor that initializes an Element with a given String and Element 9 // for its instance variables
10 public Element(String s, Element e) {} 11
12 // returns data
13 public String getData() {} 14
15 // returns nextElement
16 public Element getNextElement() {}
MyLinkedList will have two instance variables, two constructors, and several methods: 1 // represents the number of Elements this Linked List has
2 int size;
3
4 // an object reference variable referring to the first Element in this Linked
5 // List
6 Element head; 7
8 // constructor that initializes a MyLinkedList with one Element containing the String s 9 public MyLinkedList(String s) {}
10
11 // constructor that creates an empty Linked List
12 public MyLinkedList() {} 13
14 // creates an Element containing String s and adds it to the beginning of this 15 // Linked List
16 public void add(String s) {} 17
18 // returns the String held by the first Element in this Linked List 19 public String get() {}
20
21 // deletes the String held by the first Element in this Linked List 22 public void delete() {}
If you finish the assignment early, you can implement a more advanced data structure like a Doubly-Linked List and add more complicated methods to it such as the ones below. Look at the Java class ArrayList for ideas of other useful methods you can add.
1 // creates an Element containing String s and adds it at position index in this
2 // Linked List
3 public void add(int index) {} 4
5 // returns the String held by the Element at position index in this Linked List 6 public String get(int index) {}
7
8 // deletes the String held by the Element at position index in this Linked List 9 public void delete(int index) {}
20 Parentheses Matching
Write a method that takes as input a String containing parentheses of different types and returns true if all the parentheses are matching and false otherwise. The method should ignore anything that is not a parenthesis. Use your MyLinkedList class from the previous assignment to implement the parentheses matching algorithm efficiently. Why is using a Linked List more efficient than using an array? When the Java compiler is reading your code, it checks that the parentheses that delineate classes and methods are properly matched in a similar fashion. The first String below should return true but the second one should return false.
{()()}{[()]} {()}}
21 Object Oriented Programming and Inheritance
Chose a subject that you feel can be modeled accurately by Object Oriented inheritance and create an inheritance scheme for it. Your scheme should have at least 1 superclass, 3 subclasses, 2 overridden methods, 2 overloaded methods, and several instance variables. If you are running low on creativity, you can make your subject animals like we talked about in class. Make a diagram of the classes in your inheritance scheme just like we did in lecture. Each class should be appropriately named, have arrows indicating its subclasses, and have its methods and instance variables identified. Once you are done with the diagram, program each of the classes and test out their methods. If you finish early, turn your inheritance scheme into a program or game. For example, using the animal inheritance scheme, you could make an animal simulator where animals move around randomly and look for food or try to eat each other. Talk to one of the instructors about your idea.
22 Animal Game 4 Working on it. . .
23 Introduction to Recursion
Write a recursive method that prints out “Hello” 100 times.
24 Recursion Practice
Print out the following sequence of numbers using recursion. Your method should take as input the highest number in the sequence, in this case 11.
11, 9, 7, 5, 3, 1
Write a method that prints out the following sequence of numbers using recursion. Your method should take as input the highest number in the sequence, in this case 11.
1, 3, 5, 7, 9, 11
25 Fibonacci (again)
Write a method that takes as input an integer n and prints out the Fibonacci sequence until the nthterm. n is 7 in this case.
0, 1, 1, 2, 3, 5, 8 . . .
26 Computer History Museum
While observing the exhibits at the Computer History Museum, think about the relation between the big ideas of Computer Science and Engineering (Algorithms, Abstraction, Data Structures) and the evolution of computing. How were these concepts instrumental in the advancement of computing? Prepare a short presentation on one of these concepts for class the next day and write one paragraph (3-4 sentences) about your observations.
Robotics and LeJOS
1 Hello World! (again)
Write a program to print the words “Hello World!” to the LCD screen of the Lego NXT brick.
2 Building Your Robot
Build a robot from the Lego kits that has two wheels operated by two separate motors. In the next assignments, you will be steering your robot by making one motor turn faster than the other one. This is known as differential steering and will cause your robot to turn in the direction of the slower motor. You will use this robot as the base for the following robotics assignments.
3 Moving in a Straight Line
As you will find out today, moving in a straight line is a lot harder for a robot than it is for you! Write a program that makes your robot move in a straight line for one meter. To do this, you will need to measure the diameters of your wheels and how far apart they are (known as the track width). Once you have measured them, try getting your robot to move in a straight line. If it still goes to one side, you may need to adjust the values of the wheel diameters until it is as straight as possible.
4 Tracing Out Shapes5
Write a method that makes your robot trace out a square. Your method should take as input the length of one side of the square. Can you write a method that makes your robot trace out a hexagon? What about a method that takes as input the number of sides of a polygon and traces out a figure with that many sides? To accomplish these tasks, you will use a LeJOS class called DifferentialPilot. Look up its Javadoc to see how to make an instance of it and what methods it has. Note: if your robot tends to turn less that the number of degrees you tell it to, the third wheel of your robot may have a lot of friction. To reduce this friction, try to position most of your robot’s weight over the two main drive wheels and reduce the surface area of your third wheel.
5 The Line Following Robot
Design and build a robot that can follow a black line on a white surface. The line will be in the shape of an ellipse. Afterwards, see if you can make your robot go at a faster speed around the ellipse. If you finish early, use electrical tape and a poster board to make a challenge course that is tougher and see if your robot can navigate it. You can also challenge other teams to navigate your course. At the end of this assignment, we will time your robots around the ellipse-shaped course and the winner will receive a prize.
6 Dead Reckoning Navigation
Dead Reckoning refers to a navigation technique where you start from a known position and update your position every time you move. This is one of the simplest ways to navigate but it can quickly build up inaccuracies because how far you actually move may be different from how far you think you moved. For this assignment, you will use a LeJOS class called OdometryPoseProvider in conjunction with DifferentialPilot. Read the Javadoc for OdometryPoseProvider to see how it works with DifferentialPilot to estimate your robot’s current position. Write a program that initializes your robot’s position and heading to 0, 0, 0, then moves your robot to a series of waypoints, given by x, y coordinates. How close is your robot to its intended position at the last waypoint?
7 Finding a Light Beacon with a Light Sensor
Design and build a robot that can use a Light Sensor to determine in which direction the highest light intensity is and print out that angle. Write a class called SensorControl and inside this class a method called findLightDirection. findLightDirection should return the angle where the highest light intensity was found. Look up the Javadoc of the LeJOS class LightSensor to find out how to make an instance of it and what methods it has. If you finish early, talk to the instructors to find ways of improving your findLightDirection method by making it more accurate or faster.
8 Finding a Ball with an Ultrasonic Sensor
Alter your robot from the previous assignment so that it can use an Ultrasonic Sensor to find the location of a ball. Inside the class SensorControl from the previous assignment, write a new method called findBall that returns the direction and distance to the ball. Look up the Javadoc of the LeJOS class UltrasonicSensor to find out how to make an instance of it and what methods it has.
9 Soccer Tournament
Design and build a robot to compete in the EPGY Robot Soccer Tournament. Check the class dropbox for the complete rules and a description of the playing field. You will also find two starter projects here that will help you get started with the program. Each game consists of two 5 minute periods. In both periods, your robot will be radio-operated but in the second method, nobody from the competing teams will be allowed to see the playing field. You will have to rely entirely on measurements from your robot’s sensors being sent to your computer.