Shortest Program to Sort a List of numbers into Odd and Even Category

13

5

In the New Modern Times, when Charlie Chaplin encounters a computer, he is employed in the sorting Yard, as a validator to determine if the workers are correctly sorting the items. The Items in question are packets of marbles. Packets with Odd number of Marbles are stacked in the Red Basket and Packets with Even Number of Marbles are stacked in the Blue Basket.

Charlie Chaplin is supposed to punch the program that would validate if there is any anomaly in the sorting procedure. Mack Swain his immediate Boss, shares an algorithm which he needs to code.

Algorithm

L = List of Marble packets that's already sorted
L_ODD = List of packets with Odd Number of Marbles
L_EVEN = List of packets with Even Number of Marbles
Check_Digit = √(ΣL_ODD² + ΣL_EVEN²)

His Job is to determine the Check_Digit and match it with what ever value his Boss calculates.

Charlie Chaplin during his lunch hours, were able to sneak to Mack Swain's drawer and determine, that his drawer has a single card with punches on the first 46 32 columns (which means Mack was able to write a program with only 46 32 characters).

Charlie Chaplin would now need the help of all the code ninja's to write a program with as few lines as possible. He also announces a bonus of 50 points, if someone can come up with a program which is shorter than his Boss.

Summary

Given a list/array/vector of positive numbers (odd and even), you need to write a function, which would accept the array(int [])/vector<int>/list and calculate the root of the sum of the squares of the sums of odd and even numbers in the list.

The Size of the program is the size of the body of the function, i.e. excluding the size of the function signature.

Example

List = [20, 9, 4, 5, 5, 5, 15, 17, 20, 9]
Odd = [9, 5, 5, 5, 15, 17, 9]
Even = [20, 4, 20]
Check_Digit = √(ΣOdd² + ΣEven²) = 78.49203781276162

Note, the actual output might vary based on the implementation's floating point precision.

Score

Score is calculated as Σ(Characters in your Program) - 46.Score is calculated as Σ(Characters in your Program) - 32. Apart from the regular upvoting from the community, the lowest negative score would receive an additional bonus of 50 points.

Edit

  1. The offset that was used to calculate the Score has been changed from 46 to 32. Note, this would not affect the leader-board/ bounty eligibility or invalidate any solution.

Verdict

After a gruesome duel between the Ninjas, Mr. Chaplin received some wonderful answers. Unfortunately few of the answers tried to take undue advantage of the rule and was not very useful. He actually wanted a fair duel and answers where the logic was coded within the function signatures would eventually mean the function signature is an integral part of the solution. Finally, Ninja FireFly was the clear winner and awarded him the bonus he well deserves. Leaderboard (updated every day)

╒══════╤═════════════════╤══════════════╤═════════╤════════╤═══════╕
├ Rank │      Ninja      │   Dialect    │ Punches │ Scores │ Votes ┤
╞══════╪═════════════════╪══════════════╪═════════╪════════╪═══════╡
│  0   │     FireFly     │      J       │   17    │  -15   │   6   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  1   │     tmartin     │     Kona     │   22    │  -10   │   2   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  2   │ Sven Hohenstein │      R       │   24    │   -8   │   7   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  3   │    Ben Reich    │  GolfScript  │   30    │   -2   │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  4   │    mollmerx     │      k       │   31    │   -1   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  5   │ David Carraher  │ Mathematica  │   31    │   -1   │   3   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  6   │     tmartin     │      Q       │   34    │   2    │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  7   │     daniero     │      dc      │   35    │   3    │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  8   │    psion5mx     │    Python    │   38    │   6    │   2   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  9   │       O-I       │     Ruby     │   39    │   7    │   5   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  10  │      gggg       │    Julia     │   40    │   8    │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  11  │ FakeRainBrigand │  LiveScript  │   50    │   18   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  12  │    Sylwester    │    Perl5     │   50    │   18   │   2   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  13  │     daniero     │     Ruby     │   55    │   23   │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  14  │    vasuakeel    │ Coffeescript │   57    │   25   │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  15  │      dirkk      │    XQuery    │   63    │   31   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  16  │  crazedgremlin  │   Haskell    │   64    │   32   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  17  │   Uri Agassi    │     Ruby     │   66    │   34   │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  18  │     Sumedh      │     JAVA     │   67    │   35   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  19  │      Danny      │  Javascript  │   67    │   35   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  20  │     deroby      │      c#      │   69    │   37   │   1   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  21  │  Adam Speight   │      VB      │   70    │   38   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  22  │    Andrakis     │    Erlang    │   82    │   50   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  23  │      Sp0T       │     PHP      │   85    │   53   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  24  │    brendanb     │   Clojure    │   87    │   55   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  25  │  Merin Nakarmi  │      C#      │   174   │  142   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  26  │    Boopathi     │     JAVA     │   517   │  485   │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  27  │      Noyo       │     ES6      │    ?    │   ?    │   2   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  28  │     shiona      │   Haskell    │    ?    │   ?    │   0   │
├──────┼─────────────────┼──────────────┼─────────┼────────┼───────┤
│  29  │      Vivek      │     int      │    ?    │   ?    │   0   │
└──────┴─────────────────┴──────────────┴─────────┴────────┴───────┘

Abhijit

Posted 2014-02-05T19:51:11.973

Reputation: 2 841

8Why does the lowest score need a bonus, they already won? – gggg – 2014-02-05T20:02:29.760

6Moreover, the offset of 46 doesn't change anything regarding the order. – Howard – 2014-02-05T20:06:36.670

@gggg I think they mean they'll give the lowest scoring answer a +50 bounty. – None – 2014-02-05T23:27:48.420

1@gggg: I will actually start a bounty as soon as I am allowed to. So that's what I meant by bonus. – Abhijit – 2014-02-06T02:01:24.527

@Howard: the lowest negative score would receive an additional bonus of 50 points. So in order to qualify for Bounty, there should be at least one answer which fairs better than 46 characters. It seems now that we already have few :-) – Abhijit – 2014-02-06T02:03:00.330

"Score is calculated as Σ(Characters in your Program) - 32 [...] an additional bonus of 50 points.". So it isn't code-golf, which, according to the tag, simply requires *the fewest bytes of source code* . – r.e.s. – 2014-02-06T13:10:24.657

@res: If you closely observe, the lowest score, is suppose to have fewest bytes. So this still remains a code-golf. – Abhijit – 2014-02-06T15:49:52.320

Hm, looks like scores were never updated.. @Abhijit, did you see the entries with the score of -31? :] – Noyo – 2014-02-16T23:47:53.250

@Noyo: I have added a verdict paragraph, which might answer your doubt as to why your answer was not selected as the winning solution. – Abhijit – 2014-02-17T16:13:36.353

1Aw, rats. Here I thought the rules were there to be taken advantage of, and that cleverness would be rewarded here. ;] Still, fun question, and good job, everyone! – Noyo – 2014-02-17T16:49:49.530

Answers

7

J, 18 17 chars - 32 = ⁻15

[:+/&.:*:2&|+//.]

(As a "function body"; has to be parenthesized or bound to a name.)

Explanation

I tried making an exploded view of what each piece does, like Tobia does in APL answers.

               +//. ]    NB. sum up partitions
           2&|           NB.   given by equality on (x mod 2)
        *:               NB. square,
   +/                    NB. sum,
     &.:                 NB. then revert the squaring (square-root)
                         NB. (f&.:g in general acts like g⁻¹(f(g(x))))
[:                       NB. (syntax to indicate composition of +/&.:*: and (2&| +//. ]))

+/&.:*: could be replaced with |@j./ making use of O-I's complex magnitude trick to save yet another two characters.

Example

   f =: [:+/&.:*:2&|+//.]
   f 20 9 4 5 5 5 15 17 20 9
78.492

FireFly

Posted 2014-02-05T19:51:11.973

Reputation: 7 107

9

ES6, (48 - 32) = 16 (1 - 32) = -31

Original version:

f=l=>(e=o=0)+l.map(x=>x%2?e+=x:o+=x)&&Math.hypot(e,o)

Entire function definition is 53 characters, body only is 48.

Updated version, taking full advantage of the problem definition and moving pretty much everything out of the body and into the signature:

f=(l,e=0,o=0,g=x=>x%2?e+=x:o+=x,c=l.map(g)&&Math.hypot(e,o))=>c

New function definition is now 63 "punches" total, but function BODY is now just ONE DAMN CHARACTER LONG. Plus it no longer corrupts the global namespace! :D

Usage:

>>> f([20, 9, 4, 5, 5, 5, 15, 17, 20, 9])
78.49203781276161

Noyo

Posted 2014-02-05T19:51:11.973

Reputation: 943

...and now I feel kinda dirty. :] – Noyo – 2014-02-10T10:28:58.060

+1, I've deleted my ES6 solution since yours is way better :) – Florent – 2014-02-10T14:58:22.717

Haha, thanks. We'll see if the rules are changed once the OP sees this.. ;] – Noyo – 2014-02-10T18:34:26.753

1Well, it looks like the rules were indeed implicitly changed, even after an answer was accepted and the bounty awarded. Oh well! I still consider this to be the solution with the lowest score according to the rules of the challenge. :] – Noyo – 2014-02-17T16:42:55.220

1Actually reminds me of those c code-contests where people would do all kind of trickery in the preprocessor making a seemingly 'simple' function returning very complex stuff. The net result was off course that compiling took hours & hours (& hours) while the actual execution would return pi up to 100k numbers (or something like that) in a fraction of a second as the result was pretty much hard-coded into the binaries. Anyway, although I think we both know you were were cheating I'd say "well played sir" =P – deroby – 2014-02-18T08:25:12.423

7

R, (24 − 32) = −8

f=function(x)
    sum(by(x,x%%2,sum)^2)^.5  

The function body consists of 24 characters.

Usage:

f(c(20, 9, 4, 5, 5, 5, 15, 17, 20, 9))
[1] 78.49204

Sven Hohenstein

Posted 2014-02-05T19:51:11.973

Reputation: 2 464

Ergh!!! You have exactly the same solution as I just elaborated!! sqrt(sum(by(x,x%%2,sum)^2)) I only have not optimized the sqrt.... damn :-) +1 :-) PS: it is interesting how by seems to be out at first because of the shitty output format but when you run sum over it it is fixed ;-) – Tomas – 2014-02-10T11:59:23.293

@Tomas In this example, by returns a one-dimensional array. One shouldn't judge the function by the result of the print.by function. – Sven Hohenstein – 2014-02-12T07:30:06.093

Nope, by doesn't return an array (btw, what you mean by "array"? There are none in R. You probably meant a vector), neither a vector. by returns object of class by. – Tomas – 2014-02-14T11:00:54.263

@Tomas There are arrays in R. Have a look at ?array. Furthermore, is.array(by(1,1,I)) returns TRUE.

– Sven Hohenstein – 2014-02-14T11:24:35.637

6

Ruby 2.1+ — (39 characters total - 7 non-body - 32 offset = 0)

Slightly different approach. I create a complex number a+b*i such that a and b are the sums of the even and odd numbers in list, respectively. Then I just take the absolute value.

f=->l{l.reduce{|s,x|s+x*1i**(x%2)}.abs}

My previous solution, which is 5 characters longer but works on 1.9.3+:

f=->l{l.reduce{|s,x|s+x*?i.to_c**(x%2)}.abs}

On a final note, if Rails + Ruby 2.1+ were allowed, we can use Array#sum to get the body down to a mere 25 characters:

l.sum{|x|x+1i**(x%2)}.abs

O-I

Posted 2014-02-05T19:51:11.973

Reputation: 759

Very clever, I like it! This would save me a few chars in J as well. – FireFly – 2014-02-09T00:05:12.813

Thanks, @FireFly. Yours is nice. Gotta learn J sometime. Cheers! – O-I – 2014-02-09T00:16:50.997

You only have to count the body of the function, I'd say 37 chars. – steenslag – 2014-02-09T16:58:08.823

Thanks for the tip @steenslag. Updated. I also shaved off an additional 5 characters by using the new Complex literal shorthand. Only works in Ruby 2.1 and above, though. – O-I – 2014-02-09T20:26:48.293

5

Python 2.7: 45, nay: 40, nay: 38 - 32 = 6

Nothing very new here, just a combination of the complex number trick I saw in the recent Pythagoras challenge, lambda for compactness, and syntax/parenthesis minimisation:

lambda x:abs(sum(a*(1-a%2+a%2*1j)for a in x))

Update - saved a few chars. Thanks to @DSM for the trick of raising the complex component to 0/1.

lambda x:abs(sum(a*1j**(a%2)for a in x))

Ok, reading the question and recognising the 'body of the function' count rule saves another 2 chars:

def f(x):
    return abs(sum(a*1j**(a%2)for a in x))

iPython testing:

In [650]: x = [20, 9, 4, 5, 5, 5, 15, 17, 20, 9]

In [651]: print (lambda l:abs(sum(a*(1-a%2+a%2*1j)for a in l)))(x)
78.4920378128

...

In [31]: def f(x):
   ....:     return abs(sum(a*1j**(a%2)for a in x))
   ....:

In [32]: f(x)
Out[32]: 78.49203781276162

psion5mx

Posted 2014-02-05T19:51:11.973

Reputation: 121

nice! it's like the problem was build exactly for abs of complex numbers – jozxyqk – 2014-02-14T15:04:13.053

4

APL (27 - 46 = -19)

{.5*⍨+/2*⍨+⌿⍵×[1]z,⍪~z←2|⍵}

e.g.:

      {.5*⍨+/2*⍨+⌿⍵×[1]z,⍪~z←2|⍵} 20 9 4 5 5 5 15 17 20 9
78.49203781

marinus

Posted 2014-02-05T19:51:11.973

Reputation: 30 224

4

Mathematica 31-32 = -1

√Tr[(Tr/@GatherBy[#,OddQ])²]//N &

GatherBy[#,OddQ] produces the even-packet, odd-packet lists.

The inner Trfinds the totals, both of which are squared and then summed (by the outer Tr).

N converts from an irrational number (the square root of an integer) to a decimal approximation.

Example

√Tr[(Tr/@GatherBy[#,OddQ])²]//N &[{9, 5, 5, 5, 15, 17, 9, 20, 4, 20}]

78.492


If f[n_]:= is not included in the count, an additional character can be saved.

    f[n_]:=
    √Tr[(Tr/@GatherBy[n,OddQ])²]//N 

Example

f[{9, 5, 5, 5, 15, 17, 9, 20, 4, 20}]

78.492

DavidC

Posted 2014-02-05T19:51:11.973

Reputation: 24 524

3

Perl5 : (50 - 32 = 18)

map{$0[$_&1]+=$_}@ARGV;print sqrt$0[0]**2+$0[1]**2

Sylwester

Posted 2014-02-05T19:51:11.973

Reputation: 3 678

+1 perhaps you may save a few chars by using say instead of print and <> instead of @ARGV (while supplying the args on the STDIN instead of on the command-line) – Tomas – 2014-02-09T18:47:09.487

@Tomas Wouldn't using say require a use? switching from an argument array to <> would require an additional split/ /,. – Sylwester – 2014-02-09T23:46:21.337

>

  • No, say feature can be enabled from the command line. 2) I guess no split would be needed if you provide those numbers each per line.
  • – Tomas – 2014-02-10T10:04:58.443

    3

    dc 3 (35 - 32)

    Using arrays, as suggested by @Tomas. This saves some of characters because I can calculate the parity of each number and use it as an index, instead of tweaking the with parity as a method of branching and putting the right values in the right registers. Also it turns out that arrays will give you a 0 even if the array/index haven't been used, so you don't have to initialize anything.

    [d2%dsP;S+lP:Sz0<L]dsLx0;S2^1;S2^+v
    

    Assumes the numbers are already on the stack, and leaves the result as the only value left when it's done.

    Test:

    $ dc  
    20 9 4 5 5 5 15 17 20 9  
    [d2%dsP;S+lP:Sz0<L]dsLx0;S2^1;S2^+v 
    p
    78
    

    dc 16 (48 - 32)

    First version using registers o and e to store odd and even numbers.

    0dsose[dd2%rd1+2%*lo+so*le+sez0<x]dsxxle2^lo2^+v
    

    daniero

    Posted 2014-02-05T19:51:11.973

    Reputation: 17 193

    1

    +1 for using dc. Ha ha sose ;-) perhaps you could get shorter result using dc array commands?

    – Tomas – 2014-02-10T12:07:01.887

    1@Tomas thanks a bunch! I first dismissed the idea of using arrays for some stupid reason, but after your suggestion I tried again and they turned out to be very helpful! A register had to be used to temporarily store the parity, but overall I think this is a much more elegant solution. – daniero – 2014-02-10T16:33:53.510

    You are welcome, I knew this would help :-) – Tomas – 2014-02-11T10:02:24.123

    3

    Kona, 22 - 32 = -10

    {(+/(+/'x@=x!2)^2)^.5}
    

    tmartin

    Posted 2014-02-05T19:51:11.973

    Reputation: 3 917

    2

    Prolog (73 - 32 = 41)

    Here we count everything after ':-' as the function body.

    f([],0,0,0).
    f([H|T],O,E,X):-(1 is H mod 2,f(T,S,E,_),O is H+S,!;f(T,O,S,_),E is H+S),sqrt(O*O+E*E,X).
    

    Call function like so:

    f([20, 9, 4, 5, 5, 5, 15, 17, 20, 9],_,_,X).
    

    mwcoomber

    Posted 2014-02-05T19:51:11.973

    Reputation: 61

    2

    Julia, 40-46=-6

    Implementation

    function f(l)
        a=sum(l);b=sum(l[l%2 .==1]);hypot(a-b,b)
    end
    

    Output

    julia> f([20, 9, 4, 5, 5, 5, 15, 17, 20, 9])
    78.49203781276161
    

    gggg

    Posted 2014-02-05T19:51:11.973

    Reputation: 1 715

    2

    Python, 9 (55 - 46)

    lambda x:sum([sum([i*(d-i%2) for i in x])**2for d in(0,1)])**0.5
    

    Using a lambda function saves some bytes on newlines, tabs and return.

    Example:

    x = [20, 9, 4, 5, 5, 5, 15, 17, 20, 9]
    print (lambda x:sum([sum([i*(d-i%2) for i in x])**2for d in(0,1)])**0.5)(x)
    78.4920378128
    

    Flogo

    Posted 2014-02-05T19:51:11.973

    Reputation: 161

    2

    Ruby, 55 - 46 = 9

    f=->a{h=[0,0];a.map{|v|h[v%2]+=v};e,o=h;(e*e+o*o)**0.5}
    

    Test:

    f[[20, 9, 4, 5, 5, 5, 15, 17, 20, 9]] => 78.49203781276162`
    

    daniero

    Posted 2014-02-05T19:51:11.973

    Reputation: 17 193

    1You can use an array for h: f=->a{h=[0,0];a.map{|v|h[v%2]+=v};e,o=h;(e*e+o*o)**0.5} – Neil Slater – 2014-02-06T10:30:49.847

    @NeilSlater doh! Thanks :) – daniero – 2014-02-06T13:57:18.493

    2

    Q, 34 - 32 = 2

    {sqrt sum{x*x}(+/')(.)x(=)x mod 2}
    

    .

    q){sqrt sum{x*x}(+/')(.)x(=)x mod 2} 20 9 4 5 5 5 15 17 20 9
    78.492037812761623
    

    tmartin

    Posted 2014-02-05T19:51:11.973

    Reputation: 3 917

    2

    Ruby (66 - 32 = 34)

    f=->a{o,e=a.partition(&:odd?).map{|x|x.reduce(:+)**2};(e+o)**0.5}
    

    test:

    f.([20, 9, 4, 5, 5, 5, 15, 17, 20, 9])
    => 78.49203781276162 
    

    Uri Agassi

    Posted 2014-02-05T19:51:11.973

    Reputation: 281

    1Math.hypot *a.partition(&:odd?).map{|x|eval x*?+} shaves off a few chars – steenslag – 2014-02-09T17:02:10.550

    2

    Coffeescript, (57 - 32 =25)

    Implementaion

    f=(a)->r=[0,0];r[e%2]+=e for e in a;[e,o]=r;(e*e+o*o)**.5
    

    Vasu Adari

    Posted 2014-02-05T19:51:11.973

    Reputation: 941

    I don't know coffeescript, but i wonder if you can remove the space after the += and change 0.5 to .5 – user12205 – 2014-02-09T09:49:46.577

    2

    GolfScript 30

    .{2%},]{{+}*}/.@\-]{2?}/+2-1??
    

    I don't think GolfScript has much of a chance on this one!

    Ben Reich

    Posted 2014-02-05T19:51:11.973

    Reputation: 1 577

    2

    c#: 69-32=37

    double t=l.Sum(),o=l.Sum(x=>x*(x%2)),e=t-o;return Math.Sqrt(o*o+e*e);
    

    Full code:

    class Program
    {
        static void Main(string[] args)
        {
            int[] list = { 20, 9, 4, 5, 5, 5, 15, 17, 20, 9 };
            Console.WriteLine(F(list));
            Console.ReadKey();
        }
    
        static double F(int[] l)
        {
            double t = l.Sum(),  // total sum of all elements
                   o = l.Sum(x => x * (x % 2)),  // total of odd elements, if even %2 will return zero
                   e = t - o; // even = total - odd
            return Math.Sqrt(o * o + e * e);
        }        
    }
    

    PS: Just for fun, this works too, sadly it doesn't change the number of characters needed:

    double t=l.Sum(),o=l.Sum(x=>x*(x%2));return Math.Sqrt(t*t-2*o*(t-o));
    

    deroby

    Posted 2014-02-05T19:51:11.973

    Reputation: 141

    1

    C# 174

    using System;class P{static void Main(){double[] L={20,9,4,5,5,5,15,17,20,9};double O=0,E=0;foreach(int i in L){if(i%2==0)E+=i;else O+=i;}Console.Write(Math.Sqrt(E*E+O*O));}}
    

    Readable

    using System;
    class P
    {
      static void Main()
      {
          double[] L = { 20, 9, 4, 5, 5, 5, 15, 17, 20, 9 };
          double O = 0, E = 0;
          foreach (int i in L)
          {
            if (i % 2 == 0)
                E += i;
            else
                O += i;
          }
          Console.Write(Math.Sqrt(E * E + O * O));
       }
    }
    

    Charlie's Output

    Merin Nakarmi

    Posted 2014-02-05T19:51:11.973

    Reputation: 247

    You haven't golfed this at all. We're trying to get a solution that fits on the boss's punchcard! – Riking – 2014-02-06T00:24:32.730

    Why not? Explain Please. – Merin Nakarmi – 2014-02-06T00:41:56.623

    2Your code is fully indented with spaces all over. Code golf is all about getting the lowest character count. This question is tagged [tag:code-golf]. – Riking – 2014-02-06T01:14:52.910

    Thanks Riking. I edited it. I have fewer characters now.:) – Merin Nakarmi – 2014-02-06T01:36:52.230

    I think the list is supposed to be provided as input, not hardcoded. – Timwi – 2014-02-06T14:48:50.683

    Math.Sqrt(L.GroupBy(x=>x%2).Select(x=>x.Sum()).Select(x=>x*x).Sum()); You can Console.Write on the same line, and accept the input from args as a main parameter. – Benjamin Gruenbaum – 2014-02-09T07:20:15.373

    Thanks Benjamin. But the Main method accepts only string as argument and we will have to convert it to double. – Merin Nakarmi – 2014-02-11T17:46:16.693

    1

    Matlab (44 - 46 = -2)

    Function body is 44 characters:

    C=mod(A,2)>0;O=(sum(A(C))^2+sum(A(~C))^2)^.5
    

    Total function as follows:

    function O = Q(A)
    C=mod(A,2)>0;O=(sum(A(C))^2+sum(A(~C))^2)^.5
    end
    

    Tests of the function:

    >> A = [20 9 4 5 5 5 15 17 20 9];
    >> Q(A)
    
    O =
    
       78.4920
    
    
    ans =
    
       78.4920
    

    >> B = [8 3 24 1 9 8 4 5 52];
    >> Q(B)
    
    O =
    
       97.6729
    
    
    ans =
    
       97.6729
    

    virusered

    Posted 2014-02-05T19:51:11.973

    Reputation: 11

    1

    Python 2.7 - 64-46 = 18

    This could be shorter using some zip magic, but for now:

    (sum(s for s in x if s%2)**2+sum(s for s in x if s%2==0)**2)**.5
    

    For completion, it turns out you can do zip magic, but it costs you more (by a few characters), so the above stands, unless someone can improve either of these:

    sum(map(lambda i:sum(i)**2,zip(*[[(0,i),(i,0)][i%2]for i in x])))**.5
    

    user8777

    Posted 2014-02-05T19:51:11.973

    Reputation:

    1You don't need the [square brackets] inside the sum(). – daniero – 2014-02-06T00:26:13.783

    1I think you could improve this significantly by working in the complex plane, e.g. abs(sum(1j**(i%2)*i for i in x)). – DSM – 2014-02-06T02:46:15.230

    @DSM That is insane! I never thought of that. I can't edit that in its too much changed, but please make and answer so I can upvote it! – None – 2014-02-06T02:48:12.100

    @DSM: I had a similar version in my mind, but yours is sleeker – Abhijit – 2014-02-06T02:54:36.107

    Does Python accept !s%2? That's at least an incremental change you can accept – Not that Charles – 2014-02-10T02:03:22.810

    @Charles: no, not !s%2, but that's a good idea: ~s%2 should work here. – DSM – 2014-02-10T15:37:05.727

    1

    Clojure = 87 - 46 = 41

    (defn cd [v]
      (let [a apply ** #(* % %)]
        (Math/sqrt(a + (map #(** (a + (% 1)))(group-by even? v))))))
    

    Hardly idiomatic, though.

    brendanb

    Posted 2014-02-05T19:51:11.973

    Reputation: 11

    1

    Haskell, 64C - 46 = 18

    c x=sqrt$fromIntegral$s(f odd x)^2+s(f even x)^2
    f=filter
    s=sum
    

    Not too difficult to read. Example run:

    *Main> c [1..10]
    39.05124837953327
    

    danmcardle

    Posted 2014-02-05T19:51:11.973

    Reputation: 695

    1

    PHP 85-32=53

    $a=$b=0;foreach($x as $q){if(($q%2)==0)$a=$a+$q;else$b=$b+$q;}echo sqrt($a*$a+$b*$b);

    This is the best i'ld come up being a newbie. I'm sure there must be some shorter versions as well.

    EDIT:

    A reduced version of the code could be:

    foreach($x as$q)($q%2)?$a=$a+$q:$b=$b+$q;echo sqrt($a*$a+$b*$b);
    

    This version only has 64 (21 less than the original answer) chars.

    Said so, 64-32=32

    Sp0T

    Posted 2014-02-05T19:51:11.973

    Reputation: 147

    Did it independently, got 58 base: foreach($l as$m)$m%2?$o+=$m:$e+=$m;echo sqrt($o*$o+$e*$e); – Yoda – 2014-02-21T12:11:40.707

    1

    int e=0,o=0;for(int i :n){if(i%2==0)e+=i;else o+=i;}System.out.println(Math.sqrt(e*e+o*o));

    Actual method in java code

    public static void checkDigit(int[] n)
    {
        int e=0,o=0;for(int i :n){if(i%2==0)e+=i;else o+=i;}System.out.println(Math.sqrt(e*e+o*o));
    }
    

    Test Class

    public class Sint
    {
        public static void main(String[] args)
        {
            if(args == null || args.length == 0)
                args = "20 9 4 5 5 5 15 17 20 9".split(" ");
            int[] n = null;
            try
            {
                n = new int[args.length];
                for(int i=0; i<args.length; i++)
                    n[i] = Integer.parseInt(args[i]);
                System.out.print("int array is: ");
                for(int dd : n) System.out.print(dd+", ");
                System.out.print("\n");
                checkDigit(n);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    
        public static void checkDigit(int[] n)
        {
            int e=0,o=0;for(int i :n){if(i%2==0)e+=i;else o+=i;}System.out.println(Math.sqrt(e*e+o*o));
        }
    }
    

    Vivek

    Posted 2014-02-05T19:51:11.973

    Reputation: 11

    1

    Erlang: 82C - 32 = 50

    fun(L)->F={lists,sum},O=[X||X<-L,X rem 2>0],E=F(L--O),math:sqrt(F(O)*F(O)+E*E)end.
    

    Erlang isn't great for this. Most shortcuts end up being more characters (tuples etc.)

    The only real things of note:

    • {lists,sum} is a function reference to lists:sum and can be called
    • Even numbers are calculated by subtracting -- (list subtract) the odd numbers list from the full list

    Can call using:

    fun(L)->F={lists,sum},O=[X||X<-L,X rem 2>0],E=F(L--O),math:sqrt(F(O)*F(O)+E*E)end([20,9,4,5,5,5,15,17,20,9]).
    

    Output: 78.49203781276162

    Andrakis

    Posted 2014-02-05T19:51:11.973

    Reputation: 361

    1

    VB.net (81c - 11c = 70) - 32 = 38

    Via liberal usage of the term Write a function

    Function(n)Math.Sqrt(n.Sum(Function(x)x Mod 2=0)^2+n.Sum(Function(x)x Mod 2=1)^2)
    

    Adam Speight

    Posted 2014-02-05T19:51:11.973

    Reputation: 1 234

    1

    XQuery, (63 - 32 = 31)

    Implementation

    declare default function namespace 'http://www.w3.org/2005/xpath-functions/math';
    declare function local:f($s) {
      sqrt(pow(fn:sum($s[. mod 2=0]),2)+pow(fn:sum($s[. mod 2=1]),2))
    };
    

    Output

    local:f((20, 9, 4, 5, 5, 5, 15, 17, 20, 9))
    

    BaseX was used as XQuery processor.

    Reinstate Monica - dirkk

    Posted 2014-02-05T19:51:11.973

    Reputation: 251

    1

    Haskell

    57 - 32 = 25

    Straight optimization of crazedgremlins answer:

    c x=sqrt$read$show$sum(odd%x)^2+sum(even%x)^2
    (%)=filter
    

    Optimizations:

    • read$show is shorter than fromIntegral - 3 chars
    • s=sum\n and two s's has total length of 8 chars, two sum's is just 6 chars. - 2 chars
    • making filter into operator does away with need of whitespace - 2 chars

    I also tried adding more stuff to the operator, but it ended up being just as long:

    c x=sqrt$read$show$odd%x+even%x
    (%)=(((^2).sum).).filter
    

    shiona

    Posted 2014-02-05T19:51:11.973

    Reputation: 2 889

    0

    Tcl, 60 bytes (bonuses not included yet)

    proc C L {lmap c $L {incr [expr $c%2] $c}
    expr hypot($0,$1)}
    

    Try it online!

    sergiol

    Posted 2014-02-05T19:51:11.973

    Reputation: 3 055

    0

    JAVA: 67-32=35

    inside function(int[] a) :

    int x=0,y=0;
    for(int i:a)
    {
    if(i%2==0)
    x+=i;
    else y+=i;
    }
    Math.hypot(x,y);
    

    Sumedh

    Posted 2014-02-05T19:51:11.973

    Reputation: 131

    C'mon guys atleast tell why you've down-voted the answer. Its a working code. – Sumedh – 2014-02-11T12:46:14.293

    I didn't downvote. But why i*i? I also get 1108.9891793881488 when I run your code with the sample input. – Danny – 2014-02-11T17:33:08.067

    I thought we need to square them first,then add them.....ΣEven² is actually (ΣEven)², while I took it as Σ(Even²). but I should've checked with sample input earlier. Thanks @Danny. – Sumedh – 2014-02-11T18:47:43.847

    If you're trying to make the code small, you can skip the curly braces and keep everything on one line. – daniero – 2014-02-11T18:55:13.317

    0

    JAVA 517 bytes

     public class Link 
        {
            public static void main(String[] args) 
            {
                int[]a={20, 9, 4, 5, 5, 5, 15, 17, 20, 9};
                int []b=new int[10];
                int[]c=new int[10];
                int j=0,k=0,l=0,m=0;
                for(int i=0;i<a.length;i++)
                {
                    if(a[i]%2==0)
                    {
                        b[j]=a[i];
                        j++;
                    }
                    else
                    {
                        c[k]=a[i];
                        k++;
                    }
                }
                for(int i=0;i<j;i++)
                {
                    l=l+b[i];
                }
                l=l*l;
                for(int i=0;i<k;i++)
                {
                    m=m+c[i];
                }
                m=m*m;
                l=l+m;
                double t=Math.sqrt(l);
                System.out.print(t);
            }
    
        }
    

    Boopathi

    Posted 2014-02-05T19:51:11.973

    Reputation: 179

    0

    Javascript 67-32=35

    function r(a){k=j=0;a.map(function z(i){i%2?j+=i:k+=i});return Math.sqrt(k*k+j*j)}
    

    Doesn't seem like there is an easy way of spliting the array into even's and odd's without defining another function :(

    console.log(r([20, 9, 4, 5, 5, 5, 15, 17, 20, 9]));
    78.49203781276162
    

    Danny

    Posted 2014-02-05T19:51:11.973

    Reputation: 1 563

    0

    LiveScript 50 (or 1 if you're flexible)

    The 1 character solution is r where the function signature is this:

    fun = (a,o=(sum a.filter odd),e=(sum a.filter even),r=(e*e+o*o)**0.5) ->
    

    But I think that's a technicality.

    Actual answer:

    o=sum a.filter odd
    e=sum a.filter even
    (e*e+o*o)^0.5
    

    Brigand

    Posted 2014-02-05T19:51:11.973

    Reputation: 1 137

    Is it really a technicality, though? ;] http://codegolf.stackexchange.com/a/20396/8856

    – Noyo – 2014-02-11T19:05:07.870

    0

    k (31-32 = -1)

    sqrt{+/b*b:+/'(.)x@=(_a)=a:x%2}
    

    Example run:

      sqrt{+/b*b:+/'(.)x@=(_a)=a:x%2} 20 9 4 5 5 5 15 17 20 9
    78.492037812761623
    

    mollmerx

    Posted 2014-02-05T19:51:11.973

    Reputation: 229

    0

    C (68-32 = 36)

    float f(int *a, int c)
    {int s[2]={0};while(c--)s[a[c]%2]+=a[c];return sqrt(*s**s+s[1]*s[1]);}
    

    In action:

    #include <stdio.h>
    #include <math.h>
    
    float f(int *a, int c)
    {int s[2]={0};while(c--)s[a[c]%2]+=a[c];return sqrt(*s**s+s[1]*s[1]);}
    
    int main(void)
    {
        printf("%f\n", f((int[]){20, 9, 4, 5, 5, 5, 15, 17, 20, 9}, 10));
        return 0;
    }
    

    Shahbaz

    Posted 2014-02-05T19:51:11.973

    Reputation: 870

    0

    ised (10 characters - 32) = -22

    ASCII:

    @={@+E$1@+O$1}
    

    UTF8:

    @={ΣE$1ΣO$1}
    

    The variable $1 must contain the array. Example invocation from shell:

    ised --l - '@={ΣE$1ΣO$1}' <<<"20, 9, 4, 5, 5, 5, 15, 17, 20, 9"
    

    Example invocation in interactive mode:

    ised> @1{20, 9, 4, 5, 5, 5, 15, 17, 20, 9}
    20 9 4 5 5 5 15 17 20 9
    ised> @={ΣE$1ΣO$1}
    78.492
    

    Explanation: operators O and E extract odd and even elements of the array. The operator @+ or Σ sums the array. @= returns the length of the given vector.

    If you want a function, it's even shorter. Saving a function:

    ised> @2{: @={ΣExΣOx} :}
    

    The function body is only 10 characters long. The rest is the function declaration ({: :}) and storage of the function handle into memory slot 2 (@2). Invocation

    ised> $2::{20 9 4 5 5 5 15 17 20 9}
    

    Link to software: http://ised.sourceforge.net/

    orion

    Posted 2014-02-05T19:51:11.973

    Reputation: 3 095