Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- document.getElementById("submit").onclick =
- function(){
- let result = '';
- let input= document.getElementById("left").value;
- let check = input.split(',');
- if(check.length !== 2){
- result = " Wrong Input, Input can and must be two digits"
- }
- //return;
- let weigh = document.getElementById("weights-array").value;
- let checkWeight= weigh.split(',');
- if(checkWeight.length < 2){
- result = " Wrong Input, Input must be greater than two digits"
- }
- let arr = [check, checkWeight];
- return;
- function balanceScale(arr){
- //Firstly, we need to convert our strings to numbers we can use in the Array
- let scaleWeights = arr[0].match(/d+/g).map(Number);
- let weights = arr[1].match(/d+/g).map(Number);
- let leftSide = scaleWeights[0];
- let rightSide = scaleWeights[1];
- // Secondly, we check for adding weight to one side of the scale i.e leftside or rightside
- for(let i = 0; i < weights.length; i++){
- if(leftSide < rightSide){
- if(leftSide + weights[i] === rightSide){
- result = weights[i];
- return result;
- }else if(rightSide + weights[i] === leftSide){
- result = weights[i];
- return result;
- }
- }
- }
- //Thirdly, we check for adding weights to both sidess of the scale ie. leftside && rightside
- let i,j;
- for(i = 0; i < weights.length; i++){
- for(j =0; j < weights.length[i]; j++){
- if(leftSide + weights[i] === rightSide + weights[j]){
- result = weights[i] + ' ' + weights[j];
- return result;
- }else if(rightSide + weights[i] === leftSide + weights[j]){
- result = weights[i] + ' ' + weights[j];
- return result;
- }
- }
- }
- //Lastly we check to add (2) two weights to one side of the scale
- if( leftSide + weights[i] + weights[j] === rightSide){
- result = weights[i] + ' ' + weights[j];
- return result;
- }else if (rightSide + weights[i] + weights[j] === leftSide){
- result = weights[i] + ' ' + weights[j];
- return result;
- }
- // if there are no matching weights
- result = "Scale Imbalanced";
- return result;
- }
- document.getElementById("displayresult").innerHTML = result;
- }
- console.log(balanceScale(["[3, 6]", "[1, 2, 7, 7]"]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement