Skip to content

Instantly share code, notes, and snippets.

@crevier
Last active December 18, 2017 11:38
Show Gist options
  • Save crevier/d0a25ee057775609574339e934a5871e to your computer and use it in GitHub Desktop.
Save crevier/d0a25ee057775609574339e934a5871e to your computer and use it in GitHub Desktop.
script template used for code golf on codingame
/*
This is a script template used for code golf on codingame
use scriptSize to compute the size of the code between two tags
use runCode to execute the golfCode with custom STDIN/OUT for your unit tests
*/
/**
* Read this file lines and return the number of char between two line marked with the given tags
* @param startTag the tag of the starting line ex : //START
* @param endTag the tag of the end line ex : //END
* @return the size of the section
*/
int scriptSize(startTag, endTag) {
def script = new File(this.class.getName() + '.groovy').readLines()
start = script.findIndexOf { it.contains(startTag) }
end = script.findIndexOf { it.contains(endTag) }
script.subList(start + 1, end)
.join('\n')
.size()
}
/**
* Wrapper to run the golf code with custom STDIN/OUT
* @param inputFile
* @return the output as a list of string
*/
List<String> runCode(inputFile) {
def outputStream = new ByteArrayOutputStream()
(oldIn, oldOut, newIn, newOut) = [System.in, System.out] + createSystemIO(inputFile, outputStream)
setSystemIO(newIn, newOut)
golfCode()
setSystemIO(oldIn, oldOut)
outputStream.toString().readLines()
}
/**
* Create a pair of custom IO, input from a file, output to the outputStream
* @param inputFile
* @param outPutStream
* @return
*/
def createSystemIO(inputFile, outPutStream) {
def newIn = new File(inputFile).newInputStream()
def newOut = new PrintStream(true, outPutStream)
[newIn, newOut]
}
/**
* Set the System IO
* @param _in the new in
* @param _out the new out
*/
void setSystemIO(_in, _out) {
System.setIn(_in)
System.setOut(_out)
}
/**
* Write the golf code here !
* @return
*/
void golfCode() {
//START
println("hello world !")
//END
}
/*
Example of use :
size = scriptSize('//START', '//END')
println("Script size: $size") //28
List<String> result = runCode('../resources/data.txt')
assert result == ['hello world !']
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment