C++/CUDA equation printing negative for 2 positives [duplicate] - cuda

This question already has answers here:
Detecting signed overflow in C/C++
(13 answers)
Closed 2 months ago.
I am currently trying to run this equation with a ton of different inputs (x+y)^2 / xy
I have noticed an issue when i get x = 46340 and y = 1
It seems to output -46341 as seen here.
__global__ void proof() {
int x = 1;
int y = 1;
int multi_number = 100000;
bool logged = false;
while (true) {
long eq = ((x + y) * (x + y)) / (x * y);
if (x >= multi_number) {
x = 1;
y = y + 1;
}
if (eq < 4) {
if (logged == true) {
continue;
}
printf("\nGPU: Equation being used: (%d", x);
printf("+%d", y);
printf(")^2 / %d", x);
printf("*%d", y);
printf(" >= 4");
printf("\nGPU: Proof Failed: %d", x);
printf(", %d", y);
logged = true;
continue;
}
if (y >= multi_number) {
if (x >= multi_number) {
if (logged == true) {
continue;
}
printf("\nGPU: Proof is true for all cases.");
logged = true;
continue;
}
}
printf("\nGPU: Equation being used: (%d", x);
printf("+%d", y);
printf(")^2 / %d", x);
printf("*%d", y);
printf(" >= 4");
printf("\nGPU: %d", eq); // printing the equation
x = x + 1;
}
}
I have tried rewriting the equation and even putting the equation into a calculator. The calculator always gave a different response than the code is currently outputting, I have since double checked what I have put into the calculator and it remains the same.
I was expecting an output of 46342.

int overflow, used longs instead to fix the issue.

Related

using a function to compare integers and find the position where one value is even and the other is odd c++

/*
Description:
Write a function called digitsOpposite. The function has two integer parameters x and y that are
positive and have the same number of digits. It returns the number of positions where one number
has an even digit and the other has an odd one. For example, if the function was applied to 17345
and 97813 it would return 2 because the third digits are 3 and 8 and the fourth ones are 4 and 1.
(In both cases one of these is even and the other is odd.)
Problem: my code is not printing the desired output. HELP PLEASE!! I am a beginner. Thanks.
*/
#include <iostream>
using namespace std;
// declare function
int digitsOpposite(int x, int y){
int lastV1, lastV2, leftV1, leftV2;
leftV1 = 0,
leftV2 = 0;
lastV1 = 0;
lastV2 = 0;
for(int i = 5; i > 0; i--){
leftV1 += x; // 17345
leftV2 += y; // 97813
lastV1 += leftV1 % 2; //5
lastV2 += leftV2 % 2; //3
if((lastV1 == 0)&&( lastV2 != 0))
{
break;
return i;
}
else{
leftV1 += leftV1 / 10; // 1734
leftV2 += leftV2 / 10; // 9781
}
}
}
int main(){
cout <<"The position of the number is: " << digitsOpposite(17345, 97813);
return 0;
}

Codility CyclicRotation in-place implementation

I can't wrap my head around my solution for the problem:
A zero-indexed array A consisting of N integers is given. Rotation of the array means that each element is shifted right by one index, and the last element of the array is also moved to the first place.
For example, the rotation of array A = [3, 8, 9, 7, 6] is [6, 3, 8, 9, 7]. The goal is to rotate array A K times; that is, each element of A will be shifted to the right by K indexes.
I wanted to create solution without creating new array, but just modifying the one in place. It works... most of the time. Example tests pass, and other also pass, but some, for which Codility doesn't show the input, fail.
public int[] solution(int[] A, int K) {
for (var i = 0; i < A.Length - 1; i++) {
var destIndex = (i * K + K) % A.Length;
var destValue = A[destIndex];
A[destIndex] = A[0];
A[0] = destValue;
}
return A;
}
I've skipped the code related to the fact that you don't need to rotate whole array few times (ie. rotating by A.Length % K is enough).
What's wrong with my implementation? Am I missing some corner case?
The algorithm for this should be very simple, like:
aux <- array[array.Length - 1]
for index = 0, array.Length - 2 do
array[index + 1] <- array[index]
array[0] <- aux
endfor
Note, that in the special cases when array.Length <= 1, you do not need anything to achieve the rotation. If you want to achieve K rotations without an array, you can call this K times.
You will need to be tricky to achieve an optimal algorithm. Here I will take the following approach. An array's given element can have three different possible states. I explain it through the example. If I put the K'th element into a variable called aux and place the 0'th element in its place, then we have the following three states:
at element 0 the original element was already moved to another place, but the final element did not arrive yet. This is the moved state
at element K the original element was already moved and the final element already arrived there. This is the arrived state
at element 2 * K we did nothing so far, so there we have the original state
So, if we can mark somehow the elements, then the algorithm would look like this:
arrivedCount <- 0 //the number of arrived elements is counted in order to make sure we know when we need to search for an element with an original state
index <- 0
N <- array.Length
aux <- array[index]
mark(array[index], moved)
index <- (index + K) mod N
while arrivedCount < N do
state <- array[index]
if (state = moved) then
array[index] <- aux
arrivedCount <- arrivedCount + 1
mark(array[index], arrived)
if arrivedCount < N then
while (state(array[index]) <> original) do
index <- (index + 1) mod N
endwhile
aux <- array[index]
mark(array[index], moved)
index <- (index + K) mod N
endif
else //it is original
aux2 <- array[index]
array[index] <- aux
aux <- aux2
arrivedCount <- arrivedCount + 1
mark(array[index], arrived)
index <- (index + K) mod N
endif
endwhile
Now, how could we use this in practice? Let's consider the example when your array only has positive numbers as value. You mark all elements at start by assigning them their negative value (-5 instead of 5, for example). Whenever a state is modified to move, it will have a value of 0 and whenever it is arrived, you will have the positive number. It is up to you to define how you can mark such elements and you will need to do this in conformity with your task. If you are unable to mark the elements for any reason, then you will need to create an auxiliary array in order to solve this.
EDIT
Do not be afraid of the while, it should not search for too many steps because of the modulo classes. An implementation in Javascript:
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var arrivedCount = 0;
var index = 0;
var N = array.length;
var K = 3;
for (var i = 0; i < array.length; i++) array[i] = -array[i];
var aux, aux2, state;
aux = array[index];
array[index] = 0;
index = (index + K) % N;
var step = 0
while ((arrivedCount < N) && (++step < 1000)) {
if (array[index] === 0) {
array[index] = -aux;
arrivedCount++;
if (arrivedCount < N) {
while (array[index] >= 0) index = (index + 1) % N;
aux = array[index];
array[index] = 0;
index = (index + K) % N;
}
} else {
aux2 = array[index];
array[index] = -aux;
aux = aux2;
arrivedCount++;
index = (index + K) % N
}
}
Change the definition of array and K according to your will.
I've finally managed to find out what's wrong with my solution thanks to #dvaergiller who posted the question with a similar to mine approach: Fastest algorithm for circle shift N sized array for M position
This answer made me realize my solution is failing every time the greatest common divisor of A.Length and K is not 1. #IsaacTurner solution is much easier to understand, and also shows there's no need to constantly switch places of elements, but now I see I can correct my solution.
I basically should not go through all elements in the array to find correct place for every one of them, because if the greatest common divisor is not 1 I'll start switching elements again. Instead it must be stopped as soon as full cycle is made and restarted to start switching based on next position.
Here's corrected version of my solution:
int gcd(int a, int b) => b == 0 ? a : gcd(b, a % b);
public int[] solution(int[] A, int K)
{
for (var i = 0; i < gcd(A.Length, K); i++)
{
for (var j = i; j < A.Length - 1; j++)
{
var destIndex = ((j-i) * K + K + i) % A.Length;
if (destIndex == i) break;
var destValue = A[destIndex];
A[destIndex] = A[i];
A[i] = destValue;
}
}
return A;
}
You can try this, I got a 100%:
public int[] solution(int[] A, int K) {
if (A.length == 0) {
return A;
}
for (int i=0;i<K;i++) {
int[] aux = new int[A.length];
aux[0] = A[A.length-1];
System.arraycopy(A, 0, aux, 1, A.length - 1);
A = aux;
}
return A;
}
The time complexity of this would be really less :)
I tried a different approach I believe, without loops:
https://app.codility.com/demo/results/trainingE33ZRF-KGU/
public static int[] rotate(int[] A, int K){
if ( K > A.length && A.length > 0)
K = K % A.length;
if (K == A.length || K == 0 || A.length == 0){
return A;
}
int[] second = Arrays.copyOfRange(A, 0, A.length - (K));
int[] first = Arrays.copyOfRange(A, A.length - (K), A.length );
int[] both = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, both, first.length, second.length);
return both;
}
Each element is shifted right by one index, and the last element of the array is also moved to the first place.
public int[] solution(int[] A, int K) {
if (K > 0 && A.length > 0) {
K = K % A.length;
int[] B = new int[A.length];
for (int i = 0; i < A.length; i++) {
if ((i + K) > (A.length - 1)) {
B[i + K - A.length] = A[i];
} else {
B[i + K] = A[i];
}
}
return B;
} else {
return A;
}
}

Explanation of test case in the prisoner wall jump program

This would be the general problem statement:
A prisoner escapes from the jail by jumping over N walls each with height of each wall given in an array. He can jump x meters of height, but after every jump he slips y meters due to some uncontrollable factors(wind, slippery wall, etc).
Similar problem statement mentioned here
The programming task given was to debug a function which included four parameters -
NoOfJumps(int x, int y, int N, int Height[])
Number of meters he jumps
Number of meters he slips down the wall
Number of walls
Height of the walls as an array
The first test case was for parameters - (10, 1, 1, {10})
10 being the meters he jumps, 1 meter he slips down, Number of walls being 1, and height of the wall being 10. Now:
effectiveJump = x - y = 9.
So he would have to jump twice to jump over the walls. So, this function should return 2 (total number of jumps required to escape).
There was also another test case for the parameters - (3, 1, 5, {20,5,12,11,3})
3 being the meters he jumps, 1 meter he slips down, Number of walls being 5, and height of the walls given as 20m, 5m, 12m, 11m, 3m. Now:
effectiveJump = x - y = 2.
We were given the output for the above parameter values as 24.
NoOfJumps(3, 1, 5, {20,5,12,11,3})
I can't understand how this output value is obtained. How exactly are the walls arranged?
I can only think of one solution for the corner case, i.e, when the person jumps over the wall
(when (x) > remaining height of the wall),
he should not slip down else I can't obtain the required solution.
For example, in the second test case at first wall, when the person is at 18m height, and he jumps 3m to 21m and doesn't slip down as he has crossed that wall. Next he starts jumping from 21 and not 20. The sequence of jumping would be :
0->2->4->6->8->10->12->14->16->18->21->23->26->28->30->32->34->36->39->41->43->45->47->50->53
Assuming walls at height, 20, 25, 37, 48, 51.
Is this a correct assumption for solving the problem?
C code on given case 2, will work for case 1 on changing the
parameters to (10,1,1,10).
#include<conio.h>
#include<stdio.h>
int jump(int x,int y,int n,int z[]);
int jump(int x,int y,int n,int z[])
{
int i, j, countjump, total = 0, extra = 0;
clrscr();
printf("\n%d\n", n);
for (i = 0; i < n; i++) {
printf("\n%d", z[i]);
}
printf("\n");
for (j = 0; j < n; j++) {
countjump = 1;
z[j] = z[j] + (extra) - x;
while (z[j] >= 0) {
z[j] = z[j] + y;
z[j] = z[j] - x;
countjump = countjump + 1;
if (z[j] < 0) {
extra = z[j];
}
}
total = (countjump + total);
}
return total;
}
void main()
{
int res, manjump = 3, slip = 1, nwalls = 5;
int wallheights[] = {20, 5, 12, 11, 3};
clrscr();
res = jump(manjump, slip, nwalls, wallheights);
printf("\n\ntotal jumps:%d", res);
getch();
}
Try this code. May not be optimized
$input1 = Jump Height
$input2 = Slipage
$input = Array of walls height
function GetJumpCount($input1,$input2,$input3)
{
$jumps = 0;
$wallsCrossed = 0;
while($wallsCrossed != count($input3)){
$jumps++;
$input3[$wallsCrossed] = $input3[$wallsCrossed] - $input1;
if($input3[$wallsCrossed] > 0){
$input3[$wallsCrossed] = $input3[$wallsCrossed] + $input2;
}else{
$wallsCrossed++;
}
}
return $jumps;
}
The walls come one after another. After jumping wall one the position should start from zero and not from the last jump height. For the first case the output should really be 1 as the height and jump are same. In the second test case, 24 is the right output.
I've seen the exact same question on techgig contest. For the first test case the output should be 1. The test case had been explained by themselves where there is no slipping if the jump and height are same.
Try this
You don't require the number of walls as it equals to size of array
public class Jump {
public static void main(String[] a) {
int jump = 3;
int slip = 1;
int[] hights = {20,5,12,11,3};
int count = 0;
for (int hight : hights) {
int temp = hight - jump;
if (temp >= 0) {
count = count + temp / (jump - slip)+1;
}
if (temp % (jump - slip) > 0) {
count++;
}
}
System.out.println(count);
}
}
Logic is here Plz check if this solves your problem.
package puzeels;
public class Jump
{
int jump=6;
int slip=1;
int numberOfWals=4;
int height[] ={21,16,10,5};
static int count=0;
int wallheight=0;
private int findJump()
{
for(int i=0;i<height.length;i++)
{
wallheight=height[i];
while((wallheight>0))
{
count=count+1;
wallheight=wallheight-(jump-slip);
System.out.println(wallheight+" "+count);
}
System.out.println("Out of while loop");
}
return count;
}
public static void main(String arr[])
{
Jump obj = new Jump();
int countOfJumps=obj.findJump();
System.out.println("number of jumps is==> "+countOfJumps);
}
}
You can use this one.
Sample Code
public static int calculateJumps(int X, int Y, int height[]) {
int tn=0,n;
for(int i=0; i<height.length; i++) {
if(height[i]<=X) {
tn+=1;
continue;
}
n=((height[i]-X)/(X-Y));
n+=height[i]-((X-Y)*n)==X?1:2;
tn+=n;
}
return tn;
}
You need to pass only X , Y and Array than you can get you output.
I think 12 is a wrong answer, as I tried this code I got 11, last jump doesn`t have a slip:
public static void main(String [] args) {
int T;
int jcapacity, jslip, nwalls;
//BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
Scanner sc = new Scanner(System.in);
T = sc.nextInt();
jcapacity = sc.nextInt();
jslip = sc.nextInt();
nwalls = sc.nextInt();
int [] wallHeightArr = new int [nwalls];
for (int i = 0; i< nwalls; i++) {
wallHeightArr[i] = sc.nextInt();
}
sc.close();
while(T-->0) {
int distance = log(jcapacity,jslip,wallHeightArr);
System.out.println(distance);
}
}
private static int log(int jcapacity, int jslip, int[] wallHeightArr) {
// TODO Auto-generated method stub
int distance = 0;
for(int i = 0; i< wallHeightArr.length; i++) {
int cHeight = 0;
int count = 0;
while (wallHeightArr[i] - cHeight > jcapacity) {
cHeight += (jcapacity - jslip);
count++;
}
count++;
distance += count;
}
return distance;
}
def jumpTheifCount(arr, X, Y):
jump = 0
remheight = 0
for i in range(len(arr)):
if X == arr[i]:
jump = jump + 1
continue
if X < arr[i]:
jump = jump + 1
remheight = arr[i] - X + Y
if remheight > X:
jump = jump + 1
remheight = arr[i] - X + Y
if remheight < X:
jump = jump + 1
continue
return jump
arr = [11, 10, 10, 9]
X = 10
Y = 1
print(jumpTheifCount(arr, X, Y))
check if this solves your problem
def GetJumpCount(jump, slips, walls):
"""
#jump:int, Height of 1 jump
#slips:int, height of slip
#walls:array, height of walls
"""
jumps = []
for wall_height in walls:
wall_jump = 1
wall_height -= jump
while wall_height > 0:
wall_height += slips
wall_height -= jump
wall_jump += 1
jumps.append(wall_jump)
return sum(jumps)

Trying to test validity of a sudoku puzzle: Having trouble with checking for duplicates in each 3x3 square

Here's my method:
public static boolean hasDuplicatesInSections(int[][] puzzle){
z = 2;
w = 0;
while(z <= 8){
for(i = w; i <= z; i++){
for(j = w; j <= z; j++){
for(l = w; l <= z; l++){
for(k = w; k <= z; k++){
if ((puzzle[l][k] == puzzle[i][j]) &&
(puzzle[l][k] != 0) &&
(k != j)){
System.out.println("There was a match in a square. Shame on you.");
return true;
}
}
}
}
}
z += 3;
w += 3;
}
System.out.println("There wasn't a match in a square. Good job!");
return false;
}
I made a 9x9 2-D int array for the puzzle. 0 means there's just a blank space. The method looks through each 3x3 square and says whether duplicates were found in one. But sometimes it still says there wasn't a match when there was. Can anybody see what might be wrong?
Found what was wrong. All of my comparisons and iterations were correct except for when I checked:
(k != j))
It was only checking if a column wasn't equal to a column which is wrong. So what I did is just add the indexes of the rows and columns and then compare them like so:
(l+k) != (i+j))
Which worked perfectly!

ideal lowpass filter with fftw

again I am still trying to get my lowpass filter running, but I am at a point where I do not know why this is still not running. I oriented my code according to FFT Filters and my previous question FFT Question in order to apply an ideal low pass filter to the image. The code below just makes the image darker and places some white pixels in the resulting image.
// forward fft the result is in freqBuffer
fftw_execute(forward);
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
uint gid = y * w + x;
// shifting coordinates normalized to [-0.5 ... 0.5]
double xN = (x - (w / 2)) / (double)w;
double yN = (y - (h / 2)) / (double)h;
// max radius
double maxR = sqrt(0.5f * 0.5f + 0.5f * 0.5f);
// current radius normalized to [0 .. 1]
double r = sqrt(xN * xN + yN * yN) / maxR ;
// filter response
double filter = r > 0.7f ? 0.0f : 1.0f;
// applying filter response
freqBuffer[gid][0] *= filter;
freqBuffer[gid][1] *= filter;
}
}
// normlization (see fftw scaling)
for (uint i = 0; i < size; i++)
{
freqBuffer[i][0] /= (float)size;
freqBuffer[i][1] /= (float)size;
}
// backward fft
fftw_execute(backward);
Some help would be appreciated.
Wolf
If you have a filter with a step response in the frequency domain then you will see significant sin(x)/x ringing in the spatial domain. This is known as the Gibbs Phenomenon. You need to apply a window function to the desired frequency response to mitigate this.