TopcoderArchiveVisit Topcoder
SRM28 Dec 2006
SRM 332

TextStatistics

Problem statement, definition, constraints, and public examples.

Problem Statement

Most modern text editors are able to give some statistics about the text they are editing. One nice statistic is the average word length in the text.

A word is a maximal continuous sequence of letters ('a'-'z', 'A'-'Z'). Words can be separated by spaces, digits, and punctuation marks.

The average word length is the sum of all the words' lengths divided by the total number of words. For example, in the text "This is div2 easy problem.", there are 5 words: "This", "is", "div", "easy", and "problem". The sum of the word lengths is 4+2+3+4+7=20, so the average word length is 20/5=4.

Given a String text, return the average word length in it. If there are no words in the text, return 0.0.

Definition

Class:
TextStatistics
Method:
averageLength
Parameters:
String
Returns:
double
Method signature:
double averageLength(String text)
(be sure your method is public)

Notes

  • The returned value must be accurate to within a relative or absolute value of 1E-9.

Constraints

  • text will contain between 0 and 50 characters, inclusive.
  • text will contain only letters ('a'-'z', 'A'-'Z'), digits ('0'-'9'), spaces, and the following punctuation marks: ',', '.', '?', '!', '-'.

Examples

  1. "This is div2 easy problem."
    Returns: 4.0
    The example from the problem statement.
  2. "Hello, world!"
    Returns: 5.0
    In this case all words have the same length.
  3. "Simple"
    Returns: 6.0
    One word.
  4. ""
    Returns: 0.0
    No words here, so return 0.
  5. "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
    Returns: 50.0
Back to all problems