This is my code for Project Euler #19. The answer for the problem is 171 but my code is producing 172. Please can anyone figure out the problem in the code below.
#include <bits/stdc++.h>
using namespace std ;
typedef long long LL ;
int ordYear[12] = {31,28,31,30,31,30,31,31,30,31,30,31} ;
int leapYear[12] = {31,29,31,30,31,30,31,31,30,31,30,31} ;
int main(){
int leapFlag = 0 ;
LL ans = 0 ;
int dayonfirst = 2 ; // since it was tuesday on 1 Jan 1901
for (int i=1901 ; i<=2000 ; i++){
if ( (i%4==0 && i%100!=0) || (i%100==0 && i%400==0) )
leapFlag = 1 ;
for (int i=0 ; i<12 ; i++){
int oddDays ;
if (leapFlag == 1)
oddDays = leapYear[i]%7 ;
else
oddDays = ordYear[i]%7 ;
dayonfirst += oddDays ;
if(dayonfirst == 7)
ans++ ;
else if (dayonfirst > 7)
dayonfirst = dayonfirst%7 ;
}
}
cout << ans << endl ;
return 0 ;
}
You need else statement to assign leapFlag = 0 when it not a leap year:
if ( (i%4==0 && i%100!=0) || (i%100==0 && i%400==0) )
leapFlag = 1;
else
leapFlag = 0;
Related
when the first date is bigger than the second, it doesent calculate.
for example: first date 22/10/2022
second date: 15/10/2022
#include <iostream>
#include <cstdlib>
using namespace std;
class Date {
public:
Date(int d, int m, int y);
void set_date(int d, int m, int y);
void print_date();
void inc_one_day();
bool equals(Date d);
int get_day() { return day; }
int get_month() { return month; }
int get_year() { return year; }
private :
int day;
int month;
int year;
};
bool is_leap_year(int year)
{
int r = year % 33;
return r == 1 || r == 5 || r == 9 || r == 13 || r == 17 || r == 22 || r == 26 || r == 30;
}
int days_of_month(int m, int y){
if (m < 7)
return 31;
else if (m < 12)
return 30;
else if (m == 12)
return is_leap_year(y) ? 30 : 29;
else
abort();
}
void Date::inc_one_day(){
day++;
if (day > days_of_month(month, year)) {
day = 1;
month++;
if (month > 12) {
month = 1;
year++;
}
}
}
bool Date::equals(Date d) {
return day == d.day && month == d.month && year == d.year;
}
int days_between(Date d1, Date d2){
int count = 1;
while (!d1.equals(d2)){
d1.inc_one_day();
count++;
}
return count;
}
Date::Date(int d, int m, int y){
cout << "constructor called \n";
set_date(d, m, y);
}
void Date::set_date(int d, int m, int y){
if (y < 0 || m < 1 || m>12 || d < 1 || d > days_of_month(m, y))
abort();
day = d;
month = m;
year = y;
}
void Date::print_date(){
cout << day << '/' << month << '/' << year<<endl;
}
int main(){
Date bd(22, 12, 1395);
Date be(15, 12, 1395);
cout << '\n';
int i;
i= days_between(bd, be);
cout << i << endl;
}
here's my code.
I've seen many codes that calculate the days between two dates, but they didn't use class Date.
how can i solve this problem? could you guys help me please.I'm sorry i'm new in c++ so, my problem might be so basic.
It is clear why your algorithm does not work - you are incrementing the later date so it will never equal the earlier date. The solution is simply to compare the dates and swap the operands if necessary so that you are always incrementing the earlier date toward the later date.
int days_between(Date d1, Date d2)
{
int count = 0 ;
// Initially assume d2 >= d1
Date* earlier = &d1 ;
Date* later = &d2 ;
// Test if d1 > d2...
int year_diff = d2.get_year() - d1.get_year() ;
int mon_diff = d2.get_month() - d1.get_month() ;
int day_diff = d2.get_day() - d1.get_day() ;
if( year_diff < 0 ||
(year_diff == 0 && (mon_diff < 0 || (mon_diff == 0 &&
day_diff < 0 ))))
{
// d1 > d2, so swap
earlier = &d2 ;
later = &d1 ;
}
while (!earlier->equals(*later))
{
earlier->inc_one_day();
count++;
}
return count;
}
Note that it is not clear why you start with a count of 1. If the dates start equal, surely that should return a zero? That is how I have written it in any case.
If it is required to indicate whether the dates were reversed or not, you might want to return a signed value. In that case:
return earlier == &d2 ? -count : count ;
Which for the dates in your example will return -7.
Your solution is a good candidate for operator overloading so you could simply and more intuitively write:
if( d1 > d2 )
{
earlier = &d2 ;
later = &d1 ;
}
while( *earlier != *later))
{
earlier++ ;
count++ ;
}
return earlier == &d2 ? -count : count ;
and even ultimately:
i = be - bd;
What would be easier is to write a function that calculates the total number of days that have occurred since the year 0000. After that you can simply subtract them from each other and return the total number of days between them.
I am trying to check if the next move of the knight will threaten both kind and queen at the same time, if there's such position it will output YES and the position, otherwise it will be NO.
The input will contain only K for king, Q for queen, and N for knight, and they won't be repeated more than once.
Sample input :
........
........
........
...K....
....Q...
........
N.......
........
this input for example indicates that the knight is 2A , Queen is in 4E ,King is in 5D .
here's my code :
#include <cmath>
#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <ctype.h>
#include <fstream>
#include <cstddef>
#include <sstream>
#include<string.h>
#include<cstring>
#include<map>
#include<algorithm>
using namespace std;
int main ()
{
string temp ;
bool flag1 = false , flag2 = false ;
int row1 = 0 , col1 = 0 , row2 = 0 , col2 = 0 ;
int ik=0 , jk=0 , iq=0 , jq=0 , in=0 , jn=0 , i = 8 ;
while ( std::getline (std::cin,temp) )
{
for (int j = 0 ; j<=7 ; j++)
{
if(temp[j] == 'K')
{ ik = i ; jk = j+1 ; }
else if(temp[j] == 'Q')
{ iq = i ; jq = j+1 ; }
else if(temp[j] == 'N')
{ in = i ; jn = j+1 ; }
}
i-- ;
}
// j for columns , i for rows
// if jk = 1 means A , =2 means B , and so on
int threatk[8][2] = {0} , threatq[8][2]= {0} , expn[8][2] = {0} ;
// columns first ( position 0 )
// rows second ( position 1 )
threatk[0][0] = jk+1 ;
threatk[0][1] = ik+2 ;
threatk[1][0] = jk+1 ;
threatk[1][1] = ik-2 ;
threatk[2][0] = jk+2 ;
threatk[2][1] = ik+1 ;
threatk[3][0] = jk+2 ;
threatk[3][1] = ik-1 ;
threatk[4][0] = jk-1 ;
threatk[4][1] = ik+2 ;
threatk[5][0] = jk-1 ;
threatk[5][1] = ik-2 ;
threatk[6][0] = jk-2 ;
threatk[6][1] = ik+1 ;
threatk[7][0] = jk-2 ;
threatk[7][1] = ik-1 ;
threatq[0][0] = jq+1 ;
threatq[0][1] = iq+2 ;
threatq[1][0] = jq+1 ;
threatq[1][1] = iq-2 ;
threatq[2][0] = jq+2 ;
threatq[2][1] = iq+1 ;
threatq[3][0] = jq+2 ;
threatq[3][1] = iq-1 ;
threatq[4][0] = jq-1 ;
threatq[4][1] = iq+2 ;
threatq[5][0] = jq-1 ;
threatq[5][1] = iq-2 ;
threatq[6][0] = jq-2 ;
threatq[6][1] = iq+1 ;
threatq[7][0] = jq-2 ;
threatq[7][1] = iq-1 ;
expn[0][0] = jn+1 ;
expn[0][1] = in+2 ;
expn[1][0] = jn+1 ;
expn[1][1] = in-2 ;
expn[2][0] = jn+2 ;
expn[2][1] = in+1 ;
expn[3][0] = jn+2 ;
expn[3][1] = in-1 ;
expn[4][0] = jn-1 ;
expn[4][1] = in+2 ;
expn[5][0] = jn-1 ;
expn[5][1] = in-2 ;
expn[6][0] = jn-2 ;
expn[6][1] = in+1 ;
expn[7][0] = jn-2 ;
expn[7][1] = in-1 ;
for ( int a = 0 ; a<=7 ; a++)
{
for ( int b=0 ; b<=7 ; b++)
{
if ( ( expn[a][0] == threatk[b][0] && expn[a][1] == threatk[b][1] ) )
{ flag1 = true ; col1 = expn[a][0] ; row1 = expn[a][1] ; }
}
}
for ( int a = 0 ; a<=7 ; a++)
{
for ( int b=0 ; b<=7 ; b++)
{
if ( ( expn[a][0] == threatq[b][0] && expn[a][1] == threatq[b][1] ) )
{ flag2 = true ; col2 = expn[a][0] ; row2 = expn[a][1] ; }
}
}
if ( ( flag1 && flag2 ) && ( col1 >= 1 && col1 <= 8 && row1 >= 1 && row1 <= 8)
&& ( col2 >= 1 && col2 <= 8 && row2 >= 1 && row2 <= 8)
&& ( col1 = col2 && row1 = row2) )
{ string out = "" ;
if ( col1 == 1)out = "A" ;
else if ( col1 == 2) out = "B" ;
else if ( col1 == 3) out = "C" ;
else if ( col1 == 4) out = "D" ;
else if ( col1 == 5) out = "E" ;
else if ( col1 == 6) out = "F" ;
else if ( col1 == 7) out = "G" ;
else if ( col1 == 8) out = "H" ;
cout<<"YES"<<" "<<row1<<out ;
}
else cout<<"NO" ;} '
my approach is to get the threat positions for the king and the queen from a knight , and compare with it with the next possible move for the knight
it's working fine but it fails at some tests that am not aware of i just get to know if it passed all the tests or not .
what do you think is wrong ?
When you are designing code, make sure that all parts are easily testable. Design functions that do one clear thing and can be reused easily. Afterwards test them well so you can figure out what part of your code is wrong.
It is very hard to review your code and figure out what could potentially be wrong. I wrote a solution in Python that should pass all possible edge cases and I will share it here. Parsing input and output is not part of it.
N = 8
def generateThreat(y, x):
threats = []
candidate = (y+2, x+1)
if (candidate[0] < N-1 and candidate[1] < N-1):
threats.append(candidate)
candidate = (y+2, x-1)
if (candidate[0] < N-1 and candidate[1] >= 0):
threats.append(candidate)
candidate = (y-2, x+1)
if (candidate[0] >= 0 and candidate[1] < N-1):
threats.append(candidate)
candidate = (y-2, x-1)
if (candidate[0] >= 0 and candidate[1] >= 0):
threats.append(candidate)
candidate = (y+1, x+2)
if (candidate[0] < N-1 and candidate[1] < N-1):
threats.append(candidate)
candidate = (y+1, x-2)
if (candidate[0] < N-1 and candidate[1] >= 0):
threats.append(candidate)
candidate = (y-1, x+2)
if (candidate[0] >= 0 and candidate[1] < N-1):
threats.append(candidate)
candidate = (y-1, x-2)
if (candidate[0] >= 0 and candidate[1] >= 0):
threats.append(candidate)
return threats
def generateAllThreatsFromCurrent(y, x):
all_threats = set()
for next_step in generateThreat(y, x):
all_threats.update(generateThreat(next_step[0], next_step[1]))
return all_threats
def isMatePossible(king, queen, knight):
y, x = knight
all_threats = generateAllThreatsFromCurrent(y, x)
if king in all_threats and queen in all_threads:
return True
return False
I had a problem from a website. Given a string s and st, I have to found all possible combination of st in s. For example,
s = "doomdogged"
st = "dg"
answer = 4
I can choose the d from 0 or 4, and g from 6 or 7. Which gives me 4 possible combinations.
Here's my code:
#include <iostream>
#include <vector>
using namespace std;
string s, st;
bool target[26];
vector<int> positions[26];
vector<vector<int>> possibleCombinations;
void DFS_Enumeration(int, vector<int>*);
int DFS_index_max = 0;
int main(int argc, char *argv[])
{
int answer = 0;
cin >> s; //Given a string s
cin >> st; //Given a string st
//Find all possible combination of st in s
for ( int i = 0 ; i < 26 ; ++ i )
target[i] = 0;
for ( int i = 0 ; i < st.length() ; ++ i )
target[st[i] - 97] = 1;
for ( int i = 0 ; i < 26 ; ++ i )
{
if ( target[i] == 0 ) continue;
for ( int j = 0 ; j < s.length() ; ++ j )
{
if ( s[j] == i + 97 ) positions[i].push_back(j);
}
}
DFS_index_max = st.length();
vector<int> trail(0);
DFS_Enumeration(0, &trail); //Here I got an runtime error
for ( vector<int> vi : possibleCombinations )
{
int currentMax = 0;
for ( int i = 0 ; i < vi.size() ; ++ i )
{
if ( vi[i] > currentMax )
{
if ( i == vi.size() - 1 ) ++ answer;
currentMax = vi[i];
continue;
}
else
break;
}
}
cout << answer;
}
void DFS_Enumeration(int index, vector<int>* trail)
{
if ( index == DFS_index_max )
{
possibleCombinations.push_back(*trail);
return;
}
for ( int i = 0 ; i < positions[st[index] - 97].size() ; ++ i )
{
trail -> push_back(positions[st[index] - 97][i]);
DFS_Enumeration(++index, trail);
trail -> pop_back();
}
return;
}
First I look for characters in st, and mark them as needed to found in my boolean array target.
Then, I use DFS to enumerate all possible combinations. For the above example of "doomdogged" and "dg", d exists in 0, 4, 9. And g exist in 6, 7. I will get 06, 07, 46, 47, 96, 97.
Lastly, I count those which make sense, and output the answer. For some reason, my code doesn't work and generate an runtime error concerning memory at the line I've marked.
DFS_Enumeration might increment index any number of times, so st[index] could likely be past the end of the string st.
Program: So I made a program that take two numbers, N and L. N is the size of a 2D array and L is a number from 3 - 16. The program builds the array and starts at the center and works its way out in a counter clockwise spiral. I is the value of the center and its as you go through the array( in the spiral ) the value will increase by one. It it is prime, that number will be assigned to that spot and if not it * will take its place instead.
Error: I'm getting a "Floating point exception " error, how would I solve this?
Code:
void Array_Loop( int *Array, int n, int L ) ;
int Is_Prime( int Number ) ;
int main( int argc, char *argv[] ){
int **Array ;
int n, L ;
n = atoi( argv[1] ) ;
L = atoi( argv[2] ) ;
Matrix_Build( &Array, n, n ) ;
Array_Loop( Array, n, L ) ;
return 0 ;
}
void Array_Loop( int *Array, int n, int L ){
int i, j, k, h ;
int lctn, move;
lctn = n / 2 + 1 ;
i = lctn ;
j = lctn ;
move = 1
while( i != 0 && j != n ){
for( j = lctn ; j < lctn + move ; j++ ){
if( L % 2 == 2) Array[i][j] = -1 ;
else Array[i][j] = Is_Prime( L ) ;
L++ ;
}
move = move * -1 ;
for( i = i ; i > lctn - move ; i-- ){
if( L % 2 == 2) Array[i][j] = -1 ;
else Array[i][j] = Is_Prime( L ) ;
L++ ;
}
move-- ;
for( j = j ; j > lctn - move ; j-- ){
if( L % 2 == 2) Array[i][j] = -1 ;
else Array[i][j] = Is_Prime( L ) ;
L++ ;
}
move = move * -1 ;
for( i = i ; i < lctn - move ; i-- ){
if( L % 2 == 2) Array[i][j] = -1 ;
else Array[i][j] = Is_Prime( L ) ;
L++ ;
}
move++ ;
}
}
int Is_Prime( int Number ){
int i ;
for( i = 0 ; i < Number / 2 ; i++ ){
if( Number % i != 0 ) return -1 ;
}
return Number ;
}
You are getting Floating point exception because Number % i, when i is 0:
int Is_Prime( int Number ){
int i ;
for( i = 0 ; i < Number / 2 ; i++ ){
if( Number % i != 0 ) return -1 ;
}
return Number ;
}
Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.
Floating Point Exception happens because of an unexpected infinity or NaN.
You can track that using gdb, which allows you to see what is going on inside your C program while it runs. For more details:
https://www.cs.swarthmore.edu/~newhall/unixhelp/howto_gdb.php
In a nutshell, these commands might be useful...
gcc -g myprog.c
gdb a.out
gdb core a.out
ddd a.out
I wrote a program to calculate (adding) 2 positive big integer using vector to store the numbers.
#include <cstdlib>
#include <cstdio> // sd sprintf()
#include <iostream>
#include <vector>// sd vector
typedef short TYPE;// alias
void input();
void makeArray();
void display(const std::vector<TYPE> Ar);
TYPE convertChar2T( char * ch);
void add();
static std::string num1;//store big integer as string
static std::string num2;
static std::vector<TYPE> Arr1;//store as vector
static std::vector<TYPE> Arr2;
static std::vector<TYPE> result;
int main(int argc, char** argv) {
input();
makeArray();
display(Arr1);
display(Arr2);
add();
display(result);
return 0;
}
//input 2 big integer number
void input(){
std::cout << "Enter 1st number : " ;
if (! std::getline(std::cin , num1) )
std::cerr << "Not OK\n";
std::cout << "Enter 2nd number : ";
if (! std::getline(std::cin , num2) )
std::cerr << "Not OK\n";
}
//grab into 2 arrays
void makeArray(){
for (std::size_t i = 0; i < num1.size(); i++){
char temp1[2] = { num1[i], '\0'}; //use array-of-char as it need '\0'
Arr1.push_back( convertChar2T(temp1) ); //push what is converted
}
for (std::size_t i = 0; i < num2.size(); i++){
char temp2[2] = { num2[i], '\0'};
Arr2.push_back( convertChar2T(temp2) );
}
}
//convert char -> TYPE by using sscanf()
TYPE convertChar2T( char * ch){
TYPE numb ;
sscanf( ch, "%d", &numb );//NGUOC LAI SPRINTF
return numb;
}
//display array
void display(const std::vector<TYPE> Ar){
for (std::size_t i = 0; i < Ar.size(); i++)
std::cout << Ar.at(i) << '\t';
std::cout << '\n';
}
void add(){
std::size_t i = Arr1.size(); // NEVER COMES TO ZERO ( 1 AT LEAST )
std::size_t j = Arr2.size();
//check original one and later one
//3 cases : 1 - original one , not yet processed
// 2 - original # one, not yet processed
// -1 - original # one or one, processed
//NOTE: at first only value 1 or 2 ( not process )
short check_one[2] = {
( i == 1 ) ? 1 : 2,
( j == 1 ) ? 1 : 2,
};
bool boost = 0;
bool Arr1_isgood = true;// whether count to 1 or not
bool Arr2_isgood = true;// good -> not yet 1
short temp_result = 0;//temporary result to push into vector
while ( Arr1_isgood || Arr2_isgood ){// while not all comes to 1
// i == j : 2 cases
// 1st: both 1 now - 3 cases
// 1.1 #1+not process original and processed
// 1.2 processed and #1+not processed
// 1.3 both 1 original + not processed
// 2nd: both # 1
if ( i == j ) {
if ( check_one[0] == 2 && check_one[1] == -1 ){//#1+not process original and processed
temp_result = Arr1[i-1] + boost;
check_one[0] == -1;
}
else if ( check_one[0] == -1 && check_one[1] == 2 ){//processed and #1+not processed
temp_result = Arr2[j-1] + boost;
check_one[1] = -1;
}
else//both 1 original + not processed OR both # 1
temp_result = Arr1[i-1] + Arr2[j-1] + boost;
//check result >= 10 or < 10
if ( temp_result >= 10 ){
temp_result = temp_result - 10 ;
boost = 1;
}
else
boost = 0;
//result.begin() return iterator at beginning
result.insert( result.begin() ,temp_result );
//update info
if ( i == j && i == 1){ // NOTE : NEU SD i==j==1 -> sai (vi luon true)
Arr1_isgood = Arr2_isgood = false;
continue;
}
else if ( i == j && i != 1){ // i == j # 1
i--;
j--;
}
}
if (i != j){
//check to set flag ( if one of two die )
if ( i == 1 && j > 1 )
Arr1_isgood = false;
else if ( i > 1 && j == 1 )
Arr2_isgood = false;
// i die && j live OR vice versa
if ( (!Arr1_isgood && Arr2_isgood) ||
(Arr1_isgood && !Arr2_isgood ) ){
if (!Arr1_isgood && Arr2_isgood ){ //1st case
if ( check_one[0] == 1 || check_one[0] == 2){//not yet processed as SET FLAG ABOVE first
temp_result = Arr1[i-1] + Arr2[j-1] + boost;
check_one[0] = -1 ;
}
else
temp_result = Arr2[j-1] + boost;
j--;
}
else if ( Arr1_isgood && !Arr2_isgood ){ //2nd case
if ( check_one[1] == 1 || check_one[1] == 2 ){//not yet processed as SET FLAG ABOVE first
temp_result = Arr1[i-1] + Arr2[j-1] + boost;
check_one[1] = -1 ;
}
else
temp_result = Arr1[i-1] + boost;
i--;
}
}
else {// both is good
temp_result = Arr1[i-1] + Arr2[j-1] + boost;
i--;
j--;
}
//check result >= 10 or < 10
if (temp_result >= 10) {
temp_result -= 10;
boost = 1;
} else
boost = 0;
result.insert( result.begin() ,temp_result );
}
}
//insert boost (if any exists)
if (boost == 1)
result.insert( result.begin(), boost);
}
I'm torn between the use of "Arr1_isgood" bool variable and the check_one variable, it seems that they can be combined into one variable ? I tried to do it and it takes a lot of time without correct result.
Can the digit be store in some kind of smaller data structure rather than "short" type ? as "short" takes more than needed bits.
Another thing is : it seems that std::size_t only reach up to 4 billion in size, as when size_t reach 1, I decreased it several times and it comes to 4 billion ? Isn't it?
I wonder if these codes somehow can be optimized more?
If you want to manipulate big integers, you should use a big-integer library, e.g. GMP.
In your machine has 32-bit ints, suppose you represent each number (unsigned) as an array of 31-bit signed ints, starting from the least significant.
Then maybe you could do something like this:
// do c = a + b
int a[n], b[n], c[n];
int carry = 0;
for (i = 0; i < n; i++){
// do the addition with carry
c[i] = a[i] + b[i] + carry;
// if the addition carried into the sign bit
carry = (c[i] < 0);
// detect it and remove it from the sum
if (carry){
c[i] &= 0x7fffffff;
}
}
Then you could figure out how to handle negatives.