0
votes

I'm new to Scilab (and programming in general). I'm trying to implement a Scilab code to solve the cutting stock problem aka 'bin packing'.

The problem: given 'n' items of sizes[] (a vector from s1 to sn), and same capacity for all bins (c=1000), I need to minimize the number of bins required to fit all items.

I'm trying the 'next item algorithm', i.e., pick the first item from the vector, put it in the bin, then pick the next item and try to put in the same bin, in case there is no enough space, then create another bin.

Actually I don't need help in improving the algorithm, but rather in implement the code for this specific one.

Here is what I've tried so far:

// 'n' is the number of items to be packed
// 'c' is the capacity (how much items fit in the bin)
// 'sizes' a vector containing the size of n items
// 'nbins' number of bins used so far
// 'bin_rem' space left in current bin    

    sizes=[400,401,402,403,404,405,406,408,409,411,428,450,482]
    c=1000
    n=length(sizes)
    nbins = 0 
    bin_rem = c

    function y = bins(sizes,c,n)
    for i=0; i<n; i=i+1 
        if sizes[i] > bin_rem 
        nbins=nbins+1  
        bin_rem = c - sizes(i)
      bin_rem = bin_rem - sizes(i)
    end
    endfunction

    disp ("Number of bins needed "+string(bins([sizes,c,n])))
    end

I'm stuck with this error below and have no idea on how to solve it.

at line 20 of executed file endfunction ^~~~~~~~~~~^ Error: syntax error, unexpected endfunction, expecting end

Any help?

1

1 Answers

2
votes

First, seems like you still don't quite understand Scilab's syntax, since I see you using sizes[i], instead of sizes(i), and calling bins([sizes,c,n]). So, for now, try not to use functions. As for the error you get, it happens because you forgot one end. The way you wrote your code, only the if statement is closed, and for loop is still open.

Secondly, when you correct that, you'll notice that your program does not work properly, and that is because you defined the loop wrong. In Scilab, the for loop is actually a "for each" loop, therefore, you need to provide a full range of values for each iteration, instead of starting value (i=0), condition (i<n) and increment function (i=i+1).

Thirdly, seems like you understand the algorithm you're trying to use, but you implemented it wrong: the last line inside the loop should be the else statement.

Solving all those, you have the following piece of code:

sizes=[400,401,402,403,404,405,406,408,409,411,428,450,482]
c=1000
n=length(sizes)
nbins = 0  //should start as 0
bin_rem = 0 //should start as 0

for i = 1:n
    if sizes(i) > bin_rem
        nbins = nbins + 1;
        bin_rem = c - sizes(i);
    else
        bin_rem = bin_rem - sizes(i);
    end
end

disp ("Number of bins needed "+string(nbins))

Just to clarify, 1:n means a vector from 1 to n with pace of 1. You could have also written for i = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].