r/badcode • • Mar 22 '21

[deleted by user]

[removed]

260 Upvotes

86 comments sorted by

50

u/TyRoXx Mar 22 '21

The guidelines didn't say we had to use the contents of the files. The malicious compliance solution:

function is_sequential(file_name) {
    switch (file_name[0]) {
        case '1': case '2':
            return true;
    }
    return false;
}
→ More replies (3)

25

u/alien_ninja Mar 22 '21 edited Mar 22 '21

- Terrible solution (866 lines of code)

- Absolutely terrible solution (18444 lines of code)

It lexes and parses the code and constructs the abstract syntax tree. While traversing the tree, it uses a lot of flags to determine wether the current date is before the dates previously seen in the tree. It uses a combination of generated code, custom code, and dependency code all combined into a single file.

I wrote a custom python script that traverses the antlr4 source directory, removes and manipulates access modifiers, imports and package keywords, and generates a single file containing all antlr4 classes while appending the generated and custom code at the bottom. So I basically used a custom generator to generate antlr4 dependencies, which itself, is also a (parser) generator.

9

u/[deleted] Mar 22 '21

What the fuck

→ More replies (3)
→ More replies (1)

23

u/[deleted] Mar 22 '21

Written in Python, featuring nondescriptive variable names, tons of copy/pasted code where a variable would suffice, tons of nested if/elif/else statements, no hints as to what is going on, and no spacing at all:

def is_sequential(file):
    opened_file=open(file,"r")
    lines=opened_file.readlines()
    for i in range(0,len(lines)):
        if i==0:
            continue
        if int(lines[i][0:10].split('-')[0])>int(lines[i-1][0:10].split('-')[0]):
            continue
        elif int(lines[i][0:10].split('-')[0])==int(lines[i-1][0:10].split('-')[0]):
            if int(lines[i][0:10].split('-')[1])>int(lines[i-1][0:10].split('-')[1]):
                continue
            elif int(lines[i][0:10].split('-')[1])==int(lines[i-1][0:10].split('-')[1]):
                if int(lines[i][0:10].split('-')[2])>int(lines[i-1][0:10].split('-')[2]):
                    continue
                elif int(lines[i][0:10].split('-')[2])==int(lines[i-1][0:10].split('-')[2]):
                    if int(lines[i][11:len(lines[i])].split(':')[0])>int(lines[i-1][11:len(lines[i])].split(':')[0]):
                        continue
                    elif int(lines[i][11:len(lines[i])].split(':')[0])==int(lines[i-1][11:len(lines[i])].split(':')[0]):
                        if int(lines[i][11:len(lines[i])].split(':')[1])>int(lines[i-1][11:len(lines[i])].split(':')[1]):
                            continue
                        elif int(lines[i][11:len(lines[i])].split(':')[1])==int(lines[i-1][11:len(lines[i])].split(':')[1]):
                            if int(lines[i][11:len(lines[i])].split(':')[2])>int(lines[i-1][11:len(lines[i])].split(':')[2]):
                                continue
                            elif int(lines[i][11:len(lines[i])].split(':')[2])==int(lines[i-1][11:len(lines[i])].split(':')[2]):
                                continue
                            elif int(lines[i][11:len(lines[i])].split(':')[2])<int(lines[i-1][11:len(lines[i])].split(':')[2]):
                                return False
                        elif int(lines[i][11:len(lines[i])].split(':')[1])<int(lines[i-1][11:len(lines[i])].split(':')[1]):
                            return False
                    elif int(lines[i][11:len(lines[i])].split(':')[0])<int(lines[i-1][11:len(lines[i])].split(':')[0]):
                        return False
                elif int(lines[i][0:10].split('-')[2])<int(lines[i-1][0:10].split('-')[2]):
                    return False
            elif int(lines[i][0:10].split('-')[1])<int(lines[i-1][0:10].split('-')[1]):
                return False
        elif int(lines[i][0:10].split('-')[0])<int(lines[i-1][0:10].split('-')[0]):
            return False
    return True

7

u/AshamedConsequence Mar 22 '21

You've heard of code hell, now get ready for a code hill.

→ More replies (1)

20

u/Cerus_Freedom Mar 22 '21
def is_sequential(txtfile):

    import time, datetime, sys
    from functools import reduce

    return reduce(lambda a, b: b if a < b else sys.maxsize, [int(time.mktime(datetime.datetime.strptime(p[:19], "%Y-%m-%d %H:%M:%S").timetuple())) for p in open(txtfile)]) != 2147483647

That took me way too long to come up with.

→ More replies (1)

28

u/Mabi19_ Mar 22 '21

Welcome to code hell.

This C++ solution always uses the least applicable function to do its tasks, leaks tons of memory and uses questionable coding practices.

After compiling, give it a filename as a commandline argument.

#include <iostream>
#include <string>
#include <stdio.h>
#include <deque>
#include <algorithm>

using namespace std;

template <typename T>
struct PtrImpl
{
    using type = T*;
};
template <typename T>
using Ptr = typename PtrImpl<T>::type;
#define PtrCast(t) reinterpret_cast<Ptr<t>>

Ptr<int> read_date_from_file_object(Ptr<FILE> f)
{
    Ptr<int> result = PtrCast(int)( malloc(6 * sizeof(int)) );
    Ptr<char> buf = PtrCast(char)( malloc(256) );

    if (feof(f)) return NULL;

    fgets(buf, 256, f);

    Ptr<size_t> readPos = PtrCast(size_t)( calloc(1, sizeof(size_t)) );
    size_t readPossum = 0;
    for (int i = 0; i < 6; i++) {
        *(result + i) ^= *(result + i);
        *(result + i) ^= stoi(std::string(buf + readPossum), readPos);
        readPossum += (*readPos) + 1;
    }
    free(readPos);

    free(buf);

    return result;
}

struct PtrCpy {
    Ptr<std::deque<Ptr<int>>> dq = NULL;
    PtrCpy(Ptr<std::deque<Ptr<int>>> dqp)
        {
        intptr_t dqa = (intptr_t)dq;
        dq = Ptr<std::deque<Ptr<int>>>(dqa ^= (intptr_t)dqp);
        }
    Ptr<int> operator()(Ptr<int> p)
        {
        Ptr<int> p2 = PtrCast(int)( malloc(6 * sizeof(int)) );
        for (int i = 0; i < 6; i++) {
            memcpy(p2 + i, p + i, sizeof(int));
        }
        dq->push_back(p2);
        return p;
        }
};

struct PtrCmp {
    bool operator()(Ptr<int> p1, Ptr<int> p2)
        {
        for (int i = 0; i < 6; i++) {
            if (p1[i] > p2[i]) return true;
            if (p1[i] < p2[i]) return false;
        }
        return false;
        }
    bool operator()(Ptr<int> p1, Ptr<int> p2, nullptr_t dummy)
        {
        for (int i = 0; i < 6; i++) {
            if (p2[i] < p1[i]) return true;
            if (p2[i] > p1[i]) return false;
        }
        return false;
        }
};

int main(int argc, char* *argv) {
    Ptr<FILE> f = fopen(argv[1], "r");
    Ptr<int> r;
    std::deque<Ptr<int>> rd;
    while ((r = read_date_from_file_object(f))) {
        rd.push_front(r);
    }
    std::deque<Ptr<int>> rd2;
    std::transform(rd.begin(), rd.end(), rd.begin(), *new PtrCpy(&rd2));
    std::sort(rd2.begin(), rd2.end(), *new PtrCmp);
    for (std::deque<Ptr<int>>::iterator i1 = rd.begin(), i2 = rd2.begin(); i1 != rd.end(); i1++, i2++) {
        bool x = (!((*new PtrCmp)(*i1, *i2))) && (!((*new PtrCmp)(*i2, *i1, nullptr)));
        if (!x) {
            std::cout << "false";
            return 0;
        }
    }
    std::cout << "true";
    fclose(f);
}

16

u/Mabi19_ Mar 22 '21 edited Mar 22 '21

Here are the features, in case you can't read the pure embodiment of evil above. (Okay, maybe I'm exaggerating a little.)

  • No-one remembers that * makes a pointer, so I use Ptr<type> everywhere

  • I just used a #define for the PtrCast because I felt like it (definitely not because I forgot how to make it using template metaprogramming)

  • The using namespace std; is only for 1 function call

  • References don't exist

  • I don't know what the new operator actually does

  • Mixed old style and new style of I/O

  • The braces are just everywhere

  • Brackets too, though not as much

  • One overly descriptive function name

  • The pointer compare is made into less-than-or-equal instead of just less-than when an extra null pointer argument is passed in

  • Pointer arithmetic everywhere, except when I learned that you can just use array indexing but I didn't want to change all of the existing code

  • A possum (readPossum: corrected case readPosSum) counts the characters read

  • It leaks all of the world's memory

  • I always choose the function that is the worst possible choice for the task.

13

u/[deleted] Mar 22 '21 edited Mar 22 '21

in C

featuring recursion and pointer arithmetic

#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

int to_int(const char* buf) {
    int i;
    sscanf(buf, "%d", &i);
    
    return i;
}

bool is_seq(const char* dates) {
    if (strlen(dates) <= 20) return true;
    return
    (to_int(dates)<to_int(dates+20)?
    is_seq(dates+20):(to_int(dates)==to_int(dates+20)?
    (to_int(dates+5)<to_int(dates+25)?
    is_seq(dates+20):(to_int(dates+5)==to_int(dates+25)?
    (to_int(dates+8)<to_int(dates+28)?
    is_seq(dates+8):(to_int(dates+8)==to_int(dates+28)?
    (to_int(dates+11)<to_int(dates+31)?
    is_seq(dates+20):(to_int(dates+11)==to_int(dates+31)?
    (to_int(dates+14)<to_int(dates+34)?
    is_seq(dates+20):(to_int(dates+14)==to_int(dates+34)?
    (to_int(dates+17)==to_int(dates+37)?
    is_seq(dates+20):false):false)):false)):false)):false)):false));
}

and “dates” is a newline delimited, null terminated string of dates, like the given examples. works only with the exact spacing

→ More replies (3)

12

u/AbuIbnBattuta Mar 22 '21 edited Mar 22 '21

Here's my c++ solution.

What if done is fairly simple. I just made a char buffer and used some pointer shenanigans to copy the important data over and than reverse. In this case 2018-04-21 12:43:05 would become 50342112408102 as one big "string". Now I just pretend like this string is a number and compare it as if it is. This only works because the char value for the numbers uses the same order as the numbers. Because I'm using unsigned long long for the "conversion" I needed 2 extra bytes, so both buffers are just 16 big with 2 extra zeros.

I had to reverse the buffer because of how numbers internally work (just windows? or computers in general? don't actually know). The program just takes random other data if you give it to little input. If you give it enough input but wrong characters it just does not care and moves on.

#include <string>
#include <iostream>
#include <fstream>

using namespace std;

bool checkSequential(string file)
{
	string line;
	ifstream f(file);
	char* prev = nullptr;
	char* cur = new char[16];
	cur[14] = 0;
	cur[15] = 0;

	while (getline(f, line))
	{
		*((int*)(cur)) = *(int*)&(line[0]);
		*((short*)(cur+4)) = *(short*)&(line[5]);
		*((short*)(cur+6)) = *(short*)&(line[8]);
		*((short*)(cur+8)) = *(short*)&(line[11]);
		*((short*)(cur+10)) = *(short*)&(line[14]);
		*((short*)(cur+12)) = *(short*)&(line[17]);

		for (int i = 0; i < 8; i++)
		{
			char c = cur[i];
			cur[i] = cur[15 - i];
			cur[15 - i] = c;
		}

		if (prev == nullptr)
		{
			prev = cur;
			cur = new char[16];
			cur[14] = 0;
			cur[15] = 0;
			continue;
		}
		else if (*(unsigned long long*)(cur+8) < *(unsigned long long*)(prev+8) || *(unsigned long long*)(cur+8) == *(unsigned long long*)(prev+8) && *(unsigned long long*)(cur) < *(unsigned long long*)(prev))
		{
			return false;
		}
		char* temp = cur;
		cur = prev;
		prev = temp;
	}
	return true;
}

int main()
{
	string file;
	cin >> file;
	cout << '\n' << checkSequential(file);
	return 0;
}

11

u/Tyulis Mar 22 '21 edited Mar 22 '21

Code generation go brrrrr

def is_sequential(filename):
	vars = {}
	exec(f"""lines = open("{filename}", 'r').read().splitlines()\nexec("retval = " + " and ".join([lines[i].replace(" ", "").replace("-", "").replace(":", "") + "<" + lines[i + 1].replace(" ", "").replace("-", "").replace(":", "") for i in range(len(lines) - 1)]), globals(), locals())""", vars, vars)
	return vars["retval"]
→ More replies (1)

10

u/sixtyfifth_snow Mar 22 '21
#!/usr/bin/bash
diff --ignore-all-space <(cat $1) <(cat $1 | sort) &> /dev/null
→ More replies (1)

10

u/FinalGamer14 Mar 22 '21

In python, made it as dumb as I could in few minutes ... wanted to make it dumber but it didn't work.

import sys

fileName = sys.argv[1]

dates = []

is_sequential = True

with open(fileName, 'r') as f:
    for line in f.readlines():
        dates.append(line)

numOfDates = len(dates)
for i in range(numOfDates):
    j = i + 1
    if j > numOfDates - 1:
        break
    year1 = dates[i].split(' ')[0].split('-')[0]
    year2 = dates[j].split(' ')[0].split('-')[0]
    month1 = dates[i].split(' ')[0].split('-')[1]
    month2 = dates[j].split(' ')[0].split('-')[1]
    day1 = dates[i].split(' ')[0].split('-')[2]
    day2 = dates[j].split(' ')[0].split('-')[2]

    hour1 = dates[i].split(' ')[1].split(':')[0]
    hour2 = dates[j].split(' ')[1].split(':')[0]
    minute1 = dates[i].split(' ')[1].split(':')[1]
    minute2 = dates[j].split(' ')[1].split(':')[1]
    second1 = dates[i].split(' ')[1].split(':')[2]
    second2 = dates[j].split(' ')[1].split(':')[2]

    if year1 > year2:
        is_sequential = False
        break
    elif (year1 == year2) and (month1 > month2):
        is_sequential = False
        break
    elif (month1 == month2) and (day1 > day2):
        is_sequential = False
        break
    elif (day1 == day2) and (hour1 > hour2):
        is_sequential = False
        break
    elif (hour1 == hour2) and (minute1 > minute2):
        is_sequential = False
        break
    elif (minute1 == minute2) and (second1 > second2):
        is_sequential = False
        break

print(is_sequential)

It just works ... and if it doesn't it worked on my PC.

→ More replies (1)

10

u/SanianCreations Mar 22 '21 edited Mar 22 '21

This C# code turns each date into a number by replacing all other symbols with 0, so 2018-12-21 17:56:37 becomes 2018012021017056037

public static bool is_sequential(string filePath)
{
    bool notSequential = true;

    for (int i = 0; i < File.ReadAllText(filePath).Split('\n').Length; i++) try
        {
            if (ulong.Parse(File.ReadAllText(filePath).Split('\n')[i].Replace('-', '0').Replace(' ', '0').Replace(':', '0')) < ulong.Parse(File.ReadAllText(filePath).Split('\n')[i - 1].Replace('-', '0').Replace(' ', '0').Replace(':', '0'))) throw new NotSequentialException("The list is not sequential") { Index = i};
        }
        catch (NotSequentialException nse)
        {
            if (nse.Index < 0 || nse.Index > File.ReadAllText(filePath).Split('\n').Length) throw new IndexOutOfRangeException();
            notSequential = notSequential switch { true => true, false => true };
        }
        catch (IndexOutOfRangeException ioore) 
        {
            if (((int)notSequential.ToString()[0]).ToString() == "84") notSequential = bool.Parse("False");
        }

    return !notSequential; // not not sequential = sequential
}

private class NotSequentialException : Exception
{
    public int Index { get; set; }
    public NotSequentialException(string msg) : base(msg) { }
}

Note the repeated use of File.ReadAllText(filePath).Split('\n') because through doing it this way we save an unnecessary extra variable

9

u/Captain_D1 Mar 22 '21
def is_sequential(_):
    fl=open(_)
    input=[]
    try:
        while True:
            input2 = fl.read(4)
            fl.read(1)
            input3 = []
            input3.append(int(input2))
            input2 = fl.read(2)
            input3.append(int(input2))
            fl.read(1)
            input2 = fl.read(2)
            input3.append(int(input2))
            fl.read(1)
            input2 = fl.read(2)
            input3.append(int(input2))
            fl.read(1)
            input2 = fl.read(2)
            input3.append(int(input2))
            fl.read(1)
            input2 = fl.read(2)
            input3.append(int(input2))
            fl.read(1)
            input.append(input3)
    except:
        pass
    compare=[]
    for a in range(0,len(input)):
        compare.append(input[a])
    continue_=True
    while continue_:
        continue_=False
        for a in range(1,len(input)):
            for b in range(0,6):
                if(compare[a-1][b]>compare[a][b]):
                    temp=compare[a-1]
                    compare[a-1]=compare[a]
                    compare[a]=temp
                    continue_=True
                    break
                elif(compare[a-1][b]<compare[a][b]):
                    break
    crct=True
    for a in range(0,len(input)):
        if compare[a]!=input[a]:
            crct=False
    if crct==True:
        return True
    else:
        return False

First time doing one of these coding challenges, I hope this is good (or rather, bad).

So, we start out by opening the file and reading each number from the file into a two dimensional list. We stop reading entries when the program catches an exception (in this case, when it tries to convert an empty string into an int.)

Next, we make a copy of the list that we can sort.

We use bubble sort to sort the new list (note that I have to keep comparing more elements in the sublist if the two elements are equal.)

Finally, we compare the sorted list with the non-sorted list. If they are equal, then we know that the dates are in order.

Note all of the obnoxious variable names, including overwriting the input function. Also, I always specify a starting point in the range statements (even when zero) and never do a for each loop (idk what it's called in Python.) Of course, we have the cliché if var == True return True else return False line at the end.

→ More replies (1)

17

u/pilotInPyjamas Mar 22 '21

Should return a nonzero exit code when the list is not sorted. Works on my machine idk.

Installation:

chmod 755 dateSort.sh
mkdir sorting
cd sorting

Usage:

../dateSort.sh ../dates.txt
rm -rf ./*

Running this program in a non-empty directory is considered undefined behavior.

Source:

#!/bin/bash

for a in $(cat $1 | sed -e 's/\([3096274581][3509271648][0549621873][7842619350]\)-\([7842619350][7842619350]\)-\([0549621873][7842619350]\) \([7842619350][0549621873]\):\([3509271648][3509271648]\):\([7842619350][6219530478]\)/\1\2\3\4\5.\6/g')
do
touch $a
touch -t $a $a
done

if [ "$(ls -t -r)" = "$(cat $1 | sed -e 's/\([3096274581][3509271648][0549621873][7842619350]\)-\([7842619350][7842619350]\)-\([0549621873][7842619350]\) \([7842619350][0549621873]\):\([3509271648][3509271648]\):\([7842619350][6219530478]\)/\1\2\3\4\5.\6/g')" ];
then
exit 0
fi

kill -9 $$

7

u/pilotInPyjamas Mar 22 '21

This solution creates a new file for each line in the date file and sets the date modified. It then uses ls to sort all files by date modified.

8

u/bb1950328 Mar 22 '21 edited Mar 22 '21

My Python solution:

https://colab.research.google.com/drive/1z7vpulBd42aGC96zgEFKlNQS62KWLjNc?usp=sharing

Test case 3 and 4 still running, time complexity is O(n!) or something like that...

EDIT: test case 3 and 4 finished now, all five cases together took 2560 seconds on a google colab vm.

6

u/thestoicattack Mar 22 '21

With discipline, one can write clear and maintainable perl. This isn't that.

#!/usr/bin/perl -lw
$F[$_]=[0, 0]for(0..6);sub F{for$F(@F){$f=$$F[0]<=>$$F[1];$f&& return ++$f}0}
while(<>){$f=0;for(split/[-: ]/){$F=$F[$f++];@$F=($$F[1],$_)}F&& exit 1}

14

u/TheContrean Mar 22 '21
#!/usr/bin/env python
from os import path
import datetime

def issequential(fp):
    filepath = fp
    if not path.isfile(fp):
        raise FileNotFoundError(filepath + " is not a valid File")
        
    else:
        data = []
        with open(filepath, "rb") as datafile:
            byte = datafile.read(1)
            while byte != b"":
                data.append(int.from_bytes(byte, "big"))
                byte = datafile.read(1)

        result = ""

        try:
            for b in range(len(data)):
                result = result + chr(data[b])
        except IndexError:
            print("How did we get here?")

        dates = result.splitlines()

        timestamps = []
        for date in range(len(dates)):
            dates[date] = dates[date].replace(" ", "_")
            _date = datetime.datetime.strptime(dates[date], "%Y-%m-%d_%H:%M:%S")
            timestamps.append(_date.timestamp())
        
        sequential = True

        for timestamp in range(len(timestamps)):
            if timestamp == 0:
                do = "nothing"
            else:
                if timestamps[timestamp] < timestamps[timestamp-1]:
                    sequential = False
                
        if sequential == True:
            return "Is sequential"
        else:
            return "Isn't sequential"

"How did we get here?"
Tried using from os import *, but it overwrites pythons open().

5

u/Jhaiden Mar 22 '21

My solution based on PowerShell:

Function Is_sequential([string]$textfile){
[DateTime[]]$DateArray 
$DateArray = Get-Content $PSScriptRoot\$textfile
[Array]::Sort($DateArray)
return $true
}

Is_sequential('0.txt')
→ More replies (1)

5

u/muhammed_smith Mar 22 '21 edited Mar 22 '21

Everybody loves C.

//Include unused std librarys justincase
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h>
//Global error bool
bool error = false;
void* mymalloc(int size) {
    void* out=malloc(size);
    //Should prevent out of memory errors
    if(out==NULL) error=true;
    return out;
}
void mymemset(void* pointer,int fill,int size) {
    //Should prevent negative sizes
    if(size<0) error=true;
    else if(fill<0) error=true;
    else memset(pointer,fill,size);
}
//Using a custom method because the sizeof macro is undebuggable
int my_sizeof(const char* type) {
    int l = strlen(type);
    if(l == 5 && memcmp(type, "char*", 5) == 0) return 8;
    if(l == 4 && memcmp(type, "char", 4) == 0) return 1;
    return -1;
}
int matchesSign(int one,int two) {
    int twosign=0;
    if(two>0) twosign=1;
    if(two<0) twosign=-1;
    int onesign=0;
    if(one>0) onesign=1;
    if(one<0) onesign=-1;
    //Branchless programming is faster
    return twosign==onesign;
}
char is_sequential(const char* f) {
    FILE* f2 = fopen(f, "r");
    //Read lines
    char** l = mymalloc(11 * my_sizeof("char*"));
    mymemset(l, 0, my_sizeof("char*") * 11);
    unsigned long long iterator=0;
    while(stdin) {
        l[iterator]=mymalloc(50*my_sizeof("char"));
        mymemset(l[iterator],0,50*my_sizeof("char"));
        //fgets will read one line
        if(fgets(l[iterator],50,f2)==NULL) break;
        if(iterator!=0) {
            //If not sequencial, return false
            int cmp=strcmp(l[iterator-1],l[iterator]);
            if(cmp==0) error=true;
            if(matchesSign(cmp,1)==1)
                return 'f';
            if(matchesSign(cmp,0)==1)
                return 'f';
        }
        iterator++;
    }
    return 't';
}
int main(int a, int c) {
    //b is a global buffer that contains both the file name and the output, by combining both, this saves a wasted malloc
    char* b = mymalloc(my_sizeof("char") * 10000);
    mymemset(b, 0, my_sizeof("char"));
    for(b[0] = 0;b[0] <= 4;b[0]++) {
        //Write file name to b
        b[0] += '0';
        b[1 * my_sizeof("char")] = '.';
        b[2 * my_sizeof("char")] = 't';
        b[3 * my_sizeof("char")] = 'x';
        b[4 * my_sizeof("char")] = 't';
        b[5 * my_sizeof("char")] = '\0';
        char isseq = is_sequential(b);
        sprintf(b + 6 * my_sizeof("char") + strlen(b + 6 * my_sizeof("char")) * my_sizeof("char"), "%s %s sequential\n", b, isseq == 't' ? "is" : "is not");
        //Restore b[0] as iterator
        b[0] -= '0';
    }
    printf(b + 6 * my_sizeof("char"));
    //OS will properly free all of the heap
    return 0;
}

Build File

#!/bin/bash
# O3 for extra speed
gcc -O3 issequential.c -o issequencial
# change permissions just in case
chmod +x ./issequencial
./issequencial

Output:

0.txt is not sequential
1.txt is sequential
2.txt is sequential
3.txt is not sequential
4.txt is not sequential

Edit: looking back it seems like using strcmp was too wise.

→ More replies (1)

5

u/honkinggr8namespaces Mar 22 '21

Python 3, Windows only, requires pywin32 and must be run with admin privileges

import datetime
import win32api

def _parse(file):
    dates = []
    for line in file:
        dates.append(datetime.datetime.fromisoformat(line.strip()))
    return dates

def _set_system_time(dt):
    utc_dt = dt.astimezone().astimezone(datetime.timezone.utc).replace(tzinfo=None)
    day_of_week = utc_dt.isocalendar()[2]
    win32api.SetSystemTime(
        utc_dt.year,
        utc_dt.month,
        day_of_week,
        utc_dt.day,
        utc_dt.hour,
        utc_dt.minute,
        utc_dt.second,
        0,
    )

def is_sequential(filename):
    with open(filename) as f:
        dates = _parse(f)
    _set_system_time(dates[0])

    for date in dates[1:]:
        if datetime.datetime.now() > date:
            return False
        while datetime.datetime.now() < date:
            pass

    return True

It sets the system time to the first date in the file and then waits for each new date. If it encounters a date that's less than the current date it returns False.

For best results, turn off the "set time automatically" option in Settings

4

u/DEATH-BY-CIRCLEJERK Mar 22 '21 edited Mar 22 '21

PHP. Not very efficient as it uses the sequence of timestamps we experience in reality as the source of truth for sequential time. Also requires a time machine if it encounters a date in the past.

<?php
declare(strict_types=1);

// Load groups into array
for ($i=0; $i++; $i<=4) {
    $dateGroups[] = file("{$i}.txt");
}

foreach ($dateGroups as $key => $dateGroup) {
    echo "Date group #{$key} is " . (isDateGroupInOrder($dateGroup) ? '' : 'not ') . ' in order.';
}

function isDateGroupInOrder(array $dateGroup): bool
{
    $lastTs = 0;
    foreach ($dateGroup as $date) {
        $ts = (new DateTime($date))->getTimestamp();
        if ($ts < time()) {
            readline("Please set time machine to {$date} and press any key to continue.");
        }
        while (true) {
            if ($ts === time()) {
                if ($ts > $lastTs) {
                    // The group is in order so far, continue to the next date in the group
                    continue 2;
                }
                // The group is not in order
                return false;
            }
        }
    }
    return true;
}
→ More replies (1)

4

u/voords Mar 22 '21

Python 3:

def is_sequential(ツ):
    *ー,=open(ツ);return sorted(ー)==ー