Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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.

share|improve this question
1  
Do 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 Büttner Jun 19 at 9:43
1  
Line breaking before proper nouns is perfectly fine. –  Christofer Olsson Jun 19 at 9:46
2  
@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 Jun 19 at 16:40
7  
Was Arnold Schwarzenegger's letter your inspiration? –  200_success Jun 19 at 19:46
37  
I 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 Jun 20 at 7:21

11 Answers 11

CJam, 56 bytes

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

Try it online.

How it works

" Read from STDIN, duplicate and save in variable “A”.                                  ";

q_:A

" 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.     ";

"DIEIINAAGGREASEFFIRE"

{      " For every character “C” in 'DIEIINAAGGREASEFFIRE':                             ";
  S\+  " Push the string ' C'.                                                          ";
  S@+  " Prepend a space to the string “A”.                                             ";
  \#:B " Push the index of ' C' in “A” and save it in variable “B”.                     ";
  A<   " Push the substring up to the index.                                            ";
  AB>  " Push the substring after the index.                                            ";
  :A   " Save the latter in variable “A”.                                               ";
}%     "                                                                                ";

" 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 original string started with a D.                                         ";

(!

" Add 1 to the last value of “B”. If the last match was successful (and, therefore,
  all matches were successful), B != -1, so B + 1 != 0.                                 ";

B)

" Compute the logical AND of the two topmost items on the stack. Since both are
  integers, multiplication will do as well.                                             ";

*

" Swap the integer with the array of substrings and join the latter using linefeeds.    ";

\N*

" Rotate the original string on top of the stack. If the integer is non-zero, discard 
  the original string. Otherwise, discard the modified string.                          ";

@?
share|improve this answer
4  
Why do I find myself upvoting so many of your answers? Oh yeah, because they're crazy. –  primo Jun 19 at 18:17
    
So it only works if the complete angry message is encoded in the input? –  MVCylon Jun 19 at 20:08
    
@MVCylon: It does as the question says. If the string in question cannot be formatted in this way, you are to return the original string. This is what (!B)*\N*@? accomplishes. –  Dennis Jun 19 at 20:16
    
I I skipped over that. Beautiful work. –  MVCylon Jun 19 at 20:28
    
What does it do to input that contains VERY ANGRY words in ALL CAPS? –  Adam Davis Jun 20 at 17:43

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.

share|improve this answer
    
Doesn't the shebang need an absolute path? –  celtschk Jun 19 at 12:51
    
why the dots (DIEI.NA. ...? –  edc65 Jun 19 at 13:17
    
@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 Jun 19 at 13:23
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 Jun 19 at 13:25
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 Jun 19 at 19:10

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.

share|improve this answer
    
Nice work! However, this prints an additional linefeed for both successful and non-successful input. –  Dennis Jun 19 at 21:04
    
@Dennis Do you mean the automatic final newline? Considering GolfScript doesn't technically have the notion of returning a value at all (which is what the questions asks for), it seems like allowing the printed output to act as the return value is accepting its output limitations. Enforcing no final newline would impose a 4-character (I believe) penalty on all competing GolfScript solutions. –  Runer112 Jun 19 at 21:32
    
1. Yes. 2. The questions specifically asks for a program, so I'd personally analyze the output byte per byte. Whether your solution is valid or not ultimately depends on the OP. 3. You can eliminate the final linefeed by appending :n; with a penalty of only 3 chars. –  Dennis Jun 19 at 21:36
1  
You 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 Jun 19 at 22:08
    
@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 Jun 19 at 22:18

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.

share|improve this answer

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;
share|improve this answer
3  
Surely it's possible to build the regex in code and save a ton? –  Peter Taylor Jun 19 at 9:57
    
@PeterTaylor certainly, but I neither have the time nor Perl knowledge to do that right now. I might have a look later today. –  Martin Büttner Jun 19 at 9:59
    
@primo Feel free to post it as your own answer, I won't get around to improving mine any time soon. It wasn't intended as a competitive answer, just to kickstart the challenge. –  Martin Büttner Jun 19 at 10:39
    
Even so it beats my PERL answer, which I won't bother posting now :p –  Tal Jun 19 at 10:40
    
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 Jun 19 at 21:00

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 in console, (avoiding 'prompt'):

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.";

(RegExp('^('+[...'DIE IN A GREASE FIRE$'].join('.*)(')+')').exec(z)|| [,z]).slice(1).join('\n')
share|improve this answer
    
JavaScript it is. –  Peter Mortensen Jun 24 at 18:45

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.

share|improve this answer

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
share|improve this answer

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
share|improve this answer

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.

share|improve this answer
    
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. :) –  Sieg Jun 20 at 9:48
    
@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 Jun 20 at 14:55
    
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+ –  Sieg Jun 20 at 15:04
    
Try what True == 1 gives. :) –  Sieg Jun 20 at 15:09

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.