Sort by

recency

|

22 Discussions

|

  • + 0 comments

    I have reached the next solution in common lisp, but the last test keeps failing with wrong result. I cannot undestand why, I have tested locally and the result seems to be the expected, and the performance is also good. Can anyone explain me what is the problem?

    (defun sumpent (n) (if (< n 2) 1 (+ (memopent (1- n)) (- (* 3 n) 2))))

    (let ((npast (make-hash-table))) (defun memopent (n) (let ((currval (gethash n npast))) (if currval currval (setf (gethash n npast) (sumpent n))))))

    (let ((n (read))) (loop for line from 0 below n do (format t "~a~%" (memopent (read)))))

  • + 0 comments

    So for haskell you have to kind of get weird with it. The list random access operator is too slow to solve this the way I think you normally would. What I do it generate the list of pentagonal numbers and then access them in the order the test cases require. I noticed that they are either ascending or descending but also in order up to the amount provided. That's how I got around using the !! operator. Let me know if there's an actual performant dp solution.

    import Data.List (scanl1)
    import Control.Monad (mapM_)
    
    -- vertices in a pentagon with each line containing n vertices
    pNums = scanl1 (\acc e -> acc + (e * 3 - 2)) [1 ..]
    
    main = do
        n <- getLine >>= return . read
        i <- getLine >>= return . read
        let nums = let ns = take n pNums in 
                    if i == 1 
                    then ns 
                    else reverse ns
        mapM_ (putStrLn . show) nums
    
  • + 0 comments

    Epic haskell slution

    main = interact $ unlines . map (show . (\n -> (3*n*n-n) `div` 2) . read) . tail . lines
    
  • + 0 comments

    compact clojure:

    (dotimes [t (read)]
      (let [n (read)]
        (println (/ (* n (- (* 3 n) 1))2))))
    
  • + 0 comments

    The honest-but-not-DP way:

    let pentagonals = 
        seq { 1L..100000L }
        |> Seq.scan (fun pentagonal idx -> pentagonal + idx * 3L - 2L) 0L
        |> Seq.toArray
    
    let n = Console.ReadLine() |> int
    for _ in seq { 1..n } do
        pentagonals |> Array.item (Console.ReadLine() |> int) |> printfn "%d"
    

    The cheating way:

    let pentagonal n = n * (1.5 * n - 0.5)
    let n = Console.ReadLine() |> int
    for _ in seq { 1..n } do
        Console.ReadLine() |> float |> pentagonal |> int64 |> printfn "%d"