Wednesday, May 20, 2015

Snake app- available now!

Snake
an Android App by Ché Young 

       Ladies and gentlemen, I present my senior project, the Snake app. I stayed up until 1 AM making this fully functional Snake game, complete with random terrain generation, transparent shadows, high scores and screen wrapping (go off the left side of the screen, appear on the right).



Wednesday, April 15, 2015

Sorting Algorithm Visualizer v1.1

I made some changes to the sorting visualizer program to make it overall better.

1. updated timings- the delay between steps should be more accurate now.
2. fixed bug where, especially on large arrays, the program would occasionally redraw the screen without performing any steps.
3. fixed slowdown and erratic movement on large arrays.

Tuesday, April 14, 2015

Sorting Algorithm Visualizer

This was FUN. I made a program that showcases four different sorting algorithms. You can choose four different array sizes (64, 128, 256 or 512 elements), and the algorithm to display. You can also choose the speed you want the algorithm to run at by clicking the bar along the bottom- farther left is slower. If possible, the element will turn green when the algorithm deems that element sorted. It will also highlight elements being compared in red.

Also, there's a difference between Quick Sort and Quick Sort 2- the second uses the median of the leftmost, center and rightmost elements as the pivot, whereas the first just uses the element on the far left. This means Quick Sort 2 is generally more efficient in its choice of pivot.
Download it here!
Also grab the source code here!
Bubble Sort with an array of 64 elements
Gnome Sort with 128 elements
Merge Sort with 256 elements
Quick Sort with 512 elements
 
The GUI!

Thursday, March 19, 2015

Tree

"Tree"


It's funny, 'cause the code branches

Thursday, March 12, 2015

Anagram creator / Recursion

Earlier, our teacher chalenged us to write a program that outputs a list of anagrams given an input string. A bit later, he said "On second thought, it might be too hard, considering we haven't learned the skills needed yet."

WELL, I DID IT ANYWAYS.


This program uses some serious recursion to return a list of anagrams. For example, "yes" prints out "yes", "yse", "eys", "esy", "sye", and "sey". If the boolean useAllCharacters is set to false, it will print out the string at each step, meaning it will also print anagrams using only some of the characters. For example, "hi" will print "h", "hi", "i", and "ih".

The recursion function works like this- given a string and a list of characters, it will go through the list and each time, call itself with the original string plus a character from the list and the list of characters without the character added to the string. If the list is empty however, it will simply print the completed string, and end without calling itself. More visually demonstrated-


Wednesday, March 11, 2015

Rapid Counter app- available here!

Rapid Counter
an Android app by Ché Young

       To test out and better understand the Android app development and submission process, I have created this app, Rapid Counter. It is designed to be an ergonomically and aesthetically pleasing counter, with buttons to subtract as well as add to the count, along with a reset button and sounds.
     I would have this submitted to the Google Play store... except for the fact that the $50 signup fee is too high for me to comfortably pay for the moment. However, you can download it here instead. You will likely need to go into your settings to allow installing apps from non-market sources.

Regardless of whether or not you liked it, feel free to give me feedback!
Any input would be much appreciated.

Friday, March 6, 2015

Pig Latin converter

So I made this pig latin translator in class today. It doesn't handle capitalization or punctuation, but it can handle multiple words at once, separated by spaces.

import javax.swing.JOptionPane;

public class home {
static String[] vowels = {"a", "e", "i", "o", "u", "y"};
public static void main(String[] args) {
String input;
String out;
boolean x = true;
while (x) {
input = JOptionPane.showInputDialog("Words to change?");
if (input.equals("stop")){
x=false;
break;
}
out = "";
for (String ret: input.split(" ")){
int vpos = find(ret);
System.out.println(vpos);
if (vpos > 0) {
out = out + ret.substring(vpos) + ret.substring(0, vpos) + "ay ";
} else {
out = out + ret + "way ";
}
}
JOptionPane.showMessageDialog(null, out);
}
}
public static int find(String inp) {
int pos = -1;
for (String vwl: vowels) {
int vpos = inp.indexOf(vwl);
if ((vpos >= 0) && ((vpos < pos)||(pos==-1)) && (vpos != inp.indexOf("qu")+1)) {
pos=inp.indexOf(vwl);
}
}
return pos;
}
}


Monday, March 2, 2015

Age checker

Tim and I made a java program that checks to see if you're 18 years old or older.

import javax.swing.JOptionPane;
import java.util.Calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;

public class home {
public static void main(String[] args) {
int day = 0;
int month = 0;
int year = 0;
boolean workingstr = false;
while (workingstr == false) {
String inputValue = JOptionPane.showInputDialog("Please type in your birthday (mm/dd/yy)");
workingstr=true;
try {
day = Integer.parseInt(inputValue.substring(4,5));
month = Integer.parseInt(inputValue.substring(0,2));
year = Integer.parseInt("19"+inputValue.substring(inputValue.length()-2,inputValue.length()));
} catch (NumberFormatException e) {
workingstr=false;
} catch (StringIndexOutOfBoundsException e) {  
workingstr=false; //This section of the program will repeat if any errors are thrown trying to convert the
}                                      //input string to integers.
}
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Calendar cd = Calendar.getInstance();
int todayDay = Integer.parseInt(dateFormat.format(cd.getTime()).substring(0,2));
int todayMonth = Integer.parseInt(dateFormat.format(cd.getTime()).substring(4,5));
int todayYear = Integer.parseInt(dateFormat.format(cd.getTime()).substring(6,10));

if (day<=todayDay) {
month++;
}
if (month<=todayMonth){
year++;
}
if (year+18<=todayYear) {
System.out.println("You're good.");
} else {
System.out.println("Nope! You're underage.");
}
}
}

Friday, February 13, 2015

Chapter 5

For a while, I've been working on a little project called "Infinite Mario Bros". Looks pretty good so far.
Some of Chapter 5's content was actually surprisingly informative and helpful.
Consider this bit of code-
I made this before I discovered that there were two formats for for loops;
for (int i=0; i < Main.mainPanel.Enemies.size(); i++) { Main.mainPanel.enemies.get(i) }
for (Enemy test : Main.mainPanel.enemies) { test }

Using the new for loop, my code is easier to modify and looks much cleaner overall, because instead of typing "Main.mainPanel.enemies.get(i)" each time, i can just type "test".







And if you're wondering what this code does, it goes through a list of enemies, checks if they're overlapping with Mario, and if he's falling, change their state. In other words...
Goomba goes squish.

Tuesday, February 3, 2015

Chapter 4

In Chapter 4 of Headfirst Java, I learned about Instance and Local variables, and how they act. Instance variables are declared as part of the class and have default values, but Local variables are defined within a method and have no initial value. For example...

public class Dog{
    public int size;
    public void printSize() {
        System.out.print(size);
    }
}

Calling the printSize() method on this Dog class will return 0, since the default value of ints are 0. However, you can't do this...

public class Dog{
    public void printSize() {
        int size;
        System.out.print(size);
    }
}

This code won't compile because the size variabe is Local and has no default value.

I also learned that there are two different ways to compare variables, as I discovered in the cat simulator program. The == operator  compares variables on a binary level, meaning the variables have to be exactly the same values and be in the same "heap", whereas you can use .equals() to compare similar objects from different heaps (such as strings with the same characters).

Friday, January 30, 2015

Cat Simulator 2015

I worked together with my friend Tim to make a 'cat simulator' of sorts in Java. After naming your virtual cat, you can use text commands to pet it, give it things to play with / eat, or watch it interact with things you've given it. Here's an example run of the program:

You got a new pet cat! What do you want to name him?
Tom
You named him Tom.
What do you want to do?
(pet, give, watch, exit)
give
What item is it?
paper ball
Is it edible?
no
Tom plays idly with the paper ball.
(pet, give, watch, exit)
give
What item is it?
catnip
Is it edible?
yes
Tom stares at the catnip.
(pet, give, watch, exit)
watch
Tom eats the catnip. Viciously.
(pet, give, watch, exit)
watch
Tom meows.
(pet, give, watch, exit)
pet
You pet Tom and he purrs softly.
(pet, give, watch, exit)
pet
You pet Tom the wrong way, and he scratches you!
(pet, give, watch, exit)

The program is split into three .java files and three separate classes; a main class, a cat class, and an Object class. The main class handles command inputs and stores objects, the cat class decides what it wants to do with with the objects it's given, and the Object class stores information about each object.

The project code can be viewed in this Eclipse project.

Wednesday, January 28, 2015

Chapter 3

In experimenting with the Dog program example, I learned that Java reads all the class definitions (variables, constructors, methods, etc.) before executing public static void main (String[] args). This means you can have the main program inside a class, and that the program will start with one copy of that particular class. This makes me wonder if you could refer to itself in an array.

class Dog {
   public String name = "Ben";
   public static void main (String[] args) {
      Dog[] myDogs = new Dog[2];
      myDogs[0] = new Dog("Bob");
      myDogs[1] = this;
      int x = 0;
      while (x < myDogs.length) {
         System.out.println(myDogs[x].name); // Would this print "Bob" and then "Ben"?
      }
   }
   public Dog(String newnname) {
      this.name = newname;
   }
}

     

Tuesday, January 20, 2015

Chapter 2

In the second chapter of Headfirst java, I learned about subclasses and superclasses, and how subclasses can override superclass methods. For example, if we have a superclass called Shape, we can have subclasses Square and Triangle. The subclasses can have their own unique variables and classes, while preserving any of Shape's methods assuming they haven't been overridden.

Tuesday, January 13, 2015

Chapter 1 findings

In the first chapter of Headfirst Java, the two biggest things I learned about are casts and declaring arrays. Casts allow you to change numbers from one data type to another, such as from Float to Int.
Example:

float x = 32.25f;
if ((int) x == 32) {
     System.out.println("This will print because 32.25 rounds to 32.")
}
if (x==32) {
     System.out.println("This won't print because x is still 32.25.")
}

Arrays in Java are created somewhat differently than other languages- You have to tell the code you want an array after the primitive type. This means the array will only accept one type of data (String, integer, etc).

String[] animals = {"cats", "dogs", "pigs"}
int[] numbers = {1, 30, 25, 22.5} // This will throw an error, since 22.5 is a float in an integer array.

Friday, January 9, 2015

Beersong

So today I fixed a program that prints the words to the Beer Song, AKA 99 Bottles of  Beer.
Original code:

public class BeerSong {
    public static void main(String[] args) {
        int beernum = 99;
        String word = "bottles";
        
        while (beernum>0) {

            if (beernum==1) {
                word = "bottle";
            }

            System.out.println(beernum + " " + word + " of beer on the wall");
            System.out.println(beernum + " " + word + " of beer");
            System.out.println("Take one down");
            System.out.println("Pass it around");
            
            beernum = beernum - 1;

            if (beernum > 0) {
                System.out.println(beernum + " " + word + " of beer on the wall");
            } else {
                System.out.println("No more bottles of beer on the wall");
            }
        }
    }
}

This works well, except towards the end it prints "Pass it around, 1 bottles of beer on the wall" because the variable "word" is updated at the beginning of the loop rather than after the beer count changes.

public class BeerSong {
    public static void main(String[] args) {
        int beernum = 99;
        String word = "bottles";
        
        while (beernum>0) {
            System.out.println(beernum + " " + word + " of beer on the wall");
            System.out.println(beernum + " " + word + " of beer");
            System.out.println("Take one down");
            System.out.println("Pass it around");
            
            beernum = beernum - 1;
            if (beernum==1) {
                word = "bottle";
            }
            if (beernum!=0) {
                System.out.println(beernum + " " + word + " of beer on the wall");
            } else {
                System.out.println("No more bottles of beer on the wall");
            }
        }
    }
}

Friday, December 12, 2014

1.3.8 Activity response: While loops

Here I made a guessing game where you have to guess a number between 1 and 20 inclusive. It tells you if you guessed too high or too low, and even if you guessed a number outside of 1-20.

import random
def goguess():
    maxval = 20
    minval = 1
    target = random.randint(minval, maxval)
    print("I have a number between " + str(minval) + " and " + str(maxval) + ".")
    guess = int(raw_input("Guess: ")) #We put our first guess here because we check
    count = 1                         #the guess at the beginning of the while loop.
    while (not (guess == target)): #the while loop ends when you guess the number.
        if (guess <= maxval and guess >= minval):
            if (guess < target):
                print(str(guess) + " is too low.")
            else:
                print(str(guess) + " is too high.") # Tells if the guess is high or low.
            count += 1 #adds 1  to the count... count.
        else:
            if guess > maxval:    #Remind them if they guess outside the range.
                print(str(guess) + "is higher than " + str(maxval) + ".")
            else:
                print(str(guess) + "is lower than " + str(minval) + ".")
        guess = int(raw_input("Guess: "))
    print("You got it! The number was " + str(target) + ", and you guessed it in " + str(count) + " turns.") #This prints when the 'while' loop ends.

Conclusion question answers:

Q1: If you change between 1 and 20 from the previous program to between 1 and 6000, how many guesses will you need to guarantee that you have the right answer? Explain.

A1: To figure out how many guesses you need, you need find the first power of two above the maximum number. For example, guessing a number in a range 1-7 inclusive would take only three guesses.
2^guesses > max
2^3   = 8       > 7       --3 guesses for a range 1-7
2^5   = 32     > 20     --5 guesses for a range 1-20
2^13 = 8192 > 6000 --13 guesses for a range 1-6000.


Q2: Explain the difference between a while loop and a for loop.

A1: A "while" loop repeats constantly until a condition is met, whereas a "for" loop iterates through a list of values. In some languages like java you could use them interchangeably, but it's generally easier and faster to use whichever one makes more sense for the situation.

Tuesday, December 9, 2014

1.3.7 Activity response: For loops

On this assignment I only needed to do two of these three, but I went ahead and did all of them.

The first function, hangman_display(), will return the 'secret' string with letters that aren't in 'guessed' hidden or crossed out, much like in Hangman.
ex: hangman_display("aeiou", "hello world") -> "-e--o -o---"

The second, matches(), counts how many items between the two lists match, assuming neither list has duplicate items.
ex: matches([1,2,3], [2,3,4]) -> 2

The last function, report(), functions like the game Mastermind, returning how many items are the same in value and position, and how many items are in both lists but in different positions.
ex: report([a, b, c, d], [a, c, b, e]) -> [1, 2]

def hangman_display(guessed, secret):
    ret = ""
    for i in secret:
        x = 0
        for j in guessed:
            if i.lower() in j.lower():
                x = 1
        if x == 1 or (i in " !,.?"):
            ret = ret + i
        else:
            ret = ret + "-"
    return ret


def matches(tickets, winners):
    ret = 0
    for i in tickets:
        x=0
        for j in winners:
            if i==j:
                x = 1
        if x==1:
            ret += 1
    return ret


def report(guess, secret):
    ret = [0, 0]
    used = []
    for i in range(len(secret)):
        if secret[i]==guess[i]:
            used.append(i)
            ret[0] += 1
    for i in range(len(secret)):
        for j in range(len(guess)):
            if (not(j in used or i in used)) and secret[i]==guess[j]:
                ret[1] += 1
                used.append(j)
    return ret

Conclusion question answers:

  1. This practice, known as "loop unrolling", is actually used in some cases to speed up program execution at the cost of increasing the program size. Using unrolled loops during development is tedious, boring and just plain inefficient- it'd be a royal pain to change an unrolled version of "for i in range(10):" to "for i in range(1000):", and even more painful to change anything inside said loop.
  2. A grocery store computer might iterate over a list of items in stock.
  3. Both iteration and data analysis deal with large amounts of data. Iteration reads from and/or changes information about each item, whereas data analysis only reads from them to get statistics.

Thursday, December 4, 2014

1.3.6 Activity response: lists and tuples

Hilariously, I only used lists to test the second function despite the lesson being on lists and tuples.

import random
def roll_two_dice():
    a = random.randint(1,6)
    b = random.randint(1,6)
    return a+b

def guess_letter():
    letters = 'abcdefghijklmnopqrstuvwxyz'
    return letters[random.randint(0,len(letters)-1)]

Question answers:

  1. A can be printed and concatenated as a standard string, B can be appended and store different string lengths in each element, and C can only be read from.
  2. Languages have different variable types because different variables' contents are incompatible by nature.  "A" + 32 + True - (1,2,3) = ????
  3. Technically speaking, everything COULD be represented as integers since computers store everything as 1s and 0s anyways, but using integers to store a string would be incredibly difficult and inefficient.

Wednesday, December 3, 2014

1.3.5 Activity response: Strings

So recently I was asked to make a "Tweet verifier" in Python for a fictional "inspirational quote" contest. The Tweet needs to be 140 characters or less and needs a comma, a quote, a question mark and an exclamation mark.

The code:

from __future__ import print_function
def CheckTweet(Tweet):
    com = ',' in Tweet
    quo = '"' in Tweet
    que = "?" in Tweet #These are true of the character is in the tweet.
    exc = "!" in Tweet
    length = len(Tweet)<=140 #This is false if the tweet is over 140 characters.
    over = str(len(Tweet)-140) #Store how many characters the tweet is over the limit.
    errors = []
    if not com:
        errors.append("a comma") #Put what's missing in proper english in a list.
    if not quo:
        errors.append("a quote")
    if not que:
        errors.append("a question")
    if not exc:
        errors.append("an exclamation mark")
    if com and quo and exc and que: #If nothing is missing...
        if length:
            return "Tweet verified. You're good to go!" #AND if it's short enough.
        else:
            return "Sorry, but your Tweet is " + over + " characters over the limit (140)." 
    else:
        msg = "Sorry, but your tweet needs " #Starting off the 'missing stuff' message
        
        if len(errors)==1: #Add commas, periods and 'and's between what's missing to make proper english!
            msg = msg + errors[0] + "."
        elif len(errors)==2:
            msg = msg + errors[0] + " and " + errors[1] + "."
        elif len(errors)==3:
            msg = msg + errors[0] + ", " + errors[1] + " and " + errors[2] + "."
        else:
            msg = msg + errors[0] + ", " + errors[1] + ", " + errors[2] + " and " + errors[3] + "."
        if not length: #If you're ALSO over the limit, add this in a second line.
            msg = msg + "\nAdditionally, your Tweet is " + over + " characters over the limit (140)."
        return msg
 
tweet = raw_input('Your Tweet: ')
print(CheckTweet(tweet))

Conclusion question answers:
  1. There are 41 characters in "How many characters are in this sentence?", and it doesn't matter how many bytes Python uses to store each character; either way, Python would return the same number of characters.
  2. In lines 1 and 2, variables A and B are assigned 'one string' and 'another' respectively. In line 3, variable C is assigned a combination the first three characters of A ('one'), ' and ' and the contents of variable B ('another') to get 'one and another'. Line 4 prints characters 7-10 of variable C, which is just 'd a'.

Thursday, November 20, 2014

Blown To Bits: Chapter 2 questions

1. Judge and justify whether the use of hidden RFIDs be restricted or not.
2. Paraphrase the "Fair Information Practice Principles".
3. Predict how similar George Orwell's society in 1984 will be to our own in 15 years.
4. Try to analyze and determine where other people and companies could find information about you. 

(example: Facebook, RFIDs, GPS)
5. Compile a list of different technology and devices mentioned in this chapter used to identify people.