Coding in song - Rappresentazione di testi musicali in un linguaggio di programmazione a scelta [chiuso]


13

Scrivi un programma nella lingua di tua scelta che, quando letto, sono i testi di una canzone. si deve essere un programma valido che può essere compilato ed eseguito senza errori. Mentre potresti tecnicamente stampare sullo schermo tutti i testi, sei incoraggiato a farlo con stile ed evitando letterali di stringa ogni volta che è possibile.

Dato che questo è difficile da solo, ti è permesso scrivere una singola sezione di codice boilerplate che non conta per essere leggibile nei testi. Tuttavia, una volta che inizia il blocco di codice che deve essere letto come il testo di una canzone, non è possibile interromperlo fino al termine della canzone. È possibile indicare l'inizio e la fine del codice del brano con commenti. Si prega inoltre di specificare i testi stessi come si legge il codice. Puoi essere "liberale" con la tua interpretazione purché non ti allontani troppo da ciò che è scritto, altrimenti ti costerà punti.

Sono consentiti testi di canzoni parziali, anche se ottieni doppi punti per avere le parole di un'intera canzone. Il giudizio è diviso in 3 categorie:

  1. 10 punti - Originalità
  2. 10 punti - Difficoltà canzone
  3. 20 punti - Rappresentazione di quella canzone in codice.

Per ogni invio, ti darò il tuo punteggio in un commento qui sotto. Se modifichi la tua risposta, dammi solo un indicatore di commento e lo rivaluterò di conseguenza. Tuttavia, per essere onesti, ogni nuova valutazione sottrae 2 punti dal punteggio totale.

Un esempio potrebbe essere il seguente:

public class Song {
    public String play() {
        // Song begin
        try {
            if(this instanceof TheRealLife || this instanceof JustFantasy) {
                throw new InALandSlide();
            }
        } catch (InALandSlide e) {
        }
        return "No \"FromReality\"";
        // Song end
    }

    public static void main(String [] args) {
        Song song = new Song();
        song.play();
    }
}

Che viene letto:

Is this TheRealLife?
Or is this JustFantasy?
Caught InALandSlide.
No escape \"FromReality\"

Gli strumentali non sono ammessi, saggi. ;)


4
Questo è un concetto interessante e sono interessato a vedere i risultati, ma questo non è molto obiettivo. Come si determina la 'difficoltà' della canzone? (ecc.)
Gaffi,

3
Mi ricorda fortemente questo vincitore
IOCCC

@Gaffi, per lo più lunghezza, ma anche la parola. Esempio di una canzone che segnerebbe 0 potrebbe essere questa canzone è lunga solo 6 parole .
Neil,

Che ne dici del HQ9programma 9? : P
Li-aung Yip,

1
Suggerimento per chiunque cerchi di trovare una canzone adatta per la codifica: "Escape to the Void" sembra essere un titolo promettente :) - lyricstime.com/sepultura-escape-to-the-void-lyrics.html
Cristian Lupascu,

Risposte:


8

Python - 8 + 4 + 15 = 27 punti

Ecco un paio di stanze di The Hunting of the Snark di Lewis Carroll.
Calcola un numero, basato sull'algoritmo suggerito nel poema, e lo usa per dichiarare una prova della voce del jubjub.

class taking:
    def __init__(self, n): convenient.val = (n)
    def __enter__(self): pass
    def __exit__(self, type, value, traceback): pass
def a(x,y): x.val = y(x.val); return True
class We:
    def __init__(self): self.val=0
    def __add(self, y): return y+sum(self.x)
    def add(self, *x): self.x = x; return self.__add
    def multiply(self,x,by,diminished_by): self.val *= by-diminished_by
    def proceed2divide(self,x,by): self.val /= by
    def subtract(self,x): self.val -= x; return True
perfectly = lambda x: x and not not x
def must_be(x):
    if x: 
        print "\n".join(["Tis the %s of the Jubjub!"%["voice","note","song"][x%3] for x in range(out.val)])
        return out.val
out=convenient=as_you_see=we=then=the=We()
_ = exactly = 15
with\
\
    taking(3) as the_subject_to_reason_about:
    a(convenient, #2 state
    we.add(7,_ & 10)) and then.multiply(out,
    by=1000, diminished_by=8)

    the_result = we.proceed2divide(as_you_see,
    by=992)
    then.subtract(17) and the; answer = must_be(
    exactly and perfectly(True))

Il testo originale:

"Prendendo Tre come argomento della ragione di -
Un numero conveniente da dichiarare—
Aggiungiamo Sette e Dieci, e poi moltiplichiamo
per Mille diminuiti per Otto.

"Il risultato procediamo a dividere, come vedi,
per Nove e Novantadue:
Quindi sottrarre Diciassette e la risposta deve essere
esattamente e perfettamente vera.


È carino, mi piace. Originality: 8/10, Song difficulty: 4/10, Representation of that song in code: 15/20, Rendendo il vostro punteggio finale 27. La vergogna non si poteva usare tutta la canzone.
Neil,

2
Penso che il criterio "tutta la canzone" abbia un peso eccessivo. Sarebbe stato molto più facile scegliere una canzone di una riga.
ugoren,

Dato che The Hunting of the Snark è lungo più di 500 linee, sarebbe stata davvero un'impresa impressionante.
breadbox,

1
@breadbox, anche una singola misura sarebbe un'impresa impressionante, il tutto sarebbe un'agonia.
ugoren,

6

Python (8 + 7 + 15 = 30)

Codice Python valido in modo sintattico sebbene non faccia nulla di particolarmente utile ;-)

from sys import exit as stops ; import os
thing = [] ; me = can = remember = False ; this = open(__file__)
def terrible(v): return v

# ==== start song snippet

me = can = remember = not any(thing)
can = not this.tell(), [True, "dream"]
locals()["deep"] = {"down":{"inside":{"feel_to":"scream"}}}
if `this` + (terrible("silence")): stops(me)

# ===== end song snippet

Come dovrebbe essere letto:

Non ricordo niente.
Non posso dire se questo è vero o sogno.
Nel profondo mi sento urlare.
Questo terribile silenzio mi ferma.
...
(Metallica - One)


Caspita, scelta di brani difficili, ma molto colpito da come l'hai realizzato. Originality: 8/10, Song difficulty: 7/10, Representation of that song in code: 15/20, Rendendo il vostro punteggio finale 30.
Neil

5

C

Un po 'sciatto, ho scritto questo in circa 15 minuti per risatine. Compila e funziona bene con l'ultima versione di G ++ / MinGW (non fa molto, però). Puoi capirlo bene da solo, penso:

class Rick {

public:

    struct us { bool you; bool me; };

    bool giveYouUp()  { return false; }
    bool letYouDown() { return false; }
    bool runAround()  { return false; }
    bool desertYou()  { return false; }
    bool makeYouCry() { return false; }
    bool sayGoodbye() { return false; }
    bool tellALie()   { return false; }
    bool hurtYou()    { return false; }

    bool thinkingOf(bool whatImThinkingOf) { return whatImThinkingOf; }
    bool justWantTo(bool whatIWantToDo) { return whatIWantToDo; }
    bool tellYou(bool whatIWantToTellYou) { return whatIWantToTellYou; }

    void roll() {
        bool gonna = false;
        while (gonna) {
            giveYouUp();
            letYouDown();
            gonna = (runAround() && desertYou());
            makeYouCry();
            sayGoodbye();
            gonna = (tellALie() && hurtYou());
        }

        bool strangersToLove = true;
        us we = {!strangersToLove, !strangersToLove};

        bool knowTheRules = true;
        bool you = knowTheRules, I = knowTheRules;

        bool aFullCommitment = true;
        we.me = thinkingOf(aFullCommitment);

        int me = 0;
        Rick* guys[] = {this, nullptr, nullptr, nullptr, nullptr};

        bool howImFeeling = true;
        we.me = justWantTo(tellYou(howImFeeling));

        bool understand = true;
        while (we.you != understand) {
            we.you = understand;
        }
    }

};

int main() {
    Rick rick;
    rick.roll();

    return 0;
}

2

Scala (48 = 2 * (7 + 4 + 13))

È Linux! canzone.

object Song extends App {
  // Compose a song
  trait Compose {
    override def toString = {
      val token = """^.*\$(.*)\$.*$""".r
      val token(verse) = super.toString
      verse.replaceAll("([a-z])([A-Z])", "$1 $2").capitalize
    }
    def excl(ex: String) = println(this + ex)
    def !!(c: Compose) = { excl("."); c }
    def ***(c: Compose) = { excl("..."); c }
    def !(c: Compose) = { excl("!"); c }
    def *(c: Compose) = { excl(","); c }
    def ! = excl("!")
  }
  // It's linux  - lyrics
  case object ItBootsUpFine extends Compose
  case object AllOfTheTime extends Compose
  case object TuxThePenguinIsGreat extends Compose
  case object aPieInTheFace extends Compose
  case object ToTheManIHate extends Compose
  case object EveryoneKnowsItsLinux extends Compose
  case object StableForYouAndMe extends Compose
  case object ItsLinux extends Compose
  case object NoMoreBSODs extends Compose
  case object BetterThanNT extends Compose
  case object BestOfAllItsFree extends Compose
  case object FreeSoftwareForYouAndMe extends Compose
  case object LinuxGPLd extends Compose

  // Singer to sing a song
  def sing(song: => Unit) = { song }

  // Song begins
  sing {
      ItBootsUpFine!
      AllOfTheTime!!
      TuxThePenguinIsGreat!
      aPieInTheFace*
      ToTheManIHate***
      EveryoneKnowsItsLinux!
      ItsLinux!
      ItsLinux!
      StableForYouAndMe!
      ItsLinux!
      ItsLinux!
      NoMoreBSODs!
      ItsLinux!
      ItsLinux!
      BetterThanNT!
      ItsLinux!
      ItsLinux!
      BestOfAllItsFree!
      FreeSoftwareForYouAndMe***
      LinuxGPLd!
  }
  // Song ends
}

Produzione:

It Boots Up Fine!
All Of The Time.
A Pie In The Face,
Tux The Penguin Is Great!
To The Man IHate...
Everyone Knows Its Linux!
Its Linux!
Its Linux!
Stable For You And Me!
Its Linux!
Its Linux!
No More BSODs!
Its Linux!
Its Linux!
Better Than NT!
Its Linux!
Its Linux!
Best Of All Its Free!
Free Software For You And Me...
Linux GPLd!

Originality: 7/10, Song difficulty: 4/10, Representation of that song in code: 13/20. Dal momento che metti giù l'intera canzone, questo raddoppia il tuo punteggio, quindi significa che il tuo punteggio finale è 48. Bello. :)
Neil,

1

PHP

Ho provato la mia canzone preferita, Stairway to Heaven.

$GLOBALS['sign']= 'words';

class lady extends me // there is a lady
{
  function __construct(){   // who is sure
    global $glitters = 'gold'; // all that glitters is gold
    $buy('stairway_to_heaven'); // and shes buying the stairway to heaven
  }
  $know[] = 'stars are close'; // when she get's there she knows, the stars are close
  function word(){  // with a word she can get
    debug_backtrace(); // what she come for
  }

  $this->buy('stairway_to_heaven'); // and she's buying the stairway to heaven

  $sign = 'words'; // there is a sign on the door
  if(!$sign === $GLOBALS['sign']) // but she want to be sure, cause you know sometimes words have 2 meanings
    exit();

  in_array($tree / $brook, $songbird ? 'sings'); // (literal) in a tree by the brook, there is a songbird who sings

  mysql_real_escape_string($_GET['thoughts']); // sometimes all of our thoughts are misgiven
  for ($i=0;$i<2;i++)
    parent::wonder(); // makes me wonder , makes me wonder

}

Come viene letto:

C'è una signora che è sicura che tutto ciò che luccica è oro
E sta comprando una scala per il paradiso.
Quando arriva lì, sa se le stelle sono vicine
Con una parola può ottenere ciò per cui è venuta.
Ooh, ooh, e sta comprando una scala per il paradiso.

C'è un cartello sul muro ma lei vuole esserne sicura
perché a volte le parole hanno due significati.
In un albero vicino al ruscello, c'è un uccello canoro che canta, a
volte tutti i nostri pensieri sono incerti.
Ooh, mi fa meravigliare,
Ooh, mi fa meravigliare.


1

C

Ecco una canzone completa.
Puoi ascoltarlo nel mondo di Mama Lisa .
Nota che la canzone è inclusa così com'è, inclusa la punteggiatura.

#define breath,
#define smell breath
#define an;}Englishman; main(){printf("%d\n",sizeof
struct x{int
// Song starts here
Fee, fa, fie, fo, fum,
I smell the breath of an Englishman.
// Song ends here
I);}

Stampa il numero 4.


1

Rubino

La mia opinione sulla rappresentazione il più vicino possibile. È facile con il concatenamento delle chiamate di Ruby.

$lines = []

def thisline n=2
    caller(n).first.match(/:(\d+):/)[1].to_i
end

class Chain < Array
    def method_missing method, *args
        $lines[thisline] = Chain[first, self[1], [method, thisline, args]]
    end

    def -(arg)
        $lines[thisline] = Chain[' - ', thisline, self, arg]
    end

    def tokens
        if size < 3
            if first == :_
                []
            else
                [first.to_s.tr(?_, ?\s).strip]
            end
        elsif size < 4
            [first.to_s.tr(?_, ?\s)] + at(2).tokens
        else
            lhs = case el = at(2)
            when Chain then el.tokens
            when String
                el.empty? ? [?'] : [?', el, ?']
            end

            rhs = case el = at(3)
            when Chain then el.tokens
            when Range then el.first.tokens + ['... '] + el.last.tokens
            end

            lhs + [first.to_s.tr(?_, ?\s)] + rhs
        end
    end
end

def self.method_missing method, *args
    line = thisline(3)

    if args.length > 1
        newlines = args.first.is_a?(String) ? args.first.count(?\n) : 0
        $lines[line] = false
        $lines[line-newlines] = Chain[method, line, Chain[', ', line, *args]]
    else
        $lines[line] = Chain[method, line, *args]
    end
end

####################

The pest in_the eyes of death follows us
Through the dirty streets of blood
It begins to eat inside us, decaying_our_bones
How will we escape_if the void covers our lungs?
We are buried_in the spewed trash_for ourselves

Blood _, pain - nothing_to_say
Why then_- must_we_die?

Escape to the void
Escape to the void

I look at my face on the other side of the mirror
My face falls down_in pieces full of worms
I burst my rotten heart with my own hands
I'm dying and I can',t_help_myself

Blood _, pain - nothing_to_say
Why then_- must_we_die?

What have I been running from?
I'',m_not_guilty
You've shown me the worst way
Cause you',re_my_victim... the_next_one

The pest in_the eyes of death follows us
Through the dirty streets of blood
It begins to eat inside us, decaying_our_bones
How will we escape if_the void covers our lungs?
We are buried in_the spewed trash_for ourselves

Blood _, pain - nothing_to_say
Why then_ - must_we_die?

Escape to the void
Escape to the void

####################

$lines.drop_while {|line| !line }.each_with_index {|line, i|
    puts if line.nil?
    next if not line

    line = line.tokens
    line.map!.with_index {|el, j|
        punct = [', ', ' - ', '... ', ?']

        if line[j-1] == ?' and el == ', '
            ''
        elsif punct.include?(el) or punct.include?(line[j+1])
            el
        else
            el + ?\s
        end
    }

    puts line.join
}

Produzione

The pest in the eyes of death follows us 
Through the dirty streets of blood 
It begins to eat inside us, decaying our bones 
How will we escape if the void covers our lungs? 
We are buried in the spewed trash for ourselves 

Blood, pain - nothing to say 
Why then - must we die? 

Escape to the void 
Escape to the void 

I look at my face on the other side of the mirror 
My face falls down in pieces full of worms 
I burst my rotten heart with my own hands 
I'm dying and I can't help myself 

Blood, pain - nothing to say 
Why then - must we die? 

What have I been running from? 
I'm not guilty 
You've shown me the worst way
Cause you're my victim... the next one 

The pest in the eyes of death follows us 
Through the dirty streets of blood 
It begins to eat inside us, decaying our bones 
How will we escape if the void covers our lungs? 
We are buried in the spewed trash for ourselves 

Blood, pain - nothing to say 
Why then - must we die? 

Escape to the void 
Escape to the void

Fare

  1. Virgole multilinea (argomenti)
  2. Punti multilinea (chiamate di metodo)

0

T-SQL Bone Thugs-N-Harmony

DECLARE @line1 varchar(25);
DECLARE @line2 varchar(25);
DECLARE @line4 varchar(25);
DECLARE @line5 varchar(25);

SET @line1 = 'Wake up, wake up, wake up,';
SET @line2 = 'its the';
SET @line4 = 'to get up, get up get up';
SET @line5 = 'so cash your checks and get up';

SELECT @line1 as Layzie, @line2 as Bizzy,
CONVERT(date,DATEADD(day, -
(SELECT
DATEPART(day, GETDATE()) 
- 1), GETDATE())) as FirstOfTheMonth,
@line4 as Layzie, @line5 as Bizzy;

Sì, lo so che ho barato un po 'e potrei avere anche i membri che hanno cantato quella linea sbagliata.


0

C - Bottiglie di birra

Compila ed esegui questo. I testi vengono inseriti nel codice sorgente. Compilare ed eseguire l'output per ottenere la riga successiva del brano. Quando viene visualizzato "Time to go ....", compilare ed eseguire con il numero di flaconi specificato nella riga di comando, ad esempio:

cl prog.c
prog 32 > prog1.c
cl prog1.c
prog1 > .... etc

Il codice, testato usando VS2005: -

// Time to go to the shop and get some beer
//
//
//
//
// #####.#####.#####.#####.#####.#####.#####
// ##.#####.#####.#####.#####.#####.#####.##
// #####.#####.#####.#####.#####.#####.#####
// ##.#####.#####.#####.#####.#####.#####.##

char *z [] = {
"void l(char *s,int b){int i;printf(\"// \");for(i=0;i<b;++i)printf(s);",
"printf(\"\\n\");}\nint main(int argc, char *argv[]){\nint i,j,k,x=%d;",
"char*p;\nif(!x&&argc==2)x=atoi(argv[1]);\nif(!x){printf(\"// Time to ",
"go to the shop and get some beer\\n//\\n//\\n//\\n//\\n\");k=7;\n",
"}else{printf(\"// %%d bottles of beer on the wall, %%d bottles of beer",
".\\n\",x,x);printf(\"// Take one down and pass it round, \");\n",
"if(x>1)printf(\"%%d bottles of beer on the wall.\\n//\\n\",x-1);\n",
"else printf(\"no more bottles of beer on the wall.\\n//\\n\");\n",
"k=x>2?x:2;l(\"  ^   \",x);l(\" / \\\\  \",x);l(\"/   \\\\ \",x);",
"l(\"|   | \",x);l(\"|Duf| \",x);l(\"|   | \",x);l(\"----- \",x);}\n",
"for(i=0;i<4;++i){\nprintf(\"// %%s\", i&1 ? \"##.\" : \"\");\n",
"for(j=i&1;j<k;++j)\nprintf(\"%%s#####\",j!=(i&1)?\".\":\"\");\n",
"printf(\"%%s\\n\",i&1?\".##\":\"\");}\nprintf(\"\\nchar *z [] = {\\n\");\n",
"for(i=0;i<sizeof z/sizeof z[0];++i){\nprintf(\"\\\"\");\n",
"for(p=z[i];*p;++p)\nswitch (*p){\ncase '\\n':printf(\"\\\\n\");break;\n",
"case '\\\\':printf(\"%%c%%c\",92,92);break;\n",
"case '%%':printf(\"%%c\",37);break;\ncase '\"':printf(\"%%c%%c\",92,'\"');break;\n",
"default:printf(\"%%c\", *p);break;}\nprintf(\"\\\",\\n\");}\n",
"printf(\"};\\n\");\nfor(i=0;i<sizeof z/sizeof z[0];++i)\n",
"printf(z[i],x?x-1:0);}\n",
};
void l(char *s,int b){int i;printf("// ");for(i=0;i<b;++i)printf(s);printf("\n");}
int main(int argc, char *argv[]){
int i,j,k,x=0;char*p;
if(!x&&argc==2)x=atoi(argv[1]);
if(!x){printf("// Time to go to the shop and get some beer\n//\n//\n//\n//\n");k=7;
}else{printf("// %d bottles of beer on the wall, %d bottles of beer.\n",x,x);printf("// Take one down and pass it round, ");
if(x>1)printf("%d bottles of beer on the wall.\n//\n",x-1);
else printf("no more bottles of beer on the wall.\n//\n");
k=x>2?x:2;l("  ^   ",x);l(" / \\  ",x);l("/   \\ ",x);l("|   | ",x);l("|Duf| ",x);l("|   | ",x);l("----- ",x);}
for(i=0;i<4;++i){
printf("// %s", i&1 ? "##." : "");
for(j=i&1;j<k;++j)
printf("%s#####",j!=(i&1)?".":"");
printf("%s\n",i&1?".##":"");}
printf("\nchar *z [] = {\n");
for(i=0;i<sizeof z/sizeof z[0];++i){
printf("\"");
for(p=z[i];*p;++p)
switch (*p){
case '\n':printf("\\n");break;
case '\\':printf("%c%c",92,92);break;
case '%':printf("%c",37);break;
case '"':printf("%c%c",92,'"');break;
default:printf("%c", *p);break;}
printf("\",\n");}
printf("};\n");
for(i=0;i<sizeof z/sizeof z[0];++i)
printf(z[i],x?x-1:0);}

1
Non mi scuso per la mia arte ASCII!
Skizz,

1
Abbastanza impressionante, ma come si abbina alla sfida? Ho pensato che l'idea fosse di poter leggere la fonte come una canzone.
ugoren,

1
@ugoren: compila ed esegui l'eseguibile con un singolo parametro, il numero iniziale di birre. Quindi il programma emette il primo verso della canzone come codice sorgente (beh, i testi nel commento in alto). Compila l'output ed esegui di nuovo per ottenere il verso successivo e così via.
Skizz,

Molto bello, ma l'idea non è un programma che stampa la canzone. È un programma che, quando viene letta la sua fonte, è la canzone.
ugoren,

0

Perl esegue Barnes & Barnes

Da quando ho imparato Perl per la prima volta, ho voluto una scusa per usare l' -Popzione. Oggi è finalmente arrivata quella scusa:

#define cry $$
#define people $_
#define some kill
#define we people
#define whenyoudie END
sub yeah{}

# "When You Die", Barnes & Barnes

whenyoudie { you stop drinking beer }
whenyoudie { you stop being here }
whenyoudie { some people,cry }
whenyoudie { we=say "goodbye" }

                yeah

Eseguilo con -M5.010oltre -Pall'opzione, in questo modo:

$ perl -PM5.010 whenyoudie
goodbye
Hangup
$ 
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.