DEV Community

dbarun
dbarun

Posted on

Brute Force way of Looping Combination

How Do We LOOP C(r, n) Lets loop C(3,6)
In Combination we don't care about order so the formula of combination [n!/r!(n-r)!] gives C(3, 6) value of = 6!/3!x3! = 20

We already know we need to loop 3 times as we selected 3 items but Sometimes I confused what will the array bound and It turns out to be very simple to know the array bound

Let's take an array of [1, 2, 3, 4, 5, 6]
Here r = 3 and n = 6 = len(arr)

for the first loop the array bound will be like this
I will use go/golang and the classic for loop to write
for i := 0; i <= len(arr) - 3; i++{}
or
for i := 0; i < len(arr) - 2; i++{}
the boundary should be <= len(arr) - r or < len(arr) - (r-1)

and the second will be
for j := i+1; j <= len(arr) - 2; i++{}
or
for i := i+1; j < len(arr) - 1; i++{}
the boundary should be <= len(arr) - r-1 or < len(arr) - (r-2)

I guess now you can figure out the sequence or the formula for this.

Image description

[the second variation]
Image description

Top comments (0)