Assignment no. 2 02102 Introductory Programming s123805 s123 805 Ois´ın ın Daly Frisch Kiær Ki ær s123099 Johanne Louise Larsen s113180 Sebastian Aleksander Thomsen April 1, 2013
Work Distribution:
Opgave 1: s123099 Johanne Louise Larsen Opgave 2: s113180 Sebastian Aleksander Thomsen Opgave 3: s123805 Ois´ Ois´ın Daly Frisch Kiær and s113180 Sebastian Sebastian Aleksander Aleksander Thomsen Thomsen
1
Abstract
In this report, we will be outlining our solutions to a set of programming challenges that we were were set as part part of an introduct introductory ory programmi programming ng course. course. The first is a program program for factori factoring ng numbers into the product of a list of primes, the second program takes the user on a randomly generated walk on grids of various sizes, and the final program is a computer version of the penand-paper and-paper racing game VectorRace VectorRace.. All the challenges challenges have have been b een completed completed to specification, specification, and with some degree of creativity thrown in for good measure.
1
CONTENTS
CONTENTS
Contents 1
Abstract
1
2
PrimeFactors
3
2.1
Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3
2.2
Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3
2.3
Testing
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3
2.4
Comments and discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4
3
4
Randomwalk
5
3.1
Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5
3.2
Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
5
3.3
Testing
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6
3.4
Comments and discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6
VectorRace
8
4.1
Analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8
4.1.1
Possible features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8
4.2
Solution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
8
4.3
Testing
4.4
Comments and discussion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 4.4.1
5
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
10
Implemented features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Conclusion
13
2
2
2
PRIMEFACTORS
PrimeFactors
2.1
Analysis
Creating prime factorizations is a way of splitting any number into prime numerals. The prime numerals are read as primenumber, 1 ∗ pn, 2 ∗ ... ∗ pn, n = number. The easiest way to get the prime factorization is to ask a series of questions; ”if the number is divided with by first prime number (2) does it have a remainder?” if it does, we ask if it has one if divided with by second prime number (3) and if it does this continues until we get a number which does not. When this number is found, it is the first number of the factorization. After this, the starting number has to be divided by the first number before we again ask which prime numbers it can be divided with, without having a remainder. The second time we ask our many questions we start with the last prime number. This means that if the prime factorization start with 7, we start the next round by asking if the number/7 can be divided by 7. this now gives us the issue of factorization of prime numbers. They will always only have 1 and themselves as prime factorization. We can use that to our advantage and use it to test the code, along with known prime factorizations. 2.2
Solution
The code is constructed by first asking for a user input, using a scanner. The user is asked to enter a number ranging from 0 to MMM. this number is then stored in the variable ”tal”. A new variable is then declared in order to not change the value of tal before it makes sense, this variable is called mod. The first step was to ask if the first prime numeral could be divided with the number (tal) without it having a remainder. This is solved in the code by taking modulus to tal and saving it in mod. afterwards we ask if mod is different from 0. if it is 0 it means that there will be no remainder if we divide the two numbers, if it is anything else than 0, it means it has a remainder, and that the loop has to keep running. We used a while loop for this purpose and therefore have to have a counter inside the if statement. if mod does evaluate to 0 we save the number (i) in a string and divide tal with the same number, in order to then go back and find the second number. The while loop runs until i equals the number, this means that if the number itself is a prime number it will be printed. in order to give the user a chance to try again we introduce another while loop, which runs until another number than 1 is entered in the second scanner.0 or another number will also close the scanner for good measure. 2.3
Testing
entering 0 will give no output. entering large numbers will make the program ”think” for a very long time.
3
2.4
Comments and discussion
2
PRIMEFACTORS
Enter positive number between 0 and 9,223,372,036,854,775,807: 0
Would you like to enter another number? 1 = yes, 0 = no: 1 Enter positive number between 0 and 9,223,372,036,854,775,807: 2147483648 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 Would you like to enter another number? 1 = yes, 0 = no: 1 Enter positive number between 0 and 9,223,372,036,854,775,807: 2147483649 3 715827883 Would you like to enter another number? 1 = yes, 0 = no: 0 Program terminated
Entering a prime numeral writes the number itself. Enterpositive number between 0 and 9,223,372,036,854,775,807: 17 17 Would you like to enter another number? 1 = yes, 0 = no: 17 Program terminated
entering a negative number gives no output. Entering a character instead of a number gives a runtime error. also, the choice while loop is an integer because we don’t need large numbers, therefore anything higher than 2147483647 will also produce a runtime error. Enter positive number between 0 and 9,223,372,036,854,775,807: -8
Would you like to enter another number? 1 = yes, 0 = no: y Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at java.util.Scanner.nextInt(Unknown Source) at PrimeNumeralsbackup.main(PrimeNumeralsbackup.java:16)
2.4
Comments and discussion
In order to make the program run faster it could be beneficial to only evaluate on prime numbers and not on all numbers. This could be achieved with an array. in the instance that the user enters 0 there could have been a fixed output such as 0. this could have been done with an if-sentence before the loop. 4
3
3 3.1
RANDOMWALK
Randomwalk Analysis
I’m going to model Random Walk. The idea is to simulate a random walk trough a city with square equally sized blocks between the streets. Every time the random walker reaches a corner of a block he has to decide where he wants go next at random. He starts at the middle of the city, and keeps on walking until he reaches the border of town. While his moving a pattern of his movements is drawn. To simulate this i have to make the computer decide where the randomwalker wants to go. I chose to let the computer decide i 2 steps. First i decide if i want to walk in a vertical or horizontal direction. Then ,if horizontal, left or right or, if vertical, up or down. Based on this I increment/decrement the randomwalkers position accordingly, as you would with coordinates in a xy-graph. After the update the new p oint is draw, and the same thing happens over and over, until the randomwalker finds his way to the border of the map. The random walk is a fencepost problem in the sense that i want to map his position, compute a new position, then map the new position,compute a new position and so on. However i don’t want to draw his position again when he has reached the border. Therefore the map is initialized so the center of the map always have the coordinates (0 , 0). This allows me to put the randomwalker in the center of the map, by initializing the x and y values to 0. If the new position of the randomwalker then is beyond the map the while loop will stop and, he will ”move” no more. 3.2
Solution
The code that decides the random walk looks like this, here the call StdDraw.point(x,y) is responsible for drawing the point, the while loop terminates as soon as on of the coordinates goes beyond the limits of the map: 1
2
3
4
w h i l e (− s i z e <=x && x<= s i z e && − s i z e <=y && y<=s i z e ) { StdDraw . poi nt (x , y ) ; i f (Math. random() > 0 . 5 ) { i f (Math. random() > 0 . 5 ) {
5
x+=1;
6
} else {
7
x −=1;
8
9
10
} } else { i f (Math. random() > 0 . 5 ) {
11
y+=1;
12
} else {
13
y −=1;
14
}
5
3.3
Testing
3.3
3
RANDOMWALK
Testing
So in the following figure (Figur 2), 4 test of the random walk was done. The user entered mapsize of 10, 50, 200 and 400:
(a) Mapsize: 20x20
(b) Mapsize: 100x100
(c) Mapsize: 400x400
(d) Mapsize: 800x800
Figure 1: Varous tests If you decided that you would like to try you luck with a ”string” sized map, an exception will be thrown, this is not a checked exception and therefore i do not have to declare that an exception will be thrown in my method. This exception is thrown from the scanner object itself: Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:909) at java.util.Scanner.next(Scanner.java:1530) at java.util.Scanner.nextInt(Scanner.java:2160) at java.util.Scanner.nextInt(Scanner.java:2119) at RandomWalk.main(RandomWalk.java:10)
3.4
Comments and discussion
In the program there is a setScale method. This is only used once and is therefore not of much use as a method, since there are no redundancy, however I choose to put it in a method, with a self explanatory name so that the main method would be easier to follow. I could have make the program robust instead of interrupting the program execution, by allowing 6
3.4
Comments and discussion
3
RANDOMWALK
an exception to be thrown, but i feel that it is unnecessary in such a simple program. I think the program could become more interesting by implementing some other functionalities, for instance one could initialize a matrix to keep track of all the places the randomwalker walked, and then color each place according to the number of times visited.This would allow one to see a better picture of the exact walk Also this same matrix could be used to make the randomwalker make ”smart” choices, so that he would never visit the same place twice. Another interesting thing idea would be to make an automated simulation, to see what the maximum amount of steps you could get would be. Then store the amount of steps and the map, and overwriting these data if the next walk was greater than the last.
7
4
4
VECTORRACE
VectorRace
The scope if this assignment is more vast than previous programming challenges we have undertaken, so the documentation of our solution will, in the interest of brevity and readability, we are not going into as much detail, mainly outlining our solution and the thoughts behind it. 4.1
Analysis
We were asked to create a computer version of the pen-and-paper game Vector Race. The game has the players racing each other around a map, drawn on a grid, where they play around with simplified approximations of principles like steering, acceleration, inertia and of course vectors. The pen-and-paper version has many iterations, with pen and paper being a very flexible platform where rules can be made up on the fly. Our challenge was to code at least the basic functionality of the game into a computer program, a medium that, while lacking in flexibility, can make certain parts of playing the game simpler and less time consuming. 4.1.1
Possible features
• Drawing a map • Basic moving around on the grid, with colored lines • Collision with walls (explicit lose-state) • Multiplayer support • Crossing the finishing line (explicit win-state) • More, different maps for added challenge • Artificial Intelligence - Playing single player against the computer. • Streamlined and user friendly user interface 4.2
Solution
In order to make VectorRace we have chosen to work with point objects instead of just x and y coordinates. We decided to do so to make it easier for us to keep track of the actual point we were doing operations on, as well as keep the length of the source code shorter. Furthermore, point objects can be stored in a arrayList which enables us to implement and work with sequentially named points for keeping track of and moving around multiple players. Before the game can start, we have to draw a map; a series of methods have been implemented so that this can be achieved in an easy way. The methods have been written in such a manner so that the program could be expanded with more maps easily. We have chosen not to focus so much on a multitude of different maps, but rather on fleshing out basic gameplay functionalities. Note that there is still some variance in maps, given the fact that the map size is specified by the 8
4.2
Solution
4
VECTORRACE
player at the start of the game. When we want to move our point, according to the rules of the game, we use the previous point and the current point to calculate a reference point from. The calculation looks like this in principle: RefPoint = CurPoint + (CurPoint − PrePoint). From this reference point we can then input the direction of the steering as the numbers on a computer numpad, with the number 5 serving as the center, and the rest of the numbers corresponding to the cardinal directions. Which way to go is determined by a series of if statements that trigger only if the corresponding integer is pressed, it then modifies the point according to the steering rules. This method has been made robust in the sense that you cannot enter a number less than 1 or higher than 9, if you do you will be asked to enter a number. To have a record of the previous point, we store it as a variable just before changing the current point, that allows us to use it in the next computation of the reference point, which is then in turn used to manipulate the current point. We have implemented a collision detection as well. It detects when you reach the borders of the map, as well as when you hit the center of the map. This is done via a series of boolean operators. We have written the code so that you lose the game when you hit something outside the track. Another way to do it was to simply stop the car completely at a wall collision, backtracking any overstep to the point of collision, then allow the player to proceed the game from there with zero inertia. This was a complicated process, and also takes away from any possible tension in the gameplay, so we decided to prioritize other things. We have also been working on a different way to determinate if a point is out of bounds than the boolean operators. We made a matrix model of the map consisting of zeroes, then we marked the places where there were obstacles on the map with ones in the matrix, this way we could easier evaluate if the p oint was out of bounds in more advanced maps. But time was short so we went with a simpler but less flexible solution for this map. We designed the game so that a maximum of 4 players is allowed, in principle more could easily be added but we found that the map would be to crowded. When the game is played by multiple players, each player has his or her own line colour. The colour of the player is predefined, and is determined via the for loop iterator, the same iterator determines what point is in use, by getting the current point from the arrayList of points created in the initialization phase of the game. This way makes it easy to keep track of each of the players’ progress in the game.
9
4.3
4.3
Testing
4
VECTORRACE
Testing
Figure 2 shows four different cases of the first few moments of the game, with various map sizes and various numbers of players:
(a) Mapsize:30x30 1 player
(b) Mapsize: 20x20 2 players
(c) Mapsize: 80x80 3 players
(d) Mapsize: 50x50 4 players
Figure 2: Various tests
10
4.4
Comments and discussion
4
VECTORRACE
Here is a test of a run of the game where a user ran straight in to the wall, it shows how the game handles the issue of players ”dying”. And game over: Welcome to VectorRace Choose a map you would like to play: No.1 -Simple square map 1 What should the size of the map be? (10-20-30-50-80-100) 20 How many players are you? (1-4) 1 Player 1, where do you want to move? 6 Player 1, where do you want to move? 6 Player 1, where do you want to move? 6 Player 1, where do you want to move? 6 Player 1, where do you want to move? 6 Player 1 has crashed! All players have died; Game Over
4.4
Comments and discussion
The game has, as it is now, a lot of good things going for it. Many of the possible functionalities have been implemented, and the game is decently playable as a small quick match between friends on a single computer. The challenge is by far the most advanced one that we have been confronted with so far, and has orders of magnitude more room for creativity than anything we have done up until now. A lot of work went in to this, and there is still fantastic room for improvement. It has been interesting to work on, although we regret not having fulfilled our creative vision for the game to a greater extent. We did not have time to implement a win-state, so that will have to be managed by the players themselves. We did, however, have an idea in mind for how to manage the winning of the game: By using checkpoints along the way to the goal; each checkpoint (including the finish line) would trigger a boolean value to become true for the player in question, and the first player to have all boolean values ’true’ would have won. There are many ways to manage the win-state, but this is how we would have done it, given the time.
11
4.4
Comments and discussion
4.4.1
4
VECTORRACE
Implemented features
• Drawing a map • Basic moving around on the grid, with colored lines • Collision with walls (explicit lose-state) • Multiplayer support • Crossing the finishing line (explicit win-state) • More, different maps for added challenge • Artificial Intelligence - Playing single player against the computer. • Streamlined and user friendly user interface
12
5
5
CONCLUSION
Conclusion
All in all the assignments were solved, and the code was written to the best of our ability. We found the assignments more challenging this time, and look forward to the next challenge. We hope that the solutions have been satisfactory, and the reading interesting. Thank you for reading.
13