Mark
Mark

Reputation: 15

How to utilize JS to calculate the median from numbers inputted by the user

So in finance, sometimes finding the average of a salary does not make sense. For example, if someone really wealthy and someone in need had their salaries compared, that would be a really uneven average. Therefore, a median makes more sense to see what is in between. I want to try and recreate this but would like to know what you guys believe are the first steps.

var input = [];
var output = 0;
var t1 = 0;
var t2 = 0;

//variables setting start 
function reset(){
    input = [];
    output = 0;
    t1 = 0;
    t2 = 0;
}
//variables setting end

//caller functions start
function start(){
    reset();
    t1 = prompt("how many inputs do you want");//asking for how many inputs are wanted 
    do{// repeat until loop
        t2 = 0;
        t2 = prompt("Enter values for the array");//this is how the inputs are entered 
        input.push(t2);
    }while(input.length < t1);//waiting for condition to be met
    t1 = 0;
    input.sort(sortNumber);
    checking();
    if(t1 == 0){
    logic();
    }
}
//caller functions end 

//logic for sorting the numbers start 
function sortNumber(a, b) {
    return a - b;
}
//logic for sorting the numbers end 

// logic for finding the median start
function logic(){
    var i = 0;
    t1 = 0;
    t2 = 0;
    if(input.length % 2 == 0){
        t1 = input.length / 2;
        i = t1;
        t1 = t1 - 1;
        t2 = input[i] + input[t1];
        output = t2 / 2;
        console.log(output);
    }else{
        t1 = input.length / 2;
        t1 = t1 - 0.5;
        output = input[t1];
        console.log(output);
    }
}
//logic for finding the median end 

// logic for checking the input end 
function checking(){
    i = 0;
    do{
        if(input[i] > 0){
            if(input[i] / 1 == input[i]){
                i = i + 1;
            }else{
                console.log("you have something other then a positive integer");
                i = i + 1;
                t1 = 1;
            }
        }else{
            console.log("you have something other then a positive integer");
            i = i + 1;
            t1 = 1;
        }
    }while(i < input.length);
}
//logic for checking the input end 

Here is what I tried to achieve in my code: 1 < len(data) ≤ 1000 all(0 ≤ x < 10 ** 6 for x in data)

Upvotes: 0

Views: 177

Answers (1)

Cat
Cat

Reputation: 4246

For anyone who doesn't already know, JavaScript input/output is usually asynchronous, and listener functions can respond to clicks or other user actions in real time.

Here's a way to use them to handle calculating a median from user inputs (intentionally verbose for clarity):

/* Note: if you just want to see the math part, skip to the bottom */

// Defines globals
const
  numbers = [],
  inputElement = document.getElementById("input"),
  outputParagraph = document.getElementById("outputParagraph"),
  enterBtn = document.getElementById("enterBtn"),
  calcBtn = document.getElementById("calcBtn");

// Adds Listeners
enterBtn.addEventListener("click", addToArray);
calcBtn.addEventListener("click", calculateAndDisplayMedian);


//
// Defines Listeners
//

function addToArray(){

  // Gets the entered value (and ignores empty strings)
  let value = inputElement.value;
  if(!value.length){
    return;
  }
  
  // Coverts the value to an integer (Note: This technique truncates decimals)
  let num = parseInt(value);
  
  // Complains if the value can't be converted to a positive integer
  //   (won't happen if the HTML Input Element is doing its job)
  if(!num || num <= 0){
    outputParagraph.innerHTML = "Please enter a positive integer";
  }

  // Adds the number to the array, and clears the input
  else{
    numbers.push(num); 
    inputElement.value = "";
    outputParagraph.innerHTML = "";
  }

  // Puts the cursor back in the input
  inputElement.focus();
}


function calculateAndDisplayMedian(){

  // Automatically adds to the array any number still in the input field
  addToArray();

  // Declares local variables
  let length = numbers.length;
  let median;

  // Makes sure there is at least one number before proceeding
  if(length == 0){
    return;
  }
  
  // Sorts the array
  numbers.sort( (a, b) => a - b);

  // If the the count of numbers is odd, the middle one is the median
  if(length % 2 == 1){
    let index = length / 2 - 0.5;
    median = numbers[index];
  }
  // Otherwise, the average of the two middle numbers is the median
  else{
    let
      index1 = length / 2 - 1,
      index2 = length / 2,
      num1 = numbers[index1],
      num2 = numbers[index2];
    median = (num1 + num2) / 2;
  }
  
  // Reports the result and empties the array
  outputParagraph.innerHTML = "The median is " + median;
  numbers.length = 0;
}
<!--
The 'input HTML Element can do some of our validation automatically 
(as long as the environment where the script runs supports the attributes used)
-->
<input id="input" type="number" min="1" />
<button id="enterBtn">Enter</button>
<button id="calcBtn">Calculate Median</button>
<p id="outputParagraph"></p>

Upvotes: 1

Related Questions