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

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay