go-compression / go-compression.github.io

The Hitchhiker's Guide to Compression
https://go-compression.github.io/
MIT License
136 stars 9 forks source link

Clarification on LZSS's `elements_in_array` function #4

Closed taufiq closed 3 years ago

taufiq commented 3 years ago

Hey just read up on the LZSS implementation and I wanted to clarify the logic in the elements_in_array function. Link to page

This is the function:

def elements_in_array(check_elements, elements):
    i = 0
    offset = 0
    for element in elements:
        if len(check_elements) <= offset:
            # All of the elements in check_elements are in elements
            return i - len(check_elements)

        if check_elements[offset] == element:
            offset += 1
        else:
            offset = 0

        i += 1
    return -1

I was wondering why the <= operator was used for if len(check_elements) <= offset. If you wanted to check if all the elements in check_elements are in elements, wouldn't the == operator suffice?

phillipcutter commented 3 years ago

Hey taufiq,

You're absolutely right, to check if all elements in check_elements are in elements, the == operator works instead of the <= operator. I think I wrote it that way because I learned that you should always write while i > 10 not while i != 10 in the impossible case that i is incremented twice and since then I try to change == operations on integers to include corner cases with less than or greater than signs.

taufiq commented 3 years ago

ahhh alright i see