Java array counters - java

I am practicing using The new Boston tutorials, however there is one program that I don't fully understand. The program is designed to count the frequency of a number occuring in each dice roll and storing the results in an array. The line I have trouble with is ++freq[1+newDice.nextInt(6)]. I understand [1+newDice.nextInt(6)]; however how does the array know to increment each index by one each time the number occurs?
Random newDice = new Random ();
int freq[] = new int [7];
for(int i = 1; i<= 1000; i++)
{
++freq[1+newDice.nextInt(6)];
}
System.out.println("Dice Number\tFrequency");
for(int i = 1; i< freq.length; i++)
{
System.out.println(i+"\t\t"+freq[i]);
}

It is incrementing the value stored at that position in the array. It is not incrementing the array index.
It is equivalent to:
int index = 1+newDice.nextInt(6);
int f = freq[index];
++f;
freq[index] = f;

Related

Fill array with zero in random places

So, what I am trying to do is to fill a 2D array with zeros in random places a specific amount of times. Let's say that it has to be 20 zeros in an array of 90 places. What I have done so far is to declare a 2D array and fill it with random numbers. And my next thought was to simply choose random positions and replace them with zeros. Any idea how I could do that?
int[][] myboard = new int[9][9];
for (int i = 0; i < myboard.length; i++) {
for (int j = 0; j < myboard[i].length; j++) {
myboard[i][j] = (int) (Math.random() * 10);
}
}
It is a rather simple way to achieve the goal, but it should do the job. So you need to get the length of each row. After you have done that you can call a function that will give you a random number between some start point and the length of the row. Here is some code sample to show you what I mean:
import java.util.concurrent.ThreadLocalRandom;
import java.util.Arrays;
public class Example {
public static void main(String []args) {
int[][] myboard = new int[9][9];
for (int i = 0; i < myboard.length; i++) {
for (int j = 0; j < myboard[i].length; j++) {
// fill the row with random vals
myboard[i][j] = GetRandomNumber(0, myboard[i].length);
}
// sneak as much zeros as your heart content
int random = GetRandomNumber(0, myboard[i].length);
myboard[i][random] = 0;
}
System.out.println(Arrays.deepToString(myboard));
}
private static int GetRandomNumber(int min, int max) {
/*
min is the start point
max is the curr row len
*/
return ThreadLocalRandom.current().nextInt(min, max);
}
}
A pseudo code would look like:
while (num_zeros_filled < 20):
row = random()%total_rows
col = random()%total_cols
if (arr[row][col] == 0): # already filled in with 0
continue
else:
arr[row][col] = 0
num_zeros_filled += 1
This, however, could take infinite time theoretically if only those cells are generated which have already been filled with 0. A better approach would be to map the two-dimensional array into a 1-d array, and then sample out only from those cells which haven't been filled with 0 yet.

eliminating repeated random numbers [duplicate]

This question already has answers here:
How can I prevent the overlapping random numbers
(8 answers)
Closed 2 years ago.
I need to get the numbers 0-11 in a random order and make sure each number is only gotten once. It is still sending same numbers into my Line2 class though. How do I make sure that the int variable lineChoice is completely different every time?
My problem is the if/else is not properly making sure that I don't send an already selected lineChoice to my Line2 class.
for(int i = 0; i < 12; i++){
//get a random line choice 0-11
lineChoice = (int)(Math.random() * 11); //0-11;
//if that number was already chosen
//get a new random number and add it to the array
if(randomNumbers.contains(lineChoice)){
lineChoice = (int)(Math.random() * 11); //0-11;
randomNumbers.add(lineChoice);
}else{
//if not already in array, add to array
randomNumbers.add(lineChoice);
}
//make a Line based on the random lineChoice number
line = new Line2(lineChoice);
//add the line to the string poem
poem += "\n" + line + "\n\n\n";
}
You can create a List of Int from 1 to 11, and then randomize it.
List<Integer> ints = IntStream.range(1,12).boxed().collect(Collectors.toList());
Collections.shuffle(ints);
System.out.println(ints);
Here is the recommended way of doing it.
int [] nums = {0,1,2,3,4,5,6,7,8,9,10,11};
for (int i = nums.length-1; i >= 0; i--) {
int s = (int)(Math.random()*(i+1));
System.out.println(nums[s]); // here is where you get your number
nums[s] = nums[i];
}
or if you just want to shuffle the array.
for (int i = nums.length-1; i >= 0; i--) {
int s = (int)(Math.random()*(i+1));
int t = nums[s];
nums[s] = nums[i];
nums[i] = t;
}
You need an array to do so,
Follow the following code, you just need to generate 11 (out of 12) random numbers in total. The last number will be selected automatically.
int[] rn = new int[12];
for(int i=0; i<12; i++) rn[i]=i; // 0 to 11
Random rNumber = new Random();
int t, z;
for(int i=11; i>0; i--) {
z = rNumber.nextInt(i+1);
t = rn[i];
rn[i] = rn[z];
rn[z] = t;
}
System.out.println(Arrays.toString(rn));

How to return the largest integer in an Array that has 10 random integers in it?

So this is a coding question from school I have, I don't want to say "hey guys do my homework for me!", I actually want to understand what's going on here. We just started on arrays and they kind of confuse me so I'm looking for some help.
Here's the complete question:
Write a program in which the main method creates an array with
10 slots of type int. Assign to each slot a randomly-generated
integer. Call a function, passing it the array. The called
function should RETURN the largest integer in the array to
your main method. Your main method should display the number
returned. Use a Random object to generate integers. Create it
with
Random r = new Random(7);
Generate a random integer with
x = r.nextInt();
So, here's what I have so far:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
int x = r.nextInt();
for (int i = 0; i < count.length; i++)
{
count[i] = x;
}
}
I created that array with 10 ints, then used a for loop to assign each slot that randomly generated integer.
I'm having a hard time for what to do next, though. I'm not sure what kind of method / function to create and then how to go from there to get the largest int and return it.
Any help is really appreciated because I really want to understand what's going on here. Thank you!
Here is how to generate Random ints
public static void main(String[] args) {
int []count = new int[10];
Random r = new Random(7);
int x=0;
for (int i = 0; i < count.length; i++)
{
x = r.nextInt();
count[i] = x;
}
System.out.println("Max Number :"+maxNumber(count));}//Getting Max Number
Here is how to make method and get max number from list.
static int maxNumber(int[] mArray){//Passing int array as parameter
int max=mArray[0];
for(int i=0;i<mArray.length;i++){
if(max<mArray[i]){//Calculating max Number
max=mArray[i];
}
}
return max;//Return Max Number.
}
Ask if anything is not clear.
This is how we make method which return int.
You can do it by using a simple for loop for the Array.
First you have to create a seperate int variable (eg: int a) and assign value zero (0) and at each of the iterations of your loop you have to compare the array item with the variable a. Just like this
a < count[i]
and if it's true you have to assign the count[i] value to the variable a . And this loop will continue until the Array's last index and you will have your largest number in the a variabe. so simply SYSOUT the a variable
Important: I didn't post the code here because I want you to understand the concept because If you understand it then you can solve any of these problems in future by your self .
Hope this helps
What you have got so far is almost correct, but you currently are using the same random number in each iteration of your for-loop. Even though you need to get a new random number for each iteration of your for-loop. This is due to how the Random object is defined. You can achieve this by changing your code the following way:
import java.util.Random;
public class Q1 {
public static void main(String[] args) {
Random r = new Random(7);
int[] count = new int[11];
for (int i = 0; i < count.length; i++)
{
int x = r.nextInt(); // You need to generate a new random variable each time
count[i] = x;
}
}
Note that this code is not optimal but it is the smallest change from the code you already have.
To get the largest number from the array, you will need to write another for-loop and then compare each value in the array to the largest value so far. You could do this the following way:
int largest = 0; // Assuming all values in the array are positive.
for (int i = 0; i < count.length; i++)
{
if(largest < count[i]) { // Compare whether the current value is larger than the largest value so far
largest = count[i]; // The current value is larger than any value we have seen so far,
// we therefore set our largest variable to the largest value in the array (that we currently know of)
}
}
Of course this is also not optimal and both things could be done in the same for-loop. But this should be easier to understand.
Your code should be something like this. read the comments to understand it
public class Assignment {
public static int findMax(int[] arr) { // Defiine a function to find the largest integer in the array
int max = arr[0]; // Assume first element is the largest element in the array
for (int counter = 1; counter < arr.length; counter++) // Iterate through the array
{
if (arr[counter] > max) // if element is larger than my previous found max
{
max = arr[counter]; // then save the element as max
}
}
return max; // return the maximum value at the end of the array
}
public static void main(String[] args) {
int numberofslots =10;
int[] myIntArray = new int[numberofslots]; // creates an array with 10 slots of type int
Random r = new Random(7);
for (int i = 0; i < myIntArray.length; i++) // Iterate through the array 10 times
{
int x = r.nextInt();
myIntArray[i] = x; // Generate random number and add it as the i th element of the array.
}
int result = findMax(myIntArray); // calling the function for finding the largest value
System.out.println(result); // display the largest value
}
}
Hope you could understand the code by reading comments..
This can be done in one simple for loop no need to have 2 loops
public static void main(String[] args) {
Integer[] randomArray = new Integer[10];
randomArray[0] = (int)(Math.random()*100);
int largestNum = randomArray[0];
for(int i=1; i<10 ;i++){
randomArray[i] = (int)(Math.random()*100);
if(randomArray[i]>largestNum){
largestNum = randomArray[i];
}
}
System.out.println(Arrays.asList(randomArray));
System.out.println("Largest Number :: "+largestNum);
}
Initialize max value as array's first value. Then iterate array using a for loop and check array current value with max value.
OR you can sort the array and return. Good luck!
Here's a basic method that does the same task you wish to accomplish. Left it out of the main method so there was still some challenge left :)
public int largestValue(){
int largestNum;
int[] nums = new int[10];
for (int n = 0; n < nums.length; n++){
int x = (int) (Math.random() * 7);
nums[n] = x;
largestNum = nums[0];
if (largestNum < nums[n]){
largestNum = nums[n];
}
}
return largestNum;
}

Generation of 4 non repeating random numbers using arrays in java

I have this array
int [] marc = new int[4];
i need to insert a set of non repeating random numbers in the range of 1-10 to it
i'm using this for loop to set random numbers
for (he = 0; he < 4; he++) {
marc[he] = rn.nextInt(10 - 1 + 1) + 1;
marc[he]++;
}
it gives me random numbers but repeated ones inside the array
i'm also using
java.util.Random;
Well, yes, numbers can be repeated while being random. You need to do your own logic to validate if they're already on the array, this can be done with the following code:
In the code I used an array of 10 elements to observe there aren't repeated numbers even on that situation.
import java.util.Random;
public class RandomNumbersNoRepeating {
public static void main(String[] args) {
int array[] = new int[10];
Random random = new Random();
//Fills the array
for (int i = 0; i < array.length; i++) {
boolean found = false;
int r = 0;
do {
found = false;
r = random.nextInt(10) + 1;
//Here we check if the number is not on the array yet
for (int j = 0; j < array.length; j++) {
if (array[j] == r) {
found = true;
break;
}
}
} while (found);
array[i] = r;
}
//Prints the array
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}
Another possible solution, as given in a comment could be to shuffle an array from 1-10, and get the first four numbers
Using java.util.Random; will generate repetitive numbers more often when your range is small, which in your case is only 10. There is no condition in your code that checks whether the generated random number already exists in your array or not.
Before inserting a generated number in to the array, you first need to check whether that number already exists in your array. If it does not, you insert that number in the array, otherwise you generate a next random number.

How can I program multistage random in Java or Android?

How can I program multistage random?
An example: I have 3 int: "1;2;3"
After the first round there are only 2 left. For example: "2;3"
And in the last round remain number "3".
All this happened randomly.
How can I program this in Java?
Have an ArrayList or Set of the int. Use Random.nextInt() to get a random index that is less than the size of the collection and then access it and remove it. This way no two numbers will repeat.You can use this for int or anything you want. Another idea is to use Collections.shuffle.
More info: Picking a random element from a set
You will probably want to store the integers in an array. You can then remove the numbers using a random integer as index for the array. Example:
Random rnd = new Random();
int numOfInputs = 3;
int[] listOfNums = new int[]{1,2,3};
int removeIndex = 0;
for(int r = 0; r < numOfInputs; r++) {
removeIndex = rnd.nextInt(numOfInputs);
listOfNums[removeIndex] = 0;
// Print the list
for(int p = 0; p < numOfInputs; p++) {
if(listOfNums[p] > 0) {
System.out.print(listOfNums[p] + ";");
}
}
}

Categories

Resources