How to increment the result of a calculation inside a loop - c#

I have a loop, and every time the result of Y - X is greater than or equal to 1000, I want another variable (Z) to increment by 30. So every time the difference between Y and X increases by 1000, Z increases by 30. so:
3000 - 2000 = 1000, so Z = 30
3500 - 2000 = 1500, so Z = 30
4000 - 2000 = 2000, so Z = 60
4500 - 2000 = 2500, so Z = 60
5000 - 2000 = 3000, so Z = 90
Hopefully, that makes it clearer
etc...
I can't figure it out, any ideas?
while (Y >= X)
{
while (Y - X **==** 1000)
{
Z += 30;
break;
}
result = (Y - X) + Z;
break;
}
Obviously i know that doesn't work, and isn't tidy, I can't think how to do it

while (Y >= X)
{
Y = Y - X;
if (Y >= 1000)
{
Z += 30;
}
}

for(int y = 1000;y<= 10000;y+=1000)
{
for(int x = 1000;x< = 10000;x+=1000)
{
if(y-x>=1000)
z+=30;
}
}
If my understanding is correct,the above code should increment z by 30 whenever (y-x) is greater than or equal to 1000. Initialise z to 0 outside the loops.

Related

How to enumerate x^2 + y^2 = z^2 - 1 (with additional constraints)

Lets N be a number (10<=N<=10^5).
I have to break it into 3 numbers (x,y,z) such that it validates the following conditions.
1. x<=y<=z
2. x^2+y^2=z^2-1;
3. x+y+z<=N
I have to find how many combinations I can get from the given numbers in a method.
I have tried as follows but it's taking so much time for a higher number and resulting in a timeout..
int N= Int32.Parse(Console.ReadLine());
List<String> res = new List<string>();
//x<=y<=z
int mxSqrt = N - 2;
int a = 0, b = 0;
for (int z = 1; z <= mxSqrt; z++)
{
a = z * z;
for (int y = 1; y <= z; y++)
{
b = y * y;
for (int x = 1; x <= y; x++)
{
int x1 = b + x * x;
int y1 = a - 1;
if (x1 == y1 && ((x + y + z) <= N))
{
res.Add(x + "," + y + "," + z);
}
}
}
}
Console.WriteLine(res.Count());
My question:
My solution is taking time for a bigger number (I think it's the
for loops), how can I improve it?
Is there any better approach for the same?
Here's a method that enumerates the triples, rather than exhaustively testing for them, using number theory as described here: https://mathoverflow.net/questions/29644/enumerating-ways-to-decompose-an-integer-into-the-sum-of-two-squares
Since the math took me a while to comprehend and a while to implement (gathering some code that's credited above it), and since I don't feel much of an authority on the subject, I'll leave it for the reader to research. This is based on expressing numbers as Gaussian integer conjugates. (a + bi)*(a - bi) = a^2 + b^2. We first factor the number, z^2 - 1, into primes, decompose the primes into Gaussian conjugates and find different expressions that we expand and simplify to get a + bi, which can be then raised, a^2 + b^2.
A perk of reading about the Sum of Squares Function is discovering that we can rule out any candidate z^2 - 1 that contains a prime of form 4k + 3 with an odd power. Using that check alone, I was able to reduce Prune's loop on 10^5 from 214 seconds to 19 seconds (on repl.it) using the Rosetta prime factoring code below.
The implementation here is just a demonstration. It does not have handling or optimisation for limiting x and y. Rather, it just enumerates as it goes. Play with it here.
Python code:
# https://math.stackexchange.com/questions/5877/efficiently-finding-two-squares-which-sum-to-a-prime
def mods(a, n):
if n <= 0:
return "negative modulus"
a = a % n
if (2 * a > n):
a -= n
return a
def powmods(a, r, n):
out = 1
while r > 0:
if (r % 2) == 1:
r -= 1
out = mods(out * a, n)
r /= 2
a = mods(a * a, n)
return out
def quos(a, n):
if n <= 0:
return "negative modulus"
return (a - mods(a, n))/n
def grem(w, z):
# remainder in Gaussian integers when dividing w by z
(w0, w1) = w
(z0, z1) = z
n = z0 * z0 + z1 * z1
if n == 0:
return "division by zero"
u0 = quos(w0 * z0 + w1 * z1, n)
u1 = quos(w1 * z0 - w0 * z1, n)
return(w0 - z0 * u0 + z1 * u1,
w1 - z0 * u1 - z1 * u0)
def ggcd(w, z):
while z != (0,0):
w, z = z, grem(w, z)
return w
def root4(p):
# 4th root of 1 modulo p
if p <= 1:
return "too small"
if (p % 4) != 1:
return "not congruent to 1"
k = p/4
j = 2
while True:
a = powmods(j, k, p)
b = mods(a * a, p)
if b == -1:
return a
if b != 1:
return "not prime"
j += 1
def sq2(p):
if p % 4 != 1:
return "not congruent to 1 modulo 4"
a = root4(p)
return ggcd((p,0),(a,1))
# https://rosettacode.org/wiki/Prime_decomposition#Python:_Using_floating_point
from math import floor, sqrt
def fac(n):
step = lambda x: 1 + (x<<2) - ((x>>1)<<1)
maxq = long(floor(sqrt(n)))
d = 1
q = n % 2 == 0 and 2 or 3
while q <= maxq and n % q != 0:
q = step(d)
d += 1
return q <= maxq and [q] + fac(n//q) or [n]
# My code...
# An answer for https://stackoverflow.com/questions/54110614/
from collections import Counter
from itertools import product
from sympy import I, expand, Add
def valid(ps):
for (p, e) in ps.items():
if (p % 4 == 3) and (e & 1):
return False
return True
def get_sq2(p, e):
if p == 2:
if e & 1:
return [2**(e / 2), 2**(e / 2)]
else:
return [2**(e / 2), 0]
elif p % 4 == 3:
return [p, 0]
else:
a,b = sq2(p)
return [abs(a), abs(b)]
def get_terms(cs, e):
if e == 1:
return [Add(cs[0], cs[1] * I)]
res = [Add(cs[0], cs[1] * I)**e]
for t in xrange(1, e / 2 + 1):
res.append(
Add(cs[0] + cs[1]*I)**(e-t) * Add(cs[0] - cs[1]*I)**t)
return res
def get_lists(ps):
items = ps.items()
lists = []
for (p, e) in items:
if p == 2:
a,b = get_sq2(2, e)
lists.append([Add(a, b*I)])
elif p % 4 == 3:
a,b = get_sq2(p, e)
lists.append([Add(a, b*I)**(e / 2)])
else:
lists.append(get_terms(get_sq2(p, e), e))
return lists
def f(n):
for z in xrange(2, n / 2):
zz = (z + 1) * (z - 1)
ps = Counter(fac(zz))
is_valid = valid(ps)
if is_valid:
print "valid (does not contain a prime of form\n4k + 3 with an odd power)"
print "z: %s, primes: %s" % (z, dict(ps))
lists = get_lists(ps)
cartesian = product(*lists)
for element in cartesian:
print "prime square decomposition: %s" % list(element)
p = 1
for item in element:
p *= item
print "complex conjugates: %s" % p
vals = p.expand(complex=True, evaluate=True).as_coefficients_dict().values()
x, y = vals[0], vals[1] if len(vals) > 1 else 0
print "x, y, z: %s, %s, %s" % (x, y, z)
print "x^2 + y^2, z^2-1: %s, %s" % (x**2 + y**2, z**2 - 1)
print ''
if __name__ == "__main__":
print f(100)
Output:
valid (does not contain a prime of form
4k + 3 with an odd power)
z: 3, primes: {2: 3}
prime square decomposition: [2 + 2*I]
complex conjugates: 2 + 2*I
x, y, z: 2, 2, 3
x^2 + y^2, z^2-1: 8, 8
valid (does not contain a prime of form
4k + 3 with an odd power)
z: 9, primes: {2: 4, 5: 1}
prime square decomposition: [4, 2 + I]
complex conjugates: 8 + 4*I
x, y, z: 8, 4, 9
x^2 + y^2, z^2-1: 80, 80
valid (does not contain a prime of form
4k + 3 with an odd power)
z: 17, primes: {2: 5, 3: 2}
prime square decomposition: [4 + 4*I, 3]
complex conjugates: 12 + 12*I
x, y, z: 12, 12, 17
x^2 + y^2, z^2-1: 288, 288
valid (does not contain a prime of form
4k + 3 with an odd power)
z: 19, primes: {2: 3, 3: 2, 5: 1}
prime square decomposition: [2 + 2*I, 3, 2 + I]
complex conjugates: (2 + I)*(6 + 6*I)
x, y, z: 6, 18, 19
x^2 + y^2, z^2-1: 360, 360
valid (does not contain a prime of form
4k + 3 with an odd power)
z: 33, primes: {17: 1, 2: 6}
prime square decomposition: [4 + I, 8]
complex conjugates: 32 + 8*I
x, y, z: 32, 8, 33
x^2 + y^2, z^2-1: 1088, 1088
valid (does not contain a prime of form
4k + 3 with an odd power)
z: 35, primes: {17: 1, 2: 3, 3: 2}
prime square decomposition: [4 + I, 2 + 2*I, 3]
complex conjugates: 3*(2 + 2*I)*(4 + I)
x, y, z: 18, 30, 35
x^2 + y^2, z^2-1: 1224, 1224
Here is a simple improvement in Python (converting to the faster equivalent in C-based code is left as an exercise for the reader). To get accurate timing for the computation, I removed printing the solutions themselves (after validating them in a previous run).
Use an outer loop for one free variable (I chose z), constrained only by its relation to N.
Use an inner loop (I chose y) constrained by the outer loop index.
The third variable is directly computed per requirement 2.
Timing results:
-------------------- 10
1 solutions found in 2.3365020751953125e-05 sec.
-------------------- 100
6 solutions found in 0.00040078163146972656 sec.
-------------------- 1000
55 solutions found in 0.030081748962402344 sec.
-------------------- 10000
543 solutions found in 2.2078349590301514 sec.
-------------------- 100000
5512 solutions found in 214.93411707878113 sec.
That's 3:35 for the large case, plus your time to collate and/or print the results.
If you need faster code (this is still pretty brute-force), look into Diophantine equations and parameterizations to generate (y, x) pairs, given the target value of z^2 - 1.
import math
import time
def break3(N):
"""
10 <= N <= 10^5
return x, y, z triples such that:
x <= y <= z
x^2 + y^2 = z^2 - 1
x + y + z <= N
"""
"""
Observations:
z <= x + y
z < N/2
"""
count = 0
z_limit = N // 2
for z in range(3, z_limit):
# Since y >= x, there's a lower bound on y
target = z*z - 1
ymin = int(math.sqrt(target/2))
for y in range(ymin, z):
# Given y and z, compute x.
# That's a solution iff x is integer.
x_target = target - y*y
x = int(math.sqrt(x_target))
if x*x == x_target and x+y+z <= N:
# print("solution", x, y, z)
count += 1
return count
test = [10, 100, 1000, 10**4, 10**5]
border = "-"*20
for case in test:
print(border, case)
start = time.time()
print(break3(case), "solutions found in", time.time() - start, "sec.")
The bounds of x and y are an important part of the problem. I personally went with this Wolfram Alpha query and checked the exact forms of the variables.
Thanks to #Bleep-Bloop and comments, a very elegant bound optimization was found, which is x < n and x <= y < n - x. The results are the same and the times are nearly identical.
Also, since the only possible values for x and y are positive even integers, we can reduce the amount of loop iterations by half.
To optimize even further, since we compute the upper bound of x, we build a list of all possible values for x and make the computation parallel. That saves a massive amount of time on higher values of N but it's a bit slower for smaller values because of the overhead of the parallelization.
Here's the final code:
Non-parallel version, with int values:
List<string> res = new List<string>();
int n2 = n * n;
double maxX = 0.5 * (2.0 * n - Math.Sqrt(2) * Math.Sqrt(n2 + 1));
for (int x = 2; x < maxX; x += 2)
{
int maxY = (int)Math.Floor((n2 - 2.0 * n * x - 1.0) / (2.0 * n - 2.0 * x));
for (int y = x; y <= maxY; y += 2)
{
int z2 = x * x + y * y + 1;
int z = (int)Math.Sqrt(z2);
if (z * z == z2 && x + y + z <= n)
res.Add(x + "," + y + "," + z);
}
}
Parallel version, with long values:
using System.Linq;
...
// Use ConcurrentBag for thread safety
ConcurrentBag<string> res = new ConcurrentBag<string>();
long n2 = n * n;
double maxX = 0.5 * (2.0 * n - Math.Sqrt(2) * Math.Sqrt(n2 + 1L));
// Build list to parallelize
int nbX = Convert.ToInt32(maxX);
List<int> xList = new List<int>();
for (int x = 2; x < maxX; x += 2)
xList.Add(x);
Parallel.ForEach(xList, x =>
{
int maxY = (int)Math.Floor((n2 - 2.0 * n * x - 1.0) / (2.0 * n - 2.0 * x));
for (long y = x; y <= maxY; y += 2)
{
long z2 = x * x + y * y + 1L;
long z = (long)Math.Sqrt(z2);
if (z * z == z2 && x + y + z <= n)
res.Add(x + "," + y + "," + z);
}
});
When ran individually on a i5-8400 CPU, I get these results:
N: 10; Solutions: 1;
Time elapsed: 0.03 ms (Not parallel, int)
N: 100; Solutions: 6;
Time elapsed: 0.05 ms (Not parallel, int)
N: 1000; Solutions: 55;
Time elapsed: 0.3 ms (Not parallel, int)
N: 10000; Solutions: 543;
Time elapsed: 13.1 ms (Not parallel, int)
N: 100000; Solutions: 5512;
Time elapsed: 849.4 ms (Parallel, long)
You must use long when N is greater than 36340, because when it's squared, it overflows an int's max value. Finally, the parallel version starts to get better than the simple one when N is around 23000, with ints.
No time to properly test it, but seemed to yield the same results as your code (at 100 -> 6 results and at 1000 -> 55 results).
With N=1000 a time of 2ms vs your 144ms also without List
and N=10000 a time of 28ms
var N = 1000;
var c = 0;
for (int x = 2; x < N; x+=2)
{
for (int y = x; y < (N - x); y+=2)
{
long z2 = x * x + y * y + 1;
int z = (int) Math.Sqrt(z2);
if (x + y + z > N)
break;
if (z * z == z2)
c++;
}
}
Console.WriteLine(c);
#include<iostream>
#include<math.h>
int main()
{
int N = 10000;
int c = 0;
for (int x = 2; x < N; x+=2)
{
for (int y = x; y < (N - x); y+=2)
{
auto z = sqrt(x * x + y * y + 1);
if(x+y+z>N){
break;
}
if (z - (int) z == 0)
{
c++;
}
}
}
std::cout<<c;
}
This is my solution. On testing the previous solutions for this problem I found that x,y are always even and z is odd. I dont know the mathematical nature behind this, I am currently trying to figure that out.
I want to get it done in C# and it should be covering all the test
cases based on condition provided in the question.
The basic code, converted to long to process the N <= 100000 upper limit, with every optimizaion thrown in I could. I used alternate forms from #Mat's (+1) Wolfram Alpha query to precompute as much as possible. I also did a minimal perfect square test to avoid millions of sqrt() calls at the upper limit:
public static void Main()
{
int c = 0;
long N = long.Parse(Console.ReadLine());
long N_squared = N * N;
double half_N_squared = N_squared / 2.0 - 0.5;
double x_limit = N - Math.Sqrt(2) / 2.0 * Math.Sqrt(N_squared + 1);
for (long x = 2; x < x_limit; x += 2)
{
long x_squared = x * x + 1;
double y_limit = (half_N_squared - N * x) / (N - x);
for (long y = x; y < y_limit; y += 2)
{
long z_squared = x_squared + y * y;
int digit = (int) z_squared % 10;
if (digit == 3 || digit == 7)
{
continue; // minimalist non-perfect square elimination
}
long z = (long) Math.Sqrt(z_squared);
if (z * z == z_squared)
{
c++;
}
}
}
Console.WriteLine(c);
}
I followed the trend and left out "the degenerate solution" as implied by the OP's code but not explicitly stated.

Multi compound assignment operator?

Why the result of the following code is x = y = z = 1 ?
int x = 0, y= 0, z = 0;
x += y += z += 1;
Console.WriteLine("{0} {1} {2}", x, y, z);
Assignment statements actually evaluate to a value. The value that it evaluates to is equal to the right hand side of the assignment statement.
So x = 5; evaluates to 5.
Now let's dissect this:
x += y += z += 1;
First we replace the shorthand += to make things clearer (note that assignment operators are right-associative):
x += y += (z = z + 1)
x += (y = y + (z = z + 1))
x = x + (y = y + (z = z + 1))
Now, we evaluate! Keep in mind that assignments evaluate to the value of the right hand side!
x = x + (y = y + (z = z + 1))
x = x + (y = y + (z = 1))
x = x + (y = y + 1) // z is now 1
x = x + (y = 1)
x = x + 1 // y is now 1
x = 1
// x is now 1
As all your operators have the same priority, you need some order of execution. As seen on MSDN that order for the +=-operator is from right to left. In contrast 3 + 4 + 5 will first evaluate 3 + 4 and then add 5 to the result, as the +-operator is left to right evaluated.
The same happens in your example. First z += 1 will evaluate to one. This result (not z itself) is passed to the next +=-operator, so you get y += 1 which itself evaluates to one and is assigned to the operator += again.
An operator is basically nothing different than a simple method-call, as you can indicate by its signature:
public static int operator += (int c1, intc2) { ... }
So all you do is to call that "method" with the result of a previous call like this:
int.CallAssignPlus(ref x, int.CallIassgnPlus(ref y, int.CallAsignPlus(ref z, 1)));
Of course that code isn´t how it´s actually translated to IL, however it shows how it works.
So what´s important here is not actually the fact, that you have variables that are assigned to anything, but rather that even the result of an assignment is an expression which can be used in any other statement. Having said this z +=1 is just a statement that has a value. Thus not z is passed to y, but the value of that statement (which however is equal to the value of z).
Because:
z (0) is increased by 1 (thus:
0 + 1 = 1)
y (0) is increased by z, which is the result of the previous operation (z += 1 -> 1), hence y + z = 0 + 1 = 1
x (0) is increased by y, which is the result of the previous operation (y += z -> 1), hence x + y = 0 + 1 = 1
Even if the operations are chained, this doesn't mean they are evaluated all at once. They are always performed sequentially, from the right to the left, provided their operators have the same priority (and this is the case). Splitting your code into multiple lines following the evaluation order and simplifying the notations can probably provide a better insight on what's going on:
Int32 x = 0;
Int32 y = 0;
Int32 z = 0;
z = z + 1; // z = 0 + 1 = 1
y = y + z; // y = 0 + 1 = 1
x = x + y; // x = 0 + 1 = 1

Step through 2D array in hexagon pattern

I use a nested for loop to create a grid of hexagons. This creates a square grid:
for (int z = 0; z < gridSize; z++)
{
for (int x = 0; x < gridSize; x++)
{
// creates verts for a hexagon shape which later form a mesh
// x and z form the basis of the Vector3 position of the center
// of each hexagon
CreateCell(x, z);
}
}
I've drawn the start and end values for z & x on the image.
What I'd like is to have the grid itself also shaped hexagonally:
I think figured out the limits for x:
int greaterThan = Mathf.RoundToInt(gridSize/ 3) - 1;
int lessThan = width - greaterThan;
And that (I think) x should only be at it's min and max (0 & 6 in the examples) when z = gridSize / 2 rounded up, though I may well be wrong!
I tried putting a bunch if IFs in the loops but it quickly started to get overly complicated, I figure there must be a more 'mathsy' way to do it, but sadly I'm not mathsy!
Any idea how I can write a loop to form the required pattern?
If #AsfK's solution is not good enough, I'll give it a try as well:
private static void PrintHexLine(int z, int size)
{
if (z >= size)
{
z = 2 * size - 2 - z;
}
int start = size - z - 1;
int end = start + size + z;
for (int x = 0; x < start; x++)
{
Console.Write(" ");
}
for (int x = start; x < end; x++)
{
Console.Write("* ");
//Console.Write((x - start / 2) + " "); // position v1
//Console.Write((x - (start + 1) / 2) + " "); // position v2
}
Console.WriteLine();
}
public static void PrintHex(int size)
{
for (int z = 0; z < 2 * size - 1; z++)
{
PrintHexLine(z, size);
}
}
With such code PrintHex(4) results in
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * *
* * * * *
* * * *
And if you uncomment the position v1 line instead of the one that prints "* ", you'll get
2 3 4 5
1 2 3 4 5
1 2 3 4 5 6
0 1 2 3 4 5 6
1 2 3 4 5 6
1 2 3 4 5
2 3 4 5
similarly position v2
1 2 3 4
1 2 3 4 5
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5
1 2 3 4 5
1 2 3 4
which looks like the x indices you want. Basing on your data I'm not really sure whether you need v1 or v2 variant. The v2 looks more consistent to me but it really depends on how your CreateCell(x, z); treats the x = 0 case.
P.S. obviously you can inline PrintHexLine call but it means having two different z variables that you should not mess up with and I think it is cleaner to move that in a separate method.
According your excepted picture the center is the long row (gridSize = 7).
floor(7/2) = 3 (/2 because the long row is in the center)
Now, gridSize - 3 = 4 ==> 4 items in your first row
Then each iterate add one till you have 7 items in one row.
Then do a minus...
it's the code (draw "*", not added spaces before and after..)
int gridSize = 7;
int center = 7/2;
int delta = 1;
for (int r = 0; r < gridSize; r++) {
for (int c = gridSize - center; c < gridSize + delta; c++){
System.out.print("*");
// location of c = c - delta (position)
}
System.out.println();
if (r < center)
delta++;
else
delta--;
}
Thanks to a hint from AsfK I solved it like this
int xL, xU, xMid, zM2;
xL = Mathf.FloorToInt(width / 3) - 1;
xU = (width - xL) + 1;
xMid = Mathf.FloorToInt(width / 2);
for (int z = 0; z < height; z++)
{
for (int x = xL; x < xU; x++)
{
CreateCell(x, z);
}
zM2 = z % 2;
if(z < xMid)
{
if (zM2 == 0)
{
xL--;
}
if (z > 0 && zM2 == 1)
{
xU++;
}
} else
{
if (zM2 == 1)
{
xL++;
}
if (zM2 == 0)
{
xU--;
}
if (z == width - 1)
{
xL--;
xU++;
}
}
}
Would be great if anyone can think of a more elegant solution!

Convert list with distances and seconds to list of kilometers with pace

Imagine a list with distances and the time in seconds that belongs to it.
meterTempos
{
distance: 500,
seconds: 50
},
{
distance: 600
seconds: 60
}
The above list can be any number of 'distance-seconds'- items. This is just an example not hardcoded data.
My question is, how do I convert it to the following format?
kmTempos
{
km: 1,
distance: 1000,
seconds: 100
}, {
km: 2,
distance: 100,
seconds: 10
}
Here's what I tried:
double totaldistance = 1100; //Total distance is variable, but for the sake of simplicity, I set it to 1.1
int loops = (int)(Math.Ceiling(totaldistance / 1000));
List<KilometerTempo> kmTempos = new List<KilometerTempo>();
for (int j = 0; j < loops; j++)
{
double seconds = meterTempos[j].seconds;
double distance = meterTempos[j].meters;
//this is definitely wrong, since it will add new KilometerTempos for every item in meterTempos
kmTempos.Add(new KilometerTempo(j + 1, distance, seconds));
}
As you can see, I dont understand how to iterate over the list and work with a subresult that should be taken into account for every new kilometer.
List<KilometerTempo> kmTempos = new List<KilometerTempo>();
foreach (MeterTempo mt in meterTempos)
{
double rDistance = mt.distance; // remaining distance to add
while (rDistance > 0)
{
if (kmTempos.Count == 0 || kmTempos.Last().distance == 1000f)
{
kmTempos.Add(new KilometerTempo());
kmTempos.Last().km = kmTempos.Count;
}
// determine max distance we can add to the last km tempo
double maxAddedDistance = 1000f - kmTempos.Last().distance;
// determine how much we will add
double addedDistance = rDistance < maxAddedDistance ? rDistance : maxAddedDistance;
kmTempos.Last().distance += addedDistance;
// add seconds proportional to the added distance
kmTempos.Last().seconds += (addedDistance / mt.distance) * mt.seconds;
rDistance -= addedDistance;
}
}

Variable declared but doesn't show up during Debug C#

screenshot of debug: http://img1.uploadscreenshot.com/images/orig/12/36121481470-orig.jpg
note how x, y have values (i have no idea why x and y stopped on 69 in the for loop - x should've went up to 86 and y to 183) yet r has no value at all. (the variable doesn't exist? what?) how should I fix this?
code if you want to read:
public float[] cht(int[,] matrix)
{
float[] xyrd = new float[4];
int xthreshold, ythreshold;
float slope;
double dir;
float zone;
int[] limitsStorage = new int[3] { matrix.GetLength(0), matrix.GetLength(1), matrix.GetLength(0) / 2 - 10 };
short[,,] accumulator = new short[limitsStorage[0]+1, limitsStorage[1]+1,limitsStorage[2]+1];
for (int x = 0; x < limitsStorage[0]; x++)
{ //first dimension loop of matrix 100
for (int y = 0; y < limitsStorage[1]; y++)
{ //second dimension loop of matrix 120
if (matrix[x, y] == 225)
{//the data at the for loop location is a 1 and not 0 hit.
xthreshold = x - limitsStorage[0] / 2;
ythreshold = y - limitsStorage[1] / 2;
//forget angle, search slope: float angle = xthreshold > 0 ? ((float)Math.Atan2(xthreshold, ythreshold)) : ((float)Math.Atan2(xthreshold, ythreshold) + 180);
slope = xthreshold / ythreshold;
//initiate if loops.
dir = 180 + Math.Round(Math.Atan2(ythreshold, xthreshold) * 57.2957 / 45, 0) * 45 + 45 * (Math.Round(((Math.Atan2(ythreshold, xthreshold) * 57.2957) % 45) / 45));
if (slope > .404 || slope < -.404)
{
if (slope < 2.3558 || slope > -2.3558)
{
if (xthreshold > 0)
{
if (ythreshold > 0)
{
//+x+y zone
zone = 45 + 180;
}
else
{
//+x-y zone
zone = 180 - 45;
}
}
else
{
if (ythreshold > 0)
{
//-x+y zone
zone = 360 - 45;
}
else
{
//-x-y zone
zone = 45;
}
}
}
else if (ythreshold > 0)
{
//+y zone
zone = 360 - 90;
}
else
{
//-y zone
zone = 90;
}
}
else if (xthreshold > 0)
{
//+x zone
zone = 180;
}
else
{
//-x zone
zone = 0;
}
for (int R = 6; R < limitsStorage[2]; R++)
{ //Radius loop for scan 44
float delta = (float)((1 / R) * 57.2957);
for (float Theta = zone - 25; Theta < zone + 25; Theta += delta)
{
accumulator[(int)(((R * Math.Cos(Theta / 57.2957)) < 0 || (R * Math.Cos(Theta / 57.2957)) > limitsStorage[0]) ? 0 : R * Math.Cos(Theta / 57.2957)), (int)(((R * Math.Sin(Theta / 57.2957)) < 0 || (R * Math.Sin(Theta / 57.2957)) > limitsStorage[1]) ? 0 : R * Math.Sin(Theta / 57.2957)),R]++;
//btw, 0,0,R is always the non-center area.
}
}
}
}
}
for (int x = 1; x < limitsStorage[0]; x++)
{
for (int y = 1; y < limitsStorage[1]; y++)
{
for (int r = 6; r < limitsStorage[2]; r++)
{
if (xyrd[3] > accumulator[x, y, r])
{
xyrd[0] = x;
xyrd[1] = y;
xyrd[2] = r;
xyrd[3] = accumulator[x, y, r];
}
}
}
}
if (accPrint)
{
//do something for debugging?
accPrint = false;
}
return xyrd;
}
I just noticed that the x and y have the little lock symbol under them indicating that you have private variables named x and y in the class in which this method is executing. Those are the x and y that you are seeing in the debugger.
r is appropriately out of scope as you've exited the loop in which it is declared.
By the way, x and y are ridiculously bad member variable names, and are ridiculously bad names for for loop variables of type int, especially if they are contained in a class with member variables named x and y.
The only place you declare r is in the for statement, right? That means r goes out of scope as soon as the loop ends. So naturally if you inspect variables at he end of the function, r won't be there.
Confessing I don't know why x and y are in scope based on the comments. They could be class variables, but the asker says not. That's the only explanation I can think of, though.
The behaviour is not weird -- you actually get exactly what you expect.
Please note that the watch window can only accurately show you values that are in scope at the breakpoint.
At the highlighted breakpoint, only accumulator[x, y, r] is in scope, and you see exactly the values you expected.

Categories

Resources