Skip to content

Instantly share code, notes, and snippets.

@truh
Created November 21, 2016 15:05
Show Gist options
  • Save truh/82abb8c9db1ba0f9e3d9ab03f508aa87 to your computer and use it in GitHub Desktop.
Save truh/82abb8c9db1ba0f9e3d9ab03f508aa87 to your computer and use it in GitHub Desktop.
import sys
from pathlib import Path
def strListToCStringArray(strList):
code = '{'
for s in strList:
code += '"' + s.replace('\n', '\\n') + '",\n'
code += '}'
return code
def generateCode(testCount, testInputs, testOutputs):
code = """/*
Generated by GprGenerator.py by Jakob Klepp
https://gist.github.com/truh/82abb8c9db1ba0f9e3d9ab03f508aa87
*/
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <malloc.h>
#define TESTFILE_COUNT {testCount}""".format(testCount=testCount)
code += """
#define MAX_INPUT_LENGTH 4096
char* testFilesIn[{testCount}] = """.format(testCount=testCount)
code += strListToCStringArray(testInputs)
code += """;
char* testFilesOut[{testCount}] = """.format(testCount=testCount)
code += strListToCStringArray(testOutputs)
code += """;
bool printMatchingOutput(char* input) {
int i;
for (i = 0; i < TESTFILE_COUNT; ++i) {
if (0 == strcmp(testFilesIn[i], input)) {
printf("%s", testFilesOut[i]);
return true;
} else {
//printf("match (%s | %s): %d", testFilesIn[i], input, strcmp(testFilesIn[i], input));
}
}
printf("Not match found");
return false;
}
int main (){
char* inputBuffer = 0;
char lastChar;
int i = 0;
inputBuffer = malloc(MAX_INPUT_LENGTH);
do {
lastChar = getchar();
if (lastChar != EOF) {
inputBuffer[i++] = lastChar;
}
} while (lastChar != EOF);
printMatchingOutput(inputBuffer);
free(inputBuffer);
return 0;
}
"""
return code
def main():
if len(sys.argv) != 3:
print(__doc__)
sys.exit(0)
testfiles_path = sys.argv[1]
example_name = sys.argv[2]
inFiles = list(Path(testfiles_path).glob(example_name + "_test*.in"))
inFileContents = [open(filename).read() for filename in sorted([str(path) for path in inFiles])]
outFiles = list(Path(testfiles_path).glob(example_name + "_test*.out"))
outFileContents = [open(filename).read() for filename in sorted([str(path) for path in outFiles])]
print(generateCode(len(inFiles), inFileContents, outFileContents))
if __name__ == '__main__':
main()
__doc__ = """Generates solutions to GPR examples based on the testfiles.
Usage:
python3 GprGenerator.py <testfiles path> <example name>
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment