Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Keep all operations the same but rewrite the snippet in Java. | COBOL
identification division.
program-id. days-between.
procedure division.
compute tally =
function integer-of-formatted-date('YYYY-MM-DD', '2019-11-24')
-
function integer-of-formatted-date('YYYY-MM-DD', '2000-01-01')
display tally
compute tally =
function integer-of-formatted-date('YYYYMMDD', '20191124')
-
function integer-of-formatted-date('YYYYMMDD', '20000101')
display tally
goback.
end program days-between.
| import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates {
public static void main(String[] args) {
LocalDate fromDate = LocalDate.parse("2019-01-01");
LocalDate toDate = LocalDate.parse("2019-10-19");
long diff = ChronoUnit.DAYS.between(fromDate, toDate);
System.out.printf("Number of days between %s and %s: %d\n", fromDate, toDate, diff);
}
}
|
Keep all operations the same but rewrite the snippet in Java. | COBOL
identification division.
program-id. days-between.
procedure division.
compute tally =
function integer-of-formatted-date('YYYY-MM-DD', '2019-11-24')
-
function integer-of-formatted-date('YYYY-MM-DD', '2000-01-01')
display tally
compute tally =
function integer-of-formatted-date('YYYYMMDD', '20191124')
-
function integer-of-formatted-date('YYYYMMDD', '20000101')
display tally
goback.
end program days-between.
| import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates {
public static void main(String[] args) {
LocalDate fromDate = LocalDate.parse("2019-01-01");
LocalDate toDate = LocalDate.parse("2019-10-19");
long diff = ChronoUnit.DAYS.between(fromDate, toDate);
System.out.printf("Number of days between %s and %s: %d\n", fromDate, toDate, diff);
}
}
|
Write a version of this COBOL function in Python with identical behavior. | COBOL
identification division.
program-id. days-between.
procedure division.
compute tally =
function integer-of-formatted-date('YYYY-MM-DD', '2019-11-24')
-
function integer-of-formatted-date('YYYY-MM-DD', '2000-01-01')
display tally
compute tally =
function integer-of-formatted-date('YYYYMMDD', '20191124')
-
function integer-of-formatted-date('YYYYMMDD', '20000101')
display tally
goback.
end program days-between.
|
import sys
def days( y,m,d ):
m = (m + 9) % 12
y = y - m/10
result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
return result
def diff(one,two):
[y1,m1,d1] = one.split('-')
[y2,m2,d2] = two.split('-')
year2 = days( int(y2),int(m2),int(d2))
year1 = days( int(y1), int(m1), int(d1) )
return year2 - year1
if __name__ == "__main__":
one = sys.argv[1]
two = sys.argv[2]
print diff(one,two)
|
Change the following COBOL code into Python without altering its purpose. | COBOL
identification division.
program-id. days-between.
procedure division.
compute tally =
function integer-of-formatted-date('YYYY-MM-DD', '2019-11-24')
-
function integer-of-formatted-date('YYYY-MM-DD', '2000-01-01')
display tally
compute tally =
function integer-of-formatted-date('YYYYMMDD', '20191124')
-
function integer-of-formatted-date('YYYYMMDD', '20000101')
display tally
goback.
end program days-between.
|
import sys
def days( y,m,d ):
m = (m + 9) % 12
y = y - m/10
result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
return result
def diff(one,two):
[y1,m1,d1] = one.split('-')
[y2,m2,d2] = two.split('-')
year2 = days( int(y2),int(m2),int(d2))
year1 = days( int(y1), int(m1), int(d1) )
return year2 - year1
if __name__ == "__main__":
one = sys.argv[1]
two = sys.argv[2]
print diff(one,two)
|
Write the same code in VB as shown below in COBOL. | COBOL
identification division.
program-id. days-between.
procedure division.
compute tally =
function integer-of-formatted-date('YYYY-MM-DD', '2019-11-24')
-
function integer-of-formatted-date('YYYY-MM-DD', '2000-01-01')
display tally
compute tally =
function integer-of-formatted-date('YYYYMMDD', '20191124')
-
function integer-of-formatted-date('YYYYMMDD', '20000101')
display tally
goback.
end program days-between.
| Imports System.Globalization
Module Module1
Function DateDiff(d1 As String, d2 As String) As Integer
Dim a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Return (b - a).TotalDays
End Function
Sub Main()
Console.WriteLine(DateDiff("1970-01-01", "2019-10-18"))
End Sub
End Module
|
Translate this program into VB but keep the logic exactly as in COBOL. | COBOL
identification division.
program-id. days-between.
procedure division.
compute tally =
function integer-of-formatted-date('YYYY-MM-DD', '2019-11-24')
-
function integer-of-formatted-date('YYYY-MM-DD', '2000-01-01')
display tally
compute tally =
function integer-of-formatted-date('YYYYMMDD', '20191124')
-
function integer-of-formatted-date('YYYYMMDD', '20000101')
display tally
goback.
end program days-between.
| Imports System.Globalization
Module Module1
Function DateDiff(d1 As String, d2 As String) As Integer
Dim a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Return (b - a).TotalDays
End Function
Sub Main()
Console.WriteLine(DateDiff("1970-01-01", "2019-10-18"))
End Sub
End Module
|
Translate this program into Go but keep the logic exactly as in COBOL. | COBOL
identification division.
program-id. days-between.
procedure division.
compute tally =
function integer-of-formatted-date('YYYY-MM-DD', '2019-11-24')
-
function integer-of-formatted-date('YYYY-MM-DD', '2000-01-01')
display tally
compute tally =
function integer-of-formatted-date('YYYYMMDD', '20191124')
-
function integer-of-formatted-date('YYYYMMDD', '20000101')
display tally
goback.
end program days-between.
| package main
import (
"fmt"
"log"
"time"
)
const layout = "2006-01-02"
func daysBetween(date1, date2 string) int {
t1, err := time.Parse(layout, date1)
check(err)
t2, err := time.Parse(layout, date2)
check(err)
days := int(t1.Sub(t2).Hours() / 24)
if days < 0 {
days = -days
}
return days
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
date1, date2 := "2019-01-01", "2019-09-30"
days := daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
date1, date2 = "2015-12-31", "2016-09-30"
days = daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
}
|
Produce a language-to-language conversion: from REXX to C, same semantics. |
parse arg $1 $2 .
say abs( date('B',$1,"I") - date('B',$2,"I") ) ' days between ' $1 " and " $2
| #include<stdbool.h>
#include<string.h>
#include<stdio.h>
typedef struct{
int year, month, day;
}date;
date extractDate(char* str){
return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')};
}
bool isValidDate(char* str){
date newDate;
if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){
return false;
}
newDate = extractDate(str);
if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) ||
((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) ||
newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){
return false;
}
return true;
}
int diffDays(date date1,date date2){
int days1, days2;
date1.month = (date1.month + 9)%12;
date1.year = date1.year - date1.month/10;
date2.month = (date2.month + 9)%12;
date2.year = date2.year - date2.month/10;
days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 );
days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 );
return days2 - days1;
}
int main(int argc,char** argv)
{
if(argc!=3){
return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]);
}
if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){
return printf("Dates are invalid.\n");
}
printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2])));
return 0;
}
|
Write the same code in C as shown below in REXX. |
parse arg $1 $2 .
say abs( date('B',$1,"I") - date('B',$2,"I") ) ' days between ' $1 " and " $2
| #include<stdbool.h>
#include<string.h>
#include<stdio.h>
typedef struct{
int year, month, day;
}date;
date extractDate(char* str){
return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')};
}
bool isValidDate(char* str){
date newDate;
if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){
return false;
}
newDate = extractDate(str);
if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) ||
((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) ||
newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){
return false;
}
return true;
}
int diffDays(date date1,date date2){
int days1, days2;
date1.month = (date1.month + 9)%12;
date1.year = date1.year - date1.month/10;
date2.month = (date2.month + 9)%12;
date2.year = date2.year - date2.month/10;
days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 );
days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 );
return days2 - days1;
}
int main(int argc,char** argv)
{
if(argc!=3){
return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]);
}
if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){
return printf("Dates are invalid.\n");
}
printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2])));
return 0;
}
|
Generate a C# translation of this REXX snippet without changing its computational steps. |
parse arg $1 $2 .
say abs( date('B',$1,"I") - date('B',$2,"I") ) ' days between ' $1 " and " $2
| using System;
using System.Globalization;
public class Program
{
public static void Main() => WriteLine(DateDiff("1970-01-01", "2019-10-18"));
public static int DateDiff(string d1, string d2) {
var a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture);
return (int)(b - a).TotalDays;
}
}
|
Produce a functionally identical C# code for the snippet given in REXX. |
parse arg $1 $2 .
say abs( date('B',$1,"I") - date('B',$2,"I") ) ' days between ' $1 " and " $2
| using System;
using System.Globalization;
public class Program
{
public static void Main() => WriteLine(DateDiff("1970-01-01", "2019-10-18"));
public static int DateDiff(string d1, string d2) {
var a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture);
return (int)(b - a).TotalDays;
}
}
|
Rewrite the snippet below in C++ so it works the same as the original REXX code. |
parse arg $1 $2 .
say abs( date('B',$1,"I") - date('B',$2,"I") ) ' days between ' $1 " and " $2
| #include <iomanip>
#include <iostream>
class Date {
private:
int year, month, day;
public:
Date(std::string str) {
if (isValidDate(str)) {
year = atoi(&str[0]);
month = atoi(&str[5]);
day = atoi(&str[8]);
} else {
throw std::exception("Invalid date");
}
}
int getYear() {
return year;
}
int getMonth() {
return month;
}
int getDay() {
return day;
}
static bool isValidDate(std::string str) {
if (str.length() != 10 || str[4] != '-' || str[7] != '-') {
return false;
}
if (!isdigit(str[0]) || !isdigit(str[1]) || !isdigit(str[2]) || !isdigit(str[3])) {
return false;
}
if (!isdigit(str[5]) || !isdigit(str[6])) {
return false;
}
if (!isdigit(str[8]) || !isdigit(str[9])) {
return false;
}
int year = atoi(&str[0]);
int month = atoi(&str[5]);
int day = atoi(&str[8]);
if (year <= 0 || month <= 0 || day <= 0) {
return false;
}
if (month > 12) {
return false;
}
switch (month) {
case 2:
if (day > 29) {
return false;
}
if (!isLeapYear(year) && day == 29) {
return false;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day > 31) {
return false;
}
break;
default:
if (day > 30) {
return false;
}
break;
}
return true;
}
static bool isLeapYear(int year) {
if (year > 1582) {
return ((year % 4 == 0) && (year % 100 > 0))
|| (year % 400 == 0);
}
if (year > 10) {
return year % 4 == 0;
}
return false;
}
friend std::ostream &operator<<(std::ostream &, Date &);
};
std::ostream &operator<<(std::ostream &os, Date &d) {
os << std::setfill('0') << std::setw(4) << d.year << '-';
os << std::setfill('0') << std::setw(2) << d.month << '-';
os << std::setfill('0') << std::setw(2) << d.day;
return os;
}
int diffDays(Date date1, Date date2) {
int d1m = (date1.getMonth() + 9) % 12;
int d1y = date1.getYear() - d1m / 10;
int d2m = (date2.getMonth() + 9) % 12;
int d2y = date2.getYear() - d2m / 10;
int days1 = 365 * d1y + d1y / 4 - d1y / 100 + d1y / 400 + (d1m * 306 + 5) / 10 + (date1.getDay() - 1);
int days2 = 365 * d2y + d2y / 4 - d2y / 100 + d2y / 400 + (d2m * 306 + 5) / 10 + (date2.getDay() - 1);
return days2 - days1;
}
int main() {
std::string ds1 = "2019-01-01";
std::string ds2 = "2019-12-02";
if (Date::isValidDate(ds1) && Date::isValidDate(ds2)) {
Date d1(ds1);
Date d2(ds2);
std::cout << "Days difference : " << diffDays(d1, d2);
} else {
std::cout << "Dates are invalid.\n";
}
return 0;
}
|
Port the provided REXX code into C++ while preserving the original functionality. |
parse arg $1 $2 .
say abs( date('B',$1,"I") - date('B',$2,"I") ) ' days between ' $1 " and " $2
| #include <iomanip>
#include <iostream>
class Date {
private:
int year, month, day;
public:
Date(std::string str) {
if (isValidDate(str)) {
year = atoi(&str[0]);
month = atoi(&str[5]);
day = atoi(&str[8]);
} else {
throw std::exception("Invalid date");
}
}
int getYear() {
return year;
}
int getMonth() {
return month;
}
int getDay() {
return day;
}
static bool isValidDate(std::string str) {
if (str.length() != 10 || str[4] != '-' || str[7] != '-') {
return false;
}
if (!isdigit(str[0]) || !isdigit(str[1]) || !isdigit(str[2]) || !isdigit(str[3])) {
return false;
}
if (!isdigit(str[5]) || !isdigit(str[6])) {
return false;
}
if (!isdigit(str[8]) || !isdigit(str[9])) {
return false;
}
int year = atoi(&str[0]);
int month = atoi(&str[5]);
int day = atoi(&str[8]);
if (year <= 0 || month <= 0 || day <= 0) {
return false;
}
if (month > 12) {
return false;
}
switch (month) {
case 2:
if (day > 29) {
return false;
}
if (!isLeapYear(year) && day == 29) {
return false;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day > 31) {
return false;
}
break;
default:
if (day > 30) {
return false;
}
break;
}
return true;
}
static bool isLeapYear(int year) {
if (year > 1582) {
return ((year % 4 == 0) && (year % 100 > 0))
|| (year % 400 == 0);
}
if (year > 10) {
return year % 4 == 0;
}
return false;
}
friend std::ostream &operator<<(std::ostream &, Date &);
};
std::ostream &operator<<(std::ostream &os, Date &d) {
os << std::setfill('0') << std::setw(4) << d.year << '-';
os << std::setfill('0') << std::setw(2) << d.month << '-';
os << std::setfill('0') << std::setw(2) << d.day;
return os;
}
int diffDays(Date date1, Date date2) {
int d1m = (date1.getMonth() + 9) % 12;
int d1y = date1.getYear() - d1m / 10;
int d2m = (date2.getMonth() + 9) % 12;
int d2y = date2.getYear() - d2m / 10;
int days1 = 365 * d1y + d1y / 4 - d1y / 100 + d1y / 400 + (d1m * 306 + 5) / 10 + (date1.getDay() - 1);
int days2 = 365 * d2y + d2y / 4 - d2y / 100 + d2y / 400 + (d2m * 306 + 5) / 10 + (date2.getDay() - 1);
return days2 - days1;
}
int main() {
std::string ds1 = "2019-01-01";
std::string ds2 = "2019-12-02";
if (Date::isValidDate(ds1) && Date::isValidDate(ds2)) {
Date d1(ds1);
Date d2(ds2);
std::cout << "Days difference : " << diffDays(d1, d2);
} else {
std::cout << "Dates are invalid.\n";
}
return 0;
}
|
Please provide an equivalent version of this REXX code in Java. |
parse arg $1 $2 .
say abs( date('B',$1,"I") - date('B',$2,"I") ) ' days between ' $1 " and " $2
| import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates {
public static void main(String[] args) {
LocalDate fromDate = LocalDate.parse("2019-01-01");
LocalDate toDate = LocalDate.parse("2019-10-19");
long diff = ChronoUnit.DAYS.between(fromDate, toDate);
System.out.printf("Number of days between %s and %s: %d\n", fromDate, toDate, diff);
}
}
|
Produce a language-to-language conversion: from REXX to Java, same semantics. |
parse arg $1 $2 .
say abs( date('B',$1,"I") - date('B',$2,"I") ) ' days between ' $1 " and " $2
| import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates {
public static void main(String[] args) {
LocalDate fromDate = LocalDate.parse("2019-01-01");
LocalDate toDate = LocalDate.parse("2019-10-19");
long diff = ChronoUnit.DAYS.between(fromDate, toDate);
System.out.printf("Number of days between %s and %s: %d\n", fromDate, toDate, diff);
}
}
|
Rewrite this program in Python while keeping its functionality equivalent to the REXX version. |
parse arg $1 $2 .
say abs( date('B',$1,"I") - date('B',$2,"I") ) ' days between ' $1 " and " $2
|
import sys
def days( y,m,d ):
m = (m + 9) % 12
y = y - m/10
result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
return result
def diff(one,two):
[y1,m1,d1] = one.split('-')
[y2,m2,d2] = two.split('-')
year2 = days( int(y2),int(m2),int(d2))
year1 = days( int(y1), int(m1), int(d1) )
return year2 - year1
if __name__ == "__main__":
one = sys.argv[1]
two = sys.argv[2]
print diff(one,two)
|
Maintain the same structure and functionality when rewriting this code in Python. |
parse arg $1 $2 .
say abs( date('B',$1,"I") - date('B',$2,"I") ) ' days between ' $1 " and " $2
|
import sys
def days( y,m,d ):
m = (m + 9) % 12
y = y - m/10
result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
return result
def diff(one,two):
[y1,m1,d1] = one.split('-')
[y2,m2,d2] = two.split('-')
year2 = days( int(y2),int(m2),int(d2))
year1 = days( int(y1), int(m1), int(d1) )
return year2 - year1
if __name__ == "__main__":
one = sys.argv[1]
two = sys.argv[2]
print diff(one,two)
|
Produce a language-to-language conversion: from REXX to VB, same semantics. |
parse arg $1 $2 .
say abs( date('B',$1,"I") - date('B',$2,"I") ) ' days between ' $1 " and " $2
| Imports System.Globalization
Module Module1
Function DateDiff(d1 As String, d2 As String) As Integer
Dim a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Return (b - a).TotalDays
End Function
Sub Main()
Console.WriteLine(DateDiff("1970-01-01", "2019-10-18"))
End Sub
End Module
|
Generate a VB translation of this REXX snippet without changing its computational steps. |
parse arg $1 $2 .
say abs( date('B',$1,"I") - date('B',$2,"I") ) ' days between ' $1 " and " $2
| Imports System.Globalization
Module Module1
Function DateDiff(d1 As String, d2 As String) As Integer
Dim a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Return (b - a).TotalDays
End Function
Sub Main()
Console.WriteLine(DateDiff("1970-01-01", "2019-10-18"))
End Sub
End Module
|
Convert the following code from REXX to Go, ensuring the logic remains intact. |
parse arg $1 $2 .
say abs( date('B',$1,"I") - date('B',$2,"I") ) ' days between ' $1 " and " $2
| package main
import (
"fmt"
"log"
"time"
)
const layout = "2006-01-02"
func daysBetween(date1, date2 string) int {
t1, err := time.Parse(layout, date1)
check(err)
t2, err := time.Parse(layout, date2)
check(err)
days := int(t1.Sub(t2).Hours() / 24)
if days < 0 {
days = -days
}
return days
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
date1, date2 := "2019-01-01", "2019-09-30"
days := daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
date1, date2 = "2015-12-31", "2016-09-30"
days = daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
}
|
Transform the following REXX implementation into Go, maintaining the same output and logic. |
parse arg $1 $2 .
say abs( date('B',$1,"I") - date('B',$2,"I") ) ' days between ' $1 " and " $2
| package main
import (
"fmt"
"log"
"time"
)
const layout = "2006-01-02"
func daysBetween(date1, date2 string) int {
t1, err := time.Parse(layout, date1)
check(err)
t2, err := time.Parse(layout, date2)
check(err)
days := int(t1.Sub(t2).Hours() / 24)
if days < 0 {
days = -days
}
return days
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
date1, date2 := "2019-01-01", "2019-09-30"
days := daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
date1, date2 = "2015-12-31", "2016-09-30"
days = daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
}
|
Produce a functionally identical C code for the snippet given in Ruby. | require "date"
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
p (d1 - d2).to_i
p (d2 - d1).to_i
| #include<stdbool.h>
#include<string.h>
#include<stdio.h>
typedef struct{
int year, month, day;
}date;
date extractDate(char* str){
return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')};
}
bool isValidDate(char* str){
date newDate;
if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){
return false;
}
newDate = extractDate(str);
if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) ||
((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) ||
newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){
return false;
}
return true;
}
int diffDays(date date1,date date2){
int days1, days2;
date1.month = (date1.month + 9)%12;
date1.year = date1.year - date1.month/10;
date2.month = (date2.month + 9)%12;
date2.year = date2.year - date2.month/10;
days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 );
days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 );
return days2 - days1;
}
int main(int argc,char** argv)
{
if(argc!=3){
return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]);
}
if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){
return printf("Dates are invalid.\n");
}
printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2])));
return 0;
}
|
Rewrite this program in C while keeping its functionality equivalent to the Ruby version. | require "date"
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
p (d1 - d2).to_i
p (d2 - d1).to_i
| #include<stdbool.h>
#include<string.h>
#include<stdio.h>
typedef struct{
int year, month, day;
}date;
date extractDate(char* str){
return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')};
}
bool isValidDate(char* str){
date newDate;
if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){
return false;
}
newDate = extractDate(str);
if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) ||
((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) ||
newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){
return false;
}
return true;
}
int diffDays(date date1,date date2){
int days1, days2;
date1.month = (date1.month + 9)%12;
date1.year = date1.year - date1.month/10;
date2.month = (date2.month + 9)%12;
date2.year = date2.year - date2.month/10;
days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 );
days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 );
return days2 - days1;
}
int main(int argc,char** argv)
{
if(argc!=3){
return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]);
}
if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){
return printf("Dates are invalid.\n");
}
printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2])));
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C#. | require "date"
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
p (d1 - d2).to_i
p (d2 - d1).to_i
| using System;
using System.Globalization;
public class Program
{
public static void Main() => WriteLine(DateDiff("1970-01-01", "2019-10-18"));
public static int DateDiff(string d1, string d2) {
var a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture);
return (int)(b - a).TotalDays;
}
}
|
Write the same code in C# as shown below in Ruby. | require "date"
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
p (d1 - d2).to_i
p (d2 - d1).to_i
| using System;
using System.Globalization;
public class Program
{
public static void Main() => WriteLine(DateDiff("1970-01-01", "2019-10-18"));
public static int DateDiff(string d1, string d2) {
var a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture);
return (int)(b - a).TotalDays;
}
}
|
Change the programming language of this snippet from Ruby to C++ without modifying what it does. | require "date"
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
p (d1 - d2).to_i
p (d2 - d1).to_i
| #include <iomanip>
#include <iostream>
class Date {
private:
int year, month, day;
public:
Date(std::string str) {
if (isValidDate(str)) {
year = atoi(&str[0]);
month = atoi(&str[5]);
day = atoi(&str[8]);
} else {
throw std::exception("Invalid date");
}
}
int getYear() {
return year;
}
int getMonth() {
return month;
}
int getDay() {
return day;
}
static bool isValidDate(std::string str) {
if (str.length() != 10 || str[4] != '-' || str[7] != '-') {
return false;
}
if (!isdigit(str[0]) || !isdigit(str[1]) || !isdigit(str[2]) || !isdigit(str[3])) {
return false;
}
if (!isdigit(str[5]) || !isdigit(str[6])) {
return false;
}
if (!isdigit(str[8]) || !isdigit(str[9])) {
return false;
}
int year = atoi(&str[0]);
int month = atoi(&str[5]);
int day = atoi(&str[8]);
if (year <= 0 || month <= 0 || day <= 0) {
return false;
}
if (month > 12) {
return false;
}
switch (month) {
case 2:
if (day > 29) {
return false;
}
if (!isLeapYear(year) && day == 29) {
return false;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day > 31) {
return false;
}
break;
default:
if (day > 30) {
return false;
}
break;
}
return true;
}
static bool isLeapYear(int year) {
if (year > 1582) {
return ((year % 4 == 0) && (year % 100 > 0))
|| (year % 400 == 0);
}
if (year > 10) {
return year % 4 == 0;
}
return false;
}
friend std::ostream &operator<<(std::ostream &, Date &);
};
std::ostream &operator<<(std::ostream &os, Date &d) {
os << std::setfill('0') << std::setw(4) << d.year << '-';
os << std::setfill('0') << std::setw(2) << d.month << '-';
os << std::setfill('0') << std::setw(2) << d.day;
return os;
}
int diffDays(Date date1, Date date2) {
int d1m = (date1.getMonth() + 9) % 12;
int d1y = date1.getYear() - d1m / 10;
int d2m = (date2.getMonth() + 9) % 12;
int d2y = date2.getYear() - d2m / 10;
int days1 = 365 * d1y + d1y / 4 - d1y / 100 + d1y / 400 + (d1m * 306 + 5) / 10 + (date1.getDay() - 1);
int days2 = 365 * d2y + d2y / 4 - d2y / 100 + d2y / 400 + (d2m * 306 + 5) / 10 + (date2.getDay() - 1);
return days2 - days1;
}
int main() {
std::string ds1 = "2019-01-01";
std::string ds2 = "2019-12-02";
if (Date::isValidDate(ds1) && Date::isValidDate(ds2)) {
Date d1(ds1);
Date d2(ds2);
std::cout << "Days difference : " << diffDays(d1, d2);
} else {
std::cout << "Dates are invalid.\n";
}
return 0;
}
|
Can you help me rewrite this code in C++ instead of Ruby, keeping it the same logically? | require "date"
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
p (d1 - d2).to_i
p (d2 - d1).to_i
| #include <iomanip>
#include <iostream>
class Date {
private:
int year, month, day;
public:
Date(std::string str) {
if (isValidDate(str)) {
year = atoi(&str[0]);
month = atoi(&str[5]);
day = atoi(&str[8]);
} else {
throw std::exception("Invalid date");
}
}
int getYear() {
return year;
}
int getMonth() {
return month;
}
int getDay() {
return day;
}
static bool isValidDate(std::string str) {
if (str.length() != 10 || str[4] != '-' || str[7] != '-') {
return false;
}
if (!isdigit(str[0]) || !isdigit(str[1]) || !isdigit(str[2]) || !isdigit(str[3])) {
return false;
}
if (!isdigit(str[5]) || !isdigit(str[6])) {
return false;
}
if (!isdigit(str[8]) || !isdigit(str[9])) {
return false;
}
int year = atoi(&str[0]);
int month = atoi(&str[5]);
int day = atoi(&str[8]);
if (year <= 0 || month <= 0 || day <= 0) {
return false;
}
if (month > 12) {
return false;
}
switch (month) {
case 2:
if (day > 29) {
return false;
}
if (!isLeapYear(year) && day == 29) {
return false;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day > 31) {
return false;
}
break;
default:
if (day > 30) {
return false;
}
break;
}
return true;
}
static bool isLeapYear(int year) {
if (year > 1582) {
return ((year % 4 == 0) && (year % 100 > 0))
|| (year % 400 == 0);
}
if (year > 10) {
return year % 4 == 0;
}
return false;
}
friend std::ostream &operator<<(std::ostream &, Date &);
};
std::ostream &operator<<(std::ostream &os, Date &d) {
os << std::setfill('0') << std::setw(4) << d.year << '-';
os << std::setfill('0') << std::setw(2) << d.month << '-';
os << std::setfill('0') << std::setw(2) << d.day;
return os;
}
int diffDays(Date date1, Date date2) {
int d1m = (date1.getMonth() + 9) % 12;
int d1y = date1.getYear() - d1m / 10;
int d2m = (date2.getMonth() + 9) % 12;
int d2y = date2.getYear() - d2m / 10;
int days1 = 365 * d1y + d1y / 4 - d1y / 100 + d1y / 400 + (d1m * 306 + 5) / 10 + (date1.getDay() - 1);
int days2 = 365 * d2y + d2y / 4 - d2y / 100 + d2y / 400 + (d2m * 306 + 5) / 10 + (date2.getDay() - 1);
return days2 - days1;
}
int main() {
std::string ds1 = "2019-01-01";
std::string ds2 = "2019-12-02";
if (Date::isValidDate(ds1) && Date::isValidDate(ds2)) {
Date d1(ds1);
Date d2(ds2);
std::cout << "Days difference : " << diffDays(d1, d2);
} else {
std::cout << "Dates are invalid.\n";
}
return 0;
}
|
Port the provided Ruby code into Java while preserving the original functionality. | require "date"
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
p (d1 - d2).to_i
p (d2 - d1).to_i
| import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates {
public static void main(String[] args) {
LocalDate fromDate = LocalDate.parse("2019-01-01");
LocalDate toDate = LocalDate.parse("2019-10-19");
long diff = ChronoUnit.DAYS.between(fromDate, toDate);
System.out.printf("Number of days between %s and %s: %d\n", fromDate, toDate, diff);
}
}
|
Port the provided Ruby code into Java while preserving the original functionality. | require "date"
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
p (d1 - d2).to_i
p (d2 - d1).to_i
| import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates {
public static void main(String[] args) {
LocalDate fromDate = LocalDate.parse("2019-01-01");
LocalDate toDate = LocalDate.parse("2019-10-19");
long diff = ChronoUnit.DAYS.between(fromDate, toDate);
System.out.printf("Number of days between %s and %s: %d\n", fromDate, toDate, diff);
}
}
|
Produce a language-to-language conversion: from Ruby to Python, same semantics. | require "date"
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
p (d1 - d2).to_i
p (d2 - d1).to_i
|
import sys
def days( y,m,d ):
m = (m + 9) % 12
y = y - m/10
result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
return result
def diff(one,two):
[y1,m1,d1] = one.split('-')
[y2,m2,d2] = two.split('-')
year2 = days( int(y2),int(m2),int(d2))
year1 = days( int(y1), int(m1), int(d1) )
return year2 - year1
if __name__ == "__main__":
one = sys.argv[1]
two = sys.argv[2]
print diff(one,two)
|
Ensure the translated Python code behaves exactly like the original Ruby snippet. | require "date"
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
p (d1 - d2).to_i
p (d2 - d1).to_i
|
import sys
def days( y,m,d ):
m = (m + 9) % 12
y = y - m/10
result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
return result
def diff(one,two):
[y1,m1,d1] = one.split('-')
[y2,m2,d2] = two.split('-')
year2 = days( int(y2),int(m2),int(d2))
year1 = days( int(y1), int(m1), int(d1) )
return year2 - year1
if __name__ == "__main__":
one = sys.argv[1]
two = sys.argv[2]
print diff(one,two)
|
Produce a language-to-language conversion: from Ruby to VB, same semantics. | require "date"
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
p (d1 - d2).to_i
p (d2 - d1).to_i
| Imports System.Globalization
Module Module1
Function DateDiff(d1 As String, d2 As String) As Integer
Dim a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Return (b - a).TotalDays
End Function
Sub Main()
Console.WriteLine(DateDiff("1970-01-01", "2019-10-18"))
End Sub
End Module
|
Rewrite the snippet below in VB so it works the same as the original Ruby code. | require "date"
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
p (d1 - d2).to_i
p (d2 - d1).to_i
| Imports System.Globalization
Module Module1
Function DateDiff(d1 As String, d2 As String) As Integer
Dim a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Return (b - a).TotalDays
End Function
Sub Main()
Console.WriteLine(DateDiff("1970-01-01", "2019-10-18"))
End Sub
End Module
|
Can you help me rewrite this code in Go instead of Ruby, keeping it the same logically? | require "date"
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
p (d1 - d2).to_i
p (d2 - d1).to_i
| package main
import (
"fmt"
"log"
"time"
)
const layout = "2006-01-02"
func daysBetween(date1, date2 string) int {
t1, err := time.Parse(layout, date1)
check(err)
t2, err := time.Parse(layout, date2)
check(err)
days := int(t1.Sub(t2).Hours() / 24)
if days < 0 {
days = -days
}
return days
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
date1, date2 := "2019-01-01", "2019-09-30"
days := daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
date1, date2 = "2015-12-31", "2016-09-30"
days = daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
}
|
Translate the given Ruby code snippet into Go without altering its behavior. | require "date"
d1, d2 = Date.parse("2019-1-1"), Date.parse("2019-10-19")
p (d1 - d2).to_i
p (d2 - d1).to_i
| package main
import (
"fmt"
"log"
"time"
)
const layout = "2006-01-02"
func daysBetween(date1, date2 string) int {
t1, err := time.Parse(layout, date1)
check(err)
t2, err := time.Parse(layout, date2)
check(err)
days := int(t1.Sub(t2).Hours() / 24)
if days < 0 {
days = -days
}
return days
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
date1, date2 := "2019-01-01", "2019-09-30"
days := daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
date1, date2 = "2015-12-31", "2016-09-30"
days = daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
}
|
Change the programming language of this snippet from Scala to C without modifying what it does. | import java.time.LocalDate
import java.time.temporal.ChronoUnit
fun main() {
val fromDate = LocalDate.parse("2019-01-01")
val toDate = LocalDate.parse("2019-10-19")
val diff = ChronoUnit.DAYS.between(fromDate, toDate)
println("Number of days between $fromDate and $toDate: $diff")
}
| #include<stdbool.h>
#include<string.h>
#include<stdio.h>
typedef struct{
int year, month, day;
}date;
date extractDate(char* str){
return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')};
}
bool isValidDate(char* str){
date newDate;
if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){
return false;
}
newDate = extractDate(str);
if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) ||
((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) ||
newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){
return false;
}
return true;
}
int diffDays(date date1,date date2){
int days1, days2;
date1.month = (date1.month + 9)%12;
date1.year = date1.year - date1.month/10;
date2.month = (date2.month + 9)%12;
date2.year = date2.year - date2.month/10;
days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 );
days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 );
return days2 - days1;
}
int main(int argc,char** argv)
{
if(argc!=3){
return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]);
}
if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){
return printf("Dates are invalid.\n");
}
printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2])));
return 0;
}
|
Convert this Scala snippet to C and keep its semantics consistent. | import java.time.LocalDate
import java.time.temporal.ChronoUnit
fun main() {
val fromDate = LocalDate.parse("2019-01-01")
val toDate = LocalDate.parse("2019-10-19")
val diff = ChronoUnit.DAYS.between(fromDate, toDate)
println("Number of days between $fromDate and $toDate: $diff")
}
| #include<stdbool.h>
#include<string.h>
#include<stdio.h>
typedef struct{
int year, month, day;
}date;
date extractDate(char* str){
return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')};
}
bool isValidDate(char* str){
date newDate;
if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){
return false;
}
newDate = extractDate(str);
if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) ||
((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) ||
newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){
return false;
}
return true;
}
int diffDays(date date1,date date2){
int days1, days2;
date1.month = (date1.month + 9)%12;
date1.year = date1.year - date1.month/10;
date2.month = (date2.month + 9)%12;
date2.year = date2.year - date2.month/10;
days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 );
days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 );
return days2 - days1;
}
int main(int argc,char** argv)
{
if(argc!=3){
return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]);
}
if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){
return printf("Dates are invalid.\n");
}
printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2])));
return 0;
}
|
Write the same algorithm in C# as shown in this Scala implementation. | import java.time.LocalDate
import java.time.temporal.ChronoUnit
fun main() {
val fromDate = LocalDate.parse("2019-01-01")
val toDate = LocalDate.parse("2019-10-19")
val diff = ChronoUnit.DAYS.between(fromDate, toDate)
println("Number of days between $fromDate and $toDate: $diff")
}
| using System;
using System.Globalization;
public class Program
{
public static void Main() => WriteLine(DateDiff("1970-01-01", "2019-10-18"));
public static int DateDiff(string d1, string d2) {
var a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture);
return (int)(b - a).TotalDays;
}
}
|
Transform the following Scala implementation into C++, maintaining the same output and logic. | import java.time.LocalDate
import java.time.temporal.ChronoUnit
fun main() {
val fromDate = LocalDate.parse("2019-01-01")
val toDate = LocalDate.parse("2019-10-19")
val diff = ChronoUnit.DAYS.between(fromDate, toDate)
println("Number of days between $fromDate and $toDate: $diff")
}
| #include <iomanip>
#include <iostream>
class Date {
private:
int year, month, day;
public:
Date(std::string str) {
if (isValidDate(str)) {
year = atoi(&str[0]);
month = atoi(&str[5]);
day = atoi(&str[8]);
} else {
throw std::exception("Invalid date");
}
}
int getYear() {
return year;
}
int getMonth() {
return month;
}
int getDay() {
return day;
}
static bool isValidDate(std::string str) {
if (str.length() != 10 || str[4] != '-' || str[7] != '-') {
return false;
}
if (!isdigit(str[0]) || !isdigit(str[1]) || !isdigit(str[2]) || !isdigit(str[3])) {
return false;
}
if (!isdigit(str[5]) || !isdigit(str[6])) {
return false;
}
if (!isdigit(str[8]) || !isdigit(str[9])) {
return false;
}
int year = atoi(&str[0]);
int month = atoi(&str[5]);
int day = atoi(&str[8]);
if (year <= 0 || month <= 0 || day <= 0) {
return false;
}
if (month > 12) {
return false;
}
switch (month) {
case 2:
if (day > 29) {
return false;
}
if (!isLeapYear(year) && day == 29) {
return false;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day > 31) {
return false;
}
break;
default:
if (day > 30) {
return false;
}
break;
}
return true;
}
static bool isLeapYear(int year) {
if (year > 1582) {
return ((year % 4 == 0) && (year % 100 > 0))
|| (year % 400 == 0);
}
if (year > 10) {
return year % 4 == 0;
}
return false;
}
friend std::ostream &operator<<(std::ostream &, Date &);
};
std::ostream &operator<<(std::ostream &os, Date &d) {
os << std::setfill('0') << std::setw(4) << d.year << '-';
os << std::setfill('0') << std::setw(2) << d.month << '-';
os << std::setfill('0') << std::setw(2) << d.day;
return os;
}
int diffDays(Date date1, Date date2) {
int d1m = (date1.getMonth() + 9) % 12;
int d1y = date1.getYear() - d1m / 10;
int d2m = (date2.getMonth() + 9) % 12;
int d2y = date2.getYear() - d2m / 10;
int days1 = 365 * d1y + d1y / 4 - d1y / 100 + d1y / 400 + (d1m * 306 + 5) / 10 + (date1.getDay() - 1);
int days2 = 365 * d2y + d2y / 4 - d2y / 100 + d2y / 400 + (d2m * 306 + 5) / 10 + (date2.getDay() - 1);
return days2 - days1;
}
int main() {
std::string ds1 = "2019-01-01";
std::string ds2 = "2019-12-02";
if (Date::isValidDate(ds1) && Date::isValidDate(ds2)) {
Date d1(ds1);
Date d2(ds2);
std::cout << "Days difference : " << diffDays(d1, d2);
} else {
std::cout << "Dates are invalid.\n";
}
return 0;
}
|
Port the provided Scala code into C++ while preserving the original functionality. | import java.time.LocalDate
import java.time.temporal.ChronoUnit
fun main() {
val fromDate = LocalDate.parse("2019-01-01")
val toDate = LocalDate.parse("2019-10-19")
val diff = ChronoUnit.DAYS.between(fromDate, toDate)
println("Number of days between $fromDate and $toDate: $diff")
}
| #include <iomanip>
#include <iostream>
class Date {
private:
int year, month, day;
public:
Date(std::string str) {
if (isValidDate(str)) {
year = atoi(&str[0]);
month = atoi(&str[5]);
day = atoi(&str[8]);
} else {
throw std::exception("Invalid date");
}
}
int getYear() {
return year;
}
int getMonth() {
return month;
}
int getDay() {
return day;
}
static bool isValidDate(std::string str) {
if (str.length() != 10 || str[4] != '-' || str[7] != '-') {
return false;
}
if (!isdigit(str[0]) || !isdigit(str[1]) || !isdigit(str[2]) || !isdigit(str[3])) {
return false;
}
if (!isdigit(str[5]) || !isdigit(str[6])) {
return false;
}
if (!isdigit(str[8]) || !isdigit(str[9])) {
return false;
}
int year = atoi(&str[0]);
int month = atoi(&str[5]);
int day = atoi(&str[8]);
if (year <= 0 || month <= 0 || day <= 0) {
return false;
}
if (month > 12) {
return false;
}
switch (month) {
case 2:
if (day > 29) {
return false;
}
if (!isLeapYear(year) && day == 29) {
return false;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day > 31) {
return false;
}
break;
default:
if (day > 30) {
return false;
}
break;
}
return true;
}
static bool isLeapYear(int year) {
if (year > 1582) {
return ((year % 4 == 0) && (year % 100 > 0))
|| (year % 400 == 0);
}
if (year > 10) {
return year % 4 == 0;
}
return false;
}
friend std::ostream &operator<<(std::ostream &, Date &);
};
std::ostream &operator<<(std::ostream &os, Date &d) {
os << std::setfill('0') << std::setw(4) << d.year << '-';
os << std::setfill('0') << std::setw(2) << d.month << '-';
os << std::setfill('0') << std::setw(2) << d.day;
return os;
}
int diffDays(Date date1, Date date2) {
int d1m = (date1.getMonth() + 9) % 12;
int d1y = date1.getYear() - d1m / 10;
int d2m = (date2.getMonth() + 9) % 12;
int d2y = date2.getYear() - d2m / 10;
int days1 = 365 * d1y + d1y / 4 - d1y / 100 + d1y / 400 + (d1m * 306 + 5) / 10 + (date1.getDay() - 1);
int days2 = 365 * d2y + d2y / 4 - d2y / 100 + d2y / 400 + (d2m * 306 + 5) / 10 + (date2.getDay() - 1);
return days2 - days1;
}
int main() {
std::string ds1 = "2019-01-01";
std::string ds2 = "2019-12-02";
if (Date::isValidDate(ds1) && Date::isValidDate(ds2)) {
Date d1(ds1);
Date d2(ds2);
std::cout << "Days difference : " << diffDays(d1, d2);
} else {
std::cout << "Dates are invalid.\n";
}
return 0;
}
|
Generate an equivalent Java version of this Scala code. | import java.time.LocalDate
import java.time.temporal.ChronoUnit
fun main() {
val fromDate = LocalDate.parse("2019-01-01")
val toDate = LocalDate.parse("2019-10-19")
val diff = ChronoUnit.DAYS.between(fromDate, toDate)
println("Number of days between $fromDate and $toDate: $diff")
}
| import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates {
public static void main(String[] args) {
LocalDate fromDate = LocalDate.parse("2019-01-01");
LocalDate toDate = LocalDate.parse("2019-10-19");
long diff = ChronoUnit.DAYS.between(fromDate, toDate);
System.out.printf("Number of days between %s and %s: %d\n", fromDate, toDate, diff);
}
}
|
Convert this Scala snippet to Python and keep its semantics consistent. | import java.time.LocalDate
import java.time.temporal.ChronoUnit
fun main() {
val fromDate = LocalDate.parse("2019-01-01")
val toDate = LocalDate.parse("2019-10-19")
val diff = ChronoUnit.DAYS.between(fromDate, toDate)
println("Number of days between $fromDate and $toDate: $diff")
}
|
import sys
def days( y,m,d ):
m = (m + 9) % 12
y = y - m/10
result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
return result
def diff(one,two):
[y1,m1,d1] = one.split('-')
[y2,m2,d2] = two.split('-')
year2 = days( int(y2),int(m2),int(d2))
year1 = days( int(y1), int(m1), int(d1) )
return year2 - year1
if __name__ == "__main__":
one = sys.argv[1]
two = sys.argv[2]
print diff(one,two)
|
Generate an equivalent Python version of this Scala code. | import java.time.LocalDate
import java.time.temporal.ChronoUnit
fun main() {
val fromDate = LocalDate.parse("2019-01-01")
val toDate = LocalDate.parse("2019-10-19")
val diff = ChronoUnit.DAYS.between(fromDate, toDate)
println("Number of days between $fromDate and $toDate: $diff")
}
|
import sys
def days( y,m,d ):
m = (m + 9) % 12
y = y - m/10
result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
return result
def diff(one,two):
[y1,m1,d1] = one.split('-')
[y2,m2,d2] = two.split('-')
year2 = days( int(y2),int(m2),int(d2))
year1 = days( int(y1), int(m1), int(d1) )
return year2 - year1
if __name__ == "__main__":
one = sys.argv[1]
two = sys.argv[2]
print diff(one,two)
|
Rewrite this program in VB while keeping its functionality equivalent to the Scala version. | import java.time.LocalDate
import java.time.temporal.ChronoUnit
fun main() {
val fromDate = LocalDate.parse("2019-01-01")
val toDate = LocalDate.parse("2019-10-19")
val diff = ChronoUnit.DAYS.between(fromDate, toDate)
println("Number of days between $fromDate and $toDate: $diff")
}
| Imports System.Globalization
Module Module1
Function DateDiff(d1 As String, d2 As String) As Integer
Dim a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Return (b - a).TotalDays
End Function
Sub Main()
Console.WriteLine(DateDiff("1970-01-01", "2019-10-18"))
End Sub
End Module
|
Port the provided Scala code into VB while preserving the original functionality. | import java.time.LocalDate
import java.time.temporal.ChronoUnit
fun main() {
val fromDate = LocalDate.parse("2019-01-01")
val toDate = LocalDate.parse("2019-10-19")
val diff = ChronoUnit.DAYS.between(fromDate, toDate)
println("Number of days between $fromDate and $toDate: $diff")
}
| Imports System.Globalization
Module Module1
Function DateDiff(d1 As String, d2 As String) As Integer
Dim a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Return (b - a).TotalDays
End Function
Sub Main()
Console.WriteLine(DateDiff("1970-01-01", "2019-10-18"))
End Sub
End Module
|
Keep all operations the same but rewrite the snippet in Go. | import java.time.LocalDate
import java.time.temporal.ChronoUnit
fun main() {
val fromDate = LocalDate.parse("2019-01-01")
val toDate = LocalDate.parse("2019-10-19")
val diff = ChronoUnit.DAYS.between(fromDate, toDate)
println("Number of days between $fromDate and $toDate: $diff")
}
| package main
import (
"fmt"
"log"
"time"
)
const layout = "2006-01-02"
func daysBetween(date1, date2 string) int {
t1, err := time.Parse(layout, date1)
check(err)
t2, err := time.Parse(layout, date2)
check(err)
days := int(t1.Sub(t2).Hours() / 24)
if days < 0 {
days = -days
}
return days
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
date1, date2 := "2019-01-01", "2019-09-30"
days := daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
date1, date2 = "2015-12-31", "2016-09-30"
days = daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
}
|
Convert this Scala block to Go, preserving its control flow and logic. | import java.time.LocalDate
import java.time.temporal.ChronoUnit
fun main() {
val fromDate = LocalDate.parse("2019-01-01")
val toDate = LocalDate.parse("2019-10-19")
val diff = ChronoUnit.DAYS.between(fromDate, toDate)
println("Number of days between $fromDate and $toDate: $diff")
}
| package main
import (
"fmt"
"log"
"time"
)
const layout = "2006-01-02"
func daysBetween(date1, date2 string) int {
t1, err := time.Parse(layout, date1)
check(err)
t2, err := time.Parse(layout, date2)
check(err)
days := int(t1.Sub(t2).Hours() / 24)
if days < 0 {
days = -days
}
return days
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
date1, date2 := "2019-01-01", "2019-09-30"
days := daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
date1, date2 = "2015-12-31", "2016-09-30"
days = daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
}
|
Translate this program into C but keep the logic exactly as in Swift. | import Foundation
func daysFromTimeInterval(_ interval: Double) -> Int {
return Int(interval) / 86400
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
print("Enter date one (yyyy-MM-dd): ", terminator: "")
guard let date1Str = readLine(strippingNewline: true), let date1 = formatter.date(from: date1Str) else {
fatalError("Invalid date two")
}
print("Enter date two (yyyy-MM-dd): ", terminator: "")
guard let date2Str = readLine(strippingNewline: true), let date2 = formatter.date(from: date2Str) else {
fatalError("Invalid date two")
}
let (start, end) = date1 > date2 ? (date2, date1) : (date1, date2)
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
print("There are \(days) days between \(start) and \(end)")
| #include<stdbool.h>
#include<string.h>
#include<stdio.h>
typedef struct{
int year, month, day;
}date;
date extractDate(char* str){
return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')};
}
bool isValidDate(char* str){
date newDate;
if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){
return false;
}
newDate = extractDate(str);
if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) ||
((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) ||
newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){
return false;
}
return true;
}
int diffDays(date date1,date date2){
int days1, days2;
date1.month = (date1.month + 9)%12;
date1.year = date1.year - date1.month/10;
date2.month = (date2.month + 9)%12;
date2.year = date2.year - date2.month/10;
days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 );
days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 );
return days2 - days1;
}
int main(int argc,char** argv)
{
if(argc!=3){
return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]);
}
if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){
return printf("Dates are invalid.\n");
}
printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2])));
return 0;
}
|
Translate this program into C but keep the logic exactly as in Swift. | import Foundation
func daysFromTimeInterval(_ interval: Double) -> Int {
return Int(interval) / 86400
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
print("Enter date one (yyyy-MM-dd): ", terminator: "")
guard let date1Str = readLine(strippingNewline: true), let date1 = formatter.date(from: date1Str) else {
fatalError("Invalid date two")
}
print("Enter date two (yyyy-MM-dd): ", terminator: "")
guard let date2Str = readLine(strippingNewline: true), let date2 = formatter.date(from: date2Str) else {
fatalError("Invalid date two")
}
let (start, end) = date1 > date2 ? (date2, date1) : (date1, date2)
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
print("There are \(days) days between \(start) and \(end)")
| #include<stdbool.h>
#include<string.h>
#include<stdio.h>
typedef struct{
int year, month, day;
}date;
date extractDate(char* str){
return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')};
}
bool isValidDate(char* str){
date newDate;
if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){
return false;
}
newDate = extractDate(str);
if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) ||
((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) ||
newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){
return false;
}
return true;
}
int diffDays(date date1,date date2){
int days1, days2;
date1.month = (date1.month + 9)%12;
date1.year = date1.year - date1.month/10;
date2.month = (date2.month + 9)%12;
date2.year = date2.year - date2.month/10;
days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 );
days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 );
return days2 - days1;
}
int main(int argc,char** argv)
{
if(argc!=3){
return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]);
}
if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){
return printf("Dates are invalid.\n");
}
printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2])));
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Swift to C#. | import Foundation
func daysFromTimeInterval(_ interval: Double) -> Int {
return Int(interval) / 86400
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
print("Enter date one (yyyy-MM-dd): ", terminator: "")
guard let date1Str = readLine(strippingNewline: true), let date1 = formatter.date(from: date1Str) else {
fatalError("Invalid date two")
}
print("Enter date two (yyyy-MM-dd): ", terminator: "")
guard let date2Str = readLine(strippingNewline: true), let date2 = formatter.date(from: date2Str) else {
fatalError("Invalid date two")
}
let (start, end) = date1 > date2 ? (date2, date1) : (date1, date2)
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
print("There are \(days) days between \(start) and \(end)")
| using System;
using System.Globalization;
public class Program
{
public static void Main() => WriteLine(DateDiff("1970-01-01", "2019-10-18"));
public static int DateDiff(string d1, string d2) {
var a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture);
return (int)(b - a).TotalDays;
}
}
|
Keep all operations the same but rewrite the snippet in C#. | import Foundation
func daysFromTimeInterval(_ interval: Double) -> Int {
return Int(interval) / 86400
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
print("Enter date one (yyyy-MM-dd): ", terminator: "")
guard let date1Str = readLine(strippingNewline: true), let date1 = formatter.date(from: date1Str) else {
fatalError("Invalid date two")
}
print("Enter date two (yyyy-MM-dd): ", terminator: "")
guard let date2Str = readLine(strippingNewline: true), let date2 = formatter.date(from: date2Str) else {
fatalError("Invalid date two")
}
let (start, end) = date1 > date2 ? (date2, date1) : (date1, date2)
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
print("There are \(days) days between \(start) and \(end)")
| using System;
using System.Globalization;
public class Program
{
public static void Main() => WriteLine(DateDiff("1970-01-01", "2019-10-18"));
public static int DateDiff(string d1, string d2) {
var a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture);
return (int)(b - a).TotalDays;
}
}
|
Write the same algorithm in C++ as shown in this Swift implementation. | import Foundation
func daysFromTimeInterval(_ interval: Double) -> Int {
return Int(interval) / 86400
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
print("Enter date one (yyyy-MM-dd): ", terminator: "")
guard let date1Str = readLine(strippingNewline: true), let date1 = formatter.date(from: date1Str) else {
fatalError("Invalid date two")
}
print("Enter date two (yyyy-MM-dd): ", terminator: "")
guard let date2Str = readLine(strippingNewline: true), let date2 = formatter.date(from: date2Str) else {
fatalError("Invalid date two")
}
let (start, end) = date1 > date2 ? (date2, date1) : (date1, date2)
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
print("There are \(days) days between \(start) and \(end)")
| #include <iomanip>
#include <iostream>
class Date {
private:
int year, month, day;
public:
Date(std::string str) {
if (isValidDate(str)) {
year = atoi(&str[0]);
month = atoi(&str[5]);
day = atoi(&str[8]);
} else {
throw std::exception("Invalid date");
}
}
int getYear() {
return year;
}
int getMonth() {
return month;
}
int getDay() {
return day;
}
static bool isValidDate(std::string str) {
if (str.length() != 10 || str[4] != '-' || str[7] != '-') {
return false;
}
if (!isdigit(str[0]) || !isdigit(str[1]) || !isdigit(str[2]) || !isdigit(str[3])) {
return false;
}
if (!isdigit(str[5]) || !isdigit(str[6])) {
return false;
}
if (!isdigit(str[8]) || !isdigit(str[9])) {
return false;
}
int year = atoi(&str[0]);
int month = atoi(&str[5]);
int day = atoi(&str[8]);
if (year <= 0 || month <= 0 || day <= 0) {
return false;
}
if (month > 12) {
return false;
}
switch (month) {
case 2:
if (day > 29) {
return false;
}
if (!isLeapYear(year) && day == 29) {
return false;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day > 31) {
return false;
}
break;
default:
if (day > 30) {
return false;
}
break;
}
return true;
}
static bool isLeapYear(int year) {
if (year > 1582) {
return ((year % 4 == 0) && (year % 100 > 0))
|| (year % 400 == 0);
}
if (year > 10) {
return year % 4 == 0;
}
return false;
}
friend std::ostream &operator<<(std::ostream &, Date &);
};
std::ostream &operator<<(std::ostream &os, Date &d) {
os << std::setfill('0') << std::setw(4) << d.year << '-';
os << std::setfill('0') << std::setw(2) << d.month << '-';
os << std::setfill('0') << std::setw(2) << d.day;
return os;
}
int diffDays(Date date1, Date date2) {
int d1m = (date1.getMonth() + 9) % 12;
int d1y = date1.getYear() - d1m / 10;
int d2m = (date2.getMonth() + 9) % 12;
int d2y = date2.getYear() - d2m / 10;
int days1 = 365 * d1y + d1y / 4 - d1y / 100 + d1y / 400 + (d1m * 306 + 5) / 10 + (date1.getDay() - 1);
int days2 = 365 * d2y + d2y / 4 - d2y / 100 + d2y / 400 + (d2m * 306 + 5) / 10 + (date2.getDay() - 1);
return days2 - days1;
}
int main() {
std::string ds1 = "2019-01-01";
std::string ds2 = "2019-12-02";
if (Date::isValidDate(ds1) && Date::isValidDate(ds2)) {
Date d1(ds1);
Date d2(ds2);
std::cout << "Days difference : " << diffDays(d1, d2);
} else {
std::cout << "Dates are invalid.\n";
}
return 0;
}
|
Produce a functionally identical C++ code for the snippet given in Swift. | import Foundation
func daysFromTimeInterval(_ interval: Double) -> Int {
return Int(interval) / 86400
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
print("Enter date one (yyyy-MM-dd): ", terminator: "")
guard let date1Str = readLine(strippingNewline: true), let date1 = formatter.date(from: date1Str) else {
fatalError("Invalid date two")
}
print("Enter date two (yyyy-MM-dd): ", terminator: "")
guard let date2Str = readLine(strippingNewline: true), let date2 = formatter.date(from: date2Str) else {
fatalError("Invalid date two")
}
let (start, end) = date1 > date2 ? (date2, date1) : (date1, date2)
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
print("There are \(days) days between \(start) and \(end)")
| #include <iomanip>
#include <iostream>
class Date {
private:
int year, month, day;
public:
Date(std::string str) {
if (isValidDate(str)) {
year = atoi(&str[0]);
month = atoi(&str[5]);
day = atoi(&str[8]);
} else {
throw std::exception("Invalid date");
}
}
int getYear() {
return year;
}
int getMonth() {
return month;
}
int getDay() {
return day;
}
static bool isValidDate(std::string str) {
if (str.length() != 10 || str[4] != '-' || str[7] != '-') {
return false;
}
if (!isdigit(str[0]) || !isdigit(str[1]) || !isdigit(str[2]) || !isdigit(str[3])) {
return false;
}
if (!isdigit(str[5]) || !isdigit(str[6])) {
return false;
}
if (!isdigit(str[8]) || !isdigit(str[9])) {
return false;
}
int year = atoi(&str[0]);
int month = atoi(&str[5]);
int day = atoi(&str[8]);
if (year <= 0 || month <= 0 || day <= 0) {
return false;
}
if (month > 12) {
return false;
}
switch (month) {
case 2:
if (day > 29) {
return false;
}
if (!isLeapYear(year) && day == 29) {
return false;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day > 31) {
return false;
}
break;
default:
if (day > 30) {
return false;
}
break;
}
return true;
}
static bool isLeapYear(int year) {
if (year > 1582) {
return ((year % 4 == 0) && (year % 100 > 0))
|| (year % 400 == 0);
}
if (year > 10) {
return year % 4 == 0;
}
return false;
}
friend std::ostream &operator<<(std::ostream &, Date &);
};
std::ostream &operator<<(std::ostream &os, Date &d) {
os << std::setfill('0') << std::setw(4) << d.year << '-';
os << std::setfill('0') << std::setw(2) << d.month << '-';
os << std::setfill('0') << std::setw(2) << d.day;
return os;
}
int diffDays(Date date1, Date date2) {
int d1m = (date1.getMonth() + 9) % 12;
int d1y = date1.getYear() - d1m / 10;
int d2m = (date2.getMonth() + 9) % 12;
int d2y = date2.getYear() - d2m / 10;
int days1 = 365 * d1y + d1y / 4 - d1y / 100 + d1y / 400 + (d1m * 306 + 5) / 10 + (date1.getDay() - 1);
int days2 = 365 * d2y + d2y / 4 - d2y / 100 + d2y / 400 + (d2m * 306 + 5) / 10 + (date2.getDay() - 1);
return days2 - days1;
}
int main() {
std::string ds1 = "2019-01-01";
std::string ds2 = "2019-12-02";
if (Date::isValidDate(ds1) && Date::isValidDate(ds2)) {
Date d1(ds1);
Date d2(ds2);
std::cout << "Days difference : " << diffDays(d1, d2);
} else {
std::cout << "Dates are invalid.\n";
}
return 0;
}
|
Change the programming language of this snippet from Swift to Java without modifying what it does. | import Foundation
func daysFromTimeInterval(_ interval: Double) -> Int {
return Int(interval) / 86400
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
print("Enter date one (yyyy-MM-dd): ", terminator: "")
guard let date1Str = readLine(strippingNewline: true), let date1 = formatter.date(from: date1Str) else {
fatalError("Invalid date two")
}
print("Enter date two (yyyy-MM-dd): ", terminator: "")
guard let date2Str = readLine(strippingNewline: true), let date2 = formatter.date(from: date2Str) else {
fatalError("Invalid date two")
}
let (start, end) = date1 > date2 ? (date2, date1) : (date1, date2)
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
print("There are \(days) days between \(start) and \(end)")
| import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates {
public static void main(String[] args) {
LocalDate fromDate = LocalDate.parse("2019-01-01");
LocalDate toDate = LocalDate.parse("2019-10-19");
long diff = ChronoUnit.DAYS.between(fromDate, toDate);
System.out.printf("Number of days between %s and %s: %d\n", fromDate, toDate, diff);
}
}
|
Port the provided Swift code into Java while preserving the original functionality. | import Foundation
func daysFromTimeInterval(_ interval: Double) -> Int {
return Int(interval) / 86400
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
print("Enter date one (yyyy-MM-dd): ", terminator: "")
guard let date1Str = readLine(strippingNewline: true), let date1 = formatter.date(from: date1Str) else {
fatalError("Invalid date two")
}
print("Enter date two (yyyy-MM-dd): ", terminator: "")
guard let date2Str = readLine(strippingNewline: true), let date2 = formatter.date(from: date2Str) else {
fatalError("Invalid date two")
}
let (start, end) = date1 > date2 ? (date2, date1) : (date1, date2)
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
print("There are \(days) days between \(start) and \(end)")
| import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates {
public static void main(String[] args) {
LocalDate fromDate = LocalDate.parse("2019-01-01");
LocalDate toDate = LocalDate.parse("2019-10-19");
long diff = ChronoUnit.DAYS.between(fromDate, toDate);
System.out.printf("Number of days between %s and %s: %d\n", fromDate, toDate, diff);
}
}
|
Transform the following Swift implementation into Python, maintaining the same output and logic. | import Foundation
func daysFromTimeInterval(_ interval: Double) -> Int {
return Int(interval) / 86400
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
print("Enter date one (yyyy-MM-dd): ", terminator: "")
guard let date1Str = readLine(strippingNewline: true), let date1 = formatter.date(from: date1Str) else {
fatalError("Invalid date two")
}
print("Enter date two (yyyy-MM-dd): ", terminator: "")
guard let date2Str = readLine(strippingNewline: true), let date2 = formatter.date(from: date2Str) else {
fatalError("Invalid date two")
}
let (start, end) = date1 > date2 ? (date2, date1) : (date1, date2)
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
print("There are \(days) days between \(start) and \(end)")
|
import sys
def days( y,m,d ):
m = (m + 9) % 12
y = y - m/10
result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
return result
def diff(one,two):
[y1,m1,d1] = one.split('-')
[y2,m2,d2] = two.split('-')
year2 = days( int(y2),int(m2),int(d2))
year1 = days( int(y1), int(m1), int(d1) )
return year2 - year1
if __name__ == "__main__":
one = sys.argv[1]
two = sys.argv[2]
print diff(one,two)
|
Translate the given Swift code snippet into Python without altering its behavior. | import Foundation
func daysFromTimeInterval(_ interval: Double) -> Int {
return Int(interval) / 86400
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
print("Enter date one (yyyy-MM-dd): ", terminator: "")
guard let date1Str = readLine(strippingNewline: true), let date1 = formatter.date(from: date1Str) else {
fatalError("Invalid date two")
}
print("Enter date two (yyyy-MM-dd): ", terminator: "")
guard let date2Str = readLine(strippingNewline: true), let date2 = formatter.date(from: date2Str) else {
fatalError("Invalid date two")
}
let (start, end) = date1 > date2 ? (date2, date1) : (date1, date2)
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
print("There are \(days) days between \(start) and \(end)")
|
import sys
def days( y,m,d ):
m = (m + 9) % 12
y = y - m/10
result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
return result
def diff(one,two):
[y1,m1,d1] = one.split('-')
[y2,m2,d2] = two.split('-')
year2 = days( int(y2),int(m2),int(d2))
year1 = days( int(y1), int(m1), int(d1) )
return year2 - year1
if __name__ == "__main__":
one = sys.argv[1]
two = sys.argv[2]
print diff(one,two)
|
Rewrite the snippet below in VB so it works the same as the original Swift code. | import Foundation
func daysFromTimeInterval(_ interval: Double) -> Int {
return Int(interval) / 86400
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
print("Enter date one (yyyy-MM-dd): ", terminator: "")
guard let date1Str = readLine(strippingNewline: true), let date1 = formatter.date(from: date1Str) else {
fatalError("Invalid date two")
}
print("Enter date two (yyyy-MM-dd): ", terminator: "")
guard let date2Str = readLine(strippingNewline: true), let date2 = formatter.date(from: date2Str) else {
fatalError("Invalid date two")
}
let (start, end) = date1 > date2 ? (date2, date1) : (date1, date2)
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
print("There are \(days) days between \(start) and \(end)")
| Imports System.Globalization
Module Module1
Function DateDiff(d1 As String, d2 As String) As Integer
Dim a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Return (b - a).TotalDays
End Function
Sub Main()
Console.WriteLine(DateDiff("1970-01-01", "2019-10-18"))
End Sub
End Module
|
Rewrite the snippet below in VB so it works the same as the original Swift code. | import Foundation
func daysFromTimeInterval(_ interval: Double) -> Int {
return Int(interval) / 86400
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
print("Enter date one (yyyy-MM-dd): ", terminator: "")
guard let date1Str = readLine(strippingNewline: true), let date1 = formatter.date(from: date1Str) else {
fatalError("Invalid date two")
}
print("Enter date two (yyyy-MM-dd): ", terminator: "")
guard let date2Str = readLine(strippingNewline: true), let date2 = formatter.date(from: date2Str) else {
fatalError("Invalid date two")
}
let (start, end) = date1 > date2 ? (date2, date1) : (date1, date2)
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
print("There are \(days) days between \(start) and \(end)")
| Imports System.Globalization
Module Module1
Function DateDiff(d1 As String, d2 As String) As Integer
Dim a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Return (b - a).TotalDays
End Function
Sub Main()
Console.WriteLine(DateDiff("1970-01-01", "2019-10-18"))
End Sub
End Module
|
Rewrite this program in Go while keeping its functionality equivalent to the Swift version. | import Foundation
func daysFromTimeInterval(_ interval: Double) -> Int {
return Int(interval) / 86400
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
print("Enter date one (yyyy-MM-dd): ", terminator: "")
guard let date1Str = readLine(strippingNewline: true), let date1 = formatter.date(from: date1Str) else {
fatalError("Invalid date two")
}
print("Enter date two (yyyy-MM-dd): ", terminator: "")
guard let date2Str = readLine(strippingNewline: true), let date2 = formatter.date(from: date2Str) else {
fatalError("Invalid date two")
}
let (start, end) = date1 > date2 ? (date2, date1) : (date1, date2)
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
print("There are \(days) days between \(start) and \(end)")
| package main
import (
"fmt"
"log"
"time"
)
const layout = "2006-01-02"
func daysBetween(date1, date2 string) int {
t1, err := time.Parse(layout, date1)
check(err)
t2, err := time.Parse(layout, date2)
check(err)
days := int(t1.Sub(t2).Hours() / 24)
if days < 0 {
days = -days
}
return days
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
date1, date2 := "2019-01-01", "2019-09-30"
days := daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
date1, date2 = "2015-12-31", "2016-09-30"
days = daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
}
|
Transform the following Swift implementation into Go, maintaining the same output and logic. | import Foundation
func daysFromTimeInterval(_ interval: Double) -> Int {
return Int(interval) / 86400
}
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
print("Enter date one (yyyy-MM-dd): ", terminator: "")
guard let date1Str = readLine(strippingNewline: true), let date1 = formatter.date(from: date1Str) else {
fatalError("Invalid date two")
}
print("Enter date two (yyyy-MM-dd): ", terminator: "")
guard let date2Str = readLine(strippingNewline: true), let date2 = formatter.date(from: date2Str) else {
fatalError("Invalid date two")
}
let (start, end) = date1 > date2 ? (date2, date1) : (date1, date2)
let days = daysFromTimeInterval(DateInterval(start: start, end: end).duration)
print("There are \(days) days between \(start) and \(end)")
| package main
import (
"fmt"
"log"
"time"
)
const layout = "2006-01-02"
func daysBetween(date1, date2 string) int {
t1, err := time.Parse(layout, date1)
check(err)
t2, err := time.Parse(layout, date2)
check(err)
days := int(t1.Sub(t2).Hours() / 24)
if days < 0 {
days = -days
}
return days
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
date1, date2 := "2019-01-01", "2019-09-30"
days := daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
date1, date2 = "2015-12-31", "2016-09-30"
days = daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
}
|
Can you help me rewrite this code in Rust instead of C, keeping it the same logically? | #include<stdbool.h>
#include<string.h>
#include<stdio.h>
typedef struct{
int year, month, day;
}date;
date extractDate(char* str){
return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')};
}
bool isValidDate(char* str){
date newDate;
if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){
return false;
}
newDate = extractDate(str);
if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) ||
((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) ||
newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){
return false;
}
return true;
}
int diffDays(date date1,date date2){
int days1, days2;
date1.month = (date1.month + 9)%12;
date1.year = date1.year - date1.month/10;
date2.month = (date2.month + 9)%12;
date2.year = date2.year - date2.month/10;
days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 );
days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 );
return days2 - days1;
}
int main(int argc,char** argv)
{
if(argc!=3){
return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]);
}
if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){
return printf("Dates are invalid.\n");
}
printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2])));
return 0;
}
|
use chrono::NaiveDate;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
eprintln!("usage: {} start-date end-date", args[0]);
std::process::exit(1);
}
if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") {
if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") {
let d = end_date.signed_duration_since(start_date);
println!("{}", d.num_days());
} else {
eprintln!("Can't parse end date");
std::process::exit(1);
}
} else {
eprintln!("Can't parse start date");
std::process::exit(1);
}
}
|
Port the provided C code into Rust while preserving the original functionality. | #include<stdbool.h>
#include<string.h>
#include<stdio.h>
typedef struct{
int year, month, day;
}date;
date extractDate(char* str){
return (date){.year = 1000 * (str[0]-'0') + 100 * (str[1]-'0') + 10 * (str[2]-'0') + (str[3]-'0'), .month = 10*(str[5]-'0') + (str[6]-'0'), .day = 10*(str[8]-'0') + (str[9]-'0')};
}
bool isValidDate(char* str){
date newDate;
if(strlen(str)!=10 && str[4]!='-' && str[7]!='-'){
return false;
}
newDate = extractDate(str);
if(newDate.year<=0 || newDate.month<=0 || newDate.day<=0 || newDate.month>12 || (newDate.month==2 && newDate.day>29) ||
((newDate.month==1 || newDate.month==3 || newDate.month==5 || newDate.month==7 || newDate.month==8 || newDate.month==10 || newDate.month==12) && newDate.day>31) ||
newDate.day>30 || (newDate.year%4==0 && newDate.month==2 && newDate.month>28)){
return false;
}
return true;
}
int diffDays(date date1,date date2){
int days1, days2;
date1.month = (date1.month + 9)%12;
date1.year = date1.year - date1.month/10;
date2.month = (date2.month + 9)%12;
date2.year = date2.year - date2.month/10;
days1 = 365*date1.year + date1.year/4 - date1.year/100 + date1.year/400 + (date1.month*306 + 5)/10 + ( date1.day - 1 );
days2 = 365*date2.year + date2.year/4 - date2.year/100 + date2.year/400 + (date2.month*306 + 5)/10 + ( date2.day - 1 );
return days2 - days1;
}
int main(int argc,char** argv)
{
if(argc!=3){
return printf("Usage : %s <yyyy-mm-dd> <yyyy-mm-dd>",argv[0]);
}
if(isValidDate(argv[1])&&isValidDate(argv[2]) == false){
return printf("Dates are invalid.\n");
}
printf("Days Difference : %d\n", diffDays(extractDate(argv[1]),extractDate(argv[2])));
return 0;
}
|
use chrono::NaiveDate;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
eprintln!("usage: {} start-date end-date", args[0]);
std::process::exit(1);
}
if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") {
if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") {
let d = end_date.signed_duration_since(start_date);
println!("{}", d.num_days());
} else {
eprintln!("Can't parse end date");
std::process::exit(1);
}
} else {
eprintln!("Can't parse start date");
std::process::exit(1);
}
}
|
Translate the given C++ code snippet into Rust without altering its behavior. | #include <iomanip>
#include <iostream>
class Date {
private:
int year, month, day;
public:
Date(std::string str) {
if (isValidDate(str)) {
year = atoi(&str[0]);
month = atoi(&str[5]);
day = atoi(&str[8]);
} else {
throw std::exception("Invalid date");
}
}
int getYear() {
return year;
}
int getMonth() {
return month;
}
int getDay() {
return day;
}
static bool isValidDate(std::string str) {
if (str.length() != 10 || str[4] != '-' || str[7] != '-') {
return false;
}
if (!isdigit(str[0]) || !isdigit(str[1]) || !isdigit(str[2]) || !isdigit(str[3])) {
return false;
}
if (!isdigit(str[5]) || !isdigit(str[6])) {
return false;
}
if (!isdigit(str[8]) || !isdigit(str[9])) {
return false;
}
int year = atoi(&str[0]);
int month = atoi(&str[5]);
int day = atoi(&str[8]);
if (year <= 0 || month <= 0 || day <= 0) {
return false;
}
if (month > 12) {
return false;
}
switch (month) {
case 2:
if (day > 29) {
return false;
}
if (!isLeapYear(year) && day == 29) {
return false;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day > 31) {
return false;
}
break;
default:
if (day > 30) {
return false;
}
break;
}
return true;
}
static bool isLeapYear(int year) {
if (year > 1582) {
return ((year % 4 == 0) && (year % 100 > 0))
|| (year % 400 == 0);
}
if (year > 10) {
return year % 4 == 0;
}
return false;
}
friend std::ostream &operator<<(std::ostream &, Date &);
};
std::ostream &operator<<(std::ostream &os, Date &d) {
os << std::setfill('0') << std::setw(4) << d.year << '-';
os << std::setfill('0') << std::setw(2) << d.month << '-';
os << std::setfill('0') << std::setw(2) << d.day;
return os;
}
int diffDays(Date date1, Date date2) {
int d1m = (date1.getMonth() + 9) % 12;
int d1y = date1.getYear() - d1m / 10;
int d2m = (date2.getMonth() + 9) % 12;
int d2y = date2.getYear() - d2m / 10;
int days1 = 365 * d1y + d1y / 4 - d1y / 100 + d1y / 400 + (d1m * 306 + 5) / 10 + (date1.getDay() - 1);
int days2 = 365 * d2y + d2y / 4 - d2y / 100 + d2y / 400 + (d2m * 306 + 5) / 10 + (date2.getDay() - 1);
return days2 - days1;
}
int main() {
std::string ds1 = "2019-01-01";
std::string ds2 = "2019-12-02";
if (Date::isValidDate(ds1) && Date::isValidDate(ds2)) {
Date d1(ds1);
Date d2(ds2);
std::cout << "Days difference : " << diffDays(d1, d2);
} else {
std::cout << "Dates are invalid.\n";
}
return 0;
}
|
use chrono::NaiveDate;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
eprintln!("usage: {} start-date end-date", args[0]);
std::process::exit(1);
}
if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") {
if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") {
let d = end_date.signed_duration_since(start_date);
println!("{}", d.num_days());
} else {
eprintln!("Can't parse end date");
std::process::exit(1);
}
} else {
eprintln!("Can't parse start date");
std::process::exit(1);
}
}
|
Please provide an equivalent version of this C++ code in Rust. | #include <iomanip>
#include <iostream>
class Date {
private:
int year, month, day;
public:
Date(std::string str) {
if (isValidDate(str)) {
year = atoi(&str[0]);
month = atoi(&str[5]);
day = atoi(&str[8]);
} else {
throw std::exception("Invalid date");
}
}
int getYear() {
return year;
}
int getMonth() {
return month;
}
int getDay() {
return day;
}
static bool isValidDate(std::string str) {
if (str.length() != 10 || str[4] != '-' || str[7] != '-') {
return false;
}
if (!isdigit(str[0]) || !isdigit(str[1]) || !isdigit(str[2]) || !isdigit(str[3])) {
return false;
}
if (!isdigit(str[5]) || !isdigit(str[6])) {
return false;
}
if (!isdigit(str[8]) || !isdigit(str[9])) {
return false;
}
int year = atoi(&str[0]);
int month = atoi(&str[5]);
int day = atoi(&str[8]);
if (year <= 0 || month <= 0 || day <= 0) {
return false;
}
if (month > 12) {
return false;
}
switch (month) {
case 2:
if (day > 29) {
return false;
}
if (!isLeapYear(year) && day == 29) {
return false;
}
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (day > 31) {
return false;
}
break;
default:
if (day > 30) {
return false;
}
break;
}
return true;
}
static bool isLeapYear(int year) {
if (year > 1582) {
return ((year % 4 == 0) && (year % 100 > 0))
|| (year % 400 == 0);
}
if (year > 10) {
return year % 4 == 0;
}
return false;
}
friend std::ostream &operator<<(std::ostream &, Date &);
};
std::ostream &operator<<(std::ostream &os, Date &d) {
os << std::setfill('0') << std::setw(4) << d.year << '-';
os << std::setfill('0') << std::setw(2) << d.month << '-';
os << std::setfill('0') << std::setw(2) << d.day;
return os;
}
int diffDays(Date date1, Date date2) {
int d1m = (date1.getMonth() + 9) % 12;
int d1y = date1.getYear() - d1m / 10;
int d2m = (date2.getMonth() + 9) % 12;
int d2y = date2.getYear() - d2m / 10;
int days1 = 365 * d1y + d1y / 4 - d1y / 100 + d1y / 400 + (d1m * 306 + 5) / 10 + (date1.getDay() - 1);
int days2 = 365 * d2y + d2y / 4 - d2y / 100 + d2y / 400 + (d2m * 306 + 5) / 10 + (date2.getDay() - 1);
return days2 - days1;
}
int main() {
std::string ds1 = "2019-01-01";
std::string ds2 = "2019-12-02";
if (Date::isValidDate(ds1) && Date::isValidDate(ds2)) {
Date d1(ds1);
Date d2(ds2);
std::cout << "Days difference : " << diffDays(d1, d2);
} else {
std::cout << "Dates are invalid.\n";
}
return 0;
}
|
use chrono::NaiveDate;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
eprintln!("usage: {} start-date end-date", args[0]);
std::process::exit(1);
}
if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") {
if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") {
let d = end_date.signed_duration_since(start_date);
println!("{}", d.num_days());
} else {
eprintln!("Can't parse end date");
std::process::exit(1);
}
} else {
eprintln!("Can't parse start date");
std::process::exit(1);
}
}
|
Write a version of this C# function in Rust with identical behavior. | using System;
using System.Globalization;
public class Program
{
public static void Main() => WriteLine(DateDiff("1970-01-01", "2019-10-18"));
public static int DateDiff(string d1, string d2) {
var a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture);
return (int)(b - a).TotalDays;
}
}
|
use chrono::NaiveDate;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
eprintln!("usage: {} start-date end-date", args[0]);
std::process::exit(1);
}
if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") {
if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") {
let d = end_date.signed_duration_since(start_date);
println!("{}", d.num_days());
} else {
eprintln!("Can't parse end date");
std::process::exit(1);
}
} else {
eprintln!("Can't parse start date");
std::process::exit(1);
}
}
|
Convert this Go snippet to Rust and keep its semantics consistent. | package main
import (
"fmt"
"log"
"time"
)
const layout = "2006-01-02"
func daysBetween(date1, date2 string) int {
t1, err := time.Parse(layout, date1)
check(err)
t2, err := time.Parse(layout, date2)
check(err)
days := int(t1.Sub(t2).Hours() / 24)
if days < 0 {
days = -days
}
return days
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
date1, date2 := "2019-01-01", "2019-09-30"
days := daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
date1, date2 = "2015-12-31", "2016-09-30"
days = daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
}
|
use chrono::NaiveDate;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
eprintln!("usage: {} start-date end-date", args[0]);
std::process::exit(1);
}
if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") {
if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") {
let d = end_date.signed_duration_since(start_date);
println!("{}", d.num_days());
} else {
eprintln!("Can't parse end date");
std::process::exit(1);
}
} else {
eprintln!("Can't parse start date");
std::process::exit(1);
}
}
|
Generate a Rust translation of this Go snippet without changing its computational steps. | package main
import (
"fmt"
"log"
"time"
)
const layout = "2006-01-02"
func daysBetween(date1, date2 string) int {
t1, err := time.Parse(layout, date1)
check(err)
t2, err := time.Parse(layout, date2)
check(err)
days := int(t1.Sub(t2).Hours() / 24)
if days < 0 {
days = -days
}
return days
}
func check(err error) {
if err != nil {
log.Fatal(err)
}
}
func main() {
date1, date2 := "2019-01-01", "2019-09-30"
days := daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
date1, date2 = "2015-12-31", "2016-09-30"
days = daysBetween(date1, date2)
fmt.Printf("There are %d days between %s and %s\n", days, date1, date2)
}
|
use chrono::NaiveDate;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
eprintln!("usage: {} start-date end-date", args[0]);
std::process::exit(1);
}
if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") {
if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") {
let d = end_date.signed_duration_since(start_date);
println!("{}", d.num_days());
} else {
eprintln!("Can't parse end date");
std::process::exit(1);
}
} else {
eprintln!("Can't parse start date");
std::process::exit(1);
}
}
|
Change the programming language of this snippet from Rust to Python without modifying what it does. |
use chrono::NaiveDate;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
eprintln!("usage: {} start-date end-date", args[0]);
std::process::exit(1);
}
if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") {
if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") {
let d = end_date.signed_duration_since(start_date);
println!("{}", d.num_days());
} else {
eprintln!("Can't parse end date");
std::process::exit(1);
}
} else {
eprintln!("Can't parse start date");
std::process::exit(1);
}
}
|
import sys
def days( y,m,d ):
m = (m + 9) % 12
y = y - m/10
result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
return result
def diff(one,two):
[y1,m1,d1] = one.split('-')
[y2,m2,d2] = two.split('-')
year2 = days( int(y2),int(m2),int(d2))
year1 = days( int(y1), int(m1), int(d1) )
return year2 - year1
if __name__ == "__main__":
one = sys.argv[1]
two = sys.argv[2]
print diff(one,two)
|
Generate an equivalent VB version of this Rust code. |
use chrono::NaiveDate;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
eprintln!("usage: {} start-date end-date", args[0]);
std::process::exit(1);
}
if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") {
if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") {
let d = end_date.signed_duration_since(start_date);
println!("{}", d.num_days());
} else {
eprintln!("Can't parse end date");
std::process::exit(1);
}
} else {
eprintln!("Can't parse start date");
std::process::exit(1);
}
}
| Imports System.Globalization
Module Module1
Function DateDiff(d1 As String, d2 As String) As Integer
Dim a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Return (b - a).TotalDays
End Function
Sub Main()
Console.WriteLine(DateDiff("1970-01-01", "2019-10-18"))
End Sub
End Module
|
Generate a VB translation of this Rust snippet without changing its computational steps. |
use chrono::NaiveDate;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
eprintln!("usage: {} start-date end-date", args[0]);
std::process::exit(1);
}
if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") {
if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") {
let d = end_date.signed_duration_since(start_date);
println!("{}", d.num_days());
} else {
eprintln!("Can't parse end date");
std::process::exit(1);
}
} else {
eprintln!("Can't parse start date");
std::process::exit(1);
}
}
| Imports System.Globalization
Module Module1
Function DateDiff(d1 As String, d2 As String) As Integer
Dim a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture)
Return (b - a).TotalDays
End Function
Sub Main()
Console.WriteLine(DateDiff("1970-01-01", "2019-10-18"))
End Sub
End Module
|
Port the following code from C# to Rust with equivalent syntax and logic. | using System;
using System.Globalization;
public class Program
{
public static void Main() => WriteLine(DateDiff("1970-01-01", "2019-10-18"));
public static int DateDiff(string d1, string d2) {
var a = DateTime.ParseExact(d1, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var b = DateTime.ParseExact(d2, "yyyy-MM-dd", CultureInfo.InvariantCulture);
return (int)(b - a).TotalDays;
}
}
|
use chrono::NaiveDate;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
eprintln!("usage: {} start-date end-date", args[0]);
std::process::exit(1);
}
if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") {
if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") {
let d = end_date.signed_duration_since(start_date);
println!("{}", d.num_days());
} else {
eprintln!("Can't parse end date");
std::process::exit(1);
}
} else {
eprintln!("Can't parse start date");
std::process::exit(1);
}
}
|
Port the provided Java code into Rust while preserving the original functionality. | import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates {
public static void main(String[] args) {
LocalDate fromDate = LocalDate.parse("2019-01-01");
LocalDate toDate = LocalDate.parse("2019-10-19");
long diff = ChronoUnit.DAYS.between(fromDate, toDate);
System.out.printf("Number of days between %s and %s: %d\n", fromDate, toDate, diff);
}
}
|
use chrono::NaiveDate;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
eprintln!("usage: {} start-date end-date", args[0]);
std::process::exit(1);
}
if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") {
if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") {
let d = end_date.signed_duration_since(start_date);
println!("{}", d.num_days());
} else {
eprintln!("Can't parse end date");
std::process::exit(1);
}
} else {
eprintln!("Can't parse start date");
std::process::exit(1);
}
}
|
Keep all operations the same but rewrite the snippet in Rust. | import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class DaysBetweenDates {
public static void main(String[] args) {
LocalDate fromDate = LocalDate.parse("2019-01-01");
LocalDate toDate = LocalDate.parse("2019-10-19");
long diff = ChronoUnit.DAYS.between(fromDate, toDate);
System.out.printf("Number of days between %s and %s: %d\n", fromDate, toDate, diff);
}
}
|
use chrono::NaiveDate;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
eprintln!("usage: {} start-date end-date", args[0]);
std::process::exit(1);
}
if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") {
if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") {
let d = end_date.signed_duration_since(start_date);
println!("{}", d.num_days());
} else {
eprintln!("Can't parse end date");
std::process::exit(1);
}
} else {
eprintln!("Can't parse start date");
std::process::exit(1);
}
}
|
Change the programming language of this snippet from Rust to Python without modifying what it does. |
use chrono::NaiveDate;
fn main() {
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
eprintln!("usage: {} start-date end-date", args[0]);
std::process::exit(1);
}
if let Ok(start_date) = NaiveDate::parse_from_str(&args[1], "%F") {
if let Ok(end_date) = NaiveDate::parse_from_str(&args[2], "%F") {
let d = end_date.signed_duration_since(start_date);
println!("{}", d.num_days());
} else {
eprintln!("Can't parse end date");
std::process::exit(1);
}
} else {
eprintln!("Can't parse start date");
std::process::exit(1);
}
}
|
import sys
def days( y,m,d ):
m = (m + 9) % 12
y = y - m/10
result = 365*y + y/4 - y/100 + y/400 + (m*306 + 5)/10 + ( d - 1 )
return result
def diff(one,two):
[y1,m1,d1] = one.split('-')
[y2,m2,d2] = two.split('-')
year2 = days( int(y2),int(m2),int(d2))
year1 = days( int(y1), int(m1), int(d1) )
return year2 - year1
if __name__ == "__main__":
one = sys.argv[1]
two = sys.argv[2]
print diff(one,two)
|
Keep all operations the same but rewrite the snippet in C#. | with Ada.Text_IO, Ada.Strings.Fixed;
use Ada.Text_IO, Ada.Strings, Ada.Strings.Fixed;
function "+" (S : String) return String is
Item : constant Character := S (S'First);
begin
for Index in S'First + 1..S'Last loop
if Item /= S (Index) then
return Trim (Integer'Image (Index - S'First), Both) & Item & (+(S (Index..S'Last)));
end if;
end loop;
return Trim (Integer'Image (S'Length), Both) & Item;
end "+";
| using System;
using System.Text;
using System.Linq;
class Program
{
static string lookandsay(string number)
{
StringBuilder result = new StringBuilder();
char repeat = number[0];
number = number.Substring(1, number.Length-1)+" ";
int times = 1;
foreach (char actual in number)
{
if (actual != repeat)
{
result.Append(Convert.ToString(times)+repeat);
times = 1;
repeat = actual;
}
else
{
times += 1;
}
}
return result.ToString();
}
static void Main(string[] args)
{
string num = "1";
foreach (int i in Enumerable.Range(1, 10)) {
Console.WriteLine(num);
num = lookandsay(num);
}
}
}
|
Convert this Ada block to C, preserving its control flow and logic. | with Ada.Text_IO, Ada.Strings.Fixed;
use Ada.Text_IO, Ada.Strings, Ada.Strings.Fixed;
function "+" (S : String) return String is
Item : constant Character := S (S'First);
begin
for Index in S'First + 1..S'Last loop
if Item /= S (Index) then
return Trim (Integer'Image (Index - S'First), Both) & Item & (+(S (Index..S'Last)));
end if;
end loop;
return Trim (Integer'Image (S'Length), Both) & Item;
end "+";
| #include <stdio.h>
#include <stdlib.h>
int main()
{
char *a = malloc(2), *b = 0, *x, c;
int cnt, len = 1;
for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {
puts(x = a);
for (len = 0, cnt = 1; (c = *a); ) {
if (c == *++a)
cnt++;
else if (c) {
len += sprintf(b + len, "%d%c", cnt, c);
cnt = 1;
}
}
}
return 0;
}
|
Produce a language-to-language conversion: from Ada to C++, same semantics. | with Ada.Text_IO, Ada.Strings.Fixed;
use Ada.Text_IO, Ada.Strings, Ada.Strings.Fixed;
function "+" (S : String) return String is
Item : constant Character := S (S'First);
begin
for Index in S'First + 1..S'Last loop
if Item /= S (Index) then
return Trim (Integer'Image (Index - S'First), Both) & Item & (+(S (Index..S'Last)));
end if;
end loop;
return Trim (Integer'Image (S'Length), Both) & Item;
end "+";
| #include <iostream>
#include <sstream>
#include <string>
std::string lookandsay(const std::string& s)
{
std::ostringstream r;
for (std::size_t i = 0; i != s.length();) {
auto new_i = s.find_first_not_of(s[i], i + 1);
if (new_i == std::string::npos)
new_i = s.length();
r << new_i - i << s[i];
i = new_i;
}
return r.str();
}
int main()
{
std::string laf = "1";
std::cout << laf << '\n';
for (int i = 0; i < 10; ++i) {
laf = lookandsay(laf);
std::cout << laf << '\n';
}
}
|
Please provide an equivalent version of this Ada code in Go. | with Ada.Text_IO, Ada.Strings.Fixed;
use Ada.Text_IO, Ada.Strings, Ada.Strings.Fixed;
function "+" (S : String) return String is
Item : constant Character := S (S'First);
begin
for Index in S'First + 1..S'Last loop
if Item /= S (Index) then
return Trim (Integer'Image (Index - S'First), Both) & Item & (+(S (Index..S'Last)));
end if;
end loop;
return Trim (Integer'Image (S'Length), Both) & Item;
end "+";
| package main
import (
"fmt"
"strconv"
)
func lss(s string) (r string) {
c := s[0]
nc := 1
for i := 1; i < len(s); i++ {
d := s[i]
if d == c {
nc++
continue
}
r += strconv.Itoa(nc) + string(c)
c = d
nc = 1
}
return r + strconv.Itoa(nc) + string(c)
}
func main() {
s := "1"
fmt.Println(s)
for i := 0; i < 8; i++ {
s = lss(s)
fmt.Println(s)
}
}
|
Rewrite the snippet below in Java so it works the same as the original Ada code. | with Ada.Text_IO, Ada.Strings.Fixed;
use Ada.Text_IO, Ada.Strings, Ada.Strings.Fixed;
function "+" (S : String) return String is
Item : constant Character := S (S'First);
begin
for Index in S'First + 1..S'Last loop
if Item /= S (Index) then
return Trim (Integer'Image (Index - S'First), Both) & Item & (+(S (Index..S'Last)));
end if;
end loop;
return Trim (Integer'Image (S'Length), Both) & Item;
end "+";
| public static String lookandsay(String number){
StringBuilder result= new StringBuilder();
char repeat= number.charAt(0);
number= number.substring(1) + " ";
int times= 1;
for(char actual: number.toCharArray()){
if(actual != repeat){
result.append(times + "" + repeat);
times= 1;
repeat= actual;
}else{
times+= 1;
}
}
return result.toString();
}
|
Rewrite this program in Python while keeping its functionality equivalent to the Ada version. | with Ada.Text_IO, Ada.Strings.Fixed;
use Ada.Text_IO, Ada.Strings, Ada.Strings.Fixed;
function "+" (S : String) return String is
Item : constant Character := S (S'First);
begin
for Index in S'First + 1..S'Last loop
if Item /= S (Index) then
return Trim (Integer'Image (Index - S'First), Both) & Item & (+(S (Index..S'Last)));
end if;
end loop;
return Trim (Integer'Image (S'Length), Both) & Item;
end "+";
| def lookandsay(number):
result = ""
repeat = number[0]
number = number[1:]+" "
times = 1
for actual in number:
if actual != repeat:
result += str(times)+repeat
times = 1
repeat = actual
else:
times += 1
return result
num = "1"
for i in range(10):
print num
num = lookandsay(num)
|
Rewrite the snippet below in VB so it works the same as the original Ada code. | with Ada.Text_IO, Ada.Strings.Fixed;
use Ada.Text_IO, Ada.Strings, Ada.Strings.Fixed;
function "+" (S : String) return String is
Item : constant Character := S (S'First);
begin
for Index in S'First + 1..S'Last loop
if Item /= S (Index) then
return Trim (Integer'Image (Index - S'First), Both) & Item & (+(S (Index..S'Last)));
end if;
end loop;
return Trim (Integer'Image (S'Length), Both) & Item;
end "+";
| function looksay( n )
dim i
dim accum
dim res
dim c
res = vbnullstring
do
if n = vbnullstring then exit do
accum = 0
c = left( n,1 )
do while left( n, 1 ) = c
accum = accum + 1
n = mid(n,2)
loop
if accum > 0 then
res = res & accum & c
end if
loop
looksay = res
end function
|
Change the programming language of this snippet from Arturo to C without modifying what it does. | lookAndSay: function [n][
if n=0 -> return "1"
previous: lookAndSay n-1
result: new ""
currentCounter: 0
currentCh: first previous
loop previous 'ch [
if? currentCh <> ch [
if not? zero? currentCounter ->
'result ++ (to :string currentCounter) ++ currentCh
currentCounter: 1
currentCh: ch
]
else ->
currentCounter: currentCounter + 1
]
'result ++ (to :string currentCounter) ++ currentCh
return result
]
loop 0..10 'x [
print [x "->" lookAndSay x]
]
| #include <stdio.h>
#include <stdlib.h>
int main()
{
char *a = malloc(2), *b = 0, *x, c;
int cnt, len = 1;
for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {
puts(x = a);
for (len = 0, cnt = 1; (c = *a); ) {
if (c == *++a)
cnt++;
else if (c) {
len += sprintf(b + len, "%d%c", cnt, c);
cnt = 1;
}
}
}
return 0;
}
|
Port the provided Arturo code into C# while preserving the original functionality. | lookAndSay: function [n][
if n=0 -> return "1"
previous: lookAndSay n-1
result: new ""
currentCounter: 0
currentCh: first previous
loop previous 'ch [
if? currentCh <> ch [
if not? zero? currentCounter ->
'result ++ (to :string currentCounter) ++ currentCh
currentCounter: 1
currentCh: ch
]
else ->
currentCounter: currentCounter + 1
]
'result ++ (to :string currentCounter) ++ currentCh
return result
]
loop 0..10 'x [
print [x "->" lookAndSay x]
]
| using System;
using System.Text;
using System.Linq;
class Program
{
static string lookandsay(string number)
{
StringBuilder result = new StringBuilder();
char repeat = number[0];
number = number.Substring(1, number.Length-1)+" ";
int times = 1;
foreach (char actual in number)
{
if (actual != repeat)
{
result.Append(Convert.ToString(times)+repeat);
times = 1;
repeat = actual;
}
else
{
times += 1;
}
}
return result.ToString();
}
static void Main(string[] args)
{
string num = "1";
foreach (int i in Enumerable.Range(1, 10)) {
Console.WriteLine(num);
num = lookandsay(num);
}
}
}
|
Preserve the algorithm and functionality while converting the code from Arturo to C++. | lookAndSay: function [n][
if n=0 -> return "1"
previous: lookAndSay n-1
result: new ""
currentCounter: 0
currentCh: first previous
loop previous 'ch [
if? currentCh <> ch [
if not? zero? currentCounter ->
'result ++ (to :string currentCounter) ++ currentCh
currentCounter: 1
currentCh: ch
]
else ->
currentCounter: currentCounter + 1
]
'result ++ (to :string currentCounter) ++ currentCh
return result
]
loop 0..10 'x [
print [x "->" lookAndSay x]
]
| #include <iostream>
#include <sstream>
#include <string>
std::string lookandsay(const std::string& s)
{
std::ostringstream r;
for (std::size_t i = 0; i != s.length();) {
auto new_i = s.find_first_not_of(s[i], i + 1);
if (new_i == std::string::npos)
new_i = s.length();
r << new_i - i << s[i];
i = new_i;
}
return r.str();
}
int main()
{
std::string laf = "1";
std::cout << laf << '\n';
for (int i = 0; i < 10; ++i) {
laf = lookandsay(laf);
std::cout << laf << '\n';
}
}
|
Translate the given Arturo code snippet into Java without altering its behavior. | lookAndSay: function [n][
if n=0 -> return "1"
previous: lookAndSay n-1
result: new ""
currentCounter: 0
currentCh: first previous
loop previous 'ch [
if? currentCh <> ch [
if not? zero? currentCounter ->
'result ++ (to :string currentCounter) ++ currentCh
currentCounter: 1
currentCh: ch
]
else ->
currentCounter: currentCounter + 1
]
'result ++ (to :string currentCounter) ++ currentCh
return result
]
loop 0..10 'x [
print [x "->" lookAndSay x]
]
| public static String lookandsay(String number){
StringBuilder result= new StringBuilder();
char repeat= number.charAt(0);
number= number.substring(1) + " ";
int times= 1;
for(char actual: number.toCharArray()){
if(actual != repeat){
result.append(times + "" + repeat);
times= 1;
repeat= actual;
}else{
times+= 1;
}
}
return result.toString();
}
|
Produce a language-to-language conversion: from Arturo to Python, same semantics. | lookAndSay: function [n][
if n=0 -> return "1"
previous: lookAndSay n-1
result: new ""
currentCounter: 0
currentCh: first previous
loop previous 'ch [
if? currentCh <> ch [
if not? zero? currentCounter ->
'result ++ (to :string currentCounter) ++ currentCh
currentCounter: 1
currentCh: ch
]
else ->
currentCounter: currentCounter + 1
]
'result ++ (to :string currentCounter) ++ currentCh
return result
]
loop 0..10 'x [
print [x "->" lookAndSay x]
]
| def lookandsay(number):
result = ""
repeat = number[0]
number = number[1:]+" "
times = 1
for actual in number:
if actual != repeat:
result += str(times)+repeat
times = 1
repeat = actual
else:
times += 1
return result
num = "1"
for i in range(10):
print num
num = lookandsay(num)
|
Convert this Arturo block to VB, preserving its control flow and logic. | lookAndSay: function [n][
if n=0 -> return "1"
previous: lookAndSay n-1
result: new ""
currentCounter: 0
currentCh: first previous
loop previous 'ch [
if? currentCh <> ch [
if not? zero? currentCounter ->
'result ++ (to :string currentCounter) ++ currentCh
currentCounter: 1
currentCh: ch
]
else ->
currentCounter: currentCounter + 1
]
'result ++ (to :string currentCounter) ++ currentCh
return result
]
loop 0..10 'x [
print [x "->" lookAndSay x]
]
| function looksay( n )
dim i
dim accum
dim res
dim c
res = vbnullstring
do
if n = vbnullstring then exit do
accum = 0
c = left( n,1 )
do while left( n, 1 ) = c
accum = accum + 1
n = mid(n,2)
loop
if accum > 0 then
res = res & accum & c
end if
loop
looksay = res
end function
|
Change the following Arturo code into Go without altering its purpose. | lookAndSay: function [n][
if n=0 -> return "1"
previous: lookAndSay n-1
result: new ""
currentCounter: 0
currentCh: first previous
loop previous 'ch [
if? currentCh <> ch [
if not? zero? currentCounter ->
'result ++ (to :string currentCounter) ++ currentCh
currentCounter: 1
currentCh: ch
]
else ->
currentCounter: currentCounter + 1
]
'result ++ (to :string currentCounter) ++ currentCh
return result
]
loop 0..10 'x [
print [x "->" lookAndSay x]
]
| package main
import (
"fmt"
"strconv"
)
func lss(s string) (r string) {
c := s[0]
nc := 1
for i := 1; i < len(s); i++ {
d := s[i]
if d == c {
nc++
continue
}
r += strconv.Itoa(nc) + string(c)
c = d
nc = 1
}
return r + strconv.Itoa(nc) + string(c)
}
func main() {
s := "1"
fmt.Println(s)
for i := 0; i < 8; i++ {
s = lss(s)
fmt.Println(s)
}
}
|
Change the programming language of this snippet from AutoHotKey to C without modifying what it does. | AutoExecute:
Gui, -MinimizeBox
Gui, Add, Edit, w500 r20 vInput, 1
Gui, Add, Button, x155 w100 Default, &Calculate
Gui, Add, Button, xp+110 yp wp, E&xit
Gui, Show,, Look-and-Say sequence
Return
ButtonCalculate:
Gui, Submit, NoHide
GuiControl,, Input, % LookAndSay(Input)
Return
GuiClose:
ButtonExit:
ExitApp
Return
LookAndSay(Input) {
Loop, Parse, Input
If (A_LoopField = d)
c += 1
Else {
r .= c d
c := 1
d := A_LoopField
}
Return, r c d
}
| #include <stdio.h>
#include <stdlib.h>
int main()
{
char *a = malloc(2), *b = 0, *x, c;
int cnt, len = 1;
for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {
puts(x = a);
for (len = 0, cnt = 1; (c = *a); ) {
if (c == *++a)
cnt++;
else if (c) {
len += sprintf(b + len, "%d%c", cnt, c);
cnt = 1;
}
}
}
return 0;
}
|
Convert this AutoHotKey snippet to C# and keep its semantics consistent. | AutoExecute:
Gui, -MinimizeBox
Gui, Add, Edit, w500 r20 vInput, 1
Gui, Add, Button, x155 w100 Default, &Calculate
Gui, Add, Button, xp+110 yp wp, E&xit
Gui, Show,, Look-and-Say sequence
Return
ButtonCalculate:
Gui, Submit, NoHide
GuiControl,, Input, % LookAndSay(Input)
Return
GuiClose:
ButtonExit:
ExitApp
Return
LookAndSay(Input) {
Loop, Parse, Input
If (A_LoopField = d)
c += 1
Else {
r .= c d
c := 1
d := A_LoopField
}
Return, r c d
}
| using System;
using System.Text;
using System.Linq;
class Program
{
static string lookandsay(string number)
{
StringBuilder result = new StringBuilder();
char repeat = number[0];
number = number.Substring(1, number.Length-1)+" ";
int times = 1;
foreach (char actual in number)
{
if (actual != repeat)
{
result.Append(Convert.ToString(times)+repeat);
times = 1;
repeat = actual;
}
else
{
times += 1;
}
}
return result.ToString();
}
static void Main(string[] args)
{
string num = "1";
foreach (int i in Enumerable.Range(1, 10)) {
Console.WriteLine(num);
num = lookandsay(num);
}
}
}
|
Write the same algorithm in C++ as shown in this AutoHotKey implementation. | AutoExecute:
Gui, -MinimizeBox
Gui, Add, Edit, w500 r20 vInput, 1
Gui, Add, Button, x155 w100 Default, &Calculate
Gui, Add, Button, xp+110 yp wp, E&xit
Gui, Show,, Look-and-Say sequence
Return
ButtonCalculate:
Gui, Submit, NoHide
GuiControl,, Input, % LookAndSay(Input)
Return
GuiClose:
ButtonExit:
ExitApp
Return
LookAndSay(Input) {
Loop, Parse, Input
If (A_LoopField = d)
c += 1
Else {
r .= c d
c := 1
d := A_LoopField
}
Return, r c d
}
| #include <iostream>
#include <sstream>
#include <string>
std::string lookandsay(const std::string& s)
{
std::ostringstream r;
for (std::size_t i = 0; i != s.length();) {
auto new_i = s.find_first_not_of(s[i], i + 1);
if (new_i == std::string::npos)
new_i = s.length();
r << new_i - i << s[i];
i = new_i;
}
return r.str();
}
int main()
{
std::string laf = "1";
std::cout << laf << '\n';
for (int i = 0; i < 10; ++i) {
laf = lookandsay(laf);
std::cout << laf << '\n';
}
}
|
Convert the following code from AutoHotKey to Java, ensuring the logic remains intact. | AutoExecute:
Gui, -MinimizeBox
Gui, Add, Edit, w500 r20 vInput, 1
Gui, Add, Button, x155 w100 Default, &Calculate
Gui, Add, Button, xp+110 yp wp, E&xit
Gui, Show,, Look-and-Say sequence
Return
ButtonCalculate:
Gui, Submit, NoHide
GuiControl,, Input, % LookAndSay(Input)
Return
GuiClose:
ButtonExit:
ExitApp
Return
LookAndSay(Input) {
Loop, Parse, Input
If (A_LoopField = d)
c += 1
Else {
r .= c d
c := 1
d := A_LoopField
}
Return, r c d
}
| public static String lookandsay(String number){
StringBuilder result= new StringBuilder();
char repeat= number.charAt(0);
number= number.substring(1) + " ";
int times= 1;
for(char actual: number.toCharArray()){
if(actual != repeat){
result.append(times + "" + repeat);
times= 1;
repeat= actual;
}else{
times+= 1;
}
}
return result.toString();
}
|
Translate this program into Python but keep the logic exactly as in AutoHotKey. | AutoExecute:
Gui, -MinimizeBox
Gui, Add, Edit, w500 r20 vInput, 1
Gui, Add, Button, x155 w100 Default, &Calculate
Gui, Add, Button, xp+110 yp wp, E&xit
Gui, Show,, Look-and-Say sequence
Return
ButtonCalculate:
Gui, Submit, NoHide
GuiControl,, Input, % LookAndSay(Input)
Return
GuiClose:
ButtonExit:
ExitApp
Return
LookAndSay(Input) {
Loop, Parse, Input
If (A_LoopField = d)
c += 1
Else {
r .= c d
c := 1
d := A_LoopField
}
Return, r c d
}
| def lookandsay(number):
result = ""
repeat = number[0]
number = number[1:]+" "
times = 1
for actual in number:
if actual != repeat:
result += str(times)+repeat
times = 1
repeat = actual
else:
times += 1
return result
num = "1"
for i in range(10):
print num
num = lookandsay(num)
|
Port the following code from AutoHotKey to VB with equivalent syntax and logic. | AutoExecute:
Gui, -MinimizeBox
Gui, Add, Edit, w500 r20 vInput, 1
Gui, Add, Button, x155 w100 Default, &Calculate
Gui, Add, Button, xp+110 yp wp, E&xit
Gui, Show,, Look-and-Say sequence
Return
ButtonCalculate:
Gui, Submit, NoHide
GuiControl,, Input, % LookAndSay(Input)
Return
GuiClose:
ButtonExit:
ExitApp
Return
LookAndSay(Input) {
Loop, Parse, Input
If (A_LoopField = d)
c += 1
Else {
r .= c d
c := 1
d := A_LoopField
}
Return, r c d
}
| function looksay( n )
dim i
dim accum
dim res
dim c
res = vbnullstring
do
if n = vbnullstring then exit do
accum = 0
c = left( n,1 )
do while left( n, 1 ) = c
accum = accum + 1
n = mid(n,2)
loop
if accum > 0 then
res = res & accum & c
end if
loop
looksay = res
end function
|
Transform the following AutoHotKey implementation into Go, maintaining the same output and logic. | AutoExecute:
Gui, -MinimizeBox
Gui, Add, Edit, w500 r20 vInput, 1
Gui, Add, Button, x155 w100 Default, &Calculate
Gui, Add, Button, xp+110 yp wp, E&xit
Gui, Show,, Look-and-Say sequence
Return
ButtonCalculate:
Gui, Submit, NoHide
GuiControl,, Input, % LookAndSay(Input)
Return
GuiClose:
ButtonExit:
ExitApp
Return
LookAndSay(Input) {
Loop, Parse, Input
If (A_LoopField = d)
c += 1
Else {
r .= c d
c := 1
d := A_LoopField
}
Return, r c d
}
| package main
import (
"fmt"
"strconv"
)
func lss(s string) (r string) {
c := s[0]
nc := 1
for i := 1; i < len(s); i++ {
d := s[i]
if d == c {
nc++
continue
}
r += strconv.Itoa(nc) + string(c)
c = d
nc = 1
}
return r + strconv.Itoa(nc) + string(c)
}
func main() {
s := "1"
fmt.Println(s)
for i := 0; i < 8; i++ {
s = lss(s)
fmt.Println(s)
}
}
|
Change the programming language of this snippet from AWK to C without modifying what it does. | function lookandsay(a)
{
s = ""
c = 1
p = substr(a, 1, 1)
for(i=2; i <= length(a); i++) {
if ( p == substr(a, i, 1) ) {
c++
} else {
s = s sprintf("%d%s", c, p)
p = substr(a, i, 1)
c = 1
}
}
s = s sprintf("%d%s", c, p)
return s
}
BEGIN {
b = "1"
print b
for(k=1; k <= 10; k++) {
b = lookandsay(b)
print b
}
}
| #include <stdio.h>
#include <stdlib.h>
int main()
{
char *a = malloc(2), *b = 0, *x, c;
int cnt, len = 1;
for (sprintf(a, "1"); (b = realloc(b, len * 2 + 1)); a = b, b = x) {
puts(x = a);
for (len = 0, cnt = 1; (c = *a); ) {
if (c == *++a)
cnt++;
else if (c) {
len += sprintf(b + len, "%d%c", cnt, c);
cnt = 1;
}
}
}
return 0;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the AWK version. | function lookandsay(a)
{
s = ""
c = 1
p = substr(a, 1, 1)
for(i=2; i <= length(a); i++) {
if ( p == substr(a, i, 1) ) {
c++
} else {
s = s sprintf("%d%s", c, p)
p = substr(a, i, 1)
c = 1
}
}
s = s sprintf("%d%s", c, p)
return s
}
BEGIN {
b = "1"
print b
for(k=1; k <= 10; k++) {
b = lookandsay(b)
print b
}
}
| using System;
using System.Text;
using System.Linq;
class Program
{
static string lookandsay(string number)
{
StringBuilder result = new StringBuilder();
char repeat = number[0];
number = number.Substring(1, number.Length-1)+" ";
int times = 1;
foreach (char actual in number)
{
if (actual != repeat)
{
result.Append(Convert.ToString(times)+repeat);
times = 1;
repeat = actual;
}
else
{
times += 1;
}
}
return result.ToString();
}
static void Main(string[] args)
{
string num = "1";
foreach (int i in Enumerable.Range(1, 10)) {
Console.WriteLine(num);
num = lookandsay(num);
}
}
}
|
Write the same code in C++ as shown below in AWK. | function lookandsay(a)
{
s = ""
c = 1
p = substr(a, 1, 1)
for(i=2; i <= length(a); i++) {
if ( p == substr(a, i, 1) ) {
c++
} else {
s = s sprintf("%d%s", c, p)
p = substr(a, i, 1)
c = 1
}
}
s = s sprintf("%d%s", c, p)
return s
}
BEGIN {
b = "1"
print b
for(k=1; k <= 10; k++) {
b = lookandsay(b)
print b
}
}
| #include <iostream>
#include <sstream>
#include <string>
std::string lookandsay(const std::string& s)
{
std::ostringstream r;
for (std::size_t i = 0; i != s.length();) {
auto new_i = s.find_first_not_of(s[i], i + 1);
if (new_i == std::string::npos)
new_i = s.length();
r << new_i - i << s[i];
i = new_i;
}
return r.str();
}
int main()
{
std::string laf = "1";
std::cout << laf << '\n';
for (int i = 0; i < 10; ++i) {
laf = lookandsay(laf);
std::cout << laf << '\n';
}
}
|
Write a version of this AWK function in Java with identical behavior. | function lookandsay(a)
{
s = ""
c = 1
p = substr(a, 1, 1)
for(i=2; i <= length(a); i++) {
if ( p == substr(a, i, 1) ) {
c++
} else {
s = s sprintf("%d%s", c, p)
p = substr(a, i, 1)
c = 1
}
}
s = s sprintf("%d%s", c, p)
return s
}
BEGIN {
b = "1"
print b
for(k=1; k <= 10; k++) {
b = lookandsay(b)
print b
}
}
| public static String lookandsay(String number){
StringBuilder result= new StringBuilder();
char repeat= number.charAt(0);
number= number.substring(1) + " ";
int times= 1;
for(char actual: number.toCharArray()){
if(actual != repeat){
result.append(times + "" + repeat);
times= 1;
repeat= actual;
}else{
times+= 1;
}
}
return result.toString();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.