- 1
IT Оффтоп #223
Нашли или выдавили из себя код, который нельзя назвать нормальным, на который без улыбки не взглянешь? Не торопитесь его удалять или рефакторить, — запостите его на говнокод.ру, посмеёмся вместе!
0
IT Оффтоп #223
#193: https://govnokod.ru/28911 https://govnokod.xyz/_28911
#194: https://govnokod.ru/28914 https://govnokod.xyz/_28914
#195: https://govnokod.ru/28917 https://govnokod.xyz/_28917
#196: https://govnokod.ru/28925 https://govnokod.xyz/_28925
#197: https://govnokod.ru/28935 https://govnokod.xyz/_28935
#198: https://govnokod.ru/28938 https://govnokod.xyz/_28938
#199: https://govnokod.ru/28942 https://govnokod.xyz/_28942
#200: https://govnokod.ru/28945 https://govnokod.xyz/_28945
#201: https://govnokod.ru/28948 https://govnokod.xyz/_28948
#202: https://govnokod.ru/28951 https://govnokod.xyz/_28951
#203: https://govnokod.ru/28954 https://govnokod.xyz/_28954
#204: https://govnokod.ru/28971 https://govnokod.xyz/_28971
#205: https://govnokod.ru/28986 https://govnokod.xyz/_28986
#206: https://govnokod.ru/28991 https://govnokod.xyz/_28991
#207: https://govnokod.ru/29002 https://govnokod.xyz/_29002
#208: https://govnokod.ru/29060 https://govnokod.xyz/_29060
#209: https://govnokod.ru/29070 https://govnokod.xyz/_29070
#210: https://govnokod.ru/29079 https://govnokod.xyz/_29079
#211: https://govnokod.ru/29092 https://govnokod.xyz/_29092
#212: https://govnokod.ru/29093 https://govnokod.xyz/_29093
#213: https://govnokod.ru/29104 https://govnokod.xyz/_29104
#214: https://govnokod.ru/29114 https://govnokod.xyz/_29114
#215: https://govnokod.ru/29125 https://govnokod.xyz/_29125
#216: https://govnokod.ru/29132 https://govnokod.xyz/_29132
#217: https://govnokod.ru/29147 https://govnokod.xyz/_29147
#218: https://govnokod.ru/29156 https://govnokod.xyz/_29156
#219: https://govnokod.ru/29166 https://govnokod.xyz/_29166
#220: https://govnokod.ru/29181 https://govnokod.xyz/_29181
#221: https://govnokod.ru/29185 https://govnokod.xyz/_29185
#222: https://govnokod.ru/29190 https://govnokod.xyz/_29190
0
void makeShape(ShapeArguments shape)
{
if (shape.type == ShapeType::Square)
{
throw Square(shape);
}
if (shape.type == ShapeType::Cicle)
{
throw Circle(shape);
}
}
void handleShape(ShapeArguments shape)
{
try
{
makeShape(shape);
}
catch (const Square& square)
{
// Work with square
}
catch (const Circle& circle)
{
// Work with circle
}
}
factory
0
{-# LANGUAGE BangPatterns #-}
import Data.List (intercalate)
-- Тип для представления пары значений
data TwoVal = TwoVal !Int !Int
deriving (Show, Eq)
-- Тип для пары с флагом обмена
data TwoValAndStatus = TwoValAndStatus
{ isSwapped :: !Bool
, twoVal :: !TwoVal
} deriving (Show, Eq)
-- Тип для массива (используем список для идиоматичности Haskell)
type Array = [Int]
-- Тип для массива с состоянием сортировки
data ArrayAndStatus = ArrayAndStatus
{ hasSwap :: !Bool
, position :: !Int
, array :: !Array
} deriving (Show, Eq)
-- Сортировка двух элементов с возвратом статуса обмена
sort2 :: TwoVal -> TwoValAndStatus
sort2 (TwoVal a b)
| a > b = TwoValAndStatus True (TwoVal b a)
| otherwise = TwoValAndStatus False (TwoVal a b)
-- Чтение пары значений из массива по позиции
readTwoVal :: Array -> Int -> Maybe TwoVal
readTwoVal arr pos
| pos < length arr - 1 = Just $ TwoVal (arr !! pos) (arr !! (pos + 1))
| otherwise = Nothing
-- Сохранение значения в массив по индексу
storeVal :: Array -> Int -> Int -> Array
storeVal arr val pos =
take pos arr ++ [val] ++ drop (pos + 1) arr
-- Сохранение пары значений в массив
storeTwoVal :: Array -> TwoVal -> Int -> Array
storeTwoVal arr (TwoVal a b) pos =
storeVal (storeVal arr a pos) b (pos + 1)
-- Рекурсивная функция сортировки пузырьком
bubbleSortRec :: ArrayAndStatus -> ArrayAndStatus
bubbleSortRec state@(ArrayAndStatus swap pos arr)
| pos >= length arr - 1 =
if not swap
then state -- Сортировка завершена!
else bubbleSortRec $ ArrayAndStatus False 0 arr -- Новый проход
| otherwise =
case readTwoVal arr pos of
Nothing -> state
Just pair -> -- ← Переименовали переменную здесь
let sortResult = sort2 pair
newArr = storeTwoVal arr (twoVal sortResult) pos -- ← Используем селектор twoVal
newSwap = swap || isSwapped sortResult
in bubbleSortRec $ ArrayAndStatus newSwap (pos + 1) newArr
-- Основная функция сортировки
bubbleSort :: Array -> Array
bubbleSort arr = array $ bubbleSortRec $ ArrayAndStatus False 0 arr
-- Более идиоматичная версия для Haskell (альтернативная реализация)
bubbleSortIdiomatic :: Ord a => [a] -> [a]
bubbleSortIdiomatic = untilFixed bubblePass
where
bubblePass [] = []
bubblePass [x] = [x]
bubblePass (x:y:xs)
| x > y = y : bubblePass (x:xs)
| otherwise = x : bubblePass (y:xs)
untilFixed f x = let fx = f x
in if fx == x then x else untilFixed f fx
-- Функция для красивого вывода
showArray :: Show a => [a] -> String
showArray = intercalate ", " . map show
-- Главная функция
main :: IO ()
main = do
let initialArray = [8, 2, 4, 1, 3, 5, 7, 0, 6, 9]
let sortedArray = bubbleSort initialArray
putStrLn "input"
putStrLn $ showArray initialArray
putStrLn "\nsort:"
putStrLn $ showArray sortedArray
putStrLn "\nsort2:"
putStrLn $ showArray $ bubbleSortIdiomatic initialArray
Переписал через "ИИ" свою чисто-функциональную сортировку пузырьком на "Haskell". Оригинальный код на Си в https://govnokod.ru/27880#comment755323