Advertisement
Guest User

Untitled

a guest
May 28th, 2016
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
F# 2.05 KB | None | 0 0
  1. open System
  2. open Microsoft.FSharp.Linq
  3. open System.Linq
  4.  
  5. let GetRandomNumbers count =
  6.     let rnd = System.Random()
  7.     List.init count (fun _ -> (rnd.Next() % 100))
  8.  
  9. let rec BinarySearch (arr: Collections.Generic.List<int>, low:int, high:int, value:int) =
  10.     if (high < low) then
  11.         box None;
  12.     else
  13.         Console.WriteLine("Qual o proximo elemento a ser testado?");
  14.         let midGuess = Console.ReadLine();
  15.         let midGuessInt = Convert.ToInt32(midGuess);
  16.         let mid = (low + high) / 2
  17.  
  18.         if (mid <> midGuessInt) then
  19.             printf "Resposta correta %d" mid
  20.             Console.WriteLine();
  21.             null
  22.         else
  23.             if (arr.[mid] > value) then
  24.                     BinarySearch (arr, low, mid-1, value)
  25.                 else if (arr.[mid] < value) then
  26.                     BinarySearch (arr, mid+1, high, value)
  27.                 else
  28.                     match box arr.[mid] with
  29.                         | null -> box None
  30.                         | x -> box(Some(x))
  31.  
  32.  
  33. let PrintIndexes (high: int) =
  34.     for i = 0 to high do
  35.         printf "%d   " i
  36.  
  37. let PrintList(list: Collections.Generic.List<int>) =
  38.     for i = 0 to list.Count - 1 do
  39.         printf "%d  " (list.ElementAt(i))
  40.  
  41. [<EntryPoint>]
  42. let main argv =
  43.     let list = GetRandomNumbers(10);
  44.     let list = list.OrderBy((fun x -> x)).ToList();
  45.  
  46.     PrintIndexes (list.Count - 1)
  47.     Console.WriteLine();
  48.    
  49.     PrintList list;
  50.     Console.WriteLine();
  51.  
  52.     let random = new Random();
  53.     let value = random.Next(0, list.Count - 1);
  54.  
  55.     printf "Indique quais sao elementos testados para a pesquisa do elemento %d" (list.ElementAt(value))
  56.     Console.WriteLine();
  57.    
  58.     let result = BinarySearch(list, 0, list.Count - 1, list.ElementAt(value))
  59.    
  60.     if result <> null then
  61.         Console.WriteLine("Voce acertou");
  62.     else
  63.         Console.WriteLine("Voce errou");
  64.  
  65.     Console.WriteLine(result)
  66.     Console.WriteLine("Press any key to continue...");
  67.     Console.ReadLine() |> ignore
  68.     0 // return an integer exit code
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement