fork download
  1. open System
  2.  
  3. let rand = Random()
  4.  
  5. let cprintf color format =
  6. Printf.kprintf (fun str ->
  7. let originalColor = Console.ForegroundColor
  8. try
  9. Console.ForegroundColor <- color
  10. Console.Write str
  11. finally
  12. Console.ForegroundColor <- originalColor
  13. ) format
  14.  
  15. type TreeBuilder(maxWidth, trunkChar, leafChar) =
  16. let PrintReturn() =
  17. printfn ""
  18.  
  19. let PrintSpace() =
  20. printf " "
  21.  
  22. let PrintLeaf() =
  23. if rand.Next(4) = 0 then //20% chance to print bauble?
  24. cprintf (enum<ConsoleColor> (rand.Next(1,15))) "%c" 'o'
  25. else
  26. cprintf ConsoleColor.Green "%c" leafChar
  27.  
  28. let PrintTrunk() =
  29. cprintf ConsoleColor.Yellow "%c" trunkChar
  30.  
  31. member this.PrintTree() =
  32. for level in (maxWidth / 2) .. -1 .. -1 do
  33. let width =
  34. match level with
  35. | -1 -> 3
  36. | _ -> maxWidth - 2 * level
  37. let padding = (maxWidth - width) / 2
  38. for index in 0 .. maxWidth do
  39. match index with
  40. | _ when index = maxWidth -> PrintReturn()
  41. | _ when index < padding -> PrintSpace()
  42. | _ when index >= padding + width -> PrintSpace()
  43. | _ when level = -1 -> PrintTrunk()
  44. | _ -> PrintLeaf()
  45.  
  46.  
  47. type TreePrinter(input: string) =
  48. let args = input.Split(' ')
  49.  
  50. member this.Print() =
  51. try
  52. let maxWidth = Int32.Parse(args.[0])
  53. let trunkChar = Char.Parse(args.[1])
  54. let leafChar = Char.Parse(args.[2])
  55.  
  56. if maxWidth < 3 || maxWidth > 21 then
  57. raise(NotSupportedException("Tree size is out of range."))
  58. if maxWidth % 2 = 0 then
  59. raise(NotSupportedException("Tree size must be odd."))
  60.  
  61. let tree = new TreeBuilder(maxWidth, trunkChar, leafChar)
  62. printfn "%d character wide tree printed with '%c' trunk and '%c' leaves:"
  63. maxWidth trunkChar leafChar
  64. tree.PrintTree()
  65. printfn ""
  66. with
  67. | ex -> printfn "Input was not valid: %s" ex.Message
  68.  
  69. [<EntryPoint>]
  70. let main argv =
  71. TreePrinter("3 # *").Print()
  72. TreePrinter("13 = +").Print()
  73. TreePrinter("21 | _").Print()
  74. //System.Console.ReadLine() |> ignore
  75. 0 // return an integer exit code
Success #stdin #stdout 0.11s 12024KB
stdin
Standard input is empty
stdout
3 character wide tree printed with '#' trunk and '*' leaves:
 * 
**o
###

13 character wide tree printed with '=' trunk and '+' leaves:
      +      
     +++     
    ++++o    
   +++o+++   
  +++++o+++  
 ++++oo+++++ 
+o++++++oo+++
     ===     

21 character wide tree printed with '|' trunk and '_' leaves:
          o          
         _o_         
        o__o_        
       _o____o       
      _oo____o_      
     __o_o_____o     
    ___o_________    
   _oo____o_oo___o   
  _______o___o__o_o  
 o____o__________o_o 
_____o___o__________o
         |||