New answers tagged

0

GolfScript, 19 bytes ..|:i;{i,\i\-:i,-}% Explanation! ..|:i;{i,\i\-:i,-}% #Distinct sieve .. #Duplicate twice. Stack is [A A A] | #Binary OR. Removes duplicates. Stack is [A (A|A)] :i; #Call this A|A i, and remove it from the stack. [A], i=A|A { }% #Block notation. For each element in the ...


1

C++ (gcc), 94 bytes #import<regex> int f(int c,int*a){int s=0,d=0;for(std::sort(a,a+c);c-->d;)s+=a[c]-a[d++];c=s;} Port of the PHP solution. Kudos to Titus! Input size of the array and a non-const mutable array. Output the minimum number of moves required to equalize the array. -4 bytes thanks to ceilingcat! Try it online!


0

Perl 5 -ap, 39 bytes map$\+=abs$_-(sort{$a-$b}@F)[@F/2],@F}{ Try it online!


1

05AB1E, 4 bytes δαOß I know there is already an existing 4-bytes 05AB1E answer using the median builtin Åm, but I decided to post this alternative 4-byter without this builtin. Try it online or verify all test cases. Explanation: δ # Apply the following command double-vectorized on the given two arguments, # which will use the input-list twice ...


0

PowerShell, 52 bytes ($a=$args|sort)|%{$_-$a[--$i]}|%{$s-=$_*($_-lt0)} $s Try it online!


2

Java 8, 116 bytes With java.util.List<Integer> as parameter, which has a short sort-builtin, but is longer to retrieve a value at a given index: L->{L.sort(null);int r=0,l=L.size(),k=l;for(;k-->0;)r+=Math.abs(L.get(k)-(L.get(l/2+~l%2)+L.get(l/2)>>1));return r;} Try it online. With int[] (integer-array) as parameter, which has a long ...


0

PowerShell, 115 bytes function f($i){$m=($i|sort)[[int](($i.Count-1)/2)];return($j+=$i.ForEach({([math]::Abs($m-$_))})|measure -Sum).Sum} Try it online!


1

Ruby, 38 bytes ->a{a.map{|x|a.sum{|y|(y-x).abs}}.min} Try it online!


0

Haskell, 116 bytes p=replicate []&_=[] f&(x:xs)=(p x$minimum$take x f)++(drop x f)&xs f%n|(q,r)<-divMod(length f)n=f&((p r$q+1)++p n q) Try it online! The % operator is the bucket and minimize function, where f is the list and n is the bucket size. The & operator is a helper that repeats x times the minimum of the first x elements ...


1

Ruby, 91 77 bytes ->l,n{(0..z=l.size).flat_map{|x|(k=l.slice!(0,z/n+(z%n>x ?1:0))).map{k.min}}} Try it online!


1

Haskell, 158 145 bytes Thank you @SirBogman and @PostRockGarfHunter for saving 13 bytes and for the great tip Please feel free to improve it. l%n=map(minimum.o)[0..t-1]where(t,w,v,g,a)=(length l,t`div`n,w+1,t`mod`n*v,map(l!!));n&b=div n b*b;o i|i<g=a[i&v..i&v+w]|b<-g+(i-g)&w=a[b..b+w-1] Explanation list % n= map (minimum . ...


Top 50 recent answers are included