Skip to content

Instantly share code, notes, and snippets.

@craigjbass
Last active August 26, 2016 10:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigjbass/3ea8230ff0da7bb7466bcc05aab4a119 to your computer and use it in GitHub Desktop.
Save craigjbass/3ea8230ff0da7bb7466bcc05aab4a119 to your computer and use it in GitHub Desktop.
Code Kata: WordWrap
package uk.co.devls.coffeebook.test.unit
import org.amshove.kluent.`should equal`
import kotlin.test.*
import org.jetbrains.spek.api.Spek
class CodeDojoTest : Spek({
describe("Wrapper") {
it("should return empty string when provided empty string") {
Wrapper().wrap("", 0).`should equal`("")
Wrapper().wrap("This is cool", 50).`should equal`("This is cool")
Wrapper().wrap("a a", 1).`should equal`("a\na")
Wrapper().wrap("a a a", 1).`should equal`("a\na\na")
Wrapper().wrap("a a a", 3).`should equal`("a a\na")
Wrapper().wrap("a b c d e", 3).`should equal`("a b\nc d\ne")
Wrapper().wrap("a b c d e f g", 3).`should equal`("a b\nc d\ne f\ng")
// Wrapper().wrap("a b c d e f g h j", 3).`should equal`("a b\nc d\ne f\ng h\nj")
}
}
})
class Wrapper {
fun wrap(input: String, cols: Int): String {
if (input.length > cols) {
if (cols == 1) {
return input.replace(" ", "\n")
} else {
val beginning = input.slice(0..cols - 1) + "\n"
var rest = ""
var index = 0
var nextIndex = index + 1
if (input.length < cols*2) {
}
if (input.length > index*cols) {
index++
nextIndex = index + 1
rest = input.slice(cols..cols * 2).trim() + "\n"
}
if (input.length > index*cols) {
index += 2
nextIndex = index + 1
rest = input.slice(cols..cols * 2).trim() + "\n" + input.slice(cols * 2 + 1..cols * 3 + 1).trim() + "\n"
}
return beginning + rest + input.slice(cols * nextIndex + index..input.length - 1).trim()
}
}
return input
}
}

Problem Description

You need to write a class called Wrapper, that has a single static method named wrap that takes two arguments, a string, and a column number. The function returns the string, but with line breaks inserted at just the right places to make sure that no line is longer than the column number. You try to break lines at word boundaries.

Like a word processor, break the line by replacing the last space in a line with a newline.

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