Open jeeyeonLIM opened 4 years ago
# Enter your code here. Read input from STDIN. Print output to STDOUT
a <- scan(file="stdin")
##### MEAN #####
cat( sum(a[-1])/a[1] , '\n')
##### MEDIAN #####
#Method1
#cat( median(a[-1]), '\n')
#Method2
sorted_a = sort(a[-1])
cat( ifelse(a[1]%%2 ==1, sorted_a[a[1]/2], (sorted_a[a[1]/2]+sorted_a[(a[1]/2)+1])/2 ), '\n')
##### MODE #####
cat(names(table(a[-1])[1]),'\n' )
#cat( which.max(tabulate(a[-1])), '\n')
Objective In this challenge, we practice calculating the mean, median, and mode. Check out the Tutorial tab for learning materials and an instructional video!
Task Given an array, , of integers, calculate and print the respective mean, median, and mode on separate lines. If your array contains more than one modal value, choose the numerically smallest one.
Note: Other than the modal value (which will always be an integer), your answers should be in decimal form, rounded to a scale of decimal place (i.e., , format).
Input Format
The first line contains an integer, , denoting the number of elements in the array. The second line contains space-separated integers describing the array's elements.
Constraints
, where is the element of the array. Output Format
Print lines of output in the following order:
Print the mean on a new line, to a scale of decimal place (i.e., , ). Print the median on a new line, to a scale of decimal place (i.e., , ). Print the mode on a new line; if more than one such value exists, print the numerically smallest one. Sample Input
Sample Output
Explanation
Mean: We sum all elements in the array, divide the sum by , and print our result on a new line.
Median: To calculate the median, we need the elements of the array to be sorted in either non-increasing or non-decreasing order. The sorted array . We then average the two middle elements:
and print our result on a new line. Mode: We can find the number of occurrences of all the elements in the array:
Every number occurs once, making the maximum number of occurrences for any number in . Because we have multiple values to choose from, we want to select the smallest one, , and print it on a new line.
https://www.hackerrank.com/challenges/s10-basic-statistics/problem