[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y ] [Home]
4chanarchives logo
QUICK WRITE A PROGRAM IN YOUR FAVORITE LANGUAGE THAT CALCULATES
Images are sometimes not shown due to bandwidth/network limitations. Refreshing the page usually helps.

You are currently reading a thread in /g/ - Technology

Thread replies: 114
Thread images: 10
File: killer bird.jpg (29 KB, 412x430) Image search: [Google]
killer bird.jpg
29 KB, 412x430
QUICK

WRITE A PROGRAM IN YOUR FAVORITE LANGUAGE THAT CALCULATES THE DIFFERENCE IN DAYS BETWEEN TWO TIMESTAMPS

OR THIS BIRD IS GONNA STAB YOU
>>
#include <stdio.h>
#include <stdlib.h>

typedef struct {
int year; /* 0 to 9999 */
int month; /* 1 to 12 */
int day; /* 1 to 31 */
} date;

int leapyear(int year) {
if(year % 400 == 0) {
return 1;
}
if(year % 100 == 0) {
return 0;
}
if(year % 4 == 0) {
return 1;
}
return 0;
}

int dpm(int year, int month) {
switch(month) {
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
return 28 + leapyear(year);
default:
return 31;
}
}

int passed(date* d) {
int days = d->day - 1;
int month;
for(month = 1; month < d->month; month++) {
days += dpm(d->year, month);
}
return days;
}

int timespan(date* from, date* to) {
int days = passed(to) - passed(from);
int year;
for(year = from->year; year < to->year; year++) {
days += 365 + leapyear(year);
}
return days;
}

int main(void) {
date a = {1970, 1, 1};
date b = {2016, 7, 13};
int days = timespan(&a, &b);
printf("%d\n", days);
return EXIT_SUCCESS;
}


inb4 homework
>>
>>55562006
wow how did you do that in 53 seconds
>>
File: 1468326741525.jpg (170 KB, 528x960) Image search: [Google]
1468326741525.jpg
170 KB, 528x960
>>55562043
I'm the OP you fucking moron. Now get to work or the bird will cut you a new asshole.
>>
>>55562043
This thread has been posted every day for a while now..
>>
>>55561997
return t2 - t1; // return Unix timestamp difference
>>
>>55562060
LOL
>>
>>55561997
10 PRINT "404"
20 GOTO 10
>>
>>55562060
that bird looks like he means it...
damn...
>>
>>55562060
wow i just

wow
>>
def difference(a, b):
return (datetime.fromtimestamp(b) - datetime.fromtimestamp(a)).days
>>
>>55562091
you just wow, learning some basic grammar you spastic
>>
public class DayDiff {
public static void main(String[] args){
DateTime dayOne = DateTime.Now;
DateTime dayTwo = new DateTime(2016, 2, 16);
var diff = dayOne - dayTwo;
Console.WriteLine(diff);
}
}
>>
import "time"

func dayDiff(a, b time.Time) float64 {
return float64(b.Sub(a)) / float64(24 * time.Hour)
}
>>
>>55562063
well it's a different exercise each time so it's alright
>>
>>55562125
oops, better version

import "time"

func dayDiff(a, b time.Time) float64 {
return b.Sub(a).Hours() / 24
}
>>
>>55562071
Wrong. Enjoy your stab.
>>
=A2 - A1


make sure to format the cell as a number
>>
File: 1468358190287.gif (1 MB, 500x276) Image search: [Google]
1468358190287.gif
1 MB, 500x276
>>
Bring back containment board /prog/

programming on /g/ is dropouts who think they're better than "consumer threads" who are just as unemployable as they make the "kids" out to be

this isn't a challenge it just ends up in autism of dropouts pointing out the most autistic irrelevant shit like having an empty line with a { or not or using // over */ literally nobody besides dropout first years even THINK about this shit

you guys are like that little group of smelly hippies outside every 101 class, signed up then skipped the whole class just to jack each other off about how their obscure hipster 70s ironic stancefag-tier butt diddling lang is superior because it's shitty and unusable

Bring back containment board /prog/
>>
static int MyLifeIsShitKillMeAnyway(DateTime a, DateTime b)
{
return (b - a).Days();
}
>>
>>55562302
That's not a language, dumb wageslave
>>
>>55562006
what fucking language is that?
>>
>>55562623
fuck off retard
>>
>>55561997
shit = fuck1-fuck2
asspiss = shit % 86400
print asspiss
>>
>>55562705
wait it should be / not % i'm dum
>>
>>55562683
Lisp
>>
>>55562732
is it better than java?
>>
>>55562751
nigga are you bein serious?
>>
>>55562763
sorry we don't all have the time to pick up random languages just because we feel like it
>>
function days_between(date1, date2) {

// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24

// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()

// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)

// Convert back to days and return
return Math.round(difference_ms/ONE_DAY)

}
>>
>>55561997
#!/usr/bin/env python
import argparse
import sys
from datetime import datetime

parser = argparse.ArgumentParser(description=
'Calculates difference in days between two dates\n'
'Default date format: DD.MM.YYYY')
parser.add_argument('a', help='Date a')
parser.add_argument('b', help='Date b')
parser.add_argument('--murrica', help='Switches to the murrican date format (MM/DD/YYYY)', action='store_true')
parser.add_argument('--timestamp', help='Dates are provided as a timestamp', action='store_true')
args = parser.parse_args()

datefmt = '%d.%m.%Y'
if args.murrica:
datefmt = '%m/%d/%Y'

try:
if args.timestamp:
date_a = datetime.fromtimestamp(float(args.a))
date_b = datetime.fromtimestamp(float(args.b))
else:
date_a = datetime.strptime(args.a, datefmt)
date_b = datetime.strptime(args.b, datefmt)

except:
print 'Invalid arguments you dipshit\n'
parser.print_help()
sys.exit(1)

delta = date_b - date_a
if abs(delta.days) == 1:
print 'The time difference is %d day' % delta.days
else:
print 'The time difference is %d days' % delta.days

>>
>>55562784
C and Lisp aren't "random languages" you dolt.
>>
>>55562824
well, Lisp is.
>>
itt: we write stuxnet one line at a time
>>
>>55562843
lisp's influence is second only to C
>>
>>55562895
lol whatever grandpa
>>
>>55562006
Nice!
>>
>>55562919
you can get pretty far as a stupid programmer
>>
>>55563027
yeah

in 1960 maybe
>>
>>55562787
fixing your last print to python3 too:

print "The time difference is {} day{}".format(delta.days, "" if abs(delta.day) == 1 else "s")
>>
>>55563057
sorry, python2 only, not using print()
>>
>>55563050
webdev is pretty big
>>
>>55563090
yep and everybody is using lisp on the net cool
>>
>>55561997
<?php
function difference_in_days($timestamp1, $timestamp2) {
return ((int)($timestamp2 - $timestamp1))/86400;
}
>>
File: 1452391898237.jpg (124 KB, 600x801) Image search: [Google]
1452391898237.jpg
124 KB, 600x801
$.getScript("timestamps.js");
calculateDifference(a, b);


get on my level
>>
>>55563112
i'm implying web developers are dumb, stupid
>>
Everyone in this thread relying on unix epoch time stamps is getting stabbed.
>>
>>55563160
oh okay

nice to see lisp is as relevant as ever
>>
>>55563236
Let's see your LISP solution then, smartass.
>>
>>55563471
Like I said, I dont waste my time
>>
BIRDMIN NO
>>
Trips kill bird permanently. Check em.
>>
>>55563169
Leap seconds don't exist in epoch time. A day will always be 86400 seconds long. This problem can be solved using only timestamps and arithmetic.
>>
>>55563705
Nobody cares about leap seconds. The issue is with unix time stamps starting at 1970.
>>
>>55563057
pretty sure the old style formatting still works in python3

parentheses are needed in python3 though, which you're missing
>>
>>55561997
the problem as stated is ill-defined.
>>
>>55563715
was the bird expecting this program to work on inputs more than 292,471,208,677 years before or after 1970?
>>
>JavaScript
/code

function stampDifferenceInDays(a,b){
return Array.from(arguments).reduce((a,b) => Math.abs(a-b)) * 1000 / 60 / 60 / 24;
}
>>
/code

function stampDifferenceInDays(a,b){
return Array.from(arguments).reduce((a,b) => Math.abs(a-b)) * 1000 / 60 / 60 / 24;
}
>>
>>55563820
Considering that dealing with time is not deterministic I suppose the bird will let you get away with an almost-correct answer too.
>>
>>55562623
Lol calm down
>>
>>55562623
go fuck yourself , and tell your mother I said hi .
>>
-[------->+<]>--.[--->+<]>++.[--->+<]>-----.++[->+++<]>.-[--->+<]>--.+[->+++<]>+.++++++++.-[++>---<]>+.--[->++++<]>+.----------.++++++.---.+.++++[->+++<]>.+++++++.------.-[->+++<]>-.
>>
File: Bird.gif (2 MB, 540x306) Image search: [Google]
Bird.gif
2 MB, 540x306
I really don't know why I took out an hour out of my life to do this.
GLOBAL _start
EXTERN printf

STRUC DATE
.Year: RESD 1
.Month: RESD 1
.Day: RESD 1
ENDSTRUC

SECTION .data
Result: DB "There are %d days between the two dates", `\n`, `\0`
Days: DD 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
Date1: ISTRUC DATE
AT DATE.Year, DD 1990
AT DATE.Month, DD 1
AT DATE.Day, DD 3
IEND
Date2: ISTRUC DATE
AT DATE.Year, DD 2016
AT DATE.Month, DD 7
AT DATE.Day, DD 13
IEND
SECTION .text

%MACRO MOD_EQZERO 2
mov eax, %1
mov ebx, %2
cdq
idiv ebx
test edx, edx
%ENDMACRO

%MACRO IS_LEAPYEAR 1
MOD_EQZERO %1, 4
setz al
jnz %%done
MOD_EQZERO %1, 100
setnz al
jnz %%done
MOD_EQZERO %1, 400
setz al
jnz %%done
mov al, 1
%%done:
movsx eax, al
%ENDMACRO

_start:
IS_LEAPYEAR [Date2+DATE.Year]
add [Days+8], eax
xor ecx, ecx
mov edi, [Date2+DATE.Day]
sub edi, 1
get_days_to:
add edi, [Days+4*ecx]
add ecx, 1
cmp ecx, [Date2+DATE.Month]
jl get_days_to

mov Dword [Days+8], 28
IS_LEAPYEAR [Date1+DATE.Year]
add [Days+8], eax
xor ecx, ecx
mov esi, [Date1+DATE.Day]
sub esi, 1
get_days_from:
add esi, [Days+4*ecx]
add ecx, 1
cmp ecx, [Date1+DATE.Month]
jl get_days_from

sub edi, esi
mov ecx, [Date1+DATE.Year]
get_years:
add edi, 365
IS_LEAPYEAR ecx
add edi, eax
add ecx, 1
cmp ecx, [Date2+DATE.Year]
jl get_years

mov rsi, rdi
mov rdi, Result
call printf

mov eax, 60
mov ebx, 0
syscall
>>
>>55562060
oh.
>>
>>55562063
I really like the stabbing birds threads. Some solutions are really creative. Also, it's cool to get a look at other languages beyond Hello World.
>>
>>55562843
No one uses Lisp outside of academia
>>
>>55561997
Try this again and see if I can do it right.
Module Module1
Sub Main()
Dim i As DateTime
Dim o As DateTime
Dim n As TimeSpan
i = Now
o = Now
n = i.Subtract(o)
Console.WriteLine(n.Days)
End Sub
End Module


>>55563782
Also this, you suck ass OP.
>>
File: 1462650934753.jpg (63 KB, 500x375) Image search: [Google]
1462650934753.jpg
63 KB, 500x375
>>55564701
I don't understand how it could take an hour. What kind of mom's spaghetti code flinging poo in loo are you?
>>
>>55562060
Of course the bird is black.
>>
>>55561997
public static System.out.println dayCalc(){
int answer =Timestamp - Timestamp2;
return system.out.println("answer");

}
>>
>>55565206
public static System.out.println dayCalc(){
int answer =Timestamp - Timestamp2;
return system.out.println("answer");

}


ftfy
>>
>>55565179
Sorry, I tried.
>>
>>55562006
You inspired me to write a version with no loops. The idea is to index everything from March 1, making leap year calculation trivial. Then adjusting for the actual month with a fixed array, followed by a final adjustment if it's Jan or Feb of a leap year.

#include <stdio.h>
#include <stdlib.h>

typedef struct {
int year; /* 0 to 9999 */
int month; /* 1 to 12 */
int day; /* 1 to 31 */
} date;

/* Determines leapdays between March 1 of end and start years*/
int leapdays(int year1, int year2)
{
int leaps = year2/4 - year1/4;
leaps -= year2/100 - year1/100;
leaps += year2/400 - year1/400;
return leaps;
}

/*Returns 1 if month is Jan or Feb and it is a leap year*/
int leapyear(date* d)
{
int year = d->year;
return d->month < 3 && !(year % 4) && ((year % 100) || !(year % 400));
}

// days between first of month and March 1, Jan = 0
int daystomarch[12] = {-59,-28,0,31,61,92,122,153,184,214,245,275};

int timespan(date* from, date* to) {
int days = 365*(to->year - from->year) + to->day - from->day + daystomarch[to->month - 1] - daystomarch[from->month - 1];
days += leapdays(from->year, to->year);
days += leapyear(from) - leapyear(to);
return days;
}

int main(void) {
date a = {1970, 1, 1};
date b = {2016, 7, 13};
int days = timespan(&a, &b);
printf("%d\n", days);
return EXIT_SUCCESS;
}
>>
>>55561997
var a = new Date(1468473133)
var b = new Date(1467331200)
var diffDays = Math.round(Math.abs(a.getTime()-b.getTime())/(60*60*24))
console.log(diffDays)
>>
var moment = require('moment');

var daysDifference = moment(date1).difference(date2).days();
>>
>>55566703
well nevermind that javascript uses milliseconds, forgot a 1000 here and there, whatever
>>
>>55562683
:^)
>>
>>55561997

Ruby one-liner (as expected):

require 'date'

diff = Date.parse("25/03/2016") - Date.parse("30/05/2015")
p diff.to_i
>>
>>55568637

And before somebody nags:

If OP can include two libraries, I can include one.
>>
>>55564951
Check out reddit.com/r/dailyprogrammer. I like it for similar reasons. They have 3 challenges a week: easy on Monday, intermediate on Wednesday, and hard-on Friday.
>inb4 get out leddit
>>
>>55564951

Same goes for me.

I really to annoy C fags (like OP) with my beautifull Ruby statements.. :)

But I also enjoy looking at the solutions in Python, Perl and Haskell, because it's often astonishing smart.

Even though it's only micro tasks (unless you bother with defining structs and reinventing the wheel, like the C fags) it's still amusing.
>>
dif.days <- function(today, tomorrow){
today.date <- as.Date(today, format = "%d-%m-%Y")

today.year <- as.integer(format(today.date, "%Y"))
today.month <- as.integer(format(today.date, "%m"))
today.day <- as.integer(format(today.date, "%d"))
if (today.year %% 4 == 0 & today.year %% 100 != 0 | today.year %% 100){
today.day <- today.day + 1
}

tomorrow.date <- as.Date(tomorrow, format = "%d-%m-%Y")
tomorrow.year <- as.integer(format(tomorrow.date, "%Y"))
tomorrow.month <- as.integer(format(tomorrow.date, "%m"))
tomorrow.day <- as.integer(format(tomorrow.date, "%d"))
if (tomorrow.year %% 4 == 0 & tomorrow.year %% 100 != 0 | tomorrow.year %% 100){
tomorrow.day <- tomorrow.day + 1
}

dif.yr <- tomorrow.year - today.year
year.in.days <- dif.yr * 365
dif.mt <- tomorrow.month - today.month
month.in.days <- dif.mt * 30
dif.dy <- tomorrow.day - today.day
if (dif.yr %% 4 == 0){
dif.dy <- dif.dy + (dif.yr %/% 4)
}

total.dif <- year.in.days + month.in.days + dif.dy

if (total.dif == 1){
result1 <- paste("The difference between", today, "and", tomorrow, "is", total.dif, "day", sep = " ")
result1
} else {
result <- paste("The difference between", today, "and", tomorrow, "is", total.dif, "days", sep = " ")
result
}
}
>>
>>55562006

I'd put the leapyear function like this:

int leapyear(int year) {
if (year % 400 == 0) return 1;
if (year % 100 == 0) return 0;
if (year % 4 == 0) return 1;
return 0;
}
>>
>>55568751
Forgot to say it's in R
>>
>>55568788
What's the difference?
>>
>>55561997

Using the time crate, in Rust:

extern crate time;

use time::{strptime, Tm};

fn days_between(first: &Tm, second: &Tm) -> i64 {
(*second - *first).num_days()
}

fn main() {
let format = "%d.%m.%Y";

let n = strptime("1.5.2015", format).unwrap();
let s = strptime("1.11.2016", format).unwrap();

println!("{}", days_between(&n, &s));
}
>>
>>55569003

Not using the curly braces, therefore more readable.

>>55562302

You mean this?

With ThisWorkbook.Sheets(1)
MsgBox DateDiff("d", CDate(.Range("A1")), CDate(.Range("A2")))
End With
>>
>>55569415

Scratch that, the chrono crate is much better for that:

extern crate chrono;

use chrono::{UTC, TimeZone};

fn main() {
let n = UTC.ymd(2015, 7, 11);
let s = UTC::today();
println!("{}", (s - n).num_days());
}
>>
File: mfw.gif (229 KB, 500x316) Image search: [Google]
mfw.gif
229 KB, 500x316
>>55569544

>Rust
>>
>>55568751
Easier in R
day.dif <- function(today, tomorrow){
today <- as.Date(today, format = "%d-%m-%Y")
tomorrow <- as.Date(tomorrow, format = "%d-%m-%Y")
dif <- tomorrow - today
dif
}
>>
Module Module1
Sub Main()
Dim date1 = #5/1/2015#
Dim date2 = #7/1/2015#
Console.WriteLine(DateDiff(DateInterval.Day, date1, date2))
End Sub
End Module


Sorry plebs but Visual Basic is just too superior.
>>
Monday

Tuesday
>>
>>55569462
>Not using the curly braces, therefore more readable.

You don't read curly braces.
>>
>>55573123

int you()
{
are()
{
// ..a bracket fag
}
}
>>
>>55565193

#blackcrowsmatter
>>
>>55562006
>that fucking leapyear function

What's the point? You either just do % 4 or if you really wanna be smartass you can check last two bits
>>
>>55561997
lambda a,b: a-b/86400
>>
File: tumblr.jpg (27 KB, 452x254) Image search: [Google]
tumblr.jpg
27 KB, 452x254
>>55561997
var moment = require('moment')

var OPISAFAG = function(startDate, endDate) {
return endDate.diff(startDate, 'days')
}

var startDate = moment('2013-5-11 8:73:18', 'YYYY-M-DD HH:mm:ss')
var endDate = moment('2013-5-11 10:73:18', 'YYYY-M-DD HH:mm:ss')

console.log(OPISAFAG(startDate, endDate));

>>
>>55573851
Nvm, just noticed the second one returns 0 instead of 1
>>
>>55573851
Leap year measurement isn't trivial anon. Even that function is just an approximation.
>>
>>55562071
Difference in /days/ mang.

return (t2 - t1) / 86400; // return Unix timestamp difference in days
>>
>>55561997
calculate_the_difference_in_days_between_two_timestamps() {
timestamp1=0
timestamp2=0
echo "$((timestamp1/timestamp2)) days"
}
>>
>>55573880
Why even use momentjs for this when you could use the standard Date class?
>>
>>55574117
Because require
>>
Hey bird-stabbing OP: do you take suggestions for topics? I don't want to just make my own thread because I feel like you have a really good handle on what kinds of challenges fit in the middle ground between two easy and stupidly complicated/specific.
>>
File: shig smile trump eyes.jpg (13 KB, 314x110) Image search: [Google]
shig smile trump eyes.jpg
13 KB, 314x110
>>55568788
int leapyear(int year)
{
if (year % 4) return 0;
if (year % 100) return 1;
if (year % 400) return 0;
return 1;
}
>>
>>55562683
>i don't know any programming whatsoever
>this programming thread is the right place for me
>>
>>55573867
Order of operations fail
>>
>>55563500
clearly you are
you've obviously never programmed anything else than hello world
yet you're here in this thread
>>
>>55568662
>reddit
>>
File: 1464902023324.jpg (152 KB, 964x639) Image search: [Google]
1464902023324.jpg
152 KB, 964x639
>>55561997
Emacs Lisp

(defun cmp-time-in-days (x y)
(let ((day-in-secs (* 60 60 24)))
(/ (abs (- x y))
day-in-secs)))

(defun get-time (date-str)
(let ((date (apply #'concat (list date-str " 00:00:00 UTC"))))
(floor (float-time (date-to-time date)))))

(defun now ()
(floor (float-time)))


;; examples
(cmp-time-in-days (now)
(get-time "14 July 2016")) ;; => 0
(cmp-time-in-days (get-time "11 July 2016")
(now)) ;; => 3
(cmp-time-in-days (get-time "14 Aug 2016")
(now)) ;; => 30
>>
>>55576848
Sexy
Thread replies: 114
Thread images: 10

banner
banner
[Boards: 3 / a / aco / adv / an / asp / b / biz / c / cgl / ck / cm / co / d / diy / e / fa / fit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mu / n / news / o / out / p / po / pol / qa / r / r9k / s / s4s / sci / soc / sp / t / tg / toy / trash / trv / tv / u / v / vg / vp / vr / w / wg / wsg / wsr / x / y] [Home]

All trademarks and copyrights on this page are owned by their respective parties. Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
If a post contains personal/copyrighted/illegal content you can contact me at [email protected] with that post and thread number and it will be removed as soon as possible.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com, send takedown notices to them.
This is a 4chan archive - all of the content originated from them. If you need IP information for a Poster - you need to contact them. This website shows only archived content.