Кодування в пісні - Представлення музичної пісні на програмованій мові на ваш вибір [закрито]


13

Напишіть програму на обрану вами мову, яка під час читання - це пісня до пісні. Це повинна бути дійсна програма, яку можна компілювати та запускати без помилок. Хоча ви могли технічно надрукувати на екрані всі тексти пісень, вам рекомендується робити це зі стилем і уникати рядкових літералів, коли це можливо.

Зважаючи на те, що це важко саме по собі, ви можете написати один розділ кодової панелі, який не вважається читаним у тексті. Однак, як тільки починається блок коду, який слід читати як пісню до пісні, ви не можете перервати її, поки пісня не закінчена. Ви можете вказати початок і кінець коду пісні з коментарями. Будь ласка, вкажіть самі тексти пісень, як ви читали код. Ви можете бути "ліберальним" зі своєю інтерпретацією до тих пір, поки не будете занадто віддалятися від написаного, інакше це коштуватиме вам балів.

Часткова пісня пісні дозволена, хоча ви отримуєте подвійні бали за те, що слова є цілою піснею. Судження ділиться на 3 категорії:

  1. 10 балів - Оригінальність
  2. 10 балів - Трудність пісні
  3. 20 балів - Представлення цієї пісні в коді.

За кожне подання я дам вам свою оцінку в коментарі нижче. Якщо ви редагуєте свою відповідь, просто дайте мені індикатор коментарів, і я переоціню її відповідно. Однак, щоб бути справедливим, кожна повторна оцінка віднімає 2 бали від вашої загальної оцінки.

Прикладом може бути такий:

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();
    }
}

Що читається:

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

Мудрі хлопці, інструменти не дозволені. ;)


4
Це цікава концепція, і мені цікаво побачити результати, але це не дуже об'єктивно. Як можна визначити «складність» пісні? (тощо)
Гаффі

3
Дуже нагадує мені цього переможця
МОККЦ

@Gaffi, здебільшого довжина, але також простота. Прикладом пісні, яка набрала б 0, може бути ця пісня довжиною всього 6 слів .
Ніл

Як щодо HQ9програми 9? : P
Li-aung Yip

1
Підказка для кожного, хто намагається знайти підходящу пісню для кодування: "Втеча в порожнечу", здається, є багатообіцяючою назвою :) - lyricstime.com/sepultura-escape-to-the-void-lyrics.html
Крістіан Лупаску

Відповіді:


8

Пітон - 8 + 4 + 15 = 27 балів

Ось на декількох строфах з « Полювання на снайпер » Льюїса Керролла.
Він обчислює число, виходячи з алгоритму, запропонованого у вірші, і використовує його для доказу голосу джубюбу.

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))

Оригінальний текст:

"Беручи до уваги три - про
зручне число, яке потрібно
вказати - ми додаємо сім і десять, а потім множимо на
одну тисячу, зменшену на вісім.

"Результат, який ми продовжуємо ділити, як бачимо, на
дев'ять сотень дев'яносто два:
Потім віднімаємо сімнадцять, і відповідь повинна бути
точно і абсолютно правдивою.


Це приємно, мені це подобається. Originality: 8/10, Song difficulty: 4/10, Representation of that song in code: 15/20, Роблячи ваш остаточний рахунок 27. Ганьба ви не могли використовувати всю пісню.
Ніл

2
Я думаю, що критерій "вся пісня" має занадто велику вагу. Набагато легше було б вибрати пісню на одну лінію.
угорен

Зважаючи на те, що Полювання на Снарка триває понад 500 рядків, це справді було б вражаючим подвигом.
хлібниця

1
@breadbox, навіть одне пристосування було б вражаючим подвигом, все це було б агонією.
угорен

6

Пітон (8 + 7 + 15 = 30)

Дійсний код Python синтактично, хоча він не робить нічого корисного ;-)

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

Як це слід читати:

Я нічого не пам'ятаю.
Не можу сказати, правда це чи мрія.
Глибоко всередині я відчуваю крик.
Ця жахлива тиша зупиняє мене.
...
(Metallica - Один)


Нічого собі, складний вибір пісні, але дуже вразило, як ти це зняв. Originality: 8/10, Song difficulty: 7/10, Representation of that song in code: 15/20, Роблячи свій остаточний рахунок 30.
Neil

5

С

Дещо неохайно, я написав це приблизно за 15 хвилин для хихикань. Компілюється та працює з останньою версією G ++ / MinGW (хоча насправді не дуже багато). Ви можете самі це зрозуміти, я думаю:

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

Скала (48 = 2 * (7 + 4 + 13))

Це Linux! пісня.

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
}

Вихід:

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. Оскільки ви виставили всю пісню, це подвоює ваш рахунок, то це означає, що ваш кінцевий бал - 48. Приємний. :)
Ніл

1

PHP

Спробував мою улюблену пісню, «Сходи на небо».

$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

}

Як це читається:

Є дама, яка впевнена, що все, що сяє, - це золото,
і вона купує сходи на небо.
Коли вона туди потрапить, вона знає, якщо зірки все близько.
Словом вона може отримати те, за що прийшла.
О, о, вона купує сходи до неба.

На стіні вивіска, але вона хоче бути впевнена
: Тому що ви знаєте, що іноді слова мають два значення.
У дереві біля потоку стоїть пісня, яка співає.
Іноді всі наші думки прощаються.
О, це мене здивує,
о, це мене здивує.


1

С

Ось повна пісня.
Ви можете слухати його у світі мами Лізи .
Зауважте, що пісня включена як є, включаючи розділові знаки.

#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);}

Друкує число 4.


1

Рубін

Моє взяти якомога ближче представництво. З ланцюгом дзвінків Рубі це легко.

$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
}

Вихідні дані

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

Зробити

  1. Багаторядкові коми (аргументи)
  2. Багаторядкові точки (виклики методів)

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;

Так, я знаю, що я трохи обдурив, і я, можливо, мав членів, які також співали, який рядок також не так.


0

C - Пляшки пива

Складіть і запустіть це. Тексти текстів укладаються у вихідний код. Складіть і виконайте вихід, щоб отримати наступний рядок пісні. Коли написано "Час іти ....", тоді компілюйте та виконайте кількість пляшок, вказаних у командному рядку, наприклад:

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

Код, перевірений за допомогою 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
Я не вибачаюся за своє мистецтво ASCII!
Скізз

1
Досить вражаюче, але як це відповідає виклику? Я подумав, що ідея полягає в тому, що ви можете читати джерело як пісню.
ugoren

1
@ugoren: Скомпілюйте та запустіть виконуваний файл з одним параметром, початковою кількістю пива. Тоді програма виводить перший вірш пісні у якості вихідного коду (ну, текст у верхньому коментарі). Складіть висновок і запустіть ще раз, щоб отримати наступний вірш тощо.
Скізз

Дуже приємно, але ідея - це не програма, яка друкує пісню. Це програма, яка, читаючи її джерело, - це пісня.
угорен

0

Perl виконує Barnes & Barnes

З тих пір, як я вперше дізнався Perl, я хотів, щоб виправдати, щоб скористатися цим -Pваріантом. Сьогодні це виправдання нарешті надійшло:

#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

Запустіть його разом -M5.010із -Pопцією, наприклад:

$ perl -PM5.010 whenyoudie
goodbye
Hangup
$ 
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.