Home > Software engineering >  Why getting absurd result on Permutation caluclator in React?
Why getting absurd result on Permutation caluclator in React?

Time:02-16

I have a calculator for finding Permutation: It displays an alert message when the value of r exceeds n.When r is less than or equal to n,its supposed to give accurate result.But its behaving absurdly. The code for the same in React.js written by me:

 const PnC = () => {
    const [n, setN] = useState(null);
    const [r, setR] = useState(null);
    const [choice, setChoice] = useState("Permutation");
    const [choiceData, setChoiceData] = useState({
      name: "Permutation",
    });
    const [result, setResult] = useState(null);
    useEffect(() => {
      if (choice == "Permutation")
        setChoiceData({ name:"Permutation" });
      else
        setChoiceData({ name:"Combination" });
    }, [choice]);
    const handleChange = (e) => {
      reset();
      setChoice(e.target.value);
    }
    function reset() {
      setN(null);
      setR(null);
      setResult(null);
    }
    function factorial(x){
      var result = 1;
      for (let i = 1; i <= x; i  )
        result *= i;
      return result;
    }
    const calcResult = () => {
      console.log(n,r);
      if (choice == "Permutation") {
        if (n < r)
          alert("The value of n should not be less than r.Please enter valid values for n and r");
        else
          setResult(factorial(n) / factorial(n - r));
      }
      else  if(choice=="Combination"){
        if (n < r)
          alert("The value of n should not be less than r.Please enter valid values for n and r");
        else
          setResult(factorial(n) / (factorial(r) * factorial(n - r)));
      }

    }
    return (
      <>
        <Form>
          <Form.Group className="mb-4" controlId="choice">
            <Form.Label>Select the type of calculation</Form.Label>
            <Form.Control
              as="select"
              className="select-custom-res"
              onChange={(e) => handleChange(e)}
            >
              <option value="Permutation">Permutation</option>
              <option value="Combination">Combination</option>
            </Form.Control>
          </Form.Group>
          <Form.Group className="mb-4" controlId="text">
            <Form.Text className="text">
              <strong>
                To find the {choiceData.name}, Enter the following values
              </strong>
              <br />
            </Form.Text>
          </Form.Group>
          <Form.Group className="mb-4">
            <Form.Label>Value of N</Form.Label>
            <Form.Control
              onChange={(e) => setN(e.target.value)}
              type="number"
              placeholder={"Enter the value of n"}
              value={n === null ? "" : n}
            />
          </Form.Group>
          <Form.Group className="mb-4">
            <Form.Label>Value of R</Form.Label>
            <Form.Control
              onChange={(e) => setR(e.target.value)}
              type="number"
              placeholder={"Enter the value of r"}
              value={r === null ? "" : r}
            />
          </Form.Group>
          <Form.Group className="mb-4">
            <Form.Control
              readOnly
              type="number"
              placeholder={result === null ? "Result" : result   " "}
            />
          </Form.Group>
        </Form>
        <div className="button-custom-grp">
          <Button variant="primary" onClick={calcResult}>
            Calculate
          </Button>
          &nbsp;&nbsp;&nbsp;
          <Button variant="dark" onClick={() => reset()} type="reset">
            Reset
          </Button>
        </div>
      </>
    )
  }

for values like n=8,r=2 I am getting expected results, but for values like n=13,r=2 I am getting my custom alert message The value of n should not be less than r. Please enter valid values for n and r.The same goes for Combination calculator. Why am I getting such absurd results?

CodePudding user response:

Issue

The type of n and r after being updated from the input is type string, not number. This isn't an issue until you attempt a numerical comparison with them.

if (n < r)

It's at this point the is a string comparison position-by-position.

console.log('"8" < "2"', "8" < "2");   // false
console.log('"13" < "2"', "13" < "2"); // true

"1" char code is less than "2" and so the comparison "13" < "2" evaluates true.

Solution

Convert n and r to number type when updating state.

<Form.Group className="mb-4">
  <Form.Label>Value of N</Form.Label>
  <Form.Control
    onChange={(e) => setN(Number(e.target.value))} // <-- convert to number
    type="number"
    placeholder={"Enter the value of n"}
    value={n === null ? "" : n}
  />
</Form.Group>
<Form.Group className="mb-4">
  <Form.Label>Value of R</Form.Label>
  <Form.Control
    onChange={(e) => setR(Number(e.target.value))} // <-- convert to number
    type="number"
    placeholder={"Enter the value of r"}
    value={r === null ? "" : r}
  />
</Form.Group>

Edit why-getting-absurd-result-on-permutation-caluclator-in-react

  • Related