Javascript loop. What am I doing wrong? - javascript

Trying to make a loop that outputs 2 to the power of 0-31. So far I only have it giving me 2 to the power of 31. What am I doing wrong?
function findPower()
{
var answer=0;
for(var i=0;i<=31;i++)
{
answer=Math.pow(2,i);
}
document.getElementById("output").innerHTML=answer;
}

Because in the loop in each iteration you are overriding the value of answer, so at the end it will have the value of last iteration only.
If you want to iterate the value of each number, then an easy solution is to push them to an array and after the loop join them to create the answer string as below
function findPower() {
var answer = [];
for (var i = 0; i <= 31; i++) {
answer.push(Math.pow(2, i));
}
document.getElementById("output").innerHTML = answer.join(', ');
}
function findPower() {
var answer = [];
for (var i = 0; i <= 31; i++) {
answer.push(Math.pow(2, i));
}
document.getElementById("output").innerHTML = answer.join(', ');
}
findPower();
<div id="output"></div>

You statement inside loop "document.getElementById("output").innerHTML=answer;" is overriding previous value so you are getting the last value. So what I did is to concatinate the values instead of overriding previous values
it should like following
function findPower() {
var answer = 0;
for (var i = 0; i <= 31; i++) {
answer = Math.pow(2, i);
document.getElementById("output").innerHTML = document.getElementById("output").innerHTML + "," + answer
}
}
<body onload="return findPower();">
</body>
<span id="output"></span>

If I get you right you want to calculate a sum of powers of 2:
for (var i = 0; i <= 31; i++) {
answer += Math.pow(2, i);
}
Notice the "+" sign. Writing:
answer += Math.pow(2, i);
Is the same as writing:
answer = answer + Math.pow(2, i);

Maybe it's better and faster.
function findPower() {
var answer = [];
var pow = 1;
answer.push(pow);
for (var i = 1; i <= 31; i++) {
pow *= 2;
answer.push(pow);
}
document.getElementById("output").innerHTML = answer.join(', ');
}

Related

All possible words of any length from the input letters, javascript [duplicate]

I'm trying to create a function in JavaScript that given a string will return an array of all possible combinations of the letters with each used at most once, starting with the shortest. e.g for the string ABC it would return:
A
B
C
AB
AC
ABC
I could use loops like so:
for(i=0; i<string.length; i++) {
//add string[i]
}
for(i=0; i<string.length; i++) {
for(a=i; a<string.length; a++) {
//add string[i]+string[a]
}
}
for(i=0; i<string.length; i++) {
for(a=i; a<string.length; a++) {
for(b=a; b<string.length; b++) {
//add string[i]+string[a]+string[b]
}
}
}
But I don't know the length of the string, so wouldn't know how many loops to use.
Any ideas?
Edit: I'm not asking for permutations, abc and acb shouldn't both be returned. Also the shortest being first in the array is important.
This is not homework. It's for a program to solve a 'lights-out' type game.
This is a recursive solution that I think is very easy to understand.
var tree = function(leafs) {
var branches = [];
if (leafs.length == 1) return leafs;
for (var k in leafs) {
var leaf = leafs[k];
tree(leafs.join('').replace(leaf, '').split('')).concat("").map(function(subtree) {
branches.push([leaf].concat(subtree));
});
}
return branches;
};
console.log(tree("abc".split('')).map(function(str) {
return str.join('')
}))
You could use a nasty trick and increase a counter and use its binary representation as flags:
function combine(str){
const result = [];
for(let i = 1; i < Math.pow(2, str.length) - 1; i++)
result.push([...str].filter((_, pos) => (i >> pos) & 1).join(""));
return result;
}
console.log(combine('abcd'));
Jsbin
This is what I ended up using.
var combinations = function (string)
{
var result = [];
var loop = function (start,depth,prefix)
{
for(var i=start; i<string.length; i++)
{
var next = prefix+string[i];
if (depth > 0)
loop(i+1,depth-1,next);
else
result.push(next);
}
}
for(var i=0; i<string.length; i++)
{
loop(0,i,'');
}
return result;
}
This is usiing loop as you expected easiest way.. good luck
function mixString() {
var inputy = document.getElementById("mixValue").value
var result = document.getElementById("mix-result")
result.innerHTML=""
for (var i = 0 ; i < inputy.length; i++) {
for (var b = 0 ; b < inputy.length; b++) {
if (i == b) {
result.innerHTML += inputy.charAt(i) + ","
}
else
{
result.innerHTML += inputy.charAt(i) + inputy.charAt(b) + ","
}
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">JavaScript string combination
</div>
<div class="panel-body">
<input id="mixValue" class="form-control" />
<input type="button" onclick="mixString()" value="click" />
<div id="mix-result"></div>
</div>
</div>
</div>
function combinations(var1) {
var temp;
for (var i = 0; i < var1.length; i++) {
var2 = "";
temp = i;
while (temp < var1.length) {
var2 = var2.concat(var1.charAt(temp));
// console.log(var2)
if (i == var1.length - 1)
document.getElementById('result').innerHTML += var2;
else
document.getElementById('result').innerHTML += var2 + ',';
temp++;
}
}
}
You couldm take an iterative and recursive approach by using the character at the given key or not.
function combine(string) {
function iter(i, temp) {
if (i >= string.length) {
result.push(temp);
return;
}
iter(i + 1, temp + string[i]);
iter(i + 1, temp);
}
var result = [];
iter(0, '');
return result;
}
console.log(combine('jump'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
The accepted solution as of July 29, 2019 allows for duplicate strings to be returned in the array. The following adjustment fixes that little issue by adding a condition to the push.
// however, we don't want duplicates so...
if (!result.includes(next)) {
result.push(next);
}
Generators allow a very clean implementation:
// Very short generator produces all possible strings composed of the given chars!
let allStrings = function*(chars) {
yield '';
for (let prefix of allStrings(chars)) for (let c of chars) yield `${prefix}${c}`;
};
// Render the first 1000 strings
document.body.style.fontFamily = 'monospace';
let count = 0;
for (let str of allStrings('abcd')) {
let div = document.createElement('div');
div.innerHTML = `${(count + 1).toString().padStart(4, '0')}: ${str}`;
document.body.appendChild(div);
if (count++ > 1000) break;
}
Note that the very first result from allStrings is the empty string. If it's crucial to avoid this the following implementation can be used:
let allStrings = function*(chars, includeEmpty=false) {
if (includeEmpty) yield '';
for (let prefix of allStrings(chars, true)) for (let c of chars) yield `${prefix}${c}`;
};
//all combinations of a string
// dog => d,do,dog,og,g
function combinationString(){
let str = 'dog';
let combinationArray = [];
for(i=0; i< str.length; i++){
for(j=i+1; j<=str.length; j++){
combinationArray.push(str.slice(i,j));
}
}
console.log("Combination ", combinationArray);
}
combinationString()

Counting numbers in an random array

So I'm trying to find how many of each number from zero to ten is generated in a random array.
I created a random array list
i=0;
var ranList=[];
while (i<20){
i++;
ranList.push(Math.floor(10*Math.random()));
}
//count each number
document.write(ranList.sort().join("<br>"));
/*Then I made a function to count /elements from this array
*/
function ctnumber(array,elem){
var ct=0;
var j =0;
while(j<array.length)
{
j++;
if(array[j]==elem){
ct+=1;}
}
}
return ct;
}
alert(ctnumber(ranList,5));
The second function doesn't execute, any idea why?
Thank you!
First you should avoid using the name array for you variable:
http://www.w3schools.com/js/js_reserved.asp
Your brackets are also wrong. Change your function to this and it should work:
function ctnumber(arr,elem){
var ct=0;
var j =0;
while(j<arr.length)
{
j++;
if(arr[j]==elem){
ct+=1;}
}
return ct;
}
The problem with your code, as stated by Pardeep in his comment, is that you have an extra } after your ct+=1; in your second while loop.
The correct code would be: Fiddle
i = 0;
var ranList = [];
while (i < 20) {
i++;
ranList.push(Math.floor(10 * Math.random()));
}
//count each number
document.write(ranList.sort().join("<br>"));
function ctnumber(array, elem) {
var ct = 0;
var j = 0;
while (j < array.length) {
j++;
if (array[j] == elem) {
ct += 1; // NOTE NO } HERE NOW
}
}
return ct;
}
alert(ctnumber(ranList, 5));
I also suggest a bit of a code cleanup:
var i = 0;
var ranList = [];
while (i < 20) {
i++;
ranList.push(Math.floor(10 * Math.random());
}
function countNumbers(list, elem) {
var count = 0;
// For loops are generally more readable for looping through existing lists
for (var i = 0; i < list.length; i++) {
if (list[i] == elem) {
count++;
}
}
return count;
}
alert(countNumber(ranList, 5));
Please note that console.log() is a much better debugging tool, it can be accessed by F12 in Firefox and Chrome/IE.

How can I use for loop to count numbers?

I need to count numbers upward and have it print out with a string "then" in between: 5 then 6 then 7 then... like this. I am very confused with using the parameters vs function name when you return. My code is below.. but could someone help with this?
function countUp(start) {
start +=
for(var i = start; i < start + 10; i++) {
console.log(start[i] + "then");
}
return start;
}
I would do something like this:
function countSheep(limit){
for (var i = 1; i < limit; i +=1){
console.log(i + " sheep")
}
}
countSheep(10);
I used "sheep" instead of "then", but you get the idea. Since you just want to produce a side effect (print out a "1 then 2.." to the console, you don;t need to build up a string and then have your function return it.
If you did want to build up a string and then have your function return it though, you could do something like this instead:
function countSheep(limit){
var allMySheep = "";
for (var i = 1; i < limit; i +=1){
allMySheep += (i + " sheep, ")
}
return allMySheep;
}
console.log(countSheep(10));
Note: I started my loops at 1 (var i = 1) because I'm counting sheep, not numbers. You'd probably want to start yours at 0 (var i = 0).
We can use JavaScript join function as well to achieve this
Code
function getCountStr(count) {
var str =[];
for (var i = 1; i <= count; i++) {
str.push(i);
}
console.log(str.join(' then '));
}
There are few issues with your code
function countUp(start) {
start += // <<<<< what's this? It's an incomplete (and useless) statement
for(var i = start; i < start + 10; i++) {
console.log(start[i] + "then");
// ^^^^^^^^ why are doing this? you should only write i
}
return start; // you don't need to return anything
}
A cleaned and working version from your code
function countUp(start) {
for(var i = start; i < start + 10; i++) {
console.log(i + " then ");
}
}
But this code will have an extra 'then' at the end like 1 then 2 then, so here's a code that will handle this
function countUp(start) {
// a temporary array to store your numbers
var tmpArr = [];
for (var i = start; i < start + 10; i++) {
// store the count into the array
tmpArr.push(i);
}
// display the count by putting ' then ' between each number
var stringToDisplay = tmpArr.join(' then ');
console.log(stringToDisplay);
document.write(stringToDisplay);
}
countUp(1);

get all combinations for a string

I'm trying to create a function in JavaScript that given a string will return an array of all possible combinations of the letters with each used at most once, starting with the shortest. e.g for the string ABC it would return:
A
B
C
AB
AC
ABC
I could use loops like so:
for(i=0; i<string.length; i++) {
//add string[i]
}
for(i=0; i<string.length; i++) {
for(a=i; a<string.length; a++) {
//add string[i]+string[a]
}
}
for(i=0; i<string.length; i++) {
for(a=i; a<string.length; a++) {
for(b=a; b<string.length; b++) {
//add string[i]+string[a]+string[b]
}
}
}
But I don't know the length of the string, so wouldn't know how many loops to use.
Any ideas?
Edit: I'm not asking for permutations, abc and acb shouldn't both be returned. Also the shortest being first in the array is important.
This is not homework. It's for a program to solve a 'lights-out' type game.
This is a recursive solution that I think is very easy to understand.
var tree = function(leafs) {
var branches = [];
if (leafs.length == 1) return leafs;
for (var k in leafs) {
var leaf = leafs[k];
tree(leafs.join('').replace(leaf, '').split('')).concat("").map(function(subtree) {
branches.push([leaf].concat(subtree));
});
}
return branches;
};
console.log(tree("abc".split('')).map(function(str) {
return str.join('')
}))
You could use a nasty trick and increase a counter and use its binary representation as flags:
function combine(str){
const result = [];
for(let i = 1; i < Math.pow(2, str.length) - 1; i++)
result.push([...str].filter((_, pos) => (i >> pos) & 1).join(""));
return result;
}
console.log(combine('abcd'));
Jsbin
This is what I ended up using.
var combinations = function (string)
{
var result = [];
var loop = function (start,depth,prefix)
{
for(var i=start; i<string.length; i++)
{
var next = prefix+string[i];
if (depth > 0)
loop(i+1,depth-1,next);
else
result.push(next);
}
}
for(var i=0; i<string.length; i++)
{
loop(0,i,'');
}
return result;
}
This is usiing loop as you expected easiest way.. good luck
function mixString() {
var inputy = document.getElementById("mixValue").value
var result = document.getElementById("mix-result")
result.innerHTML=""
for (var i = 0 ; i < inputy.length; i++) {
for (var b = 0 ; b < inputy.length; b++) {
if (i == b) {
result.innerHTML += inputy.charAt(i) + ","
}
else
{
result.innerHTML += inputy.charAt(i) + inputy.charAt(b) + ","
}
}
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">JavaScript string combination
</div>
<div class="panel-body">
<input id="mixValue" class="form-control" />
<input type="button" onclick="mixString()" value="click" />
<div id="mix-result"></div>
</div>
</div>
</div>
function combinations(var1) {
var temp;
for (var i = 0; i < var1.length; i++) {
var2 = "";
temp = i;
while (temp < var1.length) {
var2 = var2.concat(var1.charAt(temp));
// console.log(var2)
if (i == var1.length - 1)
document.getElementById('result').innerHTML += var2;
else
document.getElementById('result').innerHTML += var2 + ',';
temp++;
}
}
}
You couldm take an iterative and recursive approach by using the character at the given key or not.
function combine(string) {
function iter(i, temp) {
if (i >= string.length) {
result.push(temp);
return;
}
iter(i + 1, temp + string[i]);
iter(i + 1, temp);
}
var result = [];
iter(0, '');
return result;
}
console.log(combine('jump'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
The accepted solution as of July 29, 2019 allows for duplicate strings to be returned in the array. The following adjustment fixes that little issue by adding a condition to the push.
// however, we don't want duplicates so...
if (!result.includes(next)) {
result.push(next);
}
Generators allow a very clean implementation:
// Very short generator produces all possible strings composed of the given chars!
let allStrings = function*(chars) {
yield '';
for (let prefix of allStrings(chars)) for (let c of chars) yield `${prefix}${c}`;
};
// Render the first 1000 strings
document.body.style.fontFamily = 'monospace';
let count = 0;
for (let str of allStrings('abcd')) {
let div = document.createElement('div');
div.innerHTML = `${(count + 1).toString().padStart(4, '0')}: ${str}`;
document.body.appendChild(div);
if (count++ > 1000) break;
}
Note that the very first result from allStrings is the empty string. If it's crucial to avoid this the following implementation can be used:
let allStrings = function*(chars, includeEmpty=false) {
if (includeEmpty) yield '';
for (let prefix of allStrings(chars, true)) for (let c of chars) yield `${prefix}${c}`;
};
//all combinations of a string
// dog => d,do,dog,og,g
function combinationString(){
let str = 'dog';
let combinationArray = [];
for(i=0; i< str.length; i++){
for(j=i+1; j<=str.length; j++){
combinationArray.push(str.slice(i,j));
}
}
console.log("Combination ", combinationArray);
}
combinationString()

What's the best way to break from nested loops in JavaScript? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 months ago.
Improve this question
What's the best way to break from nested loops in Javascript?
//Write the links to the page.
for (var x = 0; x < Args.length; x++)
{
for (var Heading in Navigation.Headings)
{
for (var Item in Navigation.Headings[Heading])
{
if (Args[x] == Navigation.Headings[Heading][Item].Name)
{
document.write("<a href=\""
+ Navigation.Headings[Heading][Item].URL + "\">"
+ Navigation.Headings[Heading][Item].Name + "</a> : ");
break; // <---HERE, I need to break out of two loops.
}
}
}
}
Just like Perl,
loop1:
for (var i in set1) {
loop2:
for (var j in set2) {
loop3:
for (var k in set3) {
break loop2; // breaks out of loop3 and loop2
}
}
}
as defined in EMCA-262 section 12.12. [MDN Docs]
Unlike C, these labels can only be used for continue and break, as Javascript does not have goto.
Wrap that up in a function and then just return.
I'm a little late to the party but the following is a language-agnostic approach which doesn't use GOTO/labels or function wrapping:
for (var x = Set1.length; x > 0; x--)
{
for (var y = Set2.length; y > 0; y--)
{
for (var z = Set3.length; z > 0; z--)
{
z = y = -1; // terminates second loop
// z = y = x = -1; // terminate first loop
}
}
}
On the upside it flows naturally which should please the non-GOTO crowd. On the downside, the inner loop needs to complete the current iteration before terminating so it might not be applicable in some scenarios.
I realize this is a really old topic, but since my standard approach is not here yet, I thought I post it for the future googlers.
var a, b, abort = false;
for (a = 0; a < 10 && !abort; a++) {
for (b = 0; b < 10 && !abort; b++) {
if (condition) {
doSomeThing();
abort = true;
}
}
}
Quite simple:
var a = [1, 2, 3];
var b = [4, 5, 6];
var breakCheck1 = false;
for (var i in a) {
for (var j in b) {
breakCheck1 = true;
break;
}
if (breakCheck1) break;
}
Here are five ways to break out of nested loops in JavaScript:
1) Set parent(s) loop to the end
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
{
i = 5;
break;
}
}
}
2) Use label
exit_loops:
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
break exit_loops;
}
}
3) Use variable
var exit_loops = false;
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
{
exit_loops = true;
break;
}
}
if (exit_loops)
break;
}
4) Use self executing function
(function()
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
return;
}
}
})();
5) Use regular function
function nested_loops()
{
for (i = 0; i < 5; i++)
{
for (j = 0; j < 5; j++)
{
if (j === 2)
return;
}
}
}
nested_loops();
var str = "";
for (var x = 0; x < 3; x++) {
(function() { // here's an anonymous function
for (var y = 0; y < 3; y++) {
for (var z = 0; z < 3; z++) {
// you have access to 'x' because of closures
str += "x=" + x + " y=" + y + " z=" + z + "<br />";
if (x == z && z == 2) {
return;
}
}
}
})(); // here, you execute your anonymous function
}
How's that? :)
How about using no breaks at all, no abort flags, and no extra condition checks. This version just blasts the loop variables (makes them Number.MAX_VALUE) when the condition is met and forces all the loops to terminate elegantly.
// No breaks needed
for (var i = 0; i < 10; i++) {
for (var j = 0; j < 10; j++) {
if (condition) {
console.log("condition met");
i = j = Number.MAX_VALUE; // Blast the loop variables
}
}
}
There was a similar-ish answer for decrementing-type nested loops, but this works for incrementing-type nested loops without needing to consider each loop's termination value for simple loops.
Another example:
// No breaks needed
for (var i = 0; i < 89; i++) {
for (var j = 0; j < 1002; j++) {
for (var k = 0; k < 16; k++) {
for (var l = 0; l < 2382; l++) {
if (condition) {
console.log("condition met");
i = j = k = l = Number.MAX_VALUE; // Blast the loop variables
}
}
}
}
}
If you use Coffeescript, there is a convenient "do" keyword that makes it easier to define and immediately execute an anonymous function:
do ->
for a in first_loop
for b in second_loop
if condition(...)
return
...so you can simply use "return" to get out of the loops.
I thought I'd show a functional-programming approach. You can break out of nested Array.prototype.some() and/or Array.prototype.every() functions, as in my solutions. An added benefit of this approach is that Object.keys() enumerates only an object's own enumerable properties, whereas "a for-in loop enumerates properties in the prototype chain as well".
Close to the OP's solution:
Args.forEach(function (arg) {
// This guard is not necessary,
// since writing an empty string to document would not change it.
if (!getAnchorTag(arg))
return;
document.write(getAnchorTag(arg));
});
function getAnchorTag (name) {
var res = '';
Object.keys(Navigation.Headings).some(function (Heading) {
return Object.keys(Navigation.Headings[Heading]).some(function (Item) {
if (name == Navigation.Headings[Heading][Item].Name) {
res = ("<a href=\""
+ Navigation.Headings[Heading][Item].URL + "\">"
+ Navigation.Headings[Heading][Item].Name + "</a> : ");
return true;
}
});
});
return res;
}
Solution that reduces iterating over the Headings/Items:
var remainingArgs = Args.slice(0);
Object.keys(Navigation.Headings).some(function (Heading) {
return Object.keys(Navigation.Headings[Heading]).some(function (Item) {
var i = remainingArgs.indexOf(Navigation.Headings[Heading][Item].Name);
if (i === -1)
return;
document.write("<a href=\""
+ Navigation.Headings[Heading][Item].URL + "\">"
+ Navigation.Headings[Heading][Item].Name + "</a> : ");
remainingArgs.splice(i, 1);
if (remainingArgs.length === 0)
return true;
}
});
});
How about pushing loops to their end limits
for(var a=0; a<data_a.length; a++){
for(var b=0; b<data_b.length; b++){
for(var c=0; c<data_c.length; c++){
for(var d=0; d<data_d.length; d++){
a = data_a.length;
b = data_b.length;
c = data_b.length;
d = data_d.length;
}
}
}
}
Already mentioned previously by swilliams, but with an example below (Javascript):
// Function wrapping inner for loop
function CriteriaMatch(record, criteria) {
for (var k in criteria) {
if (!(k in record))
return false;
if (record[k] != criteria[k])
return false;
}
return true;
}
// Outer for loop implementing continue if inner for loop returns false
var result = [];
for (var i = 0; i < _table.length; i++) {
var r = _table[i];
if (!CriteriaMatch(r[i], criteria))
continue;
result.add(r);
}
There are many excellent solutions above.
IMO, if your break conditions are exceptions,
you can use try-catch:
try{
for (var i in set1) {
for (var j in set2) {
for (var k in set3) {
throw error;
}
}
}
}catch (error) {
}
Hmmm hi to the 10 years old party ?
Why not put some condition in your for ?
var condition = true
for (var i = 0 ; i < Args.length && condition ; i++) {
for (var j = 0 ; j < Args[i].length && condition ; j++) {
if (Args[i].obj[j] == "[condition]") {
condition = false
}
}
}
Like this you stop when you want
In my case, using Typescript, we can use some() which go through the array and stop when condition is met
So my code become like this :
Args.some((listObj) => {
return listObj.some((obj) => {
return !(obj == "[condition]")
})
})
Like this, the loop stopped right after the condition is met
Reminder : This code run in TypeScript
Assign the values which are in comparison condition
function test(){
for(var i=0;i<10;i++)
{
for(var j=0;j<10;j++)
{
if(somecondition)
{
//code to Break out of both loops here
i=10;
j=10;
}
}
}
//Continue from here
}
An example with for .. of, close to the example further up which checks for the abort condition:
test()
function test() {
var arr = [1, 2, 3,]
var abort = false;
for (var elem of arr) {
console.log(1, elem)
for (var elem2 of arr) {
if (elem2 == 2) abort = true;
if (!abort) {
console.log(2, elem2)
}
}
}
}
Condition 1 - outer loop - will always run
The top voted and accepted answer also works for this kind of for loop.
Result: the inner loop will run once as expected
1 1
2 1
1 2
1 3
XXX.Validation = function() {
var ok = false;
loop:
do {
for (...) {
while (...) {
if (...) {
break loop; // Exist the outermost do-while loop
}
if (...) {
continue; // skips current iteration in the while loop
}
}
}
if (...) {
break loop;
}
if (...) {
break loop;
}
if (...) {
break loop;
}
if (...) {
break loop;
}
ok = true;
break;
} while(true);
CleanupAndCallbackBeforeReturning(ok);
return ok;
};
the best way is -
1) Sort the both array which are used in first and second loop.
2) if item matched then break the inner loop and hold the index value.
3) when start next iteration start inner loop with hold index value.

Categories