Generating 10 random numbers without duplicate with fundamental techniques - java

my intend is to use simplest java (array and loops) to generate random numbers without duplicate...but the output turns out to be 10 repeating numbers, and I cannot figure out why.
Here is my code:
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
do {
for (int i=0; i<number.length; i++) {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
}
} while (!repeat);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}

How about you use a Set instead? If you also want to keep track of the order of insertion you can use a LinkedHashSet.
Random r = new Random();
Set<Integer> uniqueNumbers = new HashSet<>();
while (uniqueNumbers.size()<10){
uniqueNumbers.add(r.nextInt(21));
}
for (Integer i : uniqueNumbers){
System.out.print(i+" ");
}
A Set in java is like an Array or an ArrayList except it handles duplicates for you. It will only add the Integer to the set if it doesn't already exist in the set. The class Set has similar methods to the Array that you can utilize. For example Set.size() is equivalent to the Array.length and Set.add(Integer) is semi-equivalent to Array[index] = value. Sets do not keep track of insertion order so they do not have an index. It is a very powerful tool in Java once you learn about it. ;)
Hope this helps!

You need to break out of the for loop if either of the conditions are met.
int[] number = new int[10];
int count=0;
int num;
Random r = new Random();
while(count<number.length){
num = r.nextInt(21);
boolean repeat=false;
do{
for(int i=0; i<number.length; i++){
if(num==number[i]){
repeat=true;
break;
}
else if(i==count){
number[count]=num;
count++;
repeat=true;
break;
}
}
}while(!repeat);
}
for(int j=0;j<number.length;j++){
System.out.print(number[j]+" ");
}
This will make YOUR code work but #gonzo proposed a better solution.

Your code will break the while loop under the condition: num == number[i].
This means that if the pseudo-generated number is equal to that positions value (the default int in java is 0), then the code will end execution.
On the second conditional, the expression num != number[i] is always true (otherwise the code would have entered the previous if), but, on the first run, when i == count (or i=0, and count=0) the repeat=true breaks the loop, and nothing else would happen, rendering the output something such as
0 0 0 0 0 0...

Try this:
int[] number = new int[10];
java.util.Random r = new java.util.Random();
for(int i=0; i<number.length; i++){
boolean repeat=false;
do{
repeat=false;
int num = r.nextInt(21);
for(int j=0; j<number.length; j++){
if(number[j]==num){
repeat=true;
}
}
if(!repeat) number[i]=num;
}while(repeat);
}
for (int k = 0; k < number.length; k++) {
System.out.print(number[k] + " ");
}
System.out.println();
Test it here.

I believe the problem is much easier to solve. You could use a List to check if the number has been generated or not (uniqueness). Here is a working block of code.
int count=0;
int num;
Random r = new Random();
List<Integer> numbers = new ArrayList<Integer>();
while (count<10) {
num = r.nextInt(21);
if(!numbers.contains(num) ) {
numbers.add(num);
count++;
}
}
for(int j=0;j<10;j++){
System.out.print(numbers.get(j)+" ");
}
}

Let's start with the most simple approach, putting 10 random - potentially duplicated - numbers into an array:
public class NonUniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
number[count++] = ThreadLocalRandom.current().nextInt(21);
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}
So that gets you most of the way there, the only thing you know have to do is pick a number and check your array:
public class UniqueRandoms
{
public static void main(String[] args)
{
int[] number = new int[10];
int count = 0;
while (count < number.length) {
// Use ThreadLocalRandom so this is a contained compilable unit
int candidate = ThreadLocalRandom.current().nextInt(21);
// Is candidate in our array already?
boolean exists = false;
for (int i = 0; i < count; i++) {
if (number[i] == candidate) {
exists = true;
break;
}
}
// We didn't find it, so we're good to add it to the array
if (!exists) {
number[count++] = candidate;
}
}
for (int j = 0; j < number.length; j++) {
System.out.println(number[j]);
}
}
}

The problem is with your inner 'for' loop. Once the program finds a unique integer, it adds the integer to the array and then increments the count. On the next loop iteration, the new integer will be added again because (num != number[i] && i == count), eventually filling up the array with the same integer. The for loop needs to exit after adding the unique integer the first time.
But if we look at the construction more deeply, we see that the inner for loop is entirely unnecessary.
See the code below.
import java.util.*;
public class RandomDemo {
public static void main( String args[] ){
// create random object
Random r = new Random();
int[] number = new int[10];
int count = 0;
int num;
while (count < number.length) {
num = r.nextInt(21);
boolean repeat = false;
int i=0;
do {
if (num == number[i]) {
repeat = true;
} else if (num != number[i] && i == count) {
number[count] = num;
count++;
repeat = true;
}
i++;
} while (!repeat && i < number.length);
}
for (int j = 0; j < number.length; j++) {
System.out.print(number[j] + " ");
}
}
}

This would be my approach.
import java.util.Random;
public class uniquerandom {
public static void main(String[] args) {
Random rnd = new Random();
int qask[]=new int[10];
int it,i,t=0,in,flag;
for(it=0;;it++)
{
i=rnd.nextInt(11);
flag=0;
for(in=0;in<qask.length;in++)
{
if(i==qask[in])
{
flag=1;
break;
}
}
if(flag!=1)
{
qask[t++]=i;
}
if(t==10)
break;
}
for(it=0;it<qask.length;it++)
System.out.println(qask[it]);
}}

public String pickStringElement(ArrayList list, int... howMany) {
int counter = howMany.length > 0 ? howMany[0] : 1;
String returnString = "";
ArrayList previousVal = new ArrayList()
for (int i = 1; i <= counter; i++) {
Random rand = new Random()
for(int j=1; j <=list.size(); j++){
int newRand = rand.nextInt(list.size())
if (!previousVal.contains(newRand)){
previousVal.add(newRand)
returnString = returnString + (i>1 ? ", " + list.get(newRand) :list.get(newRand))
break
}
}
}
return returnString;
}

Create simple method and call it where you require-
private List<Integer> q_list = new ArrayList<>(); //declare list integer type
private void checkList(int size)
{
position = getRandom(list.size()); //generating random value less than size
if(q_list.contains(position)) { // check if list contains position
checkList(size); /// if it contains call checkList method again
}
else
{
q_list.add(position); // else add the position in the list
playAnimation(tv_questions, 0, list.get(position).getQuestion()); // task you want to perform after getting value
}
}
for getting random value this method is being called-
public static int getRandom(int max){
return (int) (Math.random()*max);
}

Related

unable to sort or print out array

I got a task to write the methods to 1. take information in and save it into array, 2. to copy the array(only with previously given arguments) and 3. to sort the array to be in descending order. it seems to me like i got the first 2 parts working but i have been stuck on the third method for 2 days without any progress. i am still learning java so i'm pretty sure i have made a dumb mistake somewhere. thanks in advance.
import java.util.*;
public class RevisionExercise {
public static void main(String[] args) {
int[] tempArray = new int[100];
System.out.println("Type in numbers. Type zero to quit.");
int amountOfNumbers = askInfo(tempArray);
int[] realArray = new int[amountOfNumbers];
copyInfo(realArray, tempArray);
setArray(realArray);
printArray(realArray);
}
public static int askInfo(int[] tempArray) {
Scanner reader = new Scanner(System.in);
int i;
for (i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
tempArray[i] = reader.nextInt();
if (tempArray[i] == 0) {
return tempArray[i];
}
}
return i;
}
private static int[] copyInfo(int[] realArray, int[] tempArray)
{
int targetIndex = 0;
for( int sourceIndex = 0; sourceIndex < tempArray.length; sourceIndex++ )
{
if( tempArray[sourceIndex] != 0 )
tempArray[targetIndex++] = tempArray[sourceIndex];
}
realArray = new int[targetIndex];
System.arraycopy( tempArray, 0, realArray, 0, targetIndex );
return realArray;
}
public static int[] setArray(int[] realArray)
{
int temp = 0;
for (int i = 0; i <realArray.length; i++) {
for (int j = i+1; j <realArray.length; j++) {
if(realArray[i] >realArray[j]) {
temp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = temp;
}
}
}
return realArray;
}
public static void printArray(int[] realArray ) {
System.out.println("\nOrdered array: ");
for(int i = 0; i < realArray .length; i++) {
System.out.println(realArray [i]);
}
}
}
the output i'm getting looks like this.
Type in numbers. Type zero to quit.
1. number: 3
2. number: 8
3. number: 5
4. number: 6
5. number: 9
6. number: 0
Ordered array:
while it should look like this:
Type in numbers. Type zero to quit.
1. number: 3
2. number: 8
3. number: 5
4. number: 6
5. number: 9
6. number: 0
Ordered array:
9
8
6
5
3
You made a mistake in calculating the total numbers entered by the user. Your function always return 0. So change it to something like this:
public static int askInfo(int[] tempArray) {
Scanner reader = new Scanner(System.in);
int totalNumbers = 0;
for (int i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
int number = reader.nextInt();
if (number != 0) {
totalNumbers++;
tempArray[i] = number;
} else {
break;
}
}
return totalNumbers;
}
Chage the sort function to this:
public static void setArray(int[] realArray) {
int temp = 0;
for (int i = 0; i < realArray.length; i++) {
for (int j = i+1; j < realArray.length; j++) {
// Use < for descending order and > for ascending order
if(realArray[i] < realArray[j]) {
temp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = temp;
}
}
}
}
Your main program
public static void main(String[] args) {
int[] tempArray = new int[100];
System.out.println("Type in numbers. Type zero to quit.");
int amountOfNumbers = askInfo(tempArray);
int[] realArray = new int[amountOfNumbers];
copyInfo(tempArray, realArray, amountOfNumbers);
setArray(realArray);
printArray(realArray);
}
public static int askInfo(int[] tempArray) {
Scanner reader = new Scanner(System.in);
int totalNumbers = 0;
for (int i = 0; i < tempArray.length; i++) {
System.out.print((i+1) + ". number: ");
int number = reader.nextInt();
if (number != 0) {
totalNumbers++;
tempArray[i] = number;
} else {
break;
}
}
return totalNumbers;
}
private static void copyInfo(int[] tempArray, int[] realArray, int size) {
for( int sourceIndex = 0; sourceIndex < size; sourceIndex++ )
{
realArray[sourceIndex] = tempArray[sourceIndex];
}
}
public static void setArray(int[] realArray) {
int temp = 0;
for (int i = 0; i < realArray.length; i++) {
for (int j = i+1; j < realArray.length; j++) {
if(realArray[i] < realArray[j]) {
temp = realArray[i];
realArray[i] = realArray[j];
realArray[j] = temp;
}
}
}
}
public static void printArray(int[] realArray ) {
System.out.println("\nOrdered array: ");
for(int i = 0; i < realArray.length; i++) {
System.out.println(realArray [i]);
}
}
To begin with, in the askInfo method, the size of the realArray will always be 0, since amountOfNumbers is the return of
if (tempArray[i] == 0) {
return tempArray[i];
}
because your condition is tempArray[i] == 0, hence you are always returning 0. Then your copyInfo method is returning an array but you have nothing receiving the returned array. I would suggest changing your copyInfo method to
private static int[] copyInfo(int[] tempArray)
{
// same
int [] realArray = new int[targetIndex];
// same
}
and your main method to
public static void main(String[] args) {
//same
int[] realArray = new int[amountOfNumbers];
realArray = copyInfo(tempArray);
// same
}
General remark: Each of your methods returns an array but you never use this return value.
There are 2 modifications necessary to fix your code:
Keep the value of the method output:
realArray=copyInfo(realArray, tempArray);
So you put the result of the copy in the realArray variable.
You expect the askInfo method to return the number of entered numbers but in fact you return the value of the last entered number.
So instead of return tempArray[i]; you have to return i;

finding first even element and outputting index

My program:
public static void evenval (int[] array ){
int even=0;
for (int r = 0; r < array.length; r++) {
while (r == array[r]) {
if (array[r] % 2 ==0) {
even = array[r];
System.out.println("The first even number's index is:"+array[r]);
}
I'm trying to make a loop where it finds the first even number in an array and get it to output it's index to the main method.
I'm stuck, please help.
Try to use just for loop like this:
int even = 0;
for (int r=0;r<array.length;r++){
if (array[r] % 2 ==0){
even = r;
break;
}
}
System.out.println("The first even number's index is:"+ even );
Using the break; when find the even number.
For example if you want to find 100th even number use this:
int even = 0;
int count = 0;
for (int r=0;r<array.length;r++){
if(array[r] % 2 ==0){
if(count !=100){
count++;
}else{
even = r;
break;
}
}
}
System.out.println("The first even number's index is:"+ even );
It's better to create a small method in your class and call it from main to do this for you and return the index or -1 if a valid even number is not found. :
public class EvenTest{
int getFirstEvenIndex(int[] array){
for (int r=0; r < array.length; r++){
if (array[r] % 2 ==0){
return r;
}
}
return -1;
}
public static void main(String... args){
int[] arr = [3,5,1,2,7,8];
EvenTest et = new EvenTest();
System.out.println("First even is at index: " + et.getFirstEvenIndex(arr));
}
}
class test {
public static void main(String[] args) {
int[] array = {5, 7, 1, 8, 9, 3,110};
int evenCount =2;//required count ....for 100th even put evenCount = 100;
evenval(array,evenCount);
}
public static void evenval(int[] array,int evenCount) {
for (int i=0;i<array.length;i++) {
if(array[i] % 2 == 0&&--evenCount==0) {
System.out.println("the required even number is "+array[i]+" at index "+i);
return;
}
}
}
}
Just remove while statement in your code.
int even = 0;
for (int r = 0; r < array.length; r++) {
if (array[r] % 2 == 0) {
even = array[r];
System.out.println("The first even number's index is:" + array[r]);
}
}
If you want to stop after finding first even number, just put break inside if statement
int even = 0;
for (int r = 0; r < array.length; r++) {
if (array[r] % 2 == 0) {
even = array[r];
System.out.println("The first even number's index is:" + array[r]);
break;
}
}
You could simply use a bitwise operation as well (performance wise, it's quicker):
for (int n : array) {
if ((n&1) == 0) {
System.out.println("The first even number's index is:" + n);
break;
}
}

Finding non duplicate element in an array

I am stuck in the following program:
I have an input integer array which has only one non duplicate number, say {1,1,3,2,3}. The output should show the non duplicate element i.e. 2.
So far I did the following:
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
for(int j=0;j<size;j++){
if(temp == arr[j]){
if(i != j)
//System.out.println("Match found for "+temp);
flag = false;
break;
}
}
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
Restricting the solution in array is preferable. Avoid using collections,maps.
public class NonRepeatingElement {
public static void main(String[] args) {
int result =0;
int []arr={3,4,5,3,4,5,6};
for(int i:arr)
{
result ^=i;
}
System.out.println("Result is "+result);
}
}
Since this is almost certainly a learning exercise, and because you are very close to completing it right, here are the things that you need to change to make it work:
Move the declaration of flag inside the outer loop - the flag needs to be set to true every iteration of the outer loop, and it is not used anywhere outside the outer loop.
Check the flag when the inner loop completes - if the flag remains true, you have found a unique number; return it.
From Above here is the none duplicated example in Apple swift 2.0
func noneDuplicated(){
let arr = [1,4,3,7,3]
let size = arr.count
var temp = 0
for i in 0..<size{
var flag = true
temp = arr[i]
for j in 0..<size{
if(temp == arr[j]){
if(i != j){
flag = false
break
}
}
}
if(flag == true){
print(temp + " ,")
}
}
}
// output : 1 , 4 ,7
// this will print each none duplicated
/// for duplicate array
static void duplicateItem(int[] a){
/*
You can sort the array before you compare
*/
int temp =0;
for(int i=0; i<a.length;i++){
for(int j=0; j<a.length;j++){
if(a[i]<a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j] == a[k]) {
count++;
}
}
if(count==1){
System.out.println(a[j]);
}
count = 0;
}
}
/*
for array of non duplicate elements in array just change int k=j+1; to int k = 0; in for loop
*/
static void NonDuplicateItem(int[] a){
/*
You can sort the array before you compare
*/
int temp =0;
for(int i=0; i<a.length;i++){
for(int j=0; j<a.length;j++){
if(a[i]<a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =0 ;k<a.length;k++) {
if(a[j] == a[k]) {
count++;
}
}
if(count==1){
System.out.println(a[j]);
}
count = 0;
}
}
public class DuplicateItem {
public static void main (String []args){
int[] a = {1,1,1,2,2,3,6,5,3,6,7,8};
duplicateItem(a);
NonDuplicateItem(a);
}
/// for first non repeating element in array ///
static void FirstNonDuplicateItem(int[] a){
/*
You can sort the array before you compare
*/
int temp =0;
for(int i=0; i<a.length;i++){
for(int j=0; j<a.length;j++){
if(a[i]<a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int count=0;
for(int j=0;j<a.length;j++) {
//int k;
for(int k =0; k<a.length;k++) {
if(a[j] == a[k]) {
count++;
}
}
if(count==1){
System.out.println(a[j]);
break;
}
count = 0;
}
}
public class NonDuplicateItem {
public static void main (String []args){
int[] a = {1,1,1,2,2,3,6,5,3,6,7,8};
FirstNonDuplicateItem(a);
}
I have a unique answer, it basically takes the current number that you have in the outer for loop for the array and times it by itself (basically the number to the power of 2). Then it goes through and every time it sees the number isn't equal to double itself test if its at the end of the array for the inner for loop, it is then a unique number, where as if it ever find a number equal to itself it then skips to the end of the inner for loop since we already know after one the number is not unique.
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
int temp2 = 0;
int temp3 = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
temp2 = temp*temp;
for(int j=0;j<size;j++){
temp3 = temp*arr[j];
if(temp2==temp3 && i!=j)
j=arr.length
if(temp2 != temp3 && j==arr.length){
//System.out.println("Match found for "+temp);
flag = false;
result = temp;
break;
}
}
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
not tested but should work
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
int count=0;
for(int j=0;j<size;j++){
if(temp == arr[j]){
count++;
}
}
if (count==1){
result=temp;
break;
}
}
return result;
}
Try:
public class Answer{
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
int[] b =new int[a.length];
//instead of a.length initialize it to maximum element value in a; to avoid
//ArrayIndexOutOfBoundsException
for(int i=0;i<a.length;i++){
int x=a[i];
b[x]++;
}
for(int i=0;i<b.length;i++){
if(b[i]==1){
System.out.println(i); // outputs 2
break;
}
}
}
}
PS: I'm really new to java i usually code in C.
Thanks #dasblinkenlight...followed your method
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
boolean flag = true;
temp = arr[i];
for(int j=0;j<size;j++){
if(temp == arr[j]){
if(i != j){
// System.out.println("Match found for "+temp);
flag = false;
break;
}
}
}
if(flag == true)
result = temp;
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
One disastrous mistake was not enclosing the content of if(i != j) inside braces. Thanks all for your answers.
If you are coding for learning then you can solve it with still more efficiently.
Sort the given array using merge sort of Quick Sort.
Running time will be nlogn.
The idea is to use Binary Search.
Till required element found All elements have first occurrence at even index (0, 2, ..) and next occurrence at odd index (1, 3, …).
After the required element have first occurrence at odd index and next occurrence at even index.
Using above observation you can solve :
a) Find the middle index, say ‘mid’.
b) If ‘mid’ is even, then compare arr[mid] and arr[mid + 1]. If both are same, then the required element after ‘mid’ else before mid.
c) If ‘mid’ is odd, then compare arr[mid] and arr[mid – 1]. If both are same, then the required element after ‘mid’ else before mid.
Another simple way to do so..
public static void main(String[] art) {
int a[] = { 11, 2, 3, 1,1, 6, 2, 5, 8, 3, 2, 11, 8, 4, 6 ,5};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
for (int j = 0; j < a.length; j++) {
if(j==0) {
if(a[j]!=a[j+1]) {
System.out.println("The unique number is :"+a[j]);
}
}else
if(j==a.length-1) {
if(a[j]!=a[j-1]) {
System.out.println("The unique number is :"+a[j]);
}
}else
if(a[j]!=a[j+1] && a[j]!=a[j-1]) {
System.out.println("The unique number is :"+a[j]);
}
}
}
Happy Coding..
Using multiple loops the time complexity is O(n^2), So the effective way to resolve this using HashMap which in the time complexity of O(n). Please find my answer below,
`public static int nonRepeatedNumber(int[] A) {
Map<Integer, Integer> countMap = new HashMap<>();
int result = -1;
for (int i : A) {
if (!countMap.containsKey(i)) {
countMap.put(i, 1);
} else {
countMap.put(i, countMap.get(i) + 1);
}
}
Optional<Entry<Integer, Integer>> optionalEntry = countMap.entrySet().stream()
.filter(e -> e.getValue() == 1).findFirst();
return optionalEntry.isPresent() ? optionalEntry.get().getKey() : -1;
}
}`

Limiting duplicate random numbers

I just want to know how to limit to number of times a random number appears. I have generated random numbers of 1 to 10 and want to limit each number to appear 4 times.
myArray[i][j] = rand.nextInt(11);
for (int i=0; i < myArray.length; i++) {
for (int j=0; j < myArray[i].length; j++) {
myArray[i][j] = rand.nextInt(11);
System.out.print(" " + myArray[i][j]);
The code above creates the randoms numbers. Just want to limit them.
Since you are limited to 10 * 4 = 40 numbers you can use a list and randomize the index :
List<Integer> numbers = new ArrayList<Integer>();
for (int i = 1; i < 11; ++i) {
for (int j = 0; j < 4; ++j)
numbers.add(i);
}
And then when you assign a random number :
int i = rand.nextInt(numbers.size());
myArray[i][j] = numbers.get(i);
numbers.remove(i);
This assumes your two dimensional will not contain more then 40 numbers
My solution stores the result in arrayList:
public class Example {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
final int range = 10;
int[] numbers = new int[range + 1];
int sum = 0;
final int noOfOccurances = 4;
final int size = range * noOfOccurances;
Arrays.fill(numbers, 0);
Random generator = new Random();
List<Integer> numbersArray = new ArrayList<>();
while (sum != size) {
int randomNumber = generator.nextInt(range) + 1;
if (numbers[randomNumber] != noOfOccurances) {
numbers[randomNumber]++;
sum++;
numbersArray.add(randomNumber);
}
}
System.out.println(numbersArray);
}
}
How about storing the count of the generated int's in an array, or Map, or anything?
Map<Integer, Integer> randomCounts = new HashMap<Integer, Integer>();
... your for loops
myArray[i][j] = rand.nextInt(11);
if (randomCounts.containsKey(myArray[i][j])) {
randomCounts.put(myArray[i][j],randomCounts.get(myArray[i][j])+1);
} else {
randomCounts.put(myArray[i][j],1);
}
And if you want to check them, just iterate through your map, and voilá. :)
You can make a method to check if the generated number exists more than 4 times in the array and create a new random number if it does. It should look like this:
import java.util.Random;
public class rndNumberGenerator {
public static void main (String[] args) {
int[][] myArray = new int[2][5];
Random rand = new Random();
int randomNumber;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 5; j++) {
do {
randomNumber = rand.nextInt(11);
} while(overMax(myArray, randomNumber) == true);
myArray[i][j] = randomNumber;
System.out.print(" " + myArray[i][j]);
}
}
}
public static boolean overMax(int[][] array, int number) {
int max = 4;
int count = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 5; j++) {
if (array[i][j] == number) {
count++;
}
}
}
if (count >= max)
return true;
else
return false;
}
}
Hope this helped you, if you have any other questions feel free to ask.
I take suggestion by pshemek (vote up): instead the ArrayList, I use the Set because it can't contain duplicate numbers and you have'nt to espicitate control.
An implementation: the copy{right, left} is of pshemek, I had only extended the idea:)
public class Example {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
int[] numbers = new int[11];
int sum = 0;
final int range = 10;
final int noOfOccurances = 4;
Arrays.fill(numbers, 0);
Random generator = new Random();
Set<Integer> numbersArray = new TreeSet<Integer>();
while (sum != range * noOfOccurances) {
int randomNumber = generator.nextInt(range) + 1;
sum++;//correction for first comment
numbersArray.add(randomNumber); // randomNumber will never be twice: a Set cointains ever one and only one instance of an determinated element
}
System.out.println(numbersArray);
}
}//end class
You could write your own:
public static class CountedRandom {
// My rng.
Random rand = new Random();
// Keeps track of the counts so far.
Map<Integer, Integer> counts = new HashMap<Integer, Integer>();
// The limit I must apply.
final int limit;
public CountedRandom(int limit) {
this.limit = limit;
}
public int nextInt(int l) {
int r;
do {
// Keep getting a new number until we hit one that has'n been overused.
r = rand.nextInt(l);
} while (count(r) >= limit);
return r;
}
private int count(int r) {
// How many times have we seen this one so far.
Integer counted = counts.get(r);
if ( counted == null ) {
// Never!
counted = new Integer(0);
}
// Remember the new value.
counts.put(r, counted + 1);
// Returns 0 first time around.
return counted;
}
}
public void test() {
CountedRandom cr = new CountedRandom(4);
for ( int i = 0; i < 50; i++ ) {
System.out.print(cr.nextInt(4)+",");
}
System.out.println();
}
Note that this will hang if you ask for too may numbers in too small a range (as I have in my test).
Prints
2,0,1,2,1,1,3,3,0,3,0,2,2,0,1,3,
and then hangs.

How can I convert this to work with array lists instead of arrays?

This code takes a random sampling of numbers, plugs them into an array, counts the odd numbers, and then lets the user pick an integer to see if it matches. This works great now with just arrays, but I want to convert it to work with ArrayLists. What's the easiest way to do this?
import java.util.Scanner;
import java.util.Random;
public class ArrayList {
public static void main(String[] args) {
// this code creates a random array of 10 ints.
int[] array = generateRandomArray(10);
// print out the contents of array separated by the delimeter
// specified
printArray(array, ", ");
// count the odd numbers
int oddCount = countOdds(array);
System.out.println("the array has " + oddCount + " odd values");
// prompt the user for an integer value.
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer to find in the array:");
int target = input.nextInt();
// Find the index of target in the generated array.
int index = findValue(array, target);
if (index == -1) {
// target was not found
System.out.println("value " + target + " not found");
} else {
// target was found
System.out.println("value " + target + " found at index " + index);
}
}
public static int[] generateRandomArray(int size) {
// this is the array we are going to fill up with random stuff
int[] rval = new int[size];
Random rand = new Random();
for (int i = 0; i < rval.length; i++) {
rval[i] = rand.nextInt(100);
}
return rval;
}
public static void printArray(int[] array, String delim) {
// your code goes here
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
if (i < array.length - 1)
System.out.print(delim);
else
System.out.print(" ");
}
}
public static int countOdds(int[] array) {
int count = 0;
// your code goes here
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 == 1)
count++;
}
return count;
}
public static int findValue(int[] array, int value) {
// your code goes here
for (int i = 0; i < array.length; i++)
if (array[i] == value)
return i;
return -1;
}
}
I rewrite two of your functions,maybe they will useful for you.
public static List<Integer> generateRandomList(int size) {
// this is the list we are going to fill up with random stuff
List<Integer> rval = new ArrayList<Integer>(size);
Random rand = new Random();
for (int i = 0; i < size; i++) {
rval.add(Integer.valueOf(rand.nextInt(100)));
}
return rval;
}
public static int countOdds(List<Integer> rval) {
int count = 0;
for (Integer temp : rval) {
if (temp.intValue() % 2 == 1) {
count++;
}
}
return count;
}

Categories

Resources