DEV Community

loading...

Discussion on: Coding Puzzles: Week of 4/8

Collapse
laurieontech profile image
Laurie
function stray(arr) {
    return arr.reduce((a, b) => a ^ b)
}
Collapse
joshuagilless profile image
Joshua Gilless

XOR is a great idea, thanks!

Thread Thread
laurieontech profile image
Laurie

Math for the win! :D

Collapse
jacobmgevans profile image
Jacob Evans

Well I can't think of a better answer for this particular problem domain.

Collapse
threeheadedcerb profile image
russ

What is this necromancy?

Thread Thread
laurieontech profile image
Laurie • Edited

Haha, bitwise xor. Since it's immutable and commutative it'll reduce down to the stray!

I should add that this only works because it’s an odd number of elements in the array. An even number of matching elements cancel each other out to result in the “stray”.

Thread Thread
threeheadedcerb profile image
russ

Oh my, it even works in python!

def stray(arr):
    count = {}
    for index, i in enumerate(arr):
        count[i] = count.setdefault(i, 0) + 1
        if index >= 2 and len(count.keys()) > 1:
            break
    return next(k for k, v in count.items() if v == 1)

from functools import reduce

def intstray(arr: [int]):
    return reduce(lambda x,y: x ^ y, arr)

assert(intstray([1, 1, 2]) == 2)
#nope..!
#assert(intstray([1, 1, 2, 1]) == 2)
assert(intstray([17, 17, 3, 17, 17, 17, 17]) == 3)
assert(intstray([1, 2, 2]) == 1)
assert(stray(["bob", "bob", "bob", "steve", "bob"]) == "steve")
Thread Thread
laurieontech profile image
Laurie

This is one of those moments when I wish gifs worked better on Dev. But yay!

Thread Thread
aspittel profile image
Ali Spittel Author

They should work in normal image markdown!

Thread Thread
laurieontech profile image
Laurie

Whaaa?! How did I not know this! ...game changer

Collapse
mihassan profile image
Md Imrul Hassan

Same idea in Haskell:

import Data.Bits

stray :: [Int] -> Int
stray = foldl1 xor