Maneras eficientes de comparar una variable con múltiples valores

En este artículo, discutiremos las formas de comparar una variable con valores.

Método 1: La idea es comparar cada variable individualmente con todos los valores múltiples a la vez.

Programa 1:

C++

// C++ program to compare one variable
// with multiple variable
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    // Variable to be compared
    char character = 'a';
 
    // Compare the given variable
    // with vowel using || operator
 
    // Check for vowel
    if  (character == ('a' || 'e'
            || 'i' || 'o'
                    || 'u')) {
        cout << "Vowel";
    }
 
    // Otherwise Consonant
    else {
        cout << "Consonant";
    }
 
    return 0;
}

Java

// Java program to compare one variable
// with multiple variable
import java.util.*;
 
class GFG
{
 
// Driver Code
public static void main(String[] args)
{
    // Variable to be compared
    char character = 'a';
 
    // Compare the given variable
    // with vowel using || operator
    // Check for vowel
    if (character == ('a' || 'e'
            || 'i' || 'o'
                    || 'u')) {
        System.out.print("Vowel");
    }
 
    // Otherwise Consonant
    else {
        System.out.print("Consonant");
    }
 
}
}
 
// This code is contributed by Rajput-Ji

Python3

# Python program to compare one variable
# with multiple variable
 
# Driver Code
if __name__ == '__main__':
   
    # Variable to be compared
    character = 'a';
 
    # Compare the given variable
    # with vowel using or operator
    # Check for vowel
    if (character == ('a' or 'e' or 'i' or 'o' or 'u')):
        print("Vowel");
 
    # Otherwise Consonant
    else:
        print("Consonant");
 
# This code contributed by shikhasingrajput

C#

// C# program to compare one variable
// with multiple variable
using System;
 
class GFG
{
 
// Driver Code
public static void Main(String[] args)
{
    // Variable to be compared
    char character = 'a';
 
    // Compare the given variable
    // with vowel using || operator
    // Check for vowel
    if (character == ('a' || 'e'
            || 'i' || 'o'
                    || 'u')) {
        Console.Write("Vowel");
    }
 
    // Otherwise Consonant
    else {
        Console.Write("Consonant");
    }
}
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
 
// Javascript program to compare one variable
// with multiple variable
 
// Variable to be compared
var character = 'a';
 
// Compare the given variable
// with vowel using || operator
 
// Check for vowel
if  (character == ('a'. charCodeAt(0) ||
                   'e'. charCodeAt(0) ||
                   'i'. charCodeAt(0) ||
                   'o'. charCodeAt(0) ||
                   'u'. charCodeAt(0)))
{
    document.write("Vowel");
}
 
// Otherwise Consonant
else
{
    document.write("Consonant");
}
 
// This code is contributed by SoumikMondal
 
</script>
Producción

Consonant

Explicación:
el código anterior da una respuesta incorrecta o un error, ya que comparar la variable de la manera anterior es incorrecto y obliga a codificar de la siguiente manera:

C++

// C++ program to compare one variable
// with multiple variable
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    // Variable to be compared
    char character = 'a';
 
    // Compare the given variable
    // with vowel individually
 
    // Check for vowel
    if (character == 'a'
        || character == 'e'
        || character == 'i'
        || character == 'o'
        || character == 'u') {
        cout << "Vowel";
    }
 
    // Otherwise Consonant
    else {
        cout << "Consonant";
    }
 
    return 0;
}

Java

// Java program to compare
// one variable with multiple
// variable
import java.util.*;
class GFG{
 
// Driver Code
public static void main(String[] args)
{
  // Variable to be compared
  char character = 'a';
 
  // Compare the given variable
  // with vowel using || operator
 
  // Check for vowel
  if (character == 'a' || character == 'e' ||
      character == 'i' || character == 'o' ||
      character == 'u')
  {
    System.out.print("Vowel");
  }
 
  // Otherwise Consonant
  else
  {
    System.out.print("Consonant");
  }
}
}
 
// This code is contributed by 29AjayKumar

Python3

# Python3 program to compare
# one variable with multiple
# variable
 
# Driver Code
if __name__ == '__main__':
   
    # Variable to be compared
    character = 'a';
 
    # Compare the given variable
    # with vowel using or operator
 
    # Check for vowel
    if (character == 'a' or
        character == 'e' or
        character == 'i' or
        character == 'o' or
        character == 'u'):
        print("Vowel");
 
    # Otherwise Consonant
    else:
        print("Consonant");
 
# This code contributed by Princi Singh

C#

// C# program to compare
// one variable with multiple
// variable
using System;
class GFG{
 
// Driver Code
public static void Main(String[] args)
{
  // Variable to be compared
  char character = 'a';
 
  // Compare the given variable
  // with vowel using || operator
 
  // Check for vowel
  if (character == 'a' || character == 'e' ||
      character == 'i' || character == 'o' ||
      character == 'u')
  {
    Console.Write("Vowel");
  }
 
  // Otherwise Consonant
  else
  {
    Console.Write("Consonant");
  }
}
}
 
// This code is contributed by gauravrajput1

Javascript

<script>
 
// javascript program to compare one variable
// with multiple variable
 
  
// Driver Code
 
function checkCharacter(character)
{
  
    // Compare the given variable
    // with vowel using || operator
    // Check for vowel
     
if (character == 'a' || character == 'e' ||
      character == 'i' || character == 'o' ||
      character == 'u')   {
      document.write("Vowel");
    }
  
    // Otherwise Consonant
    else {
        document.write("Consonant");
    }
}
 
// Driver Code
 
checkCharacter('a');
 
// This code is contributed by bunnyram19.
</script>
Producción

Vowel

Método 2: uso de máscara de bits: otro enfoque es verificar entre múltiples grupos de valores y luego crear una máscara de bits de los valores y luego verificar que se establezca ese bit.

Programa 2:

C++

// C++ program to compare a value
// with multiple values
#include <iostream>
using namespace std;
 
// Driver Code
int main()
{
    // Create bitmasks
    unsigned group_1 = (1 << 1) | (1 << 2) | (1 << 3);
    unsigned group_2 = (1 << 4) | (1 << 5) | (1 << 6);
    unsigned group_3 = (1 << 7) | (1 << 8) | (1 << 9);
 
    // Values to be checked
    int value_to_check = 9;
 
    // Checking with created bitmask
    if ((1 << value_to_check)
        & group_1) {
        cout << "found a match in group 1";
    }
    if ((1 << value_to_check)
        & group_2) {
        cout << "found a match in group 2";
    }
    if ((1 << value_to_check)
        & group_3) {
        cout << "found a match in group 3";
    }
 
    return 0;
}

Java

// Java program to compare a value
// with multiple values
import java.util.*;
class GFG{
 
// Driver Code
public static void main(String[] args)
{
    // Create bitmasks
    int group_1 = (1 << 1) |
                  (1 << 2) | (1 << 3);
    int group_2 = (1 << 4) |
                  (1 << 5) | (1 << 6);
    int group_3 = (1 << 7) |
                  (1 << 8) | (1 << 9);
 
    // Values to be checked
    int value_to_check = 9;
 
    // Checking with created bitmask
    if (((1 << value_to_check) &
          group_1) > 0)
    {
        System.out.print("found a match " +
                         "in group 1");
    }
    if (((1 << value_to_check) &
          group_2) > 0)
    {
        System.out.print("found a match " +
                         "in group 2");
    }
    if (((1 << value_to_check) &
          group_3) > 0)
    {
        System.out.print("found a match " +
                         "in group 3");
    }
}
}
 
// This code is contributed by shikhasingrajput

Python3

# Python3 program to compare a value
# with multiple values
 
# Driver Code
if __name__ == '__main__':
     
    # Create bitmasks
    group_1 = (1 << 1) | (1 << 2) | (1 << 3)
    group_2 = (1 << 4) | (1 << 5) | (1 << 6)
    group_3 = (1 << 7) | (1 << 8) | (1 << 9)
     
    # Values to be checked
    value_to_check = 9
     
    # Checking with created bitmask
    if (((1 << value_to_check) & group_1) > 0):
        print("found a match " + "in group 1")
 
    if (((1 << value_to_check) & group_2) > 0):
        print("found a match " + "in group 2")
 
    if (((1 << value_to_check) & group_3) > 0):
        print("found a match " + "in group 3")
 
# This code is contributed by gauravrajput1

C#

// C# program to compare a value
// with multiple values
using System;
class GFG{
 
// Driver Code
public static void Main(String[] args)
{
  // Create bitmasks
  int group_1 = (1 << 1) |
                (1 << 2) |
                (1 << 3);
  int group_2 = (1 << 4) |
                (1 << 5) |
                (1 << 6);
  int group_3 = (1 << 7) |
                (1 << 8) |
                (1 << 9);
 
  // Values to be checked
  int value_to_check = 9;
 
  // Checking with created
  // bitmask
  if (((1 << value_to_check) &
        group_1) > 0)
  {
    Console.Write("found a match " +
                  "in group 1");
  }
  if (((1 << value_to_check) &
        group_2) > 0)
  {
    Console.Write("found a match " +
                  "in group 2");
  }
  if (((1 << value_to_check) &
        group_3) > 0)
  {
    Console.Write("found a match " +
                  "in group 3");
  }
}
}
 
// This code is contributed by gauravrajput1

Javascript

<script>
 
// JavaScript program to compare a value
// with multiple values
 
// Create bitmasks
    let group_1 = (1 << 1) |
                  (1 << 2) | (1 << 3);
    let group_2 = (1 << 4) |
                  (1 << 5) | (1 << 6);
    let group_3 = (1 << 7) |
                  (1 << 8) | (1 << 9);
  
    // Values to be checked
    let value_to_check = 9;
  
    // Checking with created bitmask
    if (((1 << value_to_check) &
          group_1) > 0)
    {
        document.write("found a match " +
                         "in group 1");
    }
    if (((1 << value_to_check) &
          group_2) > 0)
    {
        document.write("found a match " +
                         "in group 2");
    }
    if (((1 << value_to_check) &
          group_3) > 0)
    {
        document.write("found a match " +
                         "in group 3");
    }
 
 
// This code is contributed by unknown2108
 
</script>
Producción

found a match in group 3

Nota : este enfoque funciona mejor para valores que no superan el tamaño natural de su CPU. Por lo general, sería 64 en los tiempos modernos. La solución general a este problema usando Plantilla de C++11 . A continuación se muestra el programa para el mismo:

Programa 3:

C++

// C++ program for comparing variable
// with multiples variable
#include <algorithm>
#include <initializer_list>
#include <iostream>
using namespace std;
 
template <typename T>
 
// Function that checks given variable
// v in the list lst[]
bool is_in(const T& v,
           std::initializer_list<T> lst)
{
    return (std::find(std::begin(lst),
                      std::end(lst), v)
            != std::end(lst));
}
 
// Driver Code
int main()
{
    // Number to be compared
    int num = 10;
 
    // Compare with multiple variables
    if (is_in(num, { 1, 2, 3 }))
        cout << "Found in group" << endl;
    else
        cout << "Not in group" << endl;
 
    // Character to be compared
    char c = 'a';
 
    // Compare with multiple variables
    if (is_in(c, { 'x', 'a', 'c' }))
        cout << "Found in group" << endl;
    else
        cout << "Not in group" << endl;
 
    return 0;
}

Python3

# Python program for above approach
import math
 
# Function that checks given variable
# v in the list lst[]
def is_in(v, lst):
    return v in lst
 
 
# Driver Code
 
# Number to be compared
num = 10
 
# Compare with multiple variables
if (is_in(num, [1, 2, 3] )):
    print("Found in group")
else:
    print("Not in group")
 
# Character to be compared
c = 'a'
 
# Compare with multiple variables
if (is_in(c,  ['x', 'a', 'c'] )):
    print("Found in group")
else:
    print("Not in group")
 
#This code is contributed by shubhamsingh10

C#

// C# program for the above approach
using System;
using System.Linq;
 
public static class Extensions
{
     
    // Function that checks given variable
    // v in the list lst[]
    public static bool is_in<T>(this T[] array,
                                T target)
    {
        return array.Contains(target);
    }
}
 
class GFG{
     
// Driver Code
static public void Main ()
{
     
    // Number to be compared
    int num = 10;
    int [] arr = { 1, 2, 3 };
     
    // Compare with multiple variables
    if (arr.is_in(num))
        Console.WriteLine("Found in group");
    else
        Console.WriteLine("Not in group");
 
    // Character to be compared
    char c = 'a';
    char[] arr1 = { 'x', 'a', 'c' };
     
    // Compare with multiple variables
    if (arr1.is_in(c))
        Console.WriteLine("Found in group");
    else
        Console.WriteLine("Not in group");
}
}
 
// This code is contributed by shubhamsingh10
Producción

Not in group
Found in group

Nota : Sin embargo, no es muy eficiente cuando no se usa con tipos primitivos. Para std::string producirá un error . Esta tarea se volvió realmente fácil con C++17 , ya que viene con Fold Expression . Esto generalmente se llama Folding , que ayuda a expresar la misma idea con menos código y funciona bien con cualquier tipo de datos. Aquí, “||” operador para reducir todos los resultados booleanos a uno solo, que solo es falso si todos los resultados de la comparación son falsos . A continuación se muestra el programa para el mismo:

Programa 4:

C++

// C++ program for comparing variable
// with multiple variables
#include <algorithm>
#include <initializer_list>
#include <iostream>
#include <string>
using namespace std;
 
template <typename First, typename... T>
 
// Function that checks given variable
// first in the list t[]
bool is_in(First&& first, T&&... t)
{
    return ((first == t) || ...);
}
 
// Driver Code
int main()
{
    // Number to be compared
    int num = 10;
 
    // Compare using template
    if (is_in(num, 1, 2, 3))
        cout << "Found in group" << endl;
    else
        cout << "Not in group" << endl;
 
    // String to be compared
    string c = "abc";
 
    // Compare using template
    if (is_in(c, "xyz", "bhy", "abc"))
        cout << "Found in group" << endl;
    else
        cout << "Not in group" << endl;
 
    return 0;
}

Producción: 
 

Publicación traducida automáticamente

Artículo escrito por scorchingeagle y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *