bfcat - bir dosyayı bir brainf *** programı olarak kodlayın


18

Meydan okuma

Bir dize verilen, Brainfuck olarak derlendiğinde ve yürütüldüğünde o dizeyi döndüren geçerli bir Brainfuck programı döndüren bir program veya işlev yazın.

  1. Tüm girişlerin ASCII olarak kodlandığını varsayın.

  2. Çıkarılan BF programının sonsuz bantla bir ortamda çalışacağını varsayın.

  3. İşaretçinin 0 hücresinde başladığını ve her hücre sıfır değerine başladığını varsayın.

  4. Aşağıdaki her örnek, verilen giriş için bir olası doğru çıkışı temsil eder. Özellikle, örnekler insanın okunabilirliğine yardımcı olmak için ekstra yeni satırlar ve boşluklar içermektedir. Çözümler, çıkan BF kodunu herhangi bir şekilde biçimlendirmekte serbesttir.

  5. Kaset iki kat sonsuz.

  6. Yorumlayıcı tarafından sağlanan tüm hücreler tam olarak 8 bit hücrelerdir. Taşma ve taşma öngörülebilir ve akılcı bir maddeye sarılır.

Örnekler

Boşluk dizesi

Girdi göz önüne alındığında, programınız / fonksiyonunuz geri dönebilir:

+++++ +++++
+++++ +++++
+++++ +++++
++ .

Ünlem işareti

Girdi göz önüne alındığında, !programınız / fonksiyonunuz geri dönebilir:

+++++ +++++
+++++ +++++
+++++ +++++
+++
.

İki harf

Girdi göz önüne alındığında, hiprogramınız / fonksiyonunuz geri dönebilir:

+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

++++
.
+
.

Bu , bu yüzden en az bayt ile kod kazanır. İyi şanslar.


10
Daha fazla testcases lütfen.
Leaky Nun

1
Revizyon 9'da belirtilen kurallar tam olarak nelerdir ?
user8397947

4
Bunu tekrar açıyorum. Sanırım Peter'ın endişeleri giderildi ve neyin mükerrer olduğu konusunda oldukça net bir fikir birliği var ve bu zorluk bu kriterleri karşılamıyor.
Martin Ender

"Taşma ve taşma öngörülebilir ve akılcı bir şekilde sarılır" - böylece 127 + 1 0'a ve -128-1'i de 0'a sarar, değil mi? Bu olası bir öngörülebilir ve aklı başında.
user253751

1
@immibis Kesinlikle.
user8397947

Yanıtlar:


18

Jöle , 8 bayt

O”+ẋp“.>

Çevrimiçi deneyin!

Örnek çalışma

Giriş için hibu program yazdırılır

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++>

Bu ise, (linefeeds olmadan) yazdırırhi .

Nasıl çalışır

O”+ẋp“.>  Main link. Argument: s (string)

O         Ordinal; convert each character in s into its code point.
 ”+       Yield the character '+'.
   ẋ      Repeat '+' k times, for each k in the code points.
     “.>  Yield the string ".>".
    p     Take the Cartesian product of both results.

Seninki sınırlı hafıza üzerinde çalışmıyor, benimki.
Leaky Nun

5
Pek sayılmaz. İkimiz de yazdırmadan önce tüm çıktıyı belleğe kaydediyoruz. Yeterince büyük bir banda sahip BF tercümanları için, bant yapmadan çok önce bir sorun haline gelecektir.
Dennis

Neden .>çıktıda görünmüyor?
kedi

2
@cat Çünkü Kartezyen ürün ( p) her birine ( ;€) eklenenden daha kısadır . Bu çıkış programları yazdırma işleminden sonra ve geçiş yapmadan önce hücreyi ikiye katlar. Hücreyi asla tekrar ziyaret etmediğimiz için, çıktıyı etkilemez.
Dennis

@Dennis ahh, ilginç.
kedi

55

Brainfuck, 55 51 bayt

,[>+++[>+++++++<-]>[<++>>+++<-]<+<[>.<-]>+++.>>-.,]

Çevrimiçi deneyin!

Örnek hihat çıkışı (hat beslemeleri olmadan):

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>

açıklama

Bu program yazılırken kaset boyunca hareket eder. Çevresi ,[...,]standart bir giriş döngüsüdür. Her karakter için dört hücre kullanıyoruz:

[... x a b c ...]

xgirdiyi yazdığımız hücre nerede .

>+++[>+++++++<-]

Bu bölüm , ve öğelerinin standart çarpımı yoluyla bir hücreye ayazmak için hücre kullanır .21b37

>[<++>>+++<-]

Şimdi bunu sırasıyla ve ile çarparak içine ve içine 21yazmak için kullanıyoruz . Ardından , a (kod noktası ) haline getirilirken hücreye geri döner . Recap:42a63c23<+<x4243+

[... x 43 21 63 ...]

Şimdi ana çıkış döngüsü:

[>.<-]

Yani, azalırken her seferinde xbir tane yazdırıyoruz +.

>+++.

İşimizi bitirdikten sonra vermek için +ekleyerek hücreyi tekrar 3kullanırız ..

>>-.

Son olarak, 'e geçip 63onu 62( >) azalttık ve çıktısını aldık . Bir sonraki yineleme bu hücreyi olarak kullanacaktır x.


5
I'd give a bounty to this if I had more rep.
user8397947

34

Brainfuck, 39 33 32 31 bytes

-[-[>]<--<--],[[>.<+]>+.--.+<,]

The algorithm that places 45 on the tape is taken from Esolang's Brainfuck constants.

This answer assumes that the output program's interpreter has wrapping, bounded cells; and that , zeroes the current cell (implying that the output program is run without input). Try it online!

Koşulsuz çalışan (daha uzun) bir çözüm için diğer cevabıma bakın .

Test sürüşü

Giriş Code Golfiçin aşağıdaki çıktı üretilir.

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.,-------------------------------------------------------------------------------------------------------------------------------------------------.,------------------------------------------------------------------------------------------------------------------------------------------------------------.,-----------------------------------------------------------------------------------------------------------------------------------------------------------.,--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.,-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.,-------------------------------------------------------------------------------------------------------------------------------------------------.,----------------------------------------------------------------------------------------------------------------------------------------------------.,----------------------------------------------------------------------------------------------------------------------------------------------------------.,

Çevrimiçi deneyin!

Nasıl çalışır

45 tamsayısını (karakter kodu -) kaset hücresine koyarak başlarız . Aşağıdaki kod bunu başarır.

-      Decrement cell 0, setting it to 255.
[      While the cell under the head in non-zero:
  [>]    Advance to the next zero cell.
  <--    Decrement the cell to its left.
  <--    Decrement the next cell to the left.
]

Döngüye girmeden önce kaset buna benziyor.

         v
000 000 255

Bu üç hücre - -2 , -1 ve 0 - bu programda kullanacağımız tek hücrelerdir .

Döngünün ilk her yinelemesinde, en sağdaki hücre, daha sonra bu hücre ve orta hücre iki kez azaltılır ve aşağıdaki durum bırakılır.

     v
000 254 252

Sonraki 126 yinelemede, başlangıç -orta hücreyi azaltır, [>]<en sağdaki hücreye atlar ve --<--orta ve sağ hücreyi azaltır. Sonuç olarak, 3 orta hücreden (modulo 256 ) çıkarılır ve 2 çıkarılır en sağdaki hücreden çıkarılır.

Yana 254 ÷ 3 (mod 256) = (254 + 256) ÷ 3 = 510 ÷ 3 = 170 ve ÷ 3 = 84 252 , en sağ hücre aşağıdaki durum bırakarak ortadaki önce sıfırlanır.

     v
000 132 000

Benzer şekilde döngünün ilk yineleme için bir sonraki iterasyon hemen çıkarır 3 orta hücreden ve 2 soldaki hücre üzerinde kafa yerleştirilmesi, en soldaki hücreden.

 v
254 129 000

Subsequent iterations, as in the 126 iteration before them, subtract 3 from the leftmost cell and 2 from the rightmost cell.

254 ÷ 3 (mod 256) = 170'ten beri and 129 ÷ 2 (mod 256) is undefined, this is done 170 times, leaving the following state.

 v
000 045 000

The cell under the head is zero; the loop ends.

Artık çıktı üretmeye hazırız.

,      Read a character from STDIN and put it the leftmost cell.
[        While the leftmost cell is non-zero:
  [        While the leftmost cell is non-zero:
    >.     Print the content of the middle cell ('-').
    <-     Increment the leftmost cell.
  ]      If the leftmost cell held n, the above will print 256 - n minus signs
         which, when executed, will put n in cell 0 of the output program.
  >      Increment the middle cell, setting it to 46 ('.').
  .      Print its content ('.').
  --     Decrement the middle cell twice, setting it to 44 (',').
  .      Print its content (',').
         When executed, since the output program receives no input, the above
         will zero cell 0 of the output program.
  +      Increment the second cell, setting it back to 45 ('-').
  <,     Go back to the leftmost cell and read another character from STDIN.
]      Once EOF is reached, this will put 0 in the leftmost cell, ending the loop.

Elde edilen BF neden benim için girdi dizgisine geri çevirmiyor? Bu kullandığım tercüman , diğer cevaplar için çalıştı.
Deli

2
Bu tercümanın birçok ayarı var. 32 baytlık sürüm için dinamik belleğe ve giriş sonu: gerekir\0 .
Dennis

10

Brainfuck, 35 13 43 bayt

++[>+<------],[[>.>+<<-]>+++.->[<.>-]<--<,]

Bu cevap , çıktı programının yorumlayıcısı hakkında herhangi bir varsayımda bulunmaz .Try it online!

Daha kısa bir çözüm için (yalnızca bazı çevirmenlerle çalışır), diğer cevabıma bakın.

Test sürüşü

Giriş Code Golfiçin aşağıdaki çıktı üretilir.

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-------------------------------------------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.---------------------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.----------------------------------------------------------------------------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-----------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++.--------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-----------------------------------------------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.---------------------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------------------------------------------------------------+++++++++++++++++++++++++++++++++.---------------------------------

Çevrimiçi deneyin!

Nasıl çalışır

Kasetin ikinci hücresine 43 tamsayısını (karakter kodu +) koyarak başlıyoruz . Aşağıdaki kod bunu başarır.

++         Increment the first cell twice, setting it to 2.
[          While the first cell in non-zero:
  >+         Increment the second cell.
  <------    Decrement the first cell six times.
]

Bu esasen 2 ÷ 6 modüler bölümünü gerçekleştirir (mod 256) . Yana (2 + 256) ÷ 6 = 258 ÷ 6 = 43 , sonuç 43, as intended.

Artık çıktı üretmeye hazırız.

,      Read a character from STDIN and put it the first cell.
[        While the first cell is non-zero:
  [        While the first cell is non-zero:
    >.     Print the content of the second cell ('+').
    >+     Increment the third cell.
    <<-    Decrement the first cell.
  ]      If the first cell held n, the above prints n plus signs
         and puts n in the third cell.
  >+++   Add three to the second cell, setting it to 46 ('.').
  .      Print its content ('.').
  -      Decrement, setting it to 45 ('-').
  >      Advance to the third cell.
  [      While the third cell is non-zero:
    <.     Print the content of the second cell ('-').
    >-     Decrement the third cell.
  ]      If the first cell held n, the above prints n minus signs,
         thus negating the plus signs and zeroing the cell of the output program.
  <--    Subtract 2 from the second cell, setting it back to 43.
  <,     Go back to the first cell and read another character from STDIN.
]      Once EOF is reached, ',' will put 0 in the first cell, ending the loop.

Aw, man! You can't break the crossed-out-44-is-44 meme, come on! Anyway your attempt to defeat it failed miserably because it doesn't look struck out, it looks like there is some dirt on my screen (PHP, perhaps?) :P
cat

2
Anything to avoid that comment...
Dennis


4

05AB1E, 12 11 bytes

vyÇ`'+ׄ.>J

Explained

v             # for each char in input string
 yÇ`          # convert to its ascii value
    '+×       # push the char '+' that many times
       „.>J   # push string ".>" and join with the plus signs
              # implicitly print combined string

Try it online

Saved 1 byte thanks to @Adnan


'+× instead of F'+} saves a byte.
Adnan

1
@Adnan: Thanks! I was looking for a "repeat" command.
Emigna

4

Java, 98 bytes

class a{String A(char[]b){String z="";for(char B:b){for(int c=B;c-->0;)z+="+";z+=".>";}return z;}}

Strings are nothing more than immutable char[]s with a bunch of utility methods, so let's use the array!

Ungolfed:

class a {
    void A(char[] b) {
        for (char B : b) {
            for (int c = B; c-- > 0;)
                 System.out.print('+');
            System.out.print(".>");
        }
    }
}

Equivalent standalone program that is 138 bytes long:

interface a{static void main(String[]A){for(char b:A[0].toCharArray()){for(int B=b;B-->0;)System.out.print('+');System.out.print(".>");}}}

Bonus:

interface a{static void main(String[]A){for(char b:new java.util.Scanner(new java.io.File(A[0])).useDelimiter("\\Z").next().toCharArray()){for(int B=b;B>0;B--)System.out.print('+');System.out.print(".>");}}}

This 207-byte app actually encodes a file as a BF program, just as said in the title.


2
Is it just me or does the way the ungolfed program is indented look awesome?
user8397947

Realized right before I posted that my answer is basically a golfed down version of yours.
Insane

2

Vitsy, 19 17 bytes

I\[&'>.+'i1-\Du]Z

I                     Get the length of the input stack.
 \[            ]      Pop n, repeat this block of code n times.
   &                  Push a new stack and move to it.
    '>.+'             Push the string '+.>' to the stack.
         i            Pop an item from the input stack and push it to the current
                      program stack.
          1-          Subtract one from the top program stack item.
            \D        Duplicate the '+' in the stack that many times.
              u       Merge the current program stack with the previous.
                Z     Output the entire current stack as a string.

Note that this answer is one of the few times that I've ever used I and u. :D

Try it online!


2

O, 13 bytes

i{'+n#*".>"}d

Explanation:

i              Read standard input into a string and push it onto the stack.
 {         }d  For each character in the string...
  '+           Push "+".
    n#         Convert the character (n) to its ASCII code.
      *        Multiply the "+" by the character code to get the number of +'s needed.
       ".>"    Push the string ".>".
               In O, the stack is printed after execution, so this prints out the result.

2

K6, 16 bytes

,/{|">.",x#"+"}'

Usage

,/{|">.",x#"+"}'"some string"

Explanation

  {           }'  For each character in the string...
         x#"+"    Repeat "+" as many times as the character's ASCII code.
        ,         Combine that with...
    ">."          The code to print it and move on.
   |              But we put the string together backwards...so now it gets reversed.
,/                Combine all the substrings into one BIG string.

Explanation plz :D
Addison Crump

@VTCAKAVSMoACE Done! :)
kirbyfan64sos

2

Python 3, 43 bytes

lambda s:''.join('+'*ord(c)+'.>'for c in s)

The Python puts a number of pluses equivalent to the ASCII code of each character, followed by .> to print and move to the next cell. The brainfuck increments up to the correct value, prints, and moves on to the next cell.

Output for hi (with newlines for clarity):

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>

That program's output:

hi

2

Perl, 25 bytes

s/./"+"x ord($&).".>"/eg

Usage

echo -n hi | perl -pe 's/./"+"x ord($&).".>"/eg'

Explanation

Uses a regular expression replace operation to replace every character in every line given on standard input with a number of + calculated from the ordinal value of that character, then outputs .> to print and advance to the next character.

Uses the perl -p flag to automatically read the input and print the result, adding 1 extra to the bytecount.


2

Java, 91 bytes

String b(char[] f){String k="";for(char b:f){for(int u=b;u>0;u--)k+="+";k+=".>";}return k;}

Props to dorukayhan for beating me to it :)


You can't just remove the boilerplate and change all the names of the variables and then claim that as a new answer.
Leaky Nun

@LeakyNun I didn't, but I could if I wanted to.
Insane

How is this answer different from the answer you linked to?
Leaky Nun

@LeakyNun Downvote and move on
Insane

2

C, 72 64 60 bytes

main(c){for(;c=~getchar();)for(;printf(~c++?"+":".>")^2;);}

Ungolfed version:

main( c )
{
    for ( ; c = ~getchar( ); )
        for ( ; printf( ~c++ ? "+" : ".>" ) ^ 2; );
}

Compile and test with:
gcc -o bfcat bfcatgolf.c && cat 1.txt | ./bfcat > o.txt && beef o.txt

Results


Why is c the bitwise inverse of getchar, especially if you just invert the inversion again?
cat

@cat c = ~getchar( ) evaluates to 0 on EOF. c = ~getchar( ) and ~c++ are simply shorter than ~( c = getchar( ) ) and c--
Jacajack

2

CJam, 12 bytes

Converts each character to its ASCII value, and increments the current cell by that number of times before printing it. Since we have infinite tape we can just move to the right after processing each character.

q{i'+*'.'>}%

Try it online!


2

Lua, 67 66 61 Bytes

Simply iterate over each characters in the argument, and print a line for each one with n +s followed by .> where n is the value of this character in the ASCII Table.

Uses gmatch as @LeakyNun advised in the comment for saving 1 Bytes over the the gsub solution

for c in(...):gmatch"."do print(("+"):rep(c:byte())..".>")end

Old solution using gsub

(...):gsub(".",function(c)print(c.rep("+",c:byte())..".>")end)

Old 67

(...):gsub(".",function(c)print(string.rep("+",c:byte())..".>")end)

To run it, just save it as a file (golf.lua for instance) and run it with lua golf.lua "hi". For hi, it should output

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>

How do I use this? Just pasting it in the REPL gives attempt to index a nil value, and f = ... gives the same, and function f ... end gives unexpected symbol near ':'
cat

@cat Just save it in a file and run it as lua file.lua "argument", I will update the post to give instructions.
Katenkyo

How does that even work? is ... an identifier with argv?
cat

1
@cat ... contains the values in the table arg unpacked. Which means it will always correspond to arg[1] unless you use it in a function call as the last parameter, then it will expend.
Katenkyo

n=...for n:gmatch"."do print(("+"):rep(c:byte())..".>")end for 48 bytes
Leaky Nun

1

J, 28 bytes

[:;[:('.>',~'+'#~])"0[:]3&u:

Simple enough. 3&u: converts chars to char codes. The rest is just repeat '+' that number of times, then concatenating with .> at the end of each line, and ; flattens the result.

Some results

   bf =: [:;[:('>.',~'+'#~])"0[:]3&u:
   bf 'hi'
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>. +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>.
   bf ' !'
++++++++++++++++++++++++++++++++>. +++++++++++++++++++++++++++++++++>.
   bf ' ~'
++++++++++++++++++++++++++++++++>.
                 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>.


1

Actually, 13 bytes

O`'+*".>"@`MΣ

Try it online!

The strategy used here is the same as in many of the other solutions - for each character, output enough +s to increment a zero-initialized cell to the proper ASCII ordinal, output it with ., and move to the next cell with >.

Explanation:

O`'+*".>"@`MΣ
O              list of ordinals (technically this is Unicode code points, but code points 0-127 are the same for Unicode and ASCII)
 `'+*".>"@`M   for each ordinal:
  '+*            push a string containing that many +s
     ".>"@       push ".>" and swap (putting it before the +s)
            Σ  concatenate all the strings (if "[", "]", and "," weren't meaningful characters in BF, this technically wouldn't be necessary)

1

Mouse-2002, 27 bytes

(?'l:l.^(l.^"+"l.1-l:)".>")

This works in theory and according to the language's documentation, but the reference implementation of Mouse's interpreter seems to have a bug where string input appends a ', so for a this outputs

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++.>

Which in turn outputs a'. That may or may not be okay, so here's a 39 byte long one which doesn't output ' ever and thus is likely more invalid.

(?'l:l.39=l.0=+0=^(l.0>^"+"l.1-l:)".>")

Which gives right output in the reference impl. as long as there are no 's :)

Explained:

(              ~ while (true) {
  ?' l:        ~   l = getchar() 
  l. ^         ~   if (! (l) ) { break }
  (            ~   while (true) {
    l. ^       ~     if (! (l) ) { break }
    "+"        ~     puts("+")
    l. 1 - l:  ~     l-- // l = l - 1
  )            ~   }
  ".>"         ~   puts(".>")
)              ~ }

1

Factor, 58 bytes

[ [ [ 43 ] ""replicate-as ".>"append ] { } map-as ""join ]

Works like:

[ 
  [ 
    [ 43 ] "" replicate-as  ! ``+'' * code point, clone-like a string ""
    ".>" append             ! append ".>"
  ] 
  { } map-as                ! for each char in string and clone-like an array { }
  "" join                   ! join array of str into str by ""
]

Since Factor comes with a Brainfuck interpreter, it's simple to test.

bfcat.factor

USING: sequences ;
IN: bfcat

: string>brainfuck ( s -- bf )
  [ [ 43 ] "" replicate-as ".>" append ]
  { } map-as "" join ;

bfcat-tests.factor

USING: tools.test bfcat brainfuck ;
IN: bfcat.tests

{ "a"  } [ "a"  string>brainfuck get-brainfuck ] unit-test
{ "ab" } [ "ab" string>brainfuck get-brainfuck ] unit-test
{ "+++++++++++++" } [ "+++++++++++++" string>brainfuck get-brainfuck ] unit-test
{ "Code Golf" } [ "Code Golf" string>brainfuck get-brainfuck ] unit-test

output

Unit Test: { { "a" } [ "a" string>brainfuck get-brainfuck ] }
Unit Test: { { "ab" } [ "ab" string>brainfuck get-brainfuck ] }
Unit Test: {
    { "+++++++++++++" }
    [ "+++++++++++++" string>brainfuck get-brainfuck ]
}
Unit Test: {
    { "Code Golf" }
    [ "Code Golf" string>brainfuck get-brainfuck ]
}

Yay! they all pass.


1

Ruby, 40 38 bytes

gets.chop.each_byte{|o|puts"+"*o+".>"}

I don't know ruby but I do know you can use puts instead of print, as the format of the output is not significant as long as it is valid brainfuck and brainfuck does not care about other characters
cat

@cat oh I didn't know that bf ignores other characters, thanks!
CocoaBean

1

Sidef, 38 bytes

Hey, the same length as Ruby! just that Sidef isn't Ruby :D

read().bytes.each{|c|say"+"*c;say".>"}

Read some chars, then for each byte do that thing.


1

GNU Bash, 100 85 bytes

while IFS= read -rn1 c;do printf '+%.0s' $(seq 1 $(printf %d \'$c));echo '.>';done<$1

Thanks @cat for saving me 15 bytes!

Postramble

  1. Assumes input string is represented as-is in a file passed as first argument.
  2. Usage: bash bfcat.sh <path to file containing string>
  3. Usage (with named pipe): bash bfcat.sh <(echo -n '<string>')

Ungolfed

while IFS= read -r -n1 c # Read file byte by byte [1]
do
    n=$(printf "%d" \'"$c") # `ord` of a char in bash [2]
    printf '+%.0s' $(seq 1 $n) # emit character $n times [3]
    echo '.>' # Emit output and shift command for bf. I love infinite memory.
done <"$1"

References in Ungolfed version

  1. Read file byte by byte

  2. ord of a char in bash

  3. emit character $n times


1
I've improved some of the formatting and stuff in your answer, and removed redundant information from the links. Feel free to undo it if you don't like it. Also, it's GNU Bash, not GNU/Bash like GNU/Linux. :)
cat

1
Golfing tips (I'm no bash golfer): read -rn1, get rid of spaces after ;, get rid of the space in done <"$1" to save a total of 9 bytes
cat

1
@cat It looks awesome! I really need to get in the habit of edit->preview->edit->...
Yeow_Meng

1

ES6, 119 115 bytes

f=s=>{a='';for(i in[...s]){b=s[c='charCodeAt'](i)-(s[c](i-1)|0);a+=(b>0?'+'.repeat(b):'-'.repeat(-b))+'.'}return a}

Saved 4 bytes, thanks to @Leibrug


1
You can assign charCodeAt to some var (let's say c) and use like that: s[c](i) to shorten by 1 byte, and also remove some characters (i found 3: space before [...s], replace logical OR with bitwise one, and semicolon before return).
Leibrug

1

Sesos (non-competing)

Hexdump:

0000000: 28cbf6 02e83d 655bae 243901                       (....=e[.$9.

Size   : 12 byte(s)

Try it online!

Assembler

add 43,fwd 1,get
jmp
  jmp,sub 1,rwd 1,put,fwd 1,jnz
  add 46,put,add 16,put
  get

0

Ruby, 26 bytes

gsub(/./){?+*$&.ord+'.>'}

+ 1 byte for the p command line option. To e.g get the brainfuck code for ABC xyz you can run

$ ruby -p -e 'gsub(/./){?+*$&.ord+".>"}' <<< "ABC xyz"

and get

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>

0

Haskell 50 Bytes

f[]=[]
f(x:y)=replicate(fromEnum x)'+'++".>"++f y
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.