Randomly generated numbers in a basic array - java

I simply need to know what i should do to make so that a basic array is filled with randomly generated numbers. now i know how to do that, what i don't know how to to do is to make it so that the randomly generated numbers are bigger than the last number generated all the way through to the end of the array.

Just generate for the list, and then sort them smallest to largest.
for(int i = 0; i < arr.length; ++i) {
arr[i] = Random.nextInt(100);
}
Arrays.sort(arr);

Generate random numbers, and then sort the array.
You can sort the array using Arrays.sort()
It doesn't make sure that each number is strictly bigger then the previous numbers [it only gurantees <=], so if it is an issue - you will have to make sure you have no dupes in the generated numbers.

You can generate an array of random numbers, and then sort it using Array sort.

There was a comment on the question, I lost the author's name, that recommended adding the randomly generated number to the previous number, which I thought was an interesting approach.
arr[0] = Random.nextInt(100);
for(int i = 1; i < arr.length; ++i) {
arr[i] = arr[i-1] + Random.nextInt(100);
}
This removes the need to sort your result array.

You can have your own algorithm of generating incremental...
For example...
Random each time and add that number to the last one :)
Random class in java does not allow you to have a minim limit where to start.. only one...
For example:
myArray[0] = Random.nextInt(10000);
for(int i=1; i<myArray.length; i++)
{
myArray[i] = myArray[i-1]+Random.nextInt(10000);
}
So.. it's random and you don't have to sort it.. try keeping everything simple...

I'm surprised no one mentioned that we can use SecureRandom API to easily generate random arrays without manually populating it.
For ex. generating a random array of size 100:
SecureRandom random = new SecureRandom();
int arr[] = random.ints(100).toArray();
BTW this should be possible from java 8 onwards.

Related

Algorithm on random generated numbers with guaranteed that all numbers within the range will be selected once

I was having some problem to come out with a solution for a problem, I am currently still in the thought process. So basically the problem is to random generate numbers between 0 to 12, and get the two numbers to perform multiplication within a time frame.
However, the solution provided must guaranteed that the all 169 random generated number pairs must be shown eventually, so cannot just randomly select a number. I was thinking adding a weight to random selected number helps in this case? Or there is better approach for this?
Thanks!
What this boils down to: you don't really want the number pairs to be random, because a random value means that your next value does not depend on any previous value.
Instead, you want 169 known number pairs to come up, each only once, but you want the order of them to be random.
As if these number pairs were printed in playing cards, and you were shuffling the playing cards.
And Java has a nice method for that: Collections.shuffle acts like a professional dealer who shuffles a deck of playing cards.
You want an approach where you first generate all the playing cards, and then shuffle them. Something like this:
List<Integer[]> l = new ArrayList<>();
for (int x = 0; x <= 12; x++) {
for (int y = 0; y <= 12; y++) {
l.add(new Integer[] {x, y});
}
}
Collections.shuffle(l);

Max number from arrays in java

I have created a random program with an array with a lot of values and the frequency of each one, inside it, and I would like the program to find the 5 most frequent numbers is there any way I can do that?
`Here is the code I have already written. 2 random arrays, 2 frequencies, find the 5 numbers withe most frequency out of them:
import java.util.Random;
public class ArrayElementsAsCounters {
public static void main(String[] args){
Random rand = new Random();
int freq[] = new int[46];
int freq2[] = new int[21];
for(int roll=1; roll < 3000000;roll++){
++freq[1+rand.nextInt(45)];
++freq2[1+rand.nextInt(20)];
}
System.out.println("Number\tFrequency");
for(int number1 =1; number1<freq.length;number1++){
System.out.println(number1+"\t"+freq[number1]);
}
System.out.println("Joker\tFrequency");
for(int number2 =1; number2<freq2.length;number2++){
System.out.println(number2+"\t"+freq[number2]);
}
}
}
`
For each value that you have, make them the elements of another array.
This will be the frequency array of the elements.
Now run loop through the original array and each time you encounter an element, add one to its frequency array value.
Then sort the frequency array in descending and starting from the max, print out the first five that are encountered.
Take a look at MultiSets:
https://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multiset.html
You can add all elements into the set and do a sort by count afterwards. Given that the question is broad, I'm just giving guidelines, I'll leave the coding part as an exercise for you to do ;)

Generating Random integers within a range to meet a percentile in java

I am trying to generate random integers within a range to sample a percentile of that range. For example: for range 1 to 100 I would like to select a random sample of 20%. This would result in 20 integers randomly selected for 100.
This is to solve an extremely complex issue and I will post solutions once I get this and a few bugs worked out. I have not used many math packages in java so I appreciate your assistance.
Thanks!
Put all numbers in a arraylist, then shuffle it. Take only the 20 first element of the arraylist:
ArrayList<Integer> randomNumbers = new ArrayList<Integer>();
for(int i = 0; i < 100; i++){
randomNumbers.add((int)(Math.random() * 100 + 1));
}
Collections.shuffle(randomNumbers);
//Then the first 20 elements are your sample
If you want 20 random integers between 1 and one hundred, use Math.random() to generate a value between 0 and 0.999... Then, manipulate this value to fit your range.
int[] random = new int[20];
for(int i =0; i< random.length;i++)
{
random[i] = (int)(Math.random()*100+1);
}
When you multiply Math.random() by 100, you get a value between 0 and 99.999... To this number you add 1, yielding a value between 1.0 and 100.0. Then, I typecasted the number to an integer by using the (int) typecast. This gives a number between 1 and 100 inclusive. Then, store the values into an array.
If you are willing to go with Java 8, you could use some features of lambdas. Presuming that you aren't keeping 20% of petabytes of data, you could do something like this (number is the number of integers in the range to get) it isn't efficient in the slightest, but it works, and is fun if you'd like to do some Java 8. But if this is performance critical, I wouldn't recommend it:
public ArrayList<Integer> sampler(int min, int max, int number){
Random random = new Random();
ArrayList<Integer> generated = new ArrayList<Integer>();
IntStream ints = random.ints(min,max);
Iterator<Integer> it = ints.iterator();
for(int i = 0; i < number; i++){
int k = it.next();
while(generated.contains(k)){
k = it.next();
}
generated.add(k);
}
ints.close();
return generated;
}
If you really need to scale to petabytes of data, you're going to need a solution that doesn't require keeping all your numbers in memory. Even a bit-set, which would compress your numbers to 1 byte per 8 integers, wouldn't fit in memory.
Since you didn't mention the numbers had to be shuffled (just random), you can start counting and randomly decide whether to keep each number or not. Then stream your result to a file or wherever you need it.
Start with this:
long range = 100;
float percentile = 0.20f;
Random rnd = new Random();
for (long i=1; i < range; i++) {
if (rnd.nextFloat() < percentile) {
System.out.println(i);
}
}
You will get about 20 percent of the numbers from 1 to 100, with no duplicates.
As the range goes up, the accuracy will too, so you really wouldn't need any special logic for large data sets.
If an exact number is needed, you would need special logic for smaller data sets, but that's pretty easy to solve using other methods posted here (although I'd still recommend a bit set).

Simple Number to Array with Individual Digits

I am exceptionally new to programming, but I am working on improving my skills as a programmer. Currently, I am working on a problem I gave myself where I am trying to take a variable number and make each of its digits a separate number in an array. I don't care about the order of the digits, so if they are reversed, then it doesn't matter to me. I know people have asked this question numerous times, but they always seem to use a lot of things that I don't understand. Since my school doesn't offer any Java courses, I only know what I have learned on my own, so if you could explain any terms you use in the code that aren't extremely trivial, that would be wonderful. Right now, I have written:
int number = 1234567890;
while (number > 0) {
System.out.println(number%10);
number = number/10;
This works fine for printing the digits individually, but I can't figure out how to add them to the array. I greatly appreciate any help you can give, and please keep in mind that I much prefer simplicity over small size. Thank you in advance!
P.S. Some responses I've seen for similar questions include what I think are arrays of strings. In order for the part of the program that I have working to still work, I think that I need to use an array of integers. If you're curious, the rest of the code is used to determine if the numbers in the array are all different, in order to achieve the final result of determining if a number's digits are all distinct. It looks like this:
int repeats=0;
int[] digitArray;
digitArray = new int[10];
for (int i = 0; i < digitArray.length; i++)
for (int j = 0; j < digitArray.length; j++)
if ((i != j) && (digitArray[i]==digitArray[j])) unique = unique+1;
System.out.println(unique==0);
Method number.toString().length() will return the number of digits. That is the same as the length of your needed array. Then you use your code as before, yet instead of printing you add the digit to the array.
int number = 1234567890;
int len = Integer.toString(number).length();
int[] iarray = new int[len];
for (int index = 0; index < len; index++) {
iarray[index] = number % 10;
number /= 10;
}
I would rather suggest you to use an ArrayList, since to use an array, you would have to allocate the size in advance, for which you need to know the number of digits in your number, which you don't know.
So, either work with an array, and do the iteration over the number twice - once for finding size, and next for doing actual work. Else, move ahead with an ArrayList.
Adding an element to an ArrayList is quite simple. You just need to call - List#add(E) method with appropriate parameter.
So, here's an extension of your solution: -
// Declare a List<Integer>, since it will store integers only.
List<Integer> digits = new ArrayList<Integer>():
int number = 1234567890;
while (number > 0) {
int digit = number % 10; // Store digit in a variable
number = number/10;
// Add digit to the list
digits.add(digit);
}
Alternatively, if you want to have only unique digits in your List, then you should use a HashSet, which automatically removes the duplicates.
With Java 8:
Integer.toString(n).chars().map(a->a-'0').toArray()
char [] arr = scan.next().toCharArray();
This code will read a number from scan.next() and then it is going to give it as an input to char array which will have the number at its indices as single digit by digit.
Hope this will help.

Algorithm for finding all permutations for n alphabets

I wrote the following algorithm for finding all possible permutations of n unique alphabets.
Set<String> results = new HashSet<String>();
int size = 1;
//find the total permutations possible
for(int i=0;i<array.length;i++){
size*=(i+1);
}
// i is the number of items remaining to be shuffled.
while(results.size()<size){
for (int i = array.length; i > 1; i--) {
// Pick a random element to swap with the i-th element.
int j = rng.nextInt(i); // 0 <= j <= i-1 (0-based array)
// Swap array elements.
char tmp = array[j];
array[j] = array[i-1];
array[i-1] = tmp;
}
StringBuffer str = new StringBuffer();
for(int i=0;i<array.length;i++)
str.append(array[i]);
results.add(str.toString());
}
System.out.println(results);
1) Is there anything to be done to improve this algorithm?
2) What would be the time complexity of this algorithm?
PS: I apologize to the people who who reacted to my previous post. I'll try on my own before asking for help.
By utilizing a random shuffling, you're going to have a massive number of iterations that end up not actually putting a new item into the set - you should look for an approach that ensures that on each iteration a new item is placed into the set (by 'new' I simply mean a permutation that hasn't been seen previously).
I wouldn't like to guess at the time complexity of the algorithm supplied above - it's going to be big.
1) Is there anything to be done to improve this algorithm?
Yes. Just to give you some hints how you could generate the permutations deterministically:
imagine the lexicographic order of all permutations on N elements. Imagine, how could you generate the next permutation in that order given the previous
think about what would the set of permutations with a common prefix (eg. 435 126, 435 162 etc.) be and how could you use it in an algorithm.
The best way to generate permutations is to do so iteratively: finding a scheme to go from one permutation to the next until you've seen them all. Knuth has exposed such a scheme in one of the combinatorial fascicles of TAOCP, and without going into his assembly-like pseudo code, you might want to check these nifty C implementation of those algorithms. The algorithm you are looking for is the one that generates permutations.
The advantage of such an algorithm by opposition to (what I understand of) yours, is that it is deterministic and will generate a different permutation every single time.
Thank you for your inputs. I think I have got a better algorithm. Please provide comments
private static List<String> allPerms(char[] array) {
List<String> perms = new ArrayList<String>();
if(array.length<=1 )
perms.add(String.valueOf(array[0]));
else{
char[] newarray = Arrays.copyOf(array, array.length-1);
char lastChar = array[array.length-1];
List<String> soFar = allPerms(newarray);
for(int i=0; i<soFar.size(); i++) {
String curr = soFar.get(i);
for(int j=0;j<array.length;j++){
StringBuffer buff = new StringBuffer(curr);
perms.add(buff.insert(j, lastChar).toString());
}
}
}
return perms; }

Categories