Skip to content

Instantly share code, notes, and snippets.

@bodhi
Last active August 29, 2015 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bodhi/1d748f4f4999f769b6aa to your computer and use it in GitHub Desktop.
Save bodhi/1d748f4f4999f769b6aa 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"
"os"
"strconv"
)
var columnWidth uint64 // How long each line should be
func handle(line string) {
// Implement this!
}
func main() {
columnWidth, _ = strconv.ParseUint(os.Args[1], 10, 8)
input := bufio.NewReader(os.Stdin)
for line, err := input.ReadString('\n'); err == nil; line, err = input.ReadString('\n') {
handle(line)
}
}
@ericwo
Copy link

ericwo commented Jul 31, 2015

class Telegram
  attr_reader :elements

  def initialize file
    context = File.open(file).read
    context.gsub!("\n", ' ')
    @elements = context.split(' ')
  end

  def container
    return false if @elements.length <= 0
    length = 30
    temp_array = []

    @elements.each do |element|
      if element.length < length
        print "#{element} "
        temp_array.push element
        length = length - element.length - 1
      else
        @elements = @elements - temp_array
        print "\n"
        return
      end
    end
    @elements = @elements - temp_array
  end

  def printer
    while @elements.length > 0
      container
    end
  end
end

@bom-d-van
Copy link

Nate & Van

package main

import (
    "bufio"
    "os"
    "os/signal"
    "strconv"
    "strings"
)

var columnWidth uint64 // How long each line should be
var result string
var currentLine string

// "abc edf\n"
func handle(line string) {
    words := strings.Split(strings.Trim(line, "\n"), " ")
    for _, w := range words {
        if w == "" {
            continue
        }
        if len(currentLine)+len(w) > int(columnWidth-1) {
            result += currentLine + "\n"
            currentLine = w
        } else {
            if currentLine != "" {
                currentLine += " "
            }
            currentLine += w
        }
    }
}

func main() {
    columnWidth, _ = strconv.ParseUint(os.Args[1], 10, 8)

    go func() {
        c := make(chan os.Signal, 1)
        signal.Notify(c, os.Interrupt, os.Kill)

        <-c
        println("exit")
        // fmt.Printf("%q", result)
        result += currentLine
        println(result)
        os.Exit(0)
    }()

    input := bufio.NewReader(os.Stdin)

    for line, err := input.ReadString('\n'); err == nil; line, err = input.ReadString('\n') {
        handle(line)
    }
}

@raven-chen
Copy link

var result []string

func handle(line string) {
    line = strings.Replace(line, "\n", "", -1)
    words := strings.Split(line, " ")

    for _, word := range words {
        if len(result)+len(word) <= int(columnWidth) {
            result = append(result, word)
        }
    }

    fmt.Println("\n")
    fmt.Println("======================")
    fmt.Printf("%+v\n", result)
    fmt.Printf("%+v\n", len(result))
    fmt.Println("======================")
}

@junhuif
Copy link

junhuif commented Jul 31, 2015

package main

import (
    "fmt"
    "strings"
)

func Handle(text string) (result string) {
    columnWidth := 30
    textWithBreakLine := strings.Replace(text, "\n", " ", -1)
    words := strings.Split(textWithBreakLine, " ")

    newLine := ""
    extraWord := ""
    for _, w := range words {
        if extraWord != "" {
            newLine += extraWord + " "
            extraWord = ""
        }
        originLine := newLine

        if len(newLine) <= columnWidth {
            newLine += w + " "
            if len(newLine) > columnWidth {
                result += originLine + "\n"
                extraWord = w
                newLine = ""
            }
        }
    }
    if extraWord != "" {
        result += extraWord + "\n"
    }
    return result
}

func main() {
    text := `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.`

    fmt.Print(Handle(text))
}

TEST

package main

import (
    "strings"
    "testing"
)

func TestHandle(t *testing.T) {
    text := `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.`
    result := Handle(text)
    originOneLineText := strings.Replace(text, "\n", " ", -1)
    oneLineResult := strings.Replace(result, "\n", " ", -1)
    oneLineResult = strings.Trim(strings.Replace(oneLineResult, "  ", " ", -1), " ")

    if originOneLineText != oneLineResult {
        t.Errorf("Error")
    }

    lines := strings.Split(result, "\n")
    for _, l := range lines {
        if len(l) > 30 {
            t.Errorf("Error")
        }
    }
}

@sunfmin
Copy link

sunfmin commented Jul 31, 2015

package main

import (
    "bufio"
    "fmt"
    // "strconv"
    "strings"
)

func main() {
    max := 30

    var input = `
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.
    `

    scanner := bufio.NewScanner(strings.NewReader(input))
    // Create a custom split function by wrapping the existing ScanWords function.
    split := func(data []byte, atEOF bool) (advance int, token []byte, err error) {
        // if len(data) >= max {
        //  advance = max
        //  token = data
        // }
        token = data[:max]
        li := strings.LastIndex(string(token), " ")
        if li != 0 {
            max = li
        }
        token = data[:max]
        advance = max
        // fmt.Println("data = ", string(data))
        // fmt.Println("atEOF = ", atEOF)
        return
    }

    // Set the split function for the scanning operation.
    scanner.Split(split)
    // Validate the input
    for scanner.Scan() {
        fmt.Printf("%s\n", scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        fmt.Printf("Invalid input: %s", err)
    }

}

@jinzhu
Copy link

jinzhu commented Jul 31, 2015

@sunfmin
Copy link

sunfmin commented Jul 31, 2015

BUG 1:
When run juice's program with:

go run main.go 1000

input is:

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


OUTPUT:

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 

@ericwo
Copy link

ericwo commented Jul 31, 2015

BUG 2:

run go main.go 30

INPUT:

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.

OUTPUT:

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.

The result doesn't come out at once, need to click Enter again. Actually it's not correct ;)

@ericwo
Copy link

ericwo commented Jul 31, 2015

BUG:

run go main.go 5

INPUT:

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.

OUTPUT:

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.

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