Description

Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.

Notes:

Only lower case letters will be used (a-z). No punctuation or digits will be included. Performance needs to be considered.

Examples

scramble('rkqodlw', 'world') ==> True
scramble('cedewaraaossoqqyt', 'codewars') ==> True
scramble('katas', 'steak') ==> False

Solutions

Julia

using DataStructures
using Test


"""
if a portion of str1 characters can be rearranged to match str2
"""
#> "if a portion of str1 characters can be rearranged to match str2\n"
function scramble(str1::String, str2::String)
    dict1 = DataStructures.counter(str1)
    dict2 = DataStructures.counter(str2)

    [dict2[key]  dict1[key] for key  keys(dict2)] |> all
end
#> scramble (generic function with 1 method)


@test scramble("rkqodlw", "world") == true
#> Test Passed
#>   Expression: scramble("rkqodlw", "world") == true
#>    Evaluated: true == true
@test scramble("cedewaraaossoqqyt", "codewars") == true
#> Test Passed
#>   Expression: scramble("cedewaraaossoqqyt", "codewars") == true
#>    Evaluated: true == true
@test scramble("katas", "steak") == false
#> Test Passed
#>   Expression: scramble("katas", "steak") == false
#>    Evaluated: false == false

R

library(tidyverse)

scramble <- function(s1, s2) {
    table1 <- s1 %>%
        str_split("") %>%
        unlist() %>%
        table()

    table2 <- s2 %>%
        str_split("") %>%
        unlist() %>%
        table()

    map_lgl(.x = names(table2), .f = function(key) {
        if (!key %in% names(t1)) {
            return(FALSE)
        } else {
            return(table2[key] <= table1[key])
        }
    }) %>%
        all()
}