54
\$\begingroup\$

Based on the Duct tape can fix anything question, that was too broad, with very similar rules. Only this time the objective is very specific:

The challenge

Your mission is to make a program that displays hello mom -- without ever writing a single line of code.

You can only use code which is already written for you, both in questions and answers from StackOverflow. All you can do is duct tape it all together the best you can. And of course, it's very important that we provide appropriate attribution so that we don't get our rights terminated.


Rules

  1. You must include links to the questions/answers you used in your answer.

  2. You may not modify the code you find, with the following exceptions:

    a. You may rename variables, functions, and methods. (This doesn't mean you can change a method invocation, by changing, say scanner.nextInt() to scanner.nextLine() and claiming that you're changing a method name. The change must be in the definition or reference to the same entity.). The solution should still work if variables, functions or methods would be renamed again, so renaming code to contain hello mom as a variable name does not count.

    b. You may adjust indentation appropriately.

    c. You can assume that the proper modules are loaded for the code snippets to work. (e.g., import statements for Java and Python, using statements for C# and C++, and their equivalents in all languages) If the code snippet includes the imports for you, you can move them to the top of the code.

    d. If the language requires the code to be in some kind of method body to execute (e.g., public static void main(String[] args) for Java, static int Main(string[] args) for C#, and so on), you can wrap your code in the appropriate method. But the contents of that main method must remain unmodified.

  3. You must supply an explicit list of any variable/method/function/class rename-ings performed.

  4. You can't take snippets of snippets (meaning if you take a code block from a post, you take the whole thing)

  5. Provide a brief description of what the code does for people who aren't intimate with the language you're using.

  6. You must use snippets posted before this challenge was started.

  7. Popularity contest, so the most upvotes wins!

Deadline

I will accept the the submission that has the most votes around the end of mothersday (midnight of the UTC-11 timezone), but later submissions can still get votes.

\$\endgroup\$
19
  • 1
    \$\begingroup\$ @iamkrillin That would make it fairly trivial to transfer any hello world example into a hello mom code. Also note the last line in the rule about renaming variables. \$\endgroup\$ Commented May 9, 2014 at 14:00
  • 23
    \$\begingroup\$ 7. You must use snippets posted before this challenge was. (I could go answer a bunch of string-related questions with code that would do this) \$\endgroup\$
    – Geobits
    Commented May 9, 2014 at 14:05
  • 1
    \$\begingroup\$ Can you insert code inside another snippet? \$\endgroup\$
    – durron597
    Commented May 9, 2014 at 17:40
  • 3
    \$\begingroup\$ @Gareth you know, there are other countries... \$\endgroup\$ Commented May 9, 2014 at 18:13
  • 1
    \$\begingroup\$ @JeffGohlke or an m or an o as a literal. Or a snippet that converts code points to characters and snippets that let you calculate the right code point. The restriction is exactly what encourages creativity here. This is what I mentioned on your own challenge, and why I suggested to limit the scope (and subsequently why it was closed). \$\endgroup\$ Commented May 9, 2014 at 18:15

7 Answers 7

63
\$\begingroup\$

Brainfuck

Oh god why did I do this to myself?

It is actually possible to find each BF symbol by itself as a code snippet in some answer somewhere. The interesting bit was piecing together bits of other people's code, each representing a block of BF instructions. Unfortunately there are basically no unmatched [ and ] symbols out there, so I had to cheat a bit for those, and I had to get an awful lot of mileage out of a funky Haskell snippet which had a bunch of pluses in it. There are probably others out there. Beyond that, here's some Frankensteined code:

byte x = 1;
byte y = 2;
byte z = x + y;   // ERROR: Cannot implicitly convert type 'int' to 'byte'
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
[
int a = (b > 10) ? some_value                 
                 : another_value;
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
int a = (b > 10) ? c : d;
byte x = 1;
byte y = 2;
byte z = x + y;   // ERROR: Cannot implicitly convert type 'int' to 'byte'
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
?"<<-"
]
exec >{space}> (command)
byte z = (int) x + (int) y;
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
find . -type f -print -exec cat {} \;
git reset .
byte x = 1;
byte y = 2;
byte z = x + y;   // ERROR: Cannot implicitly convert type 'int' to 'byte'
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
System.out.print("B");
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
fatal: Failed to resolve 'HEAD' as a valid ref.
while read p; do 
echo $p
done < $filename
static HMODULE hMod = NULL;
  static bool once = false;
  if (!once++)
    hMod = LoadLibrary("xxx");
 if (originalValue.length > size) {
static HMODULE hMod = NULL;
  static bool once = true;
  if (once--)
    hMod = LoadLibrary("xxx");
$ cd /usr/local/wherever
$ grep timmy accounts.txt
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub}
ls -ld $(find .)
git commit --amend -m "New commit message"
wget -q -O - $line 
git rebase --interactive $parent_of_flawed_commit
find . -type f -user 'user1' -maxdepth 1

And, since my mother is British, the output is quite simply hello mum

Bibliography:

https://stackoverflow.com/questions/17845014/what-does-the-regex-mean

[ and ], with apologies

https://stackoverflow.com/a/21460161/2581168

find . -type f -print -exec cat {} \;

https://stackoverflow.com/questions/6161328/what-exactly-does-this-do-exec-command

exec >{space}> (command)

https://stackoverflow.com/questions/20130538/what-is-in-haskell

addop = do {symb "+"; return Op Add}  +++ do {symb "-"; return Op Sub} 

https://stackoverflow.com/questions/21947452/why-is-printing-b-dramatically-slower-than-printing

System.out.print("B");

https://stackoverflow.com/questions/941584/byte-byte-int-why

byte x = 1;
byte y = 2;
byte z = x + y;   // ERROR: Cannot implicitly convert type 'int' to 'byte'

https://stackoverflow.com/a/160295/2581168

int a = (b > 10) ? c : d;

And

int a = (b > 10) ? some_value                 
                 : another_value;

https://stackoverflow.com/questions/13273002/what-does-mean-in-r

?"<<-"

https://stackoverflow.com/questions/3450420/bool-operator-and

static HMODULE hMod = NULL;
static bool once = false;
if (!once++)
    hMod = LoadLibrary("xxx");

And

static HMODULE hMod = NULL;
static bool once = false;
if (!once--)
    hMod = LoadLibrary("xxx");

https://stackoverflow.com/questions/22776085/in-which-case-will-size-originalvalue-length-in-string-constructor-string

if (originalValue.length > size) {

https://stackoverflow.com/questions/3797795/does-mean-stdout-in-bash

wget -q -O - $line 

https://stackoverflow.com/questions/179123/how-do-i-edit-an-incorrect-commit-message-in-git/179147#179147

git commit --amend -m "New commit message"

And

git rebase --interactive $parent_of_flawed_commit

https://stackoverflow.com/questions/14763413/grep-ls-output-across-tabs/14763499#14763499

find . -type f -user 'user1' -maxdepth 1

https://stackoverflow.com/questions/945288/saving-current-directory-to-bash-history

$ cd /usr/local/wherever
$ grep timmy accounts.txt

https://stackoverflow.com/questions/348170/undo-git-add-before-commit/682343#682343

fatal: Failed to resolve 'HEAD' as a valid ref.
\$\endgroup\$
6
  • \$\begingroup\$ Error messages are not code. Though that one should be easy to fix \$\endgroup\$
    – durron597
    Commented May 10, 2014 at 0:15
  • 6
    \$\begingroup\$ Also there should probably be a ruling on whether the code snippet needs to be in the language of the answer. But well done, regardless \$\endgroup\$
    – durron597
    Commented May 10, 2014 at 0:16
  • \$\begingroup\$ @durron597, true, but I kind of like having the error message in there. There's a git add . in the same post if OP has a problem with it. \$\endgroup\$
    – ymbirtt
    Commented May 10, 2014 at 8:09
  • \$\begingroup\$ There might be some J answers out there that have unmatched []s, but those often come with .s included. stackoverflow.com/questions/21898628/… \$\endgroup\$ Commented May 11, 2014 at 16:53
  • 1
    \$\begingroup\$ This is awesome. +1000 \$\endgroup\$
    – asteri
    Commented May 11, 2014 at 17:07
34
\$\begingroup\$

Java

Start with these:

https://stackoverflow.com/a/19509316/1768232

String myStr = "hello";
String myStr1 = "hello";

https://stackoverflow.com/a/8341513/1768232

String[] history = new String[] { "hey", "you", "Mom" };

https://stackoverflow.com/a/23300004/1768232

String editednames = titleCase(name);

https://stackoverflow.com/a/20698093/1768232

myString = myString.toLowerCase();

https://stackoverflow.com/a/19393222/1768232

System.out.println(Name + " " + Income);

https://stackoverflow.com/a/1181979/1768232

public static <T> T last(T[] array) {
   return array[array.length - 1];
}

Add the required class and public static void main(String[] args){ } as allowed in Rule #2d (not around the static method), and change some variable / method names in exactly 3 of 6 snippets:

  • Change name -> history in the third snippet
  • Change editednames -> myString in the third snippet
  • Change Name -> myStr in the fifth snippet
  • Change Income -> myString in the fifth snippet
  • Change last -> titleCase in the sixth snippet

Resulting program:

public class DuctTape {
  public static void main(String[] args) {
    // https://stackoverflow.com/a/19509316/1768232
    String myStr = "hello";
    String myStr1 = "hello";

    // https://stackoverflow.com/a/8341513/1768232
    String[] history = new String[] { "hey", "you", "Mom" };

    // https://stackoverflow.com/a/23300004/1768232
    String myString = titleCase(history);

    // https://stackoverflow.com/a/20698093/1768232
    myString = myString.toLowerCase();

    // https://stackoverflow.com/a/19393222/1768232
    System.out.println(myStr + " " + myString);
  }

  // https://stackoverflow.com/a/1181979/1768232
  public static <T> T titleCase(T[] array) {
    return array[array.length - 1];
  }
}

Output:

hello mom
\$\endgroup\$
4
  • 2
    \$\begingroup\$ This appears to break the rules; 2a indicates you can't change which method is invoked by a method call, which you did in changing titleCase() to last(). \$\endgroup\$ Commented May 10, 2014 at 0:07
  • 1
    \$\begingroup\$ @BillyMailman if your interpretation is correct then you can NEVER use a method definition unless the q/a also provides a call to that method somewhere. I will try to edit if there's a ruling from OP \$\endgroup\$
    – durron597
    Commented May 10, 2014 at 0:13
  • 2
    \$\begingroup\$ Actually, @BillyMailman is right. But the way you do this is by renaming the method to titleCase() rather than renaming the external reference. That's how you'd tie it together. Rule 2a dictates that changing method/function names is legal. \$\endgroup\$
    – asteri
    Commented May 10, 2014 at 23:18
  • 1
    \$\begingroup\$ @JeffGohlke Fixed \$\endgroup\$
    – durron597
    Commented May 11, 2014 at 15:42
28
\$\begingroup\$

C#

Possibly crazy, roundabout, and convoluted way to get to the (exact) result - with only variable renames and without any literal "mom" in any of the code.

Reading the "if you take a code block from a post, you take the whole thing" rule very literally probably didn't help - but made it more fun.

using System;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

public class Program
{
    void Main()
    {
        // Step 1
        var n = 3;
        var helloAndGoodbye = "12345678900"
                    .Select((c, i) => new { letter = c, group = i / n })
                    .GroupBy(l => l.group, l => l.letter)
                    .Select(g => string.Join("", g))
                    .ToList();

        // Step 2
        string place = "world";
        string greet = String.Format("Hello {0}!", place); 

        // Step 3
        byte[] b1 = System.Text.Encoding.UTF8.GetBytes (greet);
        byte[] b2 = System.Text.Encoding.ASCII.GetBytes (greet);

        // Step 4
        string encryptionKey = "test";
        var md5 = MD5.Create();
        var keyBytes = Encoding.UTF8.GetBytes(encryptionKey);
        byte[] encryptionKeyBytes = md5.ComputeHash(keyBytes);

        // Step 5
        string strName = md5.GetType().Name;
        if(strName == "Person")
        {
            //My Code
        }

        // Step 6
        string HashAlgorithm = new string(strName.Take(n).ToArray());

        // Step 7
        int previousYear = DateTime.Now.AddYears(-1).Year;

        // Step 8
        string myString = previousYear.ToString();

        // Step 9
        string totallyRandomString = new string(myString.Take(n).ToArray());

        // Step 10
        int myInt = System.Convert.ToInt32(totallyRandomString);

        // Step 11
        int x = myInt << 1 + 1;

        // Step 12
        PasswordDeriveBytes DerivedPassword = 
                    new PasswordDeriveBytes(place, b1, HashAlgorithm, x);
        byte[] KeyBytes = DerivedPassword.GetBytes(32);

        // Step 13
        string base64 = Convert.ToBase64String(KeyBytes);
        byte[] bytes = Convert.FromBase64String(base64);

        // Step 14
        var split = base64.Split('/');
        var last = split[split.Length -1];
        var prev = split[split.Length -2];

        // Step 15
        string truncatedToNLength = new string(last.Take(n).ToArray());

        // Step 16
        Regex rgx = new Regex("[^a-zA-Z0-9 -]");
        greet = rgx.Replace(greet, "");

        // Step 17
        var newString = greet.Replace(place.ToString(), truncatedToNLength);

        // Step 18
        var searchStr = newString.ToLower();
            searchStr = searchStr.Trim();

        // Step 19
        Console.WriteLine(searchStr); 
    }
}

.NET Fiddle

http://dotnetfiddle.net/PbjhPn

http://dotnetfiddle.net/bg20wb (with redundant lines in code blocks removed)

Short explanation

Basically, we get "Hello world!" from a simple string format. Now we need "mom" to replace it. For that, we use the Base64 encoded result of running 804 iterations of PBKDF1 using MD5 with "world" as password and "Hello world!" as salt. That yields a string "ciSf5cCls1l/MoM...". We extract that "MoM" and use it as a replacement for "world". Then we clean up the string.

How do we get to 804? The previous year clipped to three characters (= "201"), and then multiplied by 4.

Long explanation and attributions

1: We start with a bit of rule-following overkill. The integer 3 is a very very important constant in this program. Here we assign that integer to n. We must include the entire block from the source. It may be redundant, but it will compile just fine, as long as we rename the split variable that we'll be needing later. Source

Replaced variable names:

split              > helloAndGoodbye

2: Set up starting string ("Hello world!"). Source

This is a very personal message to our mom. So we obviously need some cryptography to deal with those NSA types. For that, we'll need some parameters, which we prepare now.

3: Convert greet ("Hello world!") to byte array for salting. Source

myString           > greet

4: Although we're using cryptography, we don't actually need to instantiate the MD5 class. We do, however, need the string "MD5" assigned for one of our parameters to be used further down - and that's not easy to find in usable code. So we'll take another... "shortcut"... Once again, entire code block included as per rules, although we only need the second line. Source

5: Now we need the name of the type of the md5 variable (MD5CryptoServiceProvider). The if is yet another redundancy. Source

entity             > md5

6: Get the first 3 (ooh, there's our constant!) characters of the type name. Source

s                  > strName
truncatedToNLength > HashAlgorithm

7: Code-trolling: Using DateTime.Now would mean this would only work until 2019. To make it a bit more future proof, we use the previous year. Then it will work until 2020 ;-)Source

8: Convert our previousYear to string. Source

myInt              > previousYear

9: Hey, code reuse! ;-) Get the first 3 (our constant!) characters of our year. Source

s                  > myString
truncatedToNLength > totallyRandomString

10: Aaaaaaaand... convert the result back to integer. Source

myString           > totallyRandomString

11: Eric Lippert makes every answer better. Multiply by 4 in a roundabout way. Source

y                  > myInt

12: Send place (password) and greet (salt) through PBKDF1 using MD5 with x (which is now 201*4 = 804) iterations. Source

Password           > place
SaltValueBytes     > b1
PasswordIterations > x

13: Jon Skeet also makes every answer better. Convert our derived password to base 64. We throw out the bytes array. Source

bytes (first occurrence) > KeyBytes

14: What a crazy random happenstance! We now have a base64 with "MoM" in it. Conveniently, right before "MoM" is a single '/'. So split the string with that character as delimiter: Source

filePath          > base64

15: Hey, our favorite piece of code reuse tape! Get the first 3 (constant!) letters of last. Source

s                 > last

16: Remove "!". Source

str               > greet

17: MoM is our world - so make the string reflect that (replace "world" with "MoM"). Source

someTestString   > greet
someID           > place
sessionID        > truncatedToNLength

18: Finally, convert to lower case. Trim for good measure (or possibly because it's part of the duct tape block). Source

wordToSearchReplacemntsFor > newString

19: Output to console. Source

_surface         > searchStr

A bit of "bonus material"/commentary

  • At first I tried every combination of built-in cryptographic hashes (each combined with HMAC) and inputs ("world", "Hello world!", "Hello world", "hello world" etc.) to see if something would miraculously give a usable output to derive "mom" from - before taking the easy route of just looking for a number of iterations of PDKDB1 (or 2) that would be useful.

  • Wasn't quite happy with the use of the year as input for the 201*4 = 804 iterations. At first I tried to find some useful code for HttpStatusCode.Created (201) to use as input - with a "troll excuse" along the lines of "we've created our 'Hello world!' string, so a good practice would be to use a 'Created' status code" here. Unfortunately, I never found a usage of the HttpStatusCode enumeration that didn't introduce a dependency on most of the ASP.NET WebAPI framework.

  • The start of the code (the "Hello world!" string format) was never looked at again after I first added it. If I had, yeah, I might have realized that the assignment of place was actually in a different block in the source - so I could have simply assigned my derived "mom" to place rather than using "world" and later replacing it. Ah well.

\$\endgroup\$
2
  • 5
    \$\begingroup\$ +1 for "mom is our world", and "Lippert and Skeet make every answer better". \$\endgroup\$
    – Floris
    Commented May 10, 2014 at 22:59
  • \$\begingroup\$ "Trim for good measure..." gave me a good chuckle. \$\endgroup\$
    – Etheryte
    Commented May 12, 2014 at 15:17
24
\$\begingroup\$

Befunge 98

My code:

var abc = function(){};
display: table-*
display: table-*
display: table-*
display: table-*
display: table-*
display: table-*
display: table-*
display: table-*
+
+
+
+
+
+
+
, new {area = ""}
byte z = x + y;
byte z = x + y;
byte z = x + y;
byte z = x + y;
byte z = x + y;
byte z = x + y;
byte z = x + y;
byte z = x + y;
display: table-*
+
+
+
+
+
+
+
+
, new {area = ""}
"1,23,4"
  String[] temp = data.split("\\s+\\^,?\"'\\|+");
List<Set<Integer>> foo;
"1,23,4"
+
: base(name)
: base(name)
, new {area = ""}
, new {area = ""}
10001.10010110011
10001.10010110011
10001.10010110011
+
+
+
, new {area = ""}
"1,23,4"
  String[] temp = data.split("\\s+\\^,?\"'\\|+");
"1,23,4"
, new {area = ""}
"1,23,4"
[5326, 4223, 1204]
Runnable prs = new Runnable() {
    public void run() {
        Document doc = null;
        try {
            doc = Jsoup.connect("http://play.radio.com/").get();

        } catch (IOException e) {

            e.printStackTrace();
        }
        parser.postDelayed(prs, 10000);
    }
};
"1,23,4"
$selector.append("somestuff");
$selector.append("somestuff");
-new Date().getTimezoneOffset()/60;
: base(name)
10001.10010110011
10001.10010110011
10001.10010110011
+
+
+
 [0000] push        ebp
 [0001] mov         ebp,esp
 [0003] push        edi
 [0004] push        esi
 [0005] push        ebx
 [0006] sub         esp,1Ch
 [0009] xor         eax,eax
 [000b] mov         dword ptr [ebp-20h],eax
 [000e] mov         dword ptr [ebp-1Ch],eax
 [0011] mov         dword ptr [ebp-18h],eax
 [0014] mov         dword ptr [ebp-14h],eax
 [0017] xor         eax,eax
 [0019] mov         dword ptr [ebp-18h],eax
*[001c] mov         esi,1
 [0021] xor         edi,edi
 [0023] mov         dword ptr [ebp-28h],1
 [002a] mov         dword ptr [ebp-24h],0
 [0031] inc         ecx
 [0032] mov         ebx,2
 [0037] cmp         ecx,2
 [003a] jle         00000024
 [003c] mov         eax,esi
 [003e] mov         edx,edi
 [0040] mov         esi,dword ptr [ebp-28h]
 [0043] mov         edi,dword ptr [ebp-24h]
 [0046] add         eax,dword ptr [ebp-28h]
 [0049] adc         edx,dword ptr [ebp-24h]
 [004c] mov         dword ptr [ebp-28h],eax
 [004f] mov         dword ptr [ebp-24h],edx
 [0052] inc         ebx
 [0053] cmp         ebx,ecx
 [0055] jl          FFFFFFE7
 [0057] jmp         00000007
 [0059] call        64571ACB
 [005e] mov         eax,dword ptr [ebp-28h]
 [0061] mov         edx,dword ptr [ebp-24h]
 [0064] lea         esp,[ebp-0Ch]
 [0067] pop         ebx
 [0068] pop         esi
 [0069] pop         edi
 [006a] pop         ebp
 [006b] ret
10001.10010110011
+
: base(name)
, new {area = ""}
"1,23,4"
List<Set<Integer>> foo;

"1,23,4"
+
10001.10010110011
10001.10010110011
10001.10010110011
+
+
+
, new {area = ""}
, new {area = ""}
def logme(func):
    def wrapped(*args):
        for arg in args: print str(arg)
        func(*args)
    return wrapped

@logme
def my_func(*args):
    res = 1
    for arg in args :
        print "Multiplying %s by %s" % (arg, res)
        res*=arg
    print res
    return res

This works because the first v (in the first line) sends the IP downward. So we are basically executing this program:

dddddddd+++++++,bbbbbbbbd++++++++," L"+::,,111+++," ","[R           }"$$-:111+++             *                            1+:,"L "+111+++,,d     @

Which does this:

  • dddddddd+++++++, pushes 104 and prints
  • bbbbbbbbd++++++++, pushes 101 and prints
  • " L"+, pushes 32 and the ascii value of L, then adds them, duplicates twice, and prints twice
  • To the one that was duplicated, 111+++, adds 3 and prints
  • " ", prints a space. "[R }"$$-:111+++ pushes a 9 and duplicates it, then adds 3 to the top value
  • * multiplies the top two values
  • 1+:, increments that number, duplicates, and prints
  • "L "+111+++, prints o. , prints the m from earlier, and d @ pushes 13 (which does nothing) and ends the program.
\$\endgroup\$
1
  • 4
    \$\begingroup\$ And yes. I actually did run this and it outputs hello mom \$\endgroup\$
    – Justin
    Commented May 10, 2014 at 6:49
14
\$\begingroup\$

Java

import java.util.*;

public class HelloMom {

     public static void main(String[] args) {
         Hashtable<String, String> ht = new Hashtable<String, String>();

        ht.put("Answer", "42");
        ht.put("Hello", "World");    // First value association for "Hello" key.
        ht.put("Hello", "Mom");      // Second value association for "Hello" key.

        for (Map.Entry<String, String> e : ht.entrySet()) {
          System.out.println(e);
        }
    }
}

Output

Answer=42
Hello=Mom

There is a pesky = in there, but this is the best I could do

https://stackoverflow.com/a/1050075/573421

\$\endgroup\$
2
  • \$\begingroup\$ Remarkable find! \$\endgroup\$
    – Floris
    Commented May 10, 2014 at 22:57
  • 1
    \$\begingroup\$ Actually I searched a bit before starting the challenge and did not expect to find complete solutions like this in one post. Nice that you found one anyway! \$\endgroup\$ Commented May 12, 2014 at 9:30
11
\$\begingroup\$

C

Most of this code comes from an answer to Find the beginning of the first word that is a palindrom [sic] posted by BLUEPIXY, which outputs the word mom. At lines 21 and 22, the hello is printed by a code snippet at the end of an answer to printf(“%%%s”,“hello”) by user142019 (who fortunately added a semicolon at the end), and the space between the words comes from an answer to How to print space with padding in c by M Oehm.

Output:

%hello        mom

I wasn't able to eliminate the extra spaces or the percent character, unfortunately :(

Source code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int isPalindrome(const char *str){
    const char *front, *back;
    front=str;
    back =str + strlen(str)-1;
    for(;front<back;++front,--back){
        while(!isalpha(*front))++front;//isalnum?
        while(!isalpha(*back))--back;
        if(front > back || tolower(*front)!=tolower(*back))
            return 0;
    }
    return 1;
}

int main(){
    const char *data="Hello mom and dad, how is it going?";
    char *p, *src;
    printf("%%%s", "hello");
    printf("        ");
    p=src=strdup(data);
    for(;NULL!=(p=strtok(p, " \t\n,.!?"));p=NULL){
        if(isPalindrome(p)){
            printf("%s\n", p);
            break;
        }
    }
    free(src);
    return 0;
}
\$\endgroup\$
7
\$\begingroup\$

Java

import java.io.ByteArrayOutputStream;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Random;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author LH
 */
public class Kopierpaste
{

    //https://stackoverflow.com/questions/15182496/why-does-this-code-using-random-strings-print-hello-world
    //randomizer code for the first String
    public static String randomString(int i)
    {
        Random ran = new Random(i);
        StringBuilder sb = new StringBuilder();
        for (int n = 0;; n++)
        {
            int k = ran.nextInt(27);
            if (k == 0)
            {
                break;
            }

            sb.append((char) ('`' + k));
        }

        return sb.toString();
    }

    public static void main(String[] nope)
    {
        //catching a System.out() based code snippet
        //https://stackoverflow.com/questions/4183408/redirect-stdout-to-a-string-in-java
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        System.setOut(new PrintStream(baos));
        //same as randomizer
        //getting hello, world inside a ByteArray
        System.out.println(randomString(-229985452) + " " + randomString(-147909649));
        
        //undo the redirecct of System.out()
        //https://stackoverflow.com/questions/4183408/redirect-stdout-to-a-string-in-java && https://stackoverflow.com/a/14716148/1405227
        System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
        
        
        //stringify the out of first part
        //https://stackoverflow.com/questions/4183408/redirect-stdout-to-a-string-in-java
        String text = baos.toString();

        
        //getting rid of the world part
        //https://stackoverflow.com/a/17008136/1405227
        String firstWord = text.substring(0, text.indexOf(' '));

        //needing the word Mom
        //https://stackoverflow.com/a/8341513/1405227
        //history -> a
        String[] a = new String[]
        {
            "hey", "you", "Mom"
        };

        //stitching the array together in a certain fashion ([elem1, elem2, elem3]
        //https://stackoverflow.com/a/2822736/1405227
        //myarray->a
        String b = Arrays.toString(a);

        //getting rid of the ,s
        //https://stackoverflow.com/a/7552284/1405227 stripping annoying bullcrap out
        //result ->c
        //yourString ->b
        String c = b.replaceAll("[-+.^:,]", "");

        
        //getting the Mom] part
        //https://stackoverflow.com/a/15317037/1405227
        //sentence -> c
        String lastToken = c.replaceAll(".* ", "");

        //getting rid of more crap
        //https://stackoverflow.com/a/18599016/1405227
        //message -> lastToken
        lastToken = lastToken.replaceAll("\\W", "");

        
        //finally out
        //https://stackoverflow.com/a/19393222/1405227
        //name -> firstWord
        //income -> lastToken
        System.out.println(firstWord + " " + lastToken);
    }
}

Documentation and source links are in the comments ( starting with // )

clean list of sources used

\$\endgroup\$
2
  • \$\begingroup\$ +1. I wanted to go for the random hello world approach but got bored and did it more straightforwardly. nicely done \$\endgroup\$
    – durron597
    Commented May 10, 2014 at 17:59
  • \$\begingroup\$ yeah, remembered that, and to get it out i had to abuse the system.out redirect hax. took me a while to get the Mom with my approach and some nasty regexes. but luckily we got google to dig around SO \$\endgroup\$
    – masterX244
    Commented May 10, 2014 at 18:01

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