2016-08-22 12 views
0

그래서 내가 두 개의 데이터가 나는 루프에 대해 동일한 얻으려고하는 상황이있다 (물론 나는 루프에 대한 동일한 나오고 싶지 않다 반복적 인 코드가 있음).두 개의 변수에 대한 같은 루프에 대한 해결

finalFloor에 대한 검색 중입니다. 내 데이터 배열도 나를 필요로합니다. 하지만 주소 []의 어떤 인덱스에서 변수 currentFloor가 음수 값이되는지 찾고 있습니다.

아래 코드는 현재 찾고있는 최종 목표를 제외하고 동일한 코드 (원하지 않는 코드 작성 방식은 아님)를 실행하는 두 개의 별도 함수 (floorCalculator & inTheBasement)로 실행합니다. 나는 이것을 결합하는 방법을 알아 내려고 애쓰는 데 정말 고심하고있다. 어떤 아이디어 또는 포인터? 도와 주셔서 감사합니다! 첫 번째 for 루프에서 currentFloor < 0에 대한

/* ----------------- Declaration of Variables ---------------- */ 
var up = '('; // represents moving up 1 floor. 
var down = ')'; // represents moving down 1 floor. 
var input_form = $('#input-form'); // represents the html input form. 
var userInput = input_form.find('#address-input'); // represents the finding of the user's input. 
var input; // stores user input value. 
var address = []; // stores user's input value as an array of characters. 
var currentFloor = 0; // represents the current floor in the for loop, set to ground floor (0). 
var finalFloor; // represents the ending floor from the instructions given. 
var results = $('.results'); // represents the div .results for appending data to. 

/* ----------------- Parent Function ---------------- */ 
$(document).ready(initLoad); 

/* ----------------- Child Functions ---------------- */ 
function initLoad() 
{ 
    input_form.submit(function(event) // Listens for submission event at #input-form. 
{ 
event.preventDefault(); // Prevents default method of html element. 
takeInAddress();   // Calls function. 
}); 
}; 


function takeInAddress() 
{ 
    input = userInput.val(); // Stores the user input found at #address-input as var input. 
    userInput.val('');   // Clears the input field for next user input. 
    address = input.split(''); // Splits the string input into single characters stored now in the array address[ ]. 
    floorCalculator();   // Calls funciton. 
}; 

function floorCalculator() 
{ 
    for (var i = 0; i < address.length; i++) 
    { 
    if (address[i] == up) // For any '(' present at the current index... 
    { 
     currentFloor++; // Increase the value of currentFloor by 1. 
    } 
    else if (address[i] == down) // For any ')' present at the current index... 
    { 
    currentFloor--; // Decrease the value of currentFloor by 1. 
    } 
    } // end for loop 
    finalFloor = currentFloor; // Store the value of currentFloor now as finalFloor. 
    // console.log(finalFloor); 
    results.append('<h2>Floor to deliver to: ' + finalFloor + '</h2>'); // Append finalFloor value to .results html. 
    inTheBasement(); // Calls function. 
}; 

function inTheBasement() 
{ 
    currentFloor = 0; // Resets currentFloor to zero. 
    for (var i = 0; i < address.length; i++) 
    { 
    if (address[i] == up) // For any '(' present at the current index... 
    { 
     currentFloor++; // Increase the value of currentFloor by 1. 
    } 
    else if (address[i] == down) // For any ')' present at the current index... 
    { 
     currentFloor--; // Decrease the value of currentFloor by 1. 
     if (currentFloor < 0) // if currentFloor becomes a negative value... 
     { 
     // console.log(i); 
     // Append value of i 
     results.append('<h2>When you will arrive in the basement: ' + i + 'th instruction. </h2>'); 
     break; // break from loop 
     } // end if loop 
    } // end else if loop 
    } // end for loop 
    }; 

답변

0

그래서 첫 번째 루프는 "reduce"의 고전적인 사용 사례입니다. 배열을 단일 값으로 바꿉니다.

감소

함수 소요되며, 옵션으로 기본 값 : 우리는 줄이기 위해 전달 될 때, 함께 배열의 모든 값을 추가하는 함수를 작성하는거야

[1,2,1,1].reduce(aFunction, startValue) 

. reduce로 전달하는 함수는 함수 호출 사이에 상태를 저장하고 그 사이를 전달하는 '메모'와 배열에 다음 값을 나타내는 'value'를 하나씩 전달하는 두 가지 값을 받아 들여야합니다 . 값을 고려한 후 상태가 무엇이든 반환해야하며 반환되는 값은 배열의 다음 값과 함께 다음 호출에서 함수로 다시 전달됩니다.

[1,2,1,1].reduce((memo, value) => value + memo, 0) 

유일한 :

(memo, value) => value + memo 
// the return statement is implicit in this syntax 
결과

, 우리의 기능과 우리의 시작 값을 전달은 하나 라이너된다 :

function aFunction(value, memo) { 
    return value + memo; 
} 
startValue = 0; // we start with 0 for our use case 

우리는이 같은 함수 구문을 짧게 만들 수 있습니다 필요한 지식의 다른 부분은 삼항이다 :

(memo, value) => value === ")" ? memo + 1 : memo - 1 
우리는이 모든 일에 감소 호출을 수행하려는 경우 우리가 우리의 메모에 따라 좀 더 상태를 통과하고, 다른 평가를 할 필요가,

function (memo, value) { 
    if (value === ")") { 
     return memo + 1; 
    } 
    else { 
     return memo - 1; 
    } 
} 

마지막 :

위는 동일합니다. 모든 값

ourInput = ")()()((())))))()()()(".split(""); 
// it's now an array, as you know 
state = { floor: 0, basementTrigger: false, becameNegative: undefined }; 
result = ourInput.reduce((memo, value, index) => { 
    memo.floor += value === "(" ? 1 : -1; // add either 1 or negative one to our floor 
    if (!memo.basementTrigger && memo.floor < 0) { 
     memo.becameNegative = index 
     memo.basementTrigger = true; 
    } 
    return memo; 
}, state) // state is passed in as 'memo' on the inner functions's first call 

이 :

  • 추가하거나 value"("가 있는지 여부에 기초하여, 바닥으로부터 감산 중 하나.트리거가 거짓이고, 바닥 부의 경우
  • , 그것은 :

    :
    다음

우리가 추가 true로 트리거를 화나게하고, 현재의 인덱스를 저장

output += ("result = " + result.floor); 
if (result.basementTrigger) output += ("follow instruction: " + result.becameNegative) 

대체적으로이 질문에 도움이되기를 바랍니다.

면책 조항 : 교정이나 테스트 코드를 작성하지 않았거나 실수 일 수 있습니다. 내 목표는 당신에게 코드를 제공하는 것이 아니라 개념을 보여주는 것입니다. 이것은 해킹 된 렌더링이 신속하게 발생하지만 사용자가 직접 사용할 수있는 도구를 설명해야합니다.

+0

예 (바닥에 올랐다가 바닥에 있음) 7000 개의 괄호가있는 문자열입니다. 그래서 문자열을 .split ("")에 전달하여 문자열을 7000 자로 분리하고 배열 주소 []에 저장했습니다. 그런 다음 가장 쉬운 방법은 for 루프를 사용하여 배열을 반복하면서 "up"또는 "down"을 누른 다음 현재 바닥에 +/- 1을 묻는 것입니다. 보낸 코드를 설명해 주시겠습니까? 나는 여전히 JS & jQuery를 처음 사용하고있다. – rockchalkwushock

+0

기쁘게 생각합니다.하지만 우선 : 지금 코드를 이해하고 있다고 생각합니다. 확실하게 할 수 있습니까? 네가 '부정'이라면 '지하실'이 0을 반환하고 그렇지 않으면 아무것도 반환하지 않겠습니까? –

+0

@Cody, 이것이 작동하는지 알려주세요. 답변을 완전히 다시 작성했습니다. 나는 당신의 코드를 이해했다고 믿지만, 당신은 내게 알려야 할 것이다. –

0

확인합니다. 메시지를 두 번 인쇄하지 않으려면 변수를 사용하여 이미 수행했는지 기억하십시오.

function floorCalculator() 
{ 
    var foundBasement = false; 
    var basementStep; 
    for (var i = 0; i < address.length; i++) 
    { 
    if (address[i] == up) // For any '(' present at the current index... 
    { 
     currentFloor++; // Increase the value of currentFloor by 1. 
    } 
    else if (address[i] == down) // For any ')' present at the current index... 
    { 
    currentFloor--; // Decrease the value of currentFloor by 1. 
    if (currentFloor < 0 && !foundBasement) { 
     foundBasement = true; 
     basementStep = i; 
    } 
    } 
    } // end for loop 
    finalFloor = currentFloor; // Store the value of currentFloor now as finalFloor. 
    // console.log(finalFloor); 
    results.append('<h2>Floor to deliver to: ' + finalFloor + '</h2>'); // Append finalFloor value to .results html. 
    if (foundBasement) { 
    results.append('<h2>When you will arrive in the basement: ' + basementStep + 'th instruction. </h2>'); 
    } 
}; 
+0

감사합니다. currentFloor <0을 else else 문 안에 넣는 것이 옳았다. currentFloor의 모든 부정적인 인스턴스를 반복하지 않고도이를 해결할 수있는 방법을 찾지 못했습니다. 정말 도움에 감사 드리며이 전략을 기록 할 것입니다! – rockchalkwushock

관련 문제