4 kyu

Brainfuck Translator

278 of 825Varveyn

Description:

Introduction

Brainfuck is one of the most well-known esoteric programming languages. But it can be hard to understand any code longer that 5 characters. In this kata you have to solve that problem.

Description

In this kata you have to write a function which will do 3 tasks:

  1. Optimize the given Brainfuck code.
  2. Check it for mistakes.
  3. Translate the given Brainfuck programming code into C programming code.

More formally about each of the tasks:

  1. Your function has to remove from the source code all useless command sequences such as: '+-', '<>', '[]'. Also it must erase all characters except +-<>,.[].
    Example:
    "++--+." -> "+."
    "[][+++]" -> "[+++]"
    "<>><" -> ""
  2. If the source code contains unpaired braces, your function should return "Error!" string.
  3. Your function must generate a string of the C programming code as follows:

    1. Sequences of the X commands + or - must be replaced by \*p += X;\n or \*p -= X;\n.
      Example:
      "++++++++++" -> "\*p += 10;\n"
      "------" -> "\*p -= 6;\n"
      
    2. Sequences of the Y commands > or < must be replaced by p += Y;\n or p -= Y;\n.
      Example:
      ">>>>>>>>>>" -> "p += 10;\n"
      "<<<<<<" -> "p -= 6;\n"
      
    3. . command must be replaced by putchar(\*p);\n.
      Example:
      ".." -> "putchar(\*p);\nputchar(\*p);\n"
      
    4. , command must be replaced by \*p = getchar();\n.
      Example:
      "," -> "\*p = getchar();\n"
      
    5. [ command must be replaced by if (\*p) do {\n. ] command must be replaced by } while (\*p);\n.
      Example:
      "[>>]" ->
      if (\*p) do {\n
        p += 2;\n
      } while (\*p);\n
      
    6. Each command in the code block must be shifted 2 spaces to the right accordingly to the previous code block.
      Example:
      "[>>[<<]]" ->
      if (\*p) do {\n
        p += 2;\n
        if (\*p) do {\n
          p -= 2;\n
        } while (\*p);\n
      } while (\*p);\n
      

Examples

Input:
+++++[>++++.<-]
Output:
*p += 5;
if (*p) do {
  p += 1;
  *p += 4;
  putchar(*p);
  p -= 1;
  *p -= 1;
} while (*p);
Esoteric Languages
Strings

Similar Kata:

Stats:

CreatedFeb 1, 2017
PublishedFeb 7, 2017
Warriors Trained8720
Total Skips4355
Total Code Submissions20200
Total Times Completed825
C++ Completions148
C Completions188
Python Completions278
Java Completions75
JavaScript Completions133
PHP Completions38
CoffeeScript Completions8
Total Stars384
% of votes with a positive feedback rating94% of 229
Total "Very Satisfied" Votes203
Total "Somewhat Satisfied" Votes23
Total "Not Satisfied" Votes3
Total Rank Assessments5
Average Assessed Rank
2 kyu
Highest Assessed Rank
2 kyu
Lowest Assessed Rank
3 kyu
Ad
Contributors
  • Varveyn Avatar
  • Blind4Basics Avatar
  • Axure Avatar
  • nomennescio Avatar
  • Voile Avatar
  • rxe Avatar
  • iNont Avatar
  • ZahNarztiK Avatar
  • metalim Avatar
  • jpssj Avatar
Ad