text:
Ninja Assassins - which ninja stays alive?
Ninja Assassins - which ninja stays alive
some basic information

given an int N as the number of ninjas, return the number of the winning ninja.
At the end only 1 ninja survives,the question is which one? what was his number?.
Each ninja kills the ninja who stands after him. Afterwards, he passes the sword to the first alive ninja who stood after the killed one.

Explenation - How the Game Works
The ninjas are numbered from 1 to N and stand in a circle according to the numbers. The circle goes clockwise: ninja 2 is left to ninja 1, ninja 3 is left to ninja 2, ninja 4 is left to ninja 3.... ninja 1 is left to ninja N.
Ninja 1 gets a sword and the game begins:
Each ninja (starting from ninja 1) kills the closest and alive ninja he has to the left (clockwise) . Afterwards, he passes the sword to the 2nd closest and alive ninja he has to the left.The 2nd ninja does the same (kills and passes) (as an example: N=3(we have 3 ninjas), ninja 1 kills ninja 2 and gives the sword to ninja 3. Ninja 3 has ninja 1 as his closest and alive ninja to the left(clockwise - its a circle) so he kills ninja 1, stays the last ninja alive and wins (so the output\return is 3, as the number of the ninja)).
A more detailed example below
Example - Word-detailed scenario
N = 7 (we got 7 ninjas) :
1 2 3 4 5 6 7 (L=alive, D=dead)
L D L L L L L The first ninja gets the sword and kills the 2nd ninja.
              The first ninja passes the sword to the 3rd ninja.
L D L D L L L The 3rd ninja gets the sword and kills the 4th ninja.
              The 3rd Ninja passes the sword to the 5th ninja.
L D L D L D L The 5th ninja gets the sword and kills the 6th ninja.
              The 5th Ninja passes the sword to the 7th ninja.
D D L D L D L The 7th ninja gets the sword and kills the first(1st) ninja.
              The 7th ninja passes the sword to the 3rd ninja.
D D L D D D L The 3rd ninja gets the sword and kills the 5th ninja.
              The 3rd ninja passes the sword to the 7th ninja.
D D D D D D L The 7th ninja gets the sword and kills the 3rd ninja,
              stays as the last one alive and wins (the final result /
              the output is 7).

More scenarios without words
N=3 : 1 2 3 - 1 3 - 3 wins
N=4 : 1 2 3 4 - 1 3 - 1 wins
N=5 : 1 2 3 4 5 - 1 3 5 - 3 5 - 3 wins
N=6 : 1 2 3 4 5 6 - 1 3 5 - 1 5 - 5 wins
N=7 : 1 2 3 4 5 6 7 - 1 3 5 7 - 3 7 - 7 wins

Scoring is based on the least number of bytes used, as this is a code-golf question.

can it be 0-indexed, i.e. ninja 1 becomes ninja 0, etc.?

This is the Josephus Problem with constant k=2.

Obligatory OEIS A006257.

The tags code golf, code challenge, and fastest code are mutually exclusive. You can only have one win criterion. I'd suggest code golf.

Python 2, 30 bytes
lambda n:int(bin(n)[3:]+'1',2)

Takes the binary expansion of n and moves the initial 1 to the end.

That is witchcraft.

ಠ_ಠ what is this

Python 2, 32 bytes
a=lambda n:n and(n%2+a(n/2))*2-1

33 bytes:
a=lambda n:n and 2*a(n/2)-(-1)**n

Uses the recursive formula on the OEIS page.

a(2*n) = 2*a(n)-1
a(2*n+1) = 2*a(n)+1

Why a=? Do you need it?

@NoOneIsHere To recurse.

Java 7, 65 53 bytes
int f(int n){return(n-Integer.highestOneBit(n))*2+1;}

Using the algorithm for k=2 Josephus from Wikipedia. Thanks to Leaky Nun for finding the builtin.

i&i-1 saves 2 bytes

Spare parens ftw >_>

int f(int n){return(n-Integer.highestOneBit(n))*2+1;}

Dammit, I was doing highestOneBit manually and got it to 56 just now. I didn't know there was a built-in for it :/

Yeah, I use Java 7 for golfing just to avoid shady (imo) lambda nonsense :P

Pyth, 22 13 12 9 bytes
Credits to Geobit's algorithm for saving 9 bytes. It works like magic.
Credits to xnor's witchcraft for saving 3 bytes. It is simply witchcraft.

heu+G=Z%e.f!/G%ZQ2ZQQY
u?sIlH1+2GSQ1
hyaefgQT^L2
i.<.BQ1 2

Test suite.

Jelly, 4 bytes
Since xnor came up with this algorithm, I will make this community wiki.

Bṙ1Ḅ

Try it online!
Explanation
Bṙ1Ḅ
B     convert to binary
 ṙ1   left-rotate by 1
   Ḅ  convert from binary

VBA, 57 67 bytes
Well, this technically ought to work (57 bytes):
Function Z(N):Z=2*(N-2^Int(Log(N)/Log(2)))+1:End Function

But actually, because occasionally the log value of a power of two is not quite an exact multiple of the log of 2, we need a few more bytes:
Function Z(N):Z=2*(N-2^Int(Log(N)/Log(2))):Z=1-Z*(Z<N):End Function

If there were a built-in binary converter, it would be much shorter.
The recursion version is a tie, basically, but needs a line-feed for the IF
Function Y(N):Y=1:If N>1 Then Y=2*Y(N\2)+2*(N\2=N/2)+1
End Function

J, 10 bytes
(1&|.)&.#:

Using the formula where a(n) = n written in binary and rotated left by 1 place. Similar to what is used in @xnor's solution.
Using 19 bytes, we can play the game according to the rules in the challenge.
[:(2&}.,{.)^:_>:@i.

This solution only performs array manipulation in order to reach a final player.
Usage
Extra commands used for formatting multiple input/output with multiple functions.
   f =: (1&|.)&.#:
   g =: [:(2&}.,{.)^:_>:@i.
   (,.f"0,.g"0) i. 10
0 0 0
1 1 1
2 1 1
3 3 3
4 1 1
5 3 3
6 5 5
7 7 7
8 1 1
9 3 3

Explanation
(1&|.)&.#:  Input: n
        #:  Convert to binary
(    )&.    Compose next function on the binary value
 1&|.       Rotate left by 1 place
(    )&.    Compose the inverse of the previous function on the result
        #:  The inverse: convert from binary to decimal and return result

[:(2&}.,{.)^:_>:@i.  Input: n
                 i.  Creates the range [0, 1, ..., n-1]
              >:@    Increment each in the range to get [1, 2, ..., n]
[:(       )^:_       Nest the function until the result does not change and return
   2&}.              Drop the first two items in the list
        {.           Get the head of the list
       ,             Join them together. This makes it so that the head of the list
                     is always the current player and the one after the head is the
                     player to be removed

Python, 29 bytes
f=lambda n:n&n-1<1or f(n-1)+2

Outputs 1 as True when n is a power of 2, checked by n&n-1 being 0. Otherwise, outputs 2 higher than the previous value.

28 bytes:
Adapting grc's general solution to the case k=2 gives a better solution
f=lambda n:n and-~f(n-1)%n+1

Rather than explicitly checking for powers of 2, it zeroes out the result before incrementing each time f(n-1) catches up to n-1


text:
bfcat - encode a file as a brainf*** program
Challenge
Write a program or function that given a string, returns a valid Brainfuck program that when compiled and executed as Brainfuck, returns that string..

Assume all inputs are encoded as ASCII.

Assume the outputted BF program will execute in an environment with an infinite tape.

Assume the pointer starts at cell 0 with every cell initialized to a value of zero.

Each example below represent one possible correct output for the given input. In particular, the examples include extra newlines and spaces to help human readability. Solutions are free to format the outputted BF code in any way.

The tape is doubly infinite.

All cells provided by the interpreter are exactly 8-bit cells. Overflow and underflow wrap around in a predictable and sane matter.

Examples
Space string
Given the input   , your program/function could return:
+++++ +++++
+++++ +++++
+++++ +++++
++ .

Exclamation point
Given the input ! , your program/function could return:
+++++ +++++
+++++ +++++
+++++ +++++
+++
.

Two letters
Given the input hi , your program/function could return:
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++
+++++ +++++

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

++++
.
+
.

This is code-golf, so the code with the smallest number of bytes wins. Good luck.

More testcases please.

What exactly are the guidelines mentioned in Revision 9?

I'm reopening this. I think Peter's concerns have been addressed and we have a fairly clear consensus on what counts as a duplicate, and this challenge doesn't meet those criteria.

"Overflow and underflow wrap in a predictable and sane manner" - so 127+1 wraps to 0 and -128-1 also wraps to 0, correct? That's one possible predictable and sane manner.

@immibis Exactly.

Jelly, 8 bytes
O”+ẋp“.>

Try it online!
Sample run
For input hi, this program prints
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++.+++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++>++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++>

(without the linefeeds) which, in turn, prints hi.
How it works
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.

Yours don't work on limited memory, mine does.

Not really. We both store the entire output in memory before printing. For BF interpreters with a large enough tape, that will become an issue long before the tape does.

Why doesn't .> appear in the output?

@cat Because Cartesian product (p) is shorter than append to each (;€). These ouput programs double the cell after printing and before switching. Since we never revisit the cell, it doesn't affect the output.

@Dennis ahh, interesting.

Brainfuck, 55 51 bytes
,[>+++[>+++++++<-]>[<++>>+++<-]<+<[>.<-]>+++.>>-.,]

Try it online!
Example output for hi (without the linefeeds):
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>

Explanation
This moves across the tape while writing the program. The surrounding ,[...,] is a standard input loop. For each character, we use four cells:
[... x a b c ...]

where x is the cell we write the input to.
>+++[>+++++++<-]

This part uses cell a to write a 21 into cell b via a standard multiplication of 3 and 7.
>[<++>>+++<-]

Now we use that 21 to write 42 into a and 63 into c by multiplying by 2 and 3 respectively. Then <+< moves back to cell x while turning the 42 into a 43 (the code point of +). Recap:
[... x 43 21 63 ...]

Now the main output loop:
[>.<-]

That is, while decrementing x we print one + each time.
>+++.

After we're done we reuse the + cell, by adding 3 to give ..
>>-.

Finally, we move to the 63, decrement it to 62 (>) and output that as well. The next iteration will use this cell as x.

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

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!
For a (longer) solution that works unconditionally, see my other answer.
Test run
For input Code Golf, the following output is generated.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.,-------------------------------------------------------------------------------------------------------------------------------------------------.,------------------------------------------------------------------------------------------------------------------------------------------------------------.,-----------------------------------------------------------------------------------------------------------------------------------------------------------.,--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.,-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------.,-------------------------------------------------------------------------------------------------------------------------------------------------.,----------------------------------------------------------------------------------------------------------------------------------------------------.,----------------------------------------------------------------------------------------------------------------------------------------------------------.,

Try it online!
How it works
We begin by putting the integer 45 (character code of -) into a cell of the tape. The following code achieves this.
-      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.
]

Before we enter the loop, the tape looks like this.
         v
000 000 255

These three cells – -2, -1, and 0 – are the only ones we'll use in this program.
In the first each iteration of the loop, the rightmost cell is, then that cell and middle cell are decremented twice, leaving the following state.
     v
000 254 252

In the next 126 iterations, the initial - decrements the middle cell, [>]< jumps to the rightmost cell, and --<-- decrements the middle and the right cell. As a result, 3 is subtracted from the middle cell (modulo 256) and 2 is subtracted from the rightmost cell.
Since 254 ÷ 3 (mod 256) = (254 + 256) ÷ 3 = 510 ÷ 3 = 170 and 252 ÷ 3 = 84, the rightmost cell is zeroed out before the middle one, leaving the following state.
     v
000 132 000

Similarly to the first iteration of the loop, the next iteration now subtracts 3 from the middle cell and 2 from the leftmost cell, placing the head on the leftmost cell.
 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.
Since 254 ÷ 3 (mod 256) = 170 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.
Now we're ready to generate output.
,      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.

Why does the resulting BF not translate back to the input string for me? This is the interpreter I'm using, which has worked for the other answers.

That interpreter has a lot of settings. For the 32 byte version, you'd need dynamic memory and end of input: \0.

Brainfuck, 3513 43 bytes
++[>+<------],[[>.>+<<-]>+++.->[<.>-]<--<,]

This answer makes no assumptions about the interpreter of the output program. Try it online!
For a shorter solution (which works only with some interpreters), see my other answer.
Test run
For input Code Golf, the following output is generated.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-------------------------------------------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.---------------------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.----------------------------------------------------------------------------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-----------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++.--------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.-----------------------------------------------------------------------+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.---------------------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------------------------------------------------------------------++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.------------------------------------------------------------------------------------------------------+++++++++++++++++++++++++++++++++.---------------------------------

Try it online!
How it works
We begin by putting the integer 43 (character code of +) in the second cell of the tape. The following code achieves this.
++         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.
]

This essentially performs the modular division 2 ÷ 6 (mod 256). Since (2 + 256) ÷ 6 = 258 ÷ 6 = 43, the result is 43, as intended.
Now we're ready to generate output.
,      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

Anything to avoid that comment...

Pyth - 11 bytes
sm+*\+Cd".>

Try it online here.

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: Thanks! I was looking for a "repeat" command.

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.

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

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

Brainfuck, 29 bytes
,[[+>+[---------.]<]--[--.],]

Try it online!
Explanation:
,[                  loop over all characters on input
  [+                output number of minuses based on input
    >+[---------.]< print characters including -
  ]
  --[--.]           print all even characters in reverse equal to .,
,]

This solution expects classic 8-bit wrapping interpreter and uses the fact that other characters than +-,.<>[] are ignored by brainfuck interpreter. It also expects that generated program will be run with no input and thus receives null bytes as input - reading of input is used to clear the cell.
Statement generating - actually generates following string: øïæÝÔËÂ¹°§zqh_VMD;2) üóêáØÏÆ½´«¢~ulcZQH?6-$  , where the only interpretable character is -.
Statement generating ., actually generates üúøöôòðîìêèæäâàÞÜÚØÖÔÒÐÎÌÊÈÆÄÂÀ¾¼º¸¶´²°®¬ª¨¦¤¢ ~|zxvtrpnljhfdb`^\ZXVTRPNLJHFDB@><:86420.,*(&$"   where following characters are interpreted ><.,. The >< moves pointer right and then left, so it actually doesn't do anything.

Running output link

Sesos, 12 bytes
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

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!

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

@VTCAKAVSMoACE Done! :)

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.

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!

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

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.

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.

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

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

@LeakyNun Downvote and move on

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 Just save it in a file and run it as lua file.lua "argument", I will update the post to give instructions.

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

@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.

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

always forget the existence of gmatch ^^. also, shorter with for(...):gmatch"."do print(("+"):rep(c:byte())..".>")end, will update :)

@LeakyNun doesn't work as is, because the for loop isn't well declared, I'll see if I can do something.

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

hi - http://paste.ubuntu.com/17995958/
quick brown fox jumps over the lazy dog - http://paste.ubuntu.com/17996059/
source code - http://paste.ubuntu.com/18000808/

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

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

brainfuck, 27 bytes
,[[>+[++++.+++]<-]--[.--],]

Try it online! Try result
Optimized from Jiří's solution
JavaScript (V8), 49 bytes
x=>[...x].map(c=>'+'.repeat(c.charCodeAt())+.1)+0

Try it online!

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

Assumes input string is represented as-is in a file passed as first argument.
Usage: bash bfcat.sh <path to file containing string>
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

Read file byte by byte

ord of a char in bash

emit character $n times

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. :)

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 It looks awesome! I really need to get in the habit of edit->preview->edit->...

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.

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 oh I didn't know that bf ignores other characters, thanks!

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 ' ~'
++++++++++++++++++++++++++++++++>.
                 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>.

Pyke, 11 bytes
F.o\+*".>"+

Try it here!

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)

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

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).

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(".>")
)              ~ }

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.

Haskell 50 Bytes
f[]=[]
f(x:y)=replicate(fromEnum x)'+'++".>"++f y

><>, 39 41 bytes
0i:@:0(?;\~~o!
v?:+"Ā"-$/'.'~
/.13-1o'+'

Explanation
Add 256 to each char code, then print that many +, then .

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
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>

05AB1E, 9 bytes
Ç'+×„.>«J

Try it online!
Ç'+×„.>«J  # full program
        J  # join...
   ×       # runs of...
Ç          # codepoints of...
           # (implicit) each character in...
           # implicit input...
 '+        # literals...
       «   # with...
    „.>    # literal...
       «   # appended to...
           # (implicit) each element
           # implicit output

BinaryFuck, 12 bytes
0x071cbb2593eeca31d084c0ef
Technically, 11.5 bytes . But who counts fractions of bytes, anyways?
Yeah, I just took the shortest solution in Brainfuck and substituted it. (Hey, I shortened it by 19 bytes!) Here's a hex to binary converter to convert the hexadecimal to binary.

Rattle, 25 bytes
|R2I=@P[$n[b"+"]`b".>">]`

Try it Online!
Explanation
|                  parse input
 R2                reformat as string
   I               split into chars and save into consecutive memory slots, move pointer to end
    =@             set top of stack to pointer value
      P            set pointer to 0
       [...]`      loop n times where n is the top of the stack (the old pointer)

$                  swap top of stack with value in storage at the pointer
 n                 get ASCII value of top of stack
  [....]`          loop n times where n is the top of the stack
   b"+"            add "+" to the print buffer
         b".>"     add ".>" to the print buffer
              >    move pointer to next slot

Nim, 69, 67 bytes
import strutils;for i in readLine stdin:echo repeat("+",i.int)&".>"
Attempt This Online!
Wow, I beat ES6, that is a shock. Nim usually does a lot worse!

Thunno 2 JB, 7 bytes
'+×`.>+

Try it online!
or verify the resulting BF program
Explanation
'+×`.>+  '# Implicit input
          # Cast to ordinals
'+×      '# Multiply by "+"
   `.>+   # Add ".>" to each
          # Join into a string
          # Implicit output

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Evaluate a Stratego Battle
In the game Stratego, the main game mechanic is when you attack an opponent's piece with yours. In this challenge, you job is to simulate one of these battles and say who survives.
Specs
You will get as input a pair of string representing Stratego pieces. The pieces are one of "S 1 2 3 4 5 6 7 8 9 10 B" (S is the Spy, and B are bombs). The first of the pair will be the attacker, and the second the attacked.
Here are the rules for determining the results of a battle:

The higher number beats the lower number: ["4", "6"] -> ["6"].
If both are the same, then both die: ["7", "7"] -> [].
Spies are at the bottom, underneath even 1: ["S", "2"] -> ["2"].
However, if a spy attacks the 10, then the spy wins: ["S", "10"] -> ["S"].
But the normal rules still apply if the 10 is the one attacking: ["10", "S"] -> ["10"].
If anything attacks a bomb, the bomb wins: ["5", "B"] -> ["B"].
However, a miner (a 3), can defuse a bomb: ["3", "B"] -> ["3"].
A bomb will never be the attacker.
A spotter (a 1), can attack using the normal mechanism, but they can also try to "guess" the rank of the other player, which can be denoted with any sane notation.
If they guess correctly, the other piece dies: ["1(5)", "5"] -> ["1"].
If they guess wrong, nothing happens: ["1(3)", "5"] -> ["1", "5"].
Spotters can spot bombs: ["1(B)", "B"] -> ["1"].

This is code-golf, so shortest code in bytes wins!
(You can use the examples up there as test-cases, because I'm too lazy to put them all together in one list).

can we use 0 and 11 to represent S and B respectively?

@LeakyNun no, that would make it too easy to rank them.

I knew about the reversal of ranks (1s used to be best, beaten only by attacking spies, 8s were miners, and 9s were worst), but I never heard of the spotter rank or guess-and-you-win rule. But that's just me babbling. Of actual interest here: What about flags?

@msh210 I was considering having an output of "Victory!" for them, but didn't want to complicate things too much

Doesn't a Spy win any battle (if the one attacking), with the exception of a Bomb, and lose all defenses? And what set of Stratego rules is this from? Spotters (Scouts) would be 2s, and there were no 1s in my Stratego game... (or are they just modified for the purpose of the challenge?)

@mbomb007 idk, its the one I have in my house. 2s are still scouts, but don't have any special rule for attacking. And yeah, I don't know if all the games have special rules for 1's , but mine did.

2s could move like Rooks in mine.

@mbomb007 they do in mine also, but the attacking mechanics are the same.

Haskell, 131 bytes
This solution is in the form of an infix function # with type String -> String -> String
Input is accepted through the two string arguments. The format for spotter input is 1 x where x is the guess.Output is given as a string. In the case where both units survive, the returned string contains both separated by a space.
My original solution was unfortunately bugged and the fix cost me a few bytes.
('1':' ':x)#y|x==y="1"|1>0="1 "++y
"S"#"10"="S"
"3"#"B"="3"
_#"B"="B"
x#y|x==y=[]
t@"10"#_=t
_#t@"10"=t
"S"#x=x
x#"S"=x
x#y=max x y

Python, 180 153 bytes
def f(a,d,g=0):T=([[d]],[[a]]);return([[a]+[d]*(g!=d)]*(g!=0)+[[]]*(a==d)+T[d=="10"]*(a=="S")+T[1]*(d=="S")+T[a=="3"]*(d=="B")+T[int(a,36)>int(d,36)])[0]

The function takes the attacker, defender and optionally the spotter's guess (if the attacker is the spotter) as arguments.  It returns an array containing the live pieces that remain.
Ungolfed
def f(a,d,g=0):
 if g: return [a] if g==d else [a,d]
 if a==d: return []
 if a=="S": return [a] if d=="10" else [d]
 if d=="S": return[a]
 if d=="B": return [a] if a=="3" else [d]
 return [a] if int(a)>int(d) else [d]

Demo
https://repl.it/C6Oz/2

([a,d],[a])[g==d] -> [a,d][:(g!=d)+1]

@Leaky Nun - Thanks, and [a]+[d]*(g==d) is shorter still.

Javascript ES6, 98 86 bytes
(a,b,g)=>a==1?b==g?a:[a,b]:b=="B"?a==3?a:b:a=="S"?b==10?a:b:b=="S"?a:a==b?[]:+a>+b?a:b

Accepts 3 args (attacker, defender, spotter guess).
Example runs:
f("4","6")     -> "6"
f("7","7")     -> []
f("S","2")     -> "2"
f("S","10")    -> "S"
f("10","S")    -> "10"
f("5","B")     -> "B"
f("3","B")     -> "3"
f("1","5","5") -> "1"
f("1","5","3") -> ["1","5"]
f("1","B","B") -> "1"

If you don't need to return an array, you can save a handful of bytes.

Your code isn't working correctly for me when a spotter does not make a guess.  f("1","10") -> ["1","10"] rather than "10".

Javascript, 179 166 160 bytes
f=(a,c,b,n="")=>{if(c)if(c==b)return[a];else return[a,b];if(a==b)return[];a+b=="3B"&&(b=n);a=b=="B"?n:a;b=b=="S"?n:b;a+b=="S10"&&(a=n,b="S");return[+a>+b?a:b]}

This function takes 3 arguments - first one is attacker, second is used for spotters (their guess) and third is defender.

f = ( a, c, b, n = "" ) =>
{
 //Takes attacker (a), guess (c) and defender (b), n is only declaration
 //c should never be set unless a == 1
 if ( c )
  if ( c == b ) return [ a ];
  else return[ a, b ]; //Spotters

 if( a == b ) return [ ]; //Kill each other if same

 a + b == "3B" && ( b = n ); //Miners destroy bombs
 a = b == "B" ? n : a; //Bomb kills almost everything
 b = b == "S" ? n : b; //Spy dies if anything attacks him
 a + b == "S10" && ( a = n, b = "S" ); //Spies kill 10s

 console.log( JSON.stringify( [a,b] ) );

 return [ +a > +b ? a : b ] //Higher number wins
}

function fight( )
{
 var input = [ [ attacker.value, guess.value], defender.value ];
 out.innerHTML += JSON.stringify( input ) + "   ->   " + JSON.stringify( f( input[0][0], input[0][1], input[1] ) ) + "
";
}
#sword
{
 width: 40px;
 height: auto;
 margin: 10px;
 cursor: pointer;

}

#guess
{
 width: 40px;
}

textarea
{
 height: 20px;
 margin-top: 0px;
}

.panel
{
 background-color: #DDDDDD;
 padding: 5px;
 border: 3px solid black;
}

#out
{
 border: 3px solid black;
 font-family: monospace;
 padding: 10px;
}

   <textarea id=attacker placeholder="Attacker"></textarea>
   <textarea id=guess></textarea>

   <textarea id=defender placeholder="Defender"></textarea>

Sword icon comes from cliparts.co

TSQL,  162 124 bytes
Golfed:
DECLARE @1 varchar(2)='1',@ varchar(2)='3',@s varchar(2)='4'

PRINT IIF(@s>'',IIF(@=@s,@1,@1+','+@),IIF(@1=@,'',IIF(@1+@
IN('S10','3B')or'S'=@,@1,IIF(@='B'or'S'=@1,@,IIF(@1/1<@,@1,@)))))

Ungolfed:
DECLARE
  @1 varchar(2)='1', -- first piece
  @  varchar(2)='3',  -- second piece
  @s varchar(2)='4'  -- spotter(only fill this value for spotters)

PRINT
  IIF(@s>'',
    IIF(@=@s,@1,@1+','+@),
      IIF(@1=@,'',
        IIF(@1+@ IN('S10','3B')or'S'=@,@1,
          IIF(@='B'or'S'=@1,@,
            IIF(@1/1<@,@1,@)))))

Fiddle

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Can Pac-Man Eat This String?
In the arcade version of the game, Pac-Man eats pac-dots. However, in this challenge, he's hungry for alphanumeric characters and punctuation in a string.
Your task is to create a function that feeds Pac-Man a string, evaluates if he can eat it or not, and returns the string with Pac-Man's location in it.
Pac-Man (<) eats characters from left to right, leaving an underscore or space for each character as he goes, and his goal is to get from the first position-1 to the last position+1:
1. <Pac
2. _<ac
3. __<c
4. ___<

However, Pac-Man's natural enemy, the ghost, will stop him if he encounters one of the letters in the word "GHOST" (not case sensitive). Your function should return the string with Pac-Man's location as he encounters the ghost character:
1. <No!
2. _<o!

The only thing that can defeat a ghost is a power pellet. If Pac-Man reaches a letter in the word "PELLET" (also not case sensitive) before coming to a ghost, he will eat the ghost and keep moving, and that pellet will be used up. Power pellets can stack (ie, in ppgg both ghosts would be eaten). The T character exists as both as a ghost and a pellet, so it can be ignored (treated as any other letter, like a).
1. <Pop
2. _<op
3. __<p
4. ___<

To further clarify, in the string "Pac-Man loses here", the following operations occur:
P <P, +1 Pellet (1 pellet)
a <a
c <c
- <-
M <M
a <a
n <n
  <[space]
l <l, +1 Pellet (2 pellets)
o <o, -1 Pellet (1 pellet)
s <s, -1 Pellet (0 pellets)
e <e, +1 Pellet (1 pellet)
s <s, -1 Pellet (0 pellets)
  <[space]
h <h, ghost wins, returns
e
r
e

Examples
Input: Pacman wins!
Output: ____________<

Input: Pacman loses wah-wah :(
Output: _______________<h-wah :(

Input: PELLET PELLET GHOST
Output: ___________________<

Input: Hello World!
Output: <Hello World!

Input: <_!@12<_<_<
Output: ___________<

This is code-golf--lowest score in bytes wins.

So the pellets have no expiration date?

Are trailing tabulations accepted in the output?

@Katenkyo the last character should be either the last character of the input or <, barring any language quirks.

The T character can be ignored Can you clarify? Does that mean none of the inputs can contain a "t"?

@DrGreenEggsandIronMan I think it means that a T is like say an a: it doesn't have any effect

@DrGreenEggsandIronMan Luis is correct, it cancels itself and can be treated like any other character not in GHOSPEL

+1 for the fact that "here" is where pacman loses. Clever test case.

> [I]n this challenge, he's hungry for alphanumeric characters and punctuation in a string. ... Yacc-man?

Now I see a camouflaged grey pacman with black lips every time i look at the < symbol...

Jelly, 34 33 bytes
Œl“ʋʋ“ṁḍ»ċ€Ð€IF+\‘0ṭi0ð’”_×;”<;ṫ@

Try it online!
I think I'm finally starting to understand Jelly. Feels a bit scary.

I'd start worrying when you can read it fluently :)

Retina, 55 38 bytes
i`^(([elp])|[^ghos]|(?<-2>.))*
$.&$*_<

Try it online! (The first line just allows running several test cases at once.)
Explanation
The problem is essentially to find the longest prefix that doesn't have an unmatched closing parenthesis. Except that we can use either e, l or p in place of ( and either g, h, o or s in place of ).
Hence, this solution is almost a textbook example of balancing groups. I won't go into too much detail about how they work, as this code is essentially the same as the standard example you can read up on in my SO answer on balancing groups.
The entire program is therefore a single regex substitution. The i activates case-insensitivity. Then we either match a pellet with [elp] and increment the depth counter (in the form of the capture stack of group 2), or we match something that isn't a ghost with [ghos] or we match a ghost with . and decrement the depth counter by popping from stack 2. Of course, in principle this allows matching a pellet with the [^ghos] section or a non-ghost with the . section, but thanks to greedy matching and the way the regex is backtracked, these possibilities are never attempted by the regex engine.
The substitution then uses two Retina specific features: $* repeats the character to its right as many times as specified by the token on its left. That token is $.& which is the length of the entire match. This just means that we replace each character in the match with a _. And then we also append a < to those underscores. The part of the input that isn't eaten simply remains unaffected by the substitution.

Nice abuse of capturing groups!

@LeakyNun Abuse? That's what balancing groups are made for. :D

Hey look, a Retina answer that looks remotely like the regex I use

Python 2, 114 113 108 bytes
s=raw_input()
p=i=0
for c in s:
 p+=(c in'plePLE')-(c in'ghosGHOS')
 if p<0:break
 i+=1
print'_'*i+'<'+s[i:]

Your function returns None, not the answer. And how do you count 107? I count 110.

@StefanPochmann the double-spaces are tabs and its allowed to print the answer rather than returning it

@muddyfish Ah, thanks. They don't seem to be tabs here, though, not even when I go to "edit". And the problem clearly states "return"... are there site-wide rules overruling it or so? (I'm pretty new here and don't know)

@StefanPochmann tabs are eaten by SE (normally converted to 4 spaces). Unless explicitly stated printing in a function is allowed. The OP probably didn't mean to override this though

I think it's reasonable to say that it should always either return if it's a function or read from stdin and print. I'll change to reading from stdin, which should be shorter anyway.

Python 2, 89 bytes
Sometimes my stubborn determination to make Python a functional language has its benefits.
def f(s,l=1):l+=(s[:1]in'plePLE')-(s[:1]in'ghosGHOS');return s*l and'_'+f(s[1:],l)or'<'+s

(Slightly) ungolfed:
def f(s, l=1):
    l += (s[:1] in 'plePLE') - (s[:1] in 'ghosGHOS')
    return (s * l) and ('_' + f(s[1:], l)) or ('<' + s)

Builds up the result string using recursion. The update to l (for "lives") adds 1 for pellets (True - False == 1), subtracts 1 for ghosts (False - True == -1),  and adds 0 for any other character. It also adds 0 when s is the empty string, thanks to Python's slicing and the fact that '' in any_str == True, so the pellet and ghost cancel.
The return statement uses test and b or a in place of a if test else b to save one byte. The recursion base case occurs when either the string ends or Pac-Man runs out of pellets, succinctly represented as s*p, which equals '' (and therefore evaluates to false) when either s == '' or p == 0.

Pyth, 53 48 44 bytes
4 bytes thanks to @Pietu1998 for the !!@ -> } trick (which only people who know Pyth can understand)

++*Jf<@+sM._m-!!@d"PELpel"!!@d"GHOSghos"Q_1T00\_\<>QJ
++*Jf<@+sM._m-!!@d"PEL"!!@d"GHOS"rQ1_1T00\_\<>QJ
++*Jf<@+sM._m-}d"PEL"}d"GHOS"rz1_1T00\_\<>zJ

Test suite.

which only people who know Pyth can understand Well, like pretty much the rest of the code, naturally

@LuisMendo To be fair to people who don't know Pyth, I'm pretty sure most of them could understand that the set intersection between one singleton set and another set having any members is equivalent to the singleton set's member being a member of the larger set :P

@FryAmTheEggman so obviously !!@ is just a trigraph for }, right? :p

MATL, 37 36 35 bytes
tkt'ghos'mw'pel'm-Ys1=Y>&)g95*60bhh

Try it online!
Explanation
tkt      % Input string implicitly. Duplicate, convert to lower case, duplicate
'ghos'm  % True for "ghost" characters
w'pel'm  % Swap to bring lowercase copy to top. True for "pellet" characters
-Ys      % Subtract, cumulative sum. Pac-Man can reach until the first "1"
1=       % True for entries that equal 1
Y>       % Cumulative maximum. This gives false until the first true is found, and
         % true from there on
&)       % Split original string in two parts, given by the zeros and ones respectively
g95*     % Convert the first part into ones and multiply by 95. This gives a numerical
         % array containing number 95 (ASCII for '_')
60       % Push 60 (ASCII for '<')
b        % Bubble up second part of original string
hh       % Concatenate the three strings/arrays, automatically converting to char

C#, 269 256 232 212 211 Bytes
First ever post on here, so this is probably a lot longer than it could be (and probably because it is in C#). Any tips on where I could shorten it would be great!
Thank you to everyone in the comments who helped me!
Golfed version
static void p(string x){int p=0,i=0;string t='<'+x;var s=t.ToCharArray();for(;++i<s.Length;){if("PELpel".Contains(s[i]))p++;if("GHOSghos".Contains(s[i])&&--p<0)break;s[i]='<';if(i>0)s[i-1]='_';}Console.Write(s);}

Ungolfed version
static void p(string x) {
 int p = 0, i = 0;
 string t = '<' + x;
 var s = t.ToCharArray();
 for (; ++i < s.Length;) {
  if ("PELpel".Contains(s[i])) p++;
  if ("GHOSghos".Contains(s[i]) && --p < 0) break;
  s[i] = '<';
  if (i > 0) s[i - 1] = '_';
 }
 Console.Write(s);
}

You can replace types in variabledeclerations using the var-keyword.
e.g. var temp = ' ' + input; The for loop can be rewritten to save 4 chars:
for(var i = 0; i++ < s.Length;)

You can use commas to declarations "int i=0,p=0;string P="PELpel",G="GHOSghos",t=' '+x;" and the change from @CSharpie, making the loop "for(;i++<s.Length;)". Additionally, you can "Console.Write(s);" directly for a total of 235 bytes.

I think it should also work without the else saving 5 more characters. And by starting the loop at i = 1 you should be able to remove the last if as the code can be executed every time.

You can get rid of your c declaration and just inline the s[i] access for 5 characters.

Is it worth assigning P="PELpel" and G="GHOSghos"? You only use them once each. Am I missing something, or is that just 4 extra characters? Also, do you need the else? "PELpel".Contains(c) and "GHOSghos".Contains(c) should be mutually exclusive.

You could also just run this to ungolf your code: http://codebeautify.org/csharpviewer. Makes it readable enough.

if you rewrite if(GHOST.Contains(c)) if (--pellets < 0) as if(GHOST.Contains(c) && --pellets < 0) , you should be able to save at least 2bytes

You can also shorten the string decl to var s = ("<" + x).ToCharArray(); to shave some more characters and completely remove the declaration of t

However, pedantically speaking, this isn't a complete app as one will still need the class, using, and other cruft to compile.

JavaScript (ES6), 98 bytes
s=>s.replace(/./g,c=>p<0?c:(p+=/[elp]/i.test(c)-/[ghos]/i.test(c))<0?"<"+c:"_",p=0)+"<".slice(p<0)

Explanation: p maintains the current number of pellets. If it's already negative, we just return the character and move on, so that the rest of the string is untouched. Otherwise, we examine the current character, and if that makes p become negative, we insert the < character, otherwise we replace the current character with _. Finally, if p never becomes negative, we suffix a < to the string.

Lua, 198 190 184 185 163 Bytes
Ok, I admit, this is long. Very long. Lua has some tools to play around with strings, but it is limited, same goes for conditionals that takes lots of spaces.
Edit: thanks @LeakyNun for saving me 9 bytes :)
        Lost some bytes to fix a bug
Edit 2: 163 Bytes solution found by @LeakyNun
i=0p=0n=...for c in n:gmatch"."do
p=p+(c:find"[ghosGHOS]"and-1or c:find"[pelPEL]"and 1or 0)if p<0then
break else i=i+1 end end print(('_'):rep(i)..'<'..n:sub(i+1))

Old 185
p=0z=(...):gsub(".",function(c)p=p+(c:find"[ghosGHOS]"and-1or
c:find"[pelPEL]"and 1or 0)s=p<0 and 1or s
return s and c or'_'end)_,i,s=z:find"(_+)"print((s or'')..'<'..z:sub(1+(i or 0)))

Ungolfed
i=0                        -- number of characters eaten
p=0                        -- pellet counter
n=...                      -- shorthand for the argument
for c in n:gmatch"."       -- iterate over each characters in the input
do
  p=p+(c:find"[ghosGHOS]"  -- if the current char is a GHOST
        and-1              -- decrement the pellet counter
      or c:find"[pelPEL]"  -- if it's a PELLET
        and 1              -- increment it
      or 0)                -- else, leave it alone
  if p<0                   -- if we try to eat a ghost without pellet
  then
    break                  -- stop iterating
  else
    i=i+1                  -- else, increment our score
  end
end

print(('_'):rep(i)         -- print i*'_'
  ..'<'                    -- appended with Pacman
  ..n:sub(i+1))            -- appended with the remaining characters if we died

Remove d=c:lower() and search for the uppercase characters as well

and 1or s and 1or s s and s

@LeakyNun didn't see that would be shorter to just write all letters... Thanks. Also, the second comment mentioned something I changed, but only in the ungolfed >_<

print(('').rep('_',i)..','..z:sub(i+1))

@LeakyNun I'm working around a similar solution, but the problem comes from the fact that i can be nil

i=0p=0 for c in(...):gmatch"."do p=p+(c:find"[ghosGHOS]"and-1or c:find"[pelPEL]"and 1or 0)if p<0then break else i=i+1 end end print(('').rep('_',i)..'<'..n:sub(i+1)) this is 165 bytes

+1 Because I hardly ever see Lua around here.

@kirkpatt Thanks, I think I'm the main user of Lua on this site ^^.

('').rep('_',i) is really ('_'):rep(i)

Pyth, 47 46 44 bytes
++*\_Kh+f!h=+Z-}Jr@zT0"pel"}J"ghos"Uzlz\<>zK

Try it online. Test suite.
Quite a different approach from Leaky Nun's, and I'm quite sure this can be golfed further.

Use Z instead of G and change f! to f!h

@LeakyNun Just figured that out in another tab too. Thanks.

I think the t in "ghost" should be removed

If we keep golfing our solutions, what is the defining difference between our solutions?

@LeakyNun I'm not sure which of these is closer, but my first attempt got me 43 bytes, and I don't think I need to add a third answer. Maybe we should work together in the Pyth chatroom?

@LeakyNun Nothing, but duplicate answers aren't a bad thing when you work together to golf each other's answers :)

@FryAmTheEggman sure

@LeakyNun Whoops, just noticed the ghosT thing

Python 3, 176 157 150 149 134 133 124 bytes
Define a function named f which take the string as argument
def f(s):
 n=i=0
 for c in s:
  if c in"GgHhOoSs":
   if n:n-=1
   else:break
  n+=c in"PpEeLl";i+=1
 return"_"*i+"<"+s[i:]

Can be probably be golfed more
Thanks to everyone who commented :D

﹐Remove x=c.upper() and search for lowercase matches

You can save some by writing some expressions on the same line separated by a ; rather than having each on its own line. Also you can use Python 2 which allows you to use spaces as first intendation level and tabs as second one.

n=i=0, not n=0 and i=0. t[i]="_" instead of t[i] = "_", the same for t[i] = "<". return''.join(t), remove that space.

@LeakyNun There is uppercase in the testcases.

@TùxCräftîñg No, they mean "GgHhOoSs" and "PpEeLl".

What is that weird dot (﹐) on the start of your comment?

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Firstly, it's a SMALL COMMA, and i don't see it

@TùxCräftîñg On LeakyNun's comment, sorry for that!!!

@EʀɪᴋᴛʜᴇGᴏʟғᴇʀ Your snippet give me a IndentationError

return "_"*n+"<"+t[n+1:] (not tested)

@LeakyNun Can't convert 'list' object to str implicitly

then use ''.join

@LeakyNun Don't throw a error, but pacman is always at the start

I dont understand.

@LeakyNun PPCG give _<PCG, but this would normally give ____<

Oh, then replace the line with i+=1 by i+=1, and then change n to i in the return statement

@LeakyNun Yay, it's work ! Thanks you

return'' instead of return ''

t=' '+s is completely useless

(why am I transforming you to the answer above?)

why is it necessary?

change t[i+1:] to s[i:] and then remove the t=' '+s completely.

@LeakyNun Sorry, it's not neccesary, effectively...

if c in"PpEeLl":n+=1 to n+=c in"PpEeLl" (yep, transformation confirmed)

put n+=c in"PpEeLl";i+=1 on one line like that

Do if n and c in"GgHhOoSs":n-=1\n  else:break for the if statement

@cat The if n and c in"GgHhOoSs":n-=1\n else:break dont work :C

That ''.join on the last line is completely useless now

Python 3, 114 110 bytes
My first code golf.
Thanks to Dr Green Eggs and Iron Man for saving 4 bytes.
l,x=1,0
f,y,s="ghosGHOS","pelPEL",input()
while s[x:]*l:l+=(s[x]in y)-(s[x]in f);x+=l>0
print("_"*x+"<"+s[x:])

Utilises the evaluation of booleans to one and zero to condense a logical AND to a multiplication. (0*0=0, 1*0=0, 1*1=1). I hope this is a good first try.

Nice answer, and welcome to the site! Which version of python are you using? You might want to specify that. Also, I haven't tested it, but you might be able to do while s[x:]*l to take off 4 bytes.

Haskell, 119 113 Bytes
Thanks to Daniel Wagner for 6 bytes less.
p=(0!)
n!(c:s)|elem c"ghosGHOS"=if n<1then '<':c:s else(n-1)&s|elem c"elpELP"=(n+1)&s|0<1=n&s
_!_="<"
n&s='_':n!s

Call it as p "Hello World!".
The 1then is an edge case that is interpreted correctly in my GHC (7.10), but it throws of most syntax highlighters. So it might be interpreted differently in your compiler as well.
Ungolfed:
pacman string = go 0 string

-- | In the golfed version: (!)
go _   []                   = "<"                            -- won
go pellets (char:string)
 | char `elem` "ghosGHOS"
 = if pellets < 1        then '<':char:string                -- lost
                         else nextStep (pellets - 1) string  -- ghost
 | char `elem` "elpELP"
 =                            nextStep (pellets + 1) string  -- pellet
 | otherwise
 =                            nextStep  pellets      string  -- anything else

-- | In the golfed version: (&)
nextStep pellets string = '_':(go pellets string)

You can save a few bytes by putting all the guards on the same line, e.g. n!(c:s)|elem c"blah"=blah|elem c"blah"=blah|0<1=blah.

@Daniel Wagner Nice tip, thanks!

Can you add a TIO link? I keep getting errors when i try to make it work.

C, 237 bytes
#include<stdio.h>
#include<string.h>
main(p,i,j){char s[99];fgets(s,99,stdin);for(p=i=0;s[i];++i){if(strchr("GHOSghos",s[i])){if(p)p--;else break;}else if(strchr("PELpel",s[i]))p++;}j=i-(s[i]==0);while(j--)printf("_");printf("<%s",s+i);}

Python3, 211 184 bytes
The argument 's' is a string
def f(s):
    p=c=0
    for i in s:
        if i in "gGhHoOsS":
            if p<1:break
            else:p-=1
        if i in "pPeElL":p+=1
        c+=1
    return"_"*c + "<" + s[c:]

I would appreciate any golfing tips as this is my first code golf attempt
Thanks for commenting :)

Welcome to Programming Puzzles & Code Golf! Some tips:There are a lot of unneccessary whitespaces between operators. Removing them would save a good amount of bytes. Also you can use Python 2, which allows you to use spaces as first intendation level and tabs for the other ones.

You can replace the first return "_"*c + "<" + s[c:] with just a break as that code will be executed after the for loop anyways.

Try it online! I got 183 bytes by the way. Is there a trailing newline you counted?

C++, 315 373 327 Bytes
(Note: still golfing)
#include <iostream>
#include <string>
using namespace std;
int main(){string input;getline(cin, input);
if(input.find("Pac-Man loses")!=string::npos||input.find("Pacman loses")!=string::npos)
    cout<<"<"<<input.substr(15,input.length()-1);
else{for(unsigned i=0;i<=input.length();++i)
    cout << "_";
cout<<"<";
}return 0;
}

Pac-Man's not losing when it's supposed to be.

Hi @tildearrow, thanks for reviewing my code! I'll update my post.

I think this can be golfed more. Try removing newlines/spaces after if(), and removing spaces around !=, ||, =, -, and <=. Also, doesn't cin>>input work instead of getline? You can also condense around ;.

@NoOneIsHere, thanks for your comment! I'm actually new to code-golfing, so I'll try to golf my code some more and update my post. If you have any other helpful advice on code-golfing, I'd really appreciate it.

You can look at Tips for C/C++ golfing.

I don't understand how to code-golf if-else statements in C++. Could someone please provide me an explanation and some examples? Thanks!

Powershell, 185
{$l=1;$o="";for($i=0;($i -lt $_.Length) -or (($o+="<") -and 0); $i++){if ($_[$i] -match '[pel]'){$l++}if($_[$i] -match '[ghos]'){$l--}if(!$l){$o+="<"+$_.substring($i);break}$o+="_"}$o}

Ungolfed:
("Pacman wins!",
"Pacman loses wah-wah :(",
"PELLET PELLET GHOST",
"Hello World!"
) |
% {
    $l=1;$o="";
    for($i = 0; ($i -lt $_.Length) -or (($o+="<") -and 0); $i++) {
        if ($_[$i] -match '[pel]') { $l++ }
        if ($_[$i] -match '[ghos]') { $l--}
        if (!$l) { $o+="<"+$_.substring($i); break }
        $o += "_"
    }
    $o
}

Ruby, (119 bytes)
q=i=0;a=$**" ";a.split(//).each{|c|q+=((c+?p=~/[ple]/i)^1)-((c+?g=~/[ghos]/i)^1);q<0?break : i+=1};p ?_*i+?<+a[i..-1]

There is probably some things i'm missing as I am new to this...
Ruby is my friend :)

Welcome to PPCG!

Perl, 54 (52+2) bytes
s/([pel](?1)*[ghos]|[^ghos
])*/'_'x(length$&).'<'/ei

Needs -p to be specified in the command-line options.
Explanation:
The -p option causes the statement to be wrapped in a read-modify-print loop, where during each loop iteration, $_ contains a line of input, including the line delimiter.
The regex is largely the same idea as in the Retina answer.
Call the search pattern ([pel](?1)*[ghos]|[^ghos
])* "acceptable". Then it can be recursively defined as:
A string is "acceptable" if:

It is a character in PELLET except for T, followed by an acceptable string, followed by a character in GHOST except for T.
It is a character not in GHOST except for T that is not a newline character.
It is a concatenation of any number (including 0) of acceptable strings.

This definition allows more pellets than ghosts: a PEL character may be matched as either a pellet character, or a non-ghost character.
The empty string is considered acceptable, therefore the regex is guaranteed to match at position 0, where the longest acceptable substring will be matched.
This longest acceptable substring is then matched by underscores of equal length, followed by <.

iirc flags like -p count as one byte each.

@Pavel It's complicated. If the normal invocation without -p already used -, e.g. perl -e -> perl -pe, then the - is free. But I think the perl -e version is longer because of quoting, so I think I cannot use that here.


text:
Prove me wrong!
Introduction
Your mission in life is simple: Prove people wrong on the internet!
To do this you usually carefully analyze their statements and point out the contradiction in them.
It's time to automate this, but as we are lazy, we want to prove people wrong with the least effort (read: shortest code) possible.
Specification
Input
Your input will be a formula in conjunctive normal form. For the format, you may use the below format or define your own, upon the needs of your language (you may not encode more in the format than the pure CNF though). The test-cases (here) are however provided in the below format (although it won't be too hard generating your own).
Your input will be a a list of a list of a list of variables (you may also read it as strings / require strings). The input is a formula in conjunctive normal form (CNF) written as a set of clauses, each being a list of two lists. The first list in the clause encodes the positive literals (variables), the second list encodes the negative (negated) literals (variables). Every variable in the clause is OR'ed together and all clauses are AND'ed together.
To make it clearer: [[[A,B],[C]],[[C,A],[B]],[[B],[A]]] can be read as: (A OR B OR (NOT C)) AND (C OR A OR (NOT B)) AND (B OR (NOT A))
Output
The output is boolean, e.g. either some truthy value or some falsy value.
What to do?
It's simple: Check if the formula given at hand is satisfiable, e.g. whether there exists some assignment of true and false to all variables such that the overall formula yields "true". Your output will be "true" if the formula is satiesfiable and "false" if it is not.
Fun-Fact: This is a NP-complete problem in the general case.
Note: Generating a truth-table and checking if any resulting entry is true, is allowed.
Corner Cases
If you get an empty 3rd-level list, then there's no such (positive / negative) variable in that clause - a valid input.
You can leave other corner cases undefined if you want to.
You may also return true upon an empty formula (1st level list) and false upon an empty clause (2nd level list).
Who wins?
This is code-golf so the shortest answer in bytes wins!
Standard rules apply of course.
Test-cases
[[[P],[Q,R]],[[Q,R],[P]],[[Q],[P,R]]] -> true
[[[],[P]],[[S],[]],[[R],[P]],[[U],[Q]],[[X],[R]],[[Q],[S]],[[],[P,U]],[[W],[Q,U]]] -> true
[[[],[P,Q]],[[Q,P],[]],[[P],[Q]],[[Q],[P]]] -> false
[[[P],[]],[[],[P,S]],[[P,T],[]],[[Q],[R]],[[],[R,S]],[[],[P,Q,R]],[[],[P]]] -> false
optional behavior (not mandatory, may be left undefined):
[] -> true (empty formula)
[[]] -> false (empty clause)
[[[],[]]] -> false (empty clause)

May we take input as (A OR B OR (NOT C)) AND (C OR A OR (NOT B)) AND (B OR (NOT A))?

@Adám, as specified in the challenge, the format is entirely up to you, as long as it doesn't encode more information than the list-based one. (E.g. the formulation as you gave it is fully allowed)

@SEJPM If I understand the notation correctly, I think the 3rd and 4th test cases should return true. I tried substituting (P,Q)=(1,1) and (P,Q,R,S,T)=(0,0,0,0,0) and found both true, so there should at least be one case where the the expression is true.

@busukxuan, I'm 100% sure the third and fourth one are false. For the 3): this is {{P,Q},{P,!Q},{!P,Q},{!P,!Q}} (not in this order) which can be easily shown is a contradiction. For the 4): This is trivially a contradiction because it is P AND ... AND (NOT P) which can obviously never be true for any value of P.

@SEJPM Is it correct that any two non-top-level (and) expressions separated by a comma forms an or expression, so [ [], [P,Q] ] = [1,[P,Q]]=1?  Also, in case 4, I see the first and final terms merely have the order inside them reversed, and to my understanding these operations are symmetric, so I don't get how one is P and the other is !P.

@busukxuan the outer-most list is a big AND-conjunction. The next-inner layer is a big OR-disjunktion and the two lists inside this are the positive (non-negated) and the negative (negated) variables. So [[[],[P]]]=!P and everything is commutative except for the two innermost lists, of which the order is used to convey the state of the literals.

Funny how shorter code actually requires more effort to be written.

Mathematica, 12 bytes
SatisfiableQ

Well, there's a built-in...
Input format is And[Or[a, b, Not[c], Not[d]], Or[...], ...]. This does work correctly for empty sub-expressions, because Or[] is False and And[] is True.
For the record, a solution which receives the list-based format from the challenge and does the conversion itself is 44 bytes, but the OP clarified in a comment that any format is fine as long as it doesn't encode any additional information:
SatisfiableQ[Or@@Join[#,Not/@#2]&@@@And@@#]&

Because Mathematica...

Mathematica really have a insane number of builtin ._.

@TùxCräftîñg Indeed.

For split-second, I thought this answer was written in an obscure, stacked-based esolang where, by mere chance, the command sequence S a t i s f i a b l e Q would solve the problem. Only then, reading comprehension knocked on the door...

Haskell, 203 200 bytes
t=1<3
e%((t,f):r)=or((e<$>t)++map(not.e)f)&&e%r
e%_=t
u v b e s|s==v=b|t=e s
s e[]c=1<0
s e(v:w)c=e%c||s(u v t e)w c||s(u v(1<0)e)w c
g v[]=v
g v((t,f):r)=g(v++[x|x<-t++f,notElem x v])r
g[]>>=s(\x->t)

This challenge deserves a no-build-in answer, so here you go. Try it on ideone. The algorithm simply tries all variable assignments and checks whether one of them satisfies the formula.
Input is in the form of [([],["P","Q"]),(["Q","P"],[]),(["P"],["Q"]),(["Q"],["P"])], although instead of strings every type with equality will work.
Ungolfed code:
type Variable   = String
type CNF        = [([Variable], [Variable])]
type Evaluation = (Variable -> Bool)

satisfies :: Evaluation -> CNF -> Bool
satisfies eval [] = True
satisfies eval ((t,f):r) = or(map eval t ++ map (not.eval) f) && satisfies eval r

update :: Evaluation -> Variable -> Bool -> Evaluation
update eval s b var = if var == s then b else eval var

search :: Evaluation -> [Variable] -> CNF -> Bool
search eval [] cnf = False
search eval (v:vars) cnf = satisfies eval cnf || search (update eval v True) vars cnf || search (update eval v False) vars cnf

getVars :: CNF -> [Variable] -> [Variable]
getVars [] vars = vars
getVars ((t,f):cnf) vars = getVars cnf (vars ++ [v |v<-(t++f), notElem v vars])

isSat :: CNF -> Bool
isSat cnf = search (\x->True) (getVars cnf []) cnf

JavaScript 6, 69B
x=>f=(v,e)=>(e=v.pop())?[0,1].some(t=>f([...v],eval(e+'=t'))):eval(x)

Usage:
f('a|b')(['a','b'])
true


text:
Reverse and subtract
Challenge description
Let's take a positive integer n, reverse its digits to get rev(n) and get the absolute value of the difference of these two numbers: |n - rev(n)| (or abs(n - rev(n))).
Example:
n = 5067
rev(n) = 7605
|n - rev(n)| = |5067 - 7605| = |-2538| = 2538

After repeating this operation sufficiently many times, most numbers will become 0 (thus terminating the loop)...
5067 -> 2538 -> 5814 -> 1629 -> 7632 -> 5265 -> 360 -> 297 -> 495 -> 99 -> 0

...though some numbers (like 1584) get stuck in an infinite loop:
1584 -> 3267 -> 4356 -> 2178 -> 6534 -> 2178 -> 6534 -> 2178 -> 6534 -> ...
                        ^ infinite loop starts here

Your job is to determine if a given integer gets stuck in an infinite loop.
Input description
A positive integer.
Output description
A truthy value (True, 1) if the number gets stuck in an infinite loop, a falsy value (False, 0) otherwise.
Notes

Trailing zeroes should be ommited. i.e. rev(5020) = 205.
Remember that this is code-golf, so make your code as short as possible!
Relevant sequence: A072140

Related. Related.

An interesting note: it is possible to construct an arbitrarily long integer with a looping period of 2, as described in the comments on A072141. The method is identical for other periods as well, like 12, 14, 17, and 22.

Pyth, 5 bytes
4 bytes thanks to FryAmTheEggman
uas_`

Test suite.
The truthy value is one of the numbers in the loop.
The falsey value is 0.
Explanation
uas_`      Input:Q
uas_`GGQ   Implicit filling of variables.

u      Q   Set G as Q: do this repeatedly until result seen before: Set G as
 a             the absolute difference of
     G             G
    `              convert to string
   _               reverse
  s                convert to integer
      G        and G

Nice use of the auto-fill variables!

*abuse – – – – –

How does that work, for someone that does not know Pyth?

@Fatalize Done.

how is pyth so short yet still in ASCII range ._.

@Downgoat Because it is pyth.

Mathematica, 39 37 bytes
Nest[Abs[#-IntegerReverse@#]&,#,#]<1&

Simply applies the reverse/subtract transformation n times to the input n and then checks whether the result is 0. It can never take more than 10n steps to reach a loop, because the transformation cannot increase the number of digits, and there are less than 10n numbers with no more digits than n. See Dennis's proof for how to reduce this bound to n.

Jelly, 6 5 bytes
ṚḌạµ¡

Try it online!
Background
This uses @MartinEnder's upper bound of 10n iterations and the following observations.

There are 9 × 10k - 1 positive integers n with k digits.
The difference of a number and its reverse is always a multiple of 9, so only 10k - 1 of them can occur after the first iteration.
Of the multiples, more than 1 / 10 will lose a digit in the next iteration (for starters, all that start and end with the same digits, and roughly twice as many if the first digit is neither a 1 nor a 9), so it takes at most 9 × 10k - 2 to either enter a loop or lose a digit.
Applying the same reasoning to the eventual resulting integer of k - 1 digits and so on, it takes at most 9 × 10k - 2 + 9 × 10k - 2 + … ≤ 10k - 1 ≤ n iterations to enter a loop or reach 0.

How it works
ṚḌạµ¡  Main link. Argument: n

   µ¡  Iteratively apply the chain to the left n times.
Ṛ      Reverse n (casts to digits).
 Ḍ     Undecimal; convert from base 10 to integer.
  ạ    Take the absolute difference of the result and the argument.

Did Pyth beat Jelly?

Well, it's a tie.

These ain't no bytes.

@mik Please click the bytes link in the header.

Oracle SQL 11.2, 136 bytes
WITH v(n)AS(SELECT :1 FROM DUAL UNION ALL SELECT ABS(n-REVERSE(n||''))FROM v WHERE n>0)CYCLE n SET c TO 0 DEFAULT 1 SELECT MIN(c)FROM v;

Un-golfed
WITH v(n) AS
(
  SELECT :1 FROM DUAL
  UNION ALL
  SELECT ABS(n-REVERSE(n||''))FROM v WHERE n>0
) CYCLE n SET c TO 0 DEFAULT 1
SELECT MIN(c)FROM v

APL, 26 chars
0∘{⍵∊⍺:×⍵⋄(⍺,⍵)∇|⍵-⍎⌽⍕⍵}

We use the left argument as the accumulator of the values we've seen already. We initialise it to "0", which is one of the two termination conditions.
The guard ⍵∊⍺:×⍵ is read: "is the right argument something we've seen already (and that includes zero)? If so return the sign of the number, that is 1 or 0". Otherwise let's recurse by calling ourselves with the absolute value of the subtraction after having catenated the current value to the left argument.

A recast of the Mathematica solution by Martin Ender would clock at 21 chars:
 {×{|⍵-⍎⌽⍕⍵}⍣(10×⍵)⊣⍵}

It reads: "what is the sign of the result after applying the wanted 10n times"?

CJam, 15 13 bytes
ri_{_sW%i-z}*

Test it here.
Same as my Mathematica answer.

Python 2, 50 bytes
n=input()
exec'n=abs(n-int(`n`[::-1]));'*n
print n

Test it on Ideone.
Background
This uses @MartinEnder's upper bound of 10n iterations and the following observations.

There are 9 × 10k - 1 positive integers n with k digits.
The difference of a number and its reverse is always a multiple of 9, so only 10k - 1 of them can occur after the first iteration.
Of the multiples, more than 1 / 10 will lose a digit in the next iteration (for starters, all that start and end with the same digits, and roughly twice as many if the first digit is neither a 1 nor a 9), so it takes at most 9 × 10k - 2 to either enter a loop or lose a digit.
Applying the same reasoning to the eventual resulting integer of k - 1 digits and so on, it takes at most 9 × 10k - 2 + 9 × 10k - 2 + … ≤ 10k - 1 ≤ n iterations to enter a loop or reach 0.

Python, 129 120 96 bytes
If a exception is caught (normally the only exception that can be throwed with this function is a RuntimeError, due to the infinite recursion), print 1. Otherwise, print the result, 0.
def r(n):a=abs(n-int(str(n)[::-1]));return a and r(a)
try:print(r(int(input())))
except:print(1)

Thanks to @LeakyNun
Thanks to @shooqie

That's officially a (nice) abuse of infinite recursion.

return a and rev(a)

Isn't it possible to get a RuntimeError due to the recursion being very long without it being necessarily infinite?

a=[n-x,x-n][n>x]

You can shorten it drastically: def rev(n):a=abs(n-int(str(n)[::-1]));return a and rev(a). Also, name the method something short (like r instead of rev)

@shooqie I have forgotten that abs is built-in ._.

Python, 101 98 bytes
Tortoise and hare algorithm.
Truthy is any value in loop, falsey is 0.
g=lambda n:abs(n-int(str(n)[::-1]))
def r(n):
    t=g(n);h=g(t)
    while t-h:h=g(g(h));t=g(t)
    return h

Ideone it!

Python 2, 85 84 83 bytes
L=[]
def f(n,L=L):
    if n<1or n in L:print n<1
    else:L+=[n];f(abs(n-int(`n`[::-1])))

Another Python answer. It adds n to a list for every iteration, and if n is already in the list, it outputs False. Otherwise, it works down to 0.
Thanks @NonlinearFruit for one byte.

I believe print n<1 works (since n is always non-negative) and it saves a byte

def f(n,L=[]):¶ if n<1or n in L:print n<1¶ else:f(abs(n-int(\n`[::-1])),L+[n])` saves 5 bytes

05AB1E, 11 8 6 bytes
DFÂï-Ä

Explained
DF          # input number of times do
  Â         # push current number and its reverse
   ï-       # convert reverse to int and subtract
     Ä      # absolute value
            # implicitly print after loop ends

Truthy value is a number from the loop.
Falsy value is 0.
Try it online
Uses the upper bound explained in Dennis' Jelly answer
Saved 2 bytes thanks to @Adnan
In version 7.9 of 05AB1E the following 5-byte solutions works as noted by @Adnan
DFÂ-Ä

Okay, this is a bit of a weird golf but DFÂ-Ä works in version 7.9 but not in the current version. In the current version, you need to convert it to an int first (like this DFÂï-Ä), but you can use version 7.9 to make it 5 bytes :p.

@Adnan I can't believe I forgot about the bifurcation function. I'll stick to the current version though. You could post the 7.9 one as a separate answer if you'd like. Otherwise I'll put it as a note.

I probably won't post it, since it's just 1 byte away from this answer :p.

Brachylog, 49 32 23 bytes
:10*N,?:N:{r:?-+.}itT'0

Returns true for infinite loops and false otherwise.
This is a shameless adaptation of Martin Ender's algorithm.
Previous answer, 32 bytes
g{tTr:T-+U(0!\;?:ImU;?:[U]c:1&)}

Explanation of the previous answer
g{                             } Call predicate with [Input] as input
  tT                             T is the last element of Input
    r:T-                         Subtract T from the reverse of T
        +U                       U is the absolute value of T
          (0!\                   If U is 0, return false
              ;                  Or
               ?:ImU             If U is in Input, return true
                    ;            Or
                     ?:[U]c:1&)  Recursive call with U concatenated to the Input

Java 7, 161 bytes
This requires an import but I wrote it as a function. Yell at me in the comments if a full program is preferred in this scenario. Outputs 1 if there's an infinite loop and 0 if the value gets to 0.
import java.util.*;int z(int a){int o,r,c=a;Set s=new HashSet();while(c!=0){for(r=0,o=c;o!=0;r=r*10+o%10,o/=10);c=Math.abs(c-r);if(!s.add(c))return 1;}return 0;}

Noting that I've seen imports and functions done before. example

Is 1 truthy ?

@LeakyNun 1 isn't considered truthy in java but OP lists (True,1) and (False,0) as acceptable outputs.

@LeakyNun Does Java even have a sense of truthy or falsy?

@Neil Java has a sense of leveraging synergistic opportunities in vertical market contexts -- that's it

Matlab, 89 84 bytes
n=input('');z=n;while n
z=abs(z-str2num(fliplr(num2str(z))));n=[n z]*all(n~=z);end
z

Simple approach - stacks all numbers and checks if a number appeared before.
Explanation
n=input('');z=n;  -- take input, initiate z
while n           -- n is said to be positive
z=abs(z-str2num(fliplr(num2str(z)))) -- calculate the "reverse and substract"
n=[n z]           -- put the value at the end of the vector
       *all(n~=z) -- make the n all zeroes if z is previously in the vector (break the loop)
end
z                 -- print z (0 when not entered loop, >0 otherwise)

PowerShell v2+, 94 bytes
param($n)for($a=,0;){if(($n=[math]::Abs($n-(-join"$n"["$n".length..0])))-in$a){$n;exit}$a+=$n}

Takes input $n, starts an infinite for loop, with $a=,0 as the initial condition (this uses the comma operator to set $a to an array of one element, 0). This $a is our array of already-seen values.
Each loop iteration we check an if. The condition first sets the next value of $n using string-reversing and the [math]::Abs .NET call, and checks whether that value is already -in $a. If so, we output $n and exit. Otherwise, we add that value to the array and continue the loop.
Outputs 0 for input values where it does not go into an infinite loop (which is falsey in PowerShell) and outputs the value where the loop was encountered otherwise (non-zero integers are truthy). For example, outputs 2178 for input 1584.

Haskell, 65 bytes
_#0=0
a#n|elem n a=1|1<2=(n:a)#abs(n-(read$reverse$show n))
([]#)

Returns 0 for False and 1 for True. Usage example: ([]#) 1584 -> 1.
The obvious approach: keep a list with all results seen so far. Calculate the next number until 0 or it's in the list.

JavaScript (ES6), 75 bytes
f=(n,...a)=>a.includes(n=n<0?-n:n)?n:f([...n+``].reverse().join``-n,n,...a)

n<0?n=-n:n and n*=n>0||-1 also work. Algorithm somewhat resembles the PowerShell answer, although this is a recursive formulation.

Ruby, 57 bytes
->n,*h{h[n]=n=(n-"#{n}".reverse.to_i).abs until h[n];n>0}

The initially empty array h tracks previously hit values. We iterate the number until we hit a previous value, then check the value on the last iteration. Since 0 is a cycle of 1, it'll be 0 if and only if there's no larger cycle. I take an extra 2 bytes to convert this to a Boolean because 0 is truthy in Ruby.

Perl 6  58 53 33  30 bytes
sub {$/=%;$^a,{return ?1 if $/{$_}++;abs $_-.flip}...0;?0}
{$/=%;?($_,{last if $/{$_}++;abs $_-.flip}...0)[*-1]}
{?($_,{abs $_-.flip}...0)[10**$_]}

{?($_,{abs $_-.flip}...0)[$_]}
Explanation:
{ # block lambda with implicit parameter $_

  # coerce the following to Bool
  # ( False for Nil or 0, True otherwise )
  ?

  (

    $_, # start a sequence with the input

    # block lambda with implicit parameter $_
    # subtracts the previous value in the sequence and its reverse
    # ( .flip is short for $_.flip where a term is expected )
    { abs $_ - .flip }

    ... # repeat that lambda
    0   # until you get 0

  # get the element indexed with the block's input
  # may be 0, Nil, or a number that is part of a repeating sequence
  )[ $_ ]
}

( relies on the previous observation that you only need to do this transformation at most n times )

Perl 5 -p, 25 bytes
eval'$_=abs$_-reverse'x$_

Try it online!
It iterates n=|n-rev(n)| n times, so output is 0 if there is no loop, >0 otherwise. Dennis already proved this is enough.

Nice answer, and welcome to PPCG! Note that for Perl, command-line options must be included in your byte-count, so this isn't quite 30 bytes.

@TimmyD ok, +1 for -p option, -l is not necessary for a single input

changed according to new flag rules

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Convert an Expression to Panfix Notation
I was browsing esolangs, and chanced upon this language: https://github.com/catseye/Quylthulg.
One interesting thing about this language, is that it doesn't use prefix, postfix, or infix, it uses all three of them, calling it "panfix" notation.
Here is an example. To represent normal infix 1+2 in panfix, it becomes: +1+2+. Notice how the operator is both before, in between, and after the operands. Another example is (1+2)*3. This becomes *+1+2+*3*. Notice again how * is in all three places with respect to the operands +1+2+ and 3.
The Challenge
As you may have guessed, your task in this challenge is to convert an expression from infix to panfix.
A few clarifications:

You only have to deal with the four basic operations: +-*/
You won't have to deal with the unary versions of those, only binary
You have to deal with parenthesis
Assume the normal precedence rules of */ then +- and left associativity for all of them.
The numbers will be nonnegative integers
You can optionally have a spaces in both the input and output

Test Cases
1+2  ->  +1+2+
1+2+3  ->  ++1+2++3+
(1+2)*3  ->  *+1+2+*3*
10/2*5  ->  */10/2/*5*
(5+3)*((9+18)/4-1)  ->  *+5+3+*-/+9+18+/4/-1-*

This is code-golf, so shortest code in bytes wins!

JavaScript (ES6), 160 bytes
f=(s,t=s.replace(/[*-/]/g,"'$&'"),u=t.replace(/^(.*?)([*-9]+)'([*/])'([*-9]+)|([*-9]+)'([+-])'([*-9]+)|\(([*-9]+)\)/,"$1$3$2$3$4$3$6$5$6$7$6$8"))=>t==u?t:f(s,u)

Works by quoting all the operators (which gives them character codes before *), then looking for available '*' or '/' operations, '+' or '-' operations or ()s, and replacing the first with its panfix notation. Example:
(5+3)*((9+18)/4-1)
(5'+'3)'*'((9'+'18)'/'4'-'1)
(+5+3+)'*'((9'+'18)'/'4'-'1)
+5+3+'*'((9'+'18)'/'4'-'1)
+5+3+'*'((+9+18+)'/'4'-'1)
+5+3+'*'(+9+18+'/'4'-'1)
+5+3+'*'(/+9+18+/4/'-'1)
+5+3+'*'(-/+9+18+/4/-1-)
+5+3+'*'-/+9+18+/4/-1-
*+5+3+*-/+9+18+/4/-1-*

JavaScript (ES6), 285 282 281 267 251 243 241 238 234 232 231 bytes
~15 bytes thanks to Neil.
f=(I,E=I.match(/\d+|./g),i=0)=>(J=T=>T.map?T.map(J).join``:T)((R=(H,l=(P=_=>(t=E[i++])<")"?R(0):t)(),C,F)=>{for(;(C=P())>")"&&(q=C>"*"&&C<"/")*H-1;)F=q+H?l=[C,l,C,P(),C]:F?l[3]=[C,l[3],C,R(1),C]:l=R(1,l,i--)
i-=C>")"
return l})(0))

In JavaScript this is a bit harder than in Mathematica. This is basically an over-specialized and golfed operator-precedence parser.
Causes stack overflows on invalid inputs.
Demo

f=(I,E=I.match(/\d+|./g),i=0)=>(J=T=>T.map?T.map(J).join``:T)((R=(H,l=(P=_=>(t=E[i++])<")"?R(0):t)(),C,F)=>{for(;(C=P())>")"&&(q=C>"*"&&C<"/")*H-1;)F=q+H?l=[C,l,C,P(),C]:F?l[3]=[C,l[3],C,R(1),C]:l=R(1,l,i--)
i-=C>")"
return l})(0))
<input id="input" value="(5+3)*((9+18)/4-1)"/><button onclick="console.log(f(document.querySelector('#input').value))">Convert</button>

Ungolfed
convert = input => {
  tokens = input.match(/\d+|./g);
  i = 0;
  parse_token = () => (token = tokens[i++]) == "(" ? parse_tree(false) : token;
  parse_tree = (mul_div_mode, left = parse_token()) => {
    while ((oper = parse_token()) != ")" && !((is_plus_minus = oper == "+" || oper == "-") && mul_div_mode)) {
      if (is_plus_minus || mul_div_mode)
        left = [oper, left, oper, parse_token(), oper];
      else if (non_first)
        left[3] = [oper, left[3], oper, parse_tree(true), oper];
      else
        left = parse_tree(true, left, i--);
      non_first = true;
    }
    if (oper != ")")
      i--;
    return left;
  };
  format_tree = tree => tree.map ? tree.map(format_tree).join("") : tree;
  return format_tree(parse_tree(false));
}

S.split\`should be[...S], although it may actually help to match on /\d+|./g` up-front and work on that instead.

@Neil Thanks. I'll look into that.

Mathematica, 203 195 bytes
This is likely less than efficient, but seems to do the job.
Function[f,ReleaseHold[(Inactivate@f/._[Plus][a_,b_/;b<0]:>a~"-"~-b//Activate@*Hold)//.a_/b_:>a~"/"~b/.{a_Integer:>ToString@a,Plus:>"+",Times:>"*"}]//.a_String~b_~c_String:>b<>a<>b<>c<>b,HoldAll]

This is an anonymous function that takes an actual expression and returns a string with panfix notation. Mathematica sorts out the precedence of operators at parsing time, rather than evaluation time, so the nesting should be automagically correct. At least the test cases work as expected.
Explanation: It's easy enough to interpret the entire expression as a tree, like so:

At this stage the operators (every node that isn't a leaf) aren't operators any more, they've actually been converted to strings such as "+". The integers are also cast to strings. Then a repeated replacement rule converts every node that has exactly two leafs to the panfix parent-leaf1-parent-leaf2-parent. After some iterations the tree reduces to a single string.
The main loss in the byte count is that Mathematica interprets
5 - 4 -> 5 + (-4)
9 / 3 -> 9 * (3^(-1))

And this happens also at parsing time.
Golfed down a bit, since the pattern a_/b_ is also interpreted as a_ * (b_)^(-1). Also some minor optimizations elsewhere.

Prolog, 87 bytes
x(T)-->{T=..[O,A,B]}->[O],x(A),[O],x(B),[O];[T].
p:-read(T),x(T,L,[]),maplist(write,L).

This is a function (mostly because writing a full program has nightmarish levels of boilerplate in Prolog; normally, even if you compile a program, it produces a REPL when run), called p. It takes input from stdin and outputs on stdout. Note that you need to append a period to the input, which is an unfortunate consequence of the way that Prolog's input routines work (they use periods in the input in much the same way that other languages use newlines); that might or might not disqualify the answer.
Explanation
Arithmetic operators, in Prolog, are normally interpreted as tuple constructors. However, they obey the same precedence rules as the actual arithmetic operators they're based on; you can form tuples with infix notation, and + and - bind less tightly than * and /, with precedence taken left to right within a group. This is exactly what the question asks for; thus, we can read an entire nested tuple from the input, and it already has the right structure. That's what p does.
Next, we need to convert it to panfix notation. x converts the input into a panfixed list of constructors and integers, and can be read as an English sentence almost directly: "x of T is: if T is a tuple with constructor O and arguments A,B, then O, x of A, O, x of B, O, else T". Finally, we just have to print the list without any separators (i.e. using maplist to call write on each element of the list).
I used SWI-Prolog for testing this, because my version of GNU Prolog doesn't have maplist yet (apparently it's been added to a newer version), but it should generally be fairly portable between Prolog implementations.

Tamsin, 118 bytes
main=1->R&{("+"|"-")->O&1->E&R<-O+R+O+E+O}&R.1=2->R&{("*"|"/")->O&2->E&R<-O+R+O+E+O}&R.2="("&main->R&")"&R|$:alnum/''.

Try it online!
# implements +, - over expr1       # `main` is  (entrypoint)
main = expr1 -> R                  #   `expr1` (store in R)
      & {                          #   followed by zero or more:
        ("+" | "-") -> O           #     "+" or "-" (store in O)
        & expr1 -> E               #     `expr1` (store in E)
        & R <- O + R + O + E + O   #     R = O + R + O + E + O (i.e. to panfix)
      } & R.                       #   return R

# implements *, / over expr2; does the same thing as expr1 but we need seperate rule for operator precedence
expr1 = expr2 -> R
      & {
        ("*" | "/") -> O
        & expr2 -> E
        & R <- O + R + O + E + O
      } & R.

# implements parenthesis and numbers # `expr2` is
expr2 = "(" & main -> R & ")" & R    #   "(" followed by `main` followed by ")" (return match from `main`)
      | $:alnum/''.                  #   or zero or more alphanumeric char

# sed 's/expr\|#.*//g' panfix.tamsin | tr -d ' \n' | wl-copy

Fun Fact: Tamsin was designed by Chris Pressey, the same person who made Quylthulg (the language in the question)