hiropon
hiropon

Reputation: 1802

Why can't I get correct answer when I used recursive with Ruby?

I created a code snippet with Java like following. This is the code to get all combination from nCr.

code using recursion with Java , online compiler

Java version

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.HashSet;

public class prog {

    public static void main(String[] args) {

        // nCr : n=[1,2,3,4,5],r=3
        ArrayList<Integer> n = new ArrayList<>(Arrays.asList(1,2,3,4,5));
        getCombination(n,3);
    }

    private static Set<ArrayList<Integer>> getCombination(ArrayList<Integer> n, Integer r) {
        Set<ArrayList<Integer>> ans = new HashSet<ArrayList<Integer>>();
        combination(n, r, ans);
        for (ArrayList<Integer> e : ans) {
            System.out.println(e.toString());
        }
        return ans;
    }

    private static void combination(ArrayList<Integer> n, Integer r, Set<ArrayList<Integer>> ans) {
        if (n.size() == r) {
            ans.add(n);
            return;
        }
        for (int i = 0; i < n.size(); i++) {
            ArrayList<Integer> N = new ArrayList<Integer>();
            N.addAll(n);
            N.remove(i);
            combination(N,r,ans);
        }
    }
}

Next, I tried to port it with Ruby. But, it can't work well.
Can you point out what is the problem between two code snippets ?

code using recursion with Ruby, online compiler

Ruby version

require 'set'

def combi(n, r, ans)
  if n.size == r
    ans.add(n)
    return
  end
  for i in 0..n.size
    arr = n.dup
    arr.delete_at(i)
    combi(arr, r, ans)
  end
end

def get_combination(n, r)
  ans = Set.new
  combi(n, r, ans)
  #ans.map do |e|
  #  puts e.to_s
  #end
  ans
end

n1 = [1,2,3,4,5]
get_combination(n1, 3)

I know ruby has combination method, but it's not problem.

Upvotes: 2

Views: 69

Answers (1)

Arno C
Arno C

Reputation: 490

In this part:

for i in 0..n.size
    arr = n.dup
    arr.delete_at(i)
    combi(arr, r, ans)
end

of your ruby cody you go upto n.size inclusively. This has to be made exclusively with '...' making the code

for i in 0...n.size
    arr = n.dup
    arr.delete_at(i)
    combi(arr, r, ans)
end

Then your code works fine!

Upvotes: 2

Related Questions