如何在两个坐标上对图像大小进行排序?

时间:2010-12-02 15:06:11

标签: sorting haskell

我有一个以XxX形式的字符串列表,其中X是长达4位的数字(它们是(像素)x(像素)中的图像大小)。

例如:

["192x192","64x84","96x96","64x64","292x192","32x32","64x12"]

使用mySort函数,它只是插入排序,仅查看最多x:

的数字
mysort []  = []
mysort [x] = [x]
mysort (x:xs) = insert (mysort xs)
    where insert [] = [x]
          insert (y:ys) | takeUntilX x <= takeUntilX y = x : y : ys
                        | otherwise = y : insert ys

我明白了:

["192x192","292x192","32x32","64x84","64x64","64x12","96x96"]

哪个只是部分排序,所有排序的“64x **”都按照原始顺序进行了重新排序,但我希望它们也可以排序,所以我得到了这个:

["192x192","292x192","32x32","64x12","64x64","64x84","96x96"]

什么是更好的解决方案 - 修改函数mySort或编写一个新的函数来排序部分排序的列表? 你能告诉我如何做的基本想法吗?

4 个答案:

答案 0 :(得分:8)

import Data.List
import Data.List.Split

res = map (intercalate "x") . sort . map (splitOn "x")

我正在使用http://hackage.haskell.org/package/split

中的Data.List.Split

答案 1 :(得分:3)

为了满足未来需求,您还可以:
1.将您的数据转换为元组,例如(64,64)
2.使用内置排序。它可以很好地满足您的需求

我认为将来你会将数据用作整数,所以尽早转换它们可以为你节省很多麻烦。

BR,
尤哈

答案 2 :(得分:0)

编辑:更正 - 我已经弄明白了你的意思。

我将问题分开 - (1)解析字符串以获得维度; (2)按您认为合适的尺寸排序; (3)将尺寸转换回字符串。换句话说:

import List

stringToDim :: String -> (String,String)
stringToDim s = (a,c)
    where    (a,b) = break (== 'x') s
             c = drop 1 b

dimToString :: (String,String) -> String
dimToString (x,y) = x ++ "x" ++ y

dimsort :: [String] -> [String]
dimsort = map dimToString . sort . map stringToDim

答案 3 :(得分:0)

好的,这是我很满意的最终解决方案,虽然它不是我原来要求的。来自max taldykin的修改后的副本:

res x = map (intercalate "x") $ map myshow $ sort $ map (readAsInt) $ map (splitOn "x") x

readAsInt [x,y] = [read x :: Int, read y ::Int]
myshow    [x,y] = [show x, show y]

input:  ["192x192","64x184","96x96","64x64","292x192","32x32","64x12"]
output: ["32x32","64x12","64x64","64x184","96x96","192x192","292x192"]

虽然它没有给出[“192x192”,“292x192”,“32x32”,“64x12”,“64x64”,“64x184”,“96x96”]但它仍然可以满足我的想法。 / p>