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
# valkmjolnir 2021/4/2
var sort=func(vec,left,right,cmp=func(a,b){return a<=b;}){
if(left>=right) return nil;
var (L,R,tmp)=(left,right,vec[left]);
while(left<right){
while(left<right and cmp(tmp,vec[right]))
right-=1;
while(left<right and cmp(vec[left],tmp))
left+=1;
if(left!=right)
(vec[left],vec[right])=(vec[right],vec[left]);
# please make sure the compare function has the function like <= or >=
# only using < or > may cause infinite loop or the program may crash
var sort=func(){
srand(); # be aware! this causes global changes
return func(vec,left,right,cmp=func(a,b){return a<=b;}){
if(left>=right) return nil;
var base=left+int(rand()*(right-left));
(vec[left],vec[base])=(vec[base],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=""){
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){
var s=io.fin(getname(path~files[i]));
(line_cnt,semi_cnt)=(count(s,'\n'),count(s,';'));
println(rightpad(files[i],padding_length),'| ',
column(line_cnt),'line | ',
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);
ctx~=s;
line+=line_cnt;
semi+=semi_cnt;
}
println(rightpad("total:",padding_length),'| ',
column(line),'line | ',
column(semi),'semi | ',
rightpad(str(int(bytes/1024)),6),'kb');
rightpad(str(int(bytes/1024)),6),'kb | ',
md5(ctx),' |\n');
return int(bytes/1024);
}
@ -140,4 +143,4 @@ var all=calc("source code:",source)
+calc("lib:",lib,"stl/")
+calc("test file:",testfile,"test/")
+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');