OK, so in the spirit of Code-Golf, I\'m trying out something new here: Code-Bowling.
In golf, you try to get the lowest score (smallest application, mos
OK, there you go... NOW quickly send me some money so I can leave this country and live on some random pacific island where I built pitfalls and hide in the jungle so I'm safe from Crockford....
// give out greeting program
rand = Math.random;
tims = Array()
timeString = "morning ,afternoon,evening ,night" // our times of day
timesCount=4 // set timesCount to 4
// shorthand for creating array dont have to type tims[...] = ... all the time
makeArray(timeString, timesCount)
greeting = null
// this saves typing
String['prototype']['getChar'] =function(big,p){
return String.fromCharCode(big!=false? this.charCodeAt(p)-32: this.charCodeAt(p)) }
function makeArray(data,max){
ex = regeExFromStr('[a-zA-Z]+', "g")
while(m= ex.exec(data))if(tims.length< max)tims.push(m[0])
return tims }
function formatGreting(){
mesage ="Good " + randm;
msglength=0
// get string length should be fast this way
while(mesage[msglength])++msglength
captialisised=""
// check if we need to replace with upper
for(i=0;char=mesage.charCodeAt(i-1),i <msglength; i++)
// found this on another side on the internet
switch(char) {
case 32: if(char== 32)
captialisised= captialisised + mesage.getChar(true,i)
break;
default: if (char!=32)
captialisised = captialisised+mesage.getChar(false,i)
break
}
// make sure there is no whitespace should work better with regex
trimmed=regeExFromStr("([A-Za-z]+\\\s[A-Za-z]+)",'').exec(captialisised)[0]
return trimmed }
function getTime(){ // get a time of days
tims.cacheLength();arrayLenght= tims.cachedLength;
randm = eval('tims[' + randomNum(arrayLenght) + "]");
if(valid(randm))
greeting=formatGreting()
}
function regeExFromStr(string,opt){
return eval("/"+string+"/" +opt) // make regex from string
}
function randomNum(max){
// random * random is more random
return Math.floor(rand() * max*rand()) }
// make sure the string correct
function valid(str) {
valids= makeArray(tims.join('|'),timesCount)
tims.cacheLength();cachedLenght= tims.cachedLength;
hasValidated=false; // hasValidated
for(i=0; i< cachedLenght;i++)
if(!stringIsDifferent(eval("tims["+i+"]"),trimString(str)))hasValidated=true
return istrue(hasValidated)}
// stupid js has to trim
function trimString(str) {
l=0;
while(str.charCodeAt(l++)!=32)
return str.substr(0,l)
}
// found this on a side called thedailywtf.com always worked for me
function istrue(value){
bool = Boolean(value)
if(bool==true)
return true
else if(bool==false)
return false
else
return null}
// == is broken so well just use regex
function stringIsDifferent(a,b) {
ex=regeExFromStr("^"+b+"$","i")
same=ex.test(b)
return
istrue(same)
}
// length is slow
Object.prototype["initcaching"]=function(){
this.cachedLength =0;}
Object.prototype['cacheLength']=function() {
with (this) {
initcaching();
while(this[cachedLength])
cachedLength++ }}
getTime()
// print to brwoser
document.write(greeting)
PS: I've currently writing a guide about all common JS pitfalls, you might want to check it out.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// Forward declarations
struct HandleObj;
typedef struct HandleObj *Handle;
char* GetErrorString(Handle failed);
void DestroyObject(Handle obj);
Handle CreateTimeOfDayProvider(void);
Handle GetTimeOfDay(Handle timeOfDayProvider);
char* GetTimeOfDayName(Handle timeOfDay);
// Program
int main(int argc, char *argv[])
{
int argi = 0;
Handle todph, day;
char *name;
for(argi = 1; argi < argc; argi++) {
if(!strcmp(argv[argi], "-h") || !strcmp(argv[argi], "--help")) {
printf("Usage: ./greet [-h] [-v] [locale]\n");
printf(" -h, --help: Displays this help text.\n");
printf(" -v, --version: Displays version information\n");
return 0;
}
if(!strcmp(argv[argi], "-v") || !strcmp(argv[argi], "--version")) {
printf("0.1.0a\n");
return 0;
}
printf("Error: Unknown option \"%s\"\n", argv[argi]);
return 1;
}
if(!(todph = CreateTimeOfDayProvider())) {
printf("Could not create Time of Day Provider!\n");
printf("Reason: %s\n", GetErrorString(todph));
return 2;
}
if(!(day = GetTimeOfDay(todph))) {
printf("Could not get Time of Day!\n");
printf("Reason: %s\n", GetErrorString(day));
return 3;
}
if(!(name = GetTimeOfDayName(day))) {
printf("Could not get Time of Day object name!\n");
printf("Reason: %s\n", GetErrorString(day));
return 4;
}
printf("Good %s", name);
DestroyObject(todph);
DestroyObject(day);
return 0;
}
// Implementation Details
#define DAY_HANDLE 1
#define TIME_OF_DAY_PROVIDER_HANDLE 2
struct HandleObj
{
int objType;
void *objPTR;
char *error;
void (*Destructor)(void);
};
Handle CreateHandle(int objtype, void *objptr, void(*dtor)(void))
{
Handle obj = (Handle) malloc(sizeof(struct HandleObj));
obj->objType = objtype;
obj->objPTR = objptr;
obj->error = 0;
obj->Destructor = dtor;
}
void DestroyObject(Handle h)
{
if(h->Destructor) {
h->Destructor();
}
free(h->objPTR);
free(h);
}
#define OBJECT(type, code, handle, output) \
do { \
if(handle->objType != code) { \
handle->error = "Invalid operation for this handle"; \
return NULL; \
} \
output = (type*) handle->objPTR; \
} while(0);
typedef struct {
int timeIndex;
} DayObject;
typedef struct {
int seeed;
} TimeOfDayProviderObject;
Handle CreateTimeOfDayProvider(void)
{
TimeOfDayProviderObject *obj = (TimeOfDayProviderObject*) malloc(sizeof(TimeOfDayProviderObject));
obj->seeed = time(NULL) * 26 - 30;
return CreateHandle(TIME_OF_DAY_PROVIDER_HANDLE, obj, NULL);
}
Handle CreateTime(int timeIndex)
{
DayObject *time = malloc(sizeof(DayObject));
time->timeIndex = timeIndex;
return CreateHandle(DAY_HANDLE, time, NULL);
}
char *names[] = {"Morning", "Afternoon", "Evening", "Night"};
char* GetTimeOfDayName(Handle h)
{
DayObject *obj;
OBJECT(DayObject, DAY_HANDLE, h, obj);
return names[obj->timeIndex];
}
Handle GetTimeOfDay(Handle h)
{
TimeOfDayProviderObject *obj;
OBJECT(TimeOfDayProviderObject, TIME_OF_DAY_PROVIDER_HANDLE, h, obj);
srand(obj->seeed);
int value = rand();
obj->seeed = value;
return CreateTime(value % 4);
}
char* GetErrorString(Handle failed)
{
return failed->error;
}
Here we are. I use recursion, express all my numbers in their factorized form, and only output one char at a time. Unfortunately, the random number generator is simple.
#include <iostream>
#include <ctime>
using namespace std;
void startPutCharSequence(double currChar, double prevChar, double firstChar)
{
if (prevChar == 0)
{
putchar(currChar);
if(currChar / 11 == 7)
startPutCharSequence(3 * 37, currChar, currChar);
else if (currChar / 23 == 3)
startPutCharSequence(2 * 59, currChar, currChar);
else if (currChar / 13 == 5)
startPutCharSequence(2 * 3 * 17, currChar, currChar);
else if (currChar / 13 == 2 * 3)
startPutCharSequence(3 * 5 * 7, currChar, currChar);
}
else if (prevChar != 0 && currChar != 3)
{
putchar(currChar);
if(currChar == 3 * 37 && prevChar == 7 * 11 && firstChar == 7 * 11)
startPutCharSequence(2 * 3 * 19, currChar, firstChar);
else if (currChar == 2 * 3 * 19 && prevChar == 3 * 37 && firstChar == 7 * 11)
startPutCharSequence(2 * 5 * 11, currChar, firstChar);
else if (currChar == 2 * 5 * 11 && prevChar == 2 * 3 * 19 && firstChar == 7 * 11)
startPutCharSequence(3 * 5 * 7, currChar, firstChar);
else if (currChar == 3 * 5 * 7 && prevChar == 2 * 5 * 11 && firstChar == 7 * 11)
startPutCharSequence(2 * 5 * 11, currChar, firstChar);
else if (currChar == 2 * 5 * 11 && prevChar == 3 * 5 * 7 && firstChar ==7 * 11)
startPutCharSequence(103, 0 , 3);
else if(currChar == 2 * 59 && prevChar == 23 * 3 && firstChar == 23 * 3)
startPutCharSequence(101, currChar, firstChar);
else if(currChar == 101 && prevChar == 2 * 59 && firstChar == 23 * 3)
startPutCharSequence(2 * 5 * 11, currChar, firstChar);
else if(currChar == 2 * 5 * 11 && prevChar == 101 && firstChar == 23 * 3)
startPutCharSequence(3 * 5 * 7, currChar, firstChar);
else if(currChar == 3 * 5 * 7 && prevChar == 2 * 5 * 11 && firstChar == 23 * 3)
startPutCharSequence(2 * 5 * 11, currChar, firstChar);
else if(currChar == 2 * 5 * 11 && prevChar == 3 * 5 * 7 && firstChar == 23 * 3)
startPutCharSequence(103, 0, 3);
else if(currChar == 2 * 3 * 17 && prevChar == 13 * 5 && firstChar == 13 * 5)
startPutCharSequence(2 * 2 * 29, currChar, firstChar);
else if(currChar == 2 * 2 * 29 && prevChar == 2 * 3 * 17 && firstChar == 13 * 5)
startPutCharSequence(101, currChar, firstChar);
else if(currChar == 101 && prevChar == 2 * 2 * 29 && firstChar == 13 * 5)
startPutCharSequence(2 * 3 * 19, currChar, firstChar);
else if(currChar == 2 * 3 * 19 && prevChar == 101 && firstChar == 13 * 5)
startPutCharSequence(2 * 5 * 11, currChar, firstChar);
else if(currChar == 2 * 5 * 11 && prevChar == 2 * 3 * 19 && firstChar == 13 * 5)
startPutCharSequence(3 * 37, currChar, firstChar);
else if(currChar == 3 * 37 && prevChar == 2 * 5 * 11 && firstChar == 13 * 5)
startPutCharSequence(3 * 37, currChar, firstChar);
else if(currChar == 3 * 37 && prevChar == 3 * 37 && firstChar == 13 * 5)
startPutCharSequence(2 * 5 * 11, 0, 3);
else if(currChar == 3 * 5 * 7 && prevChar == 2 * 3 * 13 && firstChar == 2 * 3 * 13)
startPutCharSequence(103, currChar, firstChar);
else if(currChar == 103 && prevChar == 3 * 5 * 7 && firstChar == 2 * 3 * 13)
startPutCharSequence(2 * 2 * 2 * 13, currChar, firstChar);
else if(currChar == 2 * 2 * 2 * 13 && prevChar == 103 && firstChar == 2 * 3 * 13)
startPutCharSequence(2 * 2 * 29, 0, 3);
}
}
int main()
{
int start = 2 * 2 * 2 * 3 * 3;
putchar(--start);
putchar((start += (2 * 2 * 2 * 5)));
putchar(start);
putchar((start -= 11));
putchar((start -= 2 * 2 * 17));
srand((unsigned)time(0));
while(true)
{
int timeOfDay = rand() % 128;
if (timeOfDay == 11 * 7 || timeOfDay == 13 * 5 || timeOfDay == 3 * 23 || timeOfDay == 2 * 3 * 13)
{
startPutCharSequence(timeOfDay, 0, timeOfDay);
break;
}
}
putchar((start -= 19));
putchar((start -= 3));
return 0;
}
For your enjoyment...
<?php
$play = 71;
$ball = array(40,0,-11);
p($play,$ball);
$hello = 32;
p($hello,array());
$p = rand(1,4);
switch($p) {
case 1:
$dead = 77;
$beef = array(34,3,-4,-5,5,-7);
break;
case 2:
$dead = 65;
$beef = array(37,14,-15,13,-4,1,0,-1);
break;
case 3:
$dead = 69;
$beef = array(49,-17,9,-5,5,-7);
break;
case 4:
$dead = 78;
$beef = array(27,-2,1,12);
}
p($dead,$beef);
$peanut = 13;
$butter = array(-3);
p($peanut,$butter);
function p($place,$path) {
echo chr($place);
while (count($path)) { $x = array_shift($path); $place += $x; echo chr($place); }
}
An updated, condensed version... I actually don't see why Length is a requirement. I think it's trivially easy to maintain some of these answers (add a possible greeting, change the existing ones). You really think you'd have an easier time altering this?:
<?php
play(array(71,40,0,-11));
play(array(32));
p($hello,array());
$p = rand(1,4);
play(($p == 1 ? play(array(77,34,3,-4,-5,5,-7)) :
($p == 2 ? play(array(65,37,14,-15,13,-4,1,0,-1)) :
($p == 3 ? play(array(69,49,-17,9,-5,5,-7)) :
($p == 4 ? play(array(78,27,-2,1,12))
: die('RUN'))))));
play(array(13,-3));
function play($packet) {
if (count($packet) > 1) {
$packet[0] += $x = array_shift($packet);
echo chr($x);
play($packet);
} else echo chr($packet[0]);
}
Here's one from me, in PHP. There are at least a few WTFs in it, at least a few bugs, and way too much over-engineering. Enjoy...
<?php
class RandomString {
protected $options = array();
protected $lenght = 0;
public function __construct(array $options) {
$this->options = $options;
$this->length = count($options);
}
public function __toString() {
return Random::getArrayElement($this->options);
}
public function addString($string) {
$this->options = ArrayModifier::Add($this->options, $string);
$this->length = count($string);
}
public function removeString($string) {
$this->options = ArrayModifier::Remove($this->options, $string);
$this->length = count($string);
}
}
abstract class RandomStringFactory {
public static function make($options) {
return new RandomString(self::makeOptions($options));
}
protected static function makeOptions($options) {
if (is_array($options)) {
return $options;
} elseif (is_string($options)) {
$delimiter = self::detectDelimiter($options);
return explode($delimiter, $options);
} else {
return (array) $options;
}
}
protected static function detectDelimiter($string) {
$delims = array(',', ';', ':', '|', '&', '-', '+', '!');
foreach ($delims as $delim) {
if (strpos($string, $delim)) {
return $delim;
}
}
return ' ';
}
}
class RandomEnd extends RandomString {
public function __construct() {
parent::__construct(explode(',', 'Morning,Afternoon,Evening,Night'));
}
}
abstract class Random {
public static function getArrayElement(array $array) {
$length = count($array);
$key = self::getRandom(0, $length - 1);
$i = 0;
foreach ($array as $value) {
if ($i == $key) {
return $value;
}
$i++;
}
return end($array);
}
public static function getRandom($start, $end) {
$diff = $end - $start;
$seed = self::getRandomSeed();
return round($seed * $diff + $start);
}
public static function getRandomSeed() {
$t = microtime(true);
for ($i = 0; $i < 10000; $i++) {
$m = mt_rand(0, 10000);
if ($t % $m == mt_rand(0, 100)) {
$factor = ($m - $t) / ($t - $m);
$seed = mt_rand(0, 100000) / $factor;
$seed *= ($m - $t);
$stub = $t * 100000;
$stub += -1 * $m * 100000;
$scrum = $seed / $stub;
return $scrum;
}
}
return mt_rand(0, 10000) / 10000;
}
}
class ArrayModifier {
public static function add(&$array, $value) {
$newArray = $array;
$newArray[] = $value;
return $newArray;
}
public static function remove(&$array, $value) {
$newArray = array();
foreach ($array as $key => &$val) {
if ($val == $value) {
unset($array[$key]);
}
$newArray[$key] = $val;
}
return $newArray;
}
}
class RandomSentance {
protected $elements = array();
public function __construct(array $elements) {
$this->elements = $elements;
}
public function __toString() {
return implode(' ', $this->elements);
}
}
$sentance = new RandomSentance(
array(
RandomStringFactory::make('Good'),
RandomStringFactory::make('Morning,Afternoon,Night,Evening'),
)
);
echo $sentance;
The asker mentioned regular expressions, so clearly he is looking for an answer using regular expressions. I was baffled after I saw that most of the answers thus far totally fail to realize the power of regular expressions and embrace them.
Thus, my solution. Python code that generates random matches given a regular expression. And the output is totally random, I swear!
import random, time
def parse_regex(regex):
path = [('()', []), ('|', [])]
path[0][1].append(path[1])
i = 0
while i < len(regex):
char = regex[i]
if path[-1][0] in ('[]', '[^]'):
if char == ']' and path[-1][1]:
old2 = path.pop()
assert old2[0] in ('[]', '[^]')
elif char == '-' and len(path[-1][1]) and i+1 < len(regex) and regex[i+1] != ']':
tmp1 = path[-1][1].pop()
assert tmp1[0] is None
tmp1 = tmp1[1]
tmp2 = regex[i+1]
assert ord(tmp2) > ord(tmp1)
for tmp in range(ord(tmp1), ord(tmp2) + 1):
path[-1][1].append((None, chr(tmp)))
i += 1
else:
path[-1][1].append((None, char))
else:
if char == '(':
new1 = ('()', [])
new2 = ('|', [])
new1[1].append(new2)
path[-1][1].append(new1)
path.extend([new1, new2])
elif char == ')':
old2 = path.pop()
old1 = path.pop()
assert old2[0] == '|'
assert old1[0] == '()'
elif char == '|':
new2 = ('|', [])
old2 = path.pop()
assert old2[0] == '|'
path[-1][1].append(new2)
path.append(new2)
elif char == '[':
tmp = '[]'
if i+1 < len(regex) and regex[i+1] == '^':
tmp = '[^]'
i += 1
new = (tmp, [])
path[-1][1].append(new)
path.append(new)
elif char == '.':
path[-1][1].append(('.', None))
elif char in ('*', '+', '?'):
assert len(path[-1][1])
tmp = path[-1][1].pop()
path[-1][1].append((char, tmp))
else:
path[-1][1].append((None, char))
i += 1
assert len(path) == 2
return path[0]
def generate_match(regextree):
match = ''
if regextree[0] == '()':
regextree = random.choice(regextree[1])
match += generate_match(regextree)
elif regextree[0] == '|':
for item in regextree[1]:
match += generate_match(item)
elif regextree[0] == None:
match += regextree[1]
elif regextree[0] == '.':
match += random.choice([chr(i) for i in range(32, 127)])
elif regextree[0] in ('*', '+'):
if regextree[0] == '+':
match += generate_match(regextree[1])
# We favour shorter matches
while True:
if random.choice(['yes', 'yes', 'no']) == 'yes':
match += generate_match(regextree[1])
else:
break
elif regextree[0] == '?':
if random.choice(['yes', 'no']) == 'yes':
match += generate_match(regextree[1])
elif regextree[0] == '[]':
match += random.choice([generate_match(item) for item in regextree[1]])
elif regextree[0] == '[^]':
match += random.choice(list(set(chr(i) for i in range(32, 127)) - set(generate_match(item) for item in regextree[1])))
else:
raise
return match
t1 = time.time()
y, m, d = time.localtime(t1)[:3]
t2 = time.mktime((y, m, d, 0, 0, 0) + time.localtime(t1)[-3:])
t = int(t1 - t2)
# Can't rely on python setting the random seed randomly enough.
# Thus, we seed it with the help of cafebabe and current time.
random.seed((0xcafebabe ^ 0x4eb) + t / 21600)
print generate_match(parse_regex('Good (Morning|Afternoon|Evening|Night)'))