how to add random number to an array - java

This is classwork. I've been reading and searching and everything is telling me to use the java.util.Random of which I understand how that works and wish I could use it. but my assignment specifically tells me to use the (int) (Math.random * number) of which I am having difficulty seeing where to apply into my array. everything I've seen has been the Random pulled from java.
It is the generate 100 random integers 0-9 and how many times they occur. If someone can assist?
My error is - Exception in "main" java.lang.array index out of bounds exemption:10 and obviously there is something in my code wrong too.
public class NumberOfTimes{
public static void main(String[] args){
int rand = (int)(Math.random() * 10);
int[] counts = new int [10];
for(int i = 0; i < 100; i++){
counts[i]++;
}//end for
System.out.println("number\t" + "occurence ");
for (int num = 0; num < counts.length; num++){
System.out.println(num + "\t" + counts[num]);
}//end for
}//end main
}//end NumberOfTimes

make this change
int[] counts = new int[100];
for (int i = 0; i < counts.length; i++) {
counts[i] = (int) (Math.random() * 10);
}// end for

Your array can only hold 10 items, and on your loop you are accessing more than 10. Can be solved in two ways.
Either Increase your array length
int[] counts = new int [100];
Or either decrease your count in for loop.
for(int i = 0; i < 10; i++){

Related

Generate a random two-dimensional array of non-repeating numbers, Java

The user will type in the number for i (variant), then the number for j (elements for every variant), and finally the maximum value possible (maxElem).
Using the inputed values, the task is to generate nonrepeating random numbers (nonrepeating in a variant, meaning for i, but the numbers may repeat during the entire array).
For example, a successful output giving the input 3 (i), 5 (j), 9 (maxElem), would be:
4|8|1|7|9
3|8|2|4|5
2|6|4|8|5
As you may notice, the number 4 repeats itself during the entire array for 3 times (allowable). But, for i=0, number 4 is unique.
Please, guide me what would be the changes to this code:
static Scanner sc = new Scanner(System.in);
static int maxElem;
public static void main(String[] args) {
int[][] greatLoto;
System.out.println("Of how many variants will the ticket consist? ");
int variants = sc.nextInt();
System.out.println("Of how many elements will the variants consist? ");
int elements = sc.nextInt();
System.out.println("Which value should be considered the maximum value? ");
maxElem = sc.nextInt() + 1;
greatLoto = new int[variants][elements];
System.out.println("Initial values: ");
show(greatLoto);
System.out.println("Modifying values...");
modified(greatLoto);
System.out.println("Newest values: ");
show(greatLoto);
}
private static void show(int[][] greatLoto) {
for (int i = 0; i < greatLoto.length; i++) {
for (int j = 0; j < greatLoto[i].length; j++) {
System.out.print("|" + greatLoto[i][j] + "|");
}
System.out.println("");
}
System.out.println("");
}
private static void modified(int[][] greatLoto) {
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < greatLoto.length; i++) {
for (int j = 0; j < greatLoto[i].length; j++) {
while (Arrays.asList(greatLoto[i]).contains(r)) {
r = new Random(System.currentTimeMillis());
}
greatLoto[i][j] = r.nextInt(maxElem);;
}
System.out.println("");
}
}
This is more of a comment but too long: don't use random.next() because it forces you to check for uniqueness. Instead fill a list with the valid values and shuffle it:
List<Integer> values = new ArrayList<> ();
for (int i = 1; i <= max; i++) values.add(i);
Collections.shuffle(values);
Then you can simply iterate over the values and take the j first numbers.
Note that if j is significantly greater than i using the random approach would probably be more efficient.
The most minimal change would be:
private static void modified(int[][] greatLoto) {
Random r = new Random(System.currentTimeMillis());
for (int i = 0; i < greatLoto.length; i++) {
for (int j = 0; j < greatLoto[i].length; j++) {
do {
greatLoto[i][j] = r.nextInt(maxElem);
} while (Arrays.asList(greatLoto[i]).contains(greatLoto[i][j]));
}
System.out.println("");
}
}
But there are more elegant (but difficult to code) ways to generate unique random numbers without discarding duplicates.
You need three loops:
Loop_1: Builds an array of size j and uses Loop_1B for every field of this array.
Loop_1B: Generate an int with r.nextInt(maxElem)+1; (it has to be +1 because nextInt() is covering the 0 inclusively and the specified value exclusively). Afterwards check if the number is already used in the array, if yes, run this loop again.
Loop_2: Repeats Loop_1 i times.

Is there something wrong with my nested for-loop? counting and incrementing values of arrays

So, I generate a 100 numbers between the range of 0 and 9. I store these 100 numbers in an array called 'array'. Then I have the array called 'count'. It has 10 elements, and I wanted to check the following: for each element in 'array' if it equals to 0-9 then count[0-9] increments by 1, count[0] = how many times number 0 appears and so on count[1] = 1, count[2] = 2... . I just keep getting the output of around 20k numbers and i suppose? the sum of each element?, no idea why. I was wondering if there is something major wrong with my for loop?
import java.util.*;
class RandomInt {
public static void main(String[] args) {
int size = 100;
int max = 10;
int[] array = new int[size];
int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
int loop = 0;
Random generator = new Random();
for (int i = 0; i < size; i++) {
array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
System.out.print(array[i]);
for (int x = 0; x < size; x++) {// loop through 10 elements in count
for(int j = 0; j < 10; j++){ //loop through 100 elements in array
if (array[x] == j) {// loop through each 100 elements of array[x] and if element array[x] = value
count[j] += 1; // then count[x] = x + 1
System.out.print(count[j]);
}
}
}
}
System.out.println("0 appears " + count[0] + " times.");
}
}
Your Login is Perfect only mistake which i found u made is with the brackets........!
Generate the numbers using first loop and then count the number of occurrence using different for loop.
Here is your code's modified version which generates 10 numbers and counts the individual number occurrence count.....
public class RandomInt {
public static void main(String[] args) {
int size = 10;
int max = 10;
int[] array = new int[size];
int[] count = new int[max]; //count[0,0,0,0,0,0,0,0,0,0]
int loop = 0;
Random generator = new Random();
for (int i = 0; i < size; i++)
{
array[i] = generator.nextInt(max); // Generates 100 random numbers between 0 and 9 and stores them in array[]
System.out.print(array[i]+" ");
}
for (int x = 0; x < size; x++)
{// loop through 10 elements in count
for(int j = 0; j < 10; j++)
{ //loop through 100 elements in array
if (array[x] == j)
{// loop through each 100 elements of array[x] and if element array[x] = value
count[j] += 1; // then count[x] = x + 1
//System.out.print(count[j]);
}
}
}
System.out.println("3 appears " + count[3] + " times.");
}
}
There's a simpler way to do this without nested loops, so forgive me for suggesting this as a fix rather than finding the issue in the loop.
for(int i=0; i<size; i++){
int num = generator.nextInt(max);
array[i] = num;
count[num]++;
}
One loop, incrementing the count for each number as it appears. You may need to ensure all the entries in count start at 0, but even then an additional loop through 10 entries is MUCH faster.
To increment your counter, you don't need to have two nested for loops. Instead, you can use the value of array[x] as your counter.
for (int i = 0; i < size; i++) {
count[array[i]]++
}
You've nested your counting loop inside of your random number generating loop. Move the counting part outside.
Edit: The reason you're getting like 20k or whatever instances of zero is because when you set array[0] with a random value, you also check how many instances of 0 are in array[1] to array[99].
You probably shouldn't do your count until you have finished assigning your numbers, but here is how you could. Note that you want the value at array[i] to be your index to count.
for (int i = 0; i < size; i++) {
array[i] = generator.nextInt(max); // Generates random numbers
count[array[i]]++;
}
System.out.println(Arrays.toString(array));
System.out.println(Arrays.toString(count));

Why am I getting an error saying "<variable> might not have been initialized"? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 9 years ago.
Improve this question
This program will create an array of 10 integers. Each element in the array is initialized to 2. Each element of the array is then added up to get a total for the entire array. The answer we are expecting is 20. See if you can correct the following code to produce the correct solution.
How come I get an error saying that sum might not have been initialized even if i did it in the for loop?
public class WarmUp_01_22_2014{
public static void main(String[] args){
int[] myArray = new int[12];
int total=0;
for (int i = 0; i < 10; i++){
myArray[i] = 2;
}
for (int i = 0; i < 12; i++){
int sum = 0;
int sum += myArray[i];
}
System.out.println("The sum of the numbers in the array is " + sum);
}
}//end class WarmUp_01_22_2014
You aren't getting that message with that code; this won't compile because sum isn't visible to println. Most likely, you have a declaration of an int sum in the main body, and then you declare another int sum inside the loop. You only want to "create" the variable once, and then just assign values to it.
I suspect that you're really using total in your program; just change your second for loop to this:
for (int i = 0; i < 12; i++){
total += myArray[i]; // the variable "total" was created and set to zero above
}
public class WarmUp_01_22_2014{
public static void main(String[] args){
int[] myArray = new int[12];
int total=0;
int sum = 0;
for (int i = 0; i < 10; i++){
myArray[i] = 2;
}
for (int i = 0; i < 12; i++){
sum += myArray[i];
}
System.out.println("The sum of the numbers in the array is " + sum);
}
}//end class WarmUp_01_22_2014
Should work. Declare your variable higher up so it can be accessed by the println() method.
A few things:
an array of size 10 integers means that you need to write new int[10] instead of new int[12]
you declared sum inside of the for loop, so it is not accessible outside of that for loop (because there is no guarantee that it will even be declared).
you are also redeclaring sum in every loop by writing int sum += myArray[i] - only declare once
i < 12 and i < 10 can be changed to be i < myArray.length to make it more general.
public class WarmUp_01_22_2014{
public static void main(String[] args){
int[] myArray = new int[10]; // size 10, not 12
int sum = 0; // declare sum here
for (int i = 0; i < myArray.length; i++){ // < myArray.length
myArray[i] = 2;
}
for (int i = 0; i < myArray.length; i++){ // < myArray.length
sum += myArray[i]; // add on to the sum, don't declare it here
}
System.out.println("The sum of the numbers in the array is " + sum);
}
}
How to solve the problem
A simple adjustment such as (i) bringing the declaration before entering the loop and (ii) changing the value type (int) when using variable sum the second time to avoid conflict will do the trick:
public class WarmUp_01_22_2014{
public static void main(String[] args) {
int[] myArray = new int[12];
int total = 0;
for (int i = 0; i < 10; i++) {
myArray[i] = 2;
}
//declare varaible here to avoid error
int sum = 0;
for (int i = 0; i < 12; i++) {
//change int sum+=myArray[i] to sum+=myArray[i]
sum += myArray[i];
}
System.out.println("The sum of the numbers in the array is " + sum);
}
}
Reasoning
When the compiler compiles the source code, it still doesn't know that a variable such as sum does exists. According to the compiler, the variable sum is created only if the for loop is activated (which we as humans know is inevitable but the machine doesn't).

Randomize Array of numbers 1 through 100

I'm trying to create a program to create an array of the numbers 1 through 100 and then randomize them. So far I have this, but don't know what to do next:
public class Random100Array
{
public static void main(String args[])
{
{
int[] nums = new int[100];
char current;
int a;
for (int i = 0; i <= nums.length; i++) {
nums[i] = i + 1;
}
for (int i1 = 0; i1 <=nums.length; i1++) {
double random = (Math.random() * 100) + 1;
}
}
}
}
Also, THIS ISN'T HOMEWORK. I am a student and I'm currently on winter break. This program gives me this output for some reason. What am I doing wrong?
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 100
at Random100Array.main(Random100Array.java:11)
Use < instead of <= in your for loops.
Firstly, you should take care of your for-loops conditions as mentioned in other answers.
Then, for shuffling your input array, you can use this code:
import java.util.Random;
public class Program {
public static void main(String[] args)
{
int[] nums = new int[100];
for(int i = 0; i < nums.length; ++i)
{
nums[i] = i + 1;
}
Random generator = new Random();
for(int i = 0; i < nums.length; ++i)
{
int j = generator.nextInt(nums.length - i);
int tmp = nums[nums.length - 1 - i];
nums[nums.length - 1 - i] = nums[j];
nums[j] = tmp;
}
}
}
Initializing an array with the length of 100 means, you have indices ranging from 0 to 99, so you won't have index 100, thats why you receive this exception. nums.length will be 100 (since you initialize the length with 100. Basically your for-loop is ranging from 0 to 100 (which are 101 nums) this is out of bound.
Use < instead of <= inside the for loops
for shuffeling the array, try something like this:
https://stackoverflow.com/a/1520212/995320
You need to use < and not <=
Also, you can use a try catch to escape the exception, but this would not be considered good practice

duplicates in randomly generated array in Java

I am in a cs 2010 class. Haven't ever worked on coding before or anything of the sort. I have an okay teacher but he has a very thick accent that is hard to understand. He recently gave us a project to complete over a few days. I have been having problems getting the last part of the project done.
The project asks you to generate 10,000 random numbers between 0-9999 and arrange them in an array of 10,000 numbers without repeating any of them. As you can see, this is basically asking you to make the array put the numbers 0-9999 in an array in order of least to greatest. My problem is the non-repeating numbers. I have been working on the code for over 4 hours trying to figure out how to make it not repeat and have had no luck. I have searched online for at least an hour and all other hints or solutions have not helped. This is the code I have so far, can anyone please help me?
package array.sorter.project;
import java.util.Arrays;
import java.util.Random;
public class Sorting {
public static void main(String args[]){
int[] randomNumbers = new int[10000];
Random rand = new Random();{
for (int i = 1; i < randomNumbers.length; i++) {
int n = rand.nextInt(10000);
randomNumbers[i] = n;}
for (int i = 0; i < randomNumbers.length; i++) {
int smallestNo = randomNumbers[i];
int posWithSmallest = i;
for (int j = i+1; j < randomNumbers.length; j++) {
int val = randomNumbers[j];
if (val < smallestNo) {
smallestNo = val;
posWithSmallest = j;
}
}
int tmp = randomNumbers[i];
randomNumbers[i] = smallestNo;
randomNumbers[posWithSmallest] = tmp;
}
Arrays.sort(randomNumbers);
for (int i = 0; i < randomNumbers.length; i++) {
System.out.println("Position " + i + " : " + randomNumbers[i]);
}
}
}
}
Instead of randomly generating 10000 numbers from 0 to 9999, generate 0...9999 in ascending order and shuffle the array. Make sure that your shuffling is unbiased, e.g. that there are n! ways it can complete (if you're not sure, desk check it with n = 3 to see if it is unbiased)
You can not generate 10000 random integers in range 0-9999 without duplicates, there are only 10000 of then, so you need all.
What you can do is to rearrange, shuffle them.
So:
import java.util.Collections;
import java.util.Arrays;
...
int[] ten_thousand = new int[10000];
for (int i=0; i < 10000; i+=1) ten_thousand[i] = i;
return Collections.shuffle(Arrays.asList(ten_thousand));
Know your weapons :)
If you do not want to use shuffle
private static int[] generateRandom(int count) {
int[] randomNumbers = new int[count];
Set<Integer> checker = new HashSet<Integer>();
Random rand = new Random();
for (int i = 0; i < count;) {
int nextInt = rand.nextInt(count);
if (!checker.contains(nextInt)) {
randomNumbers[i++] = nextInt;
checker.add(nextInt);
}
}
return randomNumbers;
}
I've written a O(n) algorithm to solve this problem inspired by the book Programming Pearls, 2nd Edition.the code is below,i will explain it later:
/**
* randomly select k numbers in [0,n),and sort them in random order.(k<=n)
*/
public static int[] getRandomArray(int n, int k) {
if (k > n) {
k = n;
}
int[] rets = new int[k]; // store the random ordered number
int[] array = new int[n];// original array that array[i] is i
for (int i = 0; i < n; i++)
array[i] = i;
Random random = new Random();
for (int j = 0; j < k; j++) {
// generate a random number between [j,n) as index
int index = j + random.nextInt(n - j);
// swap array[j] and array[index],so array[0..j] are all non-repeat
// random number
int temp = array[index];
array[index] = array[j];
array[j] = temp;
// store it in rets
rets[j] = temp;
}
return rets;
}
explain:
to generate non-repeating 10,000 random numbers between 0-9999
can be considered to arrange number 0-9999 in random order。
1,the k number are stored in array,within which x in position x.
2,for the number j,random select a index from [j,n),that's index,
3,swap the position of j from j to index,(e.q. to swap the number at index to position j)
4,loop j from 0 to k,

Categories