Timothy Schwartz CSE 231 Project Zero January 15, 2012
Timothy Schwartz CSE 231 Project Zero January 15, 2012
Contents
Table of Figures: ............................................................................................................................................ 2 Part I - Sorting ............................................................................................................................................... 3 Analysis ..................................................................................................................................................... 3 Design........................................................................................................................................................ 3 Program Code ........................................................................................................................................... 4 Style/Validation......................................................................................................................................... 6 Conclusion: ................................................................................................................................................ 6 Part II Prime Numbers ................................................................................................................................ 6 Analysis ..................................................................................................................................................... 6 Design........................................................................................................................................................ 6 Program Code: .......................................................................................................................................... 8 Style/Validation:........................................................................................................................................ 9 Conclusion: ................................................................................................................................................ 9
Table of Figures:
Figure 1: Sorting Code Segment.................................................................................................................... 5 Figure 2: Algorithm Starting with 8 - Appended to 10 Outputs.................................................................... 7 Figure 3: Prime Number Algorithm Flowchart .............................................................................................. 7 Figure 4: Prime Number Code Segment ....................................................................................................... 8
Part I - Sorting
Analysis
This problem can be broken down into a few sections: user inputs data, program sorts, and program displays. For the user input, the program will be looking for numbers but the user may not input a number an exception may be needed here. When it comes to sorting, the information provided limits the amount of integers to 100. With a smaller n and efficiency not specifically mentioned, the solution can be kept simpler by using a bubble sort or quick sort as opposed to a more complicated but more efficient merge sort algorithm. Lastly for the display, instructed to have ten integers per line, a combination of print() and println() will be used.
Design
The user is first prompted to input the numbers with a space in-between. Although we can assume that the user wants to sort numbers, we must account to mistyping, or some other input error. This can be accomplished by taking whatever is entered and putting it in a string. Then, using try and catch, attempt to put that sting into an array of integers. Besides catching input errors, this will also separate the integers. Sorting the numbers is done by a bubble sort method. Although the efficiently is not the best, the simplicity of implementation is. Using two nested for loops, there is an initial sort form left to right checking the current integer with the previous neighbor. If the left neighbor is bigger, then a swap must take place. This can be accomplished easily with a temporary integer and copying. After the initial loop is done, and secondary loop runs the same process to resort what was missed the first time. (Please See the Diagram for More Information).
Start.
Display output
End.
Program Code
/** -- TIMOTHY SCHWARTZ -- CSE231 -- PROJECT ZERO -- PART I */ import java.util.Scanner; public class bubble_sort { //MAIN METHOD - ASKS FOR LIST OF NUMBERS, SORTS, DISPLAYS SORTED LIST public static void main(String[] args){ // VARIABLES Scanner myScanner = new Scanner (System.in); //TO GET THE NUMBERS int userNum[]; //STORE THE NUMBERS int sortedNum[]; //OUTPUT OF NUMBERS int counter = 0; //USED TO PUT TEN INTEGERS PER LINE String userIn = ""; //TO GET NUMBERS String temp[]; //USED WHEN SPLITING NUMBERS // GET THE NUMBERS // FIRST ASK THE USER System.out.println("Please enter 0 - 100 integers with a space in between"); System.out.println("When you are finished, please enter 'done'."); if (myScanner.hasNextLine()){ userIn = myScanner.nextLine(); //ONLY GET NUMBERS IF TYPING HAS OCCURED //BRING IN THE NUMBERS
//ECHO THE NUMBERS FOR USER TO SEE POSSIBLE MISTAKE System.out.print("You have entered: "); System.out.println(userIn); //CREATE AN INTEGER ARRAY OF PROPER SIZE }
temp = userIn.split(" "); //SEPERATE WITH SPACE DELIMITER if (temp.length > 100){ System.out.println("ERROR: This program is limited to 100 integers"); } else{ userNum = new int[temp.length];
//POPULTE INTEGER ARRAY for (int k = 0; k < temp.length; k++){ try{ userNum[k] = Integer.parseInt(temp[k]); //ONLY POPULATE IF IT IS AN INTEGER } catch(Exception e){ //ERROR TO LET USER KNOW THERE IS A PROBLEM System.out.println("ERROR: Please enter numbers only"); }finally{ } }
// SORT THE NUMBERS sortedNum = new int[userNum.length]; //SET APPROPRIATE SIZE sortedNum = mySorter(userNum); //CALL THE BUBBLE SORT // RETURN THE NUMBMERS System.out.println(" "); //SEPERATE INPUT FROM OUTPUT System.out.println("Sorted List: "); //DESCRIPTER //TEN INTEGERS PER LINE for (int p = 0; p < sortedNum.length; p ++){ if (counter < 10){ //STAY ON CURRENT LINE System.out.print(sortedNum[p]); //ADD NUMBER System.out.print(" "); //ADD SPACE counter = counter + 1; //INCREMENT } else{ System.out.println(" "); //START A NEW LINE System.out.print(sortedNum[p]); //ADD NUMBER System.out.print(" "); //ADD SPACE counter = 1; //RESET FOR NEXT LINE - 1 FOR JUST DISPLAYED } } } }
//USING BUBBLE SORT public static int[] mySorter(int[] gotNums){ //GET SIZE AND DECLARE A SWAP VARIABLE int size = gotNums.length; int swapTemp = 0; for(int i = 0; i < size; i++){ for(int j = 1; j < (size-i); j++){ //FIRST ROUND THROUGH if(gotNums[j-1] > gotNums[j]){ //COMPARE NEIGHBORS swapTemp = gotNums[j-1]; //SWAP TO RIGHT IF LEFT IS BIGGER gotNums[j-1] = gotNums[j]; gotNums[j] = swapTemp; } } } return(gotNums); } }
Style/Validation
I tested this program by cutting and pasting a list of jumbled numbers into the terminal. This allows for easy slight manipulation during testing. I also tested entering a non-number in. I have an exception to catch this. It will continue to sort and place a zero in for the non-number input. Lastly, I tested entering over 100 numbers. In this case the program will cut the user off.
Conclusion:
There were a few pieces of error checking required mostly due to the user input portion of the program. I chose the bubble sort algorithm because it is simple to implement and efficiency, in this case, is not a primary concern. In the future, or as a more general case, I think I would choose merge sort. Merge sort has a big oh of nlog(n), which is very high for a sorting algothirm.
Design
When approaching this problem, I used the hint as the basis for my algorithm (See Diagram on Next Page). The provided hint allows for fast execution which is the biggest criteria in the description. Very simply, an array of integers, numList, is created and populated by a for loop. Then, inside of a while loop, the zeroth element is displayed. A duplicate array, temp, is made, comparing each element to the zeroth element, checking for a remainder when dividing takes place. If the remainder is zero than that element is divisable by the zeroth element and should be removed from the next output array. This process continues until the array is empty. To further improve this method, an attempt could be made to eliminate the use of a temporary array. Without this extra variable, memory and execution time may be saved. The downside to this algorithm is that when 2 is the first number the output is correct, but this is not the case for any starting number. If, for example, the sequence started with 8, then by this algorithm, non-prime numbers, specifically multiples of 2, like 10, 12,etc. would be displayed. (See Picture on Next Page).
No End.
Figure 3: Prime Number Algorithm Flowchart
Program Code:
/** -- TIMOTHY SCHWARTZ -- CSE231 -- PROJECT ZERO -- PART II */ public class primes { //MAIN METHOD - CALLS THE 'displayPrimes' METHOD public static void main(String[] args){ displayPrimes(); } //DISPLAY PRIMES METHOD - CREATES LIST. //DISPLAYS MINIMUM. REMOVES MULTIPLES. REPEAT public static void displayPrimes(){ //VARIABLES int numList[] = new int[9999]; //THE MAIN LIST int temp[] = new int[9999]; //LIST FOR CALCULATION int counter = 0; //A COUNTER FOR POPULATING THE LIST //CREATE THE INTIAL LIST WITH ALL NUMBERS 2-10000 for(int i = 0; i < 9999; i++){ numList[i] = i + 2; } //MAIN LOOP FOR REDUCING THE LIST while (numList[0] != 0){ //WHEN THE PRIMES ARE DONE, numList[0] = 0 counter = 0; //INTIALIZE COUNTER System.out.print(numList[0]); //DISPLAY THE CURRENT PRIME System.out.print(" "); //ADD A SPACE //COPY THE ARRAY TO A TEMP ARRAY. CLEAR THE OUTPUT ARRAY for( int k = 0; k < numList.length; k++){ temp[k] = numList[k]; //should stop at zero ??? numList[k] = 0; //clear that spot } //REMOVE MULTIPLES for( int j = 0; j < numList.length; j++){ if (temp[j] % temp[0] == 0){ //CHECK IF MULTIPLE } else{ numList[counter] = temp[j]; counter = counter + 1; } } } } }
Style/Validation:
I tried to use meaningful variable names and added some comments, however the code may be referenced for more detail. When validating this method, I used a simple website to check the output. ( http://primes.utm.edu/lists/small/10000.txt). I trust this websites credibility for many reasons. It was close to the top on Google, it is from a university website and it matches a few other lists that I checked. In addition, I tried changing the start number to see if that affected the output and it did as mentioned above. I am not sure about error handling in this method. Most of the time, errors come from poor user input, which there is none in this case.
Conclusion:
I have chosen my solution not only because the hint suggested it, but also because it is the simplest. Although it will not handle being adapted easily, that was not one of the criterions listed.