com.github.bloodshura.sparkium.brainfxck.util.BrainfuckCodeGenerator Maven / Gradle / Ivy
Show all versions of sparkium-brainfxck Show documentation
package com.github.bloodshura.sparkium.brainfxck.util;
import com.github.bloodshura.ignitium.charset.TextBuilder;
import com.github.bloodshura.ignitium.worker.StringWorker;
import javax.annotation.Nonnull;
/**
* This utility class is responsible for generating common Brainfuck code.
*/
public class BrainfuckCodeGenerator {
/**
* Generates a Brainfuck code which outputs the specified parameter.
* The generated code will be commented.
*
* @param output The output
* @return A String containing the generated Brainfuck code
* @see #forPrinting(String, int, boolean, int)
*/
@Nonnull
public static String forPrinting(@Nonnull String output) {
return forPrinting(output, 10, true, 45);
}
/**
* Generates a Brainfuck code which outputs the specified first parameter.
*
* @param output The output
* @param factor A factor used to control the behaviour of code generation
* @param commented If the generated code must be commented or not
* @param commentOffset At what offset the comments will be present
* @return A String containing the generated Brainfuck code
*/
@Nonnull
public static String forPrinting(@Nonnull String output, int factor, boolean commented, int commentOffset) {
TextBuilder builder = new TextBuilder();
int count;
int repeatAmount;
int rest;
for (char ch : output.toCharArray()) {
repeatAmount = ch / factor;
rest = ch % factor;
count = 3 + repeatAmount + 2 + factor + 4 + rest;
builder.append('>');
builder.append(' ');
builder.append('>');
builder.appendMany('+', repeatAmount);
builder.append('[');
builder.append('<');
builder.appendMany('+', factor);
builder.append('>');
builder.append('-');
builder.append(']');
builder.append('<');
builder.appendMany('+', rest);
if (commented) {
builder.appendMany(' ', commentOffset - count);
builder.append('\'');
builder.append(' ');
builder.append(StringWorker.escape(String.valueOf(ch)));
}
builder.newLine();
}
builder.appendMany('<', output.length() - 1);
builder.newLine();
builder.append('[');
builder.append('.');
builder.append('>');
builder.append(']');
return builder.toString();
}
}