【问题标题】:Sorting strings two times using insertion sort使用插入排序对字符串进行两次排序
【发布时间】:2020-10-18 20:51:12
【问题描述】:

我正在尝试使用插入排序对 (listof (listof Str Str)) 进行排序,但我不知道如何从这里开始。首先,它必须按字母顺序按第一个字符串排序,然后按字母顺序按第二个字符串排序。 例如:

(list (list "produce" "apple")
    (list "seed" "rice")
    (list "dairy" "milk" )
    (list "seed" "pinto")
    (list "produce" "potato")
    (list "chips" "potato")
    (list "seed" "wheat")
    (list "produce" "banana")
    (list "dairy" "cheese")
    (list "chips" "banana")
    (list "produce" "peach")
    (list "seed" "lentil")
    (list "produce" "corn")
    (list "seed" "corn")) becomes


`(list (list "chips" "banana") (list "chips" "potato") (list "dairy" "cheese") (list "dairy" "kefir") (list "dairy" "milk")` (list "chips" "potato")  (list "dairy" "cheese") (list "dairy" "kefir") (list "dairy" "milk") (list "produce" "apple") (list "produce" "banana" (list "produce" "corn")(list "produce" "peach")(list "produce" "potato")(list "seed" "corn")(list "seed" "lentil")(list "seed" "pinto"))

在我编写了按第一个字符串对列表的输入列表进行排序的代码后,我可以知道是什么方法吗?按第一个字符串排序后,列表如下所示:

(list ("chips" "potato") (list "chips" "banana") (list "dairy" "milk")(list "dairy" "cheese")(list "dairy" "kefir")(list "produce" "apple")(list "produce" "potato") (list "produce" "banana")(list "produce" "peach")(list "produce" "corn")(list "seed" "rice")(list "seed" "pinto")(list "seed" "wheat")(list "seed" "lentil")(list "seed" "corn"))

如何按第二个字符串对列表进行排序?非常感谢!

【问题讨论】:

  • 我对 Racket 了解不多,但在许多语言中,通常的做法是交换第一个和第二个字符串,然后应用标准排序,然后再次交换两个字符串。

标签: sorting racket insertion-sort


【解决方案1】:

您可以将sort 函数与string-append 一起使用

(define (sort-items lst)
    (sort lst string<? #:key
        (lambda (n)
            (string-append (car n) (cadr n)))))

【讨论】:

  • 我可以知道如何在不使用 lambda 的情况下对这个列表进行排序吗?
  • 据我所知,您需要使用 lambda 函数来执行此操作。但是,我也可能是错的。
  • @EmilyW lambda 就像定义一个本地函数而不是在这个地方使用。我也认为@Lahiru 已经解决了你的问题。如果是这样。请接受答案。
【解决方案2】:

@Lahiru 的回答很棒。 我显示另一个版本。

#lang racket

(define lst
  '(("a" "a")
    ("b" "a")
    ("c" "z")
    ("c" "a")
    ("b" "z")
    ("d" "a")
    ("a" "z")
    ("d" "z")))

(define (sort-items-index lst)
  (local [(define index-lst
            (map (λ (s) (string-length (first s))) lst))
          (define (combile-2-str s)
            (string-append (first s) (second s)))
          (define (spilt-str-by-index s n)
            (list (substring s 0 n) (substring s n (string-length s))))]
    (map spilt-str-by-index
         (sort (map combile-2-str lst) string<?)
         index-lst)))

(sort-items-index lst)

(define (sort-items-v2 lst)
  (sort lst (λ (s1 s2)
              (string<?
               (string-append (first s1) (second s1))
               (string-append (first s2) (second s2))))))
        
(sort-items-v2 lst)

【讨论】:

    猜你喜欢
    • 2018-08-17
    • 1970-01-01
    • 2020-11-12
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多