How to generate 100 random 3 digit numbers in java? - java

I need to generate 100 random 3 digit numbers. I have figured out how to generate 1 3 digit number. How do I generate 100? Here's what I have so far...
import java.util.Random;
public class TheNumbers {
public static void main(String[] args) {
System.out.println("The following is a list of 100 random" +
" 3 digit numbers.");
Random rand= new Random();
int pick = rand.nextInt(900) + 100;
System.out.println(pick);
}
}

The basic concept is to use a for-next loop, in which you can repeat your calculation the required number of times...
You should take a look at The for Statement for more details
Random rnd = new Random(System.currentTimeMillis());
for (int index = 0; index < 100; index++) {
System.out.println(rnd.nextInt(900) + 100);
}
Now, this won't preclude generating duplicates. You could use a Set to ensure the uniqueness of the values...
Set<Integer> numbers = new HashSet<>(100);
while (numbers.size() < 100) {
numbers.add(rnd.nextInt(900) + 100);
}
for (Integer num : numbers) {
System.out.println(num);
}

If you adapt the following piece of code to your problem
for(int i= 100 ; i < 1000 ; i++) {
System.out.println("This line is printed 900 times.");
}
, it will do what you want.

Try for loop
for(int i=0;i<100;i++)
{
int pick = rand.nextInt(900) + 100;
System.out.println(pick);
}

Using the answer to the question Generating random numbers in a range with Java:
import java.util.Random;
public class TheNumbers {
public static void main(String[] args) {
System.out.println("The following is a list of 100 random 3 digit nums.");
Random rand = new Random();
for(int i = 1; i <= 100; i++) {
int randomNum = rand.nextInt((999 - 100) + 1) + 100;
System.out.println(randomNum);
}
}

This solution is an alternative if the 3-digit numbers include numbers that start with 0 (if for example you are generating PIN codes), such as 000, 011, 003 etc.
Set<String> codes = new HashSet<>(100);
Random rand = new Random();
while (codes.size() < 100)
{
StringBuilder code = new StringBuilder();
code.append(rand.nextInt(10));
code.append(rand.nextInt(10));
code.append(rand.nextInt(10));
codes.add(code.toString());
}
for (String code : codes)
{
System.out.println(code);
}

Related

How to produce the 10 random numbers and create stars to indicate the value [duplicate]

This question already has answers here:
Simple way to repeat a string
(32 answers)
Closed 2 years ago.
So the question for my assignment is "Produce a horizontal star line that show your 10 variables from top to bottom as individual, distinct stars varying based on its value. For example, random number is 4, so I will have ****.
This is what I did so far
import java.util.*;
public class Problem01 {
public static void main(String[] args){
//create random integer
Random ran = new Random();
for (int i = 1; i <=10; i++ ){
int random = ran.nextInt(20);
//Printing the random number
System.out.println("Number " + "(" + random + "): ");
}
}
}
I can generate 10 random number but I don't know how generate the stars, can you guys help me, thanks a lot.
private static String generateStars(final int numberOfStars) {
final StringBuilder sb = new StringBuilder(numberOfStars);
for (int i = 1; i <= n; i++) {
sb.append("*");
}
return sb.toString();
}
import java.util.*;
public class Problem01 {
public static void main(String[] args){
//create random integer
Random ran = new Random();
for (int i = 1; i <=10; i++ ){
int random = ran.nextInt(20);
//Printing the random number
System.out.println("Number " + "(" + random + "): ");
for(int j = 1; j <= random; j++)
{
System.out.print("*");
}
System.out.println();
}
}
}
Sample output
Number (0):
Number (6):
******
Number (8):
********
Number (18):
******************
Number (17):
*****************
Number (0):
Number (7):
*******
Number (10):
**********
Number (14):
**************
Number (8):
********

How to average random numbers in java?

thanks in advance for any help I'm in an intro to java class and our home work was to generate 10 random numbers between 1&50 which I got and then average the generated numbers. I can't figure out how to average them here's what I have. Is there a way to store each random number as a variable?
public class randomNumberGen
{
public static void main(String [] args)
{
Random r=new Random();
for (int i=1;i<=10;i++){
System.out.println(r.nextInt(50));
System.out.println();
int average = (i/4);
System.out.println("your average is"+average);
}
}
}
use streams with java 8
final int numberOfRandom = 10;
final int min = 0;
final int max = 50;
final Random random = new Random();
System.out.println("The ave is: "+random.ints(min, max).limit(numberOfRandom).average());
First of all you have to replace "r.nextInt(50)" for "r.nextInt(50) + 1" because r.nextInt(n) returns a number between 0 (inclusive) and n (exclusive). Then, you know that an average is just a sum of n values divided by n. What you can do is just declare a "total" variable initialized to 0 before the loop. On each iteration you add to this variable the random value generated by r.nextInt(50). After the loop you can just divide the total by 10 so you get the average.
PS: it's a good practice to don't use "magic numbers", so it would be perfect (and luckily your teacher will have it in count) if you declare a constant for the number of iterations and then use it both in the loop condition and in the average calculation. Like this, if you have to make it for 100 numbers you only have to change the constant value from 10 to 100 instead of replacing two 10's por two 100's. Also this gives you the chance to give semantic value to these numbers, because now they will be "AMOUNT_OF_NUMBERS = 10" instead of just "10".
Like every average, it's sum of elements / amount of elements. So let's apply it here:
import java.util.Random;
public class randomNumberGen
{
public static void main(String [] args)
{
Random r=new Random();
double sum = 0; // is double so to prevent int division later on
int amount = 10;
int upperBound = 50;
for (int i = 0; i < amount; i++){
int next = r.nextInt(upperBound) + 1; // creates a random int in [1,50]
System.out.println(next);
sum += next; // accumulate sum of all random numbers
}
System.out.println("Your average is: " + (sum/amount));
}
}
Store variables outside of the loop to store both the total amount of numbers generated as well as the sum of those numbers. After the loop completes, divide the sum by the total amount of numbers.
public static void main(String [] args)
{
Random r=new Random();
double sum = 0;
int totalNums;
for (totalNums=1;totalNums<=10;totalNums++){
int randomNum = r.nextInt(50);
sum += randomNum;
System.out.println(randomNum);
}
double average = sum/totalNums;
System.out.println("your average is: "+average);
}
Average = Sum of numbers / amount of numbers
int sum = 0;
for (int i=1;i<=10;i++){
sum += r.nextInt(50) +1; //nextInt 50 produces value 0 to 49 so you add 1 to get 1 to 50 OR as suggested in the comments sum/10d
}
System.out.println("Average is: " + sum/10) // If you want the result in double (with decimals) just write sum*1.0/10
You could also do the same with a while loop.
int i = 0;
int sum = 0;
while(i < 10){
sum += r.nextInt(50) +1;
i++;
}
System.out.println("Average is: " + sum*1.0/i);
Or even shorter with lambda expressions: (/java 8 streams)
OptionalDouble average = IntStream.range(1, 10).map(x-> x = r.nextInt(50) +1).average();
System.out.println("Average is "+ average.getAsDouble());
.map(x-> x = r.nextInt(50) +1) // maps (changes) each value from 1 to 10 to a random number between 1 and 50
.average(); // calculates the average.
Simply create a variable sum starting at zero that you increment at each iteration. After the loop, simply divide by the number of elements..
Average means you should add everything up and devide it by the number of elements (50).
import java.util.Random;
class Homework {
public static final Random RANDOM = Random(); // never regenerate randoms
public static void main(String args[]) {
final int N = 50;
int sum = 0;
for (int i = 0; i < N; ++i) {
sum += RANDOM.nextInt(50)+1;
}
System.out.println("Avg: "+ sum / (float) N);
}
}
This should do the trick. Try to learn from it not just C+P.
Ps: Friggin annoying to write code on a phone.

How to generate all numbers randomly between two given integers without duplication in Java?

I found answers on how to generate random numbers but nowhere how to generate all the numbers in the range without duplication in Java. Please share if you have a solution. Below is what I did but it simply generates randomly the numbers. I need to print out all numbers in the range without duplication!
package com.company;
import java.util.*;
public class RandomizeNumbers {
public static void main(String[] args) {
//Create Scanner
Scanner userInput = new Scanner(System.in);
//Ask for numbers N and M
System.out.println("Please enter two numbers and the program will randomize the numbers between them. " +
"The first number N must be bigger or equal to the second number M");
System.out.println("Please enter the first number N");
int n = userInput.nextInt();
System.out.println("Please enter the second number M");
int m = userInput.nextInt();
Random randomGenerator = new Random();
int difference = n - m;
//Randomize the numbers
if (m<=n){
for(int i = 0; i<= difference; i++ ) {
int randomInt = randomGenerator.nextInt(n - m + 1) + m;
System.out.println(randomInt);
}
}
else{
System.out.println("Please enter M less or equal to N");
}
}
}
What you need maybe generating a random permutation, pls see this link How to generate a random permutation in Java?
You can store generated number in a array.then after generate the next number check is there this number in array or no.
There are many ways to achieve this, lets suppose you want 50 numbers between A and B, then use a java.util.Set, since this collection does "ignore" duplicated values: following snippet describe it better:
Set<Integer> setA = new HashSet<Integer>();
Random r = new Random(System.currentTimeMillis());
int low = 10;
int high = 100;
int rnd = r.nextInt(high - low + 1) + low;
int maxCount = 50;
while (setA.size() < maxCount ) { //<--how many random numbers do you need?
rnd = r.nextInt(high - low + 1) + low;
setA.add(rnd);
}
and be careful, not to get in an infinite loop.
(there are only "B-A" possible integer options between A and B, so MaxCount<= B-A)
What I suggest you to do is to create a List and then shuffle it.
ArrayList<Integer> list = new ArrayList();
int high = 20;
int low = 10;
for(int i = low; i <= high; ++i)
list.add(i);
Collections.shuffle(list);
And then create a function to get a random Unique number each time.
static int index = 0;
public int roll(ArrayList<Integer> list)
{
return list.get(index ++);
}
You can put all the numbers between n & m into a list and then use Collections.shuffle(list) to make the numbers ordered randomly in the list.
if (difference > 0) {
List<Integer> integers = new ArrayList<>();
for (int i = 0; i <= difference; ++i) {
integers.add(m + i);
}
Collections.shuffle(integers);
for (Integer randNum : integers) {
System.out.print(randNum + "\t");
}
System.out.println();
} else {
System.out.println("Please enter M less or equal to N");
}

How do I write a random array of 5 integers but have it not count 0 as an integer?

I am trying to write a program that selects 5 integers at random between 1 and 6. I then need the program to display the missing integer. I can't figure out how to have it not display "0" as an integer. This is what I have so far...
import java.util.Random;
public class Task6
{
public static void main(String[] args)
{
int[] numbers = new int[5];
Random random = new Random();
for(int n = 1; n < 5; n++)
{
int select = random.nextInt(n + 1); //shuffle generator so it will not duplicate numbers
numbers[n] = numbers[select];
numbers[select] = n;
}//end for statement
for(int number : numbers)
{
System.out.println("Numbers selected : " + number);
}//end for
}
}
I have to have a O(n^2) operation in this as well.
If I understand correctly, you want your random numbers to only be between 1 and 6 (inclusive)? If that's the case then you need to restrict the range of what the RNG can actually spit out, using code similar to this:
/**
* Returns a pseudo-random number between min and max, inclusive.
* The difference between min and max can be at most
* <code>Integer.MAX_VALUE - 1</code>.
*
* #param min Minimum value
* #param max Maximum value. Must be greater than min.
* #return Integer between min and max, inclusive.
* #see java.util.Random#nextInt(int)
*/
public static int randInt(int min, int max) {
// NOTE: Usually this should be a field rather than a method
// variable so that it is not re-seeded every call.
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
Also, your for loop:
for(int n = 1; n < 5; n++) { ... }
will not generate 5 numbers, it will generate 4. Think about the constraints of the loop; it will run through once with n = 1, 2, 3, 4, and then stop (5 is not less than 5).
If you want 5 iterations, you can do this:
for (int n = 0; n < 5; n++) { ... }.
or this:
for (int n = 1; n <= 5; n++) { ... }
Your number of iterations and your random number range don't need to be related.
Check this excellent answer for more detail if you need it.
Create a method that applies your constraints to the random number. Here is an example.
// this assumes that only 0 is unacceptable.
private static int myRandomBlammy()
{
int returnValue;
do
{
returnValue = blam; // replace blam with some way of generating a random integer.
} while (returnValue == 0);
return returnValue;
}
You should have an if statement on your loop that goes through the numbers.
for(int number : numbers)
{
if(number != 0){
System.out.println("Numbers selected : " + number);
}
}//end for
I am trying to write a program that selects 5 integers at random
between 1 and 6. I then need the program to display the missing
integer. I can't figure out how to have it not display "0" as an
integer.
From your question, there may be a case where your 5 random integers will not all be unique, and there may be more than one unique number that was not generated.
I would handle this with an array that counts how many of each number is generated:
import java.util.Random;
public class RandomCounter
{
/**
* An example that uses array indices to count how many random
* numbers are generated in a range.
*/
public static void main(String[] args)
{
//use an array of size n + 1 (ignore the zero index)
int[] numbers = new int[7];
Random r = new Random();
//generate random numbers
for (int i = 1; i < 6; i++){
int next = r.nextInt(6) + 1;
numbers[next]++; //count each number at the index
}
//print any numbers that didn't occur at least once.
for(int i = 1; i < numbers.length; i++){
if(numbers[i] != 0){
System.out.println(i);
}
}
}
}
Replace the last for-loop with this code snippet to see how many of each number occurred:
//print how many of each number occurred.
for(int i = 1; i < numbers.length; i++){
System.out.println (i + ": " + numbers[i]); }
}
Array index counting is a useful way to dynamically count occurrences of numbers.

How to fill an array with specific random numbers (java)

I have to fill 1 row of an multidimensional array with integers going from 1 to 3 completely random.
Example: if I would print that row it could give : 1 2 2 1 2 3 1 2 3
Now to do this i thought following code would work:
private void fillArray()
{
for(int i=0; i<10;i++)
{
PincodeRandom[0][i]=i;
PincodeRandom[1][i]= (int)Math.random()*3 +1;
}
}
however this results into filling the entire second row with only 1 (random) integer.
How can I fix this?
If you are going to use the Random class, make sure you create an instance outside of the loop, since new Random() uses the system time as a seed. So if two randoms are created during the same tick, they will produce the same random number sequence.
private void fillArray()
{
Random rand = new Random();
for(int i=0; i<10;i++)
{
PincodeRandom[0][i]=i;
PincodeRandom[1][i]= rand.nextInt(2) + 1;
}
}
(int) will cast Math.random() to 0 before you multiply by 3, resulting in 0 * 3 + 1 which is always 1. Try:
(int)(Math.random()*3) + 1;
Try this:
import java.util.Random;
public class Test {
public static void main(String[] args){
int[][] array = new int[2][10];
Random rand = new Random();
for(int i=0; i<10;i++)
{
array[0][i]=i;
array[1][i]= (int)rand.nextInt(3) +1;
}
for (int j=0;j<10;j++){
System.out.println(Integer.toString(array[1][j]));
}
}
}
Try This...
Random r = new Random();
for(loop){
PincodeRandom[1][i]= = r.nextInt(4 - 1) + 1;
}
This is because (int)Math.random() is causing it to equal 0, since Math.random() is a double always inbetween 0 and 1.
Instead, import the java.util.Random class.
And use it like:
new Random().nextInt(2)+1

Categories

Resources