Description

Given a string of words, you need to find the highest scoring word.

Each letter of a word scores points according to its position in the alphabet: a = 1, b = 2, c = 3 etc.

You need to return the highest scoring word as a string.

If two words score the same, return the word that appears earliest in the original string.

All letters will be lowercase and all inputs will be valid.

Solutions

Julia

# Highest-Scoring-Word.jl

using Test


"""
word 是字符串切割的产物,数据类型为 SubString{String}  
其父类为 AbstractString
"""
#> "word 是字符串切割的产物,数据类型为 SubString{String}  \n其父类为 AbstractString\n"
function get_score(word::AbstractString)::Int64
    # @show typeof(word)
    word |> collect .|> (char -> char - 'a' + 1) |> sum
end
#> get_score (generic function with 1 method)


function high(x::String)::String
    words = x |> split
    _, max_index = words .|> get_score |> findmax
    return words[max_index]
end
#> high (generic function with 1 method)


@test high("man i need a taxi up to ubud") == "taxi"
#> Test Passed
#>   Expression: high("man i need a taxi up to ubud") == "taxi"
#>    Evaluated: "taxi" == "taxi"
@test high("what time are we climbing up the volcano") == "volcano"
#> Test Passed
#>   Expression: high("what time are we climbing up the volcano") == "volcano"
#>    Evaluated: "volcano" == "volcano"

R

# Highest-Scoring-Word.R

library(tidyverse)
library(testthat)


get_value <- function(word) {
    word %>%
        str_split("") %>%
        unlist() %>%
        map_int(~match(.x, letters)) %>%
        sum()
}


high <- function(x) {
    words <- x %>%
        str_split(" ") %>%
        unlist()
    values <- words %>%
        map_int(get_value)
    words[which.max(values)]
}


# unit test
test_that("Sample Tests", {
    expect_equal(high("what time are we climbing up the volcano"), "volcano")
})
#> Test passed 😸

JavaScript

/**
 * @module Highest-Scoring-Word
 */

const sum = require("../src/JavaScript/toolkit/Statistics").sum;

function get_score(word) {
  return sum(word.split('').map(c => c.charCodeAt() - 'a'.charCodeAt() + 1));
}

function high(x) {
  const words = x.split(' ');
  const values = words.map(get_score);
  return words[values.indexOf(Math.max(...values))];
}

console.log(high('what time are we climbing up the volcano'));
#> volcano

Python

# Highest-Scoring-Word.py


#%%
def get_score(word):
    return sum([ord(c) - 96 for c in word])


#%%
def high(x):
    words = x.split()
    return max(words, key=get_score)


# %%
high("what time are we climbing up the volcano")

# %%
#> 'volcano'