I am having a really stupid problem that has been bugging me for a couple of hours now. I have made a program to compare slope of an Array of points and draw a line through four points with the same slope. My problem is I take the initial slope as a comparator to each slope. Then compare the inital value to each other point in the array and if the slope of the initial comparator is the same as the next slope the counter increments. my problem is I done want the initial slope to change during the for loops but I cant get it to work. The code is below, I know im being kind of vague so if you need any more information just ask.
for(int initial = 0; initial < counter/2 ; initial ++)
{
int comparator = 1;
for(int next = 1 ; next < counter/2 ; initial ++)
{
Point finalCompare = points[initial];
Point initialCompare = points[comparator];
Point initialPoint = points[initial];
int counter_2 = 0;
Point nextPoint = points[next];
double initialSlope = (initialCompare.y - initialPoint.y/ initialCompare.x-initialPoint.x);
double nextSlope = (nextPoint.y - initialPoint.y/ nextPoint.x - initialPoint.x);
if(initialSlope == nextSlope)
{
counter_2++;
StdOut.println("Counter: " + counter_2);
finalCompare = points[next];
}
if(counter_2 >= 3)
{
StdOut.println("got here");
initialPoint.drawTo(finalCompare);
break;
}
StdOut.println(counter_2);
}
StdOut.println("comparator");
comparator++;
}
}
You're never changing next. I assume you want
for(int next = 1 ; next < counter/2 ; next++)
instead of
for(int next = 1 ; next < counter/2 ; initial ++)
Additionally, this condition seems to never be true: if(counter_2 >= 3)
You set counter_2 to 0 and increment it at most once before this statement:
int counter_2 = 0;
...
if(initialSlope == nextSlope)
{
counter_2++;
...
}
//counter_2 can either be 0 or 1 here
if(counter_2 >= 3)
{
...
}
I assume you want to move the initialization out of the inner loop:
int counter_2 = 0;
for(int next = 1 ; next < counter/2 ; next++)
Besides that, please step through your code with a debugger and see what is done at each step. This will help you find typing errors (if you understand the algorithm you're implementing, otherwise try and understand that first).
these lines
double initialSlope = (initialCompare.y - initialPoint.y/ initialCompare.x-initialPoint.x);
double nextSlope = (nextPoint.y - initialPoint.y/ nextPoint.x - initialPoint.x);
I think they are not doing what you want, remember that / has precedence , so first is going to divide initialPoint.y/ initialCompare.x , and then the rest of the operations, I think you want to do :
double initialSlope = ((initialCompare.y - initialPoint.y)/ (initialCompare.x-initialPoint.x));
double nextSlope = ((nextPoint.y - initialPoint.y)/ (nextPoint.x - initialPoint.x));
Related
I am trying to print the last element of my array. The code can be seen below:
double [] results = new double[21];
double t = 9600;
for(int y = 0; y < 21; y++) {
results[y] = t;
t *= 1.04;
System.out.println(results[results.length - 1]);
}
However, when I attempt to run this, I get this result:
0.0 (printed 20 times in a row)
...
21034.782173120842
I do not know why it is printing out 20 zero's, and then the answer I want (21034.78). I thought that by doing results[results.length - 1], only the last element of the array would be printed. I have a suspicion that this has to do with the loop, but I do not know why or how to fix it.
Any help or advice would be greatly appreciated. Thank you!
You need to put the System.out.println outside the for loop, or else you will always print 0.0 because the last index of the array isn't filled yet.
double [] results = new double[21];
double t = 9600;
for(int y = 0; y < 21; y++) {
results[y] = t;
t *= 1.04;
}
System.out.println(results[results.length - 1]);
Output: 21034.782173120842
put your System.out.println , out of loop.
for(int y = 0; y < 21; y++) {
** YOUR LOGIC **
}
System.out.println(results[results.length - 1]);
You need to move the print statement outside the loop..
double [] results = new double[21]; double t = 9600;
for(int y = 0; y < 21; y++) {
results[y] = t;
t *= 1.04;
}
System.out.println(results[results.length - 1]);
You need to make a slight alteration. Here is one thing that you can do:
double [] results = new double[21];
double t = 9600;
for(int y = 0; y < results.length; y++) {
results[y] = t;
t *= 1.04;
System.out.println(results[y]);
}
You can print the current index [y] each time through the loop. Or else you're always printing index 21 which isn't filled yet and will repeatedly print 0 until it is filled. The current iteration of the loop [y] will always be the last index that actually has a value in it, but the last index won't actually be filled with a value until your last iteration through the loop which explains your error here.
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);
I am working on an assignment where I need to create two arrays, then look through them and create a new array that holds any values inside of both the first two. Originally, I was close to accomplishing this by making an arraylist but my lab professor told me that wasn't allowed so I needed to re-start and didn't have enough time to figure out the solution.
If you'd like to see the whole code I have now: http://pastebin.com/thsYnj2z
I am really struggling with this loop here:
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++)
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
k++;
System.out.println(ArrA[k]);
break;
}
My output is remaining 0 for my ArrA[k] array. I can't seem to trouble shoot this issue on my own.
try making these changes
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++)
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]); // or print them all later
k++;
break; // break to outer loop
}
}
}
note
Assuming OP has correctly initialized ArrA
note2
Assuming that only unique values are required, hence the breaking
Does your solution require that no values are duplicated in ArrA? Or are duplicate values allowed? For example, if some values occur multiple times in each array, you could get multiple matches on the same number.
If duplicates aren't a problem:
for(int i = 0 ; i < Xarr.length ; i++){
for(int j = 0 ; j < Yarr.length ; j++){
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]);
k++;
}
}}
As I understand it, the problem is to take 2 arrays, and produce a third array which is a Union of the first 2. Union of 2 sets being the subset of the values found in both sets.
Your code was missing some braces, so put those back in there. Also you wont want to print the k+1th item after you just put a value in ArrA[k] im assuming.
Otherwise you were pretty much there. The break terminates the inner loop and allows the outer loop to increment i and continue on. This is because you have already found a match, no need to continue searching, just move onto the next index in Xarr.
Algorithm goes like this: For each value in X, search Y for a match. If it is found, add this value to A.
for(int i = 0 ; i < Xarr.length ; i++) {
for(int j = 0 ; j < Yarr.length ; j++) {
//Compare. If the two are the same, they go inside of A.
if (Xarr[i] == Yarr[j]){
ArrA[k] = Xarr[i];
System.out.println(ArrA[k]);
k++; //you probably want to increment k after you add to ArrA, not before
break;
}
}
}
public static void main(String... args){
int[] xArr = {1, 1,1,1,1,1};
int[] yArr = {1, };
int[] kArr = new int[xArr.length > yArr.length ? xArr.length : yArr.length];
int k = 0;
for(int x = 0; x < xArr.length; x++){
for(int y = 0; y < yArr.length; y ++){
int xNum = xArr[x];
int yNum = yArr[y];
if(xNum == yNum) kArr[k++] = xNum;
}
}
int[] resizedKArr = new int[k];
for(int i = 0; i < resizedKArr.length; i++) resizedKArr[i] = kArr[i];
Arrays.sort(resizedKArr);
for(int x : resizedKArr) System.out.println(x);
}
First, xArr and yArr are given some random numbers, and then kArr is initialized with the size of the lagest array we are comparing with to ensure the array has enough space to hold similar values.
Then, in the next section we do a loop inside of a loop to compare the values against each other and if they are similar then k++ and set the next value in the array. This goes on until the loops are completed, notice there really is never a need to break from either loop until all values are compared. At that point the loops break themselves and move on to the next bit of code.
The last section is just to create an array of the same size as k and move the values over, I don't know the requirements of your studies, although when using primitives like this you may want to do this in case you have a matching 0 as a number. Otherwise you'll have a ton of 0s filling the empty spaces of your array.
And lastly, we just sort the array for good measure and print it out.
Hope I've answered your question and you get something out of this post!
The problem is printing ArrA[k] after k++. Try increasing line after print.
I need to make a simple(standart) minesweeper for my project.
I want to check the surrounding elements of a random(or specific) element of a 2d array.
lets say I have an array like that
boolean board[5][5]
I want to check the surrounding elements of
board[0][0]
I wrote that:
public int numberChecker(int h, int w) {
int checker = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int he = h - 1 + i;
int wi = w - 1 + i; <---- this i should be j that was the issue
if (board.getHeight() > he && he >= 0
&& wi >= 0 && board.getWidth() > wi) {
if (boomChecker(he, wi)) {
if (w != (wi) && h != (he)) {
checker++;
}
}
}
}
}
return checker;
}
the problem is I think it only checks " \ " way (do not know how to put it in words)
ex:
(output # means uncovered numbers mean surrounding mines)
uncover 4-2
######
######
0#####
#0####
##0### <-- unlocking this one
###0##
or
uncover 0-0
0#####
#0####
##0###
###### <-- there is a mine at check spot
######
######
the code itself is not important (I know I made it a bit complicated to explain myself)
all I need is a working surrounding checking for loop (or anything)
thanks in advance
Problem solved
simple stupid mistake
int he = h - 1 + i;
int wi = w - 1 + i; <--- i should be j
thanks
I think your mistake is in this 2 lines:
int he = h - 1 + i;
int wi = w - 1 + i;
you add to the height AND to the width the value of i.
So you just check every of the 3 diagonal fields 3 times.
I think it should be
int he = h - 1 + i;
int wi = w - 1 + j;
so you really iterate through all 9 possible fields and not just through the diagonale.
Hope that helps!
I'm going to write my answer as though answering a homework question
now what you really ought to do is, for each cell in your array, there are 8 other cells to check. so something like:
count += board[i-1][j-1] ? 1 : 0;
count += board[i-1][j] ? 1 : 0;
count += board[i-1][j+1] ? 1 : 0;
count += board[i][j-1] ? 1 : 0;
etc.
be sure to include some mechanism to prevent you from accessing elements outside the bounds of the array.
also, if you were wondering what the ? and : mean, look up the Ternary Operator It's useful in all sorts of situations.
By the way, you might be better off explicitly checking each of the 8 possible surrounding cells. It's entirely possible that the JVM might automatically unroll your loop, but I don't see why you wouldn't just check them explicitly. It will be faster, and easier to understand.
boolean upleft = board[row-1][column-1];
boolean up = board[row-1][column];
boolean upright = board[row-1][column+1];
boolean left = board[row][column-1];
boolean right = board[row][column+1];
boolean downleft = board[row+1][column-1];
boolean dow = board[row+1][column];
boolean downright = board[row+1][column+1];
You'll of course have to do bounds checking if your on the edge of the board, but it makes more sense as to what is going on.
I'm working on this bacteria life game thing I have to make.
Basically I have a 2d string array let's say 20 by 20.
What would be the best way to check all 8 spots around a certain index. Each index is suppose to represent a bacteria. For each bacteria(index) I have to check to see if any of the 8 spots around this index has another bacteria in it, if the index has a bacteria in it, it's represented simply by a "*", asterik.
What would be the best way to go about checking all 8 spots around each index, because based on what is in the indices around a certain index I have to make certain changes etc.
The only idea I have come up with is having a bunch of if statements to check all 8 spots, I was wondering if there is a better way to do this
ex:
row 1 - www , row 2 = wOw , row 3 - www ,
if I am at the O index, what would be the best way to check all the index spots around it for a certain string.
Sorry, I am not very good at explaining my problems, bad english :o.
thanks for any of the help.
so you have something like this
char[][] table = new char[20][20]
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
int surroundingBacteria = 0;
for(int x = max(i-1,0); x < min(20,i+1); x++) {
for(int y = max(i-1,0); y < min(20,i+1); y++) {
if(table[x][y] == '*') surroundingBacteria++;
}
}
switch(surroundingBacteria) {
// put your case logic here
}
}
}
Here is how I've accomplished this in the past:
for(int x = -1; x<=1; x++){
if ( i+x < xLength && i+x >= 0){
for(int y = -1; y<=1; y++){
if(j+y < yLength && j+y >= 0){
//logic goes here
}
}
}
}