I have an external Numpad that has numbers from 0-9 and letters from A-D.
I want to store numbers from 0-9 in x and y as coordinates. When I press A(which equ. 10) I want to draw a point.
The problem is I can not figure out how to store first key in x and second key in y. As soon as I press a key it assigns both x and y the same numbers.
I have tried many different if-statements but it always assigns both x and y same number.
int counter=0;
numPad[16]={1,4,7,14,2,5,8,0,3,6,9,15,10,11,12,13};
if(numPad[key]<10){
x=numPad[key];
x*=16;
counter++;
}
if(counter>0 && numPad[key]<10){
y=numPad[key];
y*=8;
}
if(numPad[key]==10){
LCD_DrawPoint(x,y,WHITE);
counter=0;
}
Your if-statements for setting x and y, and drawing the point are mutually exclusive. if(numPad[key] < 10) and if(numPad[key] == 10) cannot be true at the same time. I'm not sure why you're making that comparison, but I think it is to cap the max possible input value at 9 or something. In the example below, we cap the max possible value of numPad[key] at 9, assign it to X and Y, then draw the point. The counter is useless here, but I kept it in because you had it in your original code.
int counter = 0;
numPad[16] = { 1,4,7,14,2,5,8,0,3,6,9,15,10,11,12,13 };
int someValue = numPad[key];
if(someValue > 9) {
someValue = 9;
}
x = someValue * 16;
y = someValue * 8;
LCD_DrawPoint(x,y,WHITE);
counter=0;
You could provide a minimum verifiable example next time as this will allow us to help you better.
By not providing sufficient code, those who might try to help can/will misunderstand and not "fill in the blanks" appropriately. Below is my interpretation of your question.
int x = 0, y = 0, counter = 0; // is all this contained inside one function?
int numPad[16] = { // layout increases reader comprehension
1, 4, 7, 14,
2, 5, 8, 0,
3, 6, 9, 15,
10, 11, 12, 13
};
for( ;; ) {
int key = scan_keyboard() // Not provided by OP
int value = numPad[ key ]; // translate
if( value < 10 ) {
// alternately assign scaled low values to x or y
if( !counter )
x = 16 * value;
else
y = 8 * value;
counter = !counter;
}
else if( value == 10 ) {
LCD_DrawPoint( x, y, WHITE );
x = y = counter = 0; // reset (excessive caution)
}
}
Notice the use of if/else.
Related
So I'm trying to make a recursive function that takes an integer, let's say 123, and gives back double every single digit in the integer. So 123 would become 248, not 246. The main difference obviously is that instead of doing 123x2, you do (100x2)+(20x2)+(3x2). There is also the condition that if any of the numbers are equal to or greater than 5, you replace it with a 9, so 345 becomes 689. I am trying to create it iteratively before making it recursively and I am running into an issue with the conditions. Heres what I have so far:
int double_digit(int g) {
int dubl = 0;
int mod = 10;
int i = 1;
while (g > 0) {
mod = pow(10, i);
if (g % 10 < 5) {
dubl = dubl + g % mod * 2;
g = g - (g % mod);
i++;
}
else {
dubl = dubl + (9 * (mod / 10));
g = g - (g % mod);
i++;
}
}
printf("%d", dubl);
}
If you run the code, you will see that it works for numbers under 5, but not greater than or equal to, how can I fix it?
WAY too complicated... A lookup table will shrink the code down to almost nothing. This even tries to protect against receiving a negative number.
int double_digit(int g) {
int dd = 0;
for( int w = abs(g), pow = 1; w; w /= 10, pow *= 10 )
dd += pow * "\0\02\04\06\10\011\011\011\011\011"[ w % 10 ];
return g < 0 ? 0 - dd : dd;
}
int main() {
int tests[] = { 42, 256, 123, 578, -3256, };
for( int i = 0; i < sizeof tests/sizeof tests[0]; i++ )
printf( "%d = %d\n", tests[i], double_digit( tests[i] ) );
return 0;
}
42 = 84
256 = 499
123 = 246
578 = 999
-3256 = -6499
EDIT:
C's understanding of octal bytes specified in a character array (aka string) may be new.
Here is an abridged alternative that may not be as confrontational:
int lut[] = { 0, 2, 4, 6, 8, 9, 9, 9, 9, 9, };
for( int w = abs(g), pow = 1; w; w /= 10, pow *= 10 )
dd += pow * lut[ w % 10 ];
And, then there are branchless techniques (overkill in this instance, but useful to consider in other applications):
for( int d, w = abs(g), pow = 1; w; w /= 10, pow *= 10 )
d = (w%10)<<1, dd += pow * (d*(d<9)+(d>8)*9);
In other words, there are lots of ways to achieve objectives. A good exercise is to try to discover those different ways and then to consider where each may be used to the most benefit (and where other methods may not appropriate or as clear.) Write clean, clear, concise code to the best of your abilities.
I've written the recursive version. Without accounting for negative values, the recursive version requires, to the best of my abilities, more code and takes a 'linear' (iterative) problem into other dimensions. Make the method fit the problem, not vice versa.
Card *createCard() {
/* This function dynamically allocates a new Card struct object and returns a
pointer to that struct object which will later be used to insert into a
linked list. There are three types of cards ATTACK, DEFEND, and RUN.
ATTACK and DEFEND cards also have a value.
You will assign a card type based on these random chances:
40% - ATTACK: the value is a random number between 1 and 5 inclusive.
50% - DEFEND: the value is a random number between 3 and 8 inclusive.
10% - RUN: the value is a random number between 1 and 8 inclusive.
The value of a RUN card is only used for sorting purposes.*/
Card *createdCard;
int n;
int v;
createdCard = (Card *)malloc(sizeof(Card));
n = (rand() % 10) + 1;
if (n == 1) {
createdCard->cardType = RUN;
v = (rand() % 8) + 1;
createdCard->value = v;
}
else if (n > 1 && n < 7) {
createdCard->cardType = DEFEND;
v = (rand() % 6) + 3;
createdCard->value = v;
}
else if (n > 6 && n < 10) {
createdCard->cardType = ATTACK;
v = ( rand() % 5) + 1;
createdCard->value = v;
}
createdCard->next = NULL;
return createdCard;
}
By the statement
n = (rand()%10)+1;
An integer from 1 to 10 (both inclusive) will be assigned to n.
n == 1 will be come true when n is 1.
n>1 && n<7 will become true when n is one of 2, 3, 4, 5, 6.
n>6 && n<10 will become true when n is one of 7, 8, 9.
Therefore, no assignment to createdCard->cardType and createdCard->value will performed and their value will remain indeterminate when n is 10.
If you use the indeterminate value, you will invoke undefined behavior and it seems you got zero by chance.
To resolve this issue, you should add else statement to cover n = 10 case and assign values to createdCard->cardType and createdCard->value.
Suppose rand() returns 9 here:
n = (rand()%10)+1;
Then n will be 10.
But there is no conditional statement that handles that case. This will likely cause createdCard->value to be 0 because it hasn't been initialized, and because free memory is sparse.
This will also happen when rand returns 19, 29, 39, 49, ... I e 10% of the time
I have a problem in some C code, I assume it belonged here over the Mathematics exchange.
I have an array of changes in x and y position generated by a user dragging a mouse, how could I determine if a straight line was drawn or not.
I am currently using linear regression, is there a better(more efficient) way to do this?
EDIT:
Hough transformation attempt:
#define abSIZE 100
#define ARRAYSIZE 10
int A[abSIZE][abSIZE]; //points in the a-b plane
int dX[10] = {0, 10, 13, 8, 20, 18, 19, 22, 12, 23};
int dY[10] = {0, 2, 3, 1, -1, -2, 0, 0, 3, 1};
int absX[10]; //absolute positions
int absY[10];
int error = 0;
int sumx = 0, sumy = 0, i;
//Convert deltas to absolute positions
for (i = 0; i<10; i++) {
absX[i] = sumx+=dX[i];
absY[i] = sumy+=dY[i];
}
//initialise array to zero
int a, b, x, y;
for(a = -abSIZE/2; a < abSIZE/2; a++) {
for(b = -abSIZE/2; b< abSIZE/2; b++) {
A[a+abSIZE/2][b+abSIZE/2] = 0;
}
}
//Hough transform
int aMax = 0;
int bMax = 0;
int highest = 0;
for(i=0; i<10; i++) {
x = absX[i];
y = absX[i];
for(a = -abSIZE/2; a < abSIZE/2; a++) {
for(b = -abSIZE/2; b< abSIZE/2; b++) {
if (a*x + b == y) {
A[a+abSIZE/2][b+abSIZE/2] += 1;
if (A[a+abSIZE/2][b+abSIZE/2] > highest) {
highest++; //highest = A[a+abSIZE/2][b+abSIZE/2]
aMax = a;
bMax = b;
}
}
}
}
}
printf("Line is Y = %d*X + %d\n",aMax,bMax);
//Calculate MSE
int e;
for (i = 0; i < ARRAYSIZE; i++) {
e = absY[i] - (aMax * absX[i] + bMax);
e = (int) pow((double)e, 2);
error += e;
}
printf("error is: %d\n", error);
Though linear regression sounds like a perfectly reasonable way to solve the task, here's another suggestion: Hough transform, which might be somewhat more robust against outliers. Here is a very rough sketch of how this can be applied:
initialize a large matrix A with zeros
transform your deltas to some absolute coordinates (x, y) in a x-y-plane (e.g. start with (0,0))
for each point
there are non-unique parameters a and b such that a*x + b = y. All such points (a,b) define a straight line in the a-b-plane
draw this "line" in the a-b-plane by adding ones to the corresponding cells in A, which represents the quantized plane
now you can find a maximum in the a-b-plane-matrix A, which will correspond to the parameters (a, b) of the straight line in the x-y-plane that has most support by the original points
finally, calculate MSE to the original points and decide with some threshold if the move was a straight line
More details e.g. here:
http://homepages.inf.ed.ac.uk/rbf/CVonline/LOCAL_COPIES/MARSHALL/node32.html
Edit: here's a quote from Wikipedia that explains why it's better to use a different parametrization to deal with vertical lines (where a would become infinite in ax+b=y):
However, vertical lines pose a problem. They are more naturally described as x = a and would give rise to unbounded values of the slope parameter m. Thus, for computational reasons, Duda and Hart proposed the use of a different pair of parameters, denoted r and theta, for the lines in the Hough transform. These two values, taken in conjunction, define a polar coordinate.
Thanks to Zaw Lin for pointing this out.
I'm looking for a way to find how often I can divide a constant x by two (and not get a remainder) without using loops, recursion or the logarithm. Since this is the same problem as finding the index of the least significant non-zero bit, I am hoping that there is some way to use bitwise operations to do this. Unfortunately I wasn't able to come up with it. Any ideas?
Background: I have a loop that doubles the counter on every iteration until it no longer divides the constant x. I want this loop to be unrolled, but the NVIDIA CUDA compiler isn't smart enough to figure out the number of iterations, so I want to rewrite the loop in such a way that the number of iterations becomes more obvious to the compiler:
for(i=1; CONST & i == 0; i *= 2)
bla(i);
should become something like
#define ITERATIONS missing_expr_with_CONST
for(i=0; i < ITERATIONS; i++)
fasel(i);
This can be directly solved using this code for 32 bit numbers (I take no credit).
unsigned int v; // find the number of trailing zeros in 32-bit v
int r; // result goes here
static const int MultiplyDeBruijnBitPosition[32] =
{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
r = MultiplyDeBruijnBitPosition[((uint32_t)((v & -v) * 0x077CB531U)) >> 27];
You can also do this with pure arithmetic without a lookup table (the De Bruijn sequence approach requires a lookup table), but it's expensive. Here it goes:
m = (v&-v)-1;
i = ((m)/((m)%255+1) / 255%255*8 + 7-86/((m)%255+12));
i is the index of the lowest-set bit in v. The formula is valid for values of v with up to 2000 or so zero bits, much larger than any integer type.
See here for an explanation:
Is there any way to compute the width of an integer type at compile-time?
Do a right shift, then a left shift and check for equality with AND, increment a counter for each time this check is successful.
int powerOfTwo(int x) {
int counter = 0;
while(x > 0) {
int y = x >> 1;
y <<= 1;
if(x ^ y) {
counter++;
} else {
break;
}
x >>= 1;
}
return counter;
}
This uses a loop though... I can think of ways of eliminating the loop but it's basically "unfolding" the loop.
This can be easily done with a loop (this might not be 100% correct, so feel free to correct):
int leastSigBit(int num) {
int result;
for(result = 0; num & 1 != 1; ++result)
num >>= 1;
return result;
}
But I believe this is impossible to do without a loop as you're searching for a bit at an unknown position and thus must check all possible positions.
EDIT Revised based on updated description.
If "pow" does not count as logarithm, here is a way to it for all numbers
not just "2". The inverse functions that multiply instead of divide are
also included for completeness.
GLSL code:
//://////////////////////////////////////////////////////////://
//://///://
//:IFDO: Move this somewhere more general IF you //://///://
//: ever find a need to call it from somewhere //://///://
//: else. //://///://
int //://///://
ES2_AA2_Di2( //://///://
int B //:BASE:(Affected_Number) //://///://
, int N //:NUMB:(Number_Of_Times_To_Divide_By_Two) //://///://
){ //://///://
//:programtic_equivalent_of_formula_below:---------------://
//: ://
//: var b = B; ://
//: for( var n = 0; n < N; n++ ){ ://
//: b = b / 2; ://
//: };; ://
//: return( b /** R **/ ); ://
//:______________________________________________________://
int R = int( float( 0 )
+ float( B )
/ pow( float(2) , float(N) )
);;
return( R );
return( int(0) );
}//://////////////////////////////////////////| ES2_AA2_Di2 |://
//://////////////////////////////////////////////////////////://
JavaScript Code:
//:B: Base //: MUL:A_NUMBER_OF_TIMES ://
//:N: N number of times. //: MUL:A_NUMBER_OF_TIMES ://
const AA2_Mu2=( B, N )=>{ return( B * (pow(2,N) ) ); };
const AA2_Mu3=( B, N )=>{ return( B * (pow(3,N) ) ); };
const AA2_Mu4=( B, N )=>{ return( B * (pow(4,N) ) ); };
const AA2_Mu5=( B, N )=>{ return( B * (pow(5,N) ) ); };
//:B: Base //: DIV:A_NUMBER_OF_TIMES ://
//:N: N number of times. //: DIV:A_NUMBER_OF_TIMES ://
const AA2_Di2=( B, N )=>{ return( B / (pow(2,N) ) ); };
const AA2_Di3=( B, N )=>{ return( B / (pow(3,N) ) ); };
const AA2_Di4=( B, N )=>{ return( B / (pow(4,N) ) ); };
const AA2_Di5=( B, N )=>{ return( B / (pow(5,N) ) ); };
Transcribing to C is left as an exercise to the reader.
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
I made the program but my answer doesnt match.
#include<stdio.h>
int main()
{
long unsigned int i,sum=0,x=1,y=2,num;
for(i=0;i<4000000;i++)
{
num=x+y;
if(i%2==0)
sum+=num;
x=y;
y=num;
}
printf("%lu\n",sum);
getchar();
return 0;
}
Three problems I can see:
You should start with x = 1, y = 1, since otherwise you skip the first even-valued Fibonacci;
Your loop condition should be (x + y) <= 4000000
You should test num for even-ness, not i.
(After these changes, it should be obvious that you can omit i entirely, and therefore replace the for loop with a while loop)
In your code you find the sum of fibonacci numbers with even index, not even numbers themselves + you search the first 4000000 numbers in sequence, not the numbers with values <= 4000000. Your code should be something like
while ( y < 4000000){
...
if (y %2 == 0)
sum += y;
}
I've made a minimal set of corrections and now get the right answer. You may learn more by reading this (after all, it was yours, to start with) than by me rambling on about it...
#include <stdio.h>
#define LIMIT (4 * 1000 * 1000)
int main() {
long unsigned int sum = 0, x = 1, y = 2, num;
while (x <= LIMIT) {
if ((x & 1) == 0 && x <= LIMIT)
sum += x;
num = x + y;
x = y;
y = num;
}
printf("%lu\n", sum);
return 0;
}
I think the following line
if(i%2==0)
might instead be
if( num % 2 == 0)
On further thinking, I think you don't actually need the variable i. Instead, your loop can be controlled by num as:
enum { LIMIT = 4 * 1000 * 1000 };
num = x + y;
while( num <= LIMIT ) {
print num inside the loop, for debugging
for(i=0;i<4000000;i++)
{
num=x+y;
printf("num is %lu\n", num); /* DEBUGGING */
if(i%2==0)
sum+=num;
x=y;
y=num;
}