例如:“今天,是有史以來最偉大的一天!” 應該回傳最大,因為它有 2 個 e(和 2 個 t),而且它比以前也有 2 個 e。如果沒有重復字母的單詞回傳-1。單詞將用空格分隔。輸入:“Hello Apple Pie” 輸出應該是:“Hello” 不明白我的代碼有什么問題,如果您認為有更簡單、更短的解決方法,我很想聽聽。在此先感謝您的幫助。
function LetterCountI(str) {
let unique=[... new Set(str)]
if(unique==str){
return -1}
let arr= str.split(" ")
let array=arr.map(item=>{
let temparr=item.split("")
return temparr.reduce((acc,curr)=>{
acc[curr]=acc[curr]? acc[curr] 1:1
if(acc[curr]>acc.max){
acc.max=acc[curr]}
return acc},{max:1, word:item})})
let amount=1
let largest=""
for(let item of arr){
if( item.max>amount){
amount=item.max
largest=item.word
}
}
return largest
}
uj5u.com熱心網友回復:
從獲取單詞中每個字母的頻率的簡單問題開始......
// given "sassy", will return { s:3, a:1, y:1 }
function letterFrequency(word) {
return word.split('').reduce((acc, letter) => {
if (!acc[letter]) acc[letter] = 0;
acc[letter] ;
return acc;
}, {});
}
獲得最大頻率的一個簡單問題......
// given { s:3, a:1, y:1 }, will return 3
function maxLetterFrequency(word) {
return Math.max(...Object.values(letterFrequency(word)));
}
另一個按頻率對句子排序的簡單問題......
// given "She sells seashells by the seashore"
// returns ["seashells", "sells", "seashore", "She", "by", "the"]
function wordsOrderedByMaxLetterFrequency(sentence) {
let words = sentence.split(' ');
words.sort((a, b) => {
return maxLetterFrequency(b) - maxLetterFrequency(a);
});
return words;
}
結果陣列中的第一個單詞就是答案。您可以重新測驗該單詞中的最大頻率以確定答案應為 -1。
演示...
// given "sassy", will return { s:3, a:1, y:1 }
function letterFrequency(word) {
return word.split('').reduce((acc, letter) => {
if (!acc[letter]) acc[letter] = 0;
acc[letter] ;
return acc;
}, {});
}
// given { s:3, a:1, y:1 }, will return 3
function maxLetterFrequency(word) {
return Math.max(...Object.values(letterFrequency(word)));
}
// given "She sells seashells by the seashore"
// returns ["seashells", "sells", "seashore", "She", "by", "the"]
function wordsOrderedByMaxLetterFrequency(sentence) {
let words = sentence.split(' ');
words.sort((a, b) => {
return maxLetterFrequency(b) - maxLetterFrequency(a);
});
return words;
}
const sentence = "She sells seashells by the seashore";
const sorted = wordsOrderedByMaxLetterFrequency(sentence);
console.log(sorted);
console.log('best word:', sorted[0]);
console.log('max freq in best word:', maxLetterFrequency(sorted[0]));
uj5u.com熱心網友回復:
我最初的方法將涉及分離一個maxBy函式,該函式接受一個從輸入值中提取比較數的函式,并將一個函式從一個值串列回傳到其中最大的一個。
然后我們可以撰寫letterCount來計算字串中各種字母的出現次數,并用一個函式將其包裝起來,該函式maxLetterCount計算一個字串的最大字母數,使用Math .max來自 的值letterCount,并撰寫我們的主函式將您的初始字串拆分為單詞并根據單詞串列呼叫maxByusing maxLetterCount。它可能看起來像這樣:
// DO NOT USE -- Doesn't meet all requirements!
const maxBy = (fn) => (xs) => xs .reduce (
({m, r}, x) => {const v = fn(x); return v > m ? {m: v, r: x} : {m, r}},
{m: -Infinity}
) .r
const letterCount = ([...cs]) =>
cs .reduce ((a, c) => {a [c] = (a [c] || 0) 1; return a}, {})
const maxLetterCount = (cs) =>
Math .max (... Object .values (letterCount (cs)))
const letterCountI = (s) =>
maxBy (maxLetterCount) (s .split (/\s /))
console .log (letterCountI ("Today, is the greatest day ever!"))
console .log (letterCountI ("Hello Apple Pie"))
但是這種方法存在一個問題。沒有考慮您的要求,如果沒有重復的字母,我們必須回傳-1。現在,letterCountI ("Today is the day")將回傳"Today"。
解決此問題的一種方法可能是將單詞與其最大字母數配對,將這些對過濾為僅具有多次出現字母的單詞,然后maxBy再次在對上使用,最后將單詞從獲勝對中拉出。為了處理這種-1情況,我們可以在過濾串列中插入一個虛擬對,-1用于單詞和-Infinity字母計數。如果串列是空的,那么我們將選擇這個。
這樣做可能會導致我們向 . 添加一些默認行為maximumBy,目前僅限于數字,但理想情況下應該與我們可以使用<. 如果我們默認了 的下限-Infinity,但允許覆寫,并將其與空串列的默認值配對,那么我們可能可以以相當簡單的方式完成上述操作。1
但這感覺有點過于復雜了。也許更簡單的方法是簡單地執行上面的代碼,然后測驗結果單詞是否有任何重復的字母。雖然我們可以通過該函式跟蹤這一點,但我認為最簡單的版本是再次呼叫letterCount它。所以這就是我可能會選擇撰寫這個函式的方式:
const maxBy = (fn) => (xs) => xs .reduce (
({m, r}, x) => {const v = fn(x); return v > m ? {m: v, r: x} : {m, r}},
{m: -Infinity}
) .r
const letterCount = ([...cs]) =>
cs .reduce ((a, c) => {a [c] = (a [c] || 0) 1; return a}, {})
const maxLetterCount = (cs) =>
Math .max (... Object .values (letterCount (cs)))
const letterCountI = (s, target = maxBy (maxLetterCount) (s .split (/\s /))) =>
maxLetterCount (target) > 1 ? target : -1
console .log (letterCountI ("Today, is the greatest day ever!"))
console .log (letterCountI ("Hello Apple Pie"))
console .log (letterCountI ("Today, is the day!"))
1這可能看起來像這個(未經測驗的)版本:
const maximumBy = (fn, {dfltVal = '', lowBound = -Infinity} = {}) => (xs) => xs .reduce (
({m, r}, x) => {const v = fn(x); return v > m ? {m: v, r: x} : {m, r}},
{m: lowBound, r: dfltVal}
) .r
uj5u.com熱心網友回復:
繼續使用基于 OP 的reduce方法,將提供一個函式,該函式包含兩個特定的嵌套reduce任務,負責 1)聚合一個句子的單詞特定統計資料和 2)每個單詞的字母特定統計資料。如果只有唯一(非重復)字母/字符的單詞,這種方法還可以確保''(建議的)或-1(OP 的要求)的結果。
function getFirstOccurringWordOfMaximumSameCharacterCount(value) {
function aggregateCharCountData(wordStats, char, idx, arr) {
const { charStats } = wordStats;
// aggregate character specific array.
(charStats[char] ??= []).push(char);
if (idx >= (arr.length - 1)) {
// console.log({ charStats });
// aggregate maximum character count data
// at the end of the last character reduce step.
const maxCharList = Object
.values(charStats)
.sort((aCharList, bCharList) =>
bCharList.length - aCharList.length
)[0];
wordStats.maxCharCount = maxCharList.length;
wordStats.maxCountChar = maxCharList[0];
}
return wordStats;
}
function aggregateWordSpecificCharCountData(collector, word, idx, arr) {
const { statistics } = collector;
statistics.push(
word
.split('')
.reduce(aggregateCharCountData, { word, charStats: {} })
);
if (idx >= (arr.length - 1)) {
// find the first occurring word of maximum same character count
// at the end of the last word reduce step.
const wordStats = statistics
.sort((aWordStats, bWordStats) =>
bWordStats.maxCharCount - aWordStats.maxCharCount
)[0];
// console.log({ statistics });
collector.result = (wordStats.maxCharCount >= 2)
? wordStats.word
: ''; // : -1;
}
return collector;
}
const {
// statistics,
result,
} = String(value)
.split(/\s /)
.reduce(aggregateWordSpecificCharCountData, {
statistics: [],
result: '',
});
// console.log({ statistics });
return result;
}
console.log([
'Today is the day.', // ''
'Today, is the greatest day ever!', // 'greatest'
'Hello Apple Pie', // 'Hello'
'She sells seashells by the seashore' // 'seashells'
].map(getFirstOccurringWordOfMaximumSameCharacterCount));
.as-console-wrapper { min-height: 100%!important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/454064.html
標籤:javascript 数组 算法 排序 减少
