Skip to content

Commit

Permalink
Refactored boilerplate generator
Browse files Browse the repository at this point in the history
  • Loading branch information
vishalmishraa committed Jul 29, 2024
1 parent d107e6b commit 85d09e3
Show file tree
Hide file tree
Showing 16 changed files with 619 additions and 822 deletions.
469 changes: 0 additions & 469 deletions apps/boilerplate-generator/src/FullBoilerPlateParser.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import MakeType from "../Parser/MapDataType";
import { IGenerator } from "../Parser/types";


export default function generateFullC({
problemName,
functionName,
inputFields,
outputFields
}: IGenerator
): string {
const mapDataType = new MakeType();
const inputReads = inputFields
.map((field) => {
if (field.type.startsWith("list<")) {
return `int size_${field.name};\n fscanf(file, "%d", &size_${field.name});\n ${mapDataType.ToC(field.type)} ${field.name}[size_${field.name}];\n for (int i = 0; i < size_${field.name}; i++) fscanf(file, "%d", &${field.name}[i]);`;
} else {
return `${mapDataType.ToC(field.type)} ${field.name};\n fscanf(file, "%d", &${field.name});`;
}
})
.join("\n ");
const outputType: string | undefined = outputFields[0].type;
const functionCall = `${outputType} result = ${functionName}(${inputFields.map((field) => field.name).join(", ")});`;
const outputWrite = `fprintf(stdout, "%d\\n", result);`;

return `
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <limits.h>
##USER_CODE_HERE##
int main() {
FILE *file = fopen("/dev/problems/${problemName.replace(" ", "-")}/tests/inputs/##INPUT_FILE_INDEX##.txt", "r");
vector<string> lines;
string line;
while (fgets(line, sizeof(line), file)) lines.push_back(line);
fclose(file);
${inputReads}
${functionCall}
${outputWrite}
return 0;
}
`;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { IGenerator } from '../Parser/types'
import MakeType from "../Parser/MapDataType";

export default function generateFullCpp({
problemName,
functionName,
inputFields,
outputFields
}: IGenerator): string {
const makeType = new MakeType()
const inputReads = inputFields
.map((field, index) => {
if (field.type.startsWith("list<")) {
return `int size_${field.name};\n std::istringstream(lines[${index}]) >> size_${field.name};\n ${makeType.ToCpp(field.type)} ${field.name}(size_${field.name});\n if(size_${field.name} != 0) {\n \tstd::istringstream iss(lines[${index + 1}]);\n \tfor (int i=0; i < size_${field.name}; i++) iss >> ${field.name}[i];\n }`;
} else {
return `${makeType.ToCpp(field.type)} ${field.name};\n std::istringstream(lines[${index}]) >> ${field.name};`;
}
})
.join("\n ");
const outputType = outputFields[0].type;
const functionCall = `std::${outputType} result = ${functionName}(${inputFields.map((field) => field.name).join(", ")});`;
const outputWrite = `std::cout << result << std::endl;`;

return `#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
#include <climits>
##USER_CODE_HERE##
int main() {
std::ifstream file("/dev/problems/${problemName.replace(" ", "-")}/tests/inputs/##INPUT_FILE_INDEX##.txt");
std::vector<std::string> lines;
std::string line;
while (std::getline(file, line)) lines.push_back(line);
file.close();
${inputReads}
${functionCall}
${outputWrite}
return 0;
}
`;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
type TFields = Array<{ type: string; name: string }>;
import MakeType from "../Parser/MapDataType";
import { IGenerator } from "../Parser/types";

export default function generateFullJava({
problemName,
functionName,
inputFields,
outputFields
}: IGenerator): string {
const makeType = new MakeType()
let inputReadIndex = 0;
const inputReads = inputFields
.map((field, index) => {
if (field.type.startsWith("list<")) {
let javaType = makeType.ToJava(field.type);
let inputType = javaType.match(/<(.*?)>/);
javaType = inputType ? inputType[1] : 'Integer';
let parseToType = (javaType === 'Integer') ? 'Int' : javaType;

return `int size_${field.name} = Integer.parseInt(lines.get(${inputReadIndex++}).trim());\n
${makeType.ToJava(field.type)} ${field.name} = new ArrayList<>(size_${field.name});\n
String[] inputStream = lines.get(${inputReadIndex++}).trim().split("\\s+");\n
for (String inputChar : inputStream) {\n
${field.name}.add(${javaType}.parse${parseToType}(inputChar));\n
}\n`;
} else {
let javaType = makeType.ToJava(field.type);
if (javaType === 'int') {
javaType = 'Integer';
}
else if (javaType === 'float') {
javaType = 'Float';
}
else if (javaType === 'boolean') {
javaType = 'Boolean';
} else if (javaType === 'String') {
javaType = 'String';
}
let parseToType = (javaType === 'Integer') ? 'Int' : javaType;
return `${makeType.ToJava(field.type)} ${field.name} = ${javaType}.parse${parseToType}(lines.get(${inputReadIndex++}).trim());`;
}
}).join("\n ");
const outputType = makeType.ToJava(outputFields[0].type);
const functionCall = `${outputType} result = ${functionName}(${inputFields.map((field) => field.name).join(", ")});`;
const outputWrite = `System.out.println(result);`;

return `
import java.io.*;
import java.util.*;
public class Main {
##USER_CODE_HERE##
public static void main(String[] args) {
String filePath = "/dev/problems/${problemName.replace(" ", "-")}/tests/inputs/##INPUT_FILE_INDEX##.txt";
List<String> lines = readLinesFromFile(filePath);
${inputReads}
${functionCall}
${outputWrite}
}
public static List<String> readLinesFromFile(String filePath) {
List<String> lines = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
return lines;
}
}`;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import MakeType from "../Parser/MapDataType";
import { IGenerator } from "../Parser/types";

export default function generateFullJs({
problemName,
functionName,
inputFields,
outputFields
}: IGenerator): string {
const makeType = new MakeType();
const inputReads = inputFields
.map((field) => {
if (field.type.startsWith("list<")) {
return `const size_${field.name} = parseInt(input.shift());\nconst ${field.name} = input.splice(0, size_${field.name}).map(Number);`;
} else {
return `const ${field.name} = parseInt(input.shift());`;
}
})
.join("\n ");
const outputType = outputFields[0].type;
const functionCall = `const result = ${functionName}(${inputFields.map((field) => field.name).join(", ")});`;

return `##USER_CODE_HERE##
const input = require('fs').readFileSync('/dev/problems/${problemName.replace(" ", "-")}/tests/inputs/##INPUT_FILE_INDEX##.txt', 'utf8').trim().split('\\n').join(' ').split(' ');
${inputReads}
${functionCall}
console.log(result);
`;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
type TFields = Array<{ type: string; name: string }>;
import MakeType from "../Parser/MapDataType";
import { IGenerator } from "../Parser/types";

export default function generateFullPython({
problemName,
functionName,
inputFields,
outputFields
}: IGenerator): string {
const makeType = new MakeType();
const inputReads = inputFields
.map((field) => {
if (field.type.startsWith("list<")) {
return `size_${field.name} = int(input().strip())\n${field.name} = [${makeType.ToPython(field.type)}(x) for x in input().strip().split()]`;
} else {
return `${field.name} = ${makeType.ToPython(field.type)}(input().strip())`;
}
})
.join("\n ");
const outputType = makeType.ToPython(outputFields[0].type);
const functionCall = `result = ${functionName}(${inputFields.map((field) => field.name).join(", ")});`;
const outputWrite = `print(result);`;

return `##USER_CODE_HERE##
def main():
${inputReads}
${functionCall}
${outputWrite}
if __name__ == "__main__":
main()
`;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
type TFields = Array<{ type: string; name: string }>;
import MakeType from "../Parser/MapDataType";
import { IGenerator } from "../Parser/types";

export default function generateFullRust({
problemName,
functionName,
inputFields,
outputFields
}: IGenerator): string {
const makeType = new MakeType();
const inputReads = inputFields
.map((field) => {
if (field.type.startsWith("list<")) {
return `let size_${field.name}: usize = lines.next().and_then(|line| line.parse().ok()).unwrap_or(0);\n\tlet ${field.name}: ${makeType.ToRust(field.type)} = parse_input(lines, size_${field.name});`;
} else {
return `let ${field.name}: ${makeType.ToRust(field.type)} = lines.next().unwrap().parse().unwrap();`;
}
})
.join("\n ");
const containsVector = inputFields.find((field) =>
field.type.startsWith("list<")
);
const outputType = makeType.ToPython(outputFields[0].type);
const functionCall = `let result = ${functionName}(${inputFields.map((field) => field.name).join(", ")});`;
const outputWrite = `println!("{}", result);`;

return `use std::fs::read_to_string;
use std::io::{self};
use std::str::Lines;
##USER_CODE_HERE##
fn main() -> io::Result<()> {
let input = read_to_string("/dev/problems/${problemName.replace(" ", "-")}/tests/inputs/##INPUT_FILE_INDEX##.txt")?;
let mut lines = input.lines();
${inputReads}
${functionCall}
${outputWrite}
Ok(())
}${containsVector
? `\nfn parse_input(mut input: Lines, size_arr: usize) -> Vec<i32> {
let arr: Vec<i32> = input
.next()
.unwrap_or_default()
.split_whitespace()
.filter_map(|x| x.parse().ok())
.collect();
if size_arr == 0 {
Vec::new()
} else {
arr
}
}`
: ""
}
`;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import MakeType from '../Parser/MapDataType';
import { IGenerator, TFields } from '../Parser/types';

export default class GeneratePartial {
private problemName: string = '';
private functionName: string = '';
private inputFields: TFields = [];
private outputFields: TFields = [];

constructor({
problemName,
functionName,
inputFields,
outputFields
}: IGenerator) {
this.problemName = problemName;
this.functionName = functionName;
this.outputFields = outputFields;
this.inputFields = inputFields
}

generateCpp(): string {
const makeType = new MakeType();
const inputs = this.inputFields.map(field => `${makeType.ToCpp(field.type)} ${field.name}`).join(', ');
return `${makeType.ToCpp(this.outputFields[0].type)} ${this.functionName}(${inputs}) {\n // Implementation goes here\n return result;\n}`;
}

generateC(): string {
const makeType = new MakeType();
const inputs = this.inputFields.map(field => `${makeType.ToC(field.type)} ${field.name}`).join(', ');
return `${makeType.ToC(this.outputFields[0].type)} ${this.functionName}(${inputs}) {\n // Implementation goes here\n return result;\n}`;
};

generateJava(): string {
const makeType = new MakeType();
const inputs = this.inputFields.map(field => `${makeType.ToJava(field.type)} ${field.name}`).join(', ');
return `public ${makeType.ToJava(this.outputFields[0].type)} ${this.functionName}(${inputs}) {\n // Implementation goes here\n return result;\n}`;
};

generateRust(): string {
const makeType = new MakeType();
const inputs = this.inputFields.map(field => `${field.name}: ${makeType.ToRust(field.type)}`).join(', ');
return `fn ${this.functionName}(${inputs}) -> ${makeType.ToRust(this.outputFields[0].type)} {\n // Implementation goes here\n return result;\n}`;
};

generatePython(): string {
const makeType = new MakeType();
const inputs = this.inputFields.map(field => `${field.name}: ${makeType.ToPython(field.type)}`).join(', ');
return `def ${this.functionName}(${inputs}) -> ${makeType.ToPython(this.outputFields[0].type)}:\n # Implementation goes here\n return result`;
};

generateJavascript(): string {
const inputs = this.inputFields.map(field => `${field.name}`).join(', ');
return `function ${this.functionName}(${inputs}) {\n // Implementation goes here\n return result;\n}`;
}
}
Loading

0 comments on commit 85d09e3

Please sign in to comment.