Rank of all elements in an array Solution in Go
Rank of all elements in an array
Question:
Given an array of N integers with duplicates allowed. All elements are ranked from 1 to N if they are distinct. If there are say x repeated elements of a particular value then each element should be assigned a rank equal to the arithmetic mean of x consecutive ranks.
Sample Input:
The first line of the input contains a single integer N size of the array. Next line contains N-Space separated integers, denoting elements of an array.
Output:
For each element of the array, print rank of that element .
Sample TestCase 1
Input :
- 3
- 20 30 10
Output :
- 2.0 3.0 1.0
Sample TestCase 2
Input :
- 7
- 1 2 5 2 1 60 3
Output :
- 1.5 3.5 6.0 3.5 1.5 7.0 5.0
Solution
package main
import "fmt"
func main() {
var n int
fmt.Scan(&n)
ar := make([]int, n)
ReadN(ar, 0, n)
for j := 0; j < n; j++ {
r := 1
s := 1
for k := 0; k < n; k++ {
if (j != k) && (ar[k] < ar[j]) {
r += 1
}
if (j != k) && (ar[k] == ar[j]) {
s += 1
}
}
fmt.Print(float32(float32(r) + float32(s - 1)/(float32(2))));
fmt.Print(` `)
}
}
func ReadN(all []int, i, n int) {
if n == 0 {
return
}
fmt.Scan(&all[i])
ReadN(all, i+1, n-1)
}
Subscribe to Letsgo
Get the latest posts delivered right to your inbox