There is a list of categories: salads, appetizers, soups, in each category of 6 products, then there is a set of categories, contains 2 categories and, according to the condition, the set may contain a salad or a snack, and soup. Question: the user scored goods from these categories, and I know how many products each category he chose, I need to calculate the number of sets, plus the set may not be complete (for example, only the soup is selected). I'm trying to implement this thing in javascript

You need to go through all the items in the basket and get the number of sets, for example, a light set contains salad or snacks and soup. How to do it?

  • What is the question? - Grundy
  • and that you have already tried? - Jean-Claude
  • I understand that once the soup is a mandatory component of the set, the number of sets is equal to the number of soups. - user200141
  • yes, that's right, I also thought that I had found the answer, but it works correctly under ideal conditions, if the user chooses soup and salad, this is one complete set, and if he chose another snack, then this is another set, but not complete (as there is not enough soup), and how to calculate the number of such sets - Ajlelcc
  • @Ajlelcc: You need to clearly define the rules for the formation of your sets. I see that you yourself are not fully aware of them, and we are even more so. - user200141

1 answer 1

If you look on the contrary, each product belongs to a category. Maybe something like that? It’s crooked, of course, but ...

// var товар = {название, категория, ...}; var категории = ['суп','салат',...]; var наборы = { '0' : { категория[0], категория[1] }, '1' : { категория[1] } }; var задействованные_категории = {}; for(var p in список_выбранных_товаров){ var товар = список_выбранных_товаров[p]; if(!задействованные_категории[товар.категория_к_которой_он_относится]){ задействованные_категории[товар.категория_к_которой_он_относится] = 0; } задействованные_категории[товар.категория_к_которой_он_относится]++; } var необходимые_наборы = {}; for(var n in наборы){ // по наборам var набор = наборы[i]; var будем_учитывать_этот_набор = true; for(var c in набор){ // по категориям var категория = набор[c]; if(!задействованные_категории[категория]){ будем_учитывать_этот_набор = false; break; } } if(будем_учитывать_этот_набор){ if(!необходимые_наборы[n]){ необходимые_наборы[n] = 0 } необходимые_наборы[n]++; for(var c in набор){ var категория = набор[c]; задействованные_категории[категория]--; } } } // выводим количество for(var n in необходимые_наборы){ console.log('Набор #'+n+': '+необходимые_наборы[n]); }