optimize `stl/sort.nas` and `test/calc.nas`

This commit is contained in:
ValKmjolnir 2022-09-10 15:45:25 +08:00
parent 10e579dabc
commit 91b3074ce9
2 changed files with 30 additions and 19 deletions

View File

@ -1,18 +1,26 @@
# sort.nas # sort.nas
# valkmjolnir 2021/4/2 # valkmjolnir 2021/4/2
var sort=func(vec,left,right,cmp=func(a,b){return a<=b;}){
if(left>=right) return nil; # please make sure the compare function has the function like <= or >=
var (L,R,tmp)=(left,right,vec[left]); # only using < or > may cause infinite loop or the program may crash
while(left<right){ var sort=func(){
while(left<right and cmp(tmp,vec[right])) srand(); # be aware! this causes global changes
right-=1; return func(vec,left,right,cmp=func(a,b){return a<=b;}){
while(left<right and cmp(vec[left],tmp)) if(left>=right) return nil;
left+=1; var base=left+int(rand()*(right-left));
if(left!=right) (vec[left],vec[base])=(vec[base],vec[left]);
(vec[left],vec[right])=(vec[right],vec[left]); var (i,j,tmp)=(left,right,vec[left]);
while(i!=j){
while(i<j and cmp(tmp,vec[j]))
j-=1;
vec[i]=vec[j];
while(i<j and cmp(vec[i],tmp))
i+=1;
vec[j]=vec[i];
}
vec[i]=tmp;
sort(vec,left,i-1,cmp);
sort(vec,i+1,right,cmp);
return nil;
} }
(vec[L],vec[left])=(vec[left],tmp); }();
sort(vec,L,left-1,cmp);
sort(vec,left+1,R,cmp);
return nil;
}

View File

@ -117,22 +117,25 @@ var column=func(number){
var calc=func(codetype,files,path=""){ var calc=func(codetype,files,path=""){
println(codetype); println(codetype);
var (bytes,line,semi,line_cnt,semi_cnt)=(0,0,0,0,0); var (bytes,ctx,line,semi,line_cnt,semi_cnt)=(0,"",0,0,0,0);
forindex(var i;files){ forindex(var i;files){
var s=io.fin(getname(path~files[i])); var s=io.fin(getname(path~files[i]));
(line_cnt,semi_cnt)=(count(s,'\n'),count(s,';')); (line_cnt,semi_cnt)=(count(s,'\n'),count(s,';'));
println(rightpad(files[i],padding_length),'| ', println(rightpad(files[i],padding_length),'| ',
column(line_cnt),'line | ', column(line_cnt),'line | ',
column(semi_cnt),'semi | ', column(semi_cnt),'semi | ',
rightpad(str(int(size(s)/1024)),6),'kb'); rightpad(str(int(size(s)/1024)),6),'kb | ',
md5(s),' |');
bytes+=size(s); bytes+=size(s);
ctx~=s;
line+=line_cnt; line+=line_cnt;
semi+=semi_cnt; semi+=semi_cnt;
} }
println(rightpad("total:",padding_length),'| ', println(rightpad("total:",padding_length),'| ',
column(line),'line | ', column(line),'line | ',
column(semi),'semi | ', column(semi),'semi | ',
rightpad(str(int(bytes/1024)),6),'kb'); rightpad(str(int(bytes/1024)),6),'kb | ',
md5(ctx),' |\n');
return int(bytes/1024); return int(bytes/1024);
} }
@ -140,4 +143,4 @@ var all=calc("source code:",source)
+calc("lib:",lib,"stl/") +calc("lib:",lib,"stl/")
+calc("test file:",testfile,"test/") +calc("test file:",testfile,"test/")
+calc("module:",module,"module/"); +calc("module:",module,"module/");
println('\n',rightpad("total:",padding_length),'| ',rightpad(str(all),6),'kb'); println(rightpad("total:",padding_length),'| ',rightpad(str(all),6),'kb');