Skip to content

Instantly share code, notes, and snippets.

@jinzhu
Forked from bodhi/README.md
Last active August 29, 2015 14:26
Show Gist options
  • Save jinzhu/371ee98051e0f661de39 to your computer and use it in GitHub Desktop.
Save jinzhu/371ee98051e0f661de39 to your computer and use it in GitHub Desktop.
The Telegram Problem

Implement the function handle to accept lines of text and output reformatted text, wrapped at columnWidth characters, without breaking words.

So

Yr brunch Godard, readymade pug Pinterest gastropub put a bird on it Tumblr.
Sartorial swag beard, selvage bitters tofu vinyl.
Tattooed kogi organic scenester heirloom, cred four loko cardigan cray meh Portland master cleanse photo booth Shoreditch farm-to-table.

when wrapped at 30 characters becomes

Yr brunch Godard, readymade  
pug Pinterest gastropub put a  
bird on it Tumblr. Sartorial  
swag beard, selvage bitters  
tofu vinyl. Tattooed kogi  
organic scenester heirloom,  
cred four loko cardigan cray  
meh Portland master cleanse  
photo booth Shoreditch  
farm-to-table.  

Breaking like this:

Yr brunch Godard, readymade pu  
g Pinterest gastropub put a bi  
rd on it Tumblr. Sartorial swa  
g beard, selvage bitters tofu   
vinyl. Tattooed kogi organic s  
cenester heirloom, cred four l  
oko cardigan cray meh Portland  
 master cleanse photo booth Sh  
oreditch farm-to-table.  

is incorrect.

package main
import (
"bufio"
"fmt"
"os"
"regexp"
"strconv"
"strings"
)
var columnWidth uint64 // How long each line should be
var line string
func handle(source string) {
var words = strings.Split(regexp.MustCompile("\n").ReplaceAllString(source, ""), " ")
for _, word := range words {
if length := len(line + word); length > int(columnWidth) {
if len(line) == 0 {
fmt.Println(word)
} else {
fmt.Println(line)
line = word + " "
}
} else if length == int(columnWidth) {
fmt.Println(line + word)
line = ""
} else {
line += word + " "
}
}
if source == "\n" {
fmt.Println(strings.TrimSuffix(line, " "))
line = ""
}
}
func main() {
var err error
if len(os.Args) != 2 {
fmt.Println("invalid argument, run like: go run main.go 30")
os.Exit(1)
}
if columnWidth, err = strconv.ParseUint(os.Args[1], 10, 8); err != nil {
fmt.Printf("invalid column width (%v), need a number, run like: go run main.go 30\n", err.Error())
os.Exit(1)
}
input := bufio.NewReader(os.Stdin)
for line, err := input.ReadString('\n'); err == nil; line, err = input.ReadString('\n') {
handle(line)
}
}
@raven-chen
Copy link

Van & Raven

  1. input length larger than ColumnWidth, no output
  2. cannot accept multiple lines input
  3. cannot accept Chinese
  4. the characters that after length 30 point, missing in output. should be in another line ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment