Determine group number given an index in an array

Viewed 29

Say you have an array of size n, which is composed of x groups of items of size y. For example, an array of size 12, composed of 3 groups of 4 items.

x*y = n

Given an index (i) of an item, how would you determine which group (g) it is in?

For example in the array above, you’re given an index of 6 (where index starts at 0). That means it’s the 3rd item in the 2nd group, so g = 2. An index of 8 would yield g = 3, because it's the first item in the 3rd group.

What’s the formula for deriving this result (g)?

2 Answers

If we have x,y,i and n then we can calculate the group number with below formula.

Calculate which group it belongs to: y/i.

I am assuming each of x,y and i start with 0.

Explanation:

We can write it as: suppose group is G and k is some number.

y*G+k = i; which makes, G = i-k/y

here we can ignore k. Final expression: G=floor(i/y)

Consider your example. x = 3, y = 4 and i = 6.

G = floor(6/4) = 1.

Group count starts from 0 so it will be 2nd group.

Here's my attempt

let ng = 4 // NO. of groups
let gs = 3 // Group Size
let n = ng * gs

let getGroup = (i) => {
  if (n != 0 && i != 0) {
    let mod = i % gs;
    if (mod == 0) {
      return "group " + i / gs + " | " + "position " + gs
    } else {
      return "group " + (((i - mod) / gs) + 1 )+ " | " + "position " + mod
    }
  }
}

console.log(getGroup(11))

Related