Skip to content

Instantly share code, notes, and snippets.

@AlinaWithAFace
Last active February 15, 2018 02:39
Show Gist options
  • Save AlinaWithAFace/457d0885a5d228884c442368eb29a1b7 to your computer and use it in GitHub Desktop.
Save AlinaWithAFace/457d0885a5d228884c442368eb29a1b7 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Random;
import static java.lang.Math.abs;
// DONE 1. Any problem from lecture exercises is fair game on the exam.
// DONE 2. Fill in the class below, making an ArrayList of Cows where appropriate. A Cow has a name. Read the entire
// program, and read the comments carefully to understand what you have to write. You may not need every line.
class Cow implements Simple {
String name; //Use appropriate cow names
//Write a simple constructor
Cow(String cowName) {
name = cowName;
}
//Write toString method
@Override
public String toString() {
return "Am cow named " + name;
}
public static void main(String[] args) {
Collection<Cow> myCows = new ArrayList<>();
//Add two cows to the collection
myCows.add(new Cow("Bessie"));
myCows.add(new Cow("Delores"));
//Using a for-each loop, print the entire collection
for (Cow c : myCows) {
System.out.println(c.toString());
}
//Now show a simpler way to print the contents of the collection.
System.out.println(myCows.toString());
}
@Override
public void simpleMethod() {
System.out.println("Am cow");
}
}
public class Main {
public static void main(String[] args) {
// DONE 3. Complete the main() by adding code below comments. Note that if the constants are updated, your code
// should still work
final int LENGTH = 670; // size of data set to go into array
final int NUMS_PER_ROW = 30; // numbers per row when printed
// declare an array to hold the integer data set
int[] products = new int[LENGTH];
// Initialize array to the multiples of four {0,4,8,...}
final int MULTIPLE = 4;
for (int i = 0; i < LENGTH; i++) {
products[i] = MULTIPLE * i;
}
// Print the array with NUMS_PER_ROW elements per row; last row may have fewer.
int rowCount = 0;
for (int i = 0; i < LENGTH; i++) {
if (rowCount >= NUMS_PER_ROW) {
System.out.println();
rowCount = 0;
}
System.out.print(products[i] + " ");
rowCount++;
}
System.out.println();
// Tests because reasons
System.out.println("Start some tests");
int[] testArray = {4, 1, 2, 3, -1};
ArrayList<Integer> testArrayList = new ArrayList<>();
testArrayList.add(1);
testArrayList.add(2);
testArrayList.add(-1);
System.out.println(findMin(testArray));
computeSomeFactorials(9);
System.out.println(findMin(testArrayList));
}
// DONE 4. Write a method that takes an int array of any size as the only parameter, and returns the sum of its
// contents.
static int sumIntArray(int[] anArrayToSum) {
int sum = 0;
for (int i : anArrayToSum) {
sum += i;
}
return sum;
}
// DONE 5. Write a method that takes an ArrayList<Dog> as the only parameter, and returns the total number of legs
// of all dogs.
static int sumDogLegs(ArrayList<Dog> doggos) {
int sum = 0;
for (Dog dog : doggos) {
sum += dog.legs;
}
return sum;
}
// DONE 6. Write a method that takes an int array of any size as the only parameter, and returns the average of its
// contents.
static double averageIntArray(int[] ints) {
double average = 0;
for (int i : ints) {
average += i;
}
average /= ints.length;
return average;
}
// DONE 7. Write a method that efficiently computes and prints the factorials of 0-9. Hint: you only need seven
// multiplication ops.
static void computeSomeFactorials(int topFactorial) {
int factorial = 0;
for (int i = 0; i <= topFactorial; i++) {
if (i < 1) {
factorial++;
} else {
factorial *= i;
}
System.out.println("Factorial of " + i + " is " + factorial);
}
}
// TODO 8. Write a method that takes an int array and a single int pivot, and efficiently places all the numbers
// lower than the pivot at the start of the array, and the ones larger at the end (it partitions the array). Do not
// sort (because that would be inefficient - why?). Hint: start with an index at each end of the array, and move
// each index until it is on a number that is in the wrong location. When they are each on such a number, swap the
// numbers in the array.
static int[] rearrangeIntArray(int[] ints) {
//look at how to do quicksort
return null;
}
// DONE 9. Write a method that takes an int array of any size as the only parameter, and returns the minimum value
// of its contents. Your code should be O(n).
static int findMin(int[] ints) {
int min = ints[0];
for (int i : ints) {
if (i < min) {
min = i;
}
}
return min;
}
// DONE 10. Write a method that takes an ArrayList<int> as the only parameter, and returns the minimum value of its
// contents. Your code should be O(n).
static Integer findMin(ArrayList<Integer> integers) {
Iterator<Integer> integerIterator = integers.iterator();
Integer min = integerIterator.next();
System.out.println("Set min to " + min);
for (Iterator<Integer> it = integerIterator; it.hasNext(); ) {
Integer integer = it.next();
if (integer < min) {
min = integer;
}
}
return min;
}
// TODO 12. Write a main() that will perform setup and call one of the methods above (my choice of course).
// Set up an array where you can call any of the other methods?
// TODO 13. Write a JUnit test for a given method (similar to what you did in lab 1).
}
// TODO 14. Write simple Cow and Horse classes. Write a simple interface, and make Cow and Horse implement your
// interface. Write a main that puts a Cow and a Horse into a Collection, and then calls your method from every
// object in the Collection.
// cows and horses are both ungulates
interface Simple {
void simpleMethod();
}
class Horse implements Simple {
@Override
public void simpleMethod() {
System.out.println("Am horse");
}
}
class CowHorseMain {
public static void main(String[] args) {
Collection<Simple> myFarm = new ArrayList<>();
myFarm.add(new Horse());
myFarm.add(new Cow("Terry"));
myFarm.iterator();
}
}
// TODO 15. Write simple Car, Cow and Horse classes. Represent that all three move, that cars have wheels, and that
// cows and horses have hooves. (Hint: you’ll need an interface and a super class to do this in a nice, OO way.)
// TODO 16. Write a Cat class. A cat has a number of legs, a weight, and a name. Write three constructors with
// parameters (respectively) legs/weight/name, name/weight, and name/legs. Create three cats, place them in a list,
// and show them printing nicely. Use your best coding practices!! In the comments, briefly state a significant
// problem with this design (from the perspective of a coder using your class).
// DONE 17. Write code to map the return values from nextInt() (note lack of parameter!) in the Random package into
// three approximately equal parts. Demonstrate by calling 1,000,000 times, then printing the total number of times
// a number mapped into each part. Note - you are only printing three numbers. If you did not use the modulus
// operator for this problem, you probably did too much work, and you may have excessive code.
class MapRandoms {
public static void main(String[] args) {
int[] mapCounts = mapInts(3, 1000000);
for (int i : mapCounts) {
System.out.println(i);
}
}
// Use mod to "tick" an int in an array of 3 in the 0th 1st or 2nd place
static int[] mapInts(int partsLength, int count) {
// Initialize array
int[] parts = new int[partsLength];
for (int j = 0; j < partsLength; j++) {
parts[j] = 0;
}
Random random = new Random();
for (int i = 0; i < count; i++) {
int myInt = random.nextInt();
//int myIndex = myInt % partsLength;
// The above line works well with positive numbers but retains negativeness when given negative numbers,
// which is pretty unhelpful in this particular situation, hence the following line.
int myIndex = (myInt < 0) ? (partsLength - (abs(myInt) % partsLength)) % partsLength : (myInt % partsLength);
//System.out.println("Generated int: " + myInt + " mod " + partsLength + " is " + myIndex);
parts[myIndex]++;
}
return parts;
}
}
// TODO 18. Make a “constant” equal to 12. Declare an array of 12 ints. Initialize the array using a loop, then use
// a different loop to print the array, showing four lines of three numbers. Now make one change to a single number
// (your constant) so that the program prints 75 numbers in 25 lines of three numbers (or 90 numbers in 30 lines of
// three numbers, etc). You should not have to change anything else in the code. If you did not use the modulus
// operator for this problem, you probably did too much work, and you may have excessive code.
// DONE 11. Consider the following code. What will it print? Briefly explain the difference between reference equality
// and using the equals() method
class MyStringEquality {
public static void main(String[] argyle) {
String s1 = "dog";
String s2 = "cat";
String s3 = "dogcat";
String temp = s1 + s2;
System.out.println(temp == s3);
System.out.println(temp.equals(s3));
// possibly helpful video https://www.youtube.com/watch?v=qQe69w1YF54
}
// Prints:
// false
// true
// Explanation:
// The first comparison checks if they're the same exact object,
// while the second one checks whether or not the strings are equal
}
class Dog {
String name;
int legs;
Dog(String dogName) {
name = dogName;
legs = 4;
}
@Override
public String toString() {
return ("Am dog named " + name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment