function [sBest,valBest]=SA_knapsack(Tmax,Tmin,lambda)
// Exemplu apel: [sBest,valBest]=SA_knapsack(10000,0.001,0.5) 
// Tmax = valoarea initiala a temperaturii
// Tmin = valoarea finala a temperaturii
// lambda = parametrul folosit in construirea functiei obiectiv prin tehnica penalizarii

// definirea problemei
v=[3,4,1,5,2];
w=[10,8,3,6,5];
c=20;
n=size(v,2);
// solutia initiala
s=init(n);
val=valoare(v,w,c,s);
sBest=s;    // cea mai buna solutie gasita pana in momentul curent
valBest=val;
T=Tmax;     // initializarea temperaturii
while T>Tmin
    sNew=transform(s);
    valNew=valoare(v,w,c,sNew);
    disp(valNew,'val=');
    a=accept(val,valNew,T);
    if a==1
        s=sNew;
        val=valNew;
    end
    if val>valBest
        sBest=s;    
        valBest=val;
    end;    
    T=T*0.9995;
end    
endfunction
// solutie initiala = selectie aleatoare
function s=init(n)
    s=grand(1,n,"uin",0,1);
endfunction 

//calcul functie obiectiv
function val=valoare(v,w,c,s)
     wKnapsack=w*s';
     vKnapsack=v*s';
     if wKnapsack<=c 
         val=vKnapsack;
     else
         val=lambda*vKnapsack+(1-lambda)*(c-wKnapsack);
     end           
endfunction    

// perturbare aleatoare simpla (includerea sau excluderea unui obiect)
function sNew=transform(s)
n=length(s);
sNew=s;
i=grand(1,1,"uin",1,n); 
sNew(i)=1-s(i)
endfunction

// acceptance function
// a=1 - the new tour is accepted
// a=0 - the new tour is not accepted
function a=accept(val,valNew,T)
if valNew>=val
    a=1;
else
    p=exp((valNew-val)/T);
    if grand(1,1,"unf",0,1)<p
        a=1;
    else
        a=0;
    end
end    
endfunction

[sBest,valBest]=SA_knapsack(10000,0.001,0.75)
