string - Check for continuous order in array in javascript -
var userinput = prompt('enter number here'); var number = new array(userinput.tostring().split('')); if (number ????){ //checks if number in continuous stream alert(correct); } else{ alert(invalid); }
in javascript, can @ "????" check if in continuous order/stream? how can checks order/stream after specific index in array? meaning user enters "12345678901234" pop correct, "12347678901234" pop invalid?(note there 2 7's) second part "3312345678901234" pop correct, how can implemented?
you can make function checks string stream of continuous/increasing alpha-numeric characters starting @ given index this:
function checkcontinuous(str, startindex) { startindex = startindex || 0; if (str.length <= startindex) { return false; } var last = str.charcodeat(startindex); (var = startindex + 1; < str.length; i++) { ++last; if (str.charcodeat(i) !== last) { return false; } } return true; }
if it's numbers , wrapping 9 0 considered continuous, it's little more complicated this:
function checkcontinuous(str, startindex) { // make sure startindex set 0 if not passed in startindex = startindex || 0; // skip chars before startindex str = str.substr(startindex); // string must @ least 2 chars long , must numbers if (str.length < 2 || !/^\d+$/.test(str)) { return false; } // first char code in string var last = str.charcodeat(0); // rest of string, compare last code (var = 1; < str.length; i++) { // increment last charcode can compare sequence if (last === 57) { // if 9, wrap 0 last = 48; } else { // else increment ++last; } // if find 1 char out of sequence, it's not continuous return false if (str.charcodeat(i) !== last) { return false; } } // continuous return true; }
working demo: http://jsfiddle.net/jfriend00/rhh4b/
Comments
Post a Comment