Description

Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should have in the result.

Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).

If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.

Examples

"is2 Thi1s T4est 3a"  -->  "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2"  -->  "Fo1r the2 g3ood 4of th5e pe6ople"
""  -->  ""

Solutions

Julia

using Pipe
using Test


function extract_number(s::AbstractString)::Int64
    @pipe match(r"\d", s).match |> parse(Int, _)
end
#> extract_number (generic function with 1 method)

@assert extract_number("T4est") == 4 "Something wrong in extracting numbers."


function order(words::String)::String
    @pipe words |> split |> sort(_, by=extract_number) |> join(_, " ")
end
#> order (generic function with 1 method)

@test order("is2 Thi1s T4est 3a") == "Thi1s is2 3a T4est"
#> Test Passed
#>   Expression: order("is2 Thi1s T4est 3a") == "Thi1s is2 3a T4est"
#>    Evaluated: "Thi1s is2 3a T4est" == "Thi1s is2 3a T4est"

R

## Your order, please

library(tidyverse)


#' 一个句子的各单词中含数字,按照数字的顺序对单词重排序
your_order <- function(sentence) {
    words <- sentence %>%
        str_split(" ") %>%
        unlist()

    numbers <- words %>%
        map_dbl(readr::parse_number)  # 用parse_number()提取数字,不用正则

    words[order(numbers)] %>%
        str_c(collapse = " ")
}


library(testthat)
test_that("Example Test", {
    expect_equal(your_order("is2 Thi1s T4est 3a"), "Thi1s is2 3a T4est")
})
#> Test passed 🌈

JavaScript



function order(words) {
  parseNumber = s => parseInt(s.match(/\d/g));

  return words.split(" ")
    .sort((a, b) => parseNumber(a) - parseNumber(b))
    .join(" ");
}

console.log(order("is2 Thi1s T4est 3a"));
#> Thi1s is2 3a T4est