Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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   │
└──────┴─────────────────┴──────────────┴─────────┴────────┴───────┘
share|improve this question
8  
Why does the lowest score need a bonus, they already won? –  gggg Feb 5 at 20:02
6  
Moreover, the offset of 46 doesn't change anything regarding the order. –  Howard Feb 5 at 20:06
    
@gggg I think they mean they'll give the lowest scoring answer a +50 bounty. –  Lego Stormtroopr Feb 5 at 23:27
1  
@gggg: I will actually start a bounty as soon as I am allowed to. So that's what I meant by bonus. –  Abhijit Feb 6 at 2:01
    
@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 Feb 6 at 2:03
show 5 more comments

35 Answers

up vote 7 down vote accepted
+50

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
share|improve this answer
add comment

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
share|improve this answer
    
...and now I feel kinda dirty. :] –  Noyo Feb 10 at 10:28
    
+1, I've deleted my ES6 solution since yours is way better :) –  Florent Feb 10 at 14:58
    
Haha, thanks. We'll see if the rules are changed once the OP sees this.. ;] –  Noyo Feb 10 at 18:34
    
Well, 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 Feb 17 at 16:42
    
Actually 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 Feb 18 at 8:25
add comment

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
share|improve this answer
    
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 Feb 10 at 11:59
    
@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 Feb 12 at 7:30
    
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 Feb 14 at 11:00
    
@Tomas There are arrays in R. Have a look at ?array. Furthermore, is.array(by(1,1,I)) returns TRUE. –  Sven Hohenstein Feb 14 at 11:24
    
Aha, new to me, thanks! –  Tomas Feb 14 at 14:39
add comment

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
share|improve this answer
    
Very clever, I like it! This would save me a few chars in J as well. –  FireFly Feb 9 at 0:05
    
Thanks, @FireFly. Yours is nice. Gotta learn J sometime. Cheers! –  O-I Feb 9 at 0:16
    
You only have to count the body of the function, I'd say 37 chars. –  steenslag Feb 9 at 16:58
    
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 Feb 9 at 20:26
add comment

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
share|improve this answer
add comment

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

share|improve this answer
add comment

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
share|improve this answer
    
nice! it's like the problem was build exactly for abs of complex numbers –  jozxyqk Feb 14 at 15:04
add comment

Kona, 22 - 32 = -10

{(+/(+/'x@=x!2)^2)^.5}
share|improve this answer
add comment

Perl5 : (50 - 32 = 18)

map{$0[$_&1]+=$_}@ARGV;print sqrt$0[0]**2+$0[1]**2
share|improve this answer
    
+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 Feb 9 at 18:47
    
@Tomas Wouldn't using say require a use? switching from an argument array to <> would require an additional split/ /,. –  Sylwester Feb 9 at 23:46
    
1) 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 Feb 10 at 10:04
add comment

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
share|improve this answer
add comment

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
share|improve this answer
1  
You don't need the [square brackets] inside the sum(). –  daniero Feb 6 at 0:26
1  
I 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 Feb 6 at 2:46
    
@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! –  Lego Stormtroopr Feb 6 at 2:48
    
@DSM: I had a similar version in my mind, but yours is sleeker –  Abhijit Feb 6 at 2:54
    
Does Python accept !s%2? That's at least an incremental change you can accept –  Charles Feb 10 at 2:03
show 1 more comment

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 
share|improve this answer
1  
Math.hypot *a.partition(&:odd?).map{|x|eval x*?+} shaves off a few chars –  steenslag Feb 9 at 17:02
add comment

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`
share|improve this answer
1  
You 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 Feb 6 at 10:30
    
@NeilSlater doh! Thanks :) –  daniero Feb 6 at 13:57
add comment

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
share|improve this answer
add comment

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
share|improve this answer
add comment

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
share|improve this answer
    
I don't know coffeescript, but i wonder if you can remove the space after the += and change 0.5 to .5 –  ace Feb 9 at 9:49
    
thanks that helps :) i din't notice that. –  vasuakeel Feb 9 at 9:50
add comment

GolfScript 30

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

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

share|improve this answer
add comment

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));
share|improve this answer
add comment

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
share|improve this answer
1  
+1 for using dc. Ha ha sose ;-) perhaps you could get shorter result using dc array commands‌​? –  Tomas Feb 10 at 12:07
    
@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 Feb 10 at 16:33
    
You are welcome, I knew this would help :-) –  Tomas Feb 11 at 10:02
add comment

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
share|improve this answer
add comment

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

share|improve this answer
    
You haven't golfed this at all. We're trying to get a solution that fits on the boss's punchcard! –  Riking Feb 6 at 0:24
    
Why not? Explain Please. –  Merin Nakarmi Feb 6 at 0:41
2  
Your code is fully indented with spaces all over. Code golf is all about getting the lowest character count. This question is tagged code-golf. –  Riking Feb 6 at 1:14
    
Thanks Riking. I edited it. I have fewer characters now.:) –  Merin Nakarmi Feb 6 at 1:36
    
I think the list is supposed to be provided as input, not hardcoded. –  Timwi Feb 6 at 14:48
show 2 more comments

Clojure = 87 - 46 = 41

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

Hardly idiomatic, though.

share|improve this answer
add comment

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
share|improve this answer
add comment

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));
    }
}
share|improve this answer
add comment

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

share|improve this answer
    
thanks. that really golfed the code down very much. –  Sp0T Feb 8 at 7:56
    
Did it independently, got 58 base: foreach($l as$m)$m%2?$o+=$m:$e+=$m;echo sqrt($o*$o+$e*$e); –  Yoda Feb 21 at 12:11
add comment

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)
share|improve this answer
add comment

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.

share|improve this answer
add comment

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

share|improve this answer
add comment

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
share|improve this answer
add comment

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);
        }

    }
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.