Expression Result Unused Greedy Algorithm - c

I have run this program and get the error expression result unused. I may be doing something simple wrong, but I have spent the day trying to figure it out to no avail. Any help you can provide is greatly appreciated.
#include <stdio.h>
#include <cs50.h>
int main()
{
int x, y = 0;
printf("Enter the amount of change ");
x = GetFloat() * 100;
while (x != 0)
{
if (x >= 25)
{
x - 25;
y = y + 1;
}
if (x >= 10 && x < 25)
{
x - 10;
} y = y + 1;
if (x >= 5 && x < 10)
{
x - 5;
} y = y + 1;
if (x >= 1 && x < 5)
{ x - 1;
y= y + 1;
}
}
printf("The number of coins neccessary is %d", y);
}

if (x >= 25)
{
x - 25; // This accomplishes nothing
y = y + 1;
}
if (x >= 10 && x < 25)
{
x - 10; // This accomplishes nothing
} y = y + 1;
if (x >= 5 && x < 10)
{
x - 5; // This accomplishes nothing
} y = y + 1;
if (x >= 1 && x < 5)
{
x - 1; // This accomplishes nothing
y= y + 1;
}
In each of those lines you're subtracting a number from x, but you're doing nothing with the result. If you're trying to update x with the result, you need to do just like you're doing with y, and put x = in front of the expression.
So if you want x to go down by 25, you should write:
x = x - 25;
Alternatively, you can write the shorthand:
x -= 25; // Note the equal sign

All the 4 statements x - 25, x- 10, x- 5, x - 1 will turn out to be useless unless you assign that value to x;
Because you are trying to subtract the value from x, but you are not assigning the new value to x.
Here is the solution of your problem:
#include <stdio.h>
#include <cs50.h>
int main()
{
int x, y = 0;
printf("Enter the amount of change ");
x = GetFloat() * 100;
while (x != 0)
{
if (x >= 25)
{
x = x - 25; //or x-=25;
y = y + 1;
}
if (x >= 10 && x < 25)
{
x = x - 10; //or x-=10;
y = y + 1;
}
if (x >= 5 && x < 10)
{
x = x - 5; //or x-=5;
y = y + 1;
}
if (x >= 1 && x < 5)
{
x = x - 1; //or x-=1; or x--; or --x; :)
y = y + 1;
}
}
printf("The number of coins neccessary is %d", y);
}

I would remain to be convinced about your loop structure. There's the division operator that can be used to good effect:
int total = 0;
int ncoins;
int amount = GetFloat() * 100;
assert(amount >= 0);
ncoins = amount / 25;
total += ncoins;
amount -= ncoins * 25;
assert(amount < 25);
ncoins = amount / 10;
total += ncoins;
amount -= ncoins * 10;
assert(amount < 10);
ncoins = amount / 5;
total += ncoins;
amount -= ncoins * 5;
assert(amount < 5);
total += amount;
That's written out longhand; you could devise a loop, too:
int values[] = { 25, 10, 5, 1 };
enum { N_VALUES = sizeof(values) / sizeof(values[0]) };
int total = 0;
int ncoins;
int amount = GetFloat() * 100;
assert(amount >= 0);
for (int i = 0; i < N_VALUES && amount > 0; i++)
{
ncoins = amount / values[i];
total += ncoins;
amount -= ncoins * values[i];
}
assert(amount == 0);

Related

couldn't find out how to solve this algorithm problem

I am beginner I tried so many times but I couldn't solve this problem I will be very pleased if you help me...
the question is:
Let x be an integer, and R(x) is a function that returns the reverse of the x in terms of its digits.
For example , if x:1234 then R(x)=4321.
Let’s call a positive integer mirror-friendly if it satisfies the following condition: π‘₯ + 𝑅(π‘₯) = 𝑦^2 π‘€β„Žπ‘’π‘Ÿπ‘’ 𝑦 𝑖𝑠 π‘Žπ‘› π‘–π‘›π‘‘π‘’π‘”π‘’π‘Ÿ
Write a program that reads a positive integer as n from the user and prints out a line for each of the first n mirror-friendly integers as follows: x + R(x) = y^2
Example: If the user enters 5 as n, then the program should print out the following:
2 + 2 = 2^2
8 + 8 = 4^2
29 + 92 = 11^2
38 + 83 = 11^2
47 + 74 = 11^2
Here is the my code:
int
reverse(int num)
{
int reverse,
f,
i;
reverse = 0;
i = 0;
for (; i < num + i; i++) {
f = num % 10;
reverse = (reverse * 10) + f;
num /= 10;
}
return reverse;
}
int
sqrt(int n)
{
int i = 1;
int sqrt;
for (; i <= n; i++) {
sqrt = i * i;
}
return sqrt;
}
int
main()
{
int j = 1;
int main_num = 0;
for (; main_num <= 0;) {
printf("Please enter a positive integer: \n");
scanf_s("%d", &main_num);
}
int count = 0;
for (int i = 1; i <= main_num; i++) {
for (; j <= main_num; j++) {
if (j + reverse(j) == sqrt(?)) {
printf("%d + %d = %d\n", j, reverse(j), sqrt(?));
}
}
}
}
A few issues ...
sqrt does not compute the square root
reverse seems overly complicated
main_num (i.e. n from the problem statement) is the desired maximum count of matches and not the limit on x
Too many repeated calls to sqrt and reverse
No argument given to sqrt
The if in main to detect a match is incorrect.
sqrt conflicts with a standard function.
The variables you're using don't match the names used in the problem statement.
The printf didn't follow the expected output format.
Using a function scoped variable that is the same as the function is a bit confusing (to humans and the compiler).
Unfortunately, I've had to heavily refactor the code. I've changed all the variable names to match the names used in the problem statement for clarity:
#include <stdio.h>
#include <stdlib.h>
#ifdef DEBUG
#define dbgprt(_fmt...) printf(_fmt)
#else
#define dbgprt(_fmt...) do { } while (0)
#endif
int
reverse(int x)
{
int r = 0;
for (; x != 0; x /= 10) {
int f = x % 10;
r = (r * 10) + f;
}
return r;
}
int
isqrt(int x)
{
int y = 1;
while (1) {
int y2 = y * y;
if (y2 >= x)
break;
++y;
}
return y;
}
int
main(int argc,char **argv)
{
int n = -1;
--argc;
++argv;
if (argc > 0) {
n = atoi(*argv);
printf("Positive integer is %d\n",n);
}
while (n <= 0) {
printf("Please enter a positive integer:\n");
scanf("%d", &n);
}
int x = 1234;
dbgprt("x=%d r=%d\n",x,reverse(x));
int count = 0;
for (x = 1; count < n; ++x) {
dbgprt("\nx=%d count=%d\n",x,count);
// get reverse of number (i.e. R(x))
int r = reverse(x);
dbgprt("r=%d\n",r);
// get x + R(x)
int xr = x + r;
dbgprt("xr=%d\n",xr);
// get y
int y = isqrt(xr);
dbgprt("y=%d\n",y);
if (xr == (y * y)) {
printf("%d + %d = %d^2\n", x, r, y);
++count;
}
}
return 0;
}
Here is the program output:
Positive integer is 5
2 + 2 = 2^2
8 + 8 = 4^2
29 + 92 = 11^2
38 + 83 = 11^2
47 + 74 = 11^2
UPDATE:
The above isqrt uses a linear search. So, it's a bit slow.
Here is a version that uses a binary search:
// isqrt -- get sqrt (binary search)
int
isqrt(int x)
{
int ylo = 1;
int yhi = x;
int ymid = 0;
// binary search
while (ylo <= yhi) {
ymid = (ylo + yhi) / 2;
int y2 = ymid * ymid;
// exact match (i.e. x == y^2)
if (y2 == x)
break;
if (y2 > x)
yhi = ymid - 1;
else
ylo = ymid + 1;
}
return ymid;
}
UPDATE #2:
The above code doesn't scale too well for very large x values (i.e. large n values).
So, main should check for wraparound to a negative number for x.
And, a possibly safer equation for isqrt is:
ymid = ylo + ((yhi - ylo) / 2);
Here is an updated version:
#include <stdio.h>
#include <stdlib.h>
#ifdef DEBUG
#define dbgprt(_fmt...) printf(_fmt)
#else
#define dbgprt(_fmt...) do { } while (0)
#endif
// reverse -- reverse a number (e.g. 1234 --> 4321)
int
reverse(int x)
{
int r = 0;
for (; x != 0; x /= 10) {
int f = x % 10;
r = (r * 10) + f;
}
return r;
}
// isqrt -- get sqrt (linear search)
int
isqrt(int x)
{
int y = 1;
while (1) {
int y2 = y * y;
if (y2 >= x)
break;
++y;
}
return y;
}
// isqrt2 -- get sqrt (binary search)
int
isqrt2(int x)
{
int ylo = 1;
int yhi = x;
int ymid = 0;
// binary search
while (ylo <= yhi) {
#if 0
ymid = (ylo + yhi) / 2;
#else
ymid = ylo + ((yhi - ylo) / 2);
#endif
int y2 = ymid * ymid;
// exact match (i.e. x == y^2)
if (y2 == x)
break;
if (y2 > x)
yhi = ymid - 1;
else
ylo = ymid + 1;
}
return ymid;
}
int
main(int argc,char **argv)
{
int n = -1;
--argc;
++argv;
setlinebuf(stdout);
// take number from command line
if (argc > 0) {
n = atoi(*argv);
printf("Positive integer is %d\n",n);
}
// prompt user for expected/maximum count
while (n <= 0) {
printf("Please enter a positive integer:\n");
scanf("%d", &n);
}
int x = 1234;
dbgprt("x=%d r=%d\n",x,reverse(x));
int count = 0;
for (x = 1; (x > 0) && (count < n); ++x) {
dbgprt("\nx=%d count=%d\n",x,count);
// get reverse of number (i.e. R(x))
int r = reverse(x);
dbgprt("r=%d\n",r);
// get x + R(x)
int xr = x + r;
dbgprt("xr=%d\n",xr);
// get y
#ifdef ISQRTSLOW
int y = isqrt(xr);
#else
int y = isqrt2(xr);
#endif
dbgprt("y=%d\n",y);
if (xr == (y * y)) {
printf("%d + %d = %d^2\n", x, r, y);
++count;
}
}
return 0;
}
In the above code, I've used cpp conditionals to denote old vs. new code:
#if 0
// old code
#else
// new code
#endif
#if 1
// new code
#endif
Note: this can be cleaned up by running the file through unifdef -k
for(;i<num+i;i++)
is equal to
for(; 0<num;i++)
or for(; num;i++) if we are working with positive values only.
or even to while(num)
So, we don't need variable i in reverse function.
We don't need cycle at all in sqrt function. Just return n * n; is ok. But it is not sqrt then
The last cycle is too strange. At least variable j is not initialized.

Game of Life problem with board update function in C

I need help with my Game of Life implementation in C. Other posts on Stackoverflow lead me to believe that my problem was to do with dangling pointers, but after modifying my program to use a global 2D array for the game grid instead of passing it to functions which return new 2D arrays, I realized that it was a problem with my update function.
I have tried hard-coding a number of simple patterns, including gliders and oscillators, and the grid doesn't update correctly. The patterns do update the same way every time the program is run, so I don't think it's a problem of uninitialized memory causing problems. I also know that there are no cells which contain values greater than 1. Therefore, the problem must lie in my mechanisms for updating the grid.
Can someone help me find the problem? I can't find anything wrong with my code and I believe I have programmed the rules correctly.
Here are my neighbors and update functions, along with the relevant variable and constant declarations.
#define MAX_Y 10 /* height */
#define MAX_X 30 /* width */
int grid[MAX_Y][MAX_X];
int neighbors(int x, int y) {
int dx, dy, dstx, dsty;
int n = 0;
for (dy = -1; dy <= 1; ++dy) {
for (dx = -1; dx <= 1; ++dx) {
dsty = y + dy;
dstx = x + dx;
if (dsty >= 0 && dsty < MAX_Y && dstx >= 0 && dstx < MAX_X)
n += !!grid[dsty][dstx]; /* use !! so that non-zero values eval to 1 */
}
}
/* (n > 0) ? printf("Point (%d,%d) has %d neighbors!\n", x, y, n) : 0; */
return n;
}
void update(void) {
int new[MAX_Y][MAX_X];
memset(new, 0, sizeof(int) * MAX_Y * MAX_X);
int i, j, n;
for (i = 0; i < MAX_Y; ++i) {
for (j = 0; j < MAX_X; ++j) {
n = neighbors(i, j);
/* alive, 2 or 3 neighbors -> alive!
* dead, 3 neighbors -> alive!
* anything else -> dead :(
*/
if (grid[i][j] && (n == 2 || n == 3))
new[i][j] = 1;
else if (!grid[i][j] && n == 3)
new[i][j] = 1;
else
new[i][j] = 0;
}
}
memcpy(grid, new, sizeof grid);
}
In your neighbors function, you need to think carefully about the loop iteration where dx and dy are both zero. Conway's Game of Life does not consider a cell to be neighbor of itself, so you need to avoid counting it.
You're also confusing yourself by using the letters i and j. You're allowing j to go all the way up to MAX_X, but then you are using j as the y coordinate when you call neighbors, so that will cause overflows and incorrect calculations. (Starting with the easier case of a 10x10 grid would sometimes save you from bugs like this.)
You should adjust the neighbors() function to omit the cell itself.
Here is a modified version:
#define MAX_Y 10 /* height */
#define MAX_X 30 /* width */
unsigned char grid[MAX_Y][MAX_X];
int neighbors(int x, int y) {
int n = -!!grid[y][x];
for (int dy = -1; dy <= 1; ++dy) {
for (int dx = -1; dx <= 1; ++dx) {
int dsty = y + dy;
int dstx = x + dx;
if (dsty >= 0 && dsty < MAX_Y && dstx >= 0 && dstx < MAX_X && grid[dsty][dstx])
n++;
}
}
return n;
}
void update(void) {
int new[MAX_Y][MAX_X] = { 0 };
for (int y = 0; y < MAX_Y; ++y) {
for (int x = 0; x < MAX_X; ++x) {
int n = neighbors(y, x);
/* alive, 2 or 3 neighbors -> alive!
* dead, 3 neighbors -> alive!
* anything else -> dead :(
*/
new[y][x] = (grid[y][x] && n == 2) || n == 3;
}
}
memcpy(grid, new, sizeof grid);
}
The neighbors() function can be simplified with fewer tests:
int neighbors(int x, int y) {
int n = -(grid[y][x] != 0);
int x1 = x - (x > 0);
int x2 = x + (x < MAX_X - 1);
int y1 = y - (y > 0);
int y2 = y + (y < MAX_Y - 1);
for (y = y1; y <= y2; y++) {
for (x = x1; x <= x2; x++) {
n += grid[y][x] != 0;
}
}
return n;
}

Calculation of 4 digit numbers

What I am trying to do in the code below is to to make the input a four-digit number (if it's not already) and then sort the digits in the number in an ascending and descending order. x is ascending, y is descending. Then I want to subtract x and y until I get the result 6174 of the subtraction.
#include <stdio.h>
int main() {
int number, count = 0, digit, pow = 0, result = 1, counter, temp,
x = 0, y = 0, i, j, substract = 0, count1 = 0;
scanf("%d", &number);
while (substract != 6174 && substract >= 0) {
substract = 0;
if (count1 > 0) {
temp = substract;
} else {
temp = number;
}
while (temp > 0) {
digit = temp % 10;
temp = temp / 10;
count++;
}
if (count < 4) {
pow = 4 - count;
/* Calculate base^exponent */
for (counter = 0; counter < pow; counter++) {
result = result * 10;
}
number = number * result;
}
for (i = 9, j = 0; i >= 0 && j <= 9; i--, j++) {
int tmpNumber = number;
while (tmpNumber > 0) {
int digit = tmpNumber % 10;
if (digit == i) {
x *= 10;
x += digit;
} else
if (digit == j) {
y *= 10;
y += digit;
}
tmpNumber /= 10;
}
}
substract = x - y;
count++;
printf("\n x %d", x);
printf("\n y %d", y);
printf("\n substract %d", x - y);
}
return 0;
}
When I input 3542 What I expect as an output is this
input:
3524
output:
x 5432
y 2345
subtract 3087
x 8730
y 0378
subtract 8352
x 8532
y 2358
subtract 6174
But what I get is actually this:
input:
3524
output:
x 5432
y 2345
subtract 3087
x 54325432
y 23452345
subtract 30873087
I think the problem is something with the x and y. I have to reset them to zero at some point. But I don't know where. I've tried every single place in the code. If anyone knows where I do wrong I will really appreciate the help.
The program fails for multiple reasons:
You do not reset x and y to 0 for each iteration
result should also be reset to 1
The initial phase of the loop is too complicated: you should test if substract is 0 or 6174 to stop the loop and store substract to number at the end of the loop.
Here is a simpler version that does not need to make number have 4 digits:
#include <stdio.h>
int main(void) {
int number;
if (scanf("%d", &number) == 1 && number >= 0 && number < 10000) {
for (;;) {
int x = 0, y = 0, substract;
for (int i = 9, j = 0; i >= 0 && j <= 9; i--, j++) {
for (int tmp = number, n = 0; n < 4; n++) {
int digit = tmp % 10;
if (digit == i) {
x *= 10;
x += digit;
} else
if (digit == j) {
y *= 10;
y += digit;
}
tmp /= 10;
}
}
substract = x - y;
printf("x %d\n", x);
printf("y %d\n", y);
printf("substract %d\n", substract);
if (substract == 0 || substract == 6174)
break;
number = substract;
}
}
return 0;
}

Numbers acting strange in both Lua and C

I have written this program in Lua and C which is a greedy algorithm.
Greedy = function(num)
local q = 0;
local d = 0;
local n = 0;
local p = 0;
local x = 1;
while x == 1 do
if (num >= 0.25) then
q = q + 1;
num = num - 0.25;
print("q");
elseif (num >= 0.10) then
d = d + 1;
num = num - 0.10;
print("d");
elseif (num >= 0.05) then
n = n + 1;
num = num - 0.05;
print("n");
elseif (num >= 0.01) then
p = p + 1;
num = num - 0.01;
print("p");
end
if (num == 0) then
x = 0;
end
end
if (x == 0) then
local all = q+d+n+p;
print(all);
end
end
Greedy(1);
This code works fine with some numbers but if I try to calculate numbers like 0.90,0.04 or 0.12 it wont work and I have the same code written in C too. But I have the same problem with it.
#include <stdio.h>
int greedy(void){
int quarter = 0;
int dime = 0;
int nickel = 0;
int penny = 0;
float num = 0.40;
int x = 1;
while(x == 1){
if (num >= 0.25){
quarter = quarter + 1;
num = num - 0.25;
printf("q\n");
}else if(num >= 0.10){
dime = dime + 1;
num = num - 0.10;
printf("d\n");
}else if(num >= 0.05){
nickel = nickel + 1;
num = num - 0.05;
printf("n\n");
}else if(num >= 0.01){
penny = penny + 1;
num = num - 0.01;
printf("p\n");
};
if(num == 0){
x = 0;
};
};
if(x == 0){
int all = quarter + dime + nickel + penny;
printf("%i\n", all);
};
return 0;
};
int main(void){
greedy();
}
What did I do wrong?
The problem is that, many floating-point numbers can't be represented (using double or float) precisely, try this in Lua:
> print(0.9 == 0.9 - 0.2 + 0.1 + 0.1)
false
It should be equal in maths, but not here. The same for the C code.
Seeing your scope is counting your money, rewrite your code this way:
Greedy = function(num)
local q = 0;
local d = 0;
local n = 0;
local p = 0;
local x = 1;
num=num*100
while x == 1 do
if (num >= 25) then
q = q + 1;
num = num - 25;
print("q");
elseif (num >= 10) then
d = d + 1;
num = num - 10;
print("d");
elseif (num >= 5) then
n = n + 1;
num = num - 5;
print("n");
elseif (num >= 1) then
p = p + 1;
num = num - 1;
print("p");
end
if (num == 0) then
x = 0;
end
end
if (x == 0) then
local all = q+d+n+p;
print(all);
end
end
Greedy(1);

My program stops looping and i cannot figure out why

if the user inputs the "value" as 1223445 the output should read as follows:
After change #1: 12235
After change #2: 135
the code is meant to take out two consecutive numbers with the same value. the first loop works but then it stops and I cannot figure why. here is the code:
{
int count;
int y;
int z;
int b;
int c;
int d;
int a;
int ct;
y = 0;
z = 1;
d = 0;
count = 0;
if (value > 0)
while ((z * 10 + z) != (y % 100))
{
y = value % 10 + y * 10;
z = y % 10;
value /= 10;
count = count + 1;
}
value = value * pow(10, count - 2);
y = y / 100;
count = count - 3;
while(y > 0)
{
b = y % 10;
c = pow(10, count);
d = d + c * b;
y = y / 10;
count = count - 1;
}
value = value + d;
ct = 1;
printf("After change #%d: %d\n", ct, value);
a = value;
while (a > 1)
{
if((a % 100) - (a % 10) - (10 * (a % 10)) == 0)
Change(value);
else
a = a / 10;
}
return;
}
Here's a simple solution: (not sure how you want to handle odd numbered repeats e.g. '111', '11111')
public static long strip(long value, long sum) {
if(value==0) return sum;
long tens = value % 100;
long ones = value % 10;
if(ones*10 == tens-ones) {
return strip(value /100, sum);
}
if(sum==0) sum +=(value%10);
else {
long x = (long)Math.ceil((Math.log10(sum)));
sum =(long) (Math.pow(10,x) * ones + sum);
}
return strip(value /10, sum);
}

Resources