Generate k distinct numbers less than n - java

The task is this: generate k distinct positive numbers less than n without duplication.
My method is the following.
First create array size of k where we should write these numbers:
int a[] = new int[k];
//Now I am going to create another array where I check if (at given number
//position is 1 then generate number again, else put this number in an
//array and continue cycle.
I put a piece here of code and explanations.
int a[]=new int[k];
int t[]=new int[n+1];
Random r=new Random();
for (int i==0;i<t.length;i++){
t[i]=0;//initialize it to zero
}
int m=0;//initialize it also
for (int i=0;i<a.length;i++){
m=r.nextInt(n);//random element between 0 and n
if (t[m]==1){
//I have problems with this. I want in case of duplication element
//occurs repeat this steps afain until there will be different number.
else{
t[m]=1;
x[i]=m;
}
}
So I fill concret my problem: if t[m]==1. It means that this element occurs already so I want to
generate a new number, but problem is that number of generated numbers will
not be k because if i==0 and occurs duplicate element and we write continue then it will switch at i==1.
I need like goto for the repeat step. Or:
for (int i=0;i<x.length;i++){
loop:
m=r.nextInt(n);
if ( x[m]==1){
continue loop;
}
else{
x[m]=1;
a[i]=m;
continue; //Continue next step at i=1 and so on.
}
}
I need this code in Java.

It seems that you need a random sampling algorithm. You want to be able to choose m random items from the set {0,1,2,3...,n-1}.
See this post, where I wrote about 5 efficient algorithms for random sampling.
Following is Floyd's implementation, which can be useful in your case:
private static Random rnd = new Random();
...
public static Set<Integer> randomSample(int n, int m){
HashSet<Integer> res = new HashSet<Integer>(m);
for(int i = n - m; i < n; i++){
int item = rnd.nextInt(i + 1);
if (res.contains(item))
res.add(i);
else
res.add(item);
}
return res;
}

Create an array arr with n elements (1..n);
for i=1 to k {
result[i] = arr[rand]
delete arr[result[1]]
}

Related

How do I get the code to print random numbers in all the elements of the 2d array?

I got the 2d array to print but with all zero's and the only random number comes up on the bottom right corner
How do I get the code to print random numbers in all the elements of the 2d array?
Here is my code:
public static void main(String[] args) {
int columns = 8;
int rows = 4;
int rLow = 2;
int rHigh = 9;
printRandos(columns, rows, rLow, rHigh);
}
public static void printRandos(int clmn, int rws, int rlow, int rhigh) {
Random rando = new Random();
int randoNum = rlow + rando.nextInt(rhigh);
int[][] randoArray = new int[rws][clmn];
for (int i = 0; i < rws; i++) {
for (int k = 0; k < clmn; k++) {
randoArray[rws - 1][clmn - 1] = randoNum;
System.out.print(randoArray[i][k] + " ");
}
System.out.print("\n");
}
}
for (int i = 0; i < rws; i++)
{
for (int k = 0; k < clmn; k++)
{
int randoNum = rlow + rando.nextInt(rhigh);
randoArray[i][k] = randoNum;
System.out.print(randoArray[i][k]+" ");
}
System.out.print("\n");
}
your mistake inside the inner for loop of the printRandos method. Firstly your random number is outside the loop so your array elements were receiving the same number all the time. Another mistake is that you are assigning the value to the same array element all the time i.e rws-1 and clmn-1 .
inside your inner loop replace it with this:
int randoNum = rlow + rando.nextInt(rhigh);
randoArray[i][k] = randoNum;
System.out.print(randoArray[i][k]+" ");
Your bug is in this line:
randoArray[rws-1][clmn-1] = randoNum;
This stores your random number into randoArray[rws-1][clmn-1] each time, which as you noticed, is the bottom right corner. rws is always 4, and clmn is always 8. So you store the same number there 32 times, which gives the same result as storing it only once.
In the following line you are correctly printing the number from the current array location:
System.out.print(randoArray[i][k]+" ");
An int array comes initialized with all zeroes, and since except for the last corner you have not filled anything into your array, 0 is printed.
Also if you want different random numbers in all the cells, you would need to call rando.nextInt() inside your innermost for loop.
Unless you need this 2-D array for some purpose (which doesn't show from the minimal example code that you have posted), you do not need it for printing a matrix of random numbers, i.e., you may just print the numbers form within your loop without putting them into the array first.
Finally if rhigh should be the highest possible random number in the array, you should use rando.nextInt(rhigh - rlow + 1). With rlow equal to 2 and rhigh equal to 9 this will give numbers in the range from 0 inclusive to 9 - 2 + 1 = 8 exclusive, which means that after adding to rlow = 2 you will get a number in the range from 2 to 10 exclusive, in other words, to 9 inclusive.
I am on purpose leaving to yourself to fix your code based on my comments. I believe your learning will benefit more from working it out yourself.
Your assign the array value outside the array length
int[][] randoArray = new int[rws][clmn];
randoArray[rws][clmn] = randoNum;
Here randoArray[rws] is out of bounds.

What is this method doing? (Arrays and random numbers)

My textbook gave me this code to help count the amount of times a certain number shows up in an array of integers. I tried to apply the code my textbook gave me to my assignment but it doesn't seem to be working. Basically, I have to generate 30 random integers in an array, with the upper bound being 15 and lower bond being -5.
I want to find out how many times a number in the array is equal to 0, 1, 2... all the way until 10. The first code is the one my textbook gave me. They also used a random number generator but instead of finding how many elements is equal to 0, 1, etc, they want to find how many times each number appears. (The scores array is simply the random number generator, and their upper bound is 100). The second code is mine.
int[] counts = new int [100];
for (int i = 0; i < scores.length; i++) {
int index = scores[i];
counts[index]++;
}
//This is my code
public static void main(String[] args) {
int []a = arrayHist ();
printArray (a);
}
public static int randomInt (int low, int high) {
int range = (high - low) +1;
return (int) (Math.random() * range) + low;
}
public static int[] randomIntArray (int x) {
int[] random = new int[x];
for (int i = 0; i< x; i++) {
random [i] = randomInt (-5, 15);
}
return random;
}
public static int[] arrayHist () {
int[] counts = new int [30];
int[] hist = randomIntArray (30);
for (int i = 0; i < 10 && i >= 0; i++) {
int index = hist[i];
counts[index]++;
}
return hist;
}
public static void printArray (int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println (a[i]);
}
}
I'm supposed to be getting only 11 elements, but instead I get 30 random numbers again. Why is that?
I'll put some comments in your code, and see if you can spot where it goes wrong:
//take a histogram of the array. We're only going to count values between 0 and 10
//so 25th to 75 centiles, ignoring values that are lower than 0 or higher than 10
public static int[] arrayHist () {
//need to make an array of 11 numbers for the counts
int[] counts = new int [30];
//get an array of 30 random numbers
int[] hist = randomIntArray (30);
//loop over the whole array of 30 numbers
for (int i = 0; i < 10 && i >= 0; i++) {
//retrieve the random number into a variable temporarily
int index = hist[i];
//if the value is too low or too high, skip it
//else, store it in the counts array - the value from the random array
//serves as the index position in the counts array
counts[index]++;
}
//return the counts array
return hist;
}
What I've done with my comments is equivalent to designing the algorithm using the language you think in (English) and then you can translate it into the language you're learning (java). Very few developers think in the programming language they write. As a student I recommend you should ALWAYS write comments to explain your algorithm to yourself before you write code underneath the comments. You get points for writing comments (usually) so if you write them first then a) it helps you write the code and b) you don't have the tedious job of writing comments after you get the code working
Please please, for your own good/learning, try working out what is wrong from the above before looking at the spoilers(answers) below. Roll the mouse over the box to display the spoilers
//loop over the whole array of 30 numbers - YOU ONLY LOOP 10
for (int i = 0; i < 10 && i >= 0; i++) {
//if the value is too low or too high, skip it - YOU DIDN'T DO THIS CHECK
...
}
//return the counts array - YOU RETURNED THE WRONG ARRAY
return hist;
Edits in response to comments:
Checking a range
You'll have to check two limits, and hence it will need to be of one of the following forms:
if(x < 0 || x > 10) then don't do the count
if(!(x >= 0 && x <= 10)) then don't do the count
if(x >= 0 && x <= 10) then do the count
if(!(x < 0 || x > 10)) then do the count
Tests that use NOT - the exclamation mark ! - are typically a bit harder to read and understand, so try to avoid them is possible. Tests that are "positive minded" - i.e. they return a positive result rather than a negative that needs to be negated - are easier to read and understand.
A helpful tip for loops and methods, in terms of error checking, is to test for bad values that meet certain conditions, and if a bad value is encountered, then skip processing the rest of the loop (using the continue) keyword, or skip the rest of the method (by returning from it)
Doing this means that your if body (the bit between { and } ) doesnt get massive. Compare:
for(...){
if(test for bad values)
continue;
//50 lines long loop body
}
Is neater than doing:
for(...){
if(test for goodvalues){
//50 lines long loop body
}
}
If you use the bottom pattern, you can end up after several IFs in a real indented mess, with { and } all over the place and your code is way over to the right hand side of the screen:
for(...){
//code
if(...){
//code
if(...){
//code
if(...){
//code
if(...){
//code
if(...){
//code
if(...){
//code
}
//code
}
//code
}
//code
}
//code
}
//code
}
//code
}
Keeping indent levels to a minimum helps make your code more readable
Hence, I recommend in your case, that rather than test for the value being inside the range 0 to 10 and doing something with it, you adopt the form "if value is OUTSIDE" the range 0 to 10, skip doing the rest of the loop
Your arrayHist() method just returns the array with the random numbers. It should be more like this:
public static int[] arrayHist() {
// generate array with random numbers
int[] hist = randomIntArray(30);
// initialize the array for counting
int[] counts = new int[11];
// step through the random numbers array and increase corresponding counter if the number's values is between 0 and 10
for (int j = 0; j < hist.length; j++) {
int number = hist[j];
if (number > -1 && number < 11) {
counts[number]++;
}
}
return counts;
}

Random number generator without replacement?

I have tried to program a random number generator that doesn't generate the same random number more than once. But I am unable to and can't figure out why. My code is like this at the moment:
public void printNS(){
System.out.print("Numeros Numeros: ");
for(int i=0; i < 5 ; i++){
System.out.print( (int)(Math.random()*50) + ",");
}
System.out.print("; Numeros Stars: ");
for(int i=0; i < 2 ; i++){
System.out.print( (int)(Math.random()*12)+ ",");
}
}
in java 8 you can do the following
int[] rand = new Random().ints(start, end).distinct().limit(number).toArray();
for more details/options see the doc
And before java 8 you can use a Set. Generate the random numbers until your set size is less than the desired number of random numbers
So you want k distinct random numbers from 0 to n (with k < n).
Two possible approaches:
Pick k random numbers, as you already did, and store them in a data structure. Everytime you pick a number, check if it is already contained in the structure: if it is, keep picking until you have a "new" random number. It is a simple enough approach but the loop could potentially block your application. I suggest to use a Set since it stores distinct elements by definition
Set<Integer> set = new LinkedHashSet<>(); // unordered
while (set.size() < k){
set.add((int)(Math.random()*n));
}
System.out.println(set);
Create a List and initialize it with every number between 0 and n. Then shuffle it. First k elements of the list are the numbers you want.
List<Integer> list = new ArrayList<>(n);
for (int i = 0; i < n; i++){
list.add(i);
}
Collections.shuffle(list);
list.subList(0, k).clear();
System.out.println(list);
I would suggest the second approach as it is more clean, I don't know your efficiency requirements though.
Here:
private printStars(int loops, int factor) {
for(int i=0; i < loops ; i++){
System.out.print( (int)(Math.random()*factor) + ",");
}
And now:
public void printNS(){
System.out.print("Numeros Numeros: ");
printStars(5, 50);
System.out.print("; Numeros Stars: ");
printStars(2, 12);
Hope that helps. The key point is: when you have repeating code, look at those elements that are "identical"; and then move them into another method!

Two sum - Doesn't work

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Consider input [3,2,4] and target is 6. I added (3,0) and (2,1) to the map and when I come to 4 and calculate value as 6 - 4 as 2 and when I check if 2 is a key present in map or not, it does not go in if loop.
I should get output as [1,2] which are the indices for 2 and 4 respectively
public int[] twoSum(int[] nums, int target) {
int len = nums.length;
int[] arr = new int[2];
Map<Integer,Integer> map = new HashMap<Integer,Integer>();
for(int i = 0;i < len; i++)
{
int value = nums[i] - target;
if(map.containsKey(value))
{
System.out.println("Hello");
arr[0] = value;
arr[1] = map.get(value);
return arr;
}
else
{
map.put(nums[i],i);
}
}
return null;
}
I don't get where the problem is, please help me out
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice. Consider input [3,2,4] and target is 6. I added (3,0) and (2,1) to the map and when I come to 4 and calculate value as 6 - 4 as 2 and when I check if 2 is a key present in map or not, it does not go in if loop.
Okay, let's take a step back for a second.
You have a list of values, [3,2,4]. You need to know which two will add up 6, well, by looking at it we know that the answer should be [1,2] (values 2 and 4)
The question now is, how do you do that programmatically
The solution is (to be honest), very simple, you need two loops, this allows you to compare each element in the list with every other element in the list
for (int outter = 0; outter < values.length; outter++) {
int outterValue = values[outter];
for (int inner = 0; inner < values.length; inner++) {
if (inner != outter) { // Don't want to compare the same index
int innerValue = values[inner];
if (innerValue + outterValue == targetValue) {
// The outter and inner indices now form the answer
}
}
}
}
While not highly efficient (yes, it would be easy to optimise the inner loop, but given the OP's current attempt, I forewent it), this is VERY simple example of how you might achieve what is actually a very common problem
int value = nums[i] - target;
Your subtraction is backwards, as nums[i] is probably smaller than target. So value is getting set to a negative number. The following would be better:
int value = target - nums[i];
(Fixing this won't fix your whole program, but it explains why you're getting the behavior that you are.)
This code for twoSum might help you. For the inputs of integer array, it will return the indices of the array if the sum of the values = target.
public static int[] twoSum(int[] nums, int target) {
int[] indices = new int[2];
outerloop:
for(int i = 0; i < nums.length; i++){
for(int j = 0; j < nums.length; j++){
if((nums[i]+nums[j]) == target){
indices[0] = i;
indices[1] = j;
break outerloop;
}
}
}
return indices;
}
You can call the function using
int[] num = {1,2,3};
int[] out = twoSum(num,4);
System.out.println(out[0]);
System.out.println(out[1]);
Output:
0
2
You should update the way you compute for the value as follows:
int value = target - nums[i];
You can also check this video if you want to better visualize it. It includes Brute force and Linear approach:

Randomly choose int number

I do have the following code for taking random int numbers
for (int i=1;i<=5;i++) {
int rand= new Random().nextInt(10);
Log.d("Ramdom number", String.valueOf(rand));
}
The problem is that I dont want random numbers to be repeated, mean when I run this code it gives to me 5 numbers but two of them at least repeats. Any advice?
For a small range of numbers to choose from, this should do the trick:
ArrayList<Integer> numbers = new ArrayList<Integer>();
for (int i = 0; i < 20; ++i) {
numbers.add(i);
}
Collections.shuffle(numbers);
for (int i = 0; i < 5; ++i) {
Log.d("Random number", numbers.get(i).toString());
}
The problem is that you are creating a Random object within the loop. If the loop is a 'tight', as in this case, the Random object will be seeded with the same value. Moving the Random object initialization outside the loop should do the trick.
Random r = new Random();
for (int i=1;i<=5;i++) {
int rand= r.nextInt(10)
Log.d("Ramdom number", String.valueOf(rand));
}
EDIT:
This should work (at least it did for me)
public static Integer[] getRangedInt(int maxRange, int numCount)
{
if (maxRange < numCount)
{
throw new Exception("maxRange cannot be smaller than numCount");
}
Set<Integer set = new HashSet<Integer>();
Random r = new Random();
while (Set.size() < numCount)
{
int random = r.nextInt(maxRange);
while (!set.add(random))
{
random = r.nextInt(maxRange);
}
}
return set.toArray(new Integer[set.size()]);
}
final int maxnumbers = 5;
final int maxvalue = 10;
final Random generator = new Random();
Set<Integer> numbers = new HashSet<Integer>();
while(numbers.size() < maxnumbers){
numbers.add(random.nextInt(maxvalue));
}
After this loop you should have maxnumber non-repeating random numbers between 0 and maxvalue in the set numbers. You have to watch out so you don't get too many iterations when using this method, i.e. generating 9999 non-repeating numbers out of 10000 would probably take a long time.
Another more scalable version would be to have a list of numbers:
List<Integer> numbers = new ArrayList<Integer>();
for(int i = 0; i<maxvalue; i++){ numbers.add(i); }
Collections.shuffle(numbers);
List<Integer> randomnums = numbers.subList(0, maxnumbers);
I think you need a SET of random numbers. This hint should suffice.
If not, then please comment.
You can maintain one list of generated numbers
boolean flag=false;
Vector<int> vec = new Vector<int>();
for (int i=1;i<=5;i++) {
flag=false;
int rand= r.nextInt(10);
for(int j=0;j<vec.size();j++)
{
if(vec.get(j)==rand)
{
flag=true;
break;
}
}
if(flag)
{
continue;
}
else
{
Log.d("Ramdom number", String.valueOf(rand));
vec.add(rand);
}
}
You can maintain a vector of generated numbers and check
Is that number already generated then generate new one
else display this number
So what you're looking for isn't a list of random numbers, it's a list of 30 numbers randomly ordered.
One way is to generate a list of all possible values, then order them randomly, then peel them from the front of the list as needed. Here's some pseudocode:
for(int i=1; i<=30; i++) {
double r = rand();
while (null != aTreeSet.get(r)) r = rand();
aTreeSet.put(r, i);
}
where rand() returns some random value (not the 1-30 you seek, that's i) perhaps between 0 and 1 and aTreeSet is what you think.
The loop prevents sadness in the unlikely event of a dup being returned by rand().
To use this, pull values from aTreeSet in sorted order.
edit - Gross solution
Another way is to generate the 1-30 value, and if it isn't already in a "I have seen this" Set, add it and return the value. if it is there, generate a new random number. Repeat until an unused number is discovered. This performs poorly, relatively speaking, for the last few values. For 30 values on modern processors, it will get done in milliseconds, of course. If your max value was 1,000 instead of 30, I'd start getting concerned.
What you want is a random combination, use a Hash table to avoid repetitions
From the top of my head the code should be something like:
Ramdom r = new Random();
Hashtable<Integer, Integer> h = new Hashtable<Integer, Integer>();
while( h.keys().size() < 5 ) {
int i = r.nextInt(10);
h.put(i,i);
}
Integer[] k = (Integer[]) h.keySet().toArray();
The line
h.put(i,i);
just overrides the value if it is repeated, so only different drawn numbers will have entries in the hash table.
You can save your generated numbers in a Set and use the random number only if it is not in the set
Random r = new Random();
Set<Integer> generatedNumbers = new HashSet<Integer>();
for(int i = 1;i<=5;i++) {
int rand = r.nextInt(10)
if (!generatedNumbers.contains(rand)) {
Log.d("Ramdom number", String.valueOf(rand));
generatedNumbers.add(rand);
}
}

Categories

Resources