1

let us say we have parameter with A,B,C and D values. Now we want to force the user to choose only A,B,C or A,C,D or A or B or C.

Instead of Allowing all possible 16 combination, we want to allow only 5 predefined combination. I tried it but for this i have to put condition for each and every selection.

If we assume this values are bind with checkbox and we need to check whether selected values are as per our predifined combination or not.

I need to achieve this in javascript or either angular.js. Please help me with proper algorithm for such operation.

I tried below logic to achieve this but this will not infor user instantly, alert only after final submission

// multi-dimentional array of defined combinations
var preDefinedCombinations = [['a','b','c'], ['a','c','d'], ['a'], ['b'], ['c']];

// Combination user select
var selectedvalues = [];

// Function called on selection or removing value (i.e a,b,c,d)
function selectOption(value){
    var checkIndex = selectedvalues.indexof(value);
    if(checkIndex == -1){
        selectedvalues.push(value);
    }else{
        selectedvalues.splice(checkIndex, 1);
    }

}
// function called on submition of combination
function checkVaildCombination(){
    if(preDefinedCombinations.indexOf(selectedvalues) == -1){
        alert('Invalid Combination');
    }else{
        alert('Valid Combination');
    }
}

This code gives information only about combination is valid or not, not about which may be possible combinations as per selections.

user3725294
  • 105
  • 1
  • 12
  • could you post the code you've got so far? – Nicolas Straub Oct 17 '14 at 05:43
  • @NicolásStraubValdivieso i have added a dummy sample of my logic. – user3725294 Oct 17 '14 at 06:10
  • 1
    what do you mean by "alert only after final submission"? Also what do you mean with the last paragraph you typed in there? (do you want to inform the user of all valid combos?) – Nicolas Straub Oct 17 '14 at 06:16
  • @NicolásStraubValdivieso It is a dummy sample for my code, for better understanding i have put alert to make you understand when it is success or failure – user3725294 Oct 17 '14 at 06:24
  • 1
    @NicolásStraubValdivieso An example : suppose i have selected 'a' and 'b' from available option a,b,c& d. This selected values are maintained in 'selectedvalues' array through function selectOption, and than click on submit button so in function 'checkVaildCombination' code will check [a,b] is valid combination or not and work accordingly. But in case of failure user only get message that selected values are belongs to a invalid combination and not get information that if he selects 'c' also it may become a valid combination and system will allow him to proceed. I hop you got now ? – user3725294 Oct 17 '14 at 06:24

2 Answers2

1

May be following code could help you to solve ur problem

<script>
function validateForm(){
  var checkBoxValues = this.a.checked.toString() + this.b.checked.toString() + this.c.checked.toString() + this.d.checked.toString();
  if( checkBoxValues == 'truetruetruefalse'   || // abc
      checkBoxValues == 'truefalsetruetrue'   || // acd
      checkBoxValues == 'truefalsefalsefalse' || // a
      checkBoxValues == 'falsetruefalsefalse' || // b
      checkBoxValues == 'falsefalsetruefalse' ){ // c
    return true;
  }
  return false;
}
</script>
  <form onsubmit="return validateForm()" action="javascript:alert('valid')">
    <input type="checkbox" name="mygroup" id="a">
    <input type="checkbox" name="mygroup" id="b">
    <input type="checkbox" name="mygroup" id="c">
    <input type="checkbox" name="mygroup" id="d">
    <input type="submit">
  </form>
Manivannan
  • 3,074
  • 3
  • 21
  • 32
1

stolen from https://stackoverflow.com/a/1885660/1029988 :

function intersect_safe(a, b)
{
  var ai=0, bi=0;
  var result = new Array();

  while( ai < a.length && bi < b.length )
  {
     if      (a[ai] < b[bi] ){ ai++; }
     else if (a[ai] > b[bi] ){ bi++; }
     else /* they're equal */
     {
       result.push(a[ai]);
       ai++;
       bi++;
     }
  }

  return result;
}

then in your code:

function checkVaildCombination(){
    function get_diff(superset, subset) {
        var diff = [];
        for (var j = 0; j < superset.length; j++) {
            if (subset.indexOf(superset[j]) == -1) { // actual missing bit
                diff.push(superset[j]);
            }
        }
        return diff;
    }

    if(preDefinedCombinations.indexOf(selectedvalues) == -1){
        missing_bits = [];
        diffed_bits = [];
        for (var i = 0; i < preDefinedCombinations.length; i++) {
            var intersection = intersect_safe(preDefinedCombinations[i], selectedvalues);
            if (intersection.length == selectedvalues.length) { // candidate for valid answer
                missing_bits.push(get_diff(preDefinedCombinations[i], intersection));
            } else {
                var excess_bits = get_diff(selectedvalues, intersection),
                    missing_bit = get_diff(preDefinedCombinations[i], intersection);

                diffed_bits.push({
                    excess: excess_bits,
                    missing: missing_bit
                });
            }
        }

        var message = 'Invalid Combination, if you select any of these you`ll get a valid combination:\n\n' + missing_bits.toString();
        message += '\n\n Alternatively, you can reach a valid combination by deselected some bits and select others:\n';

        for (var j = 0; j < diffed_bits.length; j++) {
            message += '\ndeselect: ' + diffed_bits[j].excess.toString() + ', select: ' + diffed_bits[j].missing.toString();
        }
        alert(message);
    } else {
        alert('Valid Combination');
    }
}

you will of course want to format the output string, but that code will (hopefully, it is napkin code after all) give you the missing bits to make valid combos with what you've got selected already

Community
  • 1
  • 1
Nicolas Straub
  • 3,381
  • 6
  • 21
  • 42
  • No it not works as expected :(.. For selected combination ['a','b','d'] it doesn't tell user to select either 'c' in place of 'd' so a valid comb. will be ['a', 'b', 'c'] or 'c' in place of 'b' so a valid comb. will be ['a', 'c', 'd'] – user3725294 Oct 17 '14 at 06:50
  • 1
    yeah, this code expects the active combination to be a subset of a valid combination... if it weren't 4 in the morning over here I'd write the other loop for you... basically for all items in `preDefinedCombinations` where the intersection is less than the selected values, you need to loop over the `selectedvalues` array finding all bits that are in `selectedvalues` but not in `preDefinedCombinations[i]` (call this the `inverse_missing_bits`), then strip these values from `selectedvalues` and run the `j` loop to find the missing bits. (continued in next comment) – Nicolas Straub Oct 17 '14 at 06:59
  • 1
    You'll end up with the values you need to deselect in `inverse_missing_bits` and the ones you need to select in `missing_bits`. The rest is just modifying the message to properly convey the user's options. I'll complete the answer tomorrow, but I'm off to bed now. Sorry :/ – Nicolas Straub Oct 17 '14 at 07:00
  • Again thanks a lot Nicolas for such a great help and i am sorry to disturb you at 4. i will try your solution.. have a great night :) thanks – user3725294 Oct 17 '14 at 07:09
  • 1
    @user3725294 on the contrary, it was a nice flexing of the grey muscle :). I updated the code, and it should provide a complete solution to the problem. It still is napkin code though, so if it doesn't work please let me know so we can fix it together – Nicolas Straub Oct 17 '14 at 23:32
  • 1
    ok, I tested it and having `['a','b','d']` alerts `Invalid Combination, if you select any of these you`ll get a valid combination: Alternatively, you can reach a valid combination by deselected some bits and select others:deselect: d, select: c; deselect: b, select: c; deselect: b,d, select: deselect: a,d, select: ; deselect: a,b,d, select: c` – Nicolas Straub Oct 17 '14 at 23:41
  • Thanks a lot :-)... it works exactly what i needed.. it solves a really big problem for me.. Great solution thanks a lot.. keep rocking \m/.. _/\_ – user3725294 Oct 20 '14 at 10:34