"Reversing the order of words in a string"

Given an input string, this NodeJS code snippet reverses the order of the words.

Problem

Given an input string, reverse the order of the words.
Example input:
"Hello world!"
Example output:
"world! Hello"

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
// Solution:
// The optimal solution is to use the split() method to split the string into an array of words, then use the reverse() method to reverse the order of the words, and finally use the join() method to join the words back into a string.

// Explanation:
// The split() method is optimal because it is a built-in method that is optimized for splitting strings into arrays.
// The reverse() method is optimal because it is a built-in method that is optimized for reversing the order of elements in an array.
// The join() method is optimal because it is a built-in method that is optimized for joining the elements of an array into a string.

// Code:
function reverseWords(str) {
  return str.split(' ').reverse().join(' ');
}

// Test:
console.log(reverseWords('Hello world!'));

A.I. Evaluation of the Solution

The candidate's solution is correct and uses built-in methods that are optimized for the task at hand.

Evaluated at: 2022-11-25 04:16:25