Find the average value of the given array of numbers.
Calculating the average value of an array has two subtasks—calculate the sum and divide it by the size of the array. So, one of the solutions can look like this:
my @data = 7, 11, 34, 50, 200;
say sum(@data) / @data;
Here, the sum built-in function returns the sum of the elements of the @data array. To get the size of an array, you may call the elems method:
say sum(@data) / @data.elems;
This is a straightforward way, which is a bit redundant for our task. As the @data is used in numeric context as an operand of the division operator, explicitly calling the elems method is not necessary.
Another approach is to use the reduction operator:
say ([+] @data) / @data;
In this example, [+] @data is equivalent to @data[0] + @data[1] + ...+ @data[N], where the + operator is placed between all the elements of the array. Be careful with the parentheses in this code. If you omit them, the result will be incorrect, as the actual sum consists of a single element @data / @data, which equals one. If you omit the space before the opening brace, it will be considered as a parenthesis grouping the arguments of the sayfunction, and the result is also incorrect, as the code prints only the sum of the array elements and divides the result of say (which is 1).
Hello Andrew
Just beginning with raku and I read the articles again and again just to get the hang of raku.
Here is the code of a beginning to learn raku person :
constant ansi-start = “\e[3m\e[33m”;
constant ansi-stop = “\e[0m”;
my Any @arr =
[
[1,2,3,4,5,6,7,8.99],
[10,20,30,40,50,60,70,80],
[100,200,300,400,500,600,700,800],
];
say “{ansi-start} Dumping @arr with dd {ansi-stop}”;
dd @arr;
# want to know how many columns there are on ech row !!!
say “{ansi-start} Content of Column 3 : {ansi-stop}” ~ @arr[*;3]; # shows the column
say “{ansi-start} Number of Items in Column 3 : {ansi-stop}” ~ @arr[*;3].end;
say “{ansi-start} Content of Row 0 : {ansi-stop}” ~ @arr[0;*]; # shows the row
say “{ansi-start} Number of Items in Row 0 : {ansi-stop}” ~ @arr[0].end;
say “{ansi-start} Number of items in Row 0 : {ansi-stop}” ~ @arr[0;*].end; # same as above
# try not to use the raku loop variant, but use a for loop
say “”;
printf “{ansi-start} %5s %-43.43s %9s %9s {ansi-stop}\n” , ‘—‘, ‘-‘ x 50 , ‘-‘ x 10 , ‘-‘ x 10;
printf “{ansi-start} %5s %-43s %9s %9s {ansi-stop}\n” , ‘IDX’, ‘Content @arr for position IDX’, ‘Sum’ , ‘Average’;
printf “{ansi-start} %5s %-43.43s %9s %9s {ansi-stop}\n” , ‘—‘, ‘-‘ x 50 , ‘-‘ x 10 , ‘-‘ x 10;
for 0 .. @arr.end -> $idx {
# using printf to show all results on 1 line !!
#say “->{@arr[$idx].elems}”;
printf “%5d ] %-45.45s %7.2f %7.2f\n” , $idx , “{@arr[$idx;*]}” , sum(@arr[$idx;*]), “{([+] @arr[$idx;*]) / @arr[$idx]}” ;
}
printf “{ansi-start} %5s %-43.43s %9s %9s {ansi-stop}\n” , ‘—‘, ‘-‘ x 50 , ‘-‘ x 10 , ‘-‘ x 10;