I've been a zone leader with DZone since 2008, and I'm crazy about community. Every day I get to work with the best that JavaScript, HTML5, Android and iOS has to offer, creating apps that truly make at difference, as principal front-end architect at Avego. James is a DZone Zone Leader and has posted 639 posts at DZone. You can read more from them at their website. View Full User Profile

Thursday Code Puzzler: Reversing Words

09.26.2012
| 3878 views |
  • submit to reddit

Thursday is code puzzler day here at DZone. The idea is simple: solve the coding problem as efficiently as you can, in any language or framework that you find suitable.

Note: Even though there really is nothing stopping you from finding a solution to this on the internet, try to keep honest, and come up with your own answer.  It's all about the participation!

Do you have code puzzlers that you'd like to share with the DZone community?  If so, please submit here. 

Reversing Words

Give an array of characters that result a sentence, write a method that will print the words in reverse order (not the characters). Watch out for punctuation marks. An example input would be 

"These puzzlers get easier every week! Wonder if there's a catch?" 

Catch up on all our previous puzzlers here.

Comments

Vijay Nathani replied on Thu, 2012/09/27 - 12:11am

I assume that puntuation marks are to be removed. Groovy code:

def reverseWords(chars) {
	chars.toList().grep(~/[A-Z a-z]/).join('').tokenize().reverse()
}
println reverseWords("These; puzzlers! are easy.".getChars())

Prints [easy, are, puzzlers, These].

Mr B Loid replied on Thu, 2012/09/27 - 7:22am

Not sure what you mean by 'Watch out for punctuation marks'  But this reverses word order in Groovy:

String.metaClass.dzonePuzzle = { ->
  delegate.split().reverse().join( ' ' )
}

println "These puzzlers get easier every week! Wonder if there's a catch?".dzonePuzzle()

Prints:

 
 
"catch? a there's if Wonder week! every easier get puzzlers These"

 

Daniel Seidler replied on Thu, 2012/09/27 - 7:38am

	public static String reverse(char[] chars, int pos){
		String result = "";
		for (;pos < chars.length; pos++) {
	      char c = chars[pos];
	      if(isLetter(c)) result = result + c;
	      else return reverse(chars, pos+1) +" "+result;
      }
		return result;
	}

	public static boolean isLetter(char c) {
		byte b = (byte) c;
		return ((b > 64 && b < 91) || (b > 96 && b < 123) || b == 39);
	}

CALL:
char[] chars = "These puzzlers get easier every week! Wonder if there's a catch?".toCharArray();
String str = reverse(chars, 0);
System.out.println(str);

catch a there's if Wonder week every easier get puzzlers These  

Rafael NUnes replied on Thu, 2012/09/27 - 8:17am

Python:

 

s="These puzzlers get easier every week! Wonder if there's a catch?"

reverse = s.split()[::-1]

print ' '.join(reverse) 

 

Or with an one-liner:

' '.join("These puzzlers get easier every week! Wonder if there's a catch?".split()[::-1])

Kieron Wilkinson replied on Thu, 2012/09/27 - 8:09am

Scala:

 string.split(" ").reverse.mkString(" ")

Version removing punctuation:

 string.split(" ").map(word => word.filter(_.isLetter)).reverse.mkString(" ")

 

Aggelos Karalias replied on Thu, 2012/09/27 - 10:12am

compatible with javascript >= 1.6

Assumptions:
- sentence ends on .!? [1]
- apostrophe is treated as part of the word when followed by s,t (eg. there's, don't) [2]
- every other punctuation in the sentence holds its original position

var reversedWords = "These puzzlers get easier every week! Wonder if there's a catch?".match(/[^\.!?]*[\.!?]/g).map(function(e){
    var l = e.length, s = e.substring(0, l-1).trim(),
        p = s.match(/(\s*'(?!s|t)\s*)|[^\w']+|$/g),
        w = s.match(/(\w+('[s,t])?)/g).reverse();
        
    return w.map(function(e,i) {
        return e + (p[i]||"");
    }).join("") + e.substring(l-1);
}).join(" ");
 
console.log(reversedWords); //"week every easier get puzzlers These! catch a there's if Wonder?"


[1] http://www.ego4u.com/en/cram-up/writing/end-sentence
[2] http://english.stackexchange.com/a/36048

Isis Binder replied on Thu, 2012/09/27 - 10:55am

Using Python

import re

input_string = raw_input("Enter the string: ")

print(' '.join(re.findall(r'\w+', input_string)[::-1])) 

 

Another way is using the reversed() function instead of [::-1].

 

 

A Hansen replied on Thu, 2012/09/27 - 2:02pm

Java:

 

  public static void reverse(char[] arg)
  {
    if (arg == null) return;
    char[] sentence = arg;
    int end = sentence.length;
    while ((--end > 0) && !Character.isLetterOrDigit(sentence[end]));
    int start = end;
    int lastPrintable = start;
    char ch;
    boolean needSpace = false;
    while (start >= 0)
    {
      ch = sentence[start];
      if (Character.isWhitespace(ch))
      {
        if (needSpace) 
        {
          System.out.print(' ');
          needSpace = false;
        }
        needSpace = lastPrintable <= end;
        while (lastPrintable <= end)
        {
          System.out.print(sentence[lastPrintable++]);
        }
        while ((--start > 0) && !Character.isLetterOrDigit(sentence[start]));
        end = start;
      }
      else if (Character.isLetterOrDigit(ch))
      {
        lastPrintable = start;
      }
      start--;
    }
    if (lastPrintable <= end)
    {
      if (needSpace) System.out.print(' ');
      while (lastPrintable <= end)
      {
        System.out.print(sentence[lastPrintable++]);
      }
    }
    System.out.println();
  }

 

Brandon Williams replied on Thu, 2012/09/27 - 10:12pm

public class ReverseSentence 
{
public static void main(String[] args)
{
char[] chars = "These puzzlers get easier every week! Wonder if there's a catch?".toCharArray();

String[] strs = new String(chars).replaceAll("[^\\w ]*", "").split(" ");

for (int i = strs.length - 1; i >= 0; i--)
{
System.out.print(strs[i] + (i > 0 ? " " : ""));
}
}
}

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.