text:
Code Golf Bingo!
You are given a Bingo board and a list of calls.  You must print BINGO! as soon as your board wins the game.
Bingo boards look like this:

They will be specified like this:
14 29 38 52 74
4 18 33 46 62
7 16 * 60 71
9 27 44 51 67
12 23 35 47 73

Immediately following the board will be calls, like this:
B7
I29
G60
G51
O71
I23
I16
N38

You must echo the calls out to standard output until just after the call that makes you win (get a row, column, or 5-long diagonal all filled), then print BINGO!.
For the above example, print:
B7
I29
G60
G51
O71
I23
I16
BINGO!

Rules
Standard code-golf rules, shortest code wins.
Details
There will always be enough calls to guarantee you a Bingo.  There will be no duplicate numbers on the board, and no duplicate calls.  Boards will always have correctly matched numbers and letters (the B column contains only 1-15, the I column contains only 16-30, and so on), as will calls.  The one and only free space will always be in the middle, marked with * instead of a number.  Consuming and discarding calls from standard input after the winning call is allowed, but not required.
Make your own test cases!

Perl, 122 120 char
$b=join'. .
',map~~<>,0..4;while(<>){/(\d+)/;$b=~s/\b$1\b/*/;print;
$b=~/(\*\s(\S+\s){$_}){4}\*/&&die"BINGO!
"for 0..7}

Build the card in $b with two additional junky columns.
Replace the numbers that are called on the card with * and print the called number.
Then the last regular expression will evaluate to true when there are 5 regularly spaced *s on the board.

Ruby 1.9 (194, 130)
This probably isn't the most sensible way to check for empty columns, but it was the first thing I thought to try!  In particular, that #transpose costs a lot.
Either a blank line between the board and the numbers or fixed width fields when declaring the board would save a lot of characters.  I couldn't think of a really nice way to read exactly 5 lines.
b=(R=0..4).map{gets}.join.scan /\d+|\*/
loop{gets
puts$_
~/\d+/
(e=b.index$&)&&b[e]=?*
R.map{|y|$><<:BINGO!&&exit if R.map{|x|[b[5*x+y],b[5*y+x],b[y<1?x*6:4*x+4]]}.transpose.any?{|a|a==[?*]*5}}}

EDIT: 130 character solution using the regular expression technique from mob's perl answer:
b=(0..4).map{gets}*'~ ~ '
loop{gets
puts$_
~/\d+/
b[/\b#$&\b/]=?*
7.times{|i|$><<:BINGO!&&exit if b=~/(\*\s(\S+\s){#{i}}){4}\*/m}}

C# – 536
(OK, this is probably not the most suitable language for that, but anyway…)
using System;using System.Collections.Generic;using System.Linq;class C{static void Main(){var s=Enumerable.Range(1,12).Select(_=>new HashSet<string>()).ToList();var b=Enumerable.Range(1,5).Select(_=>Console.ReadLine().Split(' ')).ToList();int i;for(i=0;i<5;++i){for(int j=0;j<5;++j){s[i].Add(b[i][j]);s[i+5].Add(b[j][i]);}s[10].Add(b[i][i]);s[11].Add(b[4-i][i]);}while(i>0){var l=Console.ReadLine();Console.WriteLine(l);l=l.Substring(1);foreach(var x in s){x.Remove("*");x.Remove(l);if(x.Count==0){Console.WriteLine("BINGO!");i=0;}}}}}

Formatted and commented:
using System;
using System.Collections.Generic;
using System.Linq;

class C
{
    static void Main()
    {
        // all possible winnable five-item sets – any one of them need to be emptied to win
        var s = Enumerable.Range(1, 12).Select(_ => new HashSet<string>()).ToList();
        // read the board from input to a list of arrays of numbers
        var b = Enumerable.Range(1, 5).Select(_ => Console.ReadLine().Split(' ')).ToList();
        int i;
        // split the board into the winnable sets
        for (i = 0; i < 5; ++i)
        {
            for (int j = 0; j < 5; ++j)
            {
                // sets 0–4 represent rows
                s[i].Add(b[i][j]);
                // sets 5–9 represent columns
                s[i + 5].Add(b[j][i]);
            }
            // set 10 represent one diagonal
            s[10].Add(b[i][i]);
            // set 11 represent the other diagonal
            s[11].Add(b[4 - i][i]);
        }
        while (i > 0)
        {
            // read and echo another input
            var l = Console.ReadLine();
            Console.WriteLine(l);
            // ignore the initial letter – we are guaranteed it is correct, anyway
            l = l.Substring(1);
            // remove the number from all sets
            foreach (var x in s)
            {
                x.Remove(l);
                // also remove the center * (inside the loop just to shave off a few characters)
                x.Remove("*");
                // if any set became empty, we won!
                if (x.Count == 0)
                {
                    Console.WriteLine("BINGO!");
                    // ensure the loop will stop (might not be necessary per the rules, but anyway)
                    i = 0;
                }
            }
        }
    }
}

Given the long, long, long overdue announcement of Rebol's impending release as open source software, I returned to my pet dialect to solve this Bingo problem.  I may soon be able to distribute Rebmu as its own, teensy GPL package.  :)

Rebmu 88 characters
In the compact notation:
rtZ5[GisGpcRaZisGaAPgPCaSB6zAPv'*]l5[AgL5[apGfAsk+A5]]hd+Gu[raGin-NTrM'*fisGv5]p"BINGO!"

The dialect uses a trick I call mushing which is explained on the Rebmu page.  It's "legit" in the sense that it doesn't cheat the parser; this is valid Rebol...and can actually can be freely intermingled with ordinary code as well as (ahem) "long-form" Rebmu...which BTW would be 141 characters:
[rt z 5 [g: is g pc r a z is g a ap g pc a sb 6 z ap v '*] l 5 [a: g l 5 [ap g f a sk+ a 5]] hd+ g u [ra g in- nt r m '* fis g v 5] p "BINGO!"]
(Given that I claim the compression is a trick that one can do without the help of automation or compilation, I actually develop the code in the mushed form.  It's not difficult.)
It's actually quite simple, nothing special--I'm sure other Rebol programmers could shave things off.  Some  commented source is on GitHub, but the main trick I use is to build all the possible solutions in a long series ("list", "array", what-have-you).  I  build the diagonal solutions during the input loop, as it takes five insertions at the head and five appends at the tail to make them...and there's already a five-iteration loop in progress.
The whole thing easily maps to Rebol code, and I haven't yet thrown any "matrix libraries" into Rebmu with transposition or other gimmicks that seem to come up often.  Someday I will do that but for now I'm just trying to work relatively close to the medium of Rebol itself.  Cryptic-looking things like:
 [g: is g pc r a z is g a ap g pc a sb 6 z ap v '*]

...are rather simple:
 [
     ; assign the series pointer "g" to the result of inserting
     ; the z'th element picked out of reading in some series
     ; from input that was stored in "a"...this pokes an element
     ; for the forward diagonal near the front of g
     g: insert g (pick (readin-mu a) z)

     ; insert the read-in series "a" from above into "g" as well,
     ; but *after* the forward diagonal elements we've added...
     insert g a

     ; for the reverse diagonal, subtract z from 6 and pick that
     ; (one-based) element out of the input that was stored in "a"
     ; so an element for the reverse diagonal is at the tail
     append g (pick a (subtract 6 z))

     ; so long as we are counting to 5 anyway, go ahead and add an
     ; asterisk to a series we will use called "v" to search for
     ; a fulfilled solution later
     append v '*
 ]

Note: Parentheses added above for clarity.  But Rebol programmers (like English speakers) generally eschew the application of extra structural callouts for indicating the grammar in communication...rather save them for other applications...
Just as an added bonus to show how interesting this actually is, I'll throw in some mix of normal code to sum the board.  The programming styles are actually...compatible:
rtZ5[GisGpcRaZisGaAPgPCaSB6zAPv'*]
temp-series: g
sum: 0
loop 5 * 5 [
    square: first temp-series
    if integer! == type? square [
        sum: sum + square
    ]
    temp-series: next temp-series
]
print ["Hey grandma, the board sum is" sum]
l5[AgL5[apGfAsk+A5]]hd+Gu[raGin-NTrM'*fisGv5]p"BINGO!"

That's valid Rebmu as well, and it will give you a nice board sum before playing Bingo with you.  In the example given, it says Hey grandma, the board sum is 912.  Which is probably right.  But you get the point.  :)

Mathematica 250
Disclosure: I assumed that the input was given in lists which are far more natural to use for Mathematica. So,with b representing the board and c representing the calls,
b//Grid
c//Column

If the input were to be in strings, the code would grow by about 30 characters.  (I'll later include that variation.)
Code
y = ReplacePart[ConstantArray[0, {5, 5}], {3, 3} -> 1]; d = Diagonal;
t := Tr[BitAnd @@@ Join[y, Transpose@y, {d@y}, {d[Reverse /@ y]}]] > 0;
r@i_ :=(y = ReplacePart[y, Position[x, ToExpression@StringDrop[i, 1]][[1]] -> 1];
Print@If[t, Column[{i, "BINGO!"}], i])
n = 1; While[! t, r@c[[n]]; n++]

B7
I29
G60
G51
O71
I23
I16
BINGO!

Python 249
R=raw_input;F=B=[[[x,0][x=='*']for x in row]for row in[R().split()for i in'11111']];A=any
while all([all(map(A,B)),all(map(A,zip(*B))),A(F[::6]),A(F[4:24:4])]):c=R();print c;C=c[1:];B=[[[x,0][x==C]for x in row]for row in B];F=sum(B,[])
print'BINGO!'

Usage:
$ ./bingo.py < bingo.txt
B7
I29
G60
G51
O71
I23
I16
BINGO!

You could replace row by a one-char name. Untested: try i in'*'*5] and replace [x=='*'] with [x==i].

APL (82)
{(D≡(⍵∨⌽⍵)∧D←=/¨⍳⍴⍵)∨∨/(∧⌿⍵)∨∧/⍵:'BINGO!'⋄∇⍵∨B=⍎1↓⎕←⍞}0=B←↑{⍎(K,K)[⍞⍳⍨K←11↑⎕D]}¨⍳5

{...}¨⍳5: do 5 times:
⍎(K,K)[⍞⍳⍨K←11↑⎕D]: read a line (⍞) and map all characters that aren't digits or space to 0, then evaluate the line.
B←↑: turn it into a matrix (5x5 if the input was correct), and store in B.
{...}0=B: the starting board has a 1 in the free space (0) and 0 in the other spaces.
(D≡(⍵∨⌽⍵)∧D←=/¨⍳⍴⍵)∨∨/(∧⌿⍵)∨∧/⍵: if a line, a column, or a diagonal is filled:
'BINGO!': then output BINGO
∇⍵∨B=⍎1↓⎕←⍞: otherwise, read a line (⍞), echo it (⎕←), drop the first character (1↓), evaluate it to get a number (⍎), see where it occurs on the board (B=), mark it (⍵∨), and try again (∇).

K, 114
Given the board b and the calls c
b{-1@y;a:(5*!5)_@[,/x;&(,/x)~\:1_y;:;"*"];$[max{max@min'"*"=,/'x}@/:(a;a ./:/:+:'(r;)'(r;|:r:!5));'"BINGO!";];a}/c

.
k)b
"14" "29" "38" "52" "74"
,"4" "18" "33" "46" "62"
,"7" "16" ,"*" "60" "71"
,"9" "27" "44" "51" "67"
"12" "23" "35" "47" "73"
k)c
"B7"
"I29"
"G60"
"G51"
"O71"
"I23"
"I16"
"N38"
k)b{-1@y;a:(5*!5)_@[,/x;&(,/x)~\:1_y;:;"*"];$[max{max@min'"*"=,/'x}@/:(a;a ./:/:+:'(r;)'(r;|:r:!5));'"BINGO!";];a}/c
B7
I29
G60
G51
O71
I23
I16
'BINGO


text:
m3ph1st0s's programming puzzle 1 (C++)
This is the first of a series of C++ puzzles for you. Hope you will enjoy.
So, puzzle no.1:
Given the following program:
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}

Insert some code on a single new line anywhere inside the program so that the output will be 0. The new line will contain AT MOST 18 characters (including spaces), and the rest of the lines will remain unmodified.
 To be clear, here is an example of a valid new code:
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   int* p = NULL;
   const float c=0.5;
   std::cout << a/b-a*c;
}

A new line with 15 characters was inserted so it's ok. However it does not solve the problem.
If this is too simple for you, don't worry, more is coming!!

I'm very happy someone posts a C++ question occasionally! I mean, with all the puzzles where a C++ solution would be 20 or 30 lines, then people posting solutions in J or K or Golfscript becomes frustrating after a while.

Does the result have to be valid, well-defined C++ or can it use UB? (But like Mr Lister noted, the original code isn’t even valid C++.)

@KonradRudolph - I don't know what IDE you use, I used DevC++ and it worked fine, so i wouldn't really say it's not valid C++ :) And the result has to be valid also, yes.

it is not valid. main must return int (read the c++ standard)

we are missing the point here. put an int and a return 0 if you mind, I didn't.

@Bogdan: Dafuq? For one, DevC++ is so unspeakably ancient, it's output is irrelevant. And secondly, whether or not any given compiler in any given configuration at any time targetting any OS accepts it does not make it valid C++.

Nice task, but the limit of only 18 characters forbids a lot of creative solutions. What's the point? It's obvious that those short #define ones work, but they aren't really the most interesting ones, are they?

While I find the idea very nice, there is no scoring criteria.

Hi everybody, thanks for all the feedback and the advice, since this was my first post I did make some mistakes (like ignoring the int and not mentioning 0 as the ONLY output) but I promise I'll learn out of your advice and next time it will be more precise! Cheers

@leftaroundbout: I limited the size of the line because I wanted to deny the most obvious solution: std::cout<<0; exit(0);

@BogdanAlexandru: Maybe it would be better to forbid it more explicitly, i.e. "the main function must run all of its body" or something?

#define int float

should work as well and is the same length.

this is what I had in mind when I first came with the idea

#define int float is actually undefined behavior. You are not allowed to give keywords new meaning.

Fred, can you cite your sources? The GCC cpp docs say "You may define any valid identifier as a macro, even if it is a C keyword."

@Dan: The C++ Standard forbids it.

@DeadMG Well, it doesn't forbid it, as the standard does not forbid UB. But you end up with undefined behaviour...

should work as well and is the same length error:
'::main' must return 'int' (minGW 4.4) but #define float int works fine

You'd have to make it the first line of your main, after main is defined...

@Dan In such case it works, sorry.

I tried this. It works as long as it is defined after int main().

It may be UB, but several popular compilers support it anyway.  I've done #define int ERROR to force myself to use the equivalent of int32_t instead of built-in types.  By the time I got around to int main(), I had forgotten about the macro and wondered why the heck my code wouldn't compile.

We can get rid of a=1 by moving it into another scope:
#include <iostream>
main()
{
int a=0;if(0)
    const int a=1;
    const int b=2;
    const float c=0.5;
    std::cout << a/b-a*c;
}

This is I think 13 characters. Or better yet get a new a that also results in 0:
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
if(int a=2)
   std::cout << a/b-a*c;
}

That's 11 characters

#include <iostream>
main()
{
   const int a=1;
#define a 0
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}

1 new line, 12 new chars

That's what I wanted to submit... +1 for you.

My first idea when read the question)))

So, #define a 0, Done. I saw that was posted - unsurprisingly.
Surprisingly, this wasn't posted:
#include <iostream>
main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout<<0||
   std::cout << a/b-a*c;
}

14 chars
That should do, right?

#include <iostream>
main()
{
const int a=0;//\
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}

17 chars.
By the way, the original program doesn't compile under MSVC, which complains that main doesn't have a return type.

int a=0;//\ will also do the trick

Absolutely. But is this a "shortest line wins" kind of contest?

I thought so, but it's not. Nice trick by the way

Yes, shortest solution wins on codegolf SE. see faq

Hi, like I said I used DevC++ so I didn't mind about main's return type :)

@BЈовић the FAQ says the shortest solution wins for actual code-golf questions. This question is not clearly a code-golf question.

multi-line comment - great trick!

18, including newline
#define float int

I'm not really sure this works...ur declaring c as a float and initializing it with 0.5

Which will truncate to zero.

you're right, funny thing I've never come across initializing an int with decimal value, I'd thought it would be compiler error, but it only issues a warning

@BogdanAlexandru take a gander at the C++ standard, it specifically details the implicit conversion at play here.

Note that although all compilers allow this, the standard prohibits redefining keywords (and float is a keyword).

#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   1?std::cout<<0:
   std::cout << a/b-a*c;
}

15 chars.

will output more than a "0"

why the ternary operator wouldn't work?

#include <iostream>
main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
#define a 0;1
   std::cout << a/b-a*c;
}

14 characters.

#include <iostream>
main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
std::cout<<0;//\
   std::cout << a/b-a*c;
}

It's 17 characters so it just fits.

#include <iostream>
main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   return puts("0");
   std::cout << a/b-a*c;
}

17 chars.

Best solution yet, because it flies in the face of anything related to C++.

`puts´ was not declared in this scope

@shiona what compiler are you using?

@Ashrr gcc (g++) 4.5.4

If you use return write(1,"0",1); it compiles under g++ ok

@gnibbler it's too long for solution, though.

Don't think, this code returns 0. But you can replace space via exclamation mark. Anyway, I'm not sure when puts returns zero.

I do not know C++, however based on the question, couldn't you just input a line to simply output 0? the question specifies the output should be 0, it does not specify you must CHANGE the output to 0.
std::cout << 0

(I have 0 clue on C++, perhaps somebody can use this concept though)

Oh well, the output should be just 0, I thought it was obvious, otherwise there would be no puzzle, would it?

@BogdanAlexandru You will find that exploiting a poorly written question is a common technique to solving these puzzles. If you want to prevent users from taking these shortcuts, spend a few extra minutes analyzing your own question and try to remove any potential ambiguity.

12 chars, similar to mob's solution
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
#define a b
   std::cout << a/b-a*c;
}

other combinations also work, like #define a c or #define c 0

I know it's not code-golf, but I seem to be wearing that hat today!
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;

--a;
   std::cout << a/b-a*c;
}

five chars, including the newline;

This does not compile, because a is const.

Oops, I should have given it to a compiler!  :-(

c++ whatever...
echo "0"; exit
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}

run via:
sh mp.cpp

Nice try but violates the requirement: valid C++.

A variant on Mr Lister's answer but slightly less obvious.
#include <iostream>
int main()
{
   const float a=1; //??/
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}

#include <iostream>
int main()
{
int a;if(a)
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}

How about these 11 chars...

The problem here is that the int a before the if is not being initialized, so a could have any value.

This is undefined, you’re using an uninitialised value for a.

#define a 0

http://codepad.org/N06weGJc
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
#define a 0
   std::cout << a/b-a*c;
}

Ups.. Posted the answer before looking the others. There is already the same answer: http://codegolf.stackexchange.com/a/8507/32091

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
The Major-Minor Dichotomy
Given a list of chords label them as either 'Major' or ' Minor'.
Input
Input will be a list of chords, one per line, made up of 3 notes separated by a space. Each note will consist of the note name in uppercase (A-G) and an optional accidental (# or b). Chords may be in any inversion (i.e. the notes may be in any order).
Output
If the chord is major, output 'Major'. If the chord is minor, output 'Minor'. If the chord is neither major nor minor, output a blank line.
Example
Input
C E G
F Ab C
C Eb Gb
E G B
Db F Ab
Bb G D
D A Gb

Output
Major
Minor

Minor
Major
Minor
Major

Test scripts
As in some of my past questions, I've once again butchered some test scripts originally created by Joey and Ventero to provide some test cases for this question:

bash
Powershell

Usage: ./test [your program and its arguments]
Rewards
Each entry which I can verify that meets the spec, passes the tests and has obviously had some attempt at golfing will receive an upvote from me (so please provide usage instructions with your answer). The shortest solution by the end of 13/10/2012 will be accepted as the winner.
A little theory
For those of you with no musical theory knowledge here's enough information for you to be able to compete.
A major or minor chord is made up of three notes which are separated by a specific pattern of semitones. If we consider the root (bottom note) of the chord to be 0, then a major chord is the pattern 0-4-7 and a minor chord is the pattern 0-3-7. Things are made more awkward by the fact that some notes are a semitone apart and some are a tone apart. The spread of semitones from Ab-G# is as follows:
G#/Ab A A#/Bb B/Cb B#/C C#/Db D D#/Eb E/Fb E#/F F#/Gb G G#/Ab
  0   1   2    3     4    5   6   7    8     9    10  11  12

G#/Ab means that that G# is the same note as Ab. From this we can see that the chord Ab C Eb is a major chord, and that Ab Cb Eb is minor.
To complicate matters further, the chord Eb Cb Ab is considered to be the same as Ab Cb Eb, Cb Eb Ab and Cb Ab Eb and so on. Every one of these variations is still a minor chord.

I think your bash tester needs inputs and expected answers swapped.

@flodel Yes, you're right. Sorry about that, I've corrected it now. I'll need to check that the Powershell test script doesn't have the same problem too.

GolfScript, 83 chars
n%{' '%{1\{'A#BC D EF G'?+}/.}%$(+2/{~- 12%}%.(+.(+]$0=.$]10,7>?'MMaijnoorr

'>2%}%

This is a quick first solution; I'm sure this can be golfed further.  Passes the bash test suite, after fixing the bug pointed out by flodel in the comments.
Edit 1: Saved 5 chars with a shorter way to recognize the canonicalized major and minor chord patterns.
Edit 2: Saved 2 more chars with more compact output encoding inspired by grc's solution.  (Thanks!)  As a side effect, the code now prints an extra blank line after the output, but the test harness seems to accept that, so I guess it's OK. :)
Here's how it works:

The outer loop n%{ }%n* just splits the input into lines, runs the code inside the braces for each line and joins the results with newlines.
' '% splits each line into an array of notes.  For each of those notes, 1\{'A#BC D EF G'?+}/ then converts that note into a semitone number by searching for each of its characters in the string 'A#BC D EF G' and adding up the positions (which will be -1 for any character not found in the string, notably including b).  (I'm sure I've seen this trick used before.)  Finally, the . duplicates each number, so that, at the end of the loop, e.g. the input F Ab C has been turned into [9 9 0 0 4 4].
We then sort the notes with $, move the first note to the end with (+, and split the array into pairs with 2/, so that it now looks e.g. like [[9 0] [0 4] [4 9]].  Then {~- 12%}% maps each pair of notes into its difference modulo 12, turning our example array into [9 8 7].
Next, .(+ makes a copy of the array and rotates its elements left by one position.  We do this twice and collect the copies into an array with ], so that our example now looks like [[9 8 7] [8 7 9] [7 9 8]].
We then sort this array of arrays with $ and take the first element — in this case [7 9 8] — with 0=.  We then make a copy of this array (.), sort it ($), collect both the unsorted and the unsorted array into another array of arrays (]), and search for the first occurrence of the array [7 8 9] (which is written as 10,7> to save two chars) in it.
This gives us either 0 (if the unsorted array was [7 8 9], and thus the chord is major), 1 (if the unsorted array was a permutation of [7 8 9], which, given that its first element must be smallest, can only be [7 9 8], making the chord minor) or -1 (if even the sorted array does not equal [7 8 9]).
This number is then used as a starting index into the string "MMaijnoorr\n\n" (where the \ns are given as actual linefeeds in the code), from which we take that character and every second subsequent one as the output.  If the index is -1, we start from the last character of the string, which is just a line feed.

Nice explanation. I'm having the same difficulty I always seem to have with GolfScript - I can invoke it a line at a time to test with echo "G# B# Eb" | ruby golfscript.rb ilmari.gs but how do I run the test script on it? I tried ./test ruby golfscript.rb ilmari.gs but it wasn't having any of it. (I've already given you a +1 because it obviously works, but I'm just curious)

@Gareth: Looks like that's a bug in the bash test script -- it doesn't handle multiple arguments right. To fix it, replace args="$@" with args=("$@") and got=$("$cmd" "$args") with got=$("$cmd" "${args[@]}").  (Or just make golfscript.rb executable and run it as ./test ./golfscript.rb chords.gs.)

Python, 160
f='A#BC D EF G3453543'.find
try:
 while 1:x,y,z=sorted(map(lambda x:f(x[0])+f(x[1:])+1,raw_input().split()));print'MMianjoorrr'[f(`y-x`+`z-y`)/14:-1:2]
except:0

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
m3ph1st0s's programming puzzle 2 (C++): "Call hard!"
I am back with a brand new puzzle for C/C++ addicts. Following the feedback received on the 1st puzzle, this time I will try to make the requirements crystal clear and to provide a perfectly valid code.
Here is the problem.
Given the following code:
#include <iostream>

char message[6]="hello";

void print_hello_message() {
   std::cout << message;
}

int main() {
   char* q = &message[0];

   // insert your code here
}

You are required to insert two more lines where the comment specifies in order to make the program print "hello" and nothing more, with the following restrictions:

the first line will NOT call any function, including cout

the second line will contain AT MOST 5 letters (and as many other symbols as you want)

the first line may contain new variable declarations but may not initialize them

the symbols # and / will not be used at all.

no logical operators will be used
The shortest code wins!

Does cout count as a function call ?

Yes of course. To make it clear I'll edit now and specify. Thanks for asking.

A tip for the next quiz: Please only allow standard portable C++ code. The workaround with function pointers is implementation defined on whether it actually works or not.

But cout isn't a function call. << is a function call, when applied to cout.

In thinking about it some more, the problem states "insert two more lines where the comment specifies" not "statements". Taking that into consideration, here is another shorter answer (though it depends on how you define "the first line will NOT call any function, including cout"):
std::
cout<<q;

The first line qualifies which cout will be used, and the second line includes the actual operator that results in calling operator<< for the std::ostream & const char* operands.

This is also correct and another way around my solution. In the beginning the first rule stated that the first line must end with ; but I thought about it more and decided to let people get creative and deliver two line statement.

Your submission is the shortest so you won it!

I would have sworn you gave the win to someone else. Not that it really matters, no money on the line, but thanks! :)

In thinking about it, even if you had left in the "first line must end with ;" rule, this solution would have still qualified with the addition of "//;" to the end of the first line.

If I understand what you're asking for, this is what I'd add:
using std::cout;
cout<<q;

The first line brings std::cout into the current name space so that we can use it without qualification. using namespace std; would have worked as well but is longer so I didn't use it.
The second line uses the limit of five letters (plus three symbols and no necessary white space beyond whatever the platform uses to denote end of line).
There may be something shorter, but I can't think of it at the moment.

nice! this is the "cheating" version, I tried to do my best with those restrictions to prevent things like this one, but apparently a hole could be found :) Good work!

Use q to store a pointer to print_hello_message, then cast it back to a function pointer and invoke it.
q = (char *) &print_hello_message;
(*(void(*)())q)();

Short version:
q=(char*)print_hello_message;
(*(void(*)())q)();

Love it. I didn't read the 3rd rule well enough and tried to work around having to save the function address altogether. Like so:
((void(*)())(q-40))();

great job! these are EXACTLY the two lines in my program!!

Note that it's implementation defined whether a function pointer can be reinterpret_casted to a data pointer.


text:
Ascending matrix
The "ascending matrix" is an infinite matrix of whole numbers (0 included) in which any element is the smallest available element which has not been previously used on the respective row and column:
  | 1 2 3 4 5 6 ...
--+----------------
1 | 0 1 2 3 4 5 ...
2 | 1 0 3 2 5 4 ...
3 | 2 3 0 1 6 7 ...
4 | 3 2 1 0 7 6 ...
5 | 4 5 6 7 0 1 ...
6 | 5 4 7 6 1 0 ...
. | ...............

Your task is to write a program that will output the element found at the row and column specified by the input. (standard input and output)
Test cases:
5 3 -> 6
2 5 -> 5

Code Golf rules apply—the shortest code wins.
P.S. Even if this has an algorithmic nature the code can be very, very concise.
EDIT: I wasn't expecting to see the xor solution so early. I was really hoping to see 10 posts with an algorithmic approach and THEN the xor solution. Now, having in mind that it's not much fun to see how to write xor in different languages I recommend that you also try an algorithmic approach.
So, yes, I think no one can beat the 5 character mark now—therefore I congratulate Ilmari Karonen for the smartest and shortest solution. But there's a new challenge up ahead: write the shortest algorithmic solution.

Xor is algorithmic.

GolfScript, 5 chars
~(\(^

Indeed, this task is very simple once you recognize the pattern.  The only awkward bit is the 1-based indexing — if the input indices were zero-based, this 2-character solution would suffice:
~^

To explain this to readers unfamiliar with GolfScript, the ~ command evals the input, leaving the two numbers on the stack.  ^ then XORs the two topmost numbers on the stack together, leaving the result for output.  To deal with 1-based input, two more commands are needed: ( decrements the topmost number on the stack by one, while \ swaps the top two items on the stack.

Could you please explain the ^?  I referred to the GolfScript Built-ins page and Symmetric difference; using this operation with two sets of arrays makes sense, but I don't understand how it works for just two separate numbers.

@Mike: When applied to numbers, the ^ operator returns their bitwise XOR.

That is a very cool relationship :)

You were correct in your assessment of my response, which I have since removed for being based on a misreading of the challenge.

Mathematica 10 44
Edit
My first response was based on a misunderstanding about the nature of the challenge, as noted by Ilmari.
Here's another try.
Usage
f[n___, 1, n___] := n - 1;
j_~f~k_ := BitXor[j - 1, k - 1]

@IlmariKaronen I think I got it right this time. But it doesn't even come close to the size of your solution.

K, 31
{0b/:{(x|y)&~x~y}. 0b\:'-1+x,y}

Stole Ilmari Karonen's XOR logic, which I would never have spotted myself.

PHP, 38
Just a simple implementation of Ilmari Karonen's XOR
<?php echo --$_GET['a']^--$_GET['b']?>
Usage:
.../xor.php?a=4&b=7
will print 6

Python 2, 36
I figure since I'm just starting to learn Python that this would be the perfect time to submit my first answer using it (and no one has answered using Python) and perhaps I could receive some feedback.
Thank you @IlmariKaronen for the very cool shortcut.
Thank you @Gareth for the code below.
import sys
print(input()-1^input()-1)

Python 3, 56
The original program that I had written.
import sys
x=int(input())
y=int(input())
x-=1
y-=1
print(x^y)

IDEONE with 2 and 5
IDEONE with 3 and 3

I'm assuming your using Python 2 rather than Python 3 - if not ignore this comment. input already evaluates the input so the int() shouldn't be necessary. Also since you are getting an int directly from input() you could do the -1 straight away. You can also get rid of the intermediary variables completely and go right for print(input()-1^input()-1). As to whether or not the import is necessary - other Python users on this site don't include it for programs which use input(), but I'm not a Python programmer so I couldn't say if it's necessary or not.

@Gareth Actually I was using Python 3, but I like your suggestion to use print(input()-1^input()-1).  Thank you for the help!

May I ask why you import sys?

MATL, 2 bytes
Z~

Try it online!
MATL post-dates the challenge by several years, but, hey, natural 1-based indexing and a bitwise xor function makes this nice and neat!

Haskell 174
Figured I'd make a solution that did not rely on XOR. Too lazy to golf it properly.
a 0 0=0
a b c
 |m==n=a(b-m)(c-n)
 |m>n=m+a(b-m)c
 |m<n=n+a b(c-n)
 where{g f=until(>f)(*2)1`div`2;m=g b;n=g c;}
main=do
 [x,y]<-fmap(map read.words)getLine
 print$a(x-1)(y-1)

Edit: I realized a day later that this is just calculating XOR. Thus if this counts as an algorithmic solution, so should Ilmari Karonen's.

Too lazy to golf it properly. -- please golf your submission for it to be a serious contender.

Perl 5, 12 bytes
say<>-1^<>-1

Try it online!

Javascript 13 bytes
a=>b=>--a^--b

f=a=>b=>--a^--b

result = document.getElementById('result')
<input type="text" onkeyup="result.innerHTML = f(this.value.split(',')[0])(this.value.split(',')[1])" >

Japt, 5 bytes
UÉ^VÉ

Try it online!

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Partitions of a list
The answer to this question is much too long
Your challenge is to write a partitioning function in the smallest number of characters.
Input example
['a', 'b', 'c']

Output example
[(('a'),('b'),('c')),
 (('a', 'b'), ('c')),
 (('a', 'c'), ('b')),
 (('b', 'c'), ('a')),
 (('a', 'b', 'c'))]

The input can be a list/array/set/string etc. whatever is easiest for your function to process
You can also choose the output format to suit yourself as long as the structure is clear.
Your function should work for at least 6 items in the input

shall the empty partition also be part of the output?

GolfScript (43 chars)
{[[]]:E\{:v;{:^E+1/{^1$-\[~[v]+]+}/}%}/}:P;

or
{[[]]:E\{:v;{:^E+1/{^1$-\{[v]+}%+}/}%}/}:P;

Same input format, output format, and function name as Howard's solution. There's no brute forcing: this takes the simple iterative approach of adding one element from the input list to the partition each time round the outer loop.

GolfScript, 51 characters
{[[]]\{[.;]`{1$[1$]+@@`1$`{[2$]-@@[+]+}++/}+%}/}:P;

The script defines a variable P which takes an array from top of the stack and pushes back a list of all partitions, e.g.
[1 2] P            # => [[[1] [2]] [[1 2]]]
["a" "b" "c"] P    # => [[["a"] ["b"] ["c"]] [["b"] ["a" "c"]] [["a"] ["b" "c"]] [["a" "b"] ["c"]] [["a" "b" "c"]]]

It does also work on larger lists:
6, P ,p            # prints 203, i.e. Bell number B6
8, P ,p            # 4140

You may perform own tests online.

J, 51 characters
([:<a:-.~])"1~.((>:@i.#:i.@!)#l)<@;/."1[l=:;:1!:1[1

Takes input from the keyboard, items separated by spaces:
   ([:<a:-.~])"1~.((>:@i.#:i.@!)#l)<@;/."1[l=:;:1!:1[1
a b c
+-----+------+------+------+-------+
|+---+|+--+-+|+--+-+|+-+--+|+-+-+-+|
||abc|||ab|c|||ac|b|||a|bc|||a|b|c||
|+---+|+--+-+|+--+-+|+-+--+|+-+-+-+|
+-----+------+------+------+-------+

Haskell, 90 87 71 66
Saved 5 bytes thanks to nimi.
x#[]=[[[x]]]
x#(y:s)=((x:y):s):map(y:)(x#s)
p=foldr((=<<).(#))[[]]

Example:
*Main> p "abc"
[["abc"],["bc","a"],["ac","b"],["c","ab"],["c","b","a"]]

A few bytes to save: rearrange the parentheses in the 2nd line of #: :map(y:)(x#s) and turn the lambda into a point-free version: foldr((=<<).(#))[[]].

Python 2, 131 bytes
def P(L):
 if len(L)<2:yield[L];return
 for p in P(L[1:]):
	for n,s in enumerate(p):yield p[:n]+[[L[0]]+s]+p[n+1:]
	yield[[L[0]]]+p

Try it online
Uses this algorithm.