I am passive aggressive and want to insult my boss without him finding out

93

19

It's been a rough few months at work and I feel like I just want to scream right to my boss' face. I am, however, not one to directly confront people I have a problem with. I also don't want to lose my job.

So here's an idea: I want to be able to insult him, without him ever finding out. And I realized the perfect way: I need some sort of software that encodes an insult inside an otherwise perfectly fine message. And seeing as how he's known to not see forests for trees, I think I know just how:

Write me a program that takes as input a string of unknown length, but containing no line breaks. This will be the raw message I want to send.

If possible, return the string formatted such that the message "DIE IN A GREASE FIRE" makes up the entire left column. With new paragraphs where spaces in between words should go. Now, as I am very angry, it is equally important that every letter is in upper case.

You may not modify the string in any other way, i.e. you may not turn all of the string into upper case characters.

If the string in question cannot be formatted in this way, you are to return the original string. Read input from standard input.

Normal rules apply: No HTTP requests, no consulting Marvin from THGTTG, etc.

Example input:

Dear Boss, how are things? It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it. Every last bit of it. Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go. Not that I think I should stand without blame. Not at all. All I'm saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility. Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve. Remember the Flakenhauser contract? Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart. All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources. Still, I - alone - took blame for it. Even though I said nothing then, my tolerance level for taking the blame took a serious dent then. From that point on, I have felt it necessary to always try twice as hard, just to escape scrutiny. And still, here we are again. In spite of all my accomplishments. Right where we always seem to end up these days. Every single project. It's becoming unbearable.

Example output:

Dear Boss, how are things?
It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it.
Every last bit of it.

Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go.
Not that I think I should stand without blame. Not at all.

All I'm saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility.

Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve.
Remember the Flakenhauser contract.
Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart.
All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources.
Still, I - alone - took blame for it.
Even though I said nothing then, my tolerance level for taking the blame took a serious dent then.

From that point on, I have felt it necessary to always try twice as hard, just to escape scrutiny. And still, here we are again.
In spite of all my accomplishments.
Right where we always seem to end up these days.
Every single project. It's becoming unbearable.

This is code golf. Shortest code wins.

Christofer Ohlsson

Posted 2014-06-19T09:24:47.530

Reputation: 1 014

Can we assume that there will be no control characters at all in the string? – Titus – 2016-12-20T01:23:55.597

4Do the line breaks have to occur only after sentence-ending punctuation? Or could I have a line break, before some proper now or maybe even within an abbreviation, as long as the following letter is upper case? That being said, insult-related challenges didn't fare well here in the past, but you might be able to get away, because you didn't ask for the participants' creativity in coming up with new obscenities. – Martin Ender – 2014-06-19T09:43:18.403

1Line breaking before proper nouns is perfectly fine. – Christofer Ohlsson – 2014-06-19T09:46:41.753

Just to make sure, does that line break apply also to new paragraphs (for a space in the hidden sentence)? Could that I in the word IN come from the middle of a sentence? – Tal – 2014-06-19T09:48:13.767

The I in IN can come from the middle of a sentence, as long as the I was in upper case in the original input. – Christofer Ohlsson – 2014-06-19T09:53:33.527

I really hope that your boss is as incapable of "seeing the forest through the trees" as you say, because that insult is not that well hidden. – Nzall – 2014-06-19T10:08:44.620

3@NateKerkhofs I think it's backwards: since the secret message is just a few characters in an entire message, I think that the insult is the trees, and the message is the forest. We really hope that the boss sees the forest, not the trees. – Joshua Taylor – 2014-06-19T16:40:39.013

11

Was Arnold Schwarzenegger's letter your inspiration?

– 200_success – 2014-06-19T19:46:16.640

Can we break words? For example, could "FIFA" be used for its "I"? – Dennis – 2014-06-19T22:23:50.777

@Dennis No. This is part of what I meant by not modifying the original string in any other way. – Christofer Ohlsson – 2014-06-20T05:59:11.013

@200_success good old Arnie did spring to mind! – Christofer Ohlsson – 2014-06-20T05:59:38.313

57I must admit I did a bit of a double-take when I saw this in the Hot Questions list. When I saw it was PCG and not The Workplace...well...I won't say I wasn't a little disappointed. – BenM – 2014-06-20T07:21:47.920

@ChristoferOlsson: I initially interpreted your question that way, but it only says "format", not how, and at least one other answer interpreted it differently. Thanks for clearing that up.

– Dennis – 2014-06-20T16:53:15.197

@Dennis: I did ponder these things somewhat before posting, but it seems I didn't do that enough. A lesson for future golfing questions I might ask. – Christofer Ohlsson – 2014-06-21T08:57:17.763

Answers

54

CJam, 56 53 bytes

q_"DIEIINAAGGREASEFFIRE"{S@:A+S@+#:BA<AB>}%(!B)*\N*@?

Try it online!

How it works

q_                     Read all input from STDIN and push a copy.
"DIEIINAAGGREASEFFIRE" Push the characters we're searching for in form of a
                       string. We'll try to prepend a linefeed to all of them.
                       Some characters are duplicated to prepend two linefeeds.
{                      For every character C in that string:
  S@                   Push ' ' and rotate the string on the stack on top of it.
  :A                   Save the string (initially the input) in A.
  +                    Prepend the space to A.
  S@+                  Construct the string " C".
  #                    Compute the index of " C" in the modified A.
  :B                   Save the index in the variable B.
  A<                   Push the substring of A up to the index.
  AB>                  Push the substring of A after the index.
}%
(                      Shift the first element of the resulting array.
!                      Compute the logical NOT. This pushes 1 if and only if the
                       array's first element is an empty string, which is true
                       if and only if the input string started with a D.
B)                     Push the last value of B and increment. If the last match
                       was successful and, therefore, all matches were successful,
                       B != -1, so B + 1 != 0.
*                      Compute the product of the two topmost items on the stack.
\                      Swap the resulting Booleanr with the array of substrings.
N*                     Join the array, separating by linefeeds.
@                      Rotate the input string on top of the stack.
?                      Select the joined array if the Boolean is 1 and the input
                       string otherwise.

Dennis

Posted 2014-06-19T09:24:47.530

Reputation: 196 637

14Why do I find myself upvoting so many of your answers? Oh yeah, because they're crazy. – primo – 2014-06-19T18:17:02.970

What does it do to input that contains VERY ANGRY words in ALL CAPS? – Adam Davis – 2014-06-20T17:43:16.900

2@AdamDavis: Prepending spaces to “C” and “A” makes sure that WORDS won't be broken by linefeeds. – Dennis – 2014-06-20T17:48:31.307

25

Perl - 60 bytes

#!perl -p
$_=(join$/,$_=~('DIE\IN\A\GREASE\FIRE'=~s/./($&.*)/gr))||$_

Counting the shebang as one.

This solution uses the innermost string to build up the following regex:

(D.*)(I.*)(E.*)(\.*)(I.*)(N.*)(\.*)(A.*)(\.*)(G.*)(R.*)(E.*)(A.*)(S.*)(E.*)(\.*)(F.*)(I.*)(R.*)(E.*)

which is similar to the regex used in m.buettner's solution. The generated regex is then matched against the input. In a list context, this will return an array containing each of the match groups, which are joined together by a newline (the reason for the 'match nothing' groups (\.*), is to insert an additional newline). If there is no match, the original string is output instead.


Perl - 73 bytes

#!perl -pl
$s=$_}for(map$s!~s/.*?(?=$_)//?$\='':$&,'DIEI.NA.G.REASEF.IRE$'=~/./g){

Counting the shebang as two.

This splits up the string at the appropriate delimiters, and collects the pieces in an array. If any of them fail to match, the output record separator (which was set to a newline with the -l option) is unset, and so the string is output unmodified.

primo

Posted 2014-06-19T09:24:47.530

Reputation: 30 891

Doesn't the shebang need an absolute path? – celtschk – 2014-06-19T12:51:26.750

why the dots (DIEI.NA. ...? – edc65 – 2014-06-19T13:17:51.473

@celtschk Maybe, depending on your system, and how you intend to invoke the script. Invoked as ./script.pl, then most likely yes. If invoked as perl script.pl, then no. – primo – 2014-06-19T13:23:40.857

1@edc65 The . after I will insert an additional newline before I (because it matches again at the same position). Perhaps a bit counter-intuitive. – primo – 2014-06-19T13:25:32.867

But if you invoke as perl script.pl, then shouldn't the shebang line be completely ignored (since for Perl, it's a comment)? I just tested with #!perl --invalid and got no error (while --invalid as option on the command line gives an error). – celtschk – 2014-06-19T18:50:20.513

2@celtschk The switches on the shebang will still be interpreted. You can test this by adding the -M option to the shebang, which will die with the fatal error: Too late for "-M" option at line 1. But the main reason I put it there, I too avoid needing to explain that it needs to be run as perl -pl script.pl - in its current form, it runs as-is. – primo – 2014-06-19T19:10:33.823

Ah, interesting. I wonder why it didn't error out on --invalid, then ... (it also seems to interpret the executable name; using just p instead of perl gives Can't exec p at test3.pl line 1.) – celtschk – 2014-06-19T19:43:23.897

12

GolfScript, 53 bytes

Looks like Dennis and I came up with pretty similar things in parallel... But here's my attempt.

Click on the links before each code block to try it online. Unfortunately, the online interpreter won't allow you to run code larger than 1024 characters, so I had to perform some... "compression" of the test input. But it does still work.

Squished version

..(\;68=(>"IEIINAAGGREASEFFIRE"{1$.@?:^<n@^>}/](]^0<=

Unsquished, commented version

.       # (Save input)
.(\;    # Get first character
68=(>   # If 'D', work with input; else, work with one-character string
"IEIINAAGGREASEFFIRE"
{       # For each character
 1$.@   # (Duplicate message twice)
 ?:^    # Find first index of character
 <n     # Extract part before index and add a newline
 @^>    # Extract part including and after index as new "message"
}/      # (Close loop)
](]^0<= # If last line was successfully matched, select result; else, select input

A point raised by Dennis: All GolfScript programs print an automatic final newline. Whether or not this should invalidate my solution as-is, I'm not sure. I believe it would cost 4 characters to suppress the final newline by adding "":n somewhere near the end.

Runer112

Posted 2014-06-19T09:24:47.530

Reputation: 3 636

1You don't seem to check if the character is the first character of a word. For example. "FIFA" should only be used for F, not for "I" or "A". – Dennis – 2014-06-19T22:08:31.900

@Dennis I didn't see any part of the specification that requires that. But if you imposed that restriction on yourself, lifting that from your solution seems like it would solidify its superior golfed-ness. – Runer112 – 2014-06-19T22:18:45.323

1This is how m.buettner and I interpreted the question (I'd have to take a closer look at the other answers), but you're right, it doesn't say anywhere that we cannot break words. – Dennis – 2014-06-19T22:22:47.730

7

Perl, 184 bytes

Not a spectacular score for Perl, but here is a simple regex solution

$_=<>;s/^(D.*) (I.*) (E.*) (I.*) (N.*) (A.*) (G.*) (R.*) (E.*) (A.*) (S.*) (E.*) (F.*) (I.*) (R.*) E/$1\n$2\n$3\n\n$4\n$5\n\n$6\n\n$7\n$8\n$9\n$10\n$11\n$12\n\n$13\n$14\n$15\nE/;print;

Martin Ender

Posted 2014-06-19T09:24:47.530

Reputation: 184 808

3Surely it's possible to build the regex in code and save a ton? – Peter Taylor – 2014-06-19T09:57:33.027

@PeterTaylor certainly, but I neither have the time nor Perl knowledge to do that right now. I might have a look later today. – Martin Ender – 2014-06-19T09:59:01.397

Even so it beats my PERL answer, which I won't bother posting now :p – Tal – 2014-06-19T10:40:28.760

Save 4 chars: print($_) == print. +1 point for readability: It is remarkably easy to see what is going on which is not exactly the case for other solutions. – Ole Tange – 2014-06-19T21:00:03.353

This is considered simple in Perl? – Lincoln Bergeson – 2014-06-21T23:30:43.167

@LincolnBergeson I said "simple regex" ;) ... as far as regex solutions to code golf challenges go, this is fairly straight-forward. – Martin Ender – 2014-06-21T23:56:07.937

7

Ruby - 140

a="DIEINAGREASEFIRE";n=[4,6,7,13];i=0;o='';s=ARGV[0]
s.chars.each{|c|
if c==a[i]
i+=1;o+="\n";o+="\n"if n-[i]!=n
end
o<<c
}
puts((i<16)?s:o)

No regexes in this one. It simultaneously walks the characters in the ARGV[0] input, and a string containing characters we need to break on to make our left-column message. Was originally going to stick spaces after the letters that need to have a newline, but found that it was a bit shorter to hardcode the indexes at which to insert the line break.

Once all is said and done, it checks to see that the i index has incremented enough times to have gone through every letter that needed breaking. If it hasn't, we just print out the original string. If it has, we give 'em the formatted one.

n-[i]!=n was a neat trick to save characters when checking whether or not the current index was one that needed an extra line break (as compared to n.include? i). Also saved some characters by using {}s instead of do/end despite being a multiline block, and used a ternary condition on the final puts to save characters when determining which one to output.

Not the shortest, but I thought it would be neat to do without regular expressions.

KChaloux

Posted 2014-06-19T09:24:47.530

Reputation: 579

6

JavaScript 116

Javascript implementation of m-buettner's idea

console.log((RegExp('^('+[...'DIE IN A GREASE FIRE$'].join('.*)(')+')').exec(z=prompt())||[,z]).slice(1).join('\n'))

Test snippet

z="Dear Boss, how are things? It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it. Every last bit of it. Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go. Not that I think I should stand without blame. Not at all. All I'm saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility. Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve. Remember the Flakenhauser contract? Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart. All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources. Still, I - alone - took blame for it. Even though I said nothing then, my tolerance level for taking the blame took a serious dent then. From that point on, I have felt it necessary to always try twice as hard, just to escape scrutiny. And still, here we are again. In spite of all my accomplishments. Right where we always seem to end up these days. Every single project. It's becoming unbearable.";

T1.textContent = (RegExp('^('+[...'DIE IN A GREASE FIRE$'].join('.*)(')+')').exec(z)|| [,z]).slice(1).join('\n')

z='From that FIFA point on'
T2.textContent = (RegExp('^('+[...'DIE IN A GREASE FIRE$'].join('.*)(')+')').exec(z)|| [,z]).slice(1).join('\n')
pre { border: 1px solid black }
T1<pre id=T1></pre>
T2 (the FIFA test)<pre id=T2></pre>

edc65

Posted 2014-06-19T09:24:47.530

Reputation: 31 086

This fails on the FIFA test (OP comments) – Mwr247 – 2016-01-14T18:40:42.390

@Mwr247 hard to understand: what FIFA test did you try? – edc65 – 2016-01-14T18:45:49.010

Try the test string with the following edit: From that FIFA point on. It puts a new line before the FA, and before the space before FI. – Mwr247 – 2016-01-14T18:48:19.867

@Mwr247 not for me. Tested with Firefox, I get the same exact line, no newlines in it – edc65 – 2016-01-14T19:14:15.527

JavaScript it is. – Peter Mortensen – 2014-06-24T18:45:47.507

4

Python3 (166 138)

Golfed:

s='';o=input()
for n in o.split():s+=[n,'\n'+n.title()][n[0]==("DIEINAGREASEFIRE"*len(o))[s.count('\n')]]+' '
print([o,s][s.count('\n')==16])

Ungolfed-ish:

format_s = ''
unformat_s = input()
for n in unformat_s.split():
    format_s += [n, '\n' + n.title()][n[0] == ("DIEINAGREASEFIRE"*len(unformat_s))[format_s.count('\n')]] + ' '
print([unformat_s, format_s][format_s.count('\n') == 16])

Although the use of the lambda pleases me somewhat, that mass number of variables used and the somewhat messy development has the opposite effect. Regex may have been a good idea too. Hay ho, at least it works :).

Edit: replaced lambda variable with count builtin, and shortened split statement.

idiot.py

Posted 2014-06-19T09:24:47.530

Reputation: 161

1

PHP, 136 bytes

for($f=" ".join(file(F));$c=DIEINAGREASEFIRE[$i++];){while(($p=strpos($f,$c,$p))&&$f[$p-1]>" ");$p?$f[$p-1]="\n":$i=20;}echo$i<20?$f:"";

if the whole insult can be put; prints the modified string with a leading space or linebreak; empty output if not. Run with -r.

breakdown

for($f=" ".join(file(F));       // read input from file "F"
    $c=DIEINAGREASEFIRE[$i++];) // loop through insult characters:
{
    while(($p=strpos($f,$c,$p))     // find next position of $c
        &&$f[$p-1]>" ");            // ... preceded by a space
    $p?$f[$p-1]="\n"                // if found, replace the space with a newline
    :$i=20;                         // else break the loop
}
echo$i<20?$f                // if modified text has the full insult, print it
    :"";                    // else print nothing

Titus

Posted 2014-06-19T09:24:47.530

Reputation: 13 814

1

J - 110 103 bytes

Why doesn't J have good functions to handle strings, but only array functions? I'll revise this if I figure out something smart.

Edit: Shortened and fixed output (it had extra spaces before) and checking. I also improved the explanation.

f=:[:>,&.>/@('IEIINAAGGREASEFFIRE'&t=:(}.@[t{.@[(}:@],(((0{I.@E.)({.;LF;}.)])>@{:))])`]@.(0=#@[))@< ::]

Explanation:

I'll denote function usage as [<left argument>] <function name> <right argument>, e.g. f <text>. I also won't explain every detail because the function is quite long.

@ applies the right function to the left function, eg. f@g x == f(g(x))

t=:(}.@[t{.@[(}:@],(((0{I.@E.)({.;LF;}.)])>@{:))])']@.(0=#@[) is a recursive function <delimiters> t <boxed string> that splits the string with every delimiter, in order. Fails if some delimiter is not found.

(((0{I.@E.)({.;LF;}.)])>@{:) splits the string from the left side of the delimiter, adding a linefeed between them.

>@{: gets the last string from a list (the one which hasn't been split yet)

0{I.@E. gets the index to split at, failing if the delimiter doesn't exist.

{.;LF;}. concatenates left side of the split, linefeed and right side of the split

}:@], concatenates results of the earlier splits and the result of the last function (last meaning: look up)

']@.(0=#@[) checks if there's any delimiters left, and calls the function described above (5 lines) if there is. Otherwise returns.

'IEIINAAGGREASEFFIRE'& sets the left argument of t to that string

[:>,&.>/@ joins the results of splitting

::] if something fails (I made the search for the split index the weak point), return the original string.

Examples (too long?):

   f 'Dear Boss, how are things? It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it. Every last bit of it. Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go. Not that I think I should stand without blame. Not at all. All I''m saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility. Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve. Remember the Flakenhauser contract? Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart. All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources. Still, I - alone - took blame for it. Even though I said nothing then, my tolerance lev...
Dear Boss, how are things? 
It has come to my attention that I received all the blame for the mishap last Friday. Not just the majority of it. 
Every last bit of it. 

Is it wrong for me to think that the rest of the team were at least in part responsible? After all, all six of us were involved from the get-go. 
Not that I think I should stand without blame. Not at all. 

All I'm saying is this: I do my best. I try hard. I improve constantly. And I am constantly taking responsibility. 

Generally speaking, I am very okay with taking full responsibility for my actions. But after this spring, it seems I get more than I deserve. 
Remember the Flakenhauser contract? 
Everything went down just about as smooth as one could have hoped. Or so it seemed at first. It was just at the very last minute that things fell apart. 
All of the team agreed that it was more akin to a freak accident than sloppy planning or mismanaged resources. 
Still, I - alone - took blame for it. 
Even though I said nothing then, my tolerance level for taking the blame took a serious dent then. 

From that point on, 
I have felt it necessary to always try twice as hard, just to escape scrutiny. And still, here we are again. In spite of all my accomplishments. 
Right where we always seem to end up these days. 
Every single project. It's becoming unbearable.
   f 'Die in a grease fire. It''s fun. Every time.'
Die in a grease fire. It's fun. Every time.
   f 'hai'
hai

seequ

Posted 2014-06-19T09:24:47.530

Reputation: 1 714

1


Python3 (165)

def c(m,h,l=[]):
 if h:s=m.rindex(h[0]);l=[m[s:]]+l;return c(m[:s],h[1:],l)
 return[m]+l
i=input()
try:print('\n'.join(c(i,"ERIF ESAERG A NI EID")))
except:print(i)

Ungolfed

def headings_remaining(headings): return len(headings) > 0
def head(s): return s[0]
def tail(s): return s[1:]
def prepend(l,e): l.insert(0, e)
def reverse(s): return s[::-1]

def chunk(message,headings,output_list=[]):
    if headings_remaining(headings):
        split_index = message.rindex(head(headings))
        message_init = message[:split_index]
        message_last = message[split_index:]

        prepend(output_list, message_last)
        return chunk(message_init, tail(headings), output_list)
    else:
        prepend(output_list, message)
        return output_list

input_message=input()
try:
    headings=reverse("DIE IN A GREASE FIRE")
    print('\n'.join(chunk(input_message,headings)))
except ValueError: # Couldn't keep splitting chunks because didn't find heading
    print(input_message)

Explanation

chunk recursively splits off the end of the message containing the last heading and prepends it to a list.

Caveat: this won't work if there are no spaces at all between two proposed headings in your letter for some reason, but that seems unlikely in a letter to your boss.

Steven Liao

Posted 2014-06-19T09:24:47.530

Reputation: 111

1

Ruby 115

n,a,c,i=[4,6,7,13],gets,'',0;a.chars{|x|x=='DIEINAGREASEFIRE'[i]?(i+=1;c+="\n"if n-[i]!=n;c+="\n#{x}"):c+=x};puts c

Ruby 95

a,c,i=gets,"",0;a.chars{|x|x=="DIEINAGREASEFIRE"[i]?(i+=1;c+="\n#{x}"):(c+=x)};puts c

bjhaid

Posted 2014-06-19T09:24:47.530

Reputation: 111

1

JavaScript (ES6), 93 115 bytes

alert(prompt(x=[...'DIEI1NA1G1REASEF1IRE',i=0]).replace(/\b./g,a=>i<20&&a.match(x[i])?(+x[++i]?i++&&`

`:`
`)+a:a))

I used replace to step through the string, with a match for /\b./g so as to only find characters that either followed a space or began the string. Then I checked each character to see if it matched the current index in the array I was looking for, and added a newline before it if it did, and incremented i.

EDIT: Missed the need to create newlines between words. I've done that now, which brings it up to 115.

Mwr247

Posted 2014-06-19T09:24:47.530

Reputation: 3 494

1

PHP, 328 bytes

Given a file named 'G' containing the raw text to "enmessage"

<?php
$a=implode(file("G"));$b=str_split('DIEINAGREASEFIRE');foreach(array_unique($b) as $c){foreach(str_split($a) as $h=>$d){if($c==$d)$l[$c][]=$h;}}$e=-1;$n=$a;foreach($b as $f=>$c){foreach($l as $j=>$m){if($c==$j){foreach($m as $k=>$h){if($h>$e){$n=substr($n,0,$h)."\n".$c.substr($a,$h+1);$e=$h+2;break 2;}}}}}echo nl2br($n);

Explanation (~ungolfed && commented code) :

<?php
$string=implode(file("G"));          // raw text to deal with
$msg=str_split('DIEINAGREASEFIRE');  // hidden message (make it an array)

 // 2D array : [letters of the message][corresponding positions in txt]
foreach(array_unique($msg) as $letter) {
    foreach (str_split($string) as $pos=>$let) {
        if ($letter==$let) $l[$letter][]=$pos; //1 array per seeked letter with its positions in the string
    }
}

$currentPos=-1;
$newString=$string;
foreach ($msg as $key=>$letter) { // deal with each letter of the desired message to pass
    foreach($l as $cap=>$arrPos) {// search in letters list with their positions
        if($letter==$cap) {       // array of the current parsed letter of the message
            foreach($arrPos as $kk=>$pos) { // see every position
                if ($pos>$currentPos) {     // ok, use the letter at that position
                    $newString=substr($newString,0,$pos)."\n".$letter.substr($string,$pos+1); // add line break
                    $currentPos=$pos+2; // take new characters into account (\n)
                    break 2;            // parse next letter of the message
                }
            }
        }
    }
}                    /* (note that I could have added some other (random) line breaks management, so that
                      * the message is not TOO obvious... !*/
echo nl2br($newString);

St3an

Posted 2014-06-19T09:24:47.530

Reputation: 131

0

Python - 190 Bytes

l,r="IExINxAxGREASExFIRE","\n";k=p=raw_input();y=i=0
for c in l:
    if c!="x":
        h=len(p);x=p[y:h].find(c)
        if x==-1:i+=1
        p=p[0:x+y-1]+r+p[x+y:h];y=x+y;r="\n"
    else:r=r+r
if i!=0:p=k

Ungolfed

This is my first golf attempt :) Looking to learn some great coding techniques, regardless, I just focused on using find and then some string splicing to find the appropriate characters and format the output.

Variables -

l.r = l is assigned characters we will be using as our guide to create our new formatted paragraph. r is assigned the new line character for us in spacing the new output.

k,p = The input paragraph. K is used to revert to the original as it is not reassigned during execution of the script. I check against x to know when to add a double new line for spacing purposes.

y,i = y is a "cursor" of sorts, keeps track of the last position a character was found so we find through the paragraph correctly for splicing purposes, i is sanity check, if we don't hit all of our characters we revert the paragraph (p variable) to it's original input via the k variable.

h = Input length, which we use in splicing.

x = The position of the current character represented by C, used for splicing as well.

c = Characters in l to iterate and search for.

The following code is reworded and broken out from the original code for readability to as what is happening:

letters,return="IExINxAxGREASExFIRE","\n"
input1=input2=raw_input()
lastpos=sanity=0

for char in letters:
    if char != "x":
        inputlength=len(input1)
        charposition=input1[lastpos:inputlength].find(char)
        if charposition==-1:
            sanity+=1
        input1=input1[0:position+lastpos-1]+return+input1[position+lastpos:inputlength]
        lastpos=position+lastpos
        return="\n"
    else:return=return+return
if sanity!=0:
    input1=input2

I would appreciate your feedback! I am looking to learn.

0xhughes

Posted 2014-06-19T09:24:47.530

Reputation: 101

I offered an edit with some tricks in it. Just ask me if any of them needs an explanation. Note that it could be golfed further, by a lot, but I'll leave that down to you. :) – seequ – 2014-06-20T09:48:45.667

@TheRare Thanks! I really like the "i=+x<0" line you offered in your edit, as opposed to my "if x==-1:i+=1" line. Just to make sure i'm reading it right, this is one of the ternary things I was reading about last night, right? It basically reads, "if x is less than 0 (-1 returned when it cant find the char): add x to i" Correct? So it still satisfies the sanity check with a -1 or less for a value, right? Want to make sure I am reading that right, cause that is a great space saver! – 0xhughes – 2014-06-20T14:55:54.557

Actually it adds x<0 to i. In python True is the same as 1 and False is the same as 0. So if x is -1, it adds 1 and otherwise 0. i+= is the same as i=i+ – seequ – 2014-06-20T15:04:48.167

Try what True == 1 gives. :) – seequ – 2014-06-20T15:09:50.263