4

How to calculate average of 2 digits with brainfuck ?

I mean i have two digits for example 2 3 and its average is 2.5

for 2 8 we have 5.0

How can this be done?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
Krzysztof Lewko
  • 982
  • 7
  • 24
  • 9
    I was going to say that you should show the code you have so far so that we can figure out what needs fixing, but then I realized in this case it's probably easier to just write the answer from scratch. – Jeff Jun 01 '11 at 15:42
  • I looked up some info about this language, only to find out that it is aptly named. haha – j_syk Jun 01 '11 at 15:59
  • @j_syk This language is probably the *nerdest* ever invented (well, excluding Malbolge). But it is Turing complete, which means you can implement any algorithm in it. Imagine a web-app framework based on it! ;) – Miki Jun 01 '11 at 16:01
  • @sorrow while I could imagine writing basic functions in it, i imagine debugging would be a nightmare. but since all non command characters are ignored, i'd probably have more characters of comments mingled in the code than commands! sorry to get offtopic @Chris but I am interested to learn about this. – j_syk Jun 01 '11 at 16:05

2 Answers2

2

Something along the lines of:

++>++++++++< this is input data
[<+>-] this adds the numbers
<[[->+<][->>+<<]] this does the calculation

The approach is to evenly distribute a sum of two numbers. By evenly distribute I mean that the difference between values is at most 1 (since there are no floating point numbers, you have to somehow represent e.g. 2.5). Once you have two neighbouring cells containing these values, feel free to do whatever you want with them (you can output it, then decrease numbers from each cell and if you are left with 1, then output ".5" to it).

Of course, the code above may have pointer errors, but it should be enough for a start and to debug. Furthermore, I would be really happy to see a good, efficient solution.

Miki
  • 7,052
  • 2
  • 29
  • 39
  • 1
    This does not work for multiple reasons. 1. [<+>-] tries to increment a cell to the left of the initial cell - doesn't exits 2. <[[->+<][->>+<<]] wont ever enter the second nested loop ([->>+<<]) 3. Even if it all 'worked', it would not be able to handle decimals and by handle i mean infinite loop :( fatal error – Zac Aug 13 '12 at 15:53
1

better solution:

,>,                               //input 1 and 2
>++++++[-<--------<-------->>]<<  //decrement both by 48
[->+<]>>++<                       //add them and then put 2 in the third cell(devisor)
[                                 // ... 
>[->+>+<<]
>[-<<-
[>]>>>[<[>>>-<<<[-]]>>]<<]        //integer division (4/2 = 2, 3/2 = 1...)
>>>+ 
<<[-<<+>>] 
<<<]
>[-]>>>>[-<<<<<+>>>>>]            //...
<<<<++++++[-<++++++++>]<.         //increment 28 and print result
Zac
  • 2,201
  • 24
  • 48