I need to convert this nested loop into a single loop.
This is the loop with the scenario:
First incrementer is i which starts from 0 and should run till 10
Second incrementer is j which starts from where i left off + 1 and runs till 10
.
.
My Nested Loop
for (var i = 0; i < 10; i++) {
for (var j = i + 1; j < 10; j++) {
if (some_condition) {
do_sth()
}
}
}
My Attempt at conversion
var i = 0;
while (i < 10){
var j = i + 1;
if (j < 10) {
if (some_condition) {
do_sth()
}
j++;
}
i++;
}
Unfortunately, my attempt doesn't produce the expected results.
The second snippet does not give the output which the first snippet delivers.
Can anyone please suggest me what my mistake is or provide me a better solution to achieve my target?
Thanks!
Not sure it improves readability complexity, but the following should produce the same.
var i = 0, j = 1;
while (i < 9) {
console.log(i, j);
j += 1;
if (j >= 10) {i += 1; j = i + 1}
}
You need to update i inside else statement or use continue. And declare j outside of the while body.
But keep in mind that this neither change "the order of complexity" nor "optimise" your code.
var i = 0;
var j = 1;
while (i < 10) {
if (j < 10) {
if (true) {
console.log(i, j)
}
j++;
} else {
i++;
j = i + 1;
}
}
You could adjust the loop lenght of i and check if j is greater or equal than 9, then increment i and start with fresh j.
var i = 0,
j = 1;
while (i < 9) {
console.log(i, j);
// do you stuff
if (j >= 9) j = ++i;
j++;
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have a simple question although i cannot manage to resolve this problem. Hope you can help. I need to make triangle using for loop and from this 4 exercises I don't know what to do with the third one. I haven't used Javascript before, so any help would be appreciated.
# # # # #
# # # #
# # # <----- here is triangle i need to make. Just in case
# #
#
var i;
var j;
for (i = 0; i <= 5; i++ )
{
document.write("</br>");
for ( j = 0; j < 6-i; j++ )
{
document.write( "  " );
}
for ( j = 6-i; j <= 5; j++ )
{
document.write( "*" );
}
}
This is code I wrote for D in photo.
And I'm sorry i did not add it at first.
for (let line = "*"; line.length < 8; line += "*")
console.log(line);
this question came in this book: http://eloquentjavascript.net
I don't know why there are so bad answers on google for this one.
function leftTriangle(rows){
let result = '';
for(let i=rows;i>0;i--){
if(i===rows) {
result += '*'.repeat(i) + '\n';
}else{
let empty = rows-i
result+= ' '.repeat(empty) + '*'.repeat(i)+ '\n'
}
}
return result;
}
console.log(leftTriangle(5))
I'm sure there are better solutions (simply left-padding with spaces comes to mind), but here's the quick and dirty one I created from your own solution.
for (var i = 0; i < 5; i++) {
for (var j = 0; j < i; j++) {
document.write(" ");
}
for (var j = 5; j > i; j--) {
document.write("#");
if (j > i + 1) document.write(" ");
}
document.write('<br/>')
}
https://js.do/code/diamondsinthesky
Something like this?
var rows = 5;
for (var i = rows; i--;) {
var columns = 0;
while (columns <= i) {
document.write('#');
columns++
}
document.write('<br />\n');
}
Thank you for your help. I did it. It was too obvious but somehow I couldn't find it. Thank you one more time. Here is how i did it.
for (i = 5; i > 0; i--) {
document.write("</br>");
for (j = 0; j < 6 - i; j++) {
document.write("  ");
}
for (j = 6 - i; j <= 5; j++) {
document.write("*");
}
}
var rows = 5;
for (var i = rows; i--;) {
var columns = 0;
while (columns <= i) {
document.write('#');
columns++
}
document.write('<br />\n');
}
You can also do this if you are looking for something different.
This code is for a triangle of 7 lines.
let size = 8;
let y = "#";
for (let x = 0; x < size; x++)
{
console.log(y);
y += "#";
}
// Second method
for (let i = 1; i < size;i++)
{
let me ="#".repeat(`${i}`)
console.log(me);
}
var size = 5;
for (var i = 0; i < size; i++) {
for (var j = 0; j <= i; j++) {
document.write("*");
}
document.write("<br />\n");
}
This is from Codecademy's Javascript lesson "Search Text For Your Name". The following works:
var text = "My name is Zorak. Everyone calls me Zorak.";
var myName = "Zorak";
var hits = [];
for ( i=0; i < text.length; i++ ){
if (text[i] === myName[0]) {
for (var j = i; j < i + myName.length; j++) {
hits.push(text[j])
}
}
}
However, when I replace i + myName.length with j + myName.length, it's crashing. In full:
var text = "My name is Zorak. Everyone calls me Zorak.";
var myName = "Zorak";
var hits = [];
for ( i=0; i < text.length; i++ ){
if (text[i] === myName[0]) {
for (var j = i; j < j + myName.length; j++) {
hits.push(text[j])
}
}
}
I'm not getting any errors when I run this, which led me to believe that it's just stuck in an infinite loop, except that when I place a console.log marker within the For loop in question, it doesn't print anything.
What's the reason for it crashing?
j < j + myName.length; j++
j never reaches the end. You're incrementing it, but you compare it against number that is always larger than itself (assuming myName.length is > 0). The conditions for the loop is always satisfied, causing it to run forever.
It crashes because it's an infinite loop.
Here is your second example, with the static variables converted to their values:
var text = "My name is Zorak. Everyone calls me Zorak.";
var myName = "Zorak";
var hits = [];
for (i = 0; i < 42; i++) {
if (text[i] === 'Z') {
for (var j = i; j < j + 5; j++) {
hits.push(text[j]);
}
}
}
Specifically, your inner for condition is causing the infinite loop:
for (var j = i; j < j + myName.length; j++) {
or with myName.length replaced by its value, 5:
for (var j = i; j < j + 5; j++) {
j will always be less than j + 5 so the loop continues without end, consuming memory until crash.
I am trying to write a jQuery that will find the index of a specific value within a 7x7 2D array.
So if the value I am looking for is 0 then I need the function to search the 2D array and once it finds 0 it stores the index of the two indexes.
This is what I have so far, but it returns "0 0" (the initial values set to the variable.
Here is a jsFiddle and the function I have so far:
http://jsfiddle.net/31pj8ydz/1/
$(document).ready( function() {
var items = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = 0;
var line = 0;
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
$('.text').text(row + ' ' + line);
});
HTML:
<p class="text"></p>
Your if statement is comparing
if (items[i, j] == '0,')
Accessing is wrong, you should use [i][j].
And your array has values:
[1,2,3,4,5,6,7]
....
Your value '0,' is a string, which will not match numeric values inside the array, meaning that your row and line won't change.
First, you are accessing your array wrong. To access a 2D array, you use the format items[i][j].
Second, your array doesn't contain the value '0'. It doesn't contain any strings. So the row and line variables are never changed.
You should change your if statement to look like this:
if(items[i][j] == 0) {
Notice it is searching for the number 0, not the string '0'.
You access your array with the wrong way. Please just try this one:
items[i][j]
When we have a multidimensional array we access the an element of the array, using array[firstDimensionIndex][secondDimensionIndex]...[nthDimensionIndex].
That being said, you should change the condition in your if statement:
if( items[i][j] === 0 )
Please notice that I have removed the , you had after 0. It isn't needed. Also I have removed the ''. We don't need them also.
There are following problems in the code
1) items[i,j] should be items[i][j].
2) You are comparing it with '0,' it should be 0 or '0', if you are not concerned about type.
3) In your inner for loop you should be incrementing j and testing j as exit condition.
Change your for loop like bellow and it will work
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == '0') {
row = i;
line = j;
}
}
}
DEMO
Note:-
1) Better to use === at the place of ==, it checks for type also. As you see with 0=='0' gives true.
2) Better to say i < items.length and j<items[i].length instead of hard-coding it as 7.
var foo;
items.forEach(function(arr, i) {
arr.forEach(function(val, j) {
if (!val) { //0 coerces to false
foo = [i, j];
}
}
}
Here foo will be the last instance of 0 in the 2D array.
You are doing loop wrong
On place of
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
use this
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == 0) {
row = i;
line = j;
}
}
}
Here is the demo
looks like you are still learning how to program. But here is an algorithm I've made. Analyze it and compare to your code ;)
var itens = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = null;
var collumn = null;
for (var i = 0; i < itens.length; i++) {
for (var j = 0; j < itens[i].length; j++) {
if (itens[i][j] == 0) {
row = i;
collumn = j;
}
}
}
console.log(row, collumn);
var text = "Hue, bla, hue, rhr, aek kmggg mlsd k Bjarni sdkrals fn lol Bjarni\
lelelele Bjarni";
var myName = "Bjarni";
var hits = [];
for(var i = 0; i < text.length; i++); {
if (text[i] === "B"); {
for(var j = i; j < (myName.length+i); j++) {
hits.push(text[j]);
}
}
}
console.log(hits);
This is supposed to return my name, but it just returns an array containing a few undefined values.
The problem is here:
if (text[i] === "B"); {
Get rid of the semicolon. The semicolon in that point of the code makes it like:
if (text[i] === "B")
; // DO NOTHING AT ALL
{ // START A BLOCK
for(var j = i; j < (myName.length+i); j++) {
hits.push(text[j]);
}
}
edit — oh and there's another one (with similar effects) after the for loop header. It should be:
for(var i = 0; i < text.length; i++) {
You've just got a few syntactical errors and a missing break statement to fix. This should work:
var text = "Hue, bla, hue, rhr, aek kmggg mlsd k Bjarni sdkrals fn lol Bjarni\ lelelele Bjarni";
var myName = "Bjarni";
var hits = [];
for(var i = 0; i < text.length; i++) {
if (text[i] === "B") {
for(var j = i; j < (myName.length+i); j++) {
hits.push(text[j]);
}
break;
}
}
console.log(hits);
To clarify; you had a semicolon after the line if( text[i] === "B");, another semicolon after your first for loop and you were missing a break statement, so it would've looped around throughout the entire "text" string, which may or may not have been unintentional behaviour.