2016 Update

This commit is contained in:
Tina Müller 2016-12-05 22:15:40 +01:00
parent 948b86eafa
commit dcf5d15da3
7965 changed files with 139854 additions and 31002 deletions

View file

@ -1,17 +1,29 @@
{{wikipedia}}
<br>
[[wp:Mad Libs|Mad Libs]] is a phrasal template word game where one player prompts another for a list of words to substitute for blanks in a story, usually with funny results.
Write a program to create a Mad Libs like story.
The program should read a multiline story from the input. The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements. Stop when there are none left and print the final story.
The input should be in the form:
;Task;
Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story, ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<pre>
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
</pre>
It should then ask for a <tt>name</tt>, a <tt>he or she</tt> and a <tt>noun</tt> (<tt><nowiki><name></nowiki></tt> gets replaced both times with the same value.)
{{wikipedia}}
Given this example, it should then ask for a <tt>name</tt>, a <tt>he or she</tt> and a <tt>noun</tt> (<tt><nowiki><name></nowiki></tt> gets replaced both times with the same value).
<br><br>
== {{header|Ada}} ==
The fun of Mad Libs is not knowing the story ahead of time, so the program reads the story template from a text file. The name of the text file is given as a command line argument.

View file

@ -1,48 +1,145 @@
#include <iostream>
#include <string>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
#define err(...) fprintf(stderr, ## __VA_ARGS__), exit(1)
/* We create a dynamic string with a few functions which make modifying
* the string and growing a bit easier */
typedef struct {
char *data;
size_t alloc;
size_t length;
} dstr;
inline int dstr_space(dstr *s, size_t grow_amount)
{
string story, input;
//Loop
while(true)
{
//Get a line from the user
getline(cin, input);
//If it's blank, break this loop
if(input == "\r")
break;
//Add the line to the story
story += input;
}
//While there is a '<' in the story
int begin;
while((begin = story.find("<")) != string::npos)
{
//Get the category from between '<' and '>'
int end = story.find(">");
string cat = story.substr(begin + 1, end - begin - 1);
//Ask the user for a replacement
cout << "Give me a " << cat << ": ";
cin >> input;
//While there's a matching category
//in the story
while((begin = story.find("<" + cat + ">")) != string::npos)
{
//Replace it with the user's replacement
story.replace(begin, cat.length()+2, input);
}
}
//Output the final story
cout << endl << story;
return 0;
return s->length + grow_amount < s->alloc;
}
int dstr_grow(dstr *s)
{
s->alloc *= 2;
char *attempt = realloc(s->data, s->alloc);
if (!attempt) return 0;
else s->data = attempt;
return 1;
}
dstr* dstr_init(const size_t to_allocate)
{
dstr *s = malloc(sizeof(dstr));
if (!s) goto failure;
s->length = 0;
s->alloc = to_allocate;
s->data = malloc(s->alloc);
if (!s->data) goto failure;
return s;
failure:
if (s->data) free(s->data);
if (s) free(s);
return NULL;
}
void dstr_delete(dstr *s)
{
if (s->data) free(s->data);
if (s) free(s);
}
dstr* readinput(FILE *fd)
{
static const size_t buffer_size = 4096;
char buffer[buffer_size];
dstr *s = dstr_init(buffer_size);
if (!s) goto failure;
while (fgets(buffer, buffer_size, fd)) {
while (!dstr_space(s, buffer_size))
if (!dstr_grow(s)) goto failure;
strncpy(s->data + s->length, buffer, buffer_size);
s->length += strlen(buffer);
}
return s;
failure:
dstr_delete(s);
return NULL;
}
void dstr_replace_all(dstr *story, const char *replace, const char *insert)
{
const size_t replace_l = strlen(replace);
const size_t insert_l = strlen(insert);
char *start = story->data;
while ((start = strstr(start, replace))) {
if (!dstr_space(story, insert_l - replace_l))
if (!dstr_grow(story)) err("Failed to allocate memory");
if (insert_l != replace_l) {
memmove(start + insert_l, start + replace_l, story->length -
(start + replace_l - story->data));
/* Remember to null terminate the data so we can utilize it
* as we normally would */
story->length += insert_l - replace_l;
story->data[story->length] = 0;
}
memmove(start, insert, insert_l);
}
}
void madlibs(dstr *story)
{
static const size_t buffer_size = 128;
char insert[buffer_size];
char replace[buffer_size];
char *start,
*end = story->data;
while (start = strchr(end, '<')) {
if (!(end = strchr(start, '>'))) err("Malformed brackets in input");
/* One extra for current char and another for nul byte */
strncpy(replace, start, end - start + 1);
replace[end - start + 1] = '\0';
printf("Enter value for field %s: ", replace);
fgets(insert, buffer_size, stdin);
const size_t il = strlen(insert) - 1;
if (insert[il] == '\n')
insert[il] = '\0';
dstr_replace_all(story, replace, insert);
}
printf("\n");
}
int main(int argc, char *argv[])
{
if (argc < 2) return 0;
FILE *fd = fopen(argv[1], "r");
if (!fd) err("Could not open file: '%s\n", argv[1]);
dstr *story = readinput(fd); fclose(fd);
if (!story) err("Failed to allocate memory");
madlibs(story);
printf("%s\n", story->data);
dstr_delete(story);
return 0;
}

View file

@ -0,0 +1,48 @@
#include <iostream>
#include <string>
using namespace std;
int main()
{
string story, input;
//Loop
while(true)
{
//Get a line from the user
getline(cin, input);
//If it's blank, break this loop
if(input == "\r")
break;
//Add the line to the story
story += input;
}
//While there is a '<' in the story
int begin;
while((begin = story.find("<")) != string::npos)
{
//Get the category from between '<' and '>'
int end = story.find(">");
string cat = story.substr(begin + 1, end - begin - 1);
//Ask the user for a replacement
cout << "Give me a " << cat << ": ";
cin >> input;
//While there's a matching category
//in the story
while((begin = story.find("<" + cat + ">")) != string::npos)
{
//Replace it with the user's replacement
story.replace(begin, cat.length()+2, input);
}
}
//Output the final story
cout << endl << story;
return 0;
}

View file

@ -1,34 +0,0 @@
# syntax: GAWK -f MAD_LIBS.AWK
BEGIN {
print("enter story:")
}
{ story_arr[++nr] = $0
if ($0 ~ /^ *$/) {
exit
}
while ($0 ~ /[<>]/) {
L = index($0,"<")
R = index($0,">")
changes_arr[substr($0,L,R-L+1)] = ""
sub(/</,"",$0)
sub(/>/,"",$0)
}
}
END {
PROCINFO["sorted_in"] = "@ind_str_asc"
print("enter values for:")
for (i in changes_arr) { # prompt for replacement values
printf("%s ",i)
getline rec
sub(/ +$/,"",rec)
changes_arr[i] = rec
}
printf("\nrevised story:\n")
for (i=1; i<=nr; i++) { # print the story
for (j in changes_arr) {
gsub(j,changes_arr[j],story_arr[i])
}
printf("%s\n",story_arr[i])
}
exit(0)
}

View file

@ -1,25 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace madLibs {
class Program {
static void Main(string[] args) {
string name, sex, addThis, thing;
bool isMale = false;
Console.Write("Enter a name: ");
name = Console.ReadLine();
while(isMale == false) {
Console.Write("Is that a male or female name? [m/f] ");
sex = Console.ReadLine().ToLower().ToCharArray()[0].ToString();
if(sex == "m") { isMale = true; } else if(sex == "f") { break; }
}
if (isMale){ addThis = "He "; }else{ addThis = "She "; }
Console.Write("Enter a thing: ");
thing = Console.ReadLine();
Console.WriteLine(Environment.NewLine + String.Format(("{0} went for a walk in the park. " + addThis +
"found a {1}. {0} decided to take it home."), name, thing));
Console.ReadKey();
}
}
using System.Text.RegularExpressions;
namespace MadLibs_RosettaCode
{
class Program
{
static void Main(string[] args)
{
string madLibs =
@"Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story,
ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name,
a he or she and a noun (<name> gets replaced both times with the same value).";
StringBuilder sb = new StringBuilder();
Regex pattern = new Regex(@"\<(.*?)\>");
string storyLine;
string replacement;
Console.WriteLine(madLibs + Environment.NewLine + Environment.NewLine);
Console.WriteLine("Enter a story: ");
// Continue to get input while empty line hasn't been entered.
do
{
storyLine = Console.ReadLine();
sb.Append(storyLine + Environment.NewLine);
} while (!string.IsNullOrEmpty(storyLine) && !string.IsNullOrWhiteSpace(storyLine));
// Retrieve only the unique regex matches from the user entered story.
Match nameMatch = pattern.Matches(sb.ToString()).OfType<Match>().Where(x => x.Value.Equals("<name>")).Select(x => x.Value).Distinct() as Match;
if(nameMatch != null)
{
do
{
Console.WriteLine("Enter value for: " + nameMatch.Value);
replacement = Console.ReadLine();
} while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement));
sb.Replace(nameMatch.Value, replacement);
}
foreach (Match match in pattern.Matches(sb.ToString()))
{
replacement = string.Empty;
// Guarantee we get a non-whitespace value for the replacement
do
{
Console.WriteLine("Enter value for: " + match.Value);
replacement = Console.ReadLine();
} while (string.IsNullOrEmpty(replacement) || string.IsNullOrWhiteSpace(replacement));
int location = sb.ToString().IndexOf(match.Value);
sb.Remove(location, match.Value.Length).Insert(location, replacement);
}
Console.WriteLine(Environment.NewLine + Environment.NewLine + "--[ Here's your story! ]--");
Console.WriteLine(sb.ToString());
}
}
}

View file

@ -0,0 +1,59 @@
(ns magic.rosetta
(:require [clojure.string :as str]))
(defn mad-libs
"Write a program to create a Mad Libs like story.
The program should read an arbitrary multiline story from input.
The story will be terminated with a blank line.
Then, find each replacement to be made within the story,
ask the user for a word to replace it with, and make all the replacements.
Stop when there are none left and print the final story.
The input should be an arbitrary story in the form:
<name> went for a walk in the park. <he or she>
found a <noun>. <name> decided to take it home.
Given this example, it should then ask for a name,
a he or she and a noun (<name> gets replaced both times with the same value). "
[]
(let
[story (do
(println "Please enter story:")
(loop [story []]
(let [line (read-line)]
(if (empty? line)
(str/join "\n" story)
(recur (conj story line))))))
tokens (set (re-seq #"<[^<>]+>" story))
story-completed (reduce
(fn [s t]
(str/replace s t (do
(println (str "Substitute " t ":"))
(read-line))))
story
tokens)]
(println (str
"Here is your story:\n"
"------------------------------------\n"
story-completed))))
; Sample run at REPL:
;
; user=> (magic.rosetta/mad-libs)
; Please enter story:
; One day <who> wake up at <where>.
; <who> decided to <do something>.
; While <who> <do something>, strange man
; appears and gave <who> a <thing>.
; Substitute <where>:
; Sweden
; Substitute <thing>:
; Nobel prize
; Substitute <who>:
; Bob Dylan
; Substitute <do something>:
; walk
; Here is your story:
; ------------------------------------
; One day Bob Dylan wake up at Sweden.
; Bob Dylan decided to walk.
; While Bob Dylan walk, strange man
; appears and gave Bob Dylan a Nobel prize.

View file

@ -0,0 +1,65 @@
function New-MadLibs
{
[CmdletBinding(DefaultParameterSetName='None')]
[OutputType([string])]
Param
(
[Parameter(Mandatory=$false)]
[AllowEmptyString()]
[string]
$Name = "",
[Parameter(Mandatory=$false, ParameterSetName='Male')]
[switch]
$Male,
[Parameter(Mandatory=$false, ParameterSetName='Female')]
[switch]
$Female,
[Parameter(Mandatory=$false)]
[AllowEmptyString()]
[string]
$Item = ""
)
if (-not $Name)
{
$Name = (Get-Culture).TextInfo.ToTitleCase((Read-Host -Prompt "`nEnter a name").ToLower())
}
else
{
$Name = (Get-Culture).TextInfo.ToTitleCase(($Name).ToLower())
}
if ($Male)
{
$pronoun = "He"
}
elseif ($Female)
{
$pronoun = "She"
}
else
{
$title = "Gender"
$message = "Select $Name's Gender"
$_male = New-Object System.Management.Automation.Host.ChoiceDescription "&Male", "Selects male gender."
$_female = New-Object System.Management.Automation.Host.ChoiceDescription "&Female", "Selects female gender."
$options = [System.Management.Automation.Host.ChoiceDescription[]]($_male, $_female)
$result = $host.UI.PromptForChoice($title, $message, $options, 0)
switch ($result)
{
0 {$pronoun = "He"}
1 {$pronoun = "She"}
}
}
if (-not $Item)
{
$Item = Read-Host -Prompt "`nEnter an item"
}
"`n{0} went for a walk in the park. {1} found a {2}. {0} decided to take it home.`n" -f $Name, $pronoun, $Item
}

View file

@ -0,0 +1 @@
New-MadLibs -Name hank -Male -Item shank

View file

@ -0,0 +1 @@
New-MadLibs

View file

@ -0,0 +1,8 @@
$paramLists = @(@{Name='mary'; Female=$true; Item="little lamb"},
@{Name='hank'; Male=$true; Item="shank"},
@{Name='foo'; Male=$true; Item="bar"})
foreach ($paramList in $paramLists)
{
New-MadLibs @paramList
}

View file

@ -1,36 +1,35 @@
/*REXX program prompts user for a template substitutions within a story.*/
@.=; !.=0; #=0; @= /*assign some defaults. */
parse arg iFID . /*allow use to specify input file*/
if iFID=='' then iFID="MAD_LIBS.TXT" /*Not specified? Use a default.*/
/*REXX program prompts the user for a template substitutions within a story (MAD LIBS).*/
parse arg iFID . /*allow user to specify the input file.*/
if iFID=='' | iFID=="," then iFID="MAD_LIBS.TXT" /*Not specified? Then use the default.*/
@.= /*assign defaults to some variables. */
$=; do recs=1 while lines(iFID)\==0 /*read the input file until it's done. */
@.recs=linein(iFID); $=$ @.recs /*read a record; and append it to @ */
if @.recs='' then leave /*Read a blank line? Then we're done.*/
end /*recs*/
recs=recs-1 /*adjust for a E─O─F or a blank line.*/
pm= 'please enter a word or phrase to replace: ' /*this is part of the Prompt Message. */
!.=0 /*placeholder for phrases in MAD LIBS.*/
#=0; do forever /*look for templates within the text. */
parse var $ '<' ? ">" $ /*scan for <ααα> stuff in the text.*/
if ?='' then leave /*No ααα ? Then we're all finished.*/
if !.? then iterate /*Already asked? Then keep scanning. */
!.?=1 /*mark this ααα as being "found". */
do until ans\='' /*prompt user for a replacement. */
say '' pm ? /*prompt the user with a prompt message*/
parse pull ans /*PULL obtains the text from console. */
end /*forever*/
#=#+1 /*bump the template counter. */
old.# = '<'?">"; new.# = ans /*assign the "old" name and "new" name.*/
end /*forever*/
say /*display a blank line for a separator.*/
say; say copies('', 79) /*display a blank line and a fence. */
do recs=1 while lines(iFID)\==0 /*read the input file 'til done. */
@.recs=linein(iFID); @=@ @.recs /*read a record, append it to @ */
if @.recs='' then leave /*Read a blank line? We're done.*/
end /*recs*/
do m=1 for recs /*display the text, line for line. */
do n=1 for # /*perform substitutions in the text. */
@.m=changestr(old.n, @.m, new.n) /*maybe replace text in @.m haystack.*/
end /*n*/
say @.m /*display the (new) substituted text. */
end /*m*/
recs=recs-1 /*adjust for E─O─F or blank line.*/
do forever /*look for templates in the text.*/
parse var @ '<' ? '>' @ /*scan for <ααα> stuff in text.*/
if ?='' then leave /*if no ααα, then we're done. */
if !.? then iterate /*already asked? Keep scanning.*/
!.?=1 /*mark this ααα as "found". */
do forever /*prompt user for a replacement. */
say ' please enter a word or phrase to replace: ' ?
parse pull ans; if ans\='' then leave
end /*forever*/
#=#+1 /*bump the template counter. */
old.# = '<'?">"; new.# = ans /*assign "old" name & "new" name.*/
end /*forever*/
say; say copies('',79) /*display a blank and a fence. */
do m=1 for recs /*display the text, line for line*/
do n=1 for # /*perform substitutions in text. */
@.m = changestr(old.n, @.m, new.n)
end /*n*/
say @.m /*display (new) substituted text.*/
end /*m*/
say copies('',79) /*display a final (output) fence.*/
/*stick a fork in it, we're done.*/
say copies('', 79) /*display a final (output) fence. */
say /*stick a fork in it, we're all done. */