I am trying to fill an array with random int values from 0 to 6. To control my code i am printing out the random values I generate. I try to exclude duplicates in the nested if-statement inside the for-loop, but when I run the code I get my seven values, but some of them are still duplicated. Can someone please help me?
Here is my code:
import java.util.Random;
public class TesterArrayer
{
public static void main(String[] args)
{
int size = 7;
Random randomNumber = new Random();
int randomArray[] = new int[size];
for(int x =0; x < size; x++)
{
int randomValue = randomNumber.nextInt(6);
if (randomValue != randomArray[x])
{
randomArray[x] = randomValue;
}
}//End for-loop
for (int y = 0; y < size; y++)
{
System.out.println(randomArray[y]);
}
}
}
public static void main(String[] args) {
int size = 7;
boolean add = true;
int counter = 0;
Random randomNumber = new Random();
int randomArray[] = new int[size];
for(int j = 0; j < size; j++)
{
randomArray[j] = -1;
}
while (counter < size) {
add = true;
int randomValue = randomNumber.nextInt(7);
for (int x = 0; x < size; x++) {
if (randomValue == randomArray[x]) {
add = false;
}
}// End for-loop
if(add)
{
randomArray[counter] = randomValue;
counter++;
}
}
for (int y = 0; y < size; y++) {
System.out.println(randomArray[y]);
}
}
Try something like this. You don't want to add the number unless it's not already in the list. Also for your random you need 7 instead of 6 if you want 0-6.
This code will fill your array with 0-6 not repeating any numbers.
If you only want the numbers 0..length-1 in random order you can do something like this:
int length = 7;
List<Integer> list = new ArrayList<>(length);
for(int i=0; i<length; i++){
list.add(Integer.valueOf(i));
}
//list is now in order, need to randomly shuffle it
Collections.shuffle(list);
//now list is shuffled, convert to array
int array[] = new int[length];
for(int i=0; i<length; i++){
array[i] = list.get(i);
}
Change minLimit, maxLimit and noOfItems to get random Numbers
public class RandomIntegers
{
public static final Random random = new Random();
public static final int maxLimit = 6;
public static final int minLimit = 0;
public static final int noOfItems = 7;
public static void main( String[] args )
{
Set<Integer> uniqueRandomIntegerSet = new HashSet< Integer >();
while(uniqueRandomIntegerSet.size() < noOfItems)
uniqueRandomIntegerSet.add( random.nextInt( maxLimit - minLimit + 1 ) + minLimit );
Integer[] randomUniqueIntegers = uniqueRandomIntegerSet.toArray( new Integer[0] );
}
}
As you should use a more optimal data structure for this approach, as mentioned in the other answer and comments, you can still accomplish this with an array of course. As you have defined the problem you would need to change int randomValue = randomNumber.nextInt(6); to int randomValue = randomNumber.nextInt(7); or else this will loop infinitely as there is no possible way to have no duplicates in a size 7 array with only 6 values.
You can do something like this to modify your code for it to work:
boolean flag = false;
for(int x = 0; x < size; x++)
{
int randomValue = randomNumber.nextInt(7);
for (int i = 0; i < x; i++)
{
if (randomValue == randomArray[i])
{
//randomArray[x] = randomValue;
flag = true;
x--;
}
}
if (!flag)
randomArray[x] = randomValue;
flag = false;
}//End for-loop
This code is simply flagging when it sees a duplicate value in the array already and will skip this value and decrement the x value so that it will create another random value for this spot in the array.
byte[] source = new byte[1024];
Random rand = new Random();
rand.nextBytes(source);
Related
What code would i need to get a letter to randomly generate inside this code?
public class Array {
public static void main(String[] args) {
// Create 2-dimensional array.
int[][] values = new int[5][5];
// Loop over top-level arrays.
for (int i = 0; i < values.length; i++) {
// Loop and display sub-arrays.
int[] sub = values[i];
for (int x = 0; x < sub.length; x++) {
System.out.print(sub[x] + " ");
}
System.out.println();
}
}
}
String s = "abcdefghijklmnopqrstuvwxyz";
//loop through rows
for(int x = 0; x< values[0].length;x++)
{
//loops through columns
for(int y = 0; y< values.length;y++)
{
int x = (int)(Math.random()*26); // random int between 0-25
String letter = ""+s.charAt(x); //concatenates
values[x][y] = letter; // declares.
}
}
here is How you would get a letter to randomly generate inside the code.
I'm stuck..... i have been trying to use Arrays in methods to count the number of numbers divisible by 10 from the range 1-100.
here's my code:
import java.util.Scanner;
import java.util.Random;
public class Journal5a {
// METHOD
public int[] creatArray (int size)
{
int[] array = new int[size];
Random r = new Random();
for (int i = 0; i < array.length; i++)
array[i] = r.nextInt(100);
return array;
}
public int[] DivByTen()
{
int x = 0;
int y[] = this.creatArray(1);
for (int i = 0; i < y.length; i++)
if (y[i] % 10 == 0)
{
x++;
}
return x;
}
public int[] printArray ()
{
int[] myArray = this.creatArray(1);
for (int i = 0; i<myArray.length; i++)
System.out.println(myArray[i]);
return myArray;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Journal5a j5a = new Journal5a();
j5a.DivByTen();
}
So my output would be :
there is 10 numbers divisible by 10
Another problem is the x used in the method DivByTen isn't being returned.
Your createArray() method fills the array with random numbers from 0-99, so it is not clear how much numbers are dividable by 10.
for(int i = 0; i < size; i++) {
array[i] = i;
}
will create an array with values from 0 to size - 1.
The second problem is that your return type is int[] instead of int
First, create and fill the array. For the range 1 to 100 you would need to pass in 100 and either start with i at 1 (or add 1 to i when you initialize the array);
private static int[] creatArray(int size) {
int[] arr = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = i + 1;
}
return arr;
}
Next, count the multiples of some multiple. Something like,
private static int countMultiples(int[] arr, int multiple) {
int count = 0;
for (int val : arr) {
if (val != 0 && val % multiple == 0) {
count++;
}
}
return count;
}
Finally, call the above methods and output the result
public static void main(String[] args) {
final int multiple = 10;
int count = countMultiples(creatArray(100), multiple);
System.out.printf("There are %d numbers divisible by %d.", count, multiple);
}
Output is
There are 10 numbers divisible by 10.
Disclaimer: Still very new to code and have only basic skills with java. Trying to learn as much as i can on my own and from others. Not currently studying at uni.
Hello everyone.
I am trying to create an array with a small capacity (5 integers) to store a randomly generated integer in each array element. The randomly generated integer is in a set range (0-75) which ive no issue with.
What i cant figure out how to do is how to Generate a new integer, then check it against the current existing integers in each array element, before storing it and moving on to the next.
What i tried was this:
public class ItemSet
{
public static void main(String []args)
{
int[] itemSet;
itemSet = new int[5];
itemSet[0] = 0; /* to initialise the array elements. Im not sure if i actually have to do this or not */
itemSet[1] = 0;
itemSet[2] = 0;
itemSet[3] = 0;
itemSet[4] = 0;
int count = 1;
int assignItem = 0;
int countTwo = 1;
while (count > 5) {
while (countTwo == 1) {
assignItem = (int)(Math.random()*76);
// here is where i get totally lost
if (assignItem.compareTo(itemSet)) {
countTwo = 1;
} else {
itemSet[(count--)] = assignItem;
countTwo = 0;
}
}
count = count++;
}
}
}
Ive been looking at this so long my head is starting to hurt. I'd appreciate any advice you can give me. :) Thank you in advance. xx
Edit: Couldnt find the solution i needed in any of the "how can i test if an array contains a certain value" type questions, because i need to be able to have the number randomise again before it stores itself in the array element if it does happen to be the same as another previously generated integer.
You are doing too much to just fill an array. To fill an array, try using a "for" loop like so:
public class ItemSet {
public static void main(String []args) {
int[] itemSet;
itemSet = new int[5];
int count = 1;
int assignItem = 0;
int countTwo = 1;
for (int i = 0; i < itemSet.length; i++) {
itemSet[i] = (int) (Math.random() * 76);
}
}
}
To print the values stored in the array, try using an enhanced-for loop:
for (int element : itemSet) {
System.out.println(element);
}
To check the values BEFORE storing the next integer, (say to see ensure that the new stored value would be unique) you could use a nested for loop that starts at the value beneath the outer loop and walks backwards, comparing each value that came before to the value that was just stored, and if they are the same, it will decrement the outer counter which will then override the data on the next loop:
import java.util.Arrays; // you need this to use Arrays.toString()
public class ItemSet {
public static void main(String []args) {
int[] itemSet;
itemSet = new int[5];
int count = 1;
int assignItem = 0;
int countTwo = 1;
for (int i = 0; i < itemSet.length; i++) {
itemSet[i] = (int) (Math.random() * 76);
for (int j = i - 1; j >= 0; j--) {
if (itemSet[j] == itemSet[i]) {
System.out.println("Comparing " + itemSet[j] +
" and " + itemSet[i]);
i--;
break; // not really needed but illustrates a way to exit a loop immediately
}
}
}
// this is a handy way to print all the data in an array quickly
System.out.println(Arrays.toString(itemSet));
}
}
public static void main (String[] args){
//you dont need to initialize the array with zeros
int[] itemSet = new int[5];
int counter = 0;
while(counter < itemSet.length){
int random = (int)(Math.random() * 76);
//checks if the array already contains the random number
if(!Arrays.asList(itemSet).contains(random)){
itemSet[counter] = random;
counter++;
}
}
//print the array
for(int i : itemSet) System.out.println(i);
}
There are many ways you could solve this problem, I would suggest using a helping method that looks for duplicates in your array. This would be a working example:
public static void main(String[] args) {
int[] itemSet;
itemSet = new int[5];
int assignItem;
for (int i = 0; i < 5; i++) {
assignItem = (int)(Math.random()*76);
if(!duplicate(assignItem,itemSet,i)){
itemSet[i] = assignItem;
}
}
}
private static boolean duplicate(int assignItem, int[] itemSet, int i) {
for (int j = 0; j < i; j++) {
if (assignItem == itemSet[j])
return true;
}
return false;
}
The most straight forward way would be checking through the array for existing value before inserting the current random value.
Generate a random value
Check if value exists in array
If already exist in array, generate another value
If not exist in array, set value to current element
In codes:
public static void main(String[] args){
int idx = 0;
int[] myArray = new int[5];
Random rnd = new Random();
int val = rnd.nextInt(76);
do{
if(numExistInArray(val, myArray))
val = rnd.nextInt(76); //if val exist in array, generate another number
else
myArray[idx++] = val; //if val not exist in array, fill array
}while(idx != myArray.length); //do not exit loop till all numbers are filled
}
public static boolean numExistInArray(int val, int[] array){
for(int x=0; x<array.length; x++)
if(array[x] == val)
return true;
return false;
}
I had a hard time understanding what youre asking for but ill give it a go anyway hoping this is what you want:
for (int count = 0; count < 5 ; count++) {
assignItem = (int)(Math.random()*76);
if (assignItem==itemSet[count]&&itemSet[count]!=0) {
//If true do this
}
else {
itemSet[count] = assignItem;
}
}
Checking if the generated number is equal to a position and if the position is empty (0) if its not equal (a new number) then it will assign value to your array.
If you know your set range (which is 0-75) and space isn't an issue, I would suggest maintaining a pool of unused integers. This would guarantee each value is unique, and would avoid iterating over your array of integers to check for duplicates:
public static void main(String[] args) {
List<Integer> unusedNumbers = new ArrayList();
// Populate list with values
for (int i = 0; i <= 75; i++) unusedNumbers.add(i);
int[] itemSet = new int[5];
for (int i = 0; i < 5; i++) {
int randomIndex = (int) (Math.random() * unusedNumbers.size());
int randomInt = unusedNumbers.remove(randomIndex);
itemSet[i] = randomInt;
}
}
I came across this problem called compress. The objective is to take an array, remove any repeated values and return a new array.
I know this would be very easy with ArrayLists, but I want to do it without them.
So far, I've just written a loop to determine the number of unique values so I can construct a new array of the appropriate length. How can I then get the unique values into the new array?
public static int[] compress(int[] array){
int length = 0;
boolean contains = false;
for (int i = 0; i < array.length; i++){
contains = false;
for (int j = 0; j < i; j++){
if (a[i] == a[j]){
contains = true;
j = i;
} else {
contains = false;
}
}
if (!contains){
length++;
}
}
int[] uniqueArray = new int[length];
}
Not Tested but I think this should do the trick.
public static int[] copyArray(int [] num){
int x = 0;
int numDuplicate = 0;
int[] copy = new int[num.length]; // we use this to copy the non duplicates
HashMap<Integer, Integer> count = new HashMap<>(); //hashmap to check duplicates
for(int i = 0; i < num.length; i++){
if(count.containsKey(num[i])){
count.put(num[i], count.get(num[i])+1);
numDuplicate++; // keep track of duplicates
}else{
count.put(num[i], 1); // first occurence
copy[x] = num[i]; // copy unique values, empty values will be at end
x++;
}
}
// return only what is needed
int newSize = num.length - numDuplicate;
int[] copyNum = new int[newSize];
for(int i = 0; i < copyNum.length; i++){
copyNum[i] = copy[i];
}
return copyNum;
}
public static void main(String[] args) {
// sample elements
int[] nums = new int[20];
for(int i = 0; i < nums.length; i++){
nums[i] = (int)(Math.random() * 20);
}
System.out.println(Arrays.toString(nums));
System.out.println(Arrays.toString(copyArray(nums)));
}
I am writing this code to run 10000000 times and randomly generate a number and pick the most oftenly generated number, but the results do not seem random. The I have written is
public class Randomizer {
public static int[][] numbers = new int[45][2];
public static int maxN = 0;
public static int finalChoice;
public static void main(String[] args){
int arithmoi[] = new int[5];
for(int i =0; i < 5; i++){
arithmoi[i] = randomizer(1000000, 45);
System.out.println("A "+i+": "+arithmoi[i]);
}
int extra_num = randomizer(1000000, 20);
System.out.println("\nT: "+extra_num);
}
public static int randomizer(int times, int amount){
int[][] numbers = new int[amount][2];
for(int i = 0; i < amount; i++){
numbers[i][0] = i + 1;
numbers[i][1] = 0;
}
for(int i = 0; i < times; i ++){
int rnd = (int)(Math.random() * amount + 1);
for(int j = 0; j < amount; j++){
if(rnd == numbers [j] [0]){
numbers[j][1] ++ ;
break;
}
}
}
for(int i = 0; i < amount; i++){
if(maxN < numbers[i][1]){
finalChoice = numbers[i][0];
maxN = numbers[i][1];
}
}
return finalChoice;
}
}
The result that it gives me are A 0: 36
A 1: 36
A 2: 36
A 3: 36
A 4: 29
T: 14, A 0: 26
A 1: 44
A 2: 44
A 3: 44
A 4: 44
T: 4
and similar. What could the problem be?
import java.util.Random;
public class Randomizer {
public static int[][] numbers = new int[45][2];
public static int maxN = 0;
public static int finalChoice;
public static void main(String[] args){
int arithmoi[] = new int[5];
for(int i =0; i < 5; i++){
arithmoi[i] = randomizer(1000000, 45);
System.out.println("A "+(i+1)+": "+arithmoi[i]);
}
int extra_num = randomizer(1000000, 20);
System.out.println("\nT: "+extra_num);
}
public static int randomizer(int times, int amount){
int[][] numbers = new int[amount][2];
Random randomGenerator = new Random();
for(int i = 0; i < amount; i++){
numbers[i][0] = i + 1;
numbers[i][1] = 0;
}
for(int i = 0; i < times; i ++){
int rnd = randomGenerator.nextInt(amount);
for(int j = 0; j < amount; j++){
if(rnd == numbers [j] [0]){
numbers[j][1] ++ ;
break;
}
}
}
for(int i = 0; i < amount; i++){
if(maxN < numbers[i][1]){
finalChoice = numbers[i][0];
maxN = numbers[i][1];
}
}
return finalChoice;
}
}
The new code has still the same results(I used the Random Class)
You should use Java's Random class (java.util.Random) instead of writing your own. It is written by experts and has improved over many years as it is used and therefore tested by millions. It has been proven to generate pseudo-random numbers that do not have any particular pattern.
Writing your own pseudo-random generator would not be straight forward as there are a lot of factors involved.
Here is an example of its use:
Random random = new Random();
int maxIterations = 10000000;
int maxRandomValue = 100;
for(int i=0; i< maxIterations; i++)
{
System.out.println("Next random value: " + random.nextInt(maxRandomValue));
}
I think the main problem of you code it the way you tired to solve the task.
First of int[][] numbers = new int[amount][2]; holds redundant information because numbers[*][0] hold the position. Since numbers[i][1] holds the result for position i + 1 you can reduce the structure to int[amount].
Unlike other languages java defines the initial state of an int array to be always zero, so you do not need the first loop.
Your task is to let it rain on a line and check after n rounds, how many raindrops hit a certain spot/position.
It is okay to loop n times but since rnd.nextInt(amount) already gives you the spot the raindrop landed on, you do not have to iterate to find it.
for(int i = 0; i < times; i++) {
number[rnd.nextInt(amount)]++;
}
This will simulate the raindrops, but to get the proper random, you should initialize private static Random rnd = new Random() at class level and not at method level.
I hope this will help to solve your task.