Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

As programmers, we all know the saying: "You can have it fast and good, but it won't be cheap, you can have it cheap and good, but it won't be fast, or you can have it fast and cheap, but it won't be good."

For this challenge, you are implementing an imaginary configuration tool for your custom programming services. You should render a set of three check boxes, with a heading of "SELECT ANY TWO":

SELECT ANY TWO  
☐ FAST  
☐ CHEAP  
☐ GOOD

Once two items have been selected, the third item must be disabled. Upon deselecting one of the two selected items, all options must again be enabled. Put another way, if zero or one items are selected, all are still enabled, but if two items are selected, the third must be disabled.

No special controls allowed. The check boxes should be the standard check box in your language of choice. For example, don't use a "CheckBoxList" control, if your language has one. I'm imagining most entries will be HTML/jQuery, but that is not a rule. This is code golf, looking for the shortest entry.

WINNERS SO FAR

I'll break it down into categories. There are some clear winners:

jQuery: nderscore, Mr. Tenacity Under 100b when you exclude text "resources". Honorable mention should also go to Matt for introducing the jQuery concepts that many took inspiration from.

Dyalog APL: marinus, a.k.a. Mr. Unicode How do you type all those things? I can see why you would want to write short programs.

PHP: SuperScript I believe this is the shortest entry that actually disables rather than deselecting the third option, following the strictest interpretation of the rules.

share|improve this question
    
Can I just make it so that only two can be selected at a time? So that selecting the third de-selects one of the other ones? Or perhaps add an accept button that gets greyed out if 3 options are selected? –  Quincunx May 8 at 3:30
7  
@Quincunx - Since there is no heuristic (outside of mind-reading) that could decide which one to deselect, this would confuse the user... so I'll have to say no, because we don't want the first impression of our custom software services to be a bad one. ;) –  Bruce Pierson May 8 at 3:53
    
This question interested me in Python 3's tkinter, so I am trying to learn that now. IMO, the best way to learn GUI is by trial and error. I tried this: ideone.com/YHLZIQ . Result: rapid opening of new GUIs. I had to open task manager to close them. :-). Image (the number soon climbed to 340: i.stack.imgur.com/c9wQi.png) –  Quincunx May 8 at 5:29
    
The bonus contest should be another question as there is no objective primary winning criterion or any description of the "bonus". It said that code should be "...elegant and flexible..." and "...concise and clear..." which is against code-golf. VTC as unclear what you are asking. Please don't radically change questions long after they are asked. –  user80551 May 8 at 17:38
1  
@BrucePierson Actually, there is. We could deselect the oldest selected checkbox. However, the code for that would be much more than the code you require. –  Quincunx May 8 at 20:15

24 Answers 24

up vote 22 down vote accepted

Javascript (ES5) with jQuery - 143 (Demo)

I modified Matt's solution and golfed it as far down as I think it can go:

$("*").html(["SELECT ANY TWO","FAST","GOOD","CHEAP"].join("<input type=checkbox onclick=(a=$('input:not(:checked)')).prop('disabled',!a[1])>"))

Javascript (ES5) without jQuery - 185 175 (Demo)

Using jQuery is kind of cheating, so here's a solution without it:

(d=document).write(["SELECT ANY TWO","FAST","GOOD","CHEAP"].join("<input type=checkbox onclick='for(b in a=d.querySelectorAll(\"input:not(:checked)\"))a[b].disabled=!a[1]'>"))

If we're allowed to prevent the user from checking the 3rd box instead of actually disabling the field, we can make it even shorter:

With jQuery - 126 123 (Demo)

$("*").html(["SELECT ANY TWO","FAST","GOOD","CHEAP"].join("<input type=checkbox onclick=this.checked*=!$(':checked')[2]>"))

Without jQuery - 150 147 (Demo)

(d=document).write(["SELECT ANY TWO","FAST","GOOD","CHEAP"].join("<input type=checkbox onclick=this.checked*=!d.querySelectorAll(':checked')[2]>"))
share|improve this answer
    
Cool. Using .join is a good trick! –  SuperScript May 8 at 19:16
    
"SELECT ANY TWO0FAST0GOOD0CHEAP".replace(/0/g, is another way to do it resulting in the same length. –  nderscore May 8 at 19:17
    
just being picky, the jquery version should use prop, not attr –  Einacio May 8 at 19:21
    
@Einacio your wish is my command! –  nderscore May 8 at 19:22
4  
@Einacio But codegolf is about worst practices! :P –  nderscore May 9 at 0:07

JavaScript - 184 169 (with jQuery)

b="input",a="<input type=checkbox>",c=":checked";$("body").html("SELECT ANY TWO"+a+"FAST"+a+"GOOD"+a+"CHEAP").click(function(){$(b).not(c).attr("disabled",!!$(b+c)[1])})

http://jsfiddle.net/L33JK/16/

EDIT: improved with help from @Daniel Lisik - http://codegolf.stackexchange.com/a/26805/16278

share|improve this answer
5  
Nice! Not enough rep to upvote... but you're hired! –  Bruce Pierson May 8 at 3:55
2  
The more I look at this, the more I'm learning. The cleverness of the variable assignment inside a jQuery selector. Very cool. Also, could you explain what the "double bang" (!!) is doing? –  Bruce Pierson May 8 at 5:01
1  
The single bang, coerces a boolean value, and double will obviously invert that. undefined coerces to true. That and the variable assignment are probably the only little tricks used really. –  Matt May 8 at 5:03
    
Your code can be reduced to 179 characters like this: a="<input type='checkbox'>",b="input",c=":checked",$("body").html("SELECT ANY TWO"+a+"FAST"+a+"GOOD"+a+"CHEAP").change(function(){$(b+":not("+c+")").attr("dis‌​abled",!!$(b+c)[1])}) jsfiddle.net/L33JK/15 –  Daniel Lisik May 8 at 14:10
1  
143: jsfiddle.net/_nderscore/69Ted –  nderscore May 8 at 17:18

Dyalog APL (on Windows) (169)

This is a static function, to test it if you don't know APL, type )ed C and paste this in the edit window, then run C.

C
'R'⎕WC'Form' 'Select any two',2/⊂S←2/20
1 21 41{('R.',⊃⍵)⎕WC'Button'⍵(⍺1)S'Check'('Event' 'Select' 'F')}¨'Fast' 'Cheap' 'Good'
B←R.(F C G)
F←{B.Active←X∨2≠+/X←B.State}

Newer bits of APL have long keywords. I still beat HTML though.

Explanation:

  • 'R'⎕WC'Form' 'Select any two',2/⊂S←2/20: create a form R, with title Select any two and size and position 20 20. Also stores 20 20 in S.
  • 1 21 41{...}¨'Fast' 'Cheap' 'Good': for each of these pairs of data (name and y-coordinate, which are the only variables that differ between the checkboxes:
    • ('R.',⊃⍵)⎕WC'Button': create a button within R with the first letter of the name,
    • ⍵(⍺1)S'Check': with the right argument as the title, (left arg, 1) as position, reusing S as the size and Check as style,
    • ('Event' 'Select' 'F'), which calls the function F when clicked.
  • B←R.(F C G): use B as an abbreviation for the three checkboxes we created
  • F←{...}: define the callback function as:
    • X←B.State: get the state for each checkbox and store them in X,
    • X∨2≠+/X: sum X, if this is not equal to two all checkboxes must be active, if it is equal to two only checked checkboxes must be active
    • B.Active←: enable or disable the checkboxes

Result:

screenshot

share|improve this answer
    
Great explanation, thanks! –  Bruce Pierson May 8 at 14:45

Rebol, 219 197

load-gui p: func[p][p/state/value]x: func[v][if all[p a p b p c][set-face v false]] view [title"SELECT ANY TWO"a: check"FAST"on-action[x a]b: check"CHEAP"on-action[x b]c: check"GOOD"on-action[x c]]

Ungolfed:

load-gui    ;; this is temporary while r3-gui is in beta

p: func [p] [p/state/value]

x: func [v] [
    if all [p a p b p c] [set-face v false]
]

view [
    title "SELECT ANY TWO"
    a: check "FAST" on-action [x a]
    b: check "CHEAP" on-action [x b]
    c: check "GOOD" on-action [x c]
]

This is the Rebol 3 View dialect (r3-gui). Screendump below from Ubuntu Linux:

example of rebol 3 view

Update - Thanks to Earl & Graham from Rebol SO Chatroom for shaving 22 chars of the code - http://chat.stackoverflow.com/transcript/message/16345039#16345039

share|improve this answer
    
It is invalid answer, as third is disabled but also checked, that means all 3 are checked, so please fix it. –  ST3 May 9 at 6:40
2  
@ST3 - You are incorrect I'm afraid. The "GOOD" checkbox isn't checked or in fact disabled (my code simply flicks the third box checked OFF). This is how Rebol 3 view shows an unchecked box (by default). –  draegtun May 9 at 7:01
1  
@ST3 et al - Here is a link showing default checkbox look I've described above (1st image shows no checkboxes clicked, 2nd just "GOOD") - plus.google.com/u/0/104216037702741908932/posts/Z2EbuQX67aq –  draegtun May 9 at 7:11
    
Well... I look into print-screen you added and I see all three checkboxes checked, just only one cannot be unchecked. –  ST3 May 9 at 7:14
2  
@ST3 - A greyed out checkbox is just Rebol 3 View way of showing that it's a checkbox that can be checked. The tick turns green when checked and turns back to grey when unchecked. These are the defaults. In the image in answer above you can see that "GOOD" as the input focus (blue blur) because its being "clicked" but it remains grey and not green (so not checked). –  draegtun May 9 at 7:18

Java, 421 ... 378 369 bytes

import java.awt.*;class F extends Checkbox{F(String s){super(s);}public static void main(String[]a){Frame f=new Frame();Panel p=new Panel();f.add(p);p.add(new Label("SELECT ANY TWO"));F[]c={new F("FAST"),new F("CHEAP"),new F("GOOD")};for(F b:c){p.add(b);b.addItemListener(e->{int x=0;for(F d:c)x+=d.getState()?1:0;if(x>2)((F)e.getSource()).setState(1<0);});}f.show();}}

Java... because Java. Nicer looking code:

import java.awt.*;

class F extends Checkbox {

    F(String s) {
        super(s);
    }

    public static void main(String[] a) {
        Frame f = new Frame();
        Panel p = new Panel();
        f.add(p);
        p.add(new Label("SELECT ANY TWO"));
        F[] c = {new F("FAST"), new F("CHEAP"), new F("GOOD")};
        for (F b : c) {
            p.add(b);
            b.addItemListener(e -> {
                int x = 0;
                for (F d : c) {
                    x += d.getState() ? 1 : 0;
                }
                if (x > 2) {
                    ((F) e.getSource()).setState(1 < 0);
                }
            });
        }
        f.show();
    }
}

Sample run (different sizings of the window, first is on startup):

enter image description here
enter image description here
enter image description here

The checkboxes are arranged horizontally; this is allowed. It would take much more to align it properly. Also, I'm disabling by unchecking the box when it is clicked, not by making it impossible to be clicked.

EDITS:

  1. saved 3 bytes by making the main class extend Checkbox.
  2. reread Lambda Expressions and realized that the type name was unnecessary. Take that Python!
  3. converted a while loop to a foreach loop (thanks Lee); why didn't I think of that before?
share|improve this answer
    
No restriction on the alignment (so I suppose Matt could reduce his by 5 characters). Props for a complete running program... but I don't see that the third option is disabled. –  Bruce Pierson May 8 at 4:15
    
@BrucePierson It is disabled. It cannot be clicked. If it is clicked, nothing happens. –  Quincunx May 8 at 4:16
2  
Ah, I think I see. You're immediately "unsetting" the checked state without disabling? That would be acceptable. –  Bruce Pierson May 8 at 4:19
    
@BrucePierson That's right. To actually disable, I'd have to change if(x>2)((Checkbox)e.getSource()).setState(1<0); to if(x>2){Checkbox b=(Checkbox)e.getSource();b.setState(1<0);b.setEnabled(1<0);} –  Quincunx May 8 at 4:22
1  
@BrucePierson Whenever you think, This looks funny when it has to do with using a character representation of some graphical thing, look for unicode. Alternatively, for graphical design things, turn to User Experience SE: i.stack.imgur.com/xFkzy.png –  Quincunx May 8 at 4:39

Python 3 2, 454 434 ... 393 392 bytes

I thought, Python must be shorter than Java. Here is the "proof" (EDIT: now it really is shorter):

from Tkinter import*
t=Tk()
r=str.replace
exec r(r(r(r('a@b@c@l=Label(t,text="SELECT ANY TWO");A`FAST|a);B`CHEAP|b);C`GOOD|c);l^A^B^C^','`','=Checkbutton(t,text="'),'|','",v='),'^','.pack();'),'@','=IntVar();')
def f(p,b,B,s):
 for i in 0,1,2:
    y=b[i].get()
    if p[i]-y:
     p[i]=y;s-=1
     if p[i]:s>0and B[i].toggle();s+=2
 t.after(1,f,p,b,B,s)
t.after(1,f,[0]*3,[a,b,c],[A,B,C],0)
t.mainloop()

For those of you curious as to what the exec expression actually executes, it executes this (this is what the replaces do to the string. Newlines added for readability):

a=IntVar();
b=IntVar();
c=IntVar();
l=Label(t,text="SELECT ANY TWO");
A=Checkbutton(t,text="FAST",v=a);
B=Checkbutton(t,text="CHEAP",v=b);
C=Checkbutton(t,text="GOOD",v=c);
l.pack();
A.pack();
B.pack();
C.pack();

This uses the same logic as my Java answer: unselect the checkbox if it causes more than 2 checkboxes to be selected. Unf Fortunately Unfortunately, I spent more less more bytes doing this.

enter image description here

EDITS:

  1. massive adjustment of code to use exec, saving a whopping 1 byte!
  2. switched to python 2 to squeeze two bytes from the exec (removing parentheses).
  3. more golfing. Includes changing range(3) to 0,1,2 and changing the indentation to have one layer of tabs. Unsure if \t\t would work instead of \t__(_ is the space character). Finally reached the longest my Java answer ever was.
  4. used replace trick
  5. used Bakiru's suggestion, and golfed some more. Actually made it shorter than Java! But now, the Java answer got golfed more, so this is again longer. :-(
  6. used improved replace trick.
  7. changed a != for a -.
share|improve this answer
    
Interesting approach. +1 –  cjfaure May 8 at 17:07
    
I can cheat with the turbo mode on my keyboard. First, I check two boxes. Second, I use Tab to highlight the third. Now I hold Space Bar in turbo mode for a few seconds. Sometimes, this checks the third box! –  kernigh May 8 at 23:12
    
@kernigh I believe that is because my code gets to the point where it knows that the box has been toggled, but the code hasn't reached the point where it re-toggles the box. So if you toggle the box in that time (to off), my code will put a checkmark on it. –  Quincunx May 9 at 3:34
1  
You can avoid the indented block starting with if p[i] using an and instead of an if: if p[i]:s>1 and B[i].toggle();s+=1. –  Bakuriu May 9 at 7:36
    
@kernigh I was wrong; replacing B[i].toggle() with B[i].deselect() doesn't change anything. I have no idea why this is so. Perhaps it is a flaw with tkinter –  Quincunx May 9 at 23:57

CoffeeScript - 167, 154

CoffeeScript port of @Matt's answer.

b="input";a="<input type=checkbox>";c=":checked";$("body").html("SELECT ANY TWO#{a}FAST#{a}GOOD#{a}CHEAP").click ->$(b).not(c).attr "disabled",!!$(b+c)[1]

Somewhat ungolfed:

b = "input"
a = "<input type=checkbox>"
c = ":checked"

$( "body" ).html( "SELECT ANY TWO#{a}FAST#{a}GOOD#{a}CHEAP" ).click ->
    $( b ).not( c ).attr "disabled", !!$( b + c )[1]

JSFiddle.

share|improve this answer

PHP, Javascript, jQuery - 135b

I was admiring @nderscore's answer, but then I decided to copy and one-up him.

<?echo"SELECT ANY TWO".($m="<input type=checkbox onclick=(a=$('input:not(:checked)')).prop('disabled',!a[1])>")."FAST$m GOOD$m CHEAP"?>

Basically I replaced his .join trick with some PHP Hypertext Preprocessing.

share|improve this answer
    
When you consider that 27 bytes are required for the text "resources" in the program, this is getting very close to a 100b program. Well done! –  Bruce Pierson May 8 at 21:07
1  
I'm not much of a PHP golfer, but I chopped a few bytes off for you: (128) SELECT ANY TWO<?=($m="<input type=checkbox onclick=(a=$('input:not(:checked)')).prop('disabled',!a[1])>").FAST.$m.GOOD.$m.C‌​HEAP; –  nderscore May 8 at 23:05

Ruby, 219 218 bytes

I use the same Tk widgets as the Python 3 answer by Quincunx.

This program breaks the rules because it has a check box list. (The rules said, "Don't use a check box list.") Yes, a is an array of 3 TkCheckButton objects, and I believe that an array is a list. My defense is that I did not use any existing check box list, but I used the standard check boxes and made my own list.

require'tk'
o=->(c){c.variable.value>?0}
TkLabel.new{text'SELECT ANY TWO'
pack}
a=%w[FAST CHEAP GOOD].map{|t|TkCheckButton.new{text t
command{a.map{|c|c.state a.count(&o)<2||o[c]?:normal: :disabled}}
pack}}
Tk.mainloop

CHEAP and GOOD checked, but FAST disabled

I tested with Ruby 2.1.0 and Tk 8.5.15.

  • o[c] is a predicate to test if check button c is selected. With the default strings, c.variable.value is '0' or '1', so the string comparison is only true if '1'>'0'. EDIT: I saved 1 byte (219 down to 218) by changing '0' to ?0. In Ruby, ?0 is a character constant.
  • a.count(&o) uses the predicate to count the selected check buttons.
  • When the user toggles a check button, the command calls a.map to loop for all buttons, making them :normal or :disabled.
share|improve this answer
1  
Very good. No rule breaking here - I was referring to a check box list control that may happen to be part of the language framework. I believe all of the answers so far use some kind of map or selector, so this is totally legit. –  Bruce Pierson May 8 at 21:01

JavaScript (with jQuery) - 224, 222, 210, 205, 178

a="<input type=checkbox>",c=":checked",e="input",f="disabled",d=$("body").html("SELECT ANY TWO"+a+" FAST"+a+"CHEAP"+a+"GOOD").click(function(){$(e).not(c).attr(f,$(e+c).length>1)})

Thanks to a comment from brilliant @Matt I reduced the code by 27 characters.

JSFiddle

share|improve this answer
    
Save 25 or so by moving your condition $(e+c).length>1 into the assignment as such: $(e).not(c).attr(f,$(e+c).length>1) since you're only changing the boolean itself. –  Matt May 8 at 13:47
1  
@Matt that's super clever! Will use it. Thanks :) –  Daniel Lisik May 8 at 13:53
1  
Managed to get it down to 169 using a mix of yours and mine. The !! coercion and a little extra golfing with not assigning body to d. a="<input type=checkbox>",c=":checked",e="input";$("body").html("SELECT ANY TWO"+a+"FAST"+a+"CHEAP"+a+"GOOD").click(function(){$(e).not(c).attr("disabled",!‌​!$(e+c)[1])}) –  Matt May 8 at 14:11

Mathematica

A more code-golfed version as suggested by David, 255 characters:

h = Checkbox;
i = Dynamic;
j = Enabled;
t = True;
i[
 If[Total@Boole@{a, b, c} == 2,
  {d, e, f} = {a, b, c},
  {d, e, f} = {t, t, t}
  ];
 Row@{
   "SELECT ANY TWO",
   h[i@a, j -> d], "FAST",
   h[i@b, j -> e], "CHEAP",
   h[i@c, j -> f], "GOOD"
   }
 ]
share|improve this answer
    
You can save some characters by using h=Checkbox;i=Dynamic;j=Enabled. –  David Carraher May 8 at 12:42
    
@DavidCarraher Thanks, I can see myself using that technique for other code golfing question in the future as well. –  Calle May 8 at 12:49
1  
No need to include both versions. And don't forget to use h and to adjust your char count in the heading. –  David Carraher May 8 at 23:34

Thanks to Rotem and Johnbot for the golfing help!

C# 343 334

This one uses the same "cheat" as Quincunx's Java answer - the checkboxes aren't actually disabled; they just don't allow you to check them if that check makes 3.

using System.Windows.Forms;using System.Linq;class P:Form{static void Main(){P p=new P();p.Text="SELECT ANY TWO";int y=0;var a=new CheckBox[3];foreach(var n in "FAST CHEAP GOOD".Split()){var c=new CheckBox();a[y]=c;c.Top=y++*50;c.Text=n;c.Validating+=(s,e)=>{if(a.Count(b=>b.Checked)>1)e.Cancel=true;};p.Controls.Add(c);}Application.Run(p);}}

There's also a minor bug that you can't close the window after selecting the third checkbox unless you unselect one, because the validation won't pass. But this is , so who cares? ;)

C# 403 397 374

This is a proper one that actually disables the third checkbox.

using System.Windows.Forms;using System.Linq;class P:CheckBox{static void Main(){var p=new Form{Text="SELECT ANY TWO"};P[]a=null;a="FAST CHEAP GOOD".Split().Select((x,i)=>{var c=new P{Top=i*50,Text=x};c.Click+=(s,e)=>{a.First(b=>!b.Checked).Enabled=a.Count(b=>b.Checked)>1?1<0:a.All(b=>b.Enabled=0<1);};p.Controls.Add(c);return c;}).ToArray();Application.Run(p);}}

Screenshot

Kinda ungolfed:

using System.Windows.Forms;
using System.Linq;

class P:Form
{
    static void Main()
    {
        P p = new P();
        p.Text = "SELECT ANY TWO";
        int y = 0;
        var a = new CheckBox[3];
        foreach (var n in "FAST CHEAP GOOD".Split())
        {
            var c = new CheckBox(); a[y] = c; c.Top = y++ * 50; c.Text = n; c.Click += (s, e) =>
            {
                if (a.Count(b => b.Checked) == 2)
                {
                    a.First(b => !b.Checked).Enabled = false;
                }
                else
                {
                    foreach (var b in a) b.Enabled = true;
                }
            };
            p.Controls.Add(c);
        }
        Application.Run(p);
    }
}
share|improve this answer
1  
Couldn't if(a.Count(b=>b.Checked)==2)e.Cancel=true; be rewritten as e.Cancel=a.Count(b=>b.Checked)==2;? –  Rotem May 8 at 11:16
    
@Rotem Yes, yes it could. I'm dumb. And there's a similar optimisation for the other one. Thanks! –  Bob May 8 at 14:32
    
Wait, no, there isn't for the other one. Eh, still saved some chars. –  Bob May 8 at 14:40
1  
If you switch the inheritance to CheckBox, use object initializers and abuse Linq a bit you can get the proper one down to 374: using System.Windows.Forms;using System.Linq;class P:CheckBox{static void Main(){var p=new Form{Text="SELECT ANY TWO"};P[]a=null;a="FAST CHEAP GOOD".Split().Select((x,i)=>{var c=new P{Top=i*50,Text=x};c.Click+=(s,e)=>{if(a.Count(b=>b.Checked)>1){a.First(b=>!b.Ch‌​ecked).Enabled=1<0;}else a.All(b=>b.Enabled=0<1);};p.Controls.Add(c);return c;}).ToArray();Application.Run(p);}} –  Johnbot May 9 at 11:25
1  
364 if you use the conditional operator in place of the if statement. Replace if(a.Count(b=>b.Checked)>1){a.First(b=>!b.Ch‌​ecked).Enabled=1<0;}else a.All(b=>b.Enabled=0<1); with a.First(b=>!b.Checked).Enabled=a.Count(b=>b.Checked)>1?1<0:a.All(b=>b.Enabled=0‌​<1); –  Johnbot May 9 at 12:08

C++11/Qt5.2 - 561 481 433 423 369

Because why not.

Shockingly, as of now we are shorter than Python, and the non-buggy C#, and tied with Java!

Credits to EveBird for cutting it down from 561 to 481.

And once more EveBird shortens it from 481 to 433!

Took a few off with a lambda connect

Down to 389 with C++11 initializers

And 373 without the separate class

Removed a few spaces - 369

Golf'd:

#include<QtWidgets>
#define C(x,y,z)z.setEnabled(x.isChecked()+y.isChecked()<2);
#define S(x)l.addWidget(&x);
#define X(x)S(x);x.connect(&x,&QCheckBox::clicked,[&](){C(g,f,c)C(g,c,f)C(f,c,g)});
int main(int n,char**v){QApplication a(n,v);QWidget m;QLabel t{"Select any two"};QCheckBox g{"Good"},f{"Fast"},c{"Cheap"};QVBoxLayout l(&m);S(t)X(g)X(f)X(c)m.show();a.exec();}

Sort of Un-Golfed:

#include<QtWidgets>

#define C(x,y,z)z.setEnabled(x.isChecked()+y.isChecked()<2);
#define S(x)l.addWidget(&x);
#define X(x)S(x);connect(&x, &QCheckBox::clicked, [&](){C(g,f,c)C(g,c,f)C(f,c,g)});

int main(int n,char**v){ 
    QApplication a(n,v);
    QWidget m;
    QLabel t{"Select any two"};
    QCheckBox g{"Good"},f{"Fast"},c{"Cheap"};
    QVBoxLayout l(&m);
    S(t)X(g)X(f)X(c)m.show();
    a.exec();
}

GFC

share|improve this answer
1  
+1 for the self-flagellating "why not" :) –  Bruce Pierson May 10 at 4:58

AngularJS - 214

<input type=checkbox ng-model=fast ng-disabled=cheap&&good>FAST</input>
<input type=checkbox ng-model=cheap ng-disabled=fast&&good>CHEAP</input>
<input type=checkbox ng-model=good ng-disabled=fast&&cheap>GOOD</input>
share|improve this answer
    
I tried this out at JSFiddle, but without any success. Can you provide a working example? –  squeamish ossifrage May 9 at 9:42
    
    
You did not mention "ng-app". Check <head> in my example. –  user12345 May 9 at 10:25
1  
Ah, OK :-) You can golf it down a bit by removing the quotation marks and extra line breaks. –  squeamish ossifrage May 9 at 10:33

mIRC script (727 719 bytes)

Forgot about this language until a drunken conversation last night.

alias select_two {
  dialog -m s2 s2
}

dialog s2 {
  title "Select any two:"
  size -1 -1 200 100
  check "Fast",1, 5 10 170 25
  check "Cheap",2, 5 30 170 25
  check "Good",3, 5 50 170 25 
}

on *:dialog:s2:sclick:*: {
  if ($did(s2, $did).state = 1) {
    if ($did = 1) {
      if ($did(s2, 2).state = 1) { did -b s2 3 }
      if ($did(s2, 3).state = 1) { did -b s2 2 }
    }
    if ($did = 2) {
      if ($did(s2, 1).state = 1) { did -b s2 3 }
      if ($did(s2, 3).state = 1) { did -b s2 1 }
    }
    if ($did = 3) {
      if ($did(s2, 1).state = 1) { did -b s2 2 }
      if ($did(s2, 2).state = 1) { did -b s2 1 }
    }
  }
  if ($did(s2, $did).state = 0) {
    did -e s2 1
    did -e s2 2
    did -e s2 3
  }
}

More should be coded in this language! But there needs to be a way to make this into a real mess so it can be as good as Perl.

Edit: noticed that my Python-isms are leaking through and was able to reduce the code by 8 bytes!

share|improve this answer
    
Haha, I like the intro to this one. It's kind of verbose though - could it be the beer speaking? =c) –  Bruce Pierson May 10 at 6:03

Groovy - 357 221 217 chars

I've ported Quincunx's solution to Groovy 2.2.1, using SwingBuilder (and made it even more Groovier):

c=[];new groovy.swing.SwingBuilder().frame(){panel(){label("SELECT ANY TWO");f={if(c.count{it.isSelected()}>2)it.source.setSelected(1<0)};["FAST","CHEAP","GOOD"].each{c<<checkBox(label:it,itemStateChanged:f)}}}.show()

Ungolfed:

c=[]
new groovy.swing.SwingBuilder().frame() {
    panel() {
        label("SELECT ANY TWO")
        f = { if (c.count{it.isSelected()} > 2) it.source.setSelected(1<0) }
        ["FAST","CHEAP","GOOD"].each { c << checkBox(label: it, itemStateChanged: f) }
    }
}.show()
share|improve this answer

QML - 369 315 254 251 248 bytes

Here goes QML (QtQuick 2.0) version, given only the .qml file contents. This code requires Qt 5.1 at least to run. Not a big deal as its huge compared to other solutions (248 bytes), but it's a full featured cross-platform application (Android and iOs included)! :D

    import QtQuick 2.0;import QtQuick.Controls 1.1;Row{Text{text:"SELECT ANY TWO"}CheckBox{id:a;text:"FAST";enabled:!b.checked|!c.checked}CheckBox{id:b;text:"CHEAP";enabled:!a.checked|!c.checked}CheckBox{id:c;text:"GOOD";enabled:!b.checked|!a.checked}}

Horizontal layout dialog

To run it, save the code to a .qml file, install Qt 5.1 and run qmlscene.exe (or just qmlscene on linux), which will show an open file dialog. Chose the .qml file you've saved the code to and see the awesome result! :D

share|improve this answer

JavaScript 209 (was 346)

Shortened: thanks for comments.

function f(){var a=document.getElementsByClassName("x"),n=0,i=0;for(i in a){if(a[i].checked)n++;}if(n<2){for(i in a){a[i].disabled=false;}}else{for(i in a){i(false===a[i].checked){a[i].disabled=true;break;}}}}

Golfed function:

function f(a,b,c){
var x=document.getElementById(a);
var y=document.getElementById(b);
var z=document.getElementById(c);
var n=0,i=0;
var a=[x,y,z];
for(i in a)
{
if(a[i].checked) n++;
}
if(n<2)
{
for(i in a)
{
a[i].disabled=false;
}
}
else
{
for(i in a)
{
if(false===a[i].checked)
{
a[i].disabled=true;
break;
}
}
}
}

HTML form: provides input and calls the function. * Form now uses class=x to group inputs.

<form>
        SELECT ANY TWO<br>
        FAST <input id="a" type="checkbox" class="x" value="0" onchange="f()"><br>
        CHEAP <input id="b" type="checkbox" class="x" value="1" onchange="f()"><br>
        GOOD <input id="c" type="checkbox" class="x" value="2" onchange="f()"><br>
    </form>

Tested with NetBeans and Chrome.

share|improve this answer
    
You can golf the function further and reduce it to 264 characters by consolidating all of your vars, removing unnecessary braces and whitespace (including newline chars). You could probably get it smaller if you use an ES6 lambda. –  Tony H. May 8 at 8:07
    
Apart from some more obvious golfing, consider using a class to pull all of the input elements into an array in one hit instead, using getElementsByClassName eg. a=document.getElementsByClassName('q'). –  Matt May 8 at 8:28
    
change the ids to name and just call them with document.a, document.c, document.c also put them directly into a[] –  frieder May 8 at 11:25

C#, 335 333 326 320 308

Based off Bobs Answer, mine does use fewer characters than his (335 v 342), but I might not understand fully how to count this.

using System.Linq;using System.Windows.Forms;class P:Form{static void Main(){new P();}P(){Text="SELECT ANY TWO";var a="FAST CHEAP GOOD".Split().Select(r=>new CheckBox{Text=r,Top=r[0]%9*20}).ToList();a.All(r=>{r.Validating+=(b,c)=>c.Cancel=a.Count(z=>z.Checked)>1;Controls.Add(r);return 1>0;});ShowDialog();}}

Ungolfed

using System.Linq;
using System.Windows.Forms;

class P : Form
{
    static void Main()
    {
        new P();
    }

    P()
    {
        Text = "SELECT ANY TWO";

        var a = "FAST CHEAP GOOD".Split().Select(r => new CheckBox
        {
            Text = r,
            Top = r[0] % 9 * 20
        }).ToList();

        //loops, I dont need no stinking loops
        a.All(r => { r.Validating += (b, c) => c.Cancel = a.Count(z => z.Checked) > 1; Controls.Add(r); return 1 > 0; });
        ShowDialog();
    }
}
share|improve this answer
    
Great use of anon functions and Linq here, especially like the Select. –  Bruce Pierson May 8 at 15:26
    
You can save a couple more characters by replacing the ==2 with a >1, and the true with a 1>0. You can also use a All instead of Where and Last. ToList is also shorter than ToArray. –  Bob May 9 at 11:57
    
@Bob Good call, don't know how I missed All(), and as a bonus, turns out with All you don't have to materialize it, saving even more –  iamkrillin May 9 at 12:06

Groovy

Based on the Java version, but much slimmed down ;)

Types were replaced by 'def', semicolons removed, add replaced by <<, the 1<0 replaced by 0, collect for creating the checkboxes, removed the itemevent type, removed casting the checkbox, enhanced the loops.

import java.awt.*
class F {
    def static main(a) {
        def f = new Frame()
        def p = new Panel()
        f << p
        p << new Label("SELECT ANY TWO")
        def c = ['FAST','CHECK','GOOD'].collect { new Checkbox(it) }
        c.each { b ->
            p << b
            b.addItemListener { e->
                int x = 0, i = 0
                3.times {
                    x += c[it].state ? 1 : 0
                }
                if (x > 2) {
                    e.source.state = 0                        
                }
            }
        }
        f.show()
    }
}
share|improve this answer
    
Groovy is not java. That means that all those enhancements don't count as much. Everything you removed was necessary in java, but not groovy. –  Quincunx May 9 at 17:52
    
You're right, Groovy is not Java, that why it's called Groovy. I'm not sure what you're trying to say here. –  Erik Pragt May 10 at 13:36

JavaScript / jQuery 237 234 229

Very similar approach as Matt's answer, although a little longer.

$(function(){var e="input ",t="disabled",n,r;$("body").html("SELECT ANY TWO|FAST|CHEAP|GOOD".replace(/\|/g,"<"+e+'type="checkbox">'));n=$(e);n.change(function(){n.removeAttr(t);r=$(":checked");if(r.length>1)n.not(r).attr(t,t)})})
share|improve this answer

TCL 347

At least it beats Python and Java.

set d .
proc a v {upvar f f c c g g d d $v x
if $x&&$f+$c+$g==2 {set d .$f$c$g
$d configure -state disabled} 
if !$x {$d configure -state normal}}
set z -variable
set y -command
set x checkbutton
label .l -text {SELECT ANY TWO}
$x .011 -text FAST $z f $y a\ f
$x .101 -text CHEAP $z c $y a\ c
$x .110 -text GOOD $z g $y a\ g
pack .l .011 .101 .110

Note: if you start by selecting one checkbox and immediately unselecting it, you will get an error. You can fix it by adding 110 to the end of the first line.

Ungolfed:

# Keep track of the last disabled button. Set it to something valid to start with.
set last .110

proc toggled name {
        # Access some globals
        upvar fast  fast
        upvar cheap cheap
        upvar good  good
        upvar last  last
        upvar $name value

        # Just toggled one on, check if exactly two are now on
        if {$value == 1 && ($fast + $cheap + $good) == 2} {
                set last .$fast$cheap$good
                $last configure -state disabled
        }
        # Just toggled one off. Re-enable disabled one.
        if {$value == 0} {
                $last configure -state normal
        }
}

label .label -text {SELECT ANY TWO}

checkbutton .011 -text FAST  -variable fast  -command {toggled fast}
checkbutton .101 -text CHEAP -variable cheap -command {toggled cheap}
checkbutton .110 -text GOOD  -variable good  -command {toggled good}

pack .label .011 .101 .110
share|improve this answer

Javascript + Knockout: ~250 Characters

a=function(i){return "<input type=checkbox data-bind='value: "+i+", checked: x, disable: x().length>=2 && x().indexOf(\""+i+"\")==-1'>"},document.body.innerHTML = "SELECT ANY TWO"+a(0)+"Fast"+a(1)+"Good"+a(2)+"Cheap"; ko.applyBindings({x:ko.observableArray([])})
share|improve this answer

AngularJS - 155 (Demo)

SELECT ANY TWO :<i ng-init=t=[]><p ng-repeat="(i,v) in ['FAST','CHEAP','GOOD']"><input type=checkbox ng-disabled=t[(i+1)%3]&&t[(i+2)%3] ng-model=t[i]>{{v}}

The ungolfed version:

SELECT ANY TWO :
<i ng-init="checkedArray = []" /> <!-- A useless tag to initialize the array (which can't be done on the `input` tag, unfortunately) -->
<p ng-repeat="(key, value) in ['FAST', 'CHEAP', 'GOOD']">
    <input
        type="checkbox"
        ng-model="checkedArray[key]"
        ng-disabled="checkedArray[(key + 1) % 3] && checkedArray[(key + 2) % 3]"
    />
    {{value}}
</p>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.