Write a function which takes a sentence as an input and output a sorted sentence.
1.Each character of the word should be arranged in alphabetical order
Note: - Word only can have lowercase letters
Example :
Inputs str = "she lives with him in a small apartment"
Output = "a in ehs him hitw eilsv allms aaemnprtt"
function makeAlphabetSentenceSort(str) {
var word = str.split(' ');
for (var j = 0; j < word.length; j++) {
word[j] = word[j].split('').sort().join('');
}
for (var h = 0; h < word.length - 1; h++) {
for (var i = 0; i < word.length - h - 1; i++) {
if (String(word[i]).length > String(word[i + 1]).length) {
var temp = word[i];
word[i] = word[i + 1];
word[i + 1] = temp;
}
}
}
return word.join(' ');
}
console.log(makeAlphabetSentenceSort("she lives with him in a small apartment"));
ERROR message is "The answer should be valid for any given input."
Upon further reflection, it's clear that their challenge isn't following their own rules. It clearly states:
Word only can have lowercase letters
Yet, it runs this through the code (with punctuation):
he was curious about how it would taste, so he took a small bite.
To make matters worse, it expects the following output, which places how
before saw
, even though how
appears after saw
:
a eh it os eh how asw koot .beit allms dlouw abotu ,aestt ciorsuu
So, to be able to pass this challenge, you're also going to need to swap words of the same length with each other.
The following produces the correct results in NodeJS, but not in the browser, in fact, sort()
gave me different results in different browsers!
function makeAlphabetSentenceSort(str) {
var word = str.split(' ');
for (var j = 0; j < word.length; j++) {
word[j] = word[j].split('').sort().join('');
}
return word.sort((a, b) => a.length - b.length).join(' ');
}
console.log(makeAlphabetSentenceSort('he was curious about how it would taste, so he took a small bite.'));
I then read about why sort is so unreliable, and this article is a great resource, unfortunately, the solution in it provides reliable results, but not in the way this challenge expects it.
https://medium.com/@fsufitch/is-javascript-array-sort-stable-46b90822543f
http://ccc.fidenz.com/en/challenges/challenges/challenge--86
This is a horribly designed challenge, you really should focus your efforts on a better website to practice programming, such as HackerRank, instead of this hodgepodge mess.