Skip to content

Ενδεικτική λύση εργαστηριακής άσκησης 4 2023-2024

Εκφώνηση

Λύση

Κώδικας σε Python

python_plain_timer.py
import os

from core import quicksort
from math import sqrt
from timeit import default_timer as timer


def main(input_file_name):
    points = []
    with open(input_file_name, "r") as fp:
        while True:
            line = fp.readline()
            if not line:
                break
            a_point = tuple(float(x) for x in line.split())
            distance = sqrt(a_point[0] ** 2 + a_point[1] ** 2 + a_point[2] ** 2)
            points.append((distance,) + a_point)

    start = timer()
    # points = quicksort(points)
    points.sort()
    time_passed = timer() - start
    print(f"Elapsed time for sorting alone: {time_passed:.6f}")

    output_file_name = f"{input_file_name[:-4]}-sorted-python-plain.txt"
    output_file_name = os.path.join(os.path.dirname(__file__), output_file_name)
    with open(output_file_name, "w") as fp:
        for a_point in points:
            fp.write(f"{a_point[1]} {a_point[2]} {a_point[3]}\n")


if __name__ == "__main__":
    inputs = ["input1000.txt", "input100000.txt", "input1000000.txt"]
    for input in inputs:
        input = os.path.join(os.path.dirname(__file__), input)
        start = timer()
        main(input)
        time_passed = timer() - start
        print(f"{input} - elapsed time {time_passed:.6f}")

Κώδικας σε Haskell

main.hs
import System.IO
import Data.List ( sort )

main :: IO()
main = do
--    let file_name = "input1000"
--    let file_name = "input10000"
--    let file_name = "input100000"
   let file_name = "input1000000"
   content <- readFile (file_name ++ ".txt")
   let points = lines content
       list_of_string_triples = map words points
       tmp = [(read (x!!0) :: Double, read (x!!1) :: Double, read (x!!2) :: Double) | x <- list_of_string_triples]
       list_of_double_triples =  [(distance x, x) | x <- tmp]
    --    list_of_double_triples_sorted = sort list_of_double_triples
       list_of_double_triples_sorted = quicksort list_of_double_triples
       list_of_double_triples_sorted2 = [snd x | x <- list_of_double_triples_sorted]
       list_of_double_triples_sorted3 = [show (get1st x) ++ " " ++ show (get2nd x) ++ " " ++ show (get3rd x) | x <- list_of_double_triples_sorted2]
--    print  list_of_double_triples_sorted3
   writeFile (file_name ++ "-sorted-haskell.txt") (unlines list_of_double_triples_sorted3)

get1st (a,_,_) = a

get2nd (_,a,_) = a

get3rd (_,_,a) = a

slice i j s = drop i (take j s)

distance (x,y,z) =
    sqrt (x**2 + y**2 + z**2)

quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
  let smallerSorted = quicksort [a | a <- xs, a <= x]
      biggerSorted = quicksort [a | a <- xs, a > x]
  in  smallerSorted ++ [x] ++ biggerSorted