Code Kata Answers to Calculating averages

Following on from Code Kata friday

I know John's works (C#) and mine (Ruby) - The good doctor's I assume does (F#) - So that gives you a solution in C# Ruby and F# (I found  the # key on a mac - its [alt-3]!) 

Enjoy 

 

John's solution 

decimal[] CalculateAverages(IEnumerable<decimal?> series)
{
  return series.Select((d, i) => new {D = d.GetValueOrDefault(), I = i/2})
                       .GroupBy(arg => arg.I)
                       .Select(grouping => grouping.Average (arg => arg.D))
                       .ToArray();
}

my solution

(I'll post the full file at the bottom as Pascal didnt help me out with the random list generator - I had to write my own) 

def calculate_averages()
    @results = []
    #make all the nulls 0
    @working_array.each{|item| if(item == nil)
                                    @working_array[@working_array.index(item)]=0
                               end}
    #if we are odd length add last again so not to skew avge
    if(@working_array.length.odd?)
         @working_array << @working_array.last
    end
    #I think this is cool tho !!
    1.step(@working_array.length, 2) {|i| @results << ((@working_array[i] + @working_array[(i-1)])/2.00)} 
    puts "Results = #{@results}"
end

The good doctors solution



let swap f x y = f y x
 
let rec avgRec x acc =
    let avg a  =
        match a with   
            | Some x,Some y -> (x + y) / 2.0
            | None, Some y -> y /2.0
            | Some x, None -> x /2.0
            | _ -> 0.0
    match x with
        | f::s::t ->  avgRec t (acc @ [avg (f,s)])
        | _ -> acc
 
let Average  : float list= swap avgRec [] 
 
let src = [for i in 1 .. 20 -> if i % 3 <> 0 then Some(float(i)) else None]
let res = src |> Average



 

And for anyone interested the rest of the ruby class with the list generator

class BuildAndAveragePairs
  #accepts the beginning array length and the max random number allowed
  def initialize(array_length, max_random_number)
    @array_length = array_length
    @max_rand = max_random_number
  end

  #generate a 10 digit array with a nil inserted in a random place 25% of the the places?
  def random_array_with_null
    @working_array = []
    (1..@array_length).each do |x|
      if((rand(100)) > 75)
        @working_array << nil
      else
        @working_array << rand(@max_rand)
      end
    end
    @start_array = @working_array
    puts "Working array is #{@working_array}"
    calculate_averages()
  end

#calculate averages def goes here 

end

myCalc = BuildAndAveragePairs.new(10, 100)


(1..5).each do |x|
  myCalc.random_array_with_null
end

hope you enjoyed it :-) I'll post the next one when we have it

August 16 2011
blog comments powered by Disqus