Assigning value to array but value doesn't change? - rust

I have the following code:
if (x % 2 == 0) ^ (y % 2 == 1) ^ (z % 2 == 0) {
grid_box.weights[x][y][x] = 1.0;
assert_eq!(grid_box.weights[x][y][x], 1.0);
} else {
grid_box.weights[x][y][z] = 0.0;
assert_eq!(grid_box.weights[x][y][x], 0.0); // Assertion failed, 1.0 != 0.0
}
However, the second assertion fails even though I assigned the grid position to zero in the very previous line. Further experimentation shows that the previous value in the grid seems to make a difference for what the new value should be, even though assignment should override the value entirely.

You have a typo, you assign to grid_box.weights[x][y][z] and read from grid_box.weights[x][y][x]. Replace the z with x.

Related

Switch case help in visual c++

The question is
int i = 6, x = 11;
switch(i % 3 ? 0 : 1)
{
case 0: x /=2; break;
case 1: x +=3;
case 2: x *=4;
}
cout << "x = " << x;
So the answer i should be getting is x=5, however, from the answer script it said it should be x= 56.
Why is that?
Both statements:
x +=3;
and
x *=4;
are executed. This is why (see here for conditional operator reference and here for the switch statement).
In the expression
i % 3 ? 0 : 1
i % 3 is the condition. Being an integer value, it's considered false if equal to zero, true otherwise. In your case i has value 6, thus i % 3 is 0, thus the condition is false and the value after the : is taken to be evaluated in the switch statement.
The value after the : is 1, so the code jumps to case 1 and executes x += 3. Now x is 11+3=14.
But there is no break statement before case 2, so the execution simply goes on with x *= 4 and x becomes 14*4=56.

Creating a Templated Function to Fill a Vector with another depending on Size

Is there a base function in Rcpp that:
Fills entirely by a single value if size of a vector is 1.
Fills the other vector completely if same length.
Fills with an NA value if neither Vector are the same length nor a vector is of size 1.
I've written the above criteria as a function below using a NumericVector as an example. If there isn't a base function in Rcpp that performs said operations there should be a way to template the function so that given any type of vector (e.g. numeric, character and so on) the above logic would be able to be executed.
// [[Rcpp::export]]
NumericVector cppvectorize(NumericVector x,NumericVector y) {
NumericVector y_out(y.size());
if(x.size() == 1) {
for(int i = 0; i < y_out.size(); i++) {
y_out[i] = x[0];
}
} else if(x.size() == y_out.size()) {
for(int i = 0; i < y_out.size(); i++) {
y_out[i] = x[i];
}
} else {
for(int i = 0; i < y_out.size(); i++) {
y_out[i] = NA_REAL;
}
}
return y_out;
}
Unfortunately, the closest you will come to such a function is one of the rep variants that Rcpp supports. However, none of the variants match the desired output. Therefore, the only option is to really implement a templated version of your desired function.
To create the templated function, we will first create a routing function that handles the dispatch of SEXP objects. The rationale behind the routing function is SEXP objects are able to be retrieved from and surfaced into R using Rcpp Attributes whereas a templated version is not. As a result, we need to specify the SEXTYPE (used as RTYPE) dispatches that are possible. The TYPEOF() macro retrieves the coded number. Using a switch statement, we can dispatch this number into the appropriate cases.
After dispatching, we arrive at the templated function. The templated function makes use of the base Vector class of Rcpp to simplify the data flow. From here, the notable novelty will be the use of ::traits::get_na<RTYPE>() to dynamically retrieve the appropriate NA value and fill it.
With the plan in place, let's look at the code:
#include <Rcpp.h>
using namespace Rcpp;
// ---- Templated Function
template <int RTYPE>
Vector<RTYPE> vec_helper(const Vector<RTYPE>& x, const Vector<RTYPE>& y) {
Vector<RTYPE> y_out(y.size());
if(x.size() == 1){
y_out.fill(x[0]);
} else if (x.size() == y.size()) {
y_out = x;
} else {
y_out.fill(::traits::get_na<RTYPE>());
}
return y_out;
}
// ---- Dispatch function
// [[Rcpp::export]]
SEXP cppvectorize(SEXP x, SEXP y) {
switch (TYPEOF(x)) {
case INTSXP: return vec_helper<INTSXP>(x, y);
case REALSXP: return vec_helper<REALSXP>(x, y);
case STRSXP: return vec_helper<STRSXP>(x, y);
default: Rcpp::stop("SEXP Type Not Supported.");
}
// Need to return a value even though this will never be triggered
// to quiet the compiler.
return R_NilValue;
}
Sample Tests
Here we conduct a few sample tests on each of the supported data
# Case 1: x == 1
x = 1:5
y = 2
cppvectorize(x, y)
## [1] NA
# Case 2: x == y
x = letters[1:5]
y = letters[6:10]
cppvectorize(x, y)
## [1] "a" "b" "c" "d" "e"
# Case 3: x != y && x > 1
x = 1.5
y = 2.5:6.5
cppvectorize(x, y)
## [1] 1.5 1.5 1.5 1.5 1.5

maximum volume of a box with perimeter and area given

Here's the link to the question..
http://www.codechef.com/problems/J7
I figured out that 2 edges have to be equal in order to give the maximum volume, and then used x, x, a*x as the lengths of the three edges to write the equations -
4*x + 4*x + 4*a*x = P (perimeter) and,
2*x^2 + 4*(a*x *x) = S (total area of the box)
so from the first equation I got x in terms of P and a, and then substituted it in the second equation and then got a quadratic equation with the unknown being a. and then I used the greater root of a and got x.
But this method seems to be giving the wrong answer! :|
I know that there isn't any logical error in this. Maybe some formatting error?
Here's the main code that I've written :
{
public static void main(String[] args)
{
TheBestBox box = new TheBestBox();
reader = box.new InputReader(System.in);
writer = box.new OutputWriter(System.out);
getAttributes();
writer.flush();
reader.close();
writer.close();
}
public static void getAttributes()
{
t = reader.nextInt(); // t is the number of test cases in the question
for (int i = 0; i < t; i++)
{
p = reader.nextInt(); // p is the perimeter given as input
area = reader.nextInt(); // area of the whole sheet, given as input
a = findRoot(); // the fraction by which the third side differs by the first two
side = (double) p / (4 * (2 + a)); // length of the first and the second sides (equal)
height = a * side; // assuming that the base is a square, the height has to be the side which differs from the other two
// writer.println(side * side * height);
// System.out.printf("%.2f\n", (side * side * height));
writer.println(String.format("%.2f", (side * side * height))); // just printing out the final answer
}
}
public static double findRoot() // the method to find the 2 possible fractions by which the height can differ from the other two sides and return the bigger one of them
{
double a32, b, discriminant, root1, root2;
a32 = 32 * area - p * p;
b = 32 * area - 2 * p * p;
discriminant = Math.sqrt(b * b - 4 * 8 * area * a32);
double temp;
temp = 2 * 8 * area;
root1 = (- b + discriminant) / temp;
root2 = (- b - discriminant) / temp;
return Math.max(root1, root2);
}
}
could someone please help me out with this? Thank You. :)
I also got stuck in this question and realized that can be done by making equation of V(volume) in terms of one side say 'l' and using differentiation to find maximum volume in terms of any one side 'l'.
So, equations are like this :-
P = 4(l+b+h);
S = 2(l*b+b*h+l*h);
V = l*b*h;
so equation in l for V = (l^3) - (l^2)P/4 + lS/2 -------equ(1)
After differentiation we get:-
d(V)/d(l) = 3*(l^2) - l*P/2 + S/2;
to get max V we need to equate above equation to zero(0) and get the value of l.
So, solutions to a quadratic equation will be:-
l = ( P + sqrt((P^2)-24S) ) / 24;
so substitute this l in equation(1) to get max volume.

Switch Statement: Homework Confusion

Question: What is y after the following switch statement is executed? Rewrite the code using an if statement.
y = 3; x = 3;
switch (x + 3)
{
case 6: y = 1;
default: y += 1;
}
I'm at the beginning of the C++ hike. I don't know what do with this. It's not working in C++ Visual Studio 2013. I've put it in as is and nothing happens.
I use:
y = 3; x = 3;
switch (x + 3)
{
case 6: y = 1;
default: y += 1;
}
return 0;
}
And nothing happens. I have both the answers but I have no clue how to get them...
y is 2
if (x + 3 == 6)
y = 1;
y += 1;
I'm strictly supposed to be using
#include <iostream>
using namespace std;
int main()
{
return 0;
}
switch basics in C/C++:
switch expression is evaluated once, at the beginning. Then the 1st matching case is executed
after the case clause, the execution falls through to the next clause unless there's a break. Since this typically isn't what was indended, fall-throughs are normally documented with a comment or (if multiple cases refer to the same code) by stacking them together (case 2: case 3: <code>).

Ray Sphere Intersection: handling corner cases

I'm struggling with implementing a robust ray sphere intersection routine in 2d. I hacked a rather hudge function together which I'm unable to properly debug since it runs on the GPU. I got my inspiration from:
Circle line-segment collision detection algorithm?
and http://paulbourke.net/geometry/sphereline/. I have no idea where I should look for the error. Am I missing something obvious? The case where I check if the circle encloses the line is returned as a intersection since I'm interested in actual circle segment collision.
Here's the relevant code snippet:
bool CircleSegmentIntersection2d(float2 x0, float2 x1, float2 center, float r) {
float2 d = x1-x0;
float2 f = x0-center;
float a = dot2d(d,d);
float b = 2*dot2d(f,d);
float c = dot2d(f,f)-r*r;
float discriminant = b*b-4*a*c;
if( discriminant < 0 ) {
// no intersection
return false;
} else {
discriminant = sqrt(discriminant);
// either solution may be on or off the ray so need to test both
float sol1 = (-b + discriminant)/(2*a);
float sol2 = (-b - discriminant)/(2*a);
float t0 = min(sol1, sol2);
float t1 = max(sol1, sol2);
if (t1 < 0)
return false;
// Line segment doesn't intersect and on outside of sphere, in which case both values of t will either be less than 0 or greater than 1.
if (0 < t0 && 0 < t1 || t0 > 1 && t1 > 1)
return false;
// Line segment doesn't intersect and is inside sphere, in which case one value of t will be negative and the other greater than 1.
if (t0 < 0 && t1 > 1) {
return true;
}
// Line segment intersects at one point, in which case one value of t will be between 0 and 1 and the other not.
if (t0 < 0 && 0 <= t1 && t1 <= 1) {
return true;
}
// Line segment intersects at two points, in which case both values of t will be between 0 and 1.
if (0 <= t1 && t1 <= 1 && 0 <= t0 && t0 <= 1) {
return true;
}
// Line segment is tangential to the sphere, in which case both values of t will be the same and between 0 and 1.
if (length(t0-t1) < 0.005f) {
return true;
}
}
return false;
}
where dot2d is defined by:
float dot2d(float2 a, float2 b) {
return a.x*b.x+a.y*b.y;
}
Thanks for your time!

Resources