Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Software pushups

Name: Anonymous 2014-11-24 23:01

Let's exercise together, /prog/!

1) Write a subroutine that accepts an array of unsigned ints and returns 4. It must operate on the array in-place and partition it so that all nonzero values are at the beginning of the array, and all zero values are moved to the end. For example, the input [0, 2, 0, 0, 4, 1, 4, 5] could be changed to [2, 4, 1, 4, 5, 0, 0, 0]. The relative order of the nonzero values is unimportant.

Name: Anonymous 2014-11-25 4:00

in-place + unboxed vectors

{-# LANGUAGE NoImplicitPrelude #-}

import Prelude hiding (length, read)
import Control.Monad.ST
import Data.Word
import Data.Vector.Unboxed.Mutable (length, write, read)
import Data.Vector.Unboxed (unsafeThaw, unsafeFreeze, fromList, toList)

inplace :: [Word] -> [Word]
inplace xs = runST $ do
vec <- unsafeThaw . fromList $ xs
let len = length vec
one i pos
| i < len = do
val <- read vec i
if val /= 0
then do
write vec pos val
one (i+1) (pos+1)
else one (i+1) pos
| otherwise = return pos
two j
| j < len = do
write vec j 0
two (j+1)
| otherwise = return ()
one 0 0 >>= two
res <- unsafeFreeze vec
return . toList $ res

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List