Difference between revisions of "Calculate the sum over a container"

From CodeCodex

(Ruby: array sum method done another way)
(It replaces an order. It corrected ruby)
Line 30: Line 30:
 
returns 18.
 
returns 18.
  
 +
===Assembly===
 +
INT_MAX = 2147483647.
 +
<pre>
 +
sum proc
 +
mov ecx,DWORD PTR [esp]
 +
add esp,4
 +
xor eax,eax
 +
sum_loop1:
 +
add eax,DWORD PTR [esp]
 +
add esp,4
 +
cmp DWORD PTR [esp],2147483647
 +
jne sum_loop1
 +
mov DWORD PTR [esp],ecx
 +
ret
 +
sum endp
 +
</pre>
  
 
===C===
 
===C===
Line 71: Line 87:
 
</highlightsyntax>
 
</highlightsyntax>
  
===Assembly===
+
===Excel===
INT_MAX = 2147483647.
+
 
<pre>
 
<pre>
sum proc
+
=SUM([cells])
mov ecx,DWORD PTR [esp]
+
add esp,4
+
xor eax,eax
+
sum_loop1:
+
add eax,DWORD PTR [esp]
+
add esp,4
+
cmp DWORD PTR [esp],2147483647
+
jne sum_loop1
+
mov DWORD PTR [esp],ecx
+
ret
+
sum endp
+
 
</pre>
 
</pre>
  
Line 151: Line 155:
 
assert total(1,2,3,sys.maxint) == 6
 
assert total(1,2,3,sys.maxint) == 6
 
</highlightsyntax>
 
</highlightsyntax>
 
  
 
===Ruby===
 
===Ruby===
<highlightsyntax language="ruby">
+
<pre>
 
class Array
 
class Array
   def sum;     inject(0) { |s, v| s += v }; end
+
   def sum
 +
     inject { |s, v| s += v }
 +
  end
 
end
 
end
</highlightsyntax>
+
</pre>
 
Or more concisely,  
 
Or more concisely,  
<highlightsyntax language="ruby">
+
<pre>
 
class Array
 
class Array
   def sum;     reduce(:+); end
+
   def sum
 +
     reduce(:+)
 +
  end
 
end
 
end
</highlightsyntax>
+
</pre>
  
 
===Scheme===
 
===Scheme===
Line 179: Line 186:
 
return sum
 
return sum
 
}
 
}
</pre>
 
 
===Excel===
 
<pre>
 
=SUM([cells])
 
 
</pre>
 
</pre>
  
Line 189: Line 191:
 
[[Category:Arrays]]
 
[[Category:Arrays]]
  
 +
[[Category:Algol 68]]
 +
[[Category:Assembly]]
 
[[Category:C]]
 
[[Category:C]]
 +
[[Category:C++]]
 +
[[Category:Common Lisp]]
 
[[Category:Excel]]
 
[[Category:Excel]]
[[Category:C++]]
+
[[Category:F sharp]]
[[Category:Assembly]]
+
 
[[Category:Haskell]]
 
[[Category:Haskell]]
 
[[Category:Java]]
 
[[Category:Java]]
 +
[[Category:Objective Caml]]
 
[[Category:Perl]]
 
[[Category:Perl]]
 
[[Category:Python]]
 
[[Category:Python]]
[[Category:Objective Caml]]
 
 
[[Category:Ruby]]
 
[[Category:Ruby]]
[[Category:Algol 68]]
 
[[Category:Common Lisp]]
 
 
[[Category:Scheme]]
 
[[Category:Scheme]]
[[Category:F sharp]]
 
 
[[Category:Zsh]]
 
[[Category:Zsh]]

Revision as of 02:47, 22 July 2010

Related content:

This code demonstrates how to calculate the sum of a container (most often an array or similar structure).

See also

Implementations

Algol 68

The following function computes the sum of the elements of the array passed to it. The type of the array elements is called NUM, which can be defined as any suitable integer or real type.

MODE NUM = INT; # type of array element #

PROC sum = ([] NUM a) NUM :
    BEGIN
        NUM result := 0;
        FOR i FROM LWB a TO UPB a DO
            result +:= a[i]
        OD;
        result
    END

For instance, the call

sum((3, 4, 5, 6))

returns 18.

Assembly

INT_MAX = 2147483647.

sum proc
	mov ecx,DWORD PTR [esp]
	add esp,4
	xor eax,eax
	sum_loop1:
	add eax,DWORD PTR [esp]
	add esp,4
	cmp DWORD PTR [esp],2147483647
	jne sum_loop1
	mov DWORD PTR [esp],ecx
	ret
sum endp

C

Total of a series function. Terminate by using INT_MAX <highlightsyntax language="c"> //stdarg.h must be included for this type of function to be declared

  1. include <stdarg.h>

int total( int first, ... ) {

  int count = 0, sum = 0, i = first;
  va_list marker;
  va_start( marker, first );     /* Initialize variable arguments. */
  while( i != INT_MAX )
  {
     sum += i;                   //increases the sum
     i = va_arg( marker, int);   //Gets the next argument
  }
  va_end( marker );              // Resets the list
  return sum;

} </highlightsyntax>

C++

<highlightsyntax language="cpp">

  1. include<numeric>

sum = std::accumulate(coll.begin(),coll.end(),0); </highlightsyntax>

Common Lisp

<highlightsyntax language="lisp"> (reduce #'+ list) (reduce #'+ list :initial-value 0) ; improved version that also works with empty lists </highlightsyntax>

Another way:

<highlightsyntax language="lisp"> (apply #'+ list) </highlightsyntax>

Excel

=SUM([cells])

F#

<highlightsyntax language="fsharp"> Seq.sum container </highlightsyntax>

Haskell

<highlightsyntax language="haskell"> sum container </highlightsyntax>

Java

<highlightsyntax language="java122"> import java.util.*;

public class Total {

   public static int total(int... values) {
       int total = 0;
       for (int i : values) total += i;       
       return total;
   }
   public static void main(String[] args) {
       System.out.println("Total: %d: ", total(1,2,4,40));
       
   }

} </highlightsyntax>

OCaml

Summing is a special case of folding the addition operator starting with zero:

# let sum = List.fold_left ( + ) 0;;
val sum : int list -> int = <fun>

For example:

# sum [1; 2; 4; 40];;
- : int = 47

Perl

<HIGHLIGHTSYNTAX language="perl"> use List::Util qw(sum); sum @arr; sum 0, @arr; # improved version that also works with empty arrays </HIGHLIGHTSYNTAX>

Python

A function that sums the values in a sequence is built into python, its name is 'sum'. <highlightsyntax language="python"> assert sum([1,2,3]) == 6 </highlightsyntax> A parallel to the ANSI C example given above is as follows: <highlightsyntax language="python"> import itertools def total(*values):

 return sum(itertools.takewhile(sys.maxint.__cmp__, values))

assert total(1,2,3,sys.maxint) == 6 </highlightsyntax>

Ruby

class Array
  def sum
    inject { |s, v| s += v }
  end
end

Or more concisely,

class Array
  def sum
    reduce(:+)
  end
end

Scheme

<highlightsyntax language="scheme"> (apply + list) </highlightsyntax>

Zsh

zsum() {
	local -a array
	array=(1 2 3 4 5)
	(( sum=${(j:+:)array} ))
	return sum
}