I have to write a program that will solve the hanoi towers.
I have 3 columns, A-B-C and all the discs will have to be on the B column as the result. I have to write out the steps that each disc performs and in what order.
I tried to write it on my own, it works to some extent.
Some problems are:
The numbers are not written out correctly, at the n-j it should
calculate the n-j but it's always 1, but it shouldn't be.
The steps that the program performs are good only to some extent,
for example the last 3 or 4 steps are always wrong.
What did I write incorrectly?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int n,i,j,k,first_pos,last_pos,num_ofsteps,num;
char first_peg,next_peg;
printf("Enter the number of disks: ");
scanf("%d",&n);
int a[n];
for (i=0;i<n;++i) {
a[i]=0;
}
num_ofsteps = pow(2,n);
first_pos = 0;
last_pos = n-1;
for (i=0;i<num_ofsteps-1;++i) {
if (i%2==0) {
if (a[n-1]==0) {
a[n-1] = 1;
printf("1 steps: A->B\n");
} else if (a[n-1]==1) {
a[n-1] = 2;
printf("1 steps: B->C\n");
} else if (a[n-1]==2) {
a[n-1] = 0;
printf("1 steps: C->A\n");
}
} else {
for (j=n-1;j>=0;--j) {
if (a[j]!=a[j-1]) {
if ((a[j]==0 && a[j-1]==1) || (a[j]==1 && a[j-1]==0)) {
next_peg = 'C';
} else if ((a[j]==1 && a[j-1]==2) || (a[j]==2 && a[j-1]==1)) {
next_peg = 'A';
} else if ((a[j]==0 && a[j-1]==2) || (a[j]==2 && a[j-1]==0)) {
next_peg = 'B';
}
num=n-j;
if (a[j-1]==0) {
first_peg = 'A';
a[j-1] = 1;
printf("%d steps: %c->%c\n",num,first_peg,next_peg);
break;
} else if (a[j-1]==1) {
first_peg = 'B';
a[j-1] = 2;
printf("%d steps: %c->%c\n",num,first_peg,next_peg);
break;
} else if (a[j-1]==2) {
first_peg = 'C';
a[j-1] = 0;
printf("%d steps: %c->%c\n",num,first_peg,next_peg);
break;
}
}
}
}
}
return 0;
}
Related
I am taking CS50, and I completed the first week problem of implementing the Luhn Check algorithm. Although my solution works, I feel it's very sloppy and not efficient. Can someone please suggest how I can improve my solution. (It's a first week problem; you are not intended to use arrays or functions.)
Here is the code:
#include<stdio.h>
#include<stdlib.h>
#include<cs50.h>
int main()
{
long long x,j=0;
int len,i,len_flag,flag=0,flag_val=0,sp_len=0,check_flag=0; //basic integers related to loop etc
int res,sum,fin_sum=0,h=0,d2_sum=0,d1_sum=0,ff_num=0; // variables related to extracting numbers
int sum_len=0,in_sum=0,in_fsum=0,len_sum=0,m=0; // extraing numbers from more than single sum result
int sum_f=0,sum_final=0;
do{
x = get_long("enter a valid card number \n");
j=x;
len_flag = 0;
len = 0;
while(len_flag!=1)
{
x = x / 10;
if(x==0)
{
len_flag = 1; //finding the lenght of the number
}
len++;
}
if(len==15||len==16||len==13)
{
flag = 1;
sp_len =1;
}
else
{
flag=1;
}
}while(flag!=1);
for(i=0;i<len;i++)
{
res = j % 10;
j = j / 10;
if(i%2!=0)
{
sum = res * 2;
//printf("multi_res : %d \n",sum);
len_flag = 0;
sum_len = 0;
len_sum = sum;
while(len_flag!=1)
{
len_sum = len_sum / 10;
if(len_sum==0)
{
len_flag=1; // checking if the sum is more than single digit
}
sum_len++;
//printf("trig\n");
}
if(sum_len>1)
{ x=0;
while(x<sum_len)
{
in_sum = sum % 10;
sum = sum/10;
in_fsum = in_fsum + in_sum;
//printf("double sum : %d \n",in_fsum);
x++;
}
}
fin_sum = fin_sum + sum;
}
if(i==len-1)
{
for(h=0;h < 1;h++)
{
fin_sum = fin_sum + in_fsum;
}
d1_sum = res;
}
else if(i%2==0)
{
sum_f = sum_f + res; // adding up the number that where not x2
}
if(i==len-2)
{
d2_sum = res; //5555555555554444
}
}
sum_final = sum_f + fin_sum;
//printf("sum_final : %d\n",sum_final);
//printf("sum_f_final : %d\n",sum_f);
//printf("sum_in_final : %d\n",fin_sum);
if(sum_final%10==0)
{
flag_val=1; // checking if the number is valid
}
if(ff_num == 0)
{
ff_num = (d1_sum*10) + d2_sum; //flip
}
do
{
if(sp_len==0)
{
printf("INVALID\n");
check_flag=1;
break;
}
if((flag==1&&flag_val==1&&ff_num==34)||ff_num==37)
{
printf("AMEX\n");
check_flag=1;
break;
}
else if(flag==1&&flag_val==1&&ff_num>50&&ff_num<56)
{
printf("MASTERCARD\n");
check_flag=1;
break;
}
else if(flag==1&&flag_val==1&&d1_sum==4)
{
printf("VISA\n");
check_flag=1;
break;
}
else
{
printf("INVALID\n");
check_flag=1;
break;
}
}while(check_flag!=1);
return 0;
}
I felt like I was fixing a leak while writing the code. I would try to correct one thing, and another thing would go wrong, and this is the final result.
This is my solution for the Credit problem on CS50's Pset1. It involves using Luhn's Algorithm to test the validity of the Credit Card Number entered and based on a few conditions attempts to identify the Credit Card Company.
Check_Length attempts to find the length of the number entered.
Check_Company attempts to ID the company.
Check_Luhn validates the number based on Luhn's Algorithm.
I'd like to know if this could be done with fewer lines of code.
#include <stdio.h>
#include <cs50.h>
#include <stdbool.h>
int check_length(long);
void check_company(int,long);
bool check_luhn(long,int);
int length;
int main(void)
{
long c = get_long("Enter Credit Card Number: ");
check_length(c);
check_luhn(c,length);
if(check_luhn(c,length)==true)
{
check_company(length,c);
}
else printf("INVALID\n");
}
int check_length(long w)
{
for(int i=12;i<16;i++)
{
long power = 1;
for (int k=1;k<i+1;k++)
{
power = power * 10;
}
int scale = w/power;
if (scale<10 && scale>0)
{
length = i+1;
}
}
return length;
}
void check_company(int x,long z)
{
if(x == 15)
{
int y = z/10000000000000; //z/10^13
if(y==34||y==37)
{
printf("AMEX\n");
}
else
{
printf("INVALID\n");
}
}
else if(x==13)
{
int y = z/100000000000; //z/10^11
if(y==4)
{
printf("VISA\n");
}
}
else if(x==16)
{
int q = z/1000000000000000;
int y = z/100000000000000;
if(y==51||y==52||y==53||y==54||y==55)
{
printf("MASTERCARD\n");
}
else
if(q==4)
{
printf("VISA\n");
}
else printf("INVALID\n");
}
else printf("INVALID\n");
}
bool check_luhn(long a,int b)
{
int f = 0;
int j=0;
for(int d=1;d<b+1;d++)
{
int e = a%10;
a = a/10;
if(d%2==1)
{
f = f+e;
}
else
{
int m = 2*e;
int g = m%10;
int h = m/10;
j = j+g+h;
}
}
int l = j + f;
if(l%10==0)
{
return true;
}
else return false;
}
When I run my code, the console doesn't output anything. When I go into "debug as c application mode" and step into the makeBoard() method that is supposed to print stuff nothing is shown on the console. I can't work on this project if the console doesn't work.
Whenever I run my code with only makeBoard() in the int main(void) method, the console outputs what it's supposed to. However, when I add the rest of my code in the int main(void) method, nothing is shown in the console window.
I am very new to C and the eclipse IDE. Do I need to download something?
The makeBoard() method:
void makeBoard(){
printf("Row A: ");
for(int i = 0; i< rowAcounter; i++)
{
printf("O");
}
printf("\n");
printf("Row B: ");
for(int i = 0; i< rowBcounter; i++)
{
printf("O");
}
printf("\n");
printf("Row C: ");
for(int i = 0; i< rowCcounter; i++)
{
printf("O");
}
printf("\n");
}
My complete int main method and the rest of my program:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void makeBoard();
void nextTurn(int player);
void prompt(int turn);
_Bool isGameOver();
void done(int currentTurn);
void test();
void update();
int rowAcounter = 3;
int rowBcounter = 5;
int rowCcounter = 8;
int currentPlayer = 0; // 0= player 1's turn, 1
= player 2's turn
char firstIn;
char secondIn;
_Bool flag = 0;
int main(void){
makeBoard();
while(isGameOver() == 0){
prompt(currentPlayer);
update();
nextTurn(currentPlayer);
if(flag == 1){
break;
}
makeBoard();
}
done(currentPlayer);
return 0;
}
the rest of my code:
void update(){
poll: scanf(" %c%c", &firstIn, &secondIn);
int checkFirst = firstIn - 'A';
if((checkFirst < 0) || (checkFirst > 2))
{
printf("\n Try again, you ape.");
goto poll;
}
int checkSecond = secondIn - '0';
if((checkSecond < 0 ) || (checkSecond > 8)){
printf("\n Try again, you fricker.");
goto poll;
}
else if(checkFirst == 0){ // the player chose row A
if(checkSecond > 3){
printf("\n Try again, you frick.");
goto poll;
}
else{
rowAcounter = rowAcounter - checkSecond;
}
}
else if(checkFirst == 1){ // the player chose row B
if(checkSecond > 5){
printf("\n Try again, you headass.");
goto poll;
}
else{
rowBcounter = rowBcounter - checkSecond;
}
}
else{ // the player chose row C
if(checkSecond > 8)
{
printf("\n Try again!");
goto poll;
}
else{
rowCcounter = rowCcounter - checkSecond;
}
}
if(isGameOver() == 1){
flag = 1;
}
}
void nextTurn(int player){
if(player == 0){
player = 1;
}else
{
player = 0;
}
}
void prompt(int turn){
if(turn == 0){
printf("Player 1, make your move:");
}
else{
printf("Player 2, make your move:");
}
}
_Bool isGameOver(){
if((rowAcounter == 0) && (rowBcounter == 0) && (rowCcounter == 0)){
return 1;
}
else{
return 0;
}
}
void done(int currentTurn){
if(currentTurn == 0){
puts("Player 1 wins!");
}
else{
puts("Player 2 wins!");
}
}
In the code below there is an error I can't locate causing the computer's selection to not be accounted for. The user's input is being considered in the Nim game yet the computer's pieces are not being subtracted.
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
void printInstructions();
int getUserInput(int);
int randomRange(int,int);
int PlayerTurn(int);
int smartCompMove(int);
int dumbCompMove(int);
int main()
{
srand(time(NULL));
int pieceAmount = randomRange(12,24);
char smartCompOrDumb;
printf("Do you want to play a smart computer or a dumb one? Select 'S' or 'D'.");
scanf("%c",&smartCompOrDumb);
bool gameOver = false;
bool playerTurn = true;
printInstructions();
while(pieceAmount > 0 && gameOver == false)
{
if (playerTurn == false)
{
if(pieceAmount <= 4)
{
printf("\nThe Computer has won :P ");
gameOver = true;
exit(0);
}
if (smartCompOrDumb == 's' || smartCompOrDumb == 'S')
{
playerTurn = true;
pieceAmount = smartCompMove(pieceAmount);
printf("%d",pieceAmount);
}
else if (smartCompOrDumb == 'd' || smartCompOrDumb == 'D')
{
playerTurn = true;
pieceAmount = dumbCompMove(pieceAmount);
printf("%d",pieceAmount);
}
}
else
{
if(pieceAmount <= 4)
{
printf("\nYou have won :) ");
gameOver = true;
exit(0);
}
playerTurn = false;
pieceAmount = PlayerTurn(pieceAmount);
printf("%d",pieceAmount);
}
}
return 0;
}
void printInstructions()
{
printf("\nThis game is called Nim and it is thousands of years old.");
printf("\nTake turns picking one to three pieces from a pile and whomever picks the last piece wins.");
printf("\n__________________________________________________________________________________________");
}
int randomRange(int low,int high)
{
return rand()% (high - low) + low;
}
int PlayerTurn(int pieceAmount)
{
pieceAmount = getUserInput(pieceAmount);
return pieceAmount;
}
int getUserInput(int pieceAmount)
{
int userInput = 0;
bool flag = true;
while (flag == true)
{
if (pieceAmount > 4)
{
printf("\nThere are %d pieces remaining.\n",pieceAmount);
printf("\nHow many pieces do you want to select? ");
scanf("%d", &userInput);
if (userInput >= 1 && userInput < 5)
{
pieceAmount = pieceAmount - userInput;
flag = false;
}
else
{
printf("This is not a valid move so try again.");
}
}
}
return pieceAmount;
}
int dumbCompMove(int pieceAmount)
{
int dumbPick = rand() % 3 + 1;
printf("\nComputer will pick from the stack. \n");
pieceAmount = pieceAmount - dumbPick;
printf("\nComputer picked %d pieces. \n", dumbPick );
return pieceAmount;
}
int smartCompMove(int pieceAmount)
{
int smartPick = 1;
printf("\nThe computer will select their pieces. \n");
if (pieceAmount >= 15 && pieceAmount < 24)
{
smartPick = 2;
pieceAmount = pieceAmount - smartPick;
}
else if (pieceAmount >= 10 && pieceAmount < 15)
{
smartPick = 4;
pieceAmount = pieceAmount - smartPick;
}
else if (pieceAmount >= 6 && pieceAmount < 10)
{
smartPick = 1;
pieceAmount = pieceAmount -smartPick;
}
else
pieceAmount = 3;
printf("\nThe computer selected %d pieces. \n",smartPick);
return pieceAmount;
}
I had this code working earlier yet somehow I must have altered something minor and now it will not function properly. I am using the Cloud9 program to run it.
People in a group are sitting in a group numbered 1 to N. It is known that people of same countries are sitting together.
Output is a single integer denoting no of distinct countries.
Input
4 (no of test cases)
2 (no of people in group)
1 1 ( in this there are 2 people from diff country)
2
1 3
7
1 1 2 2 3 3 3
7
7 7 7 7 7 7 7
Output should be
2
Invalid Data
4
1
My program:please tell me where is the error
#include<stdio.h>
#include<string.h>
int main()
{
int tcaseno,nopgrp,flag=0;
int arr[1000];
int count=0,i=0,j=0,t=0;
scanf("%d", &tcaseno);
t=tcaseno;
while(t>0)
{
scanf("%d\n", &nopgrp);
for (i = 0; i < nopgrp;i++)
{
scanf("%d", &arr[i]);
}
for (j = 0; j < nopgrp;j++)
{
if(arr[j]==1)
{
count++;
}
else if(arr[j]==2)
{
if(arr[j+1]==2)
{
count++;
}
else
{
flag=1;
}
}
else if(arr[j]==3)
{
if((arr[j+1]==3)&&(arr[j+2]==3))
{
count++;
}
else
{
flag=2;
}
}
else if(arr[j]==4)
{
if((arr[j+1]==4)&&(arr[j+2]==4)&&(arr[j+3]==4))
{
count++;
}
else
{
flag=3;
}
}
else if(arr[j]==5)
{
if((arr[j+1]==5)&&(arr[j+2]==5)&&(arr[j+3]==5)&&(arr[j+4]==5))
{
count++;
}
else
{
flag=4;
}
}
else if(arr[j]==6)
{
if((arr[j+1]==6)&&(arr[j+2]==6)&&(arr[j+3]==6)&&(arr[j+4]==6)&&(arr[j+5]==6))
{
count++;
}
else
{
flag=5;
}
}
else if(arr[j]==7)
{
if((arr[j+1]==7)&&(arr[j+2]==7)&&(arr[j+3]==7)&&(arr[j+4]==7)&&(arr[j+5]==7)&&(arr[j+6]==7))
{
count++;
}
else
{
flag=6;
}
}
else if(arr[j]==8)
{
if((arr[j+1]==8)&&(arr[j+2]==8)&&(arr[j+3]==8)&&(arr[j+4]==8)&&(arr[j+5]==8)&&(arr[j+6]==8)&&(arr[j+7]==8))
{
count++;
}
else
{
flag=7;
}
}
else if(arr[j]==9)
{
if((arr[j+1]==9)&&(arr[j+2]==9)&&(arr[j+3]==9)&&(arr[j+4]==9)&&(arr[j+5]==9)&&(arr[j+6]==9)&&(arr[j+7]==9)&&(arr[j+8]==9))
{
count++;
}
else
{
flag=8;
}
}
else if(arr[j]==0)
{
flag=9;
}
}
if(flag!=0)
{
printf("Invalid Data");
flag=0;
}
else
{
printf("%d\n",count);
count=0;
}
t--;
}
return 0;
}
if((arr[j+1]==9)&&(arr[j+2]==9)&&(arr[j+3]==9) ...)
You can simplify the above code with another for loop. Evidently you just want to see how many different numbers there are in the array.
Note that one of the main reasons to use C, or to learn C, is for efficiency. Therefore int arr[1000] is somewhat out of place because it allocates 4000 bytes. You may want to streamline that with malloc/free.
You should use printf to tell the user what to input.
I took some guesses on what you are trying achieve.
int tcaseno, nopgrp, error;
int count, i;
int *arr;
printf("no_test_cases: ");
scanf("%d", &tcaseno);
while(tcaseno > 0)
{
error = 0;
count = 1;
printf("no_people_in_group: ");
scanf("%d", &nopgrp);
if(nopgrp > 0 && nopgrp < 1000)
{
arr = malloc(nopgrp * sizeof(int));
printf("Enter %d numbers: ", nopgrp);
for(i = 0; i < nopgrp; i++)
scanf("%d", &arr[i]);
for(i = 1; i < nopgrp; i++)
{
if(arr[i - 1] > arr[i])
error = 1;
else if(arr[i - 1] != arr[i])
count++;
}
free(arr);
}
else
error = 1;
if(error)
printf("Invalid Data\n");
else
printf("Result: %d\n", count);
tcaseno--;
}