0

I am trying to write my own code for Singular language and I am getting errors. the question is repeated [here][1].

proc combination(int n, int t)
{
list s;
    if( t == 0)
        {return (1);}
    
    for (int i=1;i<=t;i++)
   {
       s[i]=i;
    }
    list results;
    results=s;
    int tru=1;
    while (tru)
    {
        int i = t;
        
        while (i > 0 && s[i] >= n - (t - i))
           { i = i-1;}
        
        
        if( i == 0)
            {break;}
        
        
        s[i] =s[i]+ 1;
        
        for (int j=i+1; j<=t;j++)
            {
                s[j] = s[j-1] + 1;
            }
        
        for (int i=1;i<=size(s);i++)
   {
       insert(results,s[i]);
    }
    }
    return (results);
}

I try the code in JULIA and it is working; here is the julia version

function combination(n::Int, t::Int)
    if t == 0
        return [1]
    end
    
    s = [i for i in 1:t]
    results = [s]
    while true
        i = t
        
        while i > 0 && s[i] >= n - (t - i)
            i -= 1
        end
        
        if i == 0
            break
        end
                print(i)

        s[i] += 1
        for j in i+1:t
            s[j] = s[j-1] + 1
        end
        
        
        push!(results, [s[i] for i in 1:length(s)])
    end
    
    return sort(results)
end


  [1]: https://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n
A. T
  • 1,714
  • 1
  • 8
  • 9

1 Answers1

3

This functionality is available by using Combinatorics:

julia> collect(combinations(['A','B','C','D'],3))
4-element Vector{Vector{Char}}:
 ['A', 'B', 'C']
 ['A', 'B', 'D']
 ['A', 'C', 'D']
 ['B', 'C', 'D']

If you want to see how this is implemented in Julia try:

@edit Combinatorics.Combinations(4,3)
Przemyslaw Szufel
  • 40,002
  • 3
  • 32
  • 62