Find the value of y according to condition:
I tried to do but something is wrong or I did not right so I need some help
#include <stdio.h>
int x, y;
int main() {
scanf("%d", &x);
if (x < 5)
y = x * x - 3 * x + 4;
else
y = x + 7;
printf("%d", y);
return 0;
}
Shouldn't it be:
if (x<-4) {
y=x+5;
} else if (x>=-4 && x<=7) {
y=x*x-3*x;
} else {
y=x*x*x+2*x
}
Here your piece-wise function has 3 segments in its domain. You have to divide you condition into three segments. Your syntax will be like this :
if(condition 1){
<statement 1>
}
else if(condition 2){
<statement 2>
}
else {
<statement 3>
}
Or you can use three 'if' statements to check the input value.
if(condition 1) {
<statement 1>
}
if(condition 2) {
<statement 2>
}
if(condition 3) {
<statement 3>
}
...
...
...
Hope you understand.
Related
I am making Conway's Game of life on an Arduino with a 64x64 dot matrix grid. it is working but its a little slow while running the full size. This is the code that I think is taking the longest:
int same;
int c;
// My code can run in different sizes so these needed to be writable.
int width1=64;
int height=64;
int row0[WIDTH]; // WIDTH is just the constant 64.
void check(int y)
{
int alive=0;
for(int x=0;x < width1;++x)
{
alive=0;
if(x > 0)
{
if(getPixelColor(x-1, y) > 0)
{
alive+=1;
//Serial.println("(left)");
}
}
if(x < width1-1)
{
if(getPixelColor(x+1, y) > 0)
{
alive+=1;
//Serial.println("(right)");
}
}
if(y > 0)
{
if(getPixelColor(x, y-1) > 0)
{
alive+=1;
//Serial.println("(top)");
}
if(x > 0)
{
if(getPixelColor(x-1, y-1) > 0)
{
alive+=1;
//Serial.println("(top left)");
}
}
if(x < width1-1)
{
if(getPixelColor(x+1, y-1) > 0)
{
alive+=1;
//Serial.println("(top right)");
}
}
}
if(row < height-1)
{
if(getPixelColor(x, y+1) > 0)
{
alive+=1;
//Serial.println("(bottom)");
}
if(x > 0)
{
if(getPixelColor(x-1, y+1) > 0)
{
alive+=1;
//Serial.println("(bottom left)");
}
}
if(x < width1-1)
{
if(getPixelColor(x+1, y+1) > 0)
{
alive+=1;
//Serial.println("(bottom right)");
}
}
}
god_Conway(x, y, alive);
}
}
void god_Conway(int x, int y, int a)
{
int born[]={3};
int survive[]={2, 3};
int kill=0;
bool birth1=0;
int living=getPixelColor(x, y);
if(living > 0)
{
if (a == 2 || a == 3)
{
kill=1;
}
else
{
kill=-1;
}
}
else
{
if (a == 3)
{
birth1=1;
}
}
if (kill == -1 || birth1 == 1)
{
for(int c=0;c<width1;c++)
{
if(row0[c]==-1)
{
row0[c]=x;
if(c,width1)
{
row0[c+1]=-1;
}
break;
}
}
}
if(kill == 1 || birth1 == 0)
{
same++;
}
}
This code checks around each pixel in a row and discovers how many pixels are on around a certain pixel. getPixelColor(x, y) is code I found for the matrix the reads the pixel's color and return a number greater than 0 if on. The check function takes about 29-30ms per row. Every millisecond counts.
I've tried a big if for just the non-edge pixels. getPixelColor(x, y) does not always return same number so dividing it by expected return number is not always accurate. I made a function to return 1 and 0 automatically then do alive+=That_function(x, y); but it slowed it down.
It only writes down the y of the pixels that needs changing on row0. The code that prints this stops when there is a -1.
Don't use the time consuming function getPixelColor to read the pixels from the display. Instead maintain the board in memory, e. g. static char board[64][64];, and keep a copy of the previous generation also in memory. If there is no library function to display the whole image at once, you need at least to call the presumed setPixelColor function only for the changed pixels.
You might even use a static char board[66][66]; with the image indexes 1..64 and spare yourself the edge considerations.
I am trying to solve ONP - Transform the Expression in spoj. The question is to transform infix expression into postfix expression. I have used std::stack as my data structure and shunting-yard algorithm for solving it. The code runs fine on my computer using g++. But on spoj, it gives SIGABRT error. Even on ideone, it gives run time error free() invalid pointer.
I have tried several test cases. At first, I thought that my program was taking too much memory, but upon testing with time -v (ubuntu), I found that the maximum space taken was in KB.
// ------------------- infix to postfix conversion ---------------
#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
#include <utility>
using std::stack;
using std::pair;
using std::cout;
using std::cin;
using std::endl;
using std::string;
stack< pair<char, short> > op_st; // operator stack
short op_precedence(char op) {
// return operator precedence
// input: operator; output: its precedence value
switch (op) {
case '+': return 0;
case '-': return 1;
case '*': return 2;
case '/': return 3;
case '^': return 4;
case '(': return 6;
}
}
inline bool is_operator(char sym) {
// is sym an operator?
return (sym == '+' || sym == '-' || sym == '*' || sym == '/' || sym == '^' || sym == '(');
}
inline bool is_operand(char sym) {
// is sym an operand?
return (sym >= 'a' && sym <= 'z');
}
void in_to_post(string & expr) {
// infix to postfix converter
// input: infix expression
for (int i = 0; i < expr.length(); ++i) {
if (is_operator(expr[i])) { // operator
// pop op_stack until the
// top of the stack has less precedence
// than curr operator or stack is empty
while(1) {
if (op_st.empty()) { // stack is empty; straight away push
op_st.push(std::make_pair(expr[i], op_precedence(expr[i])));
break;
}
pair <char, short> & top_op = op_st.top();
if (op_precedence(top_op.second) >= op_precedence(expr[i])) {
cout << top_op.first;
op_st.pop();
}
else {
op_st.push(std::make_pair(expr[i], op_precedence(expr[i])));
break;
}
}
}
else if (is_operand(expr[i])) { // operand; push it to output queue immediately
cout << expr[i];
}
else if (expr[i] == ')') { // right paranthesis
while (1) {
if (op_st.empty()) { // invalid expression; ')' reached before matching '('
//cout << "No matching '(' found\n";
abort();
}
pair <char, short> & top_op = op_st.top();
if (top_op.first == '(') { // matching '(' found; stop
op_st.pop();
break;
}
else {
cout << top_op.first;
op_st.pop();
}
}
}
}
// pop out the whole op_st (if any)
while (!(op_st.empty())) {
pair <char, short> & top_op = op_st.top();
cout << top_op.first;
op_st.pop();
}
}
int main() {
int t;
cin >> t;
for (int i = 0; i < t; ++i) {
string expr;
cin >> expr;
//cout << expr.length() << endl;
in_to_post(expr);
cout << "\n";
}
return 0;
}
Input to program given on my system:
((a+b)-c*(d+e))^((a+b)-c*(d+e))+((a+b)-c*(d+e))-((a+b)-c*(d+e))+((a+b)-c*(d+e))^((a+b)-c*(d+e))+((a+b)-c*(d+e))-((a+b)-c*(d+e))-((a+b)-c*(d+e))^((a+b)-c*(d+e))+((a+b)-c*(d+e))-((a+b)-c*(d+e))*((a+b)-c*(d+e))^((a+b)-c*(d+e))+((a+b)-c*(d+e))-((a+b)-c*(d+e))^((a+b)-c*(d+e))^((a+b)-c*(d+e))+((a+b)-c*(d+e))-((a+b)-c*(d+e))+((a+b)-c*(d+e))^((a+b)-c*(d+e))+((a+b)-c*(d+e))-((a+b)-c*(d+e))^((a+b)-c*(d+e))^((a+b)-c*(d+e))+((a+b)-c*(d+e))-((a+b)-c*(d+e))
Successfully gives the output:
ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*-ab+cde+*--+^^-+^+-+^^-+^*-+^--+^+-+^.
But, the same code gives free() invalid pointer error in ideone. Why is that?
op_precedence(top_op.second) calls op_precedence with the number returned by earlier op_precedence call - not with the operator character.
When op_precedence is passed an argument that doesn't match one of the recognized operators, the program exhibits undefined behavior, by way of reaching the end of a non-void function without encountering a return statement.
So, after Igor Tandetnik kindly pointed the mistake to me, in line 58, I changed op_precedence(top_op.second) to top_op.second. I also added default case to op_precedence function to correct the warning. After compiling and running, this code did actually abort() on line 75 for simple input ((a+b)). It turns out, that my implementation of the algorithm was wrong. My code didn't take into consideration associativity of operator '('. According to the question, we don't need to take into consideration associativity for other operators but for '(' we need its precedence to be higher than all other operators when outside of the stack, and lower than all other operators when inside of the stack. This is to ensure that when any operator other than '(' is the input and the top of the stack is '(', we could push the input operator into the stack. The corrected code is below:
// ------------------- infix to postfix conversion ---------------
#include <iostream>
#include <string>
#include <stack>
#include <algorithm>
#include <utility>
using std::stack;
using std::pair;
using std::cout;
using std::cin;
using std::endl;
using std::string;
short op_out_precedence(char op) {
// return operator precedence (when outside of stack)
// in and out precedence is to take care of associativity
// Here we don't require the associativity of any other operator except '('
// input: operator; output: its precedence value
switch (op) {
case '+': return 1;
case '-': return 2;
case '*': return 3;
case '/': return 4;
case '^': return 5;
case '(': return 6;
default : abort(); // not supposed to happen
// operator can't be other than the mentioned cases
}
}
short op_in_precedence(char op) {
// return operator precedence (when inside of stack)
// in and out precedence is to take care of associativity
// Here we don't require the associativity of any other operator except '('
// input: operator; output: its precedence value
switch (op) {
case '+': return 1;
case '-': return 2;
case '*': return 3;
case '/': return 4;
case '^': return 5;
case '(': return 0;
default : abort(); // not supposed to happen
// operator can't be other than the mentioned cases
}
}
inline bool is_operator(char sym) {
// is sym an operator?
return (sym == '+' || sym == '-' || sym == '*' || sym == '/' || sym == '^' || sym == '(');
}
inline bool is_operand(char sym) {
// is sym an operand?
return (sym >= 'a' && sym <= 'z');
}
void in_to_post(string & expr) {
// infix to postfix converter
// input: infix expression
stack< pair<char, short> > op_st; // operator stack
int len = expr.length();
for (int i = 0; i < len; ++i) {
if (is_operator(expr[i])) { // operator
// pop op_stack until the
// top of the stack has less or equal precedence
// than curr operator or stack is empty
while(1) {
if (op_st.empty()) { // stack is empty; straight away push
op_st.push(std::make_pair(expr[i], op_in_precedence(expr[i])));
break;
}
pair <char, short> & top_op = op_st.top();
if (top_op.second > op_out_precedence(expr[i])) {
cout << top_op.first;
op_st.pop();
}
else {
op_st.push(std::make_pair(expr[i], op_in_precedence(expr[i])));
break;
}
}
}
else if (is_operand(expr[i])) { // operand; push it to output queue immediately
cout << expr[i];
}
else if (expr[i] == ')') { // right paranthesis
while (1) {
if (op_st.empty()) { // invalid expression; ')' reached before matching '('
cout << "No matching '(' found\n";
abort();
}
pair <char, short> & top_op = op_st.top();
if (top_op.first == '(') { // matching '(' found; stop
op_st.pop();
break;
}
else {
cout << top_op.first;
op_st.pop();
}
}
}
}
// pop out the whole op_st (if any)
while (!(op_st.empty())) {
pair <char, short> & top_op = op_st.top();
cout << top_op.first;
op_st.pop();
}
}
int main() {
int t;
cin >> t;
for (int i = 0; i < t; ++i) {
string expr;
cin >> expr;
//cout << expr.length() << endl;
in_to_post(expr);
cout << "\n";
}
return 0;
}
Currently I'm learning how to create games (at a low level) at my degree. I'm programming on Ubuntu mate 16.04, Codeblocks 13.12 and this happen:
-------------- Build: Debug in s04 (compiler: GNU GCC Compiler)---------------
g++ -o bin/Debug/s04 obj/Debug/main.o obj/Debug/Pantalla.o
obj/Debug/main.o: file not recognized: File format not recognized
collect2: error: ld returned 1 exit status
Process terminated with status 1 (0 minute(s), 0 second(s))
0 error(s), 0 warning(s) (0 minute(s), 0 second(s))
I must create a new window where my "game" will run... (I add code)
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "Pantalla.h"
//Ej.1
struct BalaRep
{
int x;
int y;
int vx;
int vy;
};
typedef struct BalaRep * Bala;
//Ej.2
Bala crea_bala ( double x, double y, double vx, double vy )
{
Bala b=malloc(sizeof(struct BalaRep));
b->x = x;
b->y = y;
b->vx = vx;
b->vy = vy;
return b;
}
//Ej.3
void libera_bala( Bala b )
{
free(b);
}
//Ej.4
void mueve_bala( Bala b )
{
b->x = (b->x)+ (b->vx);
b->y = (b->y)+ (b->vy);
}
//Ej.5
void dibuja_bala( Bala b )
{
Pantalla_DibujaRectangulo( b->x, b->y, 7, 7);
}
//Ej.6
/*
double get_x_bala( Bala b )
{
return b->x;
}
*/
//Ej.7
/*
double get_y_bala( Bala b )
{
return b->y;
}
*/
int main( int argc, char *argv[] )
{
Pantalla_Crea("Ejemplo 3", 640,480);
Pantalla_ColorTrazo(255,0,0, 255);
int x = 280;
int y = 425;
int x2 = 200;
int y2 = 100;
int vx2 = 5;
Bala b = NULL;
while ( Pantalla_Activa() )
{
//Crear bala
if (Pantalla_TeclaPulsada(SDL_SCANCODE_SPACE))
{
libera_bala(b);
b=NULL;
b=crea_bala(x,y,0,-10);
}
//Movimiento del rectángulo
if (Pantalla_TeclaPulsada(SDL_SCANCODE_RIGHT))
{
x = x + 5;
}
if (Pantalla_TeclaPulsada(SDL_SCANCODE_LEFT))
{
x = x - 5;
}
/*if (Pantalla_TeclaPulsada(SDL_SCANCODE_UP))
{
y = y - 5;
}
if (Pantalla_TeclaPulsada(SDL_SCANCODE_DOWN))
{
y = y + 5;
}*/
//Bordes no-salir
if (x > 640-80)
{
x = 640 - 80;
}
if (x < 0)
{
x = 0;
}
if (y > 480-40)
{
y = 480 - 40;
}
if (y < 0)
{
y = 0;
}
//Mov enemigo
x2 = x2 + vx2;
//Bordes no-salir enemigo
if (x2 > 640-80)
{
x2 = 640 - 80;
vx2 = vx2 * (-1);
}
if (x2 < 0)
{
x2 = 0;
vx2 = vx2 * (-1);
}
//BALA
if (b!=NULL)
{
mueve_bala(b);
}
if ((b!=NULL) && ((b->y) <= 0))
{
libera_bala(b);
b=NULL;
}
Pantalla_DibujaRellenoFondo( 255,255,255, 255 );
Pantalla_DibujaRectangulo( x, y, 80,40 );
Pantalla_DibujaRectangulo( x2, y2, 80,40 );
if (b!=NULL)
{
dibuja_bala(b);
}
Pantalla_Actualiza();
Pantalla_Espera(40);
}
Pantalla_Libera();
return 0;
}
There is a file that teachers give us to run it properly. Furthermore, my classmate run the same code (what I add) on his laptop and it works. Excuse me, I know my English is bad...
Obviously the object files are incompatible either because your build process is broken or if your professor just gives you the compiled object file, because it is not ABI compatible with your implementation i.e. compiler, OS, architecture.
I am using clang-format to prettify some existing code. I want to insert a newline between two if conditions, like below code :
int main()
{
int x;
int y;
if (x == 1)
{
}
if(y == 2)
{
}
return 0;
}
should be changed to
int main()
{
int x;
int y;
if (x == 1)
{
}
/* inserted a newline */
if(y == 2)
{
}
return 0;
}
Can this be done using clang-format?
No you can't.
clang-format just format code, it can not modify code. Your case is modifing AST of source code. Use RecursiveASTVisitor to find position
you want insert, then rewrite back to code.
Or you can just write a regex script, insert what you want. :)
Thank you ,
i am trying to solve a project euler problem it wants me to print the sum of
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
this is formed by starting with the number 1 and moving to the right in a clockwise direction for a 5 by 5 matrix but i am in trouble writing a code for the spiral matrix !!
It is Highly recommended to do project Euler problems on your own and ask for help if you are really stuck
here is how i will write a code in c to print a spiral as suggested in the question
#include<stdio.h>
main()
{
int i,j,nq=9;//nq is a odd number which represents the order of the matrix
int lim=(int)nq/2,cnt=2;
int a[nq][nq];
for(i=0;i<nq;i++){
for(j=0;j<nq;j++)
a[i][j]=0;
}
a[lim][lim]=1;
a[lim][lim+1]=2;
int i1=lim,j1=lim+1;i=lim,j=lim;
while(1){
if(cnt>(nq*nq))
break;
cnt++;
if(i==i1)
{ j=j1;
if(i<=lim)
{
i=i1;
if(a[i1+1][j1]==0)
a[++i1][j]=cnt;
else
a[i1][++j1]=cnt;
}
else
{ i=i1;
if(a[i1-1][j1]==0)
a[--i1][j1]=cnt;
else
a[i1][--j1]=cnt;
}
}
else
{ i=i1;
if(j<lim)
{
j=j1;
if(a[i1][j+1]==0)
a[i1][++j1]=cnt;
else
a[--i1][j1]=cnt;
}
else
{ j=j1;
if(a[i1][j1-1]==0)
a[i1][--j1]=cnt;
else
a[++i1][j1]=cnt;
}
}
}
for(i=0;i<nq;i++){
for(j=0;j<nq;j++)
printf(" %d ",a[i][j]);
printf("\n");
}
}
I Googled your question http://projecteuler.net/problem=28 this can also be solved by taking advantage of its mathematical nature note that
Top right corner is n^2
and other corners can be shown to be n^2-2n+2 ,n^2-n+1, and n^2-3n+3. you just need to sum those corners which comes to be
= 4*n^2 - 6*n + 6
hence the final answer can be calculated by iterating over every second number from 1001 to 3
long int sum(int n){
long int sum=1;
while(n>1){
sum=sum+4*n*n-6*n+6;
n=n-2;
}
return sum;
}
I dont know whether you actually want to print the spiral but see below for my solution for #28 written in Python 2.7.
l = [1]
def corners(step,l):
counter = 0
while counter < 4:
l.append(max(l)+step)
counter +=1
return l
step = 2
while step < 1001:
l = corners(step, l)
step += 2
print sum(l)
void printSpiral(int A[3][5],int m, int n)
{
int T=0; int B=m-1; int L=0; int R=n-1;
int dir=0;
int i =0; int j=0; int k=0; int l=0;
while(T<=B && L<=R)
{
//printf("dir %d ",dir);
if(dir == 0)
{
for( i=L;i<=R;i++)
{
printf("%d ",A[T][i]);
//printf("\n");
}
T++;
dir=1;
}
else if(dir == 1)
{
// printf("%d R ",R);
for( j=T;j<= B;j++)
{
printf("%d ",A[j][R]);
//printf("\n");
//printf("dir1");
}
dir=2;
R--;
}
else if(dir == 2)
{
for(k=R;k>= L;k--)
{
printf("%d ",A[B][k]);
}
dir=3;
B--;
}
else if(dir == 3)
{
for( l=B;l>= T;l--)
{
printf("%d ",A[l][L]);
}
L++;
dir=0;
}
}
}