Skip to content
This repository has been archived by the owner on Jan 18, 2025. It is now read-only.

Commit

Permalink
add P25
Browse files Browse the repository at this point in the history
  • Loading branch information
Seasawher committed Mar 27, 2024
1 parent f1ab9b7 commit a0ae97c
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
58 changes: 58 additions & 0 deletions Src/Problem25.lean
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)
1 change: 1 addition & 0 deletions md/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
* [22: Integers within a range](./build/Problem22.md)
* [23: Random selection](./build/Problem23.md)
* [24: Draw N diffrent random numbers](./build/Problem24.md)
* [25: Random permutation](./build/Problem25.md)

# 31-40: Arithmetic

Expand Down

0 comments on commit a0ae97c

Please sign in to comment.