5 kyu
My smallest code interpreter (aka Brainf**k)
1,840 of 8,315ssineriz
Loading description...
Interpreters
Algorithms
View
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Spoiler
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}
-
-
Your rendered github-flavored markdown will appear here.
-
Label this discussion...
-
No Label
Keep the comment unlabeled if none of the below applies.
-
Issue
Use the issue label when reporting problems with the kata.
Be sure to explain the problem clearly and include the steps to reproduce. -
Suggestion
Use the suggestion label if you have feedback on how this kata can be improved.
-
Question
Use the question label if you have questions and/or need help solving the kata.
Don't forget to mention the language you're using, and mark as having spoiler if you include your solution.
-
No Label
- Cancel
Commenting is not allowed on this discussion
You cannot view this solution
There is no solution to show
Please sign in or sign up to leave a comment.
Check that you used correct indices. I used indice from out loop in inner loop and spent close to 50 minutes printing everything to see why timeout happens.
BF translation: how many nested loops should the solution support?
Очень хорошее Ката. Автор молодец, огромное тебе спасибо. Все удачного кодирования!
The description talks about ASCII-Values for input and output. ASCII has values from 0 to 127. Yet, the last input character of the first test example has a value of 255. My code looped forever until I figured this out, because that character does not have an ASCII value. [ In Swift: Character(UnicodeScalar(255)).asciiValue == nil ]
Please change the description.
Hey everyone, I am solving this kata using kotlin, and my solution passes all the testcases, but the fibinochi one. In the fibinochi testcase, my program outputs:
I7, 1, 2, ....
. As you can see that the problem is in the beginning. Does this have happend to anyone?It might be a good idea to include this crucial tip in the instructions for this awesome kata: "Brackets must be matched based on their nesting level. This means you can’t simply jump to the next ]; instead, you need to track the depth of nesting to locate the correct matching bracket.
Can someone summarize the content in 100 words?
What you mean by the "content"?
Could anyone please point me (pun not intended) in the right direction? What sort of material and topics do I need to learn before being able to solve this? (C++)
It depends with what part causes you troubles: do you have a problem understanding how Brainfuck is about and how its interpreter works, or you have problems with implementing it in C++?
In any case, you can visit Codewars Discord and its
#help-solve
or#cpp
channels.Search a topic called TOC (Theory of computation)
Need to be careful with nested brack.
I came back to this kata after 4 years
Amazing
this shit was at the same time the worst and the better problem I ever solved
I regret doing this kata
Awesome kata!
hi! first 3 test is working, 4th is working on visual studio, but i constatly get 'IndexOutOfRangeException' for the 5th test. Nonetheless, it is still unclear what to to for ',' if input is empty?
C fibonacci tests are certainly wrong 👎
(C++) I can pass the 3 basic standard tests, but get a timeout when I use the attempt button. I'm trying to debug, so I was trying to print out the code and input to see the test. However, when I print out the input, I get a bunch of unknown characters that I can't read. What can I do to find out what the tests are expecting as input/output? I can't see them. There's also no "Expected this and got that" sort of message.
For example, for cout << code << " " << input << std::endl;
I get:
,+[-.,+] Z`�3Q�C��ſ"|y�%�]:�
,[.[-],] Z`�3Q�C��ſ"|y�%�]:
If I try to feed these to some online interpreter to see the expected output, it of course doesn't work. How can I find the input and expected output of the tests that I'm failing?
nothing weird about that, see description for input spec
if the ones you printed aren't what your code gets stuck on then you might want to add a flush to ensure your prints get out
you might also want to print better to ensure you can run the same thing yourself
Hi Natan,
Thanks for commenting. I finally figured the whole thing out and solved it. I just needed to find a way to print the unsigned ASCII values of the input string, insted of trying to print the characters directly, in order to understand what was going on, among a few other things lol... Took way longer than I thought it would, but it was a good feeling to finally pass all the tests. Thanks for responding.
How is this a 5 kyu??
If you think it's easier than other 5 kyus, enjoy the cheap points.
If you think it's harder, maybe you're making it more difficult than it needs to be, or your language is doing that for you ( a kata can only have a single ranking for all languages ).
This comment has been hidden.
This thing broke while loops.
I decrement var i in while(){}. When it reenters while, (because of the condition) i is the value before.
The increment is somewhere far below the while loop.
where is the question, though?
My old (working) C solution with a modified prototype passes
should_work_for_a_few_simple_examples
andshould_work_for_more_complex_examples_with_randomness
, then segfaults atshould_work_for_a_few_runs_of_a_fibonacci_program
. Ifprintf
ed that program and ran it through my solution for Valid Braces to find that they aren't valid. I don't know what else changed, but the last item in the description says we shouldn't ever need to check for that. The same item also seems to promise that the data tape will expand automatically, even though we have to allocate it in the first place and simply "make it big enough", so I don't quite know what to think.edit: by 'data tape will expand' I really meant this: "Error-handling, e.g. unmatched square brackets and/or memory pointer going past the leftmost cell is not required in this Kata." It didn't say anything about dynamically resizing, and that's just one way to make the claim that I will never have to worry about it. But it's potentially confusing. The memory tape is supposed to be infinite, so there is no "leftmost cell". Maybe it only means that the BF programs supplied are supposed to never take the data pointer lower than the initial location, and that you don't even have to initialize the data pointer somewhere farther along the tape in order to be safe, which I did anyway.
But it seems that my segfault comes from walking off the edge of the code string while looking for a matching brace that doesn't exist. gdb says the instruction pointer is at
147424
relative to the start of the program string which seems to be 504 bytes long.This comment has been hidden.
I managed to shoehorn my C code into the C++ environment to see if that Fibonacci code was different since it apparently doesn't crash for @Horneringer (below) ...who was able to solve it eventually. It appears that the Fibonacci generator is the very first test after the sample tests, and it crashes just the same (well... with much more bureaucracy), and the BF code string I printed out appears to be identical to the one that's crashing for me in C. Can someone confirm that it has changed in the interim, and that the unmatched braces aren't some other problem such as the test environment bailing out before
fflush(0)
causes it to finish writingstderr
? I addedstd::cout << code << std::endl;
at the beginning ofbrainLuck()
to try to convince myself that it isn't some weird interaction withcstdio
and I just keep getting the one with unmatched braces.Here's a rhetorical question: do I just need to forfeit and see whether a lot of other solutions were invalidated by a changed test? Do all of those need to be manually checked and re-checked from time to time, or is it done on a schedule?
I forfeited. My copy of the crashing BF string was apparently complete. It has only matched braces. I don't know how my manual & mechanical checks both failed a week ago. I seem to have "earned" a bit of honor by copy-pasting someone else's C++ solution. Nothing makes sense.
so in C# string iterpreter thing "Codewars"+char.ConvertFromUtf32(255) specifically convert from utf32 returns this character ÿ and in total string is Codewarsÿ so what the heck should i do with this XD, thanks =)
Write a BF interpreter which according to the test comment
// Echo until byte(255) encountred
it tries to run this BF code,+[-.,+]
on a stringCodewarsÿ
which copiesCodewars
to the output, stopping atÿ
.edit:
ÿ
is only what you might see in a hex editor where the byte is 0xFF, and it appears here.0xFF
a.k.a.255
is what really matters, because the 2nd+
BF instruction increments it, and it wraps around to zero, so the following]
instruction advances to the end of the program instead of jumping back to the[
instruction and running the loop again.edit++: I mean 'jumping back to the next instruction after
[
'. I don't really know BF.So ladies and gentlemen...
In one of the tests I get the following
Expected: equal to "1, 1, 2, 3, 5, 8, 13, 21, 34, 55" actual: ""
How am I supposed to guess where the problem is? How should I understand which Brainf**k language command was used? How should I understand whether the string was supplemented with some characters or not (unless, of course, I need to know this at all)
Your options, dear)
No idea why, but sometimes Test4 passes and sometimes it doesn't. C#. Currently still trying to pass Test5, soon gonna rip my hair out btw
The
ISSUE
tag is for provable issues with the kata. See https://docs.codewars.com/training/troubleshooting/#post-discourse.My C code seems to retain data from the previous test, each test passes on their own but together I get Hodewars. I am initializing my data array inside the function and have even added memset to try to fix it, not sure whats going on.
For c++ the first testcase is ,+[-.,+] this calls , on an exhausted input
Hello !
The TypeScript tests are invalid, when I test my solution it replies:
did you rewrite the funcion call? this happens to me when I do that and forget to export the function.
I've tested the stub code
return ""
and my solution, but this error is not producible, closing as of now. Do reraise a new issue if you find such cases.Super nice kata to solve, I had a lot of fun with it.
I don't understand the task. The inputs are string of
code
that does xyz, I understand. Byte array from the String also given asinput
which you use only when,
code is reached?? Everything else, I don't. Am I supposed to initalise a byte list/array and use this with the data pointer? Or is that from the Stringinput
??Yes, BF works on a memory of byte cells which the datapointer points to. This you have to initialize/manage yourself. Maybe you should read the Wikipedia article linked in the description.
The "," command takes 1 byte from input and puts at the data pointer. So, if we have "Code" input the code ",." will output 'C'. The ",,." should return 'o'. Atleas it is as I understood the assignment.
[Clojure] Description says to assume that
,
will never be invoked when input stream is exhausted, but there is a test for "insufficient input" that is just","
with an empty string as input.I just really want to punch myself in the face right now, I can do crap, everytime I come on here it's hard I just can't I FREAKING QUIT!!!
looks like you didn't find your balance yet... ;)
This comment has been hidden.
Don't quit, just work your way towards harder kata by doing easier ones. Why were you even attempting a 5kyu kata when you are 8kyu? Try 7kyu and if you find that too easy, try 6kyu. Don't skip ahead too much as that is only a path to frustration and quiting. If you find 7kyu too hard, try 8kyu. If you are struggling with that as well then you are really a beginner and must build up some basic programming knowledge which you can do by doing beginner tutorials for your language of choice. Try w3schools, freecodecamp or simply YouTube. Best of luck.
Learning is life long process and learning is frustrating for one who do not love his work. It totally depends on us what is it we love to do.
If I do coding for money, job, status, etc but do not love it then frustration is natural.
This comment has been hidden.
You should read again how BF works. It operates on some memory cells and
,
writes memory to output, while.
reads input to memory. Your code only works on input and output.Luck yeah! What a great challenge it was))
Another question is about brainluck code itself. Let's take first sample text. ,+[-.,+] What would that supposed to mean? It is an infinite loop, isn't it?
not really
I don't get what means the second argument in process-method in tests: "Codewars" + ((char) 255) What does it for?
it's just a weird way to show that the input ends with the
"ÿ"
char (telling what's its ASCII value on the way, which is more useful for the user than the char iteslf)Hi, I'm doing this kata in C. My code runs fine until the "more complex examples with randomness", where the output is just "Expected: Hello World!, but got: (BLANK)". I printed the inputs so that I can run it on my IDE (Codeblocks) and it runs fine, outputting "Hello World!" as expected. The codes are the exact same, so I'm not sure what is wrong. Anybody has any ideas?
there may be other mistakes, but here is the first that i saw:
you did not reserve 1 byte for the nul character (
'\0'
) inccopy
andicopy
, thus thestrcpy()
calls are undefined behavior and anything can happen during program execution. (also, variable-length arrays are bad style and should not be used in clean code)fix this, and see if your solution works
Yes, that did fix it, thank you very much. And thank you for the reminder of bad practice.
This comment has been hidden.
You are using global variables (which is bad) but don't reset all of them between tests.
C++17 grading seems to be broken for this one. My solution works for a half dozen random inputs in testing using g++, but "identical" looking non-printing in both my result and the expected make debugging extremely difficult when submitting.
this is not an issue unless you can prove that the C++ version is broken. your code probably contains undefined behavior, or you are unknowingly adding invisible characters to the string that you return
This comment has been hidden.
Nasm translation
On the java When use an array passed test, but not passed attempt Failed on the testTwoNumbersMultiplier, which passed on the level test On the local all tests passed without fails Same code reworked on the array list passed test and attempt without fails
(Brainfuck translation): No (proper) random tests.
Additionally, the rank of BF translation of this kata is too low, it should be at least 4kyu. This probably has not been noticed before, because except for one other solution besides mine, ALL solutions (including the reference solution) are direct copies from someone elses work on an external website. A BF version of this task should be standalone, and should not be designed to perfectly match an existing online solution, just so that the reference solution can be lazily copied.
This translation should be nuked.
the author is inactive => only an admin could nuke the translation
Great Kata, helps to understand this fancy programming language
It was very (though oddly) enjoyable and satisfying hour, thank you, author.
The description says:
"Your memory tape should be large enough - the original implementation had 30,000 cells but a few thousand should suffice for this Kata" and: "The memory pointer should initially point to a cell in the tape with a sufficient number (e.g. a few thousand or more) of cells to its right."
However in C# at least, no test case requires more than 15 memory cells. Even if using the same memory tape for all tests without ever clearing it or winding it back, only 24 cells are needed. If this is intentional, the description's references to requiring thousands of cells should probably be changed
This comment has been hidden.
',' means to copy the next unused byte from the input string to the data cell at the data pointer. '+' means to increment the value of the current data cell.
The input is separate from the "data" which acts as temporary memory.
I thoroughly enjoyed this kata. I had heard of brainf##k before, but never taken the time to understand how it works in practice.
It was a bit difficult to get started at first.
There were a few traps:
nonetheless I was able to solve it and I had a good time
That's exactly how Brainfuck programming language is supposed to work, what is the issue?
Sorry, wrong tag
While this would have been better posted as a suggestion, I agree that the description could be clearer for people who don't already know how it's supposed to work.
Why MY WHOLE FUNCTION START ITSELF AGAIN FOR NO REASON. It works in clion but not here. Disappoint
What do you mean by "start itself again for no reason"? Tests call your function multiple times, and your solution has to be able to handle multiple consecutive calls. Does it so?
Problem: Solution is predictable and users can pass without actually programmed the interpreter Solution: Randomize the "code" input
Please provide clear examples of predictability (or better, a code that should not pass and does) + language affected. And since you know how to do it better, it'd be kind to explain more detailledly. I COBOL I tried to generate random inputs and I'm not sure the translation is affected by what you're saying. If no more precision is brought, this issue could be considered null.
great, I see
I did it' let's goooooooooo, so much time spend just for the last test fibonacci... 😅😄😄
I did it!!!! :DDDDDD
Day 3: I can't even figure it out how to do the loop system :(
I just can't come up with anything :'(
I don't get it. The , is a char that needs to be convert into a int ascii code?
You must modify values (numbers) in a stack (or a list if you prefer) following the code instructions, and when the instruction is to write to output, add the corresponding ascii char to the output string.
yeah, but when the , comes up, what I gotta do? I don't get that :C
(Edit) The
,
instruction requires you to write the current character of the input string (its ascii code, but in C it makes no difference) to your current cell in the stack. And advance in the input. It's true the description may not be clear about that: you must start with a pointer on first index of the input string. Each time you write from the input string to your stack (,), you must increment your pointer to the input string by 1.COBOL translation, please review carefully (author inactive).
approved
how does the input even work?
finally i've made it. it didn't work until i understand, that pointer input and data poiner it not the same and i should create new poiner:)
This comment has been hidden.
Confusing instructions. It says
"-[: if the byte at the data pointer is zero, then instead of moving the instruction pointer forward to the next command, jump it forward to the command after the matching ] command."
and
"-]: if the byte at the data pointer is nonzero, then instead of moving the instruction pointer forward to the next command, jump it back to the command after the matching [ command."
but really, you have to move the instruction pointer to the matching "["/"]" command. Had to use a debugger to realize this.
This comment has been hidden.
Not an issue. A question to which the answer is : https://en.wikipedia.org/wiki/Pointer_(computer_programming)
In this case (most likely an array/list/something like that).
This type of kata is a classic.
"a"
('dunno where you saw that one specifically) is coming from the input stream, I guess.data
thing..
is reading one element in the input stream and,
is writing something in the output stream. The input stream is provided as an argument, and the output "stream is what you're supposed to return.it's your job to figure out how you'll deesign the whole thing so that it can handle the requirements.
Cheers
@LearningFTW: please, if you close something, be sure to provide the correct information. Documentation about generic pointer will for sure help the user, here... (<<< ironic tone inside...)
Missing return type in initial soluton of TS
Wow, this took some time. If you are having trouble understanding how it works, doing it manually on a piece of paper might help. A little tip from me - if you are doing this on JavaScript make sure when you are checking/incrementing/decrementing the cells they aren't undefined. That stupid mistake took me a lot of time to notice.
The solution wasn't too hard, but the instructions were a little bit difficult to understand.
Excellent Kata!
This comment has been hidden.
My C# solution works in Visual Studio. However I'm unable to get it working here because it does not allow compiling as unsafe. Unsafe is needed to use pointers in C#. I could make a work around that doesn't use pointers, but it feels like that would defeat the purpose of this Kata.
Lack of
unsafe
compiler option is not a kata issue, but it's related to Codewars code runner setup. If you think that setup of C# compiler needs to be changed, you can raise an issue at runner repo.Said that, I am not really sure how inability of using pointers defeats purpose of the kata though. I would say it's quite contrary: attempt to use pointers to write C-like code in C# defeats purpose of why pointers were introduced to C#. Just the fact that you are writing a simulator of a machine which uses a pointer as an element of its architecture does not mean that BF pointer should translate into C# pointer. It can (in some very specific circumstances), but does not have to, and hardly ever should.
Nice Kata, give me a lot of trouble the Fibonacci Attemp because of the nested brackets :P
I suggest to put this example with an unused loop in the Sample Tests: ,>+-[+++[+-++]]<+.
Thanks, great suggestion - without revealing the solution in any way! Helped me debug my code
You deserve like the warmest hug ever
I have two questions about the problem statement.
Does the data pointer move forward to the next cell after the operation?
In the second test case: brain_luck(',[.[-],]', 'Codewars' + chr(0)), for the outer [, the mathing ] is the last instruction. This means there is nothing after it. What should I do here? End the pogram or loop back to the start of the instructions?
I'll answer myself.
No need to increment the data pointer.
The brackets are equivalent to a while loop. The conditions are checked both at the beginning and end of the loop.
Can anyone share the Fibonacci test? In Dart's version, it is not shown.
it is shown when you attemt your code.
This comment has been hidden.
yes (edit: the last data structre could be built with something else too)
thanks.
really nice kata, worth mentioning that brackets can be nested, was not that clear from the description
Julia translation
I found my c-language solution obsoleted. When trying to make it work again I struggle with the fibonacci part.
First - the error message looks like :
So it does not show what is to be expected.
Second, the data used as input varies from attempt to attempt. Is this by design ?
The last 6 attempts has used
as input data. The fact that it changes if the larger or smaller number comes first is what has me wondering. Also the pair of 3s.
The simple tests seem to run fine, also the more complex with randomness.
I'm quite sure that what I wrote is never called for the fibonacci test. The last that gets passed on to my function is
which I believe is the code used to multiply two numbers.
(which in this case was with 2 * 7, and correcly returned 14)
I did choose 'reset' in the kata, as I had to do that with another obsolete kata, in order to get the right test cases.
Hi! Can't seem to understand this kata. Can someone please explain? :)
The goal is to basically implement the Brainfuck compiler. Took me a while to understand the problem myself, but I think understanding how the language itself works (rather than just the various commands it has) really helps, I found this video to be a good overview: https://www.youtube.com/watch?v=-3C200nCwpk
This comment has been hidden.
XD This is quite funny issue, why do you think that the issue is with the kata, not with your code(and chances of having so is relatively larger in C)
Because it's always easier to blame others?
the C tests are fine
Doesn't work because of 255 character is interpreterd by C# as 63, that's why test 1 just loops and I can't go futher. Input gives ÿ character. Idk what to do. Any ideas?
Use byte array, worked in my case. Passed all 3 tests with that sln
Very nice kata!
This comment has been hidden.
Hi! As at now my code works. However, when I attempt, timeout error is always displayed. Is it possible to write this code without looping through the instructions once? (As this is what I did)
Check if the program goes in loop (forever)
It doesn't. The program works for shorter program inputs than longer ones. So I think it goes out of memory (although I'm really looping through only once)
Hi! When I test my solution, I have the error:
But when I test my solution with the same tests on my machine(Compiler -- TDM GCC), everything works correctly. So, I think that the problem in tests.
I will be glad to any feedback. Thank you in advance
Programming Language -- C
Not an issue. Your solution is wrong.
Ok. But why this basic tests works on my machine?
I'm having a lot of trouble with this one on python. The wiki on brainf*** helped me understand the process/movement of the commands but now I'm stumped with the actual input/output side of things. When the input is a string or a string + chr(#) it's characters are passed as a string automatically. My code, which is using integers (+/- 1) depending on the command, is running into type errors with strings/int/bytes. Am I looking to convert the input string to bytes and all of my +/-1 integers to bytes (like +chr(1)) and on the "." command convert it to string again? I tried string.encode() on the input - but then I'm dealing with another conversion. Same issue with bytes([#]) for converting the ints. In the first test the input is "Codewars"+chr(255) which shows as "Codewarsÿ". I believe the input code's commands should ultimately +1 so that the ÿ (chr(255)) becomes 0 so it completes as "Codewars" The closest I was able to get so far just adds a single space/character to the end of "Codewarsÿ" instead of altering it - but that eventually errors out anyway because of str-str/other type issues.
The Rust translation lacks random tests.
Rust kata can use the
rnd
crate these days, see the Rust language page in the wiki.ASCII is a codec with 128 characters, from
0x00
through to0x7F
, inclusive. It's a 7-bit standard.Yet, the Python test at the very least assumes that
chr(255)
is valid input; that makes the input require an 8-bit codec. It's not ASCII, so I had to assume Latin-1 (ISO 8859-1), which is a superset of ASCII.Please correct the description.
Very satisfying to finish this, a tip for anyone stuck on the fibonacci sequence: read the instructions for this kata VERY carefully.
I recently joined this website and a lot of the problems I thought were too easy.. and then this one came along and I thouroughly enjoyed it.
This was so hard, but I feel accomplished in doing it . Yay!
Can anyone tell me what this error means for C:
Test Crashed Caught unexpected signal: SIGSEGV (11). Invalid memory access.
Also can anyone give me the test inputs for random test 5
It most likely means that you didn't allocate enough memory for something, and tried writing somewhere where you didn't have access. You could try debugging with
printf()
statements and track your variables.If that doesn't help, try posting your code here. (formatted and with spoiler flag)
This comment has been hidden.
This comment has been hidden.
Could you please edit your post with formatted code? (link here)
Not sure why it doesn't display the program in console with a single printf, but if you print some stuff inside your loop, the code should show up. It seems like you're failing at fibonacci test, which is shown to me as:
It would be a lot easier if I had solved it myself in C =/ in JS there's no such test as this one.
What's weird is that it prints
input
as some unprintable characters... IDK if there's some overflows going on or what. I tried printing yourint
variables in loop and it looks like the code is stuck inside some loop, but I haven't debugged further. Somehow over 100 people solved it, so I'm assuming the tests are correct.You might wanna check the warning that your code is generating:
Maybe that's the bottleneck. Let me know if you find something out. Good luck!
.
This comment has been hidden.
Use the function calls in the test cases!
When I "attempt", the fifth test fails due to "Max Buffer Size Reached (1.5 MiB)". I am wondering where I can look up the test case to understand what is happening. Any pointers?
It means you're printing too much stuff into console.
Yes,that's true. But if I don't, it falls as well. it seems to keep looping. I'd just like to check the test to pin my error and don't know where I can find it.
Hmm... with python that can be tricky. The goal is to print just enough stuff to fill the buffer in 12s (easy if there's infinite loop), otherwise it will only display timeout message. You could print some distinct message and then print the input, so then you could use ctrl+F to find it on the left side, which shows console output. (the last one would be the failing test) Alternatively you could just print a lot of stuff in your loop and trying to debug it to see where it gets stuck.
Exactly. I was hoping I could avoid that by running the test directly on my machine. But if there's no way to look at the tests, I'll have to add a lot of print statements and do it in the browser. Thanks a bunch anyways!
There's no way to look at the tests when you hit attempt, unless you solve it :D (then you can see by clicking 'Show Kata Test Cases' below satisfaction rating)
With other languages like JS, it will display your logs regardless if your code times out or not, but not with python runner :/
But to be clear, you shouldn't need to use any external stuff. All you need is to scroll through the logs that codewars runner displays, and find what you need. ( ideally :P ) Best of luck, and if it doesn't work, let us know, we'll find a way to help.
Actually, I just found the test cases. I don't know if it's all of them (they are very few), but it seems like it might be. They are on this very discussion page: At the top you can "show kata test cases". :)
I'm having trouble in the Rust kata understanding what it means to "accept one byte" (with the
,
instruction). What exactly does this mean? A byte from where?The comma means your code should remove one character from the input string provided to the function as a parameter and add it to a tape-like memory. The dot means it gets copied from memory to a variable later to be returned.
I'm struggling now, the tests pass and they pass quite quickly but when I attempt it times out.
The only loops in my solution are the main program loop and something that does bracket matching so I'm assuming that it's a large program that has lots of [ ]
I've removed the second loop now and used a stack for matching brackets and still timing out. Any tips?
Hello guys, I have following Problem: at the end of the while loop all conditions are satisfied to exit the while. Nevertheless, the code will still execute. I checked the same code on c++ 2017 gdb and different online compiler.... Thats strange and annoying.
anyone has an idea?
Random tests are missing in some languages, e.g Haskell.
I think there should be a validation for wrong code input. like below
brain_luck('[,+[-.,+]', 'Codewars' + chr(255))
Wow, that was fun!
Please review and approve my Factor translation
This comment has been hidden.
I feel the same about the C# version. I'm not sure when the program is supposed to exit. It passes some tests if it exists when it's processed all the input but not others.
This comment has been hidden.
For c#: Should the solution be cleaner if there is a way to enable and use unsafe code.
[C#] Actual and expected values are swapped in assertions in both Sample Tests and Submit Tests, leading to confusing error messages.
For C version. Be careful with your memory allocations. Although everything looks perfect, some tests won't pass if you don't allocate/initialize the memory properly.
Updated C version to alleviate user from responsibility of allocating memory.
Training in Python 3.
I don't know what I am doing wrong but my code times out on Attempt. I tried to see
code
andinput
usingprint
to console, couldn't see input for many test cases.Only thing I was able to figure out was if I remove
+ chr(255)
from the first test case in Sample Tests, I get a timeout because the value at pointer ends up as 1 everytime it gets to[
.If that is an issue, how can that be handled?
There are no issues with the Python version of this Kata since I was able to complete it without any issues. Perhaps you may want to post your current solution here and mark it as a spoiler so that other Codewarriors may help you figure out where the problem is in your code.
This comment has been hidden.
I think you should add correct function signature to the template
From
To
std::string brainLuck(const std::string& code, const std::string& input)
- this would be the best choice.Yeah, probably. The main problem is that tester requires second arg to be const for some reason.
Implemented @FArekkusu's suggestion.
Is it possible to solve this kata in c#? Just yes or no. I'm stuck with 255 char that appears in code as 63.
Yes, it is possible.
Reading older issues, the C version still doesn't have a 255 ending character. :(
C# has the same issue. So Kata becomes unbeatable because of that?
Just completed the C# version, there is no such issue with C# as of 29/01/2020. Will check the C version later.
Fixed - also improved the function signature of the user solution and alleviated the user of the responsibility to allocate memory.
This comment has been hidden.
I thought I had the solution right but I’m getting this error:
'11, 11, 2(, 3\x1f, 5\r, 8\xf2, =\xc5, E}, R\x08, gK, '
should equal
'1, 1, 2, 3, 5, 8, 13, 21, 34, 55'
This test has ‘\n’ as input.
Other tests work fine as long as they don’t include characters with ‘\’.
I’m I using a wrong codification? I used chr() and ord() to change ascii<->string.
I guess this error is just because of brainfuck's nature and extremly concise explanation attached to the kata. My advice after struggling with the same error: read attentively conditions both for '[' and ']' chars.
I'm getting the same error, and I cant figure out what is wrong.
Is there a specific encoding needed?
Why does using UTF-8 instead of ASCII make the result differ if the chars are one byte only?
Maybe there are crossing-match '[' and ']' in the code? Like, in '[..[..[..]..]..]', should the first '[' jump to the first or third ']' ?
Been working on this for awhile and can't figure it out. Two questions:
>
and<
that change the data pointer. Does this refer to the brainfuck code, or the string? Which piece of data is the cursor moving on? I've been using it on the string, i.e. Codewars>
and<
refer to moving position of your stack / array that you're operating on to perform other operations, it doesn't refer to code itself or output string. You'll have to handle cases when it moves outside bounds and expand it. Let me know if that made it clearer.Thanks for the reply.
So if I have two inputs, code and string, and my output is an array, this array is where the cursor is moving? This is after
.
operator has accetped the current byte? Do the<
>
happen after the.
, or before?<
and>
control the pointer's position in the memory. You can't travel back and forth the input string.You should make sure that you remain in bounds of the memory simulation. Ideally, Brainfuck's memory is an endless tape (although, the compiler/interepreter implementations limit it to some particular size), and it's your job to deal with this fact.
XD
poor choice of words, here ;)
You can travel in the code string by moving the pointer, not in the input string (I see what you meant but, well... ;) )
There's no such thing as "code string". The fact that numbers - actual values stored in memory - are represented as characters when we input/output them doesn't mean you can call it some weird names.
XDD
You should read the description, my dear... THAT's the reason why this was a poor choice of word.
In this case there are only three places this cursor can be active, I think. @FArekkusu - Memory has to be somewhere though? I'm not doing this is C so I'm not mallocing. One of these is what the cursor moves on:
code
in Python. This is the Brainfuck code. i.e.,+[-.,+]
input
in Python. This is the string that I was moving the cursor on but was failing. i.eCodewars.
.
puts the final bytes. Also maybe referred to as memory. I think. i.e. the return valuesCodewars
There is no memory unless it's one of these? Or am I missing something? So I'm guessing that #3 is where I move. If this is the case then my second questions will not be an issue. I was moving the cursor along the wrong piece of data,
input
. It doesn't say which it should move along in the description;data
could be anything IMHO.Thanks @Blind4Basics for your clariifcation!
errrr.... now that I think about it... I did a poor job too, actually... x)
<
and>
are used to move the pointer in the tape, neither in the code nor in the "input" string. You'll have to read the "code" string and move into it in different ways, effectively (while you'll read only once (at most) the chars of the "input" string), but those moves aren't those done with<>
.About the memory (= "tape"), you have to simulate it by yourself: choose a data model and drop your "pointer" in there (not talking about C-like stuff) then move it and work wth it like described.
Alright. Last comment and if I don't get it I'll move on. I'm not sure if this right.
In the example using
,+[-.,+]
andCodewars
. I have a tape,tape = []
. Using the,
I accept inC
totape
. Nowtape = [67]
. I+
add one,-
subtract one, then I use.
to get the value at thedata-pointer
, which points totape
ortape[0]
since that is the only value. I'll push that to an outside list that holds the final output.str = []
thenstr.append(tape[0).
Next I accept antoher value at
,
to tape, nowtape = [67, 111]
. BUT now I add and subtract what? Thedata-pointer
is still pointed attape[0]
. There are no>
here, so all that happens here isC
keeps getting added. This can't be right but it's what I've gathered from our discussion.nope: you didn't get any info about moving the pointer, so you're still at index 0 as you said, so the input char is overwritting the first char. Your tape needs now to be
[111]
So there's 10 replies here and CW doesn't bother notifying me =/ I hate how it works sometimes :P There seems to be still a big disconnect for you how it works, so I'll try to simplify how you can approach it (at least how I did years ago), and hope this doesn't count as a spoiler o_O (only 5kyu tho).
So to interpret BF program you should start by defining what you need:
tape = [0]
)<
and>
are for: decremenenting / incrementing tape pointer (tp = 0
)INPUT
string, the program itself (ip = 0
).
And that should be enough to get you started. There are still some things you'll need and pitfalls to avoid, but this is as far as I can go without spoiling everything O_o
And don't be afraid to ask if it doesn't make sense.
This comment has been hidden.
Yep, it looks like you're getting the hang of it. As I said, you'll need to handle cases where Tape Pointer goes out of bounds. How can you do that? What should be initial value of any tape cell?
Thanks alot everyone. I solved it. This was by far the hardest, easy challenge I've done here. The code is very simple but it took all your help and hours to really figure out what the problem was.
I think it could be better worded, but isn't that the case with all katas pretty much.
Awesome kata. Thanks again.
I'm glad you didn't give up and solved it, well done! ^_^
It's true that some katas assume you have basic knowledge in the field of described task, which often isn't the case =/
There are a bunch of interpreter katas for esoteric languages and such, which you should now be able to solve a lot easier, if you so choose ;)
This comment has been hidden.
(C++) The expected behaviour with regards to running into the end of the input string should be described more carefully. I had to use the input data to reverse engineer the expected behaviour...
I don't think error handling is expected in this kata. I assumed that there's always enough input, and it worked.
Just solved this one, its definitely the hardest one I've done so far! The trickiest part to implement is '[' and ']' commands. If you are using Array.FindIndex('[') or something similar you are doing it wrong. You need to pair the brackets, like how brackets are paired when writing code. For example in
,[.[-],]
the first[
pairs with the last]
. Also, remember to be really careful about whether you are changing the data pointer or the instruction pointer, it's easy to make a mistake! I found the output from the second test to be confusing, however the issue I had with passing the 2nd test was also picked up by the 3rd test. I am not sure how much memory is needed for the test cases, but when I submitted mine I used a byte array of 10000. However, for the the 3 sample problems, I can pass them using a byte array of size 100.[Haskell] The behavior for "insufficient input" is inconsistent with accepted standards - instead of failing immediately and returning
Nothing
, it should do one of the following at least once:0
(like the NUL-terminator in C-strings)-1
This (incorrect) fail-fast behavior expected of the Haskell implementation of the Brainfuck interpreter also means that even simple programs such as a typical CAT program would not be correctly interpreted as it relies on the input string being exhausted by a while loop.
Fixed - I used the tests in PHP as a reference
I copied and pasted my code into Visual Studio, and everytime I call the method the same way it gets called in the Codewars tests, I get the exact answers that the tests say they're looking for. However, when I plug in the same code into Codewars, the error says that it keeps getting "Codewars" back. I'm sure this is an instance of user error, but does anyone know what could possibly be wrong? Thanks.
got a similar issue. i will move on now.
This comment has been hidden.
While writing a code I was wondering if there are no issues in the code tests (I had some problems with them... (: ). But now I passed and want to say that everything is fine with the Python 3 version. Good luck!
in 1st sample test (C) ",+[-.,+]" at the end of input string after it reads (,) ending character (\0) it then increments it (+) and this causes to loop again (]) reading next input (outside of range), outputing etc. What do I miss to understand the algorithm. How the loop is supposed to end?
英文不好,被卡了好久,说一下题目,首先第一个参数是指令,第二个参数,是输入,也就是","指令要写入的东西,一次写一个字母,第二点就是"["和"]"指令会跳转,怎么跳,每次要跳转的时候,都要跳到对应的符号那里去,因为中间会有嵌套,都要跳到对应的符号那里去,因为中间会有嵌套,都要跳到对应的符号那里去,因为中间会有嵌套,重要的事情说三遍,这一点题目好像没有体现出来。
谁可以告诉我“,”是什么意思,读入的一个字节数据从哪里读来的啊?
It should be said that it should stop if it reads input from an empty input.
It wasn't in the question so originally I just ignored it and it took me a while to realise that it shouldn't do this.
awesome kata propably one of my favourites so far. though I feel it's a bit hard for a 5kyu, alhough that could be due to the fact I haven't done many interpreter katas.
it also gave me an massive headace trying to solve it :D but the end result is so worth it thanks for the kata!
I've donbe many of these before and I just don't understand how the 3rd test case works. I'm still struggling on that one. Any references that could help? Thanks
I don't know exacyly on witch part your stuck on on the 3rd test case. just tell me what part is confusing you.
https://en.wikipedia.org/wiki/Brainfuck meaby the wiki will help?
C version still bugged (the first example doesn't have a 255 ending character, both in test cases and validation). Please either fix or explain what special behaviour is expected when running out of the string.
yep you re right
Closing because there is a more recent issue report on this same issue (which also mentions C# as well). I might consider fixing C and C# versions soon.
This kata reminds me of the time when I tried to write a json interpreter in C.
This comment has been hidden.
you are almost there, try debug your code to see where your code is broken (i got stuck on the same issue as well)
Ok I have a question about working command [ and ] if we have list of commands ",[.[-],]" on the second place we have this bracket "[" then on the last place we have "]". So if the last bracket we reach and we have value in memoryCell different than zero, we should go back to this mentioned first bracked on the second place in string (index 1) or to the bracket which appears first when we go backward - on the four place (index in string 3) ??
Ok, I have it :) it didn't mentioned but you have to go backward to the firs bracke it means to brackeet which is a pair to actual one.
This. This is what hung me up for hours. The "jump brackets" can be nested and only stop when they reach their partner - not just any closing pair. On the up side, I got to explore the rabbit hole that is "what should happen on memmory wrap-around".
this kata might be too easy to be a 4kyu kata, but its still super fun, and the solutions here are amazing! thanks:)
This should be like 4 kyu. This has been the fastest I've ever solved a 2 kyu kata.
Hello, i try to complete kata, but test has error on code ",>+>>>>++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++++<<<<<<[>[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<[>++++++++++[-<-[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<[>>>+<<<-]>>[-]]<<]>>>[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<+>>[-]]<<<<<<<]>>>>>[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]++++++++++<[->-<]>++++++++++++++++++++++++++++++++++++++++++++++++.[-]<<<<<<<<<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<-[>>.>.<<<[-]]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[<+>-]>[<+>-]<<<-]"
I must find the closest parentheses or take into account the nesting ? thanks
The parentheses are nested.
Thx)
This comment has been hidden.
Kotlin new translation description merged.
Any suggestions for how to debug a memory corruption error? I get
*** Error in `/home/codewarrior/solution': double free or corruption (!prev): 0x0000000001a23620 ***
after passing the first test. On my local machine, everything tests fine. I'm not usingfree()
at all (just to be paranoid), so I'm not sure what the issue is.Kotlin translation
Groovy translation
Did this kata formerly have Python 3 support? I see down below that about a year ago people were talking about Python 3 solutions? As a Python 3 programmer (and not a good one), refactoring my code to work in Python 2 after working without noticing what version I was coding for was a bit of a pain (: EDIT: omg i just noticed that my JavaScript solution got horribly mangled by its mix of tabs and spaces. how embarassing! i thought i got rid of all the tabs. i'm never going to use Emacs without turning off auto-tabs again
It seems there is a bug in the last test case in C#. Here is the error message I got.
Should return "1, 1, 2, 3, 5, 8, 13, 21, 34, 55" Expected string length 40 but was 32. Strings differ at index 1. Expected: "11, 11, 2(, 3, 5\r, 8ò, =Å, E}, R\b, gK, " But was: "1, 1, 2, 3, 5, 8, 13, 21, 34, 55" ------------^
So obviously my result is same to "should return" but because of the corrupted expected I can't pass this Kata...
The issue is actually in your code. The test code just mixes up "expected" and "actual".
So "11, 11, 2(, 3, 5\r, 8ò, =Å, E}, R\b, gK, " is not expected, it's what your code returns.
I had a very similar issue, and fixing a bug in my code helped.
....
This comment has been hidden.
Dart translation kumited and approved!
This comment has been hidden.
The error is just a mismatch of one number stored in one variable. Read the last 2 command of the description ^^
Just Kumited an Elixir translation here: https://www.codewars.com/kumite/595d21b210dd2ccef500003e?sel=595d21b210dd2ccef500003e
The kata is overrated. It should be 4kyu.
This comment has been hidden.
there are some issues with people complaining about timeouts in there code and indeed I ran into the same issue.
So I really looked around in my code and could not figure out why it should take so long (yeah it's a mess - but after that I don't want to refactor the correct monad stack anymore).
In the end it was rather simple: there seem to be input with spaces (char ' ') and in my case for some reason the resulting exception/failure ended up in CW complaining about timeouts.
So I would suggest adding some remark about this or removing invalid characters from the test input
According to the BF language specification, all characters other than
><+-.,[]
are treated as no-ops.After doing some other "interpreter" katas, it was relatively simple, but a good exercise. However, I'm a bit disappointed to see that the top voted python solutions are over-complicated -- compared to mine ;-)
This comment has been hidden.
I think this is way too easy for lv2, I've seen harder tasks on lower levels
C version is broken somehow. I tested out my code on my end with both GCC and Clang 3.5 and it came out correct but the Kata itself says it's wrong somehow.
This comment has been hidden.
,+[-.,+]
Endless loop
In this one (which is in the basics tests), when we get 0 from ',' to announce the end of string, the '+' increase the 0 to 1, so it loop back and overflow.
In this test, you should have the char 255 at some point in the input. Then 255+1 = 0, and it breaks the loop.
The 255 character isn't in the sample tests for the C translation, so it does just spin. I think some of the actual tests might have the same issue.
yep you re right
Closing because there is another issue on this with more info open for C (and C#).
This comment has been hidden.
Meh, I assumed the same and implemented the memory as infinite in both directions. Just meant that my linked list had to expand backwards as well as forwards, which took an additional 2 lines.
Modified the description to clarify implementation requirements specific to this Kata.
CoffeeScript-Translation kumited!
https://www.codewars.com/kumite/589ddc86ba1f855127000104
Please check and approve it! :-)
Here is a C#-Translation waiting for approving, too! :-)
https://www.codewars.com/kumite/56380022f18c6499a0000014?sel=56380022f18c6499a0000014
C Translation kumited.
This comment has been hidden.
Why does every C++er write so big code? More certainly, why do they use switch-case constructions, while if-staircases are more compact and flexible?
A switch is easier to read when you have more than 3 options. The compiler will generally create an optimised solution anyway (depending upon the compiler) so it is often better to write code that others can easily read.
Reposting this at top-level for visibility: Rust translation Please review, and approve. Let me know if there are questions or issues.
Code: ,>+>>>>++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++++<<<<<<[>[>>>>>>+>+<<<<<<<-]>>>>>>>[<<<<<<<+>>>>>>>-]<[>++++++++++[-<-[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<[>>>+<<<-]>>[-]]<<]>>>[>>+>+<<<-]>>>[<<<+>>>-]+<[>[-]<[-]]>[<<+>>[-]]<<<<<<<]>>>>>[++++++++++++++++++++++++++++++++++++++++++++++++.[-]]++++++++++<[->-<]>++++++++++++++++++++++++++++++++++++++++++++++++.[-]<<<<<<<<<<<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<-[>>.>.<<<[-]]<<[>>+>+<<<-]>>>[<<<+>>>-]<<[<+>-]>[<+>-]<<<-] INPUT: 10; STDERR: Process was terminated. It took longer than 12000ms to complete
It's the only one broken. My code runs all the other codes correctly
While I don't know what language you are running this is, it's probably a performance test. Your solution is too inefficient. I ran it through my implementations and enconutered no problems.
How can you know my solution if i never write it here? Pls....
I don't know your solution. I have two of my own and I ran your program through both of mine, and it worked just fine. In fact, it was very quick. This tells me that it is a problem with your solution. What language are you doing it in? Keep in mind there are probably dozens, if not hundreds, of people who have completed it just fine.
@driconmax: You solved the kata! Great! Please: Next time close your issue after you could solve the kata! :-)
This wasn't solved.... wtf guys, i tried even in a online compiler and it doesn't work.... don't mark as solved something that still bugged.
Again I will ask... what language are you trying it in? I will look at that language's solution -- if other people have solved it without issue, then it is a problem with your solution. Keep in mind if new test cases make previous solutions invalid, they show up as obsolete. If theirs are not obsolete, then it is a problem with your solution. And again, I will state, I executed the code you provided just fine in both my solutions (one of which is Python, which is not known for excessively fast execution) and it ran immediately.
What solution in python??? I make it in javascript, and i never could finish it.... so i don't know where are you looking at my answer.....
I am saying I ran it through my solutions. I never said anything about yours, except to ask which language you tried it in. There are also hundreds of Javascript solutions, so the problem is with your implementation, not with the test case. This is why test cases exist, to find problems with the implementation.
"I executed the code you provided just fine" - "I never said anything about yours"
The brainfuck code you provided. I was saying there is nothing wrong with the test case, and the brainfuck code you provided, especially since hundreds of other people have solved this just fine in Javascript. So, if your code is timing out, it is either wrong or just too slow. You even called this brainfuck code "Code". I am not aware of how to make this any clearer.
So... how can this works only here with others peoples codes, and not in all the online Brainfuck compilers?
I ran it through this one and it worked just fine. (Input is \10) It finished in 10ms.
I test it on that page and the browser crashed..........................
"the machine memory or 'data' should behave like a potentially infinite array of bytes"
Is this the case for both directions (left and right)?
In other words, is there an initial position in the array that cannot be passed, lest it cause an error? Or is it legal for the program to move the data pointer left and right ad infinitum (similar to the tape in a turing machine)?
Depending on the language, some tests will never move left of the initial zero pointer. However, some BF programs do move left of the zero pointer. So, a perfect implementation would let you move left and right without restriction.
Looks like the author is no longer active. Any change of getting a moderator to approve these translations? Looks like the Crystal one was the last to be approved. I would like to write a Rust translation (and help out the very limited Rust library of Kata here) but I don't want to spend the time if no one is going to approve it (well, maybe I will anyway).
Hi Keozon. I confess I've been practically absent in the past year :(, but I still read my mails. If you decide to translate this kata in Rust, I'll be glad to aprove it. I have no experience in Rust, but I think I'll be able to read it anyway.
Rust translation Please review, and approve. Let me know if there are questions or issues.
Thanks for the translation. C++ needs more high level katas :)
TypeScript translation
PHP Translation Kumited - please accept :D
nice kata
Crystal Translation
This is not an issue. Please re-open it as a Suggestion instead.
Nice kata! The instructions were straightforward and the kata itself wasn't too hard either. Moderate thinking required. :)
Python3: Tests passed, running Submit…
You probably figured this out by now, but python3 doesn't have xrange. use range instead.
The Kata is compatible with Python 3.6.0 as of 28/01/2020.
The behaviour should be specified when the data pointer is pointing to an uninitialized data point. Looks like the current behaviour is setting the uninitialized data point as zero.
As of 28/01/2020, the Kata Description says:
I enjoyed this kata! Pretty straightforward, but also took some thinking.
Nice kata, I implemented a solution I'd imagine is somewhat more optimized than a naive one.. at least for the longer, complicated, perhaps even commented programs :D
Beautiful kata! Was a bit confused with the Input description at the beginning but after reading more on Brainf%%% i actually got it :) Would be lovely if we could complete it in assembler ;)
Nice kata, pretty simple and pretty hard. But 'input' is reserved word in Python, it'd be nice to change it.
Afaik input is no longer a reserved keyword in python it may have been when you commented though.
No,
input
is definitely a reserved keyword. It's just that python does not raise any error if you want to override the value, but that's still a very bad habit.Changed parameter
input
in Initial Solution toprogram_input
.Implemented not so worst design as saw in solution) For other who'll try: You could print code in input to console, and see exaples that you can use for debugging.
My initial solution was too slow (I kept having timeouts) so I rewrote it to compile to Ruby and now it works. I think the nested loops in the final test case murdered my performance (my code to deal with loops was pretty naïve).
Fun kata!
This comment has been hidden.
Exactly what I did! Worked like a charm.
easy to implement but very hard to debug it could be a good idea to implement a simple compiler to bf I give it a try
This is the first time I tried anything about BrainF--k. Never wrote or read it before. I printed almost every parameter I defined, just to locate a bug in my code... It's hard to imagine the daily work of an assembly programmer. Still, this is quite a challenge and a lot of fun. My thanks to the author of this kata! :)
If you have problem about the 5th test case, I've got it on the bottom of my code. It's a torment to read it through, you know?
There should probably be a test case for the overflow of +, and the underflow of -. The description says that 255 + 1 should be 0 and 0 - 1 = 255, but I forgot to implement this and only noticed after my submission had been accepted.
True, sadly I don't know how to edit translations. I guess you still deserved it (although I don't agree on that logarithmic memory access). ;)
This comment has been hidden.
Really nice kata! Thanks a lot for creating it. I have translated it to
java
in case you are interested.Very nice kata, I had a good time solving it. :)
I can't get the tests (or solution) to run fast enough. I wrote an optimizing system that runs simple (+-<>) loops in one step and runs the test suite in 0.1080 seconds on my machine - and it still times out on CodeWars. Would it be possible to have a compilation option? I think the Haskell Control.Lens package doesn't do that well in interpreted mode.
system give 6 seconds to run this test. maybe you can try again.
Mine wasn't passing the fifth test then suddenly is passed.
If you liked this one check out my interpreter challenge! http://www.codewars.com/kata/rubyfunge-interpreter
Great kata! Gives me some ideas for some new ones!
Quick question, what is the expected behaviour if we use the '<' instruction and the pointer currently points to the first memory location (0)? For example, what would be the expected pointer location if the code vaariable was just '<'?
Brainfuck isn't a standardized language. Depending on your interpreter, you might allow negative memory locations like
mem[-1]
,mem[-123]
. However, all tests use only non-negative memory locations, that is, the number of<
is less or equal than the amount of preceding>
.Good to know, I'll build it so it prepends a new memory location to the front of the data.
This one was excellent! Short and simple, but still excellent.
This was fun! Took all morning.
This comment has been hidden.
...How is this a suggestion, exactly?
On a more informative point, you'll first have to complete the kata and enable kumite, if you haven't done so already. Then, click the big plus button that appears next to the supported languages on this kata. You can then make a translation.
How would you have asked this instead?
Thanks for the tip.
Wow, the last test really gave me a hard time. It took me a while to find my own bug. No wonder they call it a "turing tarpit".
I get this error:
Test Failed: Expected: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, instead got: 02, 2, 3, 5, 8, 13, 21, 34, 55, 89
Any idea what could be going wrong? I have tested my interpreter with almost every program I could get my hands on and it has never failed.02? If it's getting the string 02 then it's possible you're doing string concatenation by accident, in which case you'd want to make sure you're calling parseInt.
hmm... I'll doublecheck all the arithmetic operations
I am stuck on fibonacci as well (similar issue, but I get 'I7' instead of '02' in place of first '1'). Tomorrow we shall be victorious!
I ran into the exact same issue but I managed to solve it. It was related to incorectly entering the [] loop.
I was having this problem as well (with the first term of fibonacci being 'I7'). I finally tracked it down to not having all of my memory locations defaulting to 0.
@CodeMonkey25 - thanks! I had exactly the same issue and your suggestion greatly helped me with finding the bug - maybe it was similar to yours :)
I'm getting
I have no idea, would you have any?
This comment has been hidden.
This comment has been hidden.
Solid chance that eval is just very slow.
This comment has been hidden.
I've no idea how to solve this without the test or attempt timing out :-/
Try making a test function that is very small and easy to follow. There are a few suggestions above.
Also, you may want to include a few lines that check how much time has elapsed and to exit everything when time is close to 3 seconds. In this case you will at least receive the test results to that point instead of losing everything due to time out.
This comment has been hidden.
This comment has been hidden.
Compliments, you are one of the few to have built a compiler to JS! I hope you haven't been forced to because of the timeouts you can easily experience when interpreting less than elementary brainf***k code strings!
@ssnieriz Why thank you! ;P (And yes, it was because of the timeouts. CW isn't so good with long-running loops.) Fortunately, BF is so simple, it was insanely straightforward to write a regex replace to compile the code.
Awesome Kata! Had a lot of fun, even though I lost a good amount of sleep xD Wouldn't an interpreter be considered 2 Kyu? (Just wondering)
I enjoyed this one a lot.
This comment has been hidden.
I ended up crafting a similar test case to debug as well. I had an off-by-one error that wasn't caught by the first two tests.
This comment has been hidden.
',[.[-],]'
is a small echo program in brainf**k ; it also tests for whether the program is correctly matching corresponding pairs of brackets. Other than your Fibonacci test, none of your other tests check for corresponding brackets, and this is much simpler than the Fibonacci test.I've added the two (small) numbers multiplier
,>,<[>[->+>+<<]>>[-<<+>>]<<<-]>>.
in the tests. Has nested brackets, is shorter than Fibonacci sequence, is different from the existing tests and can even come in handy, lol! Thanks for suggestions.This comment has been hidden.
Ok, I added the test case, but I still can't explain myself the [-] loop. Anyway, I wouldn't be in the shoes of your student if you are torturing him with Brainf**k, lol!
the
[-]
zeros value at the data pointer after every character is outputted. It's not necessary, but it's for debugging. It's an easy program to debug which has nested brackets, which was why I used it for my own debugging.OMG I have had to retype the code three full times because I didn't save my code to the clipboard or elsewhere...
Woooo saved! @jhoffner: So I wrote up the code and was testing it. Then I accidently hit the "discuss" link. Clicking the back button brought me to the code editor but loaded with the default code, not the thing of beauty I had been working on. Then I clicked forward and wrote the above comment. I then clicked "train again" and it returned to the code screen with all my code nicely saved.
There are a few ambiguities that need to be cleared up in the instructions:
brainLuck(',.','') == ???
As in real life, many things are left to interpretation and proper necessities. I didn't even told the instruction's string and input string had to be assumed "big endian", as common sense would suggest. Basically, I feed the tests with correct instructions and strings and ignore error handling. Nontheless, you are giving me a nice idea for a higher level kata: write a brainf### compiler (not an interpreter) that will compile in JS and may alse include error handling (bad instructions in the code string, unmatched square braces, overflow/underflow, etc...), generate the loops instead of moving back and forth on the instruction string, and, above all, pack the multiple '+++...' and '>>>>...' instructions, because the main limit with the interpreter (or at least, my naive version of the interpreter) it's that it times out easily, even with small programs (well, speed has never been the reason to brag of brainf###). Ok, I've added at least the requirement to treat the uninitialized data cells as having value 0. Cheers, Jacques
A compiler would be a pretty cool challenge.
This comment has been hidden.
Thanks to you. I hope I've fixed the instructions and the test fixture to help avoid the unsigned byte rounding trap. The funniest thing is that I ran into the same issue too, lol.
Okay, I don't get this error: "Test Failed: Expected: w34q3680k9, instead got: w34q3680k9". What am I supposed to do here? When I test it in the console it works perfectly. I don't get what's wrong.
This comment has been hidden.
It was a modding issue, I fixed it.
Very nice, I would've liked to have had the initial test feature populated, but attempting to submit sufficed.
My solution seems to work when tested on chrome's console, but when tried in here, system says "Code timedout". How fast is it supposed to work?
I believe the limit is a few seconds, as I found out on the image processing kata ;-)
UPDATE: now after solving the problem, I'm morbidly curious just what you're doing that's timing out...
Don't worry, was just an infinite loop with one of the test cases. Solved.