J2ME - Storing ints in an array or similar - arrays

I am currently writing an app for a card game in j2me, I have used random number generator to create 5 random ints that will be stored in an array or similar to represent the players hand of cards (as each number represents a corresponding card in the pack)
At the moment, the following card creates the random numbers
int n = 0;
Random r = new Random();
while(n<5) {
int i = r.nextInt(52);
System.out.println( i);
n++;
I have tried to use a vector to store the 5 i values but I could not get this working, I was hoping for any suggestions of what I should consider using for storing i which will be accessible during gameplay.
Thanks Guys! :-) x

I dont see why you cant use Vector to store the values.
try this..
int n = 0;
**Vector<int> name = new Vector<int>();**
Random r = new Random();
while(n<5) {
int i = r.nextInt(52);
System.out.println( i);
**name.set(i, n);**
n++;
}
if this code was in a method, you can pass in the vector as a reference, so you can store the values.

Related

how can i make two equal random numbers in c

I'm new to coding and i need help with my project: so, what i need to do is code a "finding the two same cards game", in which every card has a number and we're basically trying to find that two equal numbers. those numbers should be generated with rand() function but i cannot think a way to how to make two random numbers equal to each other if I'm using the rand() function. i don't know if i worded this the best way but i hope you get what i mean and if you don't I'm open to explain it with an example.
thanx in advance!
Just create half as many elements and duplicate them. You can actually take consecutive numbers and shuffle them. This way you make sure every number is repeated exactly once:
int main()
{
enum { size = 10 };
int cards[size];
for (int i = 0; i != size / 2; ++i)
{
cards[i] = i;
cards[size/2 + i] = i;
}
// now shuffle the array
}

How would I convert the data type int[] to the data type int

I have set up an array to randomize 5 different numbers in one class. In a different class I have prompted a user to guess the random number, and must reference the number each time to determine whether they have guessed correctly or not. My issue is that the numbers being randomized are in the data type int[], and I need to compare them to the data type int. When trying to reference the randomized numbers I get the error "Type mismatch: cannot convert from int[] to int". Any advice on how I would do that?
Class diceNumGen
final static int ARRAY_SIZE = 5;
public static int[] randNumArray = new int [ARRAY_SIZE];
public static int[] randNums(){
for(int i=0; i < randNumArray.length; i++) {
randNumArray[i] = (int) (Math.random()*12);
System.out.println(randNumArray);
}
return randNumArray.clone();
}}
Class Bet
static Bet bet = new Bet();
diceNumGen newClassObj = new diceNumGen();
int secondArray = diceNumGen.randNumArray;
//Set Turns variable where turns = 5
public int turnsToGo = 5;
//Set up the bet() method
public void bet() {
//Sets up the options as an array to be on the JOptionPane, each are numbered 0, 1, and 2 respectively
String[] options = {"Guess below 7", "Guess 7", "Guess above 7"};
welcome here, I'm newcomer too, this is my first answer.
I assume that you are using java, because of keywords, it is good to define the programming language in the question or tags to get better responses.
the first thing about your code is you don't need a whole class for generating an array, an ordinary function like this would be OK too:
static int[] randomGen(int len){
java.util.Random rand = new java.util.Random();
int[] randoms = new int[len];
for (int i = 0; i < len; i++) {
randoms[i] = rand.nextInt(12);
}
return randoms;
}
the next thing is, please indent your code, un-indented code (or badly indented code) will confuse the reader.
and about your question, at the first point why are you creating random array with the size of 5? if you just need one random number, just create one random number (with your Math.random() or better, nextInt(12) in Random class)
if user have 5 chances to guess same number you don't need 5 random numbers. just use this:
int randomNumber = (int) (Math.random() * 12);
or if you want user to guess 5 separate numbers, you need a for loop to iterate this random array per user guess.
Good luck in learning java.

Create a Stream using Scanner

This is usually how I accept an Array from a user. I ask for the size, then loop and populate the Array.
Scanner scan = new Scanner(System.in);
int N = scan.nextInt();
int[] numbers = new int[N];
for (int n=0; n<N; n++){
numbers[n] = scan.nextInt();
}
I have been trying to learn java 8 and I noticed that the Random class has a method now to create a stream. It is pretty easy now to declare a n-sized array with random numbers.
int[] randomNumbers = new Random().ints().limit(N).toArray();
What I have been trying to do is create an array doing something similar with either streams or lambda expressions but for user input. What I tried doing is creating an IntStream, map the values to Scanner#nextInt, then create an array.
int[] numbers = new IntStream().map(x -> scan.nextInt()).limit(N).toArray();
What I can do is something like this:
int[] numbers = new int[N];
Arrays.fill(numbers, 0);
numbers = Arrays.stream(numbers).map(x -> scan.nextInt()).toArray();
System.out.println(Arrays.toString(numbers));
But that still feels a bit redundant. Filling the array with some arbitrary number only to replace it in the next line.
Due to the way, the current implementation handles limit(…)s, it’s more efficient to create a stream using:
IntStream.range(0, N).map(i -> scan.nextInt())
which will be more efficient when using toArray() as well as for parallel processing despite creating an otherwise unused value with the range operation. Further, this creates an ordered stream which maintains the element order.
So when using,
int[] numbers = IntStream.range(0, N).map(i -> scan.nextInt()).toArray();
it benefits from knowing the array size in advance.
Use IntStream.generate:
int[] numbers = IntStream.generate(() -> scan.nextInt()).limit(N).toArray();
As mentionned in the comments, this generates an unordered stream. If you want it to be ordered, you can use:
IntStream.range(0, N).map(i -> scan.nextInt()).toArray();

Generate random numbers without repeats

I want to generate random numbers without repeats till all gone, then again generating random numbers with the initial dataset.
I know keeping already generated numbers in an array and loopin through them to check whether it is alredy generated or the method deducting the numbers that are generated from the array and randomize numbers with the new array.
What I want is not those methods, if there is a way that is efficient using data structures will be quite nice, if it is any other method also ok
Thanks
Say you want to generate 1,000 unique random numbers and present them to some code one at a time. When you exhaust those numbers, you want to present the same numbers again, but in a different sequence.
To generate the numbers, use a hash table. In C#, it would look like this:
const int MaxNumbers = 1000;
HashSet<int> uniqueNumbers = new HashSet<int>();
Random rnd = new Random();
// generate random numbers until there are 1000 in the hash table
while (uniqueNumbers.Count < MaxNumbers)
{
uniqueNumbers.Add(rnd.Next());
}
// At this point you have 1,000 unique random numbers
// Put them in an array
int[] myNumbers = uniqueNumbers.ToArray();
This works because the HashSet.Add method rejects duplicates. And it's very fast because lookup in the hash table is O(1).
Now, you can serve them by setting a current index at 0 and increment it every time a number is requested. Something like:
int ixCurrent = 0;
int GetNextNumber()
{
if (ixCurrent < MaxNumbers)
{
++ixCurrent;
return myNumbers[ixCurrent-1];
}
But what to do when ixCurrent runs off the end of the array? Enter the Fisher-Yates Shuffle:
// out of numbers. Shuffle the array and return the first one.
for (int i = MaxNumbers-1; i > 0; --i)
{
int j = rnd.Next(i+1);
int temp = myNumbers[i];
myNumbers[i] = myNumbers[j];
myNumbers[j] = temp;
}
ixCurrent = 1;
return myNumbers[0];
}
If you know that the numbers you want to return are within a particular range (that is, you want to return the numbers 0-999 in random order), then you just fill an array with the values 0-999 and shuffle it.
I'm not sure what language you are using, but here's some C++ code that does what you're looking for. Instead of it searching an array, it just does a direct check of a specific section of memory for a set flag and if it isn't set then the number chosen is new and printed.
The section I marked as handler is the code that is first executed when a unique number is found. Change the 10's and the 11 to different numbers if you want a larger set of random numbers but you might have to wait forever for the output.
int main(int argc, char *argv[]){
char randn[10];
char randnset[10];
int n;
int ct=0;
memset(randnset,'1',10);
memset(randn,0,10);
while (ct < 10){
srand(time(NULL));
n=rand() % 11;
if (!randn[n]){
printf("%d\n",n); // handler
randn[n]='1';
ct++;
}
}
return 0;
}
Every random generator function takes a seed value as a parameter and uses it in its internal algorithm to generate random numbers. If you want to generate the same sequence of numbers, you have to use the same seed value. As an example you can achieve this in Java like this:
int seed = 10;
Random r = new Random(seed);
for(int i=0; i<10; i++){
System.out.println(r.nextInt());
}
The output is something like this (of course it will have different results in your system):
-1157793070
1913984760
1107254586
1773446580
254270492
-1408064384
1048475594
1581279777
-778209333
1532292428
and it gives me the same results each time I execute it.

How to get N unique random quantities without indefinite loop?

I want to generate 5 random positions on a map. I can only come up with the code below, which uses while (1) and break:
int map[10][10];
memset(map,0,sizeof(map));
for (int i = 0; i < 5; i++) {
while (1) {
int x = RAND_FROM_TO(0, 10);
int y = RAND_FROM_TO(0, 10);
if (map[x][y]==0) {
map[x][y]=1;
break;
}
}
}
Is there any other way to do the same job without while(1), because I have been told the while(1) is very bad.
I just want to find a simple way to do it, so the efficiency of the generating random numbers is not under my consideration.
You can use a shuffle algorithm such as Fisher–Yates. I would pose a modified (truncated) version as so:
Express your XY coordinates as a single number.
Construct a list of all coordinates.
Pick one at random, mark it.
Remove that coordinate from the list (swap it with the one at the end of the list, and treat the list as 1 element shorter)
repeat with the list that no longer contains the marked coordinate.
This way, rather than choosing 5 numbers from 0-99, you choose one 0-99, 0-98, ... 0-95, which guarantees that you can complete the task with exactly 5 choices.
EDIT: Upon further consideration, step 1 is not strictly necessary, and you could use this on a system with sparse coordinates if you did it that way.
What about something like this:
// Create an array of valid indexes for both x and y.
NSMutableArray *xCoords = [NSMutableArray array];
NSMutableArray *yCoords = [NSMutableArray array];
for (int i = 0; i < 9; ++i) {
[xCoords addObject:#(i)];
[yCoords addObject:#(i)];
}
int map[10][10];
memset(map, 0, sizeof(map));
for (int i = 0; i < 5; ++i) {
// Pick a random x coordinate from the valid x coordinate list.
int rand = RAND_FROM_TO(0, [xCoords count]);
int x = [xCoords objectAtIndex:rand];
// Now remove that coordinate so it cannot be picked again.
[xCoords removeObjectAtIndex:rand];
// Repeat for y.
rand = RAND_FROM_TO(0, [yCoords count]);
int y = [yCoords objectAtIndex:rand];
[yCoords removeObjectAtIndex:rand];
assert(map[x][y] == 0);
map[x][y] = 1;
}
Note: I'm using NSMutableArray because you originally specified Objective-C as a tag.
Note 2: An array of valid indexes is not the most efficient representation. Using NSMutableIndexSet instead is left as an exercise to the reader. As is using basic C primitives if you don't / can't use NSMutableArray.
Note 3: This has a bug where if you pick, say, x = 3 the first time, no further choices will end up with x = 3, even though there will be valid choices where x = 3 but y is different. Fixing that is also left as an exercise, but this does satisfy your requirements, on the surface.

Resources