Permutations/Derangements: Difference between revisions

m (→‎Using a module: Add libheader)
Line 2,393:
 
=={{header|PureBasic}}==
Brute Force
{{incomplete|PureBasic|Missing the subfactorial !n.}}
Brute Force: Tested up to n=10
<lang PureBasic>
 
Procedure.q perm(n)
ifIf n=0:ProcedureReturn 1:endifEndIf
ifIf n=1:ProcedureReturn 0:endifEndIf
ProcedureReturn (perm(n-1)+perm(n-2))*(n-1)
EndProcedure
 
factFile.s="factorials.txt"
tempFile.s="temp.txt"
Line 2,409 ⟶ 2,407:
DeleteFile(tempFile.s)
DeleteFile(drngFile.s)
 
n=4
 
; create our storage file
f.s=factFile.s
If CreateFile(21130,f.s)
WriteStringN(21130,"1.2")
WriteStringN(21130,"2.1")
CloseFile(21130)
Else
Debug "not createfile :"+f.s
EndIf
 
showfactorial=#FALSEFalse
 
ifIf showfactorial
; cw("nfactorial n ="+str(n))
Debug "nfactorial n ="+strStr(n)
EndIf
endif
 
; build up the factorial combinations
forFor l=1 toTo n-2
gosubGosub nfactorial
Next
next
 
; extract the derangements
; cw("derangements["+str(perm(n))+"] for n="+str(n))
Debug "derangements["+strStr(perm(n))+"] for n="+strStr(n)
gosubGosub derangements
; cw("")
Debug ""
 
; show the first 20 derangements
forFor i=0 toTo 20
; cw("derangements["+str(perm(i))+"] for n="+str(i))
Debug "derangements["+strStr(perm(i))+"] for n="+strStr(i)
Next
next
end
 
End
derangements:
x=0
If ReadFile(21120,factFile.s) andAnd CreateFile(21131,drngFile.s)
Repeat
repeat
r.s = ReadString(21120)
cs=CountString(r.s,".")
ifIf cs
hit=0
t.s=""
; scan for numbers at their index
forFor i=1 toTo cs+1
s.s=StringField(r.s,i,".")
t.s+s.s+"."
ifIf valVal(s.s)=i:hit+1:endifEndIf
Next
next
t.s=rtrimRTrim(t.s,".")
; show only those which are valid
ifIf notNot hit
x+1
; cw(t.s+" "+str(x))
Debug t.s+" "+strStr(x)
WriteStringN(21131,t.s+" "+strStr(x))
EndIf
endif
EndIf
endif
Until Eof(0)
until eof(2112)
CloseFile(21120)
CloseFile(21131)
Else
Debug "not readfile :"+factFile.s
Line 2,481 ⟶ 2,480:
; cw("")
Debug ""
Return
return
 
nfactorial:
x=0
If ReadFile(21120,factFile.s) andAnd CreateFile(21131,tempFile.s)
Repeat
repeat
r.s = ReadString(21120)
cs=CountString(r.s,".")
ifIf cs
forFor j=1 toTo cs+2
t.s=""
forFor i=1 toTo cs+1
s.s=StringField(r.s,i,".")
ifIf i=j
t.s+"."+strStr(cs+2)+"."+s.s
Else
else
t.s+"."+s.s
EndIf
endif
Next
next
ifIf j=cs+2:t.s+"."+strStr(cs+2):endifEndIf
t.s=trimTrim(t.s,".")
x+1
ifIf cs+2=n andAnd showfactorial
; cw(t.s+" "+str(x))
Debug t.s+" "+strStr(x)
EndIf
endif
WriteStringN(21131,t.s)
Next
next
EndIf
endif
Until Eof(0)
until eof(2112)
CloseFile(21120)
CloseFile(21131)
Else
Debug "not readfile :"+factFile.s
Line 2,519 ⟶ 2,518:
CopyFile(tempFile.s,factFile.s)
DeleteFile(tempFile.s)
Return
return
</lang>
 
Anonymous user