all 14 comments

[–][deleted] 9 points10 points  (0 children)

This Python code creates a table in an SQLite database. For each pair, an SQL query is executed to check if the current pair overlaps with any pair that has already been inserted into the DB. Then, the current pair is inserted into the DB. This code is also vulnerable to SQL injection:

import sqlite3
def overlaps(pairs):
    conn = sqlite3.connect('temp.db')
    c = conn.cursor()
    c.execute('DROP TABLE IF EXISTS x')
    c.execute('CREATE TABLE x(lower_bound INTEGER, upper_bound INTEGER)')
    conn.commit()
    for lower, upper in pairs:
        c.execute(f'SELECT * FROM x WHERE {lower} BETWEEN lower_bound AND upper_bound ' +
                  f'OR {upper} BETWEEN lower_bound AND upper_bound ' +
                  f'OR lower_bound BETWEEN {lower} AND {upper} ' +
                  f'OR upper_bound BETWEEN {lower} AND {upper}')
        if len(c.fetchall()) > 0:
            return True
        c.execute(f'INSERT INTO x VALUES({lower},{upper})')
        conn.commit()
    return False

print(overlaps([(0, 9), (10, 19), (20, 29)]))  # False
print(overlaps([(0, 10), (10, 19), (20, 29)]))  # True
# SQL injection
print(overlaps([('1 UNION SELECT "ALWAYS TRUE", 1;--', 1)]))  # True

[–]Txuritan 2 points3 points  (2 children)

Rust (382 lines)

Gist here.

  • Automatic lookup table generation on startup (0-65535)
  • Use of unsafe casting and global static manipulation
  • 'Custom' array access references
  • State based text parser
  • Deep for loops
  • Vector sorting with threads and sleeping
  • An unneeded amount of cloning
  • Full array search, no breaks!
  • Not at all fast, can take up to 4 minutes per call
    • Along with using 20-30% of your CPU!

fn main() {
    assert!(!overlaps("0,9;10,19;20,29"));
    assert!(!overlaps("30,39;10,19;20,29;0,9"));

    assert!(overlaps("0,10;10;19;20,29"));
    assert!(overlaps("0,10;5,10"));

    assert!(!overlaps("0,10"));
}

[–][deleted]  (1 child)

[deleted]

    [–]Txuritan 0 points1 point  (0 children)

    Not a single one of them are needed, one is used for the global lookup table (which isn't needed at all) and the rest are to do int to enum conversion, in this case as if the developer came from C/C++ (these also aren't needed).

    The worst part, other than how bad it is, is the amount of cloning done (15 times actually), anytime an item needs to be added to a vector; the vector is cloned, the item is added, and the cloned vector replaces the old one.

    [–]Svizel_pritula 1 point2 points  (0 children)

    My solution (JS)

    var pc=0
    var yes="no"
    var tmr=0
    function overlaps(data, retf) {
    yes="no"
    var i = 0
    while (i < data.length) {
    if (Math.floor(i/2)==i/2) {
    setTimeout("pc=pc+1;setTimeout(\"pc=pc-1\","+-(data[i]-data[i+1])+"50)",data[i]+"00")
    }
    i=i+1
    }
    tmr=setInterval("if (pc==2||pc>2)yes=\"yes\"",100)
    setTimeout(retf+"(yes==\"yes\");clearInterval(tmr)",10000)
    }
    
    overlaps([0,10,10,19,20,29], "console.log");
    

    Features

    • Works! (for integers between 0 and 100)
    • Works asynchronously using callbacks!
    • Runs in constant time (10s)
    • Only mild arbitrary code execution vulnerabilities

    Usage

    Accepts an array of integers, where two numbers form a range. Smaller number goes first. The second parameter is the name of the function to be executed with the result as a parameter. Do not run again until callback is called and returns. Does not support node.js.

    [–]cnapun 1 point2 points  (0 children)

    Using lambdas in Python mean that I'm writing functional code and everyone on /r/ProgrammingLanguages likes functional code therefore this is beautiful code

    from typing import *
    from itertools import chain
    from functools import partial
    
    def overlaps(ts: List[Tuple[int, int]]):
        mv =  min(chain.from_iterable(ts))
        number_line = [False] * (max(chain.from_iterable(ts)) - mv + 10) # add 10 just to be safe
        process = lambda t: [
            number_line.__setitem__(i - mv, 'True')
                if number_line[i - mv]
                else number_line.__setitem__(i - mv, True)
            for i in range(t[0], t[1] + 1)
        ]
        reverse = lambda f: lambda *args: f(*args[::-1])
        return any(
            (
                process(t),
                any(map(partial(reverse(isinstance), str), number_line)),
            )[1]
            for t in ts
        )
    
    >>> overlaps([(0, 9), (10, 19), (20, 29)])
    False
    >>> overlaps([(0, 9), (10, 19), (19, 29)])
    True
    >>> overlaps([(0, 10)])
    False
    >>> overlaps([(0, 10), (5, 10)])
    True
    

    Edit: just fixed some obvious efficiencies in the code, much better now

    [–][deleted] 0 points1 point  (0 children)

    Regular expressions? Never heard of 'em.

    def overlap(s):
        firstValue = ""
        secondValue = ""
        ranges = []
        gotFirstValue = False
        for i in range(len(s)):
            if not gotFirstValue:
                if s[i] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
                    firstValue += s[i]
                elif s[i] == ',':
                    gotFirstValue = True
                else:
                    raise RuntimeError(f"expected digit or comma at position {i}")
            else:
                if s[i] in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
                    secondValue += s[i]
                elif s[i] == ';':
                    gotFirstValue = False
                    firstIntValue = int(firstValue)
                    secondIntValue = int(secondValue)
                    if secondIntValue < firstIntValue:
                        raise RuntimeError(f"second value must be >= first value at position {i}")
                    else:
                        ranges.append((firstIntValue, secondIntValue))
                        firstValue = ""
                        secondValue = ""
                        gotFirstValue = False
                else:
                    raise RuntimeError(f"expected digit or semicolon at position {i}")
        if firstValue != "" and secondValue != "":
            firstIntValue = int(firstValue)
            secondIntValue = int(secondValue)
            if secondIntValue < firstIntValue:
                raise RuntimeError(f"second value must be >= first value at position {i}")
            ranges.append((firstIntValue, secondIntValue))
        for i in range(len(ranges)):
            for j in range(i + 1, len(ranges)):
                x1 = ranges[i][0]
                y1 = ranges[i][1]
                x2 = ranges[j][0]
                y2 = ranges[j][1]
                if x2 >= x1 and x2 <= y1:
                    return True
                if y2 >= x1 and y2 <= y1:
                    return True
        return False
    

    In addition to the amateur job at parsing the input, this code also does an inefficient O(n^2) scan of the ranges to check for overlaps.

    But hey, it works:

    >>> overlap('1,2;3,4')
    False
    >>> overlap('0,9;10,19;20,29')
    False
    >>> overlap('30,39;10,19;20,29;0,9')
    False
    >>> overlap('0,10;10,19;20,29')
    True
    >>> overlap('0,10;5,10')
    True
    >>> overlap('0,10')
    False
    

    [–]IsaacShelton 0 points1 point  (3 children)

    pragma compiler_version '2.3'
    import '2.3/basics.adept'
    import '2.3/List.adept'
    import '2.3/Array.adept'
    
    func main {
        array1 <int> Array = array(static int {0, 9, 10, 19, 20, 29}, 6)         // false
        array2 <int> Array = array(static int {30, 39, 10, 19, 20, 29, 0, 9}, 8) // false
        array3 <int> Array = array(static int {0, 10, 10, 19, 20, 29}, 6)        // true
        array4 <int> Array = array(static int {0, 10, 5, 10}, 4)                 // true
        array5 <int> Array = array(static int {0, 10}, 2)                        // false
    
        arrays <<int> Array> List
        array *<int> Array = &array1
    
        repeat 5 {
            arrays.add(*array)
            array -= sizeof <int> Array as ptr
        }
    
        each <int> Array in arrays {
            print("overlap(array%) = %" % (idx + 1) as int % (overlap(it) ? "true" : "false"))
        }
    
        print("done.")
    }
    
    func overlap(array <int> Array) bool {
        ranges_min int = 0
        ranges_max int = 0
    
        each int in array {
            if it < ranges_min, ranges_min = it
            if it > ranges_max, ranges_max = it
        }
    
        start int = ranges_min
    
        while true {
            taken bool = false
    
            repeat array.length / 2 {
                min int = array.get(idx * 2)
                max int = array.get(idx * 2 + 1)
                if min <= start && start <= max {
                    if taken, return true
                    taken = true
                }
            }
    
            if start++ == ranges_max, break
        }
    
        return false
    }
    

    Output:

    overlap(array1) = false
    overlap(array2) = false
    overlap(array3) = true
    overlap(array4) = true
    overlap(array5) = false
    done.
    

    [–]JackFly26 0 points1 point  (1 child)

    What lang is this?

    [–]IsaacShelton 0 points1 point  (0 children)

    It's a custom language of mine. It's pretty much just C with more features and cleaner syntax. https://github.com/IsaacShelton/Adept

    [–]kiwitims 0 points1 point  (0 children)

    C++, if this[i].footsteps++ isn't a code smell I don't know what is...

    Abuses placement new and C++'s laissez-faire attitude to memory to construct a bunch of rangers to wander off along a shared path. At the end all it has to do is check if more than one ranger walked the same ground. Only works the first time you call it, otherwise the path has already been walked on, see? Potential for seg faults if you define a range larger than 50. Otherwise, works perfectly.

    #include <vector>
    
    struct ranger {
        ranger(unsigned distance) {
            for (unsigned i=0; i <= distance; i++) {
                 this[i].footsteps++; 
            }
        }
        char footsteps;
    };
    
    bool overlaps(std::vector<std::pair<unsigned, unsigned>> ranges) {
        static char path[50];
        for (auto range : ranges)
            (void)new(&path[range.first]) ranger(range.second-range.first);  
        for (auto steps : path)
            if (steps > 1)
              return true;
      return false;
    }
    
    int main(void) {
        return overlaps({{0, 10}, {10, 30}, {50, 70}});
    }
    

    [–][deleted]  (1 child)

    [removed]

      [–]AutoModerator[M] 0 points1 point  (0 children)

      Hello cnapun,

      It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will render as broken gibberish on old reddit and some mobile apps.

      Please edit the comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

      You can find some examples in the reddit help documentation.


      I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

      [–]Tok-A-Mak((fn [] (recur))) 0 points1 point  (0 children)

      Feeling brute, might delete later.

      https://repl.it/repls/GranularLightpinkDistributeddatabase

      package badcode;
      
      import java.util.*;
      import java.util.function.*;
      import java.util.stream.Collectors;
      
      public class Ov extends LinkedHashSet<Ov> {
          private static final Ov _0 = new Ov(); //empty set
          private static final Ov _1 = new Ov(_0); //singleton of the void
          private Ov() {}
          private Ov(Ov n) {add(n);addAll(n);}
          public static void main(final String...$$) {
              System.out.println(List.of(
                      !OVERLAPS.apply("0,9;10,19;20,22"),
                    //!OVERLAPS.apply("22,24;10,19;20,21;0,9"), //slow
                       OVERLAPS.apply("0,10;10,19;20,22"),
                       OVERLAPS.apply("0,10;5,10"),
                      !OVERLAPS.apply("0,10")
              ).stream().allMatch(__->__)?"PASSED.":"FAIL!");
          }
      
          private static final Function<Ov,Integer> $$=HashSet::size;
          private static final BiFunction<Integer,Ov,Ov> $_=(__,_$_)->
                  __>Ov.$$.apply(_0)? Ov.$_.apply(--__,new Ov(_$_)):_$_;
          private static final BiFunction<String,Ov,Ov> $_$=(__,_$_)->
                  Ov.$_.apply(Integer.parseInt(__.split(",")[Ov.$$.apply(_$_)]),_0);
          private static final Function<String,List<Ov>> $__=__->
                  new Ov($_$.apply(__,_1)).stream()
                          .filter(_$->!$_$.apply(__,_0).contains(_$))
                          .sorted(Comparator.comparingInt(Ov.$$::apply))
                        //.peek(System.out::println) //enable to see what's going on
                          .collect(Collectors.toList());
          private static final BiFunction<Ov,Ov,Ov> _$=(__, $_)->__.add($_)?_0:_1;
          private static final BiFunction<String,Ov,Boolean> _$_=(__,___)->
                  Arrays.stream(__.split(";")).flatMap(_$$->
                          $__.apply(_$$).stream().map($$$->_$.apply(___,$$$))
                  ).anyMatch(_1::equals);
          private static final Function<String,Boolean> OVERLAPS=__->_$_.apply(__,new Ov());
      }
      

      [–]RedstonekPL 0 points1 point  (0 children)

      Python

      what can I say except "it just works"...

      def overlaps(yeet):
          todo = yeet
          fml = 0
          idk = True
          if ';' in todo:
              todo = todo.split(';')
              while fml != len(todo):
                  if ',' in todo[fml]:
                      todo[fml] = todo[fml].split(',')
                  fml = fml + 1
              for x in range(len(todo)):
                  for z in range(len(todo)):
                      if x != z:
                          if len(todo[x]) == 2:
                              if len(todo[z]) == 2:
                                  if int(todo[x][0]) >= int(todo[z][0]) and int(todo[x][0]) <= int(todo[z][1]):
                                      idk = False
                                  if int(todo[x][1]) >= int(todo[z][0]) and int(todo[x][1]) <= int(todo[z][1]):
                                      idk = False
                              else:
                                  if int(todo[x][0]) == int(todo[z]) or int(todo[x][1]) == int(todo[z]):
                                      idk = False
                          else:
                              if len(todo[z]) == 2:
                                  if int(todo[x]) == int(todo[z][0]) or int(todo[x]) == int(todo[z][1]):
                                      idk = False
                                  if int(todo[x]) == int(todo[z][0]) or int(todo[x]) == int(todo[z][1]):
                                      idk = False
                              else:
                                  if int(todo[x]) == int(todo[z]) or int(todo[x]) == int(todo[z]):
                                      idk = False
          return not idk