I received the task of simulating a lottery draw in java. The program skeleton yields the method generateOneDraw, which creates 6 random numbers between 1 and 49
static int[] generateOneDraw() {
int numbers[] = new int[NUMBER_OF_ELEMENT_PER_DRAW];
for(int i=0; i<numbers.length; ++i) {
int nextNumber;
do {
nextNumber = generateNextRandomNumber();
} while(numberIsInArray(nextNumber, numbers));
numbers[i] = nextNumber;
}
return numbers;
}
We are then required to implement a function that simulates the lottery draw over 5 weeks and stores them in the variable draws. I believe this should be done over a two-dimensional array. Am I right in this way of thinking? Any pointers on implementing it would be greatly appreciated.
static void generateAllDraws()
Thanks in advance.
EDIT: Nevermind, I did it with a simple two dimensional array and it worked.
Since this seems like home work, I will not go into much detail but you can either:
Create a 2 dimensional list, as per your initial reasoning;
Create a Draw class which represents a lotto draw, and create multiple instances of this class. Each Draw class could have a Date which would denote when did the draw take place.
Both approaches should work, the second approach is a little more object oriented.
Related
I'm using an example Turtle project from BlueJ to trace out polygons. I already have a method that would sketch a polygon after providing it with the number of sides and length of the sides. Now, I would like to call upon that method a specific number of times such that I can specify, for example, that I would like to create 3 polygons, then provide the above parameters for each polygon, then have it proceed to sketch it out.
My method for sketching out a polygon is as follows:
public void drawPolygon(int numberOfSides, int lengthOfSide, Color penColor){
world.dropIn(fred);
fred.setColor(penColor);
fred.penUp();
fred.left(90);
fred.forward(200);
fred.right(90);
fred.penDown();
for(int i=0; i<numberOfSides; i++) {
fred.right( 360 / numberOfSides );
fred.forward(lengthOfSide);
}
world.removeTurtle(fred);
FYI: fred is the name of my turtle and the Color related lines are for changing the color of the pen fred is using.
I've tried writing the following:
public void drawPolygons(int numberOfPolygons){
for(int i=0; i<numberOfPolygons; i++){
drawPolygon(int numberOfSides, int lengthOfSide, Color penColor);
}
}
But I get a variety of errors. Is it possible to call a method with parameters within another method with parameters or am I barking mad?
I'm sorry if this is too basic a question for Stackoverflow, I'm completely new to programming and any help would be much appreciated!
Is it possible to call a method with parameters within another method with parameters...
Yes, this is a common paradigm. You just need to fix your invocation of drawPolygon:
public void drawPolygons(int numberOfPolygons){
for(int i=0; i<numberOfPolygons; i++){
drawPolygon(numberOfSides, lengthOfSide, penColor);
}
}
I want to make a program that each semester, creates a schedule depending of a list of classes I input, so if I add various classes, depending of the time and days that these classes will happen then the program would be able to match what classes can be added without intercepting each other. I want to know if there is an algorithms or way of comparing the class schedule in order to determine what classes can I have from the list of courses.
The only way of doing these that I can imagine is with many if statements or adding an starting course and then having an array that tracks the hours, starting each position at 0 and then each time an hour is occupied I change the array position to 1. Then when adding a course I check what positions are different to 1 and try to add the class.
I want to find a more optimal solution to this problem than the ones I can imagine.
This is a planning problem. Planning problem are very difficult to solve in a efficient way: performance issues arise very quickly in this kind of problem.
If you just want to solve the problem, you should check an existing planning problem solver like OptaPlanner: it's open source, so you can try to understand how it work and there is a blog with interresting thoughts about planning problem.
If you're wanting a method where, given a group of classes with their times and a chosen class, output the available classes, you can use simple iteration to do the job. Suppose you have a 5 hour slot with 4 classes you could represent each class with a single array:
int[][] times = {
{0,1,1,0,0},
{1,1,0,0,0},
{0,1,0,0,0},
{0,0,0,1,1}
};
So if you were to choose the class taking up the last 2hrs then the remaining options would be:
{0,1,1,0,0},
{1,1,0,0,0},
{0,1,0,0,0}
Given this representation you could do something like:
import java.util.*;
public class C {
static int[][] available(int[] c,int[][] times){
ArrayList<Integer> index = new ArrayList<>();
ArrayList<Integer> result = new ArrayList<>();
for(int i=0;i<c.length;i++)
if(c[i]==1) index.add(i);
for(int i = 0; i < times.length; i++){
if(!times[i].equals(c)) {
for (int j = 0; j < times[0].length; j++) {
if(times[i][j]==1){
if(index.contains(j)) break;
}
if(j==times[0].length-1) result.add(i);
}
}
}
int[][] r = new int[result.size()][c.length];
for(int i=0;i<result.size();i++){
r[i] = times[result.get(i)];
}
return r;
}
public static void main(String[] args) {
int[][] times = {
{0,1,1,0,0},
{1,1,0,0,0},
{0,1,0,0,0},
{0,0,0,1,1}
};
int[] c = {0,0,0,1,1};
available(c,times);
System.out.println(Arrays.deepToString(available(c,times)));
}
}
I'm new to Java and I am having trouble wrapping my mind around one of the concepts.
The assignment I am currently working on is the card game War. The current instructions is for me to remove a random card from a a deck of cards.
I have created an array, but it is an array of class Card. The class creates the card by basically adding an int and a String together. I then created the array from that class. In my mind, I neither have an int or a String in my array, is that correct?
Now I need to remove one of the random cards from the deck and give it to a player. This is where I am getting lost. I would think I can just use Random to remove a random card, but I always seem to get an error.
I'm not asking for you to do the assignment for me, but if you would please point me in the right direction and possibly correct me if I am confused.
Current Class I am working on:
import java.util.Random;
import java.util.*;
public class War3
{
Random ran = new Random();
public FullDeck randomCard()
{
ArrayList <FullDeck> randCard = new ArrayList <FullDeck> (52);
int index = ran.nextInt(randCard.size());
FullDeck x = randCard.remove(index);
return x;
}
public void display()
{
System.out.println("Your card is" + randomCard());
}
}
Entire project for clarification Java - War Game - Gist
Many thanks in advance.
ArrayList <FullDeck> randCard = new ArrayList <FullDeck> (52);
This creates an ArrayList. You do not need to specify the number 52, since ArrayLists grow dynamically, as opposed to Arrays. The call is similar to
ArrayList <FullDeck> randCard = new ArrayList <FullDeck> ();, the difference being that the constructor you used sets the initial capacity of the ArrayList to 52. That in no way restricts the size of the ArrayList though.
Anyway, you are creating a new, empty ArrayList. Then you want the size, but since you didn't put anything into the list, it is still empty, to the size is zero. You then try to call ran.nextInt(0)... nextInt(int n) expects a number greater than zero. From the javadoc:
public int nextInt(int n) {
if (n <= 0)
throw new IllegalArgumentException("n must be positive");
Two issues that I see:
You're creating an ArrayList that can hold a reference to 52 instances of the FullDeck class, but you're not adding anything to it. You need to do something like randCard.add(new FullDeck()) 52 times/in a loop**. Then likely you'll want to "shuffle" the deck, see this question for how to do that.
You're naming is a little weird...the FullDeck class in actuality seems like it should be renamed to just Card, and the randCard variable should be renamed to something like fullDeck...after you've added 52 Cards.
**EDIT: actually, the generation of a deck of cards will be more complicated to make sure you don't have any duplicate cards.
Hello I am trying to create a method in Java that Accepts an integer from the user. Calculate and display how many occurences of the integer are in the array(i'm Creating a random array) as well as what percentage of the array values is the entered integer.
This is how i create my Array:
public void fillVector ( )
{
int myarray[] = new int [10];
for (int i = 0 ; i < 10 ; i++)
{
myarray [i] = (int) (Math.random () * 10);
}
}
Any sugestions how can i do to accomplish this ?
This seems like a homework to you so I am not gonna give you the full solution but I will break down the steps of what you need to do in order to solve your problem. You have to find out how to code those steps yourself, or at least provide some code and your specific problem because your question is too vague right now.
Ask the user to input the number.
Store that number somewhere.
Check each cell of the array for that number. If you find one appearance
increase the counter and continue until the end of your index.
Print out the appearances of the given number.
Print out the percentage of the cells containing the given value to the total amount of cells.
As I can see from your code (if it's yours) you are capable to pull this off on your own. It shouldn't be too hard.
I created two methods for my Bingo Game in Java. One method creates a new board which populates the Bingo Board with integers according to the Bingo rule (1-75). My second method generates random numbers with a range of 1 - 75.
public static int drawNum(){
Random rand = new Random();
int num = rand.nextInt(75)+1;
return num;
}
public static void bingoCard(){
int [][]card=new int [5][5];
ArrayList<Integer> alreadyUsed = new ArrayList<Integer>();
boolean valid = false;
int tmp = 0;
for(int i = 0; i <= 4; i++){
for(int row = 0; row < card.length; row++){
while(!valid){
tmp = (int)(Math.random() * 15) + 1 + 15 * i;
if(!alreadyUsed.contains(tmp)){
valid = true;
alreadyUsed.add(tmp);
}
}
card[row][i] = tmp;
valid = false;
}
}
card[2][2] = 0;
//create array to make title.
String title []={"B","I","N","G","O"};
for(int i=0;i<title.length;i++){
System.out.print(title[i]+ "\t");
}
System.out.println();
for(int row=0;row<card.length;row++){
for(int col=0;col<card[row].length;col++){
System.out.print(card[row][col]+ "\t");
}
System.out.println();
}
}
What I need help with is, how do I check whether or not the drawNum() method corresponds to any values stored inside my bingoCard() array? If so, print out a new array with the integers filled in. If the condition is met for a bingo, then you win.
I hope I don't make it sound like I want you to do it for me, but I am confused as to how to start coding that part. Thank you.
This my recommendation - Learn Object Oriented Programming immediately
I see you are using objects provided in the JDK, so why not learn to make your own?
Make two classes with the following methods (-) and members (+) (PS. This is not a formal way to document code)
BingoCard
+list of numbers on card
-reset() : gets new numbers for this card
-test(BingoDrawer) : Tests to see if this card won on this drawing
-toString() : returns a String representation of this card
BingoDrawer
+list of numbers drawn
-reset() : draws new numbers
-hasNumber(int number) : tests if this number was drawn
-toString() : returns a String representation of this drawing
One more suggestions
Instead of keeping track of what you used, keep track of what you have not used, it will make things much easier because you can just choose stuff from that list randomly. Unlike your current action which is choosing (a logical number) from thin air and hoping (which causes issues) it is not a collision
If you follow my recommendation you can write code like this
public static void main(String[] args) {
BingoCard bc = new BingoCard();
BingoDrawer bd = new BingoDrawer();
while(thePlayerWantsToPlay()) { //function to be defined by you
bc.reset();
bd.reset();
System.out.println(bc);
System.out.println(bd);
System.out.println(bc.test(bd));
}
}
You can take it a step further and make a BingoGame class and do what I did in main there and just create an instance of BingoGame and call some start method on the object.
For checking if you have the number in your board, read through the board in a similar manner as you do for the already_used numbers, except with the number the user just entered.
The conditions for the user to win should be checked after the board has another number guessed.
There are a few ways to do this, a simple one would be to iterate over every possible pattern that could win, checking to see if there are tokens there.
All of this would be in a loop, that goes a little like this:
Set up board via user entering numbers.
Start loop
set either a timer to wait for, or wait for a keypress (so the game doesn't just play really fast)
Get random number
Possibly add to board
Check if winner
if winner, break the loop and do something else.
Print the new board out.
(end of loop)
If they got here, that could mean they won!
Wait to exit
You can just write it out as pseudo-code and fill in the methods after that. It usually helps to work on these things in a top-down fashion. So, for bingo you might have:
board = generateBoard();
while (!bingoFound(board)) {
number = drawNumber();
board = stampNumbers(board, number);
}
If that makes sense, you can go a step deeper and define each method. For example, bingoFound might look like:
public boolean bingoFound(int[][] board) {
boolean wasFound = bingoRowFound(board)
|| bingoColFound(board)
|| bingoDiagonalFound(board);
return wasFound;
}
Again, I've defined everything in (mostly) pseudo-code. If this looks ok, you can move a step deeper. Let's define the bingoRowFound method.
public boolean bingoRowFound(int[][] board) {
for (int row = 0; row < NUM_ROWS; row++) {
boolean rowIsABingo = true;
for (int col = 0; col < NUM_COLS; col++) {
// We have to check that everything up until this point has
// been marked off. I am using -1 to indicate that a spot has
// been marked.
rowIsABingo = rowIsABingo && board[row][col] == -1;
}
if (rowIsABingo) { return rowIsABingo; }
}
return false; // If we didn't find a bingo, return false.
}
Some of the methods (like drawNumber) will be really easy to implement. Others, like looking for a diagonal bingo might be a bit more difficult.
Feb 12 2014 Update:
Retracted code, since this was a college course assignment, and I want to prevent people just copying the code. I almost got in trouble for being accused of sharing code (which is a nono in assignments) when another student lifted my code from my Github repo and sent it in as their own.
There were two classes, one main class and a class to hold my methods and constructors.
BINGOFINAL.java was my main class.
Bingo_Card.java held my constructor and methods.
If you want to run this, make sure you create a new project called BINGOFINAL, and put Bingo_Card.java into that same */src/ extension.