Final CS360 - Painter
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Painter
{
public static void main( String[] args )
{
// create JFrame
JFrame application = new JFrame( "A simple paint program" );
PaintPanel paintPanel = new PaintPanel(); // create paint panel
application.add( paintPanel, BorderLayout.CENTER ); // in center
// create a label and place it on SOUTH of BorderLayout
application.add( new JLabel("Grag the mouse to dra"),
BorderLayout.SOUTH );
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
application.setSize( 400, 200 ); // set frame size
application.setVisible( true ); // display frame
} // end main
} // end class Painter
Monday, December 20, 2010
Sunday, December 19, 2010
Assignment - WildcardTest
Assignment - WildcardTest
//wildcardTest.java
import java.util.ArrayList;
public class WildcardTest
{
public static void main(String[]args)
{
//create, initialize and output ArrayList of Integers, then display total of the elements
Integer[]integers = {1,2,3,4,5};
ArrayList<Integer>integerList=new ArrayList<Integer>();
//insert elements in interger list
for (Integer element:integers)
integerList.add(element);
System.out.printf("integerList contains: %s\n", integerList);
System.out.printf("Total of the elements in integerList:%.0f\n\n", sum(integerList));
//create, initialize and output ArrayList of Doubles, then display total of the elements
Double[]doubles={1.1,3.3,5.5};
ArrayList<Double>doubleList=new ArrayList<Double>();
//insert elements in doubleList
for (Double element:doubles)
doubleList.add(element);
System.out.printf("doubleList contains:%s\n", doubleList);
System.out.printf("Total of the elements in doubleList:%.1f\n\n", sum(doubleList));
//create, initialize and output ArrayList of numbers containing both integers and doubles, then display total of the elements
Number[]numbers={1,2.4,3,4.1}; //integers and doubles
ArrayList<Number>numberList=new ArrayList<Number>();
//insert elements in numberList
for (Number element:numbers)
numberList.add(element);
System.out.printf("numberList contains:%s\n",numberList);
System.out.printf("Total of the elements in numberList:%.1f\n", sum (numberList));
}//end main
//total the elements; using a wildcard in the ArrayList parameter
public static double sum(ArrayList<? extends Number>list)
{
double total=0; //initialize total
//calculate sum
for (Number element:list)
total +=element.doubleValue();
return total;
}//end method sum
}//end class WildcardTest
//wildcardTest.java
import java.util.ArrayList;
public class WildcardTest
{
public static void main(String[]args)
{
//create, initialize and output ArrayList of Integers, then display total of the elements
Integer[]integers = {1,2,3,4,5};
ArrayList<Integer>integerList=new ArrayList<Integer>();
//insert elements in interger list
for (Integer element:integers)
integerList.add(element);
System.out.printf("integerList contains: %s\n", integerList);
System.out.printf("Total of the elements in integerList:%.0f\n\n", sum(integerList));
//create, initialize and output ArrayList of Doubles, then display total of the elements
Double[]doubles={1.1,3.3,5.5};
ArrayList<Double>doubleList=new ArrayList<Double>();
//insert elements in doubleList
for (Double element:doubles)
doubleList.add(element);
System.out.printf("doubleList contains:%s\n", doubleList);
System.out.printf("Total of the elements in doubleList:%.1f\n\n", sum(doubleList));
//create, initialize and output ArrayList of numbers containing both integers and doubles, then display total of the elements
Number[]numbers={1,2.4,3,4.1}; //integers and doubles
ArrayList<Number>numberList=new ArrayList<Number>();
//insert elements in numberList
for (Number element:numbers)
numberList.add(element);
System.out.printf("numberList contains:%s\n",numberList);
System.out.printf("Total of the elements in numberList:%.1f\n", sum (numberList));
}//end main
//total the elements; using a wildcard in the ArrayList parameter
public static double sum(ArrayList<? extends Number>list)
{
double total=0; //initialize total
//calculate sum
for (Number element:list)
total +=element.doubleValue();
return total;
}//end method sum
}//end class WildcardTest
Assignment 18 - MenuFrame / MenueTest
/*
Assignment 18
*/
// Fig. 22.5: MenuFrame.java
// Demonstrating menus.
import java.awt.Color;
import java.awt.Font;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JFrame;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
public class MenuFrame extends JFrame
{
private final Color colorValues[] =
{ Color.BLACK, Color.BLUE, Color.RED, Color.GREEN };
private JRadioButtonMenuItem colorItems[]; // color menue items
private JRadioButtonMenuItem fonts[]; // font menue items
private JCheckBoxMenuItem styleItems[]; // font style menue items
private JLabel displayJLabel; // displays sample text
private ButtonGroup fontButtonGroup; // manages font menu items
private ButtonGroup colorButtonGroup; // manages color menu items
private int style; // used to create style for font
// no-argument constructor set up GUI
public MenuFrame()
{
super( "Using JMenus" );
JMenu fileMenu = new JMenu( "File" ); // create file menu
fileMenu.setMnemonic( 'F' ); // set mnemonic to F
// create About... menu item
JMenuItem aboutItem = new JMenuItem( "About..." );
fileMenu.add( aboutItem ); // add about item to fiel menu
aboutItem.addActionListener(
new ActionListener() // anonymouse inner class
{
//display message dialog when user selects About...
public void actionPerformed( ActionEvent event )
{
JOptionPane.showMessageDialog( MenuFrame.this,
"This is an Example\nof using menus",
"About", JOptionPane.PLAIN_MESSAGE );
} // end method actionPerformed
} // end anonymous inner class
); // end call to addActionListener
JMenuItem exitItem = new JMenuItem( "Exit" ); // create exit item
exitItem.setMnemonic( 'x' ); // set mnemonic to x
fileMenu.add( exitItem ); // add exit item to fiel menu
exitItem.addActionListener(
new ActionListener() //anonymous inner class
{
// terminate application when user clicks exitItem
public void actionPerformed( ActionEvent event )
{
System.exit( 0 ); // exit application
} // end method actionPerformed
} // end anonymous inner class
); // end call to addActionListener
JMenuBar bar = new JMenuBar(); // create menu bar
setJMenuBar ( bar ); // add menu bar to application
bar.add( fileMenu ); // add fiel menu to menu bar
JMenu formatMenu = new JMenu( "Format" ); // create format menu
formatMenu.setMnemonic( 'r' ); // set mnemonic to r
// array listing string colors
String colors[] = { "Black", "Blue", "Red", "Green" };
JMenu colorMenu = new JMenu( "Color" ); // create color menu
colorMenu.setMnemonic( 'C' ); // set mnemonic to C
//create radio button menu items for colors
colorItems = new JRadioButtonMenuItem[ colors.length ];
colorButtonGroup = new ButtonGroup(); // manages colors
ItemHandler itemHandler = new ItemHandler(); // handler for colors
// create color radio button menu items
for ( int count = 0; count < colors.length; count++ )
{
colorItems[ count ] =
new JRadioButtonMenuItem( colors[ count ] ); // create item
colorMenu.add( colorItems[ count ] ); // add item to color menu
colorButtonGroup.add( colorItems[ count ] ); // add to group
colorItems[ count ].addActionListener( itemHandler );
} // end for
colorItems[ 0 ].setSelected( true ); // select first Color item
formatMenu.add( colorMenu ); // add color menu to format menu
formatMenu.addSeparator(); // add separator in menu
// array listing font names
String fontNames[] = { "Serif", "Monospaced", "SansSerif" };
JMenu fontMenu = new JMenu( "Font" ); // create font menu
fontMenu.setMnemonic( 'n' ); // set mnemonic to n
// create radio button menu items for font names
fonts = new JRadioButtonMenuItem[ fontNames.length ];
fontButtonGroup = new ButtonGroup(); // manages front names
// create Front radio button menu items
for ( int count = 0; count < fonts.length; count++ )
{
fonts[ count ] = new JRadioButtonMenuItem( fontNames[ count ] );
fontMenu.add( fonts[ count ] ); // add font to font menu
fontButtonGroup.add( fonts[ count ] ); // add to button group
fonts[ count ].addActionListener( itemHandler ); // add handler
} // end for
fonts[ 0 ].setSelected( true ); // select first Font menu item
fontMenu.addSeparator(); // add separator bar to font menu
String styleNames[] = { "Bold", "Italic" }; // names of styles
styleItems = new JCheckBoxMenuItem[ styleNames.length ];
StyleHandler styleHandler = new StyleHandler(); // style handler
// create style checkbox menu items
for ( int count = 0; count < styleNames.length; count++ )
{
styleItems[ count ] =
new JCheckBoxMenuItem( styleNames[ count ] ); // for style
fontMenu.add( styleItems[ count ] ); //add to font menu
styleItems[ count ].addItemListener( styleHandler ); // handler
} // end for
formatMenu.add( fontMenu ); // add Front menu to Format menu
bar.add( formatMenu ); // add Format menu to menu bar
// set up labe to display text
displayJLabel = new JLabel( "Sample Text", SwingConstants.CENTER );
displayJLabel.setForeground( colorValues[ 0 ] );
displayJLabel.setFont( new Font( "Serif", Font.PLAIN, 72 ) );
getContentPane().setBackground( Color.CYAN ); // set background
add( displayJLabel, BorderLayout.CENTER ); // add displayJLabel
} // end MenuFrame constructor
// inner class to handle action events from menu items
private class ItemHandler implements ActionListener
{
// process color and font selections
public void actionPerformed( ActionEvent event )
{
// process color selection
for ( int count = 0; count < colorItems.length; count++ ){
if ( colorItems[ count ].isSelected() )
{
displayJLabel.setForeground( colorValues[ count ] );
break;
} // end if
} // end for
// process font selection
for ( int count = 0; count < fonts.length; count++ )
{
if ( event.getSource() == fonts[ count ] )
{
displayJLabel.setFont(
new Font( fonts[ count ].getText(), style, 72 ) );
} // end if
} // end for
repaint(); // redraw application
} // end method actionPerformed
} // end class ItemHandler
// inner class to handle item events from check box menu items
private class StyleHandler implements ItemListener
{
// process font style selections
public void itemStateChanged( ItemEvent e )
{
style = 0; // initialize style
// check for bold selection
if (styleItems[ 0 ].isSelected() )
style += Font.BOLD; // add bold to style
// check for italic selection
if ( styleItems[ 1 ].isSelected() )
style += Font.ITALIC; // add italic to style
displayJLabel.setFont(
new Font( displayJLabel.getFont().getName(), style, 72 ) );
repaint(); // redraw application
} // end method itemStateChanged
} // end class StyleHandler
} // end class MenuFrame
//Fig. 22.6: MenuTest.java
//Testing javax.swing.JFrame;
import javax.swing.JFrame;
public class MenuTest
{
public static void main( String args[])
{
MenuFrame menuFrame = new MenuFrame(); // create MenuFrame
menuFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
menuFrame.setSize( 500, 200 ); // set frame size
menuFrame.setVisible( true ); // display frame
} // end main
} // end class Menu Test
Assignment 9-18-10 - FibonacciCalculator / FibonacciTest
Assignment 9-18-10 - FibonacciCalculator / FibonacciTest
/*
*/
public class FibonacciCalculator
{
//reverse declaration of method Fibonacci
public long fibonacci( long number )
{
if((number ==0)||(number ==1)) //base cases
return number;
else //recursion step
return fibonacci( number-1) + fibonacci(number-2);
}
public void displayFibonacci()
{
for (int counter=0; counter<=10; counter++)
System.out.printf("Fibonacci of %d is %d\n", counter, fibonacci(counter)
);
}
}
/*
*/
public class FibonacciTest
{
public static void main(String args[])
{
FibonacciCalculator fibonacciCalculator=new FibonacciCalculator();
fibonacciCalculator.displayFibonacci();
}
}
/*
*/
public class FibonacciCalculator
{
//reverse declaration of method Fibonacci
public long fibonacci( long number )
{
if((number ==0)||(number ==1)) //base cases
return number;
else //recursion step
return fibonacci( number-1) + fibonacci(number-2);
}
public void displayFibonacci()
{
for (int counter=0; counter<=10; counter++)
System.out.printf("Fibonacci of %d is %d\n", counter, fibonacci(counter)
);
}
}
/*
*/
public class FibonacciTest
{
public static void main(String args[])
{
FibonacciCalculator fibonacciCalculator=new FibonacciCalculator();
fibonacciCalculator.displayFibonacci();
}
}
Assignment - DeckofCards
Assignment - DeckofCards
// Fig. 20.10: DeckOfCards.java
// Card shuffling and dealing with collections method shuffle.
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
// class to represent a cards in a deck of cards
class Card
{
public static enum Face { Ace, Deuce, Three, Four, Five, Six,
Seven, Eight, Nine, Ten, Jack, Queen, King };
public static enum Suit { Clubs, Diamonds, Hearts, Spades };
private final Face face; // face of card
private final Suit suit; // suit of card
// two-arment constructor
public Card( Face cardFace, Suit cardSuit )
{
face = cardFace; // initialize face of card
suit = cardSuit; // initialize suit of card
} // end two-argument Card constructor
// return face of the cards
public Face getFace()
{
return face;
} // end method getFace
// return suit of Card
public Suit getSuit()
{
return suit;
} // end method getSuit
// return String representation of Card
public String toString()
{
return String.format( "%s of %s", face, suit );
} // end method toString
} // end class card
// class DeckOfCards declaration
public class DeckOfCards
{
private List< Card > list; // declare List that will store Cards
// set up deck of Cards and shuffle
public DeckOfCards()
{
Card[] deck = new Card[ 52 ];
int count = 0; // number of cards
// populate deck with card objects
for ( Card.Suit suit : Card.Suit.values() )
{
for ( Card.Face face : Card.Face.values() )
{
deck[ count ] = new Card( face, suit );
++count;
} // end for
} // end for
list = Arrays.asList( deck ); // get List
Collections.shuffle( list ); // shuffle deck
} // end DeckOfCards constructor
// output deck
public void printCards()
{
// display 52 cards in two columns
for ( int i = 0; i < list.size(); i++ )
System.out.printf( "%-19s%s", list.get( i ),
( ( i + 1 ) % 4 == 0 ) ? "\n" : "" );
} // end method printCards
public static void main( String[] args )
{
DeckOfCards cards = new DeckOfCards();
cards.printCards();
} // end main
} // end class DeckOfCards
// Fig. 20.10: DeckOfCards.java
// Card shuffling and dealing with collections method shuffle.
import java.util.List;
import java.util.Arrays;
import java.util.Collections;
// class to represent a cards in a deck of cards
class Card
{
public static enum Face { Ace, Deuce, Three, Four, Five, Six,
Seven, Eight, Nine, Ten, Jack, Queen, King };
public static enum Suit { Clubs, Diamonds, Hearts, Spades };
private final Face face; // face of card
private final Suit suit; // suit of card
// two-arment constructor
public Card( Face cardFace, Suit cardSuit )
{
face = cardFace; // initialize face of card
suit = cardSuit; // initialize suit of card
} // end two-argument Card constructor
// return face of the cards
public Face getFace()
{
return face;
} // end method getFace
// return suit of Card
public Suit getSuit()
{
return suit;
} // end method getSuit
// return String representation of Card
public String toString()
{
return String.format( "%s of %s", face, suit );
} // end method toString
} // end class card
// class DeckOfCards declaration
public class DeckOfCards
{
private List< Card > list; // declare List that will store Cards
// set up deck of Cards and shuffle
public DeckOfCards()
{
Card[] deck = new Card[ 52 ];
int count = 0; // number of cards
// populate deck with card objects
for ( Card.Suit suit : Card.Suit.values() )
{
for ( Card.Face face : Card.Face.values() )
{
deck[ count ] = new Card( face, suit );
++count;
} // end for
} // end for
list = Arrays.asList( deck ); // get List
Collections.shuffle( list ); // shuffle deck
} // end DeckOfCards constructor
// output deck
public void printCards()
{
// display 52 cards in two columns
for ( int i = 0; i < list.size(); i++ )
System.out.printf( "%-19s%s", list.get( i ),
( ( i + 1 ) % 4 == 0 ) ? "\n" : "" );
} // end method printCards
public static void main( String[] args )
{
DeckOfCards cards = new DeckOfCards();
cards.printCards();
} // end main
} // end class DeckOfCards
Assignment 14 - MergeSort / Test
Assignment 14 - MergeSort / Test and Image Result
/*
//Merge Sort
*/
import java.util.Random;
public class MergeSort
{
private int[] data; //array of values
private static Random generator = new Random();
//create array of given size and fill with random integers
public MergeSort( int size )
{
data = new int[size]; //create space for array
//fill array with random ints range 10-99
for( int i = 0; i < size; i++ )
data[i] = 10 + generator.nextInt( 90 );
}
//calls recursive split method to begin merge sorting
public void sort()
{
sortArray( 0, data.length - 1); //split entire array
}
//splits array, sort subarrays and merges subarrays into sorted array
private void sortArray( int low, int high )
{
//test case: size of array equals 1
if( ( high - low ) >= 1 ) //if not base case
{
int middle1 = (low + high )/2; //calculate middle of array
int middle2 = middle1 + 1; //calculate next element over
//output split step
System.out.println( "split: " + subarray( low, high ) );
System.out.println( " " + subarray( low, middle1 ) );
System.out.println( " " + subarray( middle2, high ) );
//split array in half; sort each half of array
sortArray( low, middle1 ); //first half of array
sortArray( middle2, high ); //second half of array
//merge 2 sorted arrays after split calls return
merge( low, middle1, middle2, high );
}
}
//merge 2 sorted subarrays into one sorted sub array
private void merge( int left, int middle1, int middle2, int right )
{
int leftIndex = left; //index into left subarray
int rightIndex = middle2; //index into right subarray
int combinedIndex = left; //index into temp. work array
int[] combined = new int[data.length]; //working array
//output 2 subarrays before merging
System.out.println( "merge: " + subarray( left, middle1 ) );
System.out.println( " " + subarray( middle2, right ) );
//merge arrays until reaching end of either
while( leftIndex <= middle1 && rightIndex <= right )
{
//place smaller of 2 current elements into result
//and move to next space in arrays
if( data[leftIndex] <= data[rightIndex] )
combined[combinedIndex++] = data[leftIndex++];
else
combined[combinedIndex++] = data[rightIndex++];
}
//if array is empty
if( leftIndex == middle2 )
//copy in rest of right array
while( rightIndex <= right )
combined[combinedIndex++] = data[rightIndex++];
else
//copy in rest of left array
while( leftIndex <= middle1 )
combined[combinedIndex++] = data[leftIndex++];
//copy values back into original array
for( int i = left; i <= right; i++ )
data[i] = combined[i];
//output merged array
System.out.println(" " + subarray( left, right ) );
System.out.println();
}
//method to output certain values in array
public String subarray( int low, int high )
{
StringBuilder temporary = new StringBuilder();
//output spaces for alignment
for( int i = 0; i < low; i++ )
temporary.append( "" );
//output elements left in array
for( int i = low; i <= high; i++ )
temporary.append( "" + data[i] );
return temporary.toString();
}
//method to output values in array
public String toString()
{
return subarray( 0, data.length - 1 );
}
}
/*
//main function
*/
public class MergeSortTest
{
public static void main( String[] args )
{
//create object to perform merge sort
MergeSort sortArray = new MergeSort(10);
//print unsorted array
System.out.println( "Unsorted: " + sortArray + "\n" );
sortArray.sort(); //sort array
//print sorted array
System.out.println( "Sorted: " + sortArray );
}
}
/*
//Merge Sort
*/
import java.util.Random;
public class MergeSort
{
private int[] data; //array of values
private static Random generator = new Random();
//create array of given size and fill with random integers
public MergeSort( int size )
{
data = new int[size]; //create space for array
//fill array with random ints range 10-99
for( int i = 0; i < size; i++ )
data[i] = 10 + generator.nextInt( 90 );
}
//calls recursive split method to begin merge sorting
public void sort()
{
sortArray( 0, data.length - 1); //split entire array
}
//splits array, sort subarrays and merges subarrays into sorted array
private void sortArray( int low, int high )
{
//test case: size of array equals 1
if( ( high - low ) >= 1 ) //if not base case
{
int middle1 = (low + high )/2; //calculate middle of array
int middle2 = middle1 + 1; //calculate next element over
//output split step
System.out.println( "split: " + subarray( low, high ) );
System.out.println( " " + subarray( low, middle1 ) );
System.out.println( " " + subarray( middle2, high ) );
//split array in half; sort each half of array
sortArray( low, middle1 ); //first half of array
sortArray( middle2, high ); //second half of array
//merge 2 sorted arrays after split calls return
merge( low, middle1, middle2, high );
}
}
//merge 2 sorted subarrays into one sorted sub array
private void merge( int left, int middle1, int middle2, int right )
{
int leftIndex = left; //index into left subarray
int rightIndex = middle2; //index into right subarray
int combinedIndex = left; //index into temp. work array
int[] combined = new int[data.length]; //working array
//output 2 subarrays before merging
System.out.println( "merge: " + subarray( left, middle1 ) );
System.out.println( " " + subarray( middle2, right ) );
//merge arrays until reaching end of either
while( leftIndex <= middle1 && rightIndex <= right )
{
//place smaller of 2 current elements into result
//and move to next space in arrays
if( data[leftIndex] <= data[rightIndex] )
combined[combinedIndex++] = data[leftIndex++];
else
combined[combinedIndex++] = data[rightIndex++];
}
//if array is empty
if( leftIndex == middle2 )
//copy in rest of right array
while( rightIndex <= right )
combined[combinedIndex++] = data[rightIndex++];
else
//copy in rest of left array
while( leftIndex <= middle1 )
combined[combinedIndex++] = data[leftIndex++];
//copy values back into original array
for( int i = left; i <= right; i++ )
data[i] = combined[i];
//output merged array
System.out.println(" " + subarray( left, right ) );
System.out.println();
}
//method to output certain values in array
public String subarray( int low, int high )
{
StringBuilder temporary = new StringBuilder();
//output spaces for alignment
for( int i = 0; i < low; i++ )
temporary.append( "" );
//output elements left in array
for( int i = low; i <= high; i++ )
temporary.append( "" + data[i] );
return temporary.toString();
}
//method to output values in array
public String toString()
{
return subarray( 0, data.length - 1 );
}
}
/*
//main function
*/
public class MergeSortTest
{
public static void main( String[] args )
{
//create object to perform merge sort
MergeSort sortArray = new MergeSort(10);
//print unsorted array
System.out.println( "Unsorted: " + sortArray + "\n" );
sortArray.sort(); //sort array
//print sorted array
System.out.println( "Sorted: " + sortArray );
}
}
Assignment 13 - InsertionSort / Test
Assignment 13 - InsertionSort / Test
/*
Assignment 13
Insertion Sort
*/
import java.util.Random;
public class InsertionSort
{
private int[] data; //array of values
private static Random generator = new Random();
//create array of given size to fill
public InsertionSort( int size )
{
data = new int[size]; //create space for arrays
//fill arrays with random numbers 10-99
for( int i = 0; i < size; i++ )
data[i] = 10 + generator.nextInt(90);
}
//sort array using insertion sort
public void sort()
{
int insert; //temp; variable to hold element to insert
//loop over data.length - elements
for( int next = 1; next < data.length; next++ )
{
//sort value in current element
insert = data[next];
//initialize location to palce element
int moveItem = next;
//search for place to put current element
while( moveItem > 0 && data[moveItem - 1] > insert )
{
//shift element right one slot
data[moveItem] = data[moveItem - 1];
moveItem--;
}
data[moveItem] = insert; //place inserted element
printPass( next, moveItem ); //output pass of algorithm
}
}
//print a pass of the algorithm
public void printPass( int pass, int index )
{
System.out.print( String.format( "after pass %2d: ", pass ) );
//output elements till swapped item
for( int i = index + 1; i < data.length; i++ )
System.out.print( data[i] + " ");
System.out.print( "\n " ); //for allignment
//indicate amount of array that is sorted
for( int i = 0; i <= pass; i++ )
System.out.print( "-- " );
System.out.println( "\n" ); //add endline
}
//method to output values in array
public String toString()
{
StringBuilder temporary = new StringBuilder();
//iterate through array
for ( int element : data )
temporary.append( element + " " );
temporary.append( "\n" ); //add endline character
return temporary.toString();
}
}
/*
Assignment 13
main function
*/
public class InsertionSortTest
{
public static void main( String[] args )
{
//create object to preform insertion sort
InsertionSort sortArray = new InsertionSort( 10 );
System.out.println( "Unsorted array: " );
System.out.println( sortArray ); //print unsorted array
sortArray.sort();
System.out.println( "Sorted array: " );
System.out.println( sortArray ); //print sorted array
}
}
/*
Assignment 13
Insertion Sort
*/
import java.util.Random;
public class InsertionSort
{
private int[] data; //array of values
private static Random generator = new Random();
//create array of given size to fill
public InsertionSort( int size )
{
data = new int[size]; //create space for arrays
//fill arrays with random numbers 10-99
for( int i = 0; i < size; i++ )
data[i] = 10 + generator.nextInt(90);
}
//sort array using insertion sort
public void sort()
{
int insert; //temp; variable to hold element to insert
//loop over data.length - elements
for( int next = 1; next < data.length; next++ )
{
//sort value in current element
insert = data[next];
//initialize location to palce element
int moveItem = next;
//search for place to put current element
while( moveItem > 0 && data[moveItem - 1] > insert )
{
//shift element right one slot
data[moveItem] = data[moveItem - 1];
moveItem--;
}
data[moveItem] = insert; //place inserted element
printPass( next, moveItem ); //output pass of algorithm
}
}
//print a pass of the algorithm
public void printPass( int pass, int index )
{
System.out.print( String.format( "after pass %2d: ", pass ) );
//output elements till swapped item
for( int i = index + 1; i < data.length; i++ )
System.out.print( data[i] + " ");
System.out.print( "\n " ); //for allignment
//indicate amount of array that is sorted
for( int i = 0; i <= pass; i++ )
System.out.print( "-- " );
System.out.println( "\n" ); //add endline
}
//method to output values in array
public String toString()
{
StringBuilder temporary = new StringBuilder();
//iterate through array
for ( int element : data )
temporary.append( element + " " );
temporary.append( "\n" ); //add endline character
return temporary.toString();
}
}
/*
Assignment 13
main function
*/
public class InsertionSortTest
{
public static void main( String[] args )
{
//create object to preform insertion sort
InsertionSort sortArray = new InsertionSort( 10 );
System.out.println( "Unsorted array: " );
System.out.println( sortArray ); //print unsorted array
sortArray.sort();
System.out.println( "Sorted array: " );
System.out.println( sortArray ); //print sorted array
}
}
Assignment 12 - SelectionSort / Test
Assignment 12 - SelectionSort / Test and Image Result
/*
//Selection Sort Algorithm
*/
import java.util.Random;
public class SelectionSort
{
private int[] data; //array of value
private static Random generator = new Random();
//create array if given size and fill w/ random int
public SelectionSort( int size)
{
data = new int[size]; //create space for array
//fill array with random int 10-99
for( int i = 0; i < size; i++ )
data[i] = 10 + generator.nextInt( 90 );
}
//sort array using selection sort
public void sort()
{
int smallest; //index of smallest element
//loop over data length -1
for (int i = 0; i < data.length - 1; i++)
{
smallest = i; //first index of remaining array
//loops to find index of smallest element
for (int index = i + 1; index < data.length; index++)
if( data[index] < data[smallest])
smallest = index;
swap( i, smallest); //swap smallest elements into position
printPass( i + 1, smallest );
}
}
//helper method to swap values intwo elements
public void swap( int first, int second )
{
int temporary = data[first]; //store first in temporary
data[first] = data[second]; //replace first in second
data[second] = temporary; // put temporary in second
}
//print a pass of algorithm
public void printPass( int pass, int index )
{
System.out.print( String.format( "after pass %2d: ",pass) );
//output elements till selected itme
for (int i=0; i < index; i++)
System.out.print( data[i] + " ");
System.out.print( "\n "); //for alignment
//indicate amount of array that is sorted
for( int j = 0; j < pass; j++ )
System.out.print("--");
System.out.println("\n"); //add endline
}
//method to output values in array
public String toString()
{
StringBuilder temporary = new StringBuilder();
//iterate through array
for (int element : data)
temporary.append( element + " " );
temporary.append("\n");
return temporary.toString();
}
}
/*
//main function
*/
public class SelectionSortTest
{
public static void main( String[] args )
{
//create object to preform selection sort
SelectionSort sortArray = new SelectionSort(10);
System.out.println( "Unsortoed array:");
System.out.println( sortArray ); //print unsorted array
sortArray.sort(); //sort array
System.out.println( "Sorted Array:");
System.out.println( sortArray ); //print sorted array
}
}
/*
//Selection Sort Algorithm
*/
import java.util.Random;
public class SelectionSort
{
private int[] data; //array of value
private static Random generator = new Random();
//create array if given size and fill w/ random int
public SelectionSort( int size)
{
data = new int[size]; //create space for array
//fill array with random int 10-99
for( int i = 0; i < size; i++ )
data[i] = 10 + generator.nextInt( 90 );
}
//sort array using selection sort
public void sort()
{
int smallest; //index of smallest element
//loop over data length -1
for (int i = 0; i < data.length - 1; i++)
{
smallest = i; //first index of remaining array
//loops to find index of smallest element
for (int index = i + 1; index < data.length; index++)
if( data[index] < data[smallest])
smallest = index;
swap( i, smallest); //swap smallest elements into position
printPass( i + 1, smallest );
}
}
//helper method to swap values intwo elements
public void swap( int first, int second )
{
int temporary = data[first]; //store first in temporary
data[first] = data[second]; //replace first in second
data[second] = temporary; // put temporary in second
}
//print a pass of algorithm
public void printPass( int pass, int index )
{
System.out.print( String.format( "after pass %2d: ",pass) );
//output elements till selected itme
for (int i=0; i < index; i++)
System.out.print( data[i] + " ");
System.out.print( "\n "); //for alignment
//indicate amount of array that is sorted
for( int j = 0; j < pass; j++ )
System.out.print("--");
System.out.println("\n"); //add endline
}
//method to output values in array
public String toString()
{
StringBuilder temporary = new StringBuilder();
//iterate through array
for (int element : data)
temporary.append( element + " " );
temporary.append("\n");
return temporary.toString();
}
}
/*
//main function
*/
public class SelectionSortTest
{
public static void main( String[] args )
{
//create object to preform selection sort
SelectionSort sortArray = new SelectionSort(10);
System.out.println( "Unsortoed array:");
System.out.println( sortArray ); //print unsorted array
sortArray.sort(); //sort array
System.out.println( "Sorted Array:");
System.out.println( sortArray ); //print sorted array
}
}
Assignment 360 - Towers of Hanoi / Test
Assignment 360 - Towers of Hanoi / Test and Image result
/*
Towers of Hanoi
*/
public class TowersOfHanoi
{
private int numDisks; //number od idsks to move
public TowersOfHanoi( int disks )
{
numDisks = disks;
}
//recursively more diks between towers
public void solveTowers( int disks, int sourcePeg, int destinationPeg, int tempPeg)
{
//base case -- only one disk to move
if(disks == 1)
{
System.out.printf( "\n%d --> %d", sourcePeg, destinationPeg);
return;
}
//recursing step -- move (disk - 1) disks from sourcePeg
//to tempPEg using destinationPeg
solveTowers( disks - 1, sourcePeg, tempPeg, destinationPeg );
//move last disk from sourcePeg to destinationPeg
System.out.printf( "\n%d --> %d", sourcePeg, destinationPeg);
//move (disks - 1) disks from tempPeg to destinationPeg
solveTowers( disks - 1, tempPeg, destinationPeg, sourcePeg);
}
}
TowersOfHanoiTest
/*
main function to be run
*/
public class TowersOfHanoiTest
{
public static void main( String args[] )
{
int startPeg = 1; //value 1 used to indicate startPeg in output
int endPeg = 3; //value 3 used to indicate endPeg in output
int tempPeg = 2; //value 2 used to indicate tempPeg output
int totalDisks = 3; // number of disks
TowersOfHanoi towersOfHanoi = new TowersOfHanoi( totalDisks );
//initial nonrecursive call: move all disks
towersOfHanoi.solveTowers( totalDisks, startPeg, endPeg, tempPeg );
}
}
/*
Towers of Hanoi
*/
public class TowersOfHanoi
{
private int numDisks; //number od idsks to move
public TowersOfHanoi( int disks )
{
numDisks = disks;
}
//recursively more diks between towers
public void solveTowers( int disks, int sourcePeg, int destinationPeg, int tempPeg)
{
//base case -- only one disk to move
if(disks == 1)
{
System.out.printf( "\n%d --> %d", sourcePeg, destinationPeg);
return;
}
//recursing step -- move (disk - 1) disks from sourcePeg
//to tempPEg using destinationPeg
solveTowers( disks - 1, sourcePeg, tempPeg, destinationPeg );
//move last disk from sourcePeg to destinationPeg
System.out.printf( "\n%d --> %d", sourcePeg, destinationPeg);
//move (disks - 1) disks from tempPeg to destinationPeg
solveTowers( disks - 1, tempPeg, destinationPeg, sourcePeg);
}
}
TowersOfHanoiTest
/*
main function to be run
*/
public class TowersOfHanoiTest
{
public static void main( String args[] )
{
int startPeg = 1; //value 1 used to indicate startPeg in output
int endPeg = 3; //value 3 used to indicate endPeg in output
int tempPeg = 2; //value 2 used to indicate tempPeg output
int totalDisks = 3; // number of disks
TowersOfHanoi towersOfHanoi = new TowersOfHanoi( totalDisks );
//initial nonrecursive call: move all disks
towersOfHanoi.solveTowers( totalDisks, startPeg, endPeg, tempPeg );
}
}
Assignment 1 9/30/10 FactorialCalculator and FactorialTest
Assignment 1 9/30/10 FactorialCalculator and FactorialTest with results
/*
Assignment 1 09/30/10
*/
public class FactorialCalculator
{
//recursive declaration on method factorial
public long factorial( long number )
{
if (number <=1 ) //test for base case
return 1; //base cases: 0!=1 and 1!=1
else //recursion step
return number * factorial(number - 1);
}
//output factorials for values 0-10
public void displayFactorials()
{
//calculate factorials of 0 thourhg 10
for (int counter = 0; counter <= 10; counter++)
System.out.printf( "%d! = %d\n", counter, factorial( counter ) );
}
}
/*
Fig 15.4
9/18/07
*/
public class FactorialTest
{
//calculate factorials of 0-10
public static void main( String args[] )
{
FactorialCalculator factorialCalculator = new FactorialCalculator();
factorialCalculator.displayFactorials();
}
}
/*
Assignment 1 09/30/10
*/
public class FactorialCalculator
{
//recursive declaration on method factorial
public long factorial( long number )
{
if (number <=1 ) //test for base case
return 1; //base cases: 0!=1 and 1!=1
else //recursion step
return number * factorial(number - 1);
}
//output factorials for values 0-10
public void displayFactorials()
{
//calculate factorials of 0 thourhg 10
for (int counter = 0; counter <= 10; counter++)
System.out.printf( "%d! = %d\n", counter, factorial( counter ) );
}
}
/*
Fig 15.4
9/18/07
*/
public class FactorialTest
{
//calculate factorials of 0-10
public static void main( String args[] )
{
FactorialCalculator factorialCalculator = new FactorialCalculator();
factorialCalculator.displayFactorials();
}
}
Subscribe to:
Posts (Atom)