I realize this has been asked before and I had a look at it but, for me, it only works to a point. After some struggle, I thought I'd ask.
I have an array of floats in an object's constructor.
That goes like this:
count = 3;
angles = new float[count];
The array length is really small though I'd like implement a modular and reusable approach.
I loop through the array assigning floats:
for (int i = 0; i < angles.length; i++) {
angles[i] = radians(random(360));
}
Then, with a new loop, I check if the singular elements have less than 30 degrees in between them, and if so, assign a new random value:
for (int i = 0; i < angles.length; i++) {
for (int k = i+1; k < angles.length; k++){
if(angles[i] != angles[k]){
if(abs(angles[i] - angles[k]) <= radians(30)){
angles[i] = radians(random(360));
}
}
}
}
This works nice and well but it doesn't guarantee that the new random number will keep the 30 degrees limit with the remaining elements. This, I assume, has to do with the length of the 'for' loop.
What would be the best way to overcome this and guarantee that newly fetched number will always conform to the 30 degree rule?
Instead of just checking once with an if statement, you could change it to a while statement, so that it attempts to find a new random number until the new one works.
while (abs(angles[i] - angles[k]) <= radians(30)){
angles[i] = radians(random(360));
}
However, if there are no numbers that follow your 30 degree rule, your program will get stuck in this loop, so you might want to check that there is a possible solution before entering the loop.
Edit: the above solution will ensure that the number follows the 30 degree rule with only one number in your array. Add a boolean to determine if the condition has been met, and loop until the boolean is true.
for (int i = 0; i < angles.length; i++) {
boolean meetsCondition = false;
while (!meetsCondition) {
for (int k = 0; k < angles.length; k++){
if(i != k){
if(abs(angles[i] - angles[k]) <= radians(30)){
angles[i] = radians(random(360));
meetsCondition = false;
break;
}
}
}
meetsCondition = true; //if the for loop completes, it has met the condition.
}
}
Why not use recursion earlier on:
for (int i = 0; i < angles.length; i++) {
angles[i] = findSuitable( i==0 ? 0 : angles[i-1] )
}
...
float findSuitable(float limit){
float sample = radians(random(360));
if(Math.abs(sample-limit) > 30)
return sample;
else
return findSuitable(limit);
}
In my opinion, you can try to change the the codes of random to this:
Random d = new Random();
int a = d.nextInt(360);
Related
Right now I have the following idea:
int WORK[] = new int[]{5, 4, 3};
int release[] = new int[]{3, 2, 3};
boolean check = false;
for (int i = 0; i < WORK.length; i++)
{
if (WORK[i] >= release[i])
{
for (int j = 0; j < WORK.length; j++)
{
if (WORK[j] >= release[j])
{
for (int k = 0; k < WORK.length; k++)
{
if (WORK[k] >= release[k])
{
check = true;
System.out.print("All elements in work are bigger than release");
break;
}
}
break;
}
}
break;
}
}
if(!check)
{
System.out.print("Not every element in work is bigger than release");
}
Now I want to know if there is a more efficient way to do this? But my main problem is that I need to do this with n elements. With `n´ elements it is not efficient neither useful, because I don't know how many elements will be there.
What I want to know is there a function in Java Arrays or something, which could help me?
Any help?
With Java 8, you can do this in a functional style with streams (this would not be a performance optimization; it's just less code to write).
IntPredicate lowerThanRelease = i -> IntStream.of(release).allMatch(j -> i <= j);
boolean allLower = IntStream.of(work).allMatch(lowerThanRelease);
One efficient way to do this is two have 4 variables
workmax, workmin, needmax, needmin.
Iterate through both arrays one at a time and find the max and min values within that array. Then all you need to do is compare the min value of one array with max value of the second array
This way you just need two loops (no nesting).
Then its a matter of simple comparison.
e.g.
if (workmin > needmax) then System.out.print("All elements in " + work + "are bigger than need");
I think you can come up with the code if you understand the approach mentioned above.
I hope I got your question correctly.
if (array1.length == array2.length) {
for (int i = 0; i < array1.length; i++) {
for (int j =0; j < array2.length; j++) {
// compare array1[i] with array2[j];
}
}
} else {
System.out.println("Arrays have different lengths.");
}
This gives you the opportunity to compare all numbers of one array with all numbers of the second. So your basic idea was not that bad.
Hope it helps.
This one seems very basic, but it should do it.
I'm trying to find a way to fill a 2d array of length n with boolean values randomly. The array must have an equal amount of each value if n is even, and if n is odd the extra value must be the same boolean each and every time (doesn't matter which one). Any tips on how to do this in Java? I'm currently shuffling arrays that I make with equal amounts of both values, but this isn't truly random because there will always be n/2 (or n/2+1 and n/2-1 for the odd ns) of each value.
Any advice?
Given your requirements, filling the array with the amount you need, then shuffling it, is a good solution.
Make sure to use a truly random shuffling algorithm, such as the Fisher-Yates shuffle, not the "swap a random pair a bunch of times" method. If you're using Collections.shuffle or similar, you don't need to worry about this.
Adapting the Fisher-Yates shuffle to a 2D array is probably the simplest approach.
boolean[][] array = new boolean[rows][cols];
boolean alternating = false;
Random random = new Random();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
int k = random.nextInt(i * cols + j + 1);
int swapRow = k / cols;
int swapCol = k % cols;
boolean tmp = array[swapRow][swapCol];
array[swapRow][swapCol] = alternating;
array[i][j] = tmp;
alternating = !alternating;
}
}
This is pretty much a verbatim implementation of http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_.22inside-out.22_algorithm , except that we're filling the array as we go with falses and trues.
A different approach might be to randomise the position you are placing the next value rather than the value itself. You know ahead of time exactly how many of each value you are placing.
Something like:
List<Integer> indicesList = IntStream.range(0, n * n).collect(Collectors.toList());
Collections.shuffle(indicesList);
indicesList.stream().forEach(n -> array[n % size][n / size] = (n % 2 == 0));
By my understanding that should give you completely random placement of your values and an equal number of each.
Here's a real simple solution a coworker came up with. It looks to me like it would work and be truly random (please let me know if not, I have terrible intuition about that kind of thing), although it's definitely ugly. Would be pretty efficient compared to a shuffle I imagine.
public boolean[][] generateRandom2dBooleanArray(int length) {
int numFalses = (length*length)/2;
int numTrues = (length*length)/2;
if ((length*length)%2!=0) numTrues++;
boolean[][] array = new boolean[length][length];
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (Math.random() > 0.5) {//Or is it >= 0.5?
if (numTrues >= 0) {
array[i][j] = true;
numTrues--;
} else {
//Since boolean arrays are false by default, you could probably just break here to get the right anser, but...
array[i][j] = false;
numFalses--;
}
} else {
if (numFalses >= 0) {
array[i][j] = false;
numFalses--;
} else {
array[i][j] = true;
numTrues--;
}
}
}
}
}
return array;
}
Please bear within as it might be difficult to understand
I have an array of jbuttons 50 size big, for this example ill use 7 I have jbutton object within 1 2 3 4 6 7 but not 5. These are printed on the screen. I want to remove these jbuttons however all buttons up to 5 are removed while the last two are not.
for(int i = 1; i < 51; i++){
if(seat.buttonArray[i] == null){
remove(seat.buttonArray[i]);
seat.buttonArray[i] = null;}
}
There is no way to remove element from array, assuming you want latter indexes changed after remove. For this purpose, you should use List:
Iterator buttonIterator = seat.buttonList.iterator();
while (buttonIterator.hasNext()) {
Object button = buttonIterator.next(); //or more specific type, if your list was generified
if (button == null) { //or some other criteria, wrote this just as an example
buttonIterator.remove();
}
}
If using array is mandatory, you have two options:
Set seat.buttonArray[i] to null value, indicating it has been removed;
Recreate array each time you deleted something. See System.arraycopy javadoc for details, although I do not recommend this approach because of performance considerations.
You could store the values in a temp array and then copy what you want back into your original array. Somewhat similar to this:
int myArray[50];
int temp[50];
int good;
for (int i = 0; i < 50; i++) {
myArray[i] = i;
}
for (int i = 0; i < 50; i++) {
temp[i] = myArray[i];
}
good = 0;
for (int i = 0; i < 50; i++) {
if (i < 10) {
} else {
myArray[good] = temp[i];
good += 1;
}
}
Looks messier than I first thought... But it essentially does what you're wanting.
After my array in the for loop reaches the last index, I get an exception saying that the index is out of bounds. What I wanted is for it to go back to the first index until z is equal to ctr. How can I do that?
My code:
char res;
int ctr = 10
char[] flames = {'F','L','A','M','E','S'};
for(int z = 0; z < ctr-1; z++){
res = (flames[z]);
jLabel1.setText(String.valueOf(res));
}
You need to use an index that is limited to the size of the array. More precisely, and esoterically speaking, you need to map the for-loop iterations {0..9} to the valid indexes for the flame array {0..flames.length()-1}, which are the same, in this case, to {0..5}.
When the loop iterates from 0 to 5, the mapping is trivial. When the loop iterates a 6th time, then you need to map it back to array index 0, when it iterates to the 7th time, you map it to array index 1, and so on.
== Naïve Way ==
for(int z = 0, j = 0; z < ctr-1; z++, j++)
{
if ( j >= flames.length() )
{
j = 0; // reset back to the beginning
}
res = (flames[j]);
jLabel1.setText(String.valueOf(res));
}
== A More Appropriate Way ==
Then you can refine this by realizing flames.length() is an invariant, which you move out of a for-loop.
final int n = flames.length();
for(int z = 0, j = 0; z < ctr-1; z++, j++)
{
if ( j >= n )
{
j = 0; // reset back to the beginning
}
res = (flames[j]);
jLabel1.setText(String.valueOf(res));
}
== How To Do It ==
Now, if you are paying attention, you can see we are simply doing modular arithmetic on the index. So, if we use the modular (%) operator, we can simplify your code:
final int n = flames.length();
for(int z = 0; z < ctr-1; z++)
{
res = (flames[z % n]);
jLabel1.setText(String.valueOf(res));
}
When working with problems like this, think about function mappings, from a Domain (in this case, for loop iterations) to a Range (valid array indices).
More importantly, work it out on paper before you even begin to code. That will take you a long way towards solving these type of elemental problems.
While luis.espinal answer, performance-wise, is better I think you should also take a look into Iterator's as they will give you greater flexibility reading back-and-forth.
Meaning that you could just as easy write FLAMESFLAMES as FLAMESSEMALF, etc...
int ctr = 10;
List<Character> flames = Arrays.asList('F','L','A','M','E','S');
Iterator it = flames.iterator();
for(int z=0; z<ctr-1; z++) {
if(!it.hasNext()) // if you are at the end of the list reset iterator
it = flames.iterator();
System.out.println(it.next().toString()); // use the element
}
Out of curiosity doing this loop 1M times (avg result from 100 samples) takes:
using modulo: 51ms
using iterators: 95ms
using guava cycle iterators: 453ms
Edit:
Cycle iterators, as lbalazscs nicely put it, are even more elegant. They come at a price, and Guava implementation is 4 times slower. You could roll your own implementation, tough.
// guava example of cycle iterators
Iterator<Character> iterator = Iterators.cycle(flames);
for (int z = 0; z < ctr - 1; z++) {
res = iterator.next();
}
You should use % to force the index stay within flames.length so that they make valid index
int len = flames.length;
for(int z = 0; z < ctr-1; z++){
res = (flames[z % len]);
jLabel1.setText(String.valueOf(res));
}
You can try the following:-
char res;
int ctr = 10
char[] flames = {'F','L','A','M','E','S'};
int n = flames.length();
for(int z = 0; z < ctr-1; z++){
res = flames[z %n];
jLabel1.setText(String.valueOf(res));
}
Here is how I would do this:
String flames = "FLAMES";
int ctr = 10;
textLoop(flames.toCharArray(), jLabel1, ctr);
The textLoop method:
void textLoop(Iterable<Character> text, JLabel jLabel, int count){
int idx = 0;
while(true)
for(char ch: text){
jLabel.setText(String.valueOf(ch));
if(++idx < count) return;
}
}
EDIT: found a bug in the code (idx needed to be initialized outside the loop). It's fixed now. I've also refactored it into a seperate function.
I have the following code to set 10 random values to true in a boolean[][]:
bommaker = new boolean[10][10];
int a = 0;
int b = 0;
for (int i=0; i<=9; i++) {
a = randomizer.nextInt(9);
b = randomizer.nextInt(9);
bommaker[a][b] = true;
}
However, with this code, it is possible to have the same value generated, and therefore have less then 10 values set to random. I need to build in a checker, if the value isn't already taken. And if it is already taken, then it needs to redo the randomizing. But I have no idea how to do that. Can someone help me?
simplest solution, not the best:
for (int i=0; i<=9; i++) {
do {
a = randomizer.nextInt(10);
b = randomizer.nextInt(10);
} while (bommaker[a][b]);
bommaker[a][b] = true;
}
You're problem is similar to drawing cards at random from a deck if I'm not mistaken...
But first... The following:
randomizer.nextInt(9)
will not do what you want because it shall return an integer between [0..8] included (instead of [0..9]).
Here's Jeff's take on the subject of shuffling:
http://www.codinghorror.com/blog/2007/12/shuffling.html
To pick x spot at random, you could shuffle your 100 spot and keep the first 10 spots.
Now of course seen that you'll have only 10% of all the spots taken, simply retrying if a spot is already taken is going to work too in reasonable time.
But if you were to pick, say, 50 spots out of 100, then shuffling a list from [0..99] and keeping the 50 first value would be best.
For example here's how you could code it in Java (now if speed is an issue you'd use an array of primitives and a shuffle on the primitives array):
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i < 100; i++) {
l.add(i);
}
Collections.shuffle(l);
for (int i = 0; i < n; i++) {
a[l.get(i)/10][l.get(i)%10] = true;
}