Skip to content

Instantly share code, notes, and snippets.

@anushshukla
Created April 16, 2022 13:17
Show Gist options
  • Select an option

  • Save anushshukla/4d17b230f51de21814b5b167479bd7c7 to your computer and use it in GitHub Desktop.

Select an option

Save anushshukla/4d17b230f51de21814b5b167479bd7c7 to your computer and use it in GitHub Desktop.
Reverse the line as per word length in ascending
'use strict';
const fs = require('fs');
process.stdin.resume();
process.stdin.setEncoding('utf-8');
let inputString = '';
let currentLine = 0;
process.stdin.on('data', function(inputStdin) {
inputString += inputStdin;
});
process.stdin.on('end', function() {
inputString = inputString.split('\n');
main();
});
function readLine() {
return inputString[currentLine++];
}
/*
* Complete the 'arrange' function below.
*
* The function is expected to return a STRING.
* The function accepts STRING sentence as parameter.
*/
function arrange(sentence) {
// Write your code here
console.log(sentence.split(' '));
const words = sentence
.toLowerCase()
.slice(0, -1) // remove period at the end
.split(' ');
let swapped;
const wordsLen = words.length;
if (wordsLen < 1) {
return sentence;
}
do {
swapped = false;
for (let i = 0; i < wordsLen - 1; i++) {
const currentWord = words[i];
const nextWord = words[i+1];
if (currentWord.length > nextWord.length) {
let temp = currentWord;
words[i] = nextWord;
words[i+1] = temp;
swapped = true;
}
}
} while (swapped)
const lengthWiseOrderSentence = words.join(' ');
return lengthWiseOrderSentence[0].toUpperCase()
+ lengthWiseOrderSentence.slice(1)
+ '.';
}
const expectedOutput = 'In the are lines order printed reverse.'
console.log('Test case passed:', expectedOutput === arrange('The lines are printed in reverse order.');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment