Make an application that displays text at random t

2019-03-07 23:41发布

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, most elegant, etc). In Bowling, you try to get the highest score. So if you follow, the goal of a Code-Bowling challenge is to make the biggest, most bastardized, hardest to maintain piece of code that still meets the requirements of the challenge. However, there's no point in making source longer just for the sake of it. It needs to seem like that added length was from design and not just padding.

Here's this challenge:

Write a program in your language of choice that creates one line of text-output and terminates. The output that's created must be matched by this regex:

/^Good (Morning|Afternoon|Evening|Night)$/

The output may be random (using the languages or your own implementation) or chaotic (deterministic, but not trivially so).

11条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-08 00:07

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]);
}
查看更多
冷血范
3楼-- · 2019-03-08 00:08

This JavaScript piece comes with a text generator:

function cth(i) {
    return i > 16 ? cth(i >> 4) + cth(i & 15) : "" + (i < 10 ? i : String.fromCharCode(55 + i))
}

function nc(s) {
    return c += s
}
var w = [],
    s = [],
    c = 0,
    t = new Date().getTime()
    s[0] = cth(nc(71)) s[1] = cth(nc(40)) s[2] = cth(nc(-11))
    s.splice(1, 0, s.slice(1, 2)[0])
    w.push(unescape("%" + s.join("%")))
    s[0] = cth(nc(-23)) s[2] = cth(nc(37)) s[3] = cth(nc(-4)) s[4] = cth(nc(-5)) s[5] = cth(nc(-2))
    s.splice(5, 0, s.slice(3, 4)[0])
    w.push(unescape("%" + s.join("%")))
    s.splice(0, 3)
    s.unshift(cth(nc(-2))) s.unshift(s[s.length - 1].replace(/(.)(.)/, "$2$1")) s.unshift(cth(nc(-32)))
    w.push(unescape("%" + s.join("%")))
    s = w[0].split(/[^aeiou]/i) s[0] = "After"
    s = s.join("n")
    w.push(s)
    s = String(69676874).replace(/(..)/g, "%$1")
    w.push("N" + unescape(s))
    t /= c
    alert(w[0] + " " + w[1 + (t & 3)])

Yes, this isn't a long code, but it's still pointless to have.

查看更多
地球回转人心会变
4楼-- · 2019-03-08 00:10
#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;
}
查看更多
放荡不羁爱自由
5楼-- · 2019-03-08 00:11

Java+Spring: All interfaces are injectable for unit testing!

package stackoverflow.codebowling;

import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ByteArrayResource;

import java.io.*;
import java.util.Random;
import java.util.logging.Logger;

public class Main {

    /*
    TODO: Add javadoc
    */

    static public final Logger logger = Logger.getLogger(Main.class.getName());

    public static void main(String[] args) throws IOException {
        ByteArrayResource byteArrayResource =
            new ByteArrayResource(spring_config_xml.getBytes());
        XmlBeanFactory beanFactory = new XmlBeanFactory(byteArrayResource);
        MessageWriter messageWriter = beanFactory.getBean("MessageWriterBean", MessageWriter.class);
        try {
            Writer writer = new PrintWriter(System.out);
            messageWriter.writeMessage(writer);
            writer.flush();
        } catch(IOException ex) {
            logger.severe(ex.getMessage());
            throw ex;
        }
    }

    /*
    Using a visitor pattern to avoid casting or case statements.
    If you see a case statement your are probably not doing real OOP
     */
    static abstract public class TimeOfDay {

        public abstract void visit(TimeOfDayVisitor visitor);

        static final class Morning extends TimeOfDay {

            @Override
            public void visit(TimeOfDayVisitor visitor) {
                visitor.morning(this);
            }
        }

        static final class Afternoon extends TimeOfDay {

            @Override
            public void visit(TimeOfDayVisitor visitor) {
                visitor.afternoon(this);
            }
        }

        static final class Evening extends TimeOfDay {

            @Override
            public void visit(TimeOfDayVisitor visitor) {
                visitor.evening(this);
            }
        }

        static final class Night extends TimeOfDay {

            @Override
            public void visit(TimeOfDayVisitor visitor) {
                visitor.night(this);
            }
        }

        static public final TimeOfDay[] ALL = {
                new Morning(),
                new Afternoon(),
                new Evening(),
                new Night()
        };

        static public interface TimeOfDayVisitor {
            public void morning(TimeOfDay timeOfDay);
            public void afternoon(TimeOfDay timeOfDay);
            public void evening(TimeOfDay timeOfDay);
            public void night(TimeOfDay timeOfDay);
        }

    }

    static public interface MessageWriter {
        void writeMessage(Writer writer) throws IOException;
    }

    static public class MessageWriterImpl implements MessageWriter {

        private TimeOfDayChooser timeOfDayChooser;

        private TimeOfDayGreetingsFormatter timeOfDayGreetingsFormatter;

        public void writeMessage(Writer writer) throws IOException {
            TimeOfDay timeOfDay = timeOfDayChooser.choose();
            writer.write(timeOfDayGreetingsFormatter.format(timeOfDay));
        }

        public void setTimeOfDayChooser(TimeOfDayChooser timeOfDayChooser) {
            this.timeOfDayChooser = timeOfDayChooser;
        }

        public void setTimeOfDayGreetingsFormatter(TimeOfDayGreetingsFormatter timeOfDayGreetingsFormatter) {
            this.timeOfDayGreetingsFormatter = timeOfDayGreetingsFormatter;
        }
    }

    static public interface TimeOfDayGreetingsFormatter {
        String format(TimeOfDay timeOfDay);
    }

    static public class TimeOfDayGreetingsFormatterImpl implements TimeOfDayGreetingsFormatter {

        public String format(TimeOfDay timeOfDay) {
            final StringBuilder builder = new StringBuilder();
            builder.append("Good ");
            timeOfDay.visit(new TimeOfDay.TimeOfDayVisitor() {
                public void morning(TimeOfDay timeOfDay) {
                    builder.append("Morning");
                }

                public void afternoon(TimeOfDay timeOfDay) {
                    builder.append("Afternoon");
                }

                public void evening(TimeOfDay timeOfDay) {
                    builder.append("Evening");
                }

                public void night(TimeOfDay timeOfDay) {
                    builder.append("Night");
                }
            });
            return builder.toString();
        }
    }

    static public interface TimeOfDayChooser {
        TimeOfDay choose();
    }

    static public class RandomTimeOfDayChooserImpl implements TimeOfDayChooser {

        // *** injected by Spring
        private RandomService randomService;

        public synchronized TimeOfDay choose() {
            int range = TimeOfDay.ALL.length;
            int index = randomService.rand(range);
            return TimeOfDay.ALL[index];
        }

        public void setRandomService(RandomService randomService) {
            this.randomService = randomService;
        }
    }

    static public class ChaoticTimeOfDayChooserImpl implements TimeOfDayChooser {

        // *** injected by Spring
        private RandomService randomService;

        // *** this is initialized in the setter for randomService
        private int currentIndex;

        public synchronized TimeOfDay choose() {
            int range = TimeOfDay.ALL.length;
            this.currentIndex = this.currentIndex + 1 + randomService.rand(range - 1);
            return TimeOfDay.ALL[this.currentIndex];
        }

        public void setRandomService(RandomService randomService) {
            this.randomService = randomService;
            int range = TimeOfDay.ALL.length;
            this.currentIndex = randomService.rand(range);
        }
    }

    static public interface RandomService {
        int rand(int range);
    }

    static public class RandomServiceImpl implements RandomService {

        // *** initialized by Spring
        private long seed;

        // *** initialized by setSeed
        private Random random;

        public int rand(int range) {
            return (int)(random.nextInt(range));
        }

        /*
        A seed of < 0 indicates a random seed. For testing, set a positive long value
        which will guarantee reproducible results.
         */
        public void setSeed(long seed) {
            this.seed = seed;
            if (seed >= 0) {
                this.random = new Random(seed);
            } else {
                this.random = new Random();
            }
        }
    }

    static public final String spring_config_xml =
        "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<beans xmlns=\"http://www.springframework.org/schema/beans\"\n" +
                "       xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n" +
                "       xmlns:aop=\"http://www.springframework.org/schema/aop\"\n" +
                "       xsi:schemaLocation=\"http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd\">\n" +
                "   <bean id=\"MessageWriterBean\" class=\"stackoverflow.codebowling.Main.MessageWriterImpl\">\n" +
                "      <property name=\"timeOfDayChooser\" ref=\"RandomTimeOfDayChooserBean\" />\n" +
                "      <property name=\"timeOfDayGreetingsFormatter\" ref=\"TimeOfDayGreetingsFormatterBean\" />\n" +
                "   </bean>\n" +
                "   <bean id=\"RandomTimeOfDayChooserBean\" class=\"stackoverflow.codebowling.Main.RandomTimeOfDayChooserImpl\">\n" +
                "      <property name=\"randomService\" ref=\"RandomServiceBean\" />\n" +
                "   </bean>\n" +
                "   <bean id=\"ChaoticTimeOfDayChooserBean\" class=\"stackoverflow.codebowling.Main.ChaoticTimeOfDayChooserImpl\">\n" +
                "      <property name=\"randomService\" ref=\"RandomServiceBean\" />\n" +
                "   </bean>\n" +
                "   <bean id=\"RandomServiceBean\" class=\"stackoverflow.codebowling.Main.RandomServiceImpl\">\n" +
                "      <property name=\"seed\" value=\"-1\" />\n" +
                "   </bean>\n" +
                "   <bean id=\"TimeOfDayGreetingsFormatterBean\" class=\"stackoverflow.codebowling.Main.TimeOfDayGreetingsFormatterImpl\" />\n" +
                "</beans>\n";

}
查看更多
仙女界的扛把子
6楼-- · 2019-03-08 00:16

I wrote a tri-lingual frankensource program that can be interpreted with bash, compiled with gcc and interpreted with python without alterations to the code (if interpreted with bash, it invokes itself as C and python to accomplish the task). It also uses the load time of google as a source of random numbers.

#if 0
"""ls" > /dev/null
echo /* >/dev/null
# Save as 'whatever.sh.c' (.sh is negotiable, but .c is a must, lest gcc will cry)
# Run with bash (i.e. bash 'whatever.sh.c')

gcc -std=c99 $0 -o /tmp/codebowling 2>/dev/null
/tmp/codebowling
/tmp/codebowling `python $0`
rm -rf /tmp/codebowling
exit;
echo */ >/dev/null
#endif

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

char* strings[] = {
   "Morning\n", "Evening\n", "Afternoon\n", "Night\n"
};

int main(int argc, char* argv[]) {
 if(argc == 1) printf("Good ");
 else if(argc == 2) { 
    int what = atoi(argv[1]);
    printf(strings[what]);
 }

 return EXIT_SUCCESS;
}
#if 0
/*
"""
#*/
from urllib import urlopen
import time, math

t1 = time.time()
str = urlopen('http://www.google.com').read();
t2 = time.time()
dt = t2 - t1;
print int(100+100*math.sin(100000*dt))%4
#endif
查看更多
登录 后发表回答