Xah Talk Show 2022-09-16 Coding Challenge, Get the Odd Count. WolframLang vs Python Ruby JavaScript PHP Haskell

vidthumb zPs5vejJ8GA
  • https://youtu.be/zPs5vejJ8GA
  • Xah Talk Show 2022-09-16 Coding Challenge, Get the Odd Count. WolframLang vs Python Ruby JavaScript PHP Haskell

Georrg's Coding Challenge 2022-09-15 Get the Odd Count

Create a function f that when given an array of numbers, returns the number that appears an odd amount of times.

Only one number will ever appear an odd number of times, and there will always be one number that appears an odd amount of times.

e.g.
f([4]) //=> 4
f([0]) //=> 0
f([1,1,2,3,3]) //=> 2
f([1,7,1,7,3,7,3]) //=> 7

Try to think of the shortest solution possible in your language.

Put your solutions in threads and I'll judge the winners 🥇🥈🥉 D

WolframLang solution

count number of occur for each and every item, return the item that's odd count.

most intuitive algorithm: build a dict, by go thru the list, for each item, add to the hash. if it already exist, inc value by 1. else, add to hash with value of 1.

another, get all unique items in the list. (because, the most of the time, the unique items will be a small subset of the list). then, you still need to count, the occurrence of each uniq item.

another way, sort the whole list first. advantage being that, when you go thru the list, and when you see a diff number, then you know, the current number no longer occur.

xlist = {1,7,1,7,3,7,3};

(* result of Tally, essentially is the solution *)
Tally[ xlist ] === {{1, 2}, {7, 3}, {3, 2}};

(* first solution *)
getOdd1 = Function[ First@SelectFirst[ Tally@#, ((OddQ[ #[[2]] ]) &) ] ];

(* 2nd solution. pattern matching *)
getOdd2 = (( Cases[Tally[ # ], {_, _?OddQ }, {1}, 1 ][[1, 1]]) &) ;

(* 3rd solution. use transpose to avoid lots of taking parts. *)
getOdd3 = ((Module[{x = Transpose@Tally@#}, First[ x ][[ Position[ x[[2]], _?OddQ, {1}, 1 ][[1, 1]] ]] ]) &) ;

(* 4th solution. faster *)
getOdd4 = ((Module[{x = Transpose@Tally@#}, First@ Extract[ First@ x, Position[ x[[2]], _?OddQ, {1}, 1 ] ] ]) &);

getOdd1[xlist]
getOdd2[xlist]
getOdd3[xlist]
getOdd4[xlist]

code to generate input

xNlengh = 11;
xMaxDistinctSetLength = Ceiling[ xNlengh/2 ]
xValMin = 1;
xValMax = xMaxDistinctSetLength * 2;
xDistinctSet = Table[ RandomInteger[{ xValMin, xValMax }], {xMaxDistinctSetLength} ]