This repository has been archived by the owner on Jan 18, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
/- | ||
# Problem 25 | ||
Generate a random permutation of the elements of a list. | ||
-/ | ||
variable {α : Type} [Inhabited α] [BEq α] | ||
|
||
/-- Randomly removes one element from the given list | ||
and returns the removed element and the remaining pairs of elements in the List. -/ | ||
def List.extractOne (univ : List α) : IO (Option α × List α) := do | ||
if univ == [] then | ||
return (none, []) | ||
|
||
let index ← IO.rand 0 (univ.length - 1) | ||
let element := univ.get! index | ||
let rest := univ.take index ++ univ.drop (index + 1) | ||
return (element, rest) | ||
|
||
def rndPermu (l : List α) : IO (List α) := do | ||
-- sorry | ||
let (element, rest) ← l.extractOne | ||
match element with | ||
| none => return [] | ||
| some e => | ||
return e :: (← rndPermu rest) | ||
-- sorry | ||
|
||
-- Avoid proving that the function terminates as a recursive function. | ||
-- You don't have to fill in the `sorry` here. | ||
decreasing_by sorry | ||
|
||
-- The following codes are for test and you should not edit these. | ||
|
||
def List.isPerm [BEq α] : List α → List α → Bool | ||
| [], l₂ => l₂.isEmpty | ||
| a :: l₁, l₂ => l₂.contains a && l₁.isPerm (l₂.erase a) | ||
|
||
def runTest [ToString α] (l : List α) : IO Unit := do | ||
let result ← rndPermu l | ||
let mut check := true | ||
check := check && result.isPerm l | ||
|
||
if l.length >= 30 then | ||
let result' ← rndPermu l | ||
if result == result' then | ||
throw <| .userError "failed: Your function is not random." | ||
|
||
if check then | ||
IO.println "ok!" | ||
else | ||
throw <| .userError s!"failed: rndPermu {l} = {result}" | ||
|
||
#eval runTest [1, 2, 3] | ||
|
||
#eval runTest ['a', 'a', 'a'] | ||
|
||
#eval runTest ([] : List Nat) | ||
|
||
#eval runTest (List.range 35) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters