Skip to content

Instantly share code, notes, and snippets.

@iporsut
Created August 18, 2016 09:07
Show Gist options
  • Save iporsut/1e4491386faf2d53bf4337bc19932de2 to your computer and use it in GitHub Desktop.
Save iporsut/1e4491386faf2d53bf4337bc19932de2 to your computer and use it in GitHub Desktop.
statuses no recursion
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
"strings"
)
type Comment struct {
id int
parent int
msg string
indent int
}
func main() {
for _, comment := range Rearrange(ParseInput(os.Stdin)) {
fmt.Printf("%s- %d %s\n", strings.Repeat(" ", comment.indent), comment.id, comment.msg)
}
}
func Rearrange(comments []Comment) []Comment {
result := make([]Comment, 0, len(comments))
for i := 0; i < len(comments); i++ {
comment := comments[i]
// find last child
var found bool
var lastChildIndex int
for j := 0; j < len(result); j++ {
if comment.parent == result[j].id {
found = true
lastChildIndex = j + 1
parentIndent := result[j].indent
for lastChildIndex < len(result) && (result[lastChildIndex].parent == comment.parent || result[lastChildIndex].indent > parentIndent) {
lastChildIndex++
}
break
}
}
// count indent
var indent int
for c := comment; c.parent != 0; {
c = comments[c.parent-1]
indent++
}
comment.indent = indent
if found {
prefix := make([]Comment, len(result[:lastChildIndex]))
copy(prefix, result[:lastChildIndex])
suffix := make([]Comment, len(result[lastChildIndex:]))
copy(suffix, result[lastChildIndex:])
result = append(prefix, comment)
result = append(result, suffix...)
} else {
result = append(result, comment)
}
}
return result
}
func ParseInput(r io.Reader) (comments []Comment) {
scanner := bufio.NewScanner(r)
if scanner.Scan() {
n, _ := strconv.Atoi(scanner.Text())
comments = make([]Comment, n)
for i := 0; i < n; i++ {
scanner.Scan()
line := strings.Split(scanner.Text(), " ")
parent, _ := strconv.Atoi(line[0])
comments[i] = Comment{parent: parent, id: i + 1, msg: line[1]}
}
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment