Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import core.stdc.stdio: getchar;
- import std.stdio : writeln;
- auto get(A, I, D)(A arr, I idx, D def)
- {
- if (arr.length - 1 >= idx)
- return arr[idx];
- else
- return def;
- }
- void main(string[] args)
- {
- const string helloworld = q{
- ++++++++++[>+++++++>++++++++
- ++>+++>+<<<<-]>++.>+.+++++++
- ..+++.>++.<<+++++++++++++++.
- >.+++.------.--------.>+.>.
- };
- string code = args.get(1, helloworld);
- string input = args.get(2, "");
- string buffer = "";
- //if (code.startWith("-f=")) // then load the file content
- //{
- //}
- const bool interactive = input.length == 0;
- long[long] tape; // memory tape
- long head = 0; // reading head
- long curs = 0; // code cursor
- while (curs >= 0 && curs < code.length)
- {
- long* slot = (head in tape); // current memory slot
- switch (code[curs])
- {
- default: // unknow character, thus ignored
- break;
- case '<':
- head--;
- break;
- case '>':
- head++;
- break;
- case '+':
- if (slot is null) tape[head] = 1;
- else (*slot)++;
- break;
- case '-':
- if (slot is null) tape[head] = -1;
- else (*slot)--;
- break;
- case '.':
- if (slot is null) buffer ~= "\0";
- else buffer ~= cast(char)(*slot);
- break;
- case ',':
- {
- char chr;
- if (interactive) // interactive input mode, strip newline
- do chr = cast(char)getchar(); while(chr == '\n');
- else if (input.length == 0)
- chr = '\0';
- else
- {
- chr = input[0];
- input = input[1..$];
- }
- if (slot is null) tape[head] = chr;
- else (*slot) = chr;
- break;
- }
- case '[':
- if (slot is null || *slot == 0) // skipping till the closing bracket
- {
- long match = 1; // matching bracket counter
- long skip = curs + 1; // like curs
- while (skip >= 0 && skip < code.length)
- {
- if (code[skip] == '[') match++;
- else if (code[skip] == ']') match--;
- if (code[skip] == ']' && match == 0) break;
- skip++;
- }
- curs = skip;
- }
- break;
- case ']':
- if (slot !is null && *slot != 0) // skipping till the opening bracket
- {
- long match = 1; // matching bracket counter
- long skip = curs - 1; // like curs
- while (skip >= 0 && skip < code.length)
- {
- if (code[skip] == ']') match++;
- else if (code[skip] == '[') match--;
- if (code[skip] == '[' && match == 0) break;
- skip--;
- }
- curs = skip;
- }
- break;
- }
- curs++; // increment the code cursor
- }
- writeln(buffer); // printing the result
- }
Advertisement
Add Comment
Please, Sign In to add comment