How can I pair socks from a pile efficiently?

后端 未结 30 1174
旧巷少年郎
旧巷少年郎 2020-11-27 08:37

Yesterday I was pairing the socks from the clean laundry and figured out the way I was doing it is not very efficient. I was doing a naive search — picking one sock and

30条回答
  •  我在风中等你
    2020-11-27 09:29

    Cost: Moving socks -> high, finding/search socks in line -> small

    What we want to do is reduce the number of moves, and compensate with the number of searches. Also, we can utilize the multithreded environment of the Homo Sapiens to hold more things in the descision cache.

    X = Yours, Y = Your spouses

    From pile A of all socks:

    Pick two socks, place corresponding X sock in X line, and Y sock in Y line at next available position.

    Do until A is empty.

    For each line X and Y

    1. Pick the first sock in line, search along the line until it finds the corresponding sock.

    2. Put into the corresponding finished line of socks.

    3. Optional While you are searching the line and and the current sock you are looking at is identical to the previous, do step 2 for these socks.

    Optionally to step one, you pick up two sock from that line instead of two, as the caching memory is large enough we can quickly identify if either sock matches the current one on the line you are observing. If you are fortunate enough to have three arms, you could possibly parse three socks at the same time given that the memory of the subject is large enough.

    Do until both X and Y is empty.

    Done

    However, as this have simillar complexity as selection sort, the time taken is far less due to the speeds of I/O(moving socks) and search(searching the line for a sock).

提交回复
热议问题